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.PacketExtension;
022import org.jivesoftware.smack.provider.PacketExtensionProvider;
023import org.xmlpull.v1.XmlPullParser;
024
025/**
026 * Represents a chat state which is an extension to message packets which is used to indicate
027 * the current status of a chat participant.
028 *
029 * @author Alexander Wenckus
030 * @see org.jivesoftware.smackx.chatstates.ChatState
031 */
032public class ChatStateExtension implements PacketExtension {
033
034    private ChatState state;
035
036    /**
037     * Default constructor. The argument provided is the state that the extension will represent.
038     *
039     * @param state the state that the extension represents.
040     */
041    public ChatStateExtension(ChatState state) {
042        this.state = state;
043    }
044
045    public String getElementName() {
046        return state.name();
047    }
048
049    public String getNamespace() {
050        return "http://jabber.org/protocol/chatstates";
051    }
052
053    public String toXML() {
054        return "<" + getElementName() + " xmlns=\"" + getNamespace() + "\" />";
055    }
056
057    public static class Provider implements PacketExtensionProvider {
058
059        public PacketExtension parseExtension(XmlPullParser parser) throws Exception {
060            ChatState state;
061            try {
062                state = ChatState.valueOf(parser.getName());
063            }
064            catch (Exception ex) {
065                state = ChatState.active;
066            }
067            return new ChatStateExtension(state);
068        }
069    }
070}