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