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.last_interaction.element;
018
019import java.util.Date;
020
021import org.jivesoftware.smack.packet.ExtensionElement;
022import org.jivesoftware.smack.packet.Presence;
023import org.jivesoftware.smack.util.Objects;
024import org.jivesoftware.smack.util.XmlStringBuilder;
025
026public class IdleElement implements ExtensionElement {
027
028    public static final String NAMESPACE = "urn:xmpp:idle:1";
029    public static final String ELEMENT = "idle";
030    public static final String ATTR_SINCE = "since";
031
032    private final Date since;
033
034    /**
035     * Create a new IdleElement with the current date as date of last user interaction.
036     */
037    public IdleElement() {
038        this(new Date());
039    }
040
041    /**
042     * Create a new IdleElement.
043     * @param since date of last user interaction
044     */
045    public IdleElement(Date since) {
046        this.since = Objects.requireNonNull(since);
047    }
048
049    /**
050     * Return the value of last user interaction.
051     * @return date of last interaction
052     */
053    public Date getSince() {
054        return since;
055    }
056
057    /**
058     * Add an Idle element with current date to the presence.
059     * @param presence presence
060     */
061    public static void addToPresence(Presence presence) {
062        presence.addExtension(new IdleElement());
063    }
064
065    /**
066     * Return the IdleElement from a presence.
067     * Returns null, if no IdleElement found.
068     *
069     * @param presence presence
070     * @return idleElement from presence or null
071     */
072    public static IdleElement fromPresence(Presence presence) {
073        return presence.getExtension(ELEMENT, NAMESPACE);
074    }
075
076    /**
077     * {@inheritDoc}
078     */
079    @Override
080    public String getNamespace() {
081        return NAMESPACE;
082    }
083
084    /**
085     * {@inheritDoc}
086     */
087    @Override
088    public String getElementName() {
089        return ELEMENT;
090    }
091
092    /**
093     * {@inheritDoc}
094     */
095    @Override
096    public XmlStringBuilder toXML(String enclosingNamespace) {
097        return new XmlStringBuilder(this)
098                .attribute(ATTR_SINCE, since)
099                .closeEmptyElement();
100    }
101}