Presence.java 13.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
/**
 * Copyright (C) 2004-2007 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */

package org.xmpp.packet;

import org.dom4j.Element;

import java.util.Iterator;

/**
 * Presence packet. Presence packets are used to express an entity's current
 * network availability and to notify other entities of that availability.
 * Presence packets are also used to negotiate and manage subscriptions to the
 * presence of other entities.<p>
 *
 * A presence optionally has a {@link Type}.
 *
 * @author Matt Tucker
 */
public class Presence extends Packet {

    /**
     * Constructs a new Presence.
     */
    public Presence() {
        this.element = docFactory.createDocument().addElement("presence");
    }

    /**
     * Constructs a new Presence with the specified type.
     *
     * @param type the presence type.
     */
    public Presence(Presence.Type type) {
        this();
        setType(type);
    }

    /**
     * Constructs a new Presence using an existing Element. This is useful
     * for parsing incoming presence Elements into Presence objects.
     *
     * @param element the presence Element.
     */
    public Presence(Element element) {
        super(element);
    }

    /**
     * Constructs a new Presence using an existing Element. This is useful
     * for parsing incoming Presence Elements into Presence objects. Stringprep validation
     * on the TO address can be disabled. The FROM address will not be validated since the
     * server is the one that sets that value.
     *
     * @param element the Presence Element.
     * @param skipValidation true if stringprep should not be applied to the TO address.
     */
    public Presence(Element element, boolean skipValidation) {
        super(element, skipValidation);
    }

    /**
     * Constructs a new Presence that is a copy of an existing Presence.
     *
     * @param presence the presence packet.
     * @see #createCopy() 
     */
    private Presence(Presence presence) {
        Element elementCopy = presence.element.createCopy();
        docFactory.createDocument().add(elementCopy);
        this.element = elementCopy;
        // Copy cached JIDs (for performance reasons)
        this.toJID = presence.toJID;
        this.fromJID = presence.fromJID;
    }

    /**
     * Returns true if the presence type is "available". This is a
     * convenience method that is equivalent to:
     *
     * <pre>getType() == null</pre>
     *
     */
    public boolean isAvailable() {
        return getType() == null;
    }

    /**
     * Returns the type of this presence. If the presence is "available", the
     * type will be <tt>null</tt> (in XMPP, no value for the type attribute is
     * defined as available).
     *
     * @return the presence type or <tt>null</tt> if "available".
     * @see Type
     */
    public Type getType() {
        String type = element.attributeValue("type");
        if (type == null) {
            return null;
        }
        else {
            return Type.valueOf(type);
        }
    }

    /**
     * Sets the type of this presence.
     *
     * @param type the presence type.
     * @see Type
     */
    public void setType(Type type) {
        element.addAttribute("type", type==null?null:type.toString());
    }

    /**
     * Returns the presence "show" value, which specifies a particular availability
     * status. If the &lt;show&gt; element is not present, this method will return
     * <tt>null</tt>. The show value can only be set if the presence type is "avaialble".
     * A <tt>null</tt> show value is used to represent "available", which is the
     * default.
     *
     * @return the presence show value..
     * @see Show
     */
    public Show getShow() {
        String show = element.elementText("show");
        if (show == null) {
            return null;
        }
        else {
            return Show.valueOf(show);
        }
    }

    /**
     * Sets the presence "show" value, which specifies a particular availability
     * status. The show value can only be set if the presence type is "available".
     * A <tt>null</tt> show value is used to represent "available", which is the
     * default.
     *
     * @param show the presence show value.
     * @throws IllegalArgumentException if the presence type is not available.
     * @see Show
     */
    public void setShow(Show show) {
        Element showElement = element.element("show");
        // If show is null, clear the subject.
        if (show == null) {
            if (showElement != null) {
                element.remove(showElement);
            }
            return;
        }
        if (showElement == null) {
            if (!isAvailable()) {
                throw new IllegalArgumentException("Cannot set 'show' if 'type' attribute is set.");
            }
            showElement = element.addElement("show");
        }
        showElement.setText(show.toString());
    }

    /**
     * Returns the status of this presence packet, a natural-language description
     * of availability status.
     *
     * @return the status.
     */
    public String getStatus() {
        return element.elementText("status");
    }

    /**
     * Sets the status of this presence packet, a natural-language description
     * of availability status.
     *
     * @param status the status.
     */
    public void setStatus(String status) {
        Element statusElement = element.element("status");
        // If subject is null, clear the subject.
        if (status == null) {
            if (statusElement != null) {
                element.remove(statusElement);
            }
            return;
        }

        if (statusElement == null) {
            statusElement = element.addElement("status");
        }
        statusElement.setText(status);
    }

    /**
     * Returns the priority. The valid priority range is -128 through 128.
     * If no priority element exists in the packet, this method will return
     * the default value of 0.
     *
     * @return the priority.
     */
    public int getPriority() {
        String priority = element.elementText("priority");
        if (priority == null) {
            return 0;
        }
        else {
            try {
                return Integer.parseInt(priority);
            }
            catch (Exception e) {
                return 0;
            }
        }
    }

    /**
     * Sets the priority. The valid priority range is -128 through 128.
     *
     * @param priority the priority.
     * @throws IllegalArgumentException if the priority is less than -128 or greater
     *      than 128.
     */
    public void setPriority(int priority) {
        if (priority < -128 || priority > 128) {
            throw new IllegalArgumentException("Priority value of " + priority +
                    " is outside the valid range of -128 through 128");
        }
        Element priorityElement = element.element("priority");
        if (priorityElement == null) {
            priorityElement = element.addElement("priority");
        }
        priorityElement.setText(Integer.toString(priority));
    }

    /**
     * Returns the first child element of this packet that matches the
     * given name and namespace. If no matching element is found,
     * <tt>null</tt> will be returned. This is a convenience method to avoid
     * manipulating this underlying packet's Element instance directly.<p>
     *
     * Child elements in extended namespaces are used to extend the features
     * of XMPP. Examples include a "user is typing" indicator and invitations to
     * group chat rooms. Although any valid XML can be included in a child element
     * in an extended namespace, many common features have been standardized
     * as <a href="http://www.jabber.org/jeps">Jabber Enhancement Proposals</a>
     * (JEPs).
     *
     * @param name the element name.
     * @param namespace the element namespace.
     * @return the first matching child element, or <tt>null</tt> if there
     *      is no matching child element.
     */
    public Element getChildElement(String name, String namespace) {
        for (Iterator i=element.elementIterator(name); i.hasNext(); ) {
            Element element = (Element)i.next();
            if (element.getNamespaceURI().equals(namespace)) {
                return element;
            }
        }
        return null;
    }

    /**
     * Adds a new child element to this packet with the given name and
     * namespace. The newly created Element is returned. This is a
     * convenience method to avoid manipulating this underlying packet's
     * Element instance directly.<p>
     *
     * Child elements in extended namespaces are used to extend the features
     * of XMPP. Examples include a "user is typing" indicator and invitations to
     * group chat rooms. Although any valid XML can be included in a child element
     * in an extended namespace, many common features have been standardized
     * as <a href="http://www.jabber.org/jeps">Jabber Enhancement Proposals</a>
     * (JEPs).
     *
     * @param name the element name.
     * @param namespace the element namespace.
     * @return the newly created child element.
     */
    public Element addChildElement(String name, String namespace) {
        return element.addElement(name, namespace);
    }

    /**
     * Returns a deep copy of this Presence.
     *
     * @return a deep copy of this Presence.
     */
    public Presence createCopy() {
        return new Presence(this);
    }

    /**
     * Represents the type of a presence packet. Note: the presence is assumed
     * to be "available" when the type attribute of the packet is <tt>null</tt>.
     * The valid types are:
     *
     *  <ul>
     *      <li>{@link #unavailable Presence.Type.unavailable} -- signals that the
     *          entity is no longer available for communication.
     *      <li>{@link #subscribe Presence.Type.subscribe} -- the sender wishes to
     *          subscribe to the recipient's presence.
     *      <li>{@link #subscribed Presence.Type.subscribed} -- the sender has allowed
     *          the recipient to receive their presence.
     *      <li>{@link #unsubscribe Presence.Type.unsubscribe} -- the sender is
     *          unsubscribing from another entity's presence.
     *      <li>{@link #unsubscribed Presence.Type.unsubcribed} -- the subscription
     *          request has been denied or a previously-granted subscription has been cancelled.
     *      <li>{@link #probe Presence.Type.probe} -- a request for an entity's current
     *          presence; SHOULD be generated only by a server on behalf of a user.
     *      <li>{@link #error Presence.Type.error} -- an error has occurred regarding
     *          processing or delivery of a previously-sent presence stanza.
     * </ul>
     */
    public enum Type {

        /**
         * Typically short text message used in line-by-line chat interfaces.
         */
        unavailable,

        /**
         * The sender wishes to subscribe to the recipient's presence.
         */
        subscribe,

        /**
         * The sender has allowed the recipient to receive their presence.
         */
        subscribed,

        /**
         * The sender is unsubscribing from another entity's presence.
         */
        unsubscribe,

        /**
         * The subscription request has been denied or a previously-granted
         * subscription has been cancelled.
         */
        unsubscribed,

        /**
         * A request for an entity's current presence; SHOULD be
         * generated only by a server on behalf of a user.
         */
        probe,

        /**
         * An error has occurred regarding processing or delivery
         * of a previously-sent presence stanza.
         */
        error;
    }

    /**
     * Represents the presence "show" value. Note: a <tt>null</tt> "show" value is the
     * default, which means "available". Valid values are:
     *
     * <ul>
     *      <li>{@link #chat Presence.Show.chat} -- the entity or resource is actively
     *          interested in chatting.
     *      <li>{@link #away Presence.Show.away} -- the entity or resource is
     *          temporarily away.
     *      <li>{@link #dnd Presence.Show.dnd} -- the entity or resource is busy
     *          (dnd = "Do Not Disturb").
     *      <li>{@link #xa Presence.Show.xa} -- the entity or resource is away for an
     *          extended period (xa = "eXtended Away").
     * </ul>
     */
    public enum Show {

        /**
         * The entity or resource is actively interested in chatting.
         */
        chat,

        /**
         * The entity or resource is temporarily away.
         */
        away,

        /**
         * The entity or resource is away for an extended period (xa = "eXtended Away").
         */
        xa,

        /**
         * The entity or resource is busy (dnd = "Do Not Disturb").
         */
        dnd;
    }
}