001/**
002 *
003 * Copyright the original author or authors
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.pubsub.provider;
018
019import org.jivesoftware.smack.packet.ExtensionElement;
020import org.jivesoftware.smack.provider.ExtensionElementProvider;
021import org.jivesoftware.smack.provider.ProviderManager;
022import org.jivesoftware.smack.util.PacketParserUtils;
023
024import org.jivesoftware.smackx.pubsub.Item;
025import org.jivesoftware.smackx.pubsub.PayloadItem;
026import org.jivesoftware.smackx.pubsub.SimplePayload;
027import org.jivesoftware.smackx.pubsub.packet.PubSubNamespace;
028
029import org.xmlpull.v1.XmlPullParser;
030
031/**
032 * Parses an <b>item</b> element as is defined in both the {@link PubSubNamespace#BASIC} and
033 * {@link PubSubNamespace#EVENT} namespaces. To parse the item contents, it will use whatever
034 * {@link ExtensionElementProvider} is registered in <b>smack.providers</b> for its element name and namespace. If no
035 * provider is registered, it will return a {@link SimplePayload}.
036 * 
037 * @author Robin Collier
038 */
039public class ItemProvider extends ExtensionElementProvider<Item> 
040{
041    @Override
042    public Item parse(XmlPullParser parser, int initialDepth)
043                    throws Exception {
044        String id = parser.getAttributeValue(null, "id");
045        String node = parser.getAttributeValue(null, "node");
046
047        int tag = parser.next();
048
049        if (tag == XmlPullParser.END_TAG) 
050        {
051            return new Item(id, node);
052        }
053        else
054        {
055            String payloadElemName = parser.getName();
056            String payloadNS = parser.getNamespace();
057
058            final ExtensionElementProvider<ExtensionElement> extensionProvider = ProviderManager.getExtensionProvider(payloadElemName, payloadNS);
059            if (extensionProvider == null)
060            {
061                CharSequence payloadText = PacketParserUtils.parseElement(parser, true);
062                return new PayloadItem<>(id, node, new SimplePayload(payloadElemName, payloadNS, payloadText));
063            }
064            else
065            {
066                return new PayloadItem<>(id, node, extensionProvider.parse(parser));
067            }
068        }
069    }
070
071}