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.provider.ExtensionElementProvider;
022
023import org.jivesoftware.smackx.hoxt.packet.Base64BinaryChunk;
024
025import org.xmlpull.v1.XmlPullParser;
026import org.xmlpull.v1.XmlPullParserException;
027
028/**
029 * Stanza provider for base64 binary chunks.
030 *
031 * @author Andriy Tsykholyas
032 * @see <a href="http://xmpp.org/extensions/xep-0332.html">XEP-0332: HTTP over XMPP transport</a>
033 */
034public class Base64BinaryChunkProvider extends ExtensionElementProvider<Base64BinaryChunk> {
035
036    @Override
037    public Base64BinaryChunk parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException {
038        String streamId = parser.getAttributeValue("", Base64BinaryChunk.ATTRIBUTE_STREAM_ID);
039        String nrString = parser.getAttributeValue("", Base64BinaryChunk.ATTRIBUTE_NR);
040        String lastString = parser.getAttributeValue("", Base64BinaryChunk.ATTRIBUTE_LAST);
041        boolean last = false;
042        int nr = Integer.parseInt(nrString);
043
044        if (lastString != null) {
045            last = Boolean.parseBoolean(lastString);
046        }
047
048        String text = null;
049        boolean done = false;
050
051        while (!done) {
052            int eventType = parser.next();
053
054            if (eventType == XmlPullParser.END_TAG) {
055                if (parser.getName().equals(Base64BinaryChunk.ELEMENT_CHUNK)) {
056                    done = true;
057                } else {
058                    throw new IllegalArgumentException("unexpected end tag of: " + parser.getName());
059                }
060            } else if (eventType == XmlPullParser.TEXT) {
061                text = parser.getText();
062            } else {
063                throw new IllegalArgumentException("unexpected eventType: " + eventType);
064            }
065        }
066
067        return new Base64BinaryChunk(text, streamId, nr, last);
068    }
069}