001/**
002 *
003 * Copyright 2003-2007 Jive Software.
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 */
017
018package org.jivesoftware.smackx.chatstates.packet;
019
020import org.jivesoftware.smackx.chatstates.ChatState;
021import org.jivesoftware.smack.packet.ExtensionElement;
022import org.jivesoftware.smack.provider.ExtensionElementProvider;
023import org.jivesoftware.smack.util.XmlStringBuilder;
024import org.xmlpull.v1.XmlPullParser;
025
026/**
027 * Represents a chat state which is an extension to message packets which is used to indicate
028 * the current status of a chat participant.
029 *
030 * @author Alexander Wenckus
031 * @see org.jivesoftware.smackx.chatstates.ChatState
032 */
033public class ChatStateExtension implements ExtensionElement {
034
035    public static final String NAMESPACE = "http://jabber.org/protocol/chatstates";
036
037    private final ChatState state;
038
039    /**
040     * Default constructor. The argument provided is the state that the extension will represent.
041     *
042     * @param state the state that the extension represents.
043     */
044    public ChatStateExtension(ChatState state) {
045        this.state = state;
046    }
047
048    @Override
049    public String getElementName() {
050        return state.name();
051    }
052
053    @Override
054    public String getNamespace() {
055        return NAMESPACE;
056    }
057
058    public ChatState getChatState() {
059        return state;
060    }
061
062    @Override
063    public XmlStringBuilder toXML() {
064        XmlStringBuilder xml = new XmlStringBuilder(this);
065        xml.closeEmptyElement();
066        return xml;
067    }
068
069    public static class Provider extends ExtensionElementProvider<ChatStateExtension> {
070
071        @Override
072        public ChatStateExtension parse(XmlPullParser parser, int initialDepth) {
073            ChatState state;
074            try {
075                state = ChatState.valueOf(parser.getName());
076            }
077            catch (Exception ex) {
078                state = ChatState.active;
079            }
080            return new ChatStateExtension(state);
081        }
082    }
083}