001/*
002 *
003 * Copyright 2014 Andriy Tsykholyas
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.hoxt.provider;
018
019import java.io.IOException;
020
021import org.jivesoftware.smack.packet.XmlEnvironment;
022import org.jivesoftware.smack.provider.ExtensionElementProvider;
023import org.jivesoftware.smack.xml.XmlPullParser;
024import org.jivesoftware.smack.xml.XmlPullParserException;
025
026import org.jivesoftware.smackx.hoxt.packet.Base64BinaryChunk;
027
028import org.jxmpp.JxmppContext;
029
030/**
031 * Stanza provider for base64 binary chunks.
032 *
033 * @author Andriy Tsykholyas
034 * @see <a href="http://xmpp.org/extensions/xep-0332.html">XEP-0332: HTTP over XMPP transport</a>
035 */
036public class Base64BinaryChunkProvider extends ExtensionElementProvider<Base64BinaryChunk> {
037
038    @Override
039    public Base64BinaryChunk parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment, JxmppContext jxmppContext) throws XmlPullParserException, IOException {
040        String streamId = parser.getAttributeValue("", Base64BinaryChunk.ATTRIBUTE_STREAM_ID);
041        String nrString = parser.getAttributeValue("", Base64BinaryChunk.ATTRIBUTE_NR);
042        String lastString = parser.getAttributeValue("", Base64BinaryChunk.ATTRIBUTE_LAST);
043        boolean last = false;
044        int nr = Integer.parseInt(nrString);
045
046        if (lastString != null) {
047            last = Boolean.parseBoolean(lastString);
048        }
049
050        String text = null;
051        boolean done = false;
052
053        while (!done) {
054            XmlPullParser.Event eventType = parser.next();
055
056            if (eventType == XmlPullParser.Event.END_ELEMENT) {
057                if (parser.getName().equals(Base64BinaryChunk.ELEMENT_CHUNK)) {
058                    done = true;
059                } else {
060                    throw new IllegalArgumentException("unexpected end tag of: " + parser.getName());
061                }
062            } else if (eventType == XmlPullParser.Event.TEXT_CHARACTERS) {
063                text = parser.getText();
064            } else {
065                throw new IllegalArgumentException("unexpected eventType: " + eventType);
066            }
067        }
068
069        return new Base64BinaryChunk(text, streamId, nr, last);
070    }
071}