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.SmackException;
020import org.jivesoftware.smack.provider.ExtensionElementProvider;
021import org.jivesoftware.smack.util.ParserUtils;
022import org.jivesoftware.smackx.pubsub.Affiliation;
023import org.jivesoftware.smackx.pubsub.packet.PubSubNamespace;
024import org.jxmpp.jid.BareJid;
025import org.xmlpull.v1.XmlPullParser;
026
027/**
028 * Parses the affiliation element out of the reply stanza from the server
029 * as specified in the <a href="http://xmpp.org/extensions/xep-0060.html#schemas-pubsub">affiliation schema</a>.
030 * 
031 * @author Robin Collier
032 */
033public class AffiliationProvider extends ExtensionElementProvider<Affiliation> {
034
035    @Override
036    public Affiliation parse(XmlPullParser parser, int initialDepth)
037            throws Exception {
038        String node = parser.getAttributeValue(null, "node");
039        BareJid jid = ParserUtils.getBareJidAttribute(parser);
040
041        String affiliationString = parser.getAttributeValue(null, "affiliation");
042        Affiliation.Type affiliationType = null;
043        if (affiliationString != null) {
044            affiliationType = Affiliation.Type.valueOf(affiliationString);
045        }
046        Affiliation affiliation;
047        if (node != null && jid == null) {
048            // affiliationType may be empty
049            affiliation = new Affiliation(node, affiliationType);
050        }
051        else if (node == null && jid != null) {
052            PubSubNamespace namespace = null; // TODO
053            affiliation = new Affiliation(jid, affiliationType, namespace);
054        }
055        else {
056            throw new SmackException("Invalid affililation. Either one of 'node' or 'jid' must be set"
057                    + ". Node: " + node
058                    + ". Jid: " + jid
059                    + '.');
060        }
061        return affiliation;
062    }
063
064}