001/**
002 *
003 * Copyright 2018 Paul Schaub
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.reference.provider;
018
019import java.net.URI;
020
021import org.jivesoftware.smack.packet.ExtensionElement;
022import org.jivesoftware.smack.provider.ExtensionElementProvider;
023import org.jivesoftware.smack.provider.ProviderManager;
024import org.jivesoftware.smack.util.ParserUtils;
025import org.jivesoftware.smackx.reference.element.ReferenceElement;
026
027import org.xmlpull.v1.XmlPullParser;
028
029public class ReferenceProvider extends ExtensionElementProvider<ReferenceElement> {
030
031    public static final ReferenceProvider TEST_PROVIDER = new ReferenceProvider();
032
033    @Override
034    public ReferenceElement parse(XmlPullParser parser, int initialDepth) throws Exception {
035        Integer begin = ParserUtils.getIntegerAttribute(parser, ReferenceElement.ATTR_BEGIN);
036        Integer end =   ParserUtils.getIntegerAttribute(parser, ReferenceElement.ATTR_END);
037        String typeString = parser.getAttributeValue(null, ReferenceElement.ATTR_TYPE);
038        ReferenceElement.Type type = ReferenceElement.Type.valueOf(typeString);
039        String anchor = parser.getAttributeValue(null, ReferenceElement.ATTR_ANCHOR);
040        String uriString = parser.getAttributeValue(null, ReferenceElement.ATTR_URI);
041        URI uri = uriString != null ? new URI(uriString) : null;
042        ExtensionElement child = null;
043        outerloop: while (true) {
044            int eventType = parser.next();
045            if (eventType == XmlPullParser.START_TAG) {
046                String elementName = parser.getName();
047                String namespace = parser.getNamespace();
048                ExtensionElementProvider<?> provider = ProviderManager.getExtensionProvider(elementName, namespace);
049                if (provider != null) {
050                    child = provider.parse(parser);
051                }
052            }
053            if (eventType == XmlPullParser.END_TAG) {
054                break outerloop;
055            }
056        }
057
058        return new ReferenceElement(begin, end, type, anchor, uri, child);
059    }
060}