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 org.jivesoftware.smack.packet.Message;
020import org.jivesoftware.smack.util.XmlStringBuilder;
021import org.jivesoftware.smackx.sid.StableUniqueStanzaIdManager;
022
023public class OriginIdElement extends StableAndUniqueIdElement {
024
025    public static final String ELEMENT = "origin-id";
026
027    public OriginIdElement() {
028        super();
029    }
030
031    public OriginIdElement(String id) {
032        super(id);
033    }
034
035    /**
036     * Add an origin-id element to a message and set the stanzas id to the same id as in the origin-id element.
037     *
038     * @param message message.
039     */
040    public static OriginIdElement addOriginId(Message message) {
041        OriginIdElement originId = new OriginIdElement();
042        message.addExtension(originId);
043        // TODO: Find solution to have both the originIds stanzaId and a nice to look at incremental stanzaID.
044        // message.setStanzaId(originId.getId());
045        return originId;
046    }
047
048    /**
049     * Return true, if the message contains a origin-id element.
050     *
051     * @param message message
052     * @return true if the message contains a origin-id, false otherwise.
053     */
054    public static boolean hasOriginId(Message message) {
055        return getOriginId(message) != null;
056    }
057
058    /**
059     * Return the origin-id element of a message or null, if absent.
060     *
061     * @param message message
062     * @return origin-id element
063     */
064    public static OriginIdElement getOriginId(Message message) {
065        return message.getExtension(OriginIdElement.ELEMENT, StableUniqueStanzaIdManager.NAMESPACE);
066    }
067
068    @Override
069    public String getNamespace() {
070        return StableUniqueStanzaIdManager.NAMESPACE;
071    }
072
073    @Override
074    public String getElementName() {
075        return ELEMENT;
076    }
077
078    @Override
079    public CharSequence toXML(String enclosingNamespace) {
080        return new XmlStringBuilder(this)
081                .attribute(ATTR_ID, getId())
082                .closeEmptyElement();
083    }
084}