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