001/**
002 *
003 * Copyright 2018 Paul Schaub
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.sid.element;
018
019import javax.xml.namespace.QName;
020
021import org.jivesoftware.smack.packet.Message;
022import org.jivesoftware.smack.util.XmlStringBuilder;
023
024import org.jivesoftware.smackx.sid.StableUniqueStanzaIdManager;
025
026public class StanzaIdElement extends StableAndUniqueIdElement {
027
028    public static final String ELEMENT = "stanza-id";
029    public static final String NAMESPACE = StableUniqueStanzaIdManager.NAMESPACE;
030    public static final QName QNAME = new QName(NAMESPACE, ELEMENT);
031    public static final String ATTR_BY = "by";
032
033    private final String by;
034
035    public StanzaIdElement(String by) {
036        super();
037        this.by = by;
038    }
039
040    public StanzaIdElement(String id, String by) {
041        super(id);
042        this.by = by;
043    }
044
045    /**
046     * Return true, if a message contains a stanza-id element.
047     *
048     * @param message message
049     * @return true if message contains stanza-id element, otherwise false.
050     */
051    public static boolean hasStanzaId(Message message) {
052        return getStanzaId(message) != null;
053    }
054
055    /**
056     * Return the stanza-id element of a message.
057     *
058     * @param message message
059     * @return stanza-id element of a jid, or null if absent.
060     */
061    public static StanzaIdElement getStanzaId(Message message) {
062        return message.getExtension(StanzaIdElement.class);
063    }
064
065    public String getBy() {
066        return by;
067    }
068
069    @Override
070    public String getNamespace() {
071        return StableUniqueStanzaIdManager.NAMESPACE;
072    }
073
074    @Override
075    public String getElementName() {
076        return ELEMENT;
077    }
078
079    @Override
080    public XmlStringBuilder toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) {
081        return new XmlStringBuilder(this)
082                .attribute(ATTR_ID, getId())
083                .attribute(ATTR_BY, getBy())
084                .closeEmptyElement();
085    }
086}