StreamError.java 17.2 KB
Newer Older
1
/**
2
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
3
 *
Gaston Dombiak's avatar
Gaston Dombiak committed
4
 * This software is published under the terms of the GNU Public License (GPL),
5 6
 * a copy of which is included in this distribution, or a commercial license
 * agreement with Jive.
7 8 9 10
 */

package org.xmpp.packet;

Gaston Dombiak's avatar
Gaston Dombiak committed
11 12 13
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.QName;
14
import org.dom4j.io.OutputFormat;
Gaston Dombiak's avatar
Gaston Dombiak committed
15
import org.dom4j.io.XMLWriter;
16 17

import java.io.StringWriter;
Gaston Dombiak's avatar
Gaston Dombiak committed
18
import java.util.Iterator;
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 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484

/**
 * A stream error. Stream errors have a condition and they
 * can optionally include explanation text.
 *
 * @author Matt Tucker
 */
public class StreamError {

    private static final String ERROR_NAMESPACE = "urn:ietf:params:xml:ns:xmpp-streams";

    private static DocumentFactory docFactory = DocumentFactory.getInstance();

    private Element element;

    /**
     * Construcs a new StreamError with the specified condition.
     *
     * @param condition the error condition.
     */
    public StreamError(Condition condition) {
        this.element = docFactory.createElement(docFactory.createQName("error", "stream",
                "http://etherx.jabber.org/streams"));
        setCondition(condition);
    }

    /**
     * Constructs a new StreamError with the specified condition and error text.
     *
     * @param condition the error condition.
     * @param text the text description of the error.
     */
    public StreamError(Condition condition, String text) {
        this.element = docFactory.createElement(docFactory.createQName("error", "stream",
                "http://etherx.jabber.org/streams"));
        setCondition(condition);
        setText(text, null);
    }

    /**
     * Constructs a new StreamError with the specified condition and error text.
     *
     * @param condition the error condition.
     * @param text the text description of the error.
     * @param language the language code of the error description (e.g. "en").
     */
    public StreamError(Condition condition, String text, String language) {
        this.element = docFactory.createElement(docFactory.createQName("error", "stream",
                "http://etherx.jabber.org/streams"));
        setCondition(condition);
        setText(text, language);
    }

    /**
     * Constructs a new StreamError using an existing Element. This is useful
     * for parsing incoming error Elements into StreamError objects.
     *
     * @param element the stream error Element.
     */
    public StreamError(Element element) {
        this.element = element;
    }

    /**
     * Returns the error condition.
     *
     * @return the error condition.
     * @see Condition
     */
    public Condition getCondition() {
        for (Iterator i=element.elementIterator(); i.hasNext(); ) {
            Element el = (Element)i.next();
            if (el.getNamespaceURI().equals(ERROR_NAMESPACE) &&
                    !el.getName().equals("text"))
            {
                return Condition.fromXMPP(el.getName());
            }
        }
        return null;
    }

    /**
     * Sets the error condition.
     *
     * @param condition the error condition.
     * @see Condition
     */
    public void setCondition(Condition condition) {
        if (condition == null) {
            throw new NullPointerException("Condition cannot be null");
        }
        Element conditionElement = null;
        for (Iterator i=element.elementIterator(); i.hasNext(); ) {
            Element el = (Element)i.next();
            if (el.getNamespaceURI().equals(ERROR_NAMESPACE) &&
                    !el.getName().equals("text"))
            {
                conditionElement = el;
            }
        }
        if (conditionElement != null) {
            element.remove(conditionElement);
        }

        conditionElement = docFactory.createElement(condition.toXMPP(), ERROR_NAMESPACE);
        element.add(conditionElement);
    }

    /**
     * Returns a text description of the error, or <tt>null</tt> if there
     * is no text description.
     *
     * @return the text description of the error.
     */
    public String getText() {
        return element.elementText("text");
    }

    /**
     * Sets the text description of the error.
     *
     * @param text the text description of the error.
     */
    public void setText(String text) {
        setText(text, null);
    }

    /**
     * Sets the text description of the error. Optionally, a language code
     * can be specified to indicate the language of the description.
     *
     * @param text the text description of the error.
     * @param language the language code of the description, or <tt>null</tt> to specify
     *      no language code.
     */
    public void setText(String text, String language) {
        Element textElement = element.element("text");
        // If text is null, clear the text.
        if (text == null) {
            if (textElement != null) {
                element.remove(textElement);
            }
            return;
        }

        if (textElement == null) {
            textElement = docFactory.createElement("text", ERROR_NAMESPACE);
            if (language != null) {
                textElement.addAttribute(QName.get("lang", "xml",
                        "http://www.w3.org/XML/1998/namespace"), language);
            }
            element.add(textElement);
        }
        textElement.setText(text);
    }

    /**
     * Returns the text description's language code, or <tt>null</tt> if there
     * is no language code associated with the description text.
     *
     * @return the language code of the text description, if it exists.
     */
    public String getTextLanguage() {
        Element textElement = element.element("text");
        if (textElement != null) {
            return textElement.attributeValue(QName.get("lang", "xml",
                        "http://www.w3.org/XML/1998/namespace"));
        }
        return null;
    }

    /**
     * Returns the DOM4J Element that backs the error. The element is the definitive
     * representation of the error and can be manipulated directly to change
     * error contents.
     *
     * @return the DOM4J Element.
     */
    public Element getElement() {
        return element;
    }

    /**
     * Returns the textual XML representation of this stream error.
     *
     * @return the textual XML representation of this stream error.
     */
    public String toXML() {
        return element.asXML();
    }

    public String toString() {
        StringWriter out = new StringWriter();
        XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
        try {
            writer.write(element);
        }
        catch (Exception e) { }
        return out.toString();
    }

    /**
     * Type-safe enumeration for the error condition.<p>
     *
     * Implementation note: XMPP error conditions use "-" characters in
     * their names such as "bad-request". Because "-" characters are not valid
     * identifier parts in Java, they have been converted to "_" characters in
     * the  enumeration names, such as <tt>bad_request</tt>. The {@link #toXMPP()} and
     * {@link #fromXMPP(String)} methods can be used to convert between the
     * enumertation values and XMPP error code strings.
     */
    public enum Condition {

        /**
         * The entity has sent XML that cannot be processed; this error MAY be used
         * instead of the more specific XML-related errors, such as &lt;bad-namespace-prefix/&gt;,
         * &lt;invalid-xml/&gt;, &lt;restricted-xml/&gt;, &lt;unsupported-encoding/&gt;, and
         * &lt;xml-not-well-formed/&gt;, although the more specific errors are preferred.
         */
        bad_format("bad-format"),

        /**
         * The entity has sent a namespace prefix that is unsupported, or has sent no
         * namespace prefix on an element that requires such a prefix.
         */
        bad_namespace_prefix("bad-namespace-prefix"),

        /**
         * The server is closing the active stream for this entity because a new stream
         * has been initiated that conflicts with the existing stream.
         */
        conflict("conflict"),

        /**
         * The entity has not generated any traffic over the stream for some period of
         * time (configurable according to a local service policy).
         */
        connection_timeout("connection-timeout"),

        /**
         * The value of the 'to' attribute provided by the initiating entity in the
         * stream header corresponds to a hostname that is no longer hosted by the server.
         */
        host_gone("host-gone"),

        /**
         * The value of the 'to' attribute provided by the initiating entity in the
         * stream header does not correspond to a hostname that is hosted by the server.
         */
        host_unknown("host-unknown"),

        /**
         * A stanza sent between two servers lacks a 'to' or 'from' attribute
         * (or the attribute has no value).
         */
        improper_addressing("improper-addressing"),

        /**
         * The server has experienced a misconfiguration or an otherwise-undefined
         * internal error that prevents it from servicing the stream.
         */
        internal_server_error("internal-server-error"),

        /**
         * The JID or hostname provided in a 'from' address does not match an authorized
         * JID or validated domain negotiated between servers via SASL or dialback, or
         * between a client and a server via authentication and resource binding.
         */
        invalid_from("invalid-from"),

        /**
         * The stream ID or dialback ID is invalid or does not match an ID previously provided.
         */
        invalid_id("invalid-id"),

        /**
         * the streams namespace name is something other than "http://etherx.jabber.org/streams"
         * or the dialback namespace name is something other than "jabber:server:dialback".
         */
        invalid_namespace("invalid-namespace"),

        /**
         * The entity has sent invalid XML over the stream to a server that performs validation.
         */
        invalid_xml("invalid-xml"),

        /**
         * The entity has attempted to send data before the stream has been authenticated,
         * or otherwise is not authorized to perform an action related to stream
         * negotiation; the receiving entity MUST NOT process the offending stanza before
         * sending the stream error.
         */
        not_authorized("not-authorized"),

        /**
         * The entity has violated some local service policy; the server MAY choose to
         * specify the policy in the <text/> element or an application-specific condition
         * element.
         */
        policy_violation("policy-violation"),

        /**
         * The server is unable to properly connect to a remote entity that is required for
         * authentication or authorization.
         */
        remote_connection_failed("remote-connection-failed"),

        /**
         * The server lacks the system resources necessary to service the stream.
         */
        resource_constraint("resource-constraint"),

        /**
         * The entity has attempted to send restricted XML features such as a comment,
         * processing instruction, DTD, entity reference, or unescaped character.
         */
        restricted_xml("restricted-xml"),

        /**
         * The server will not provide service to the initiating entity but is redirecting
         * traffic to another host; the server SHOULD specify the alternate hostname or IP
         * address (which MUST be a valid domain identifier) as the XML character data of the
         * &lt;see-other-host/&gt; element.
         */
        see_other_host("see-other-host"),

        /**
         * The server is being shut down and all active streams are being closed.
         */
        system_shutdown("system-shutdown"),

        /**
         * The error condition is not one of those defined by the other conditions in this
         * list; this error condition SHOULD be used only in conjunction with an
         * application-specific condition.
         */
        undefined_condition("undefined-condition"),

        /**
         * The initiating entity has encoded the stream in an encoding that is not
         * supported by the server.
         */
        unsupported_encoding("unsupported-encoding"),

        /**
         * The initiating entity has sent a first-level child of the stream that is
         * not supported by the server.
         */
        unsupported_stanza_type("unsupported-stanza-type"),

        /**
         * the value of the 'version' attribute provided by the initiating entity in the
         * stream header specifies a version of XMPP that is not supported by the server;
         * the server MAY specify the version(s) it supports in the &lt;text/&gt; element.
         */
        unsupported_version("unsupported-version"),

        /**
         * The initiating entity has sent XML that is not well-formed.
         */
        xml_not_well_formed("xml-not-well-formed");

        /**
         * Converts a String value into its Condition representation.
         *
         * @param condition the String value.
         * @return the condition corresponding to the String.
         */
        public static Condition fromXMPP(String condition) {
            if (condition == null) {
                throw new NullPointerException();
            }
            condition = condition.toLowerCase();
            if (bad_format.toXMPP().equals(condition)) {
                return bad_format;
            }
            else if (bad_namespace_prefix.toXMPP().equals(condition)) {
                return bad_namespace_prefix;
            }
            else if (conflict.toXMPP().equals(condition)) {
                return conflict;
            }
            else if (connection_timeout.toXMPP().equals(condition)) {
                return connection_timeout;
            }
            else if (host_gone.toXMPP().equals(condition)) {
                return host_gone;
            }
            else if (host_unknown.toXMPP().equals(condition)) {
                return host_unknown;
            }
            else if (improper_addressing.toXMPP().equals(condition)) {
                return improper_addressing;
            }
            else if (internal_server_error.toXMPP().equals(condition)) {
                return internal_server_error;
            }
            else if (invalid_from.toXMPP().equals(condition)) {
                return invalid_from;
            }
            else if (invalid_id.toXMPP().equals(condition)) {
                return invalid_id;
            }
            else if (invalid_namespace.toXMPP().equals(condition)) {
                return invalid_namespace;
            }
            else if (invalid_xml.toXMPP().equals(condition)) {
                return invalid_xml;
            }
            else if (not_authorized.toXMPP().equals(condition)) {
                return not_authorized;
            }
            else if (policy_violation.toXMPP().equals(condition)) {
                return policy_violation;
            }
            else if (remote_connection_failed.toXMPP().equals(condition)) {
                return remote_connection_failed;
            }
            else if (resource_constraint.toXMPP().equals(condition)) {
                return resource_constraint;
            }
            else if (restricted_xml.toXMPP().equals(condition)) {
                return restricted_xml;
            }
            else if (see_other_host.toXMPP().equals(condition)) {
                return see_other_host;
            }
            else if (system_shutdown.toXMPP().equals(condition)) {
                return system_shutdown;
            }
            else if (undefined_condition.toXMPP().equals(condition)) {
                return undefined_condition;
            }
            else if (unsupported_encoding.toXMPP().equals(condition)) {
                return unsupported_encoding;
            }
            else if (unsupported_stanza_type.toXMPP().equals(condition)) {
                return unsupported_stanza_type;
            }
            else if (unsupported_version.toXMPP().equals(condition)) {
                return unsupported_version;
            }
            else if (xml_not_well_formed.toXMPP().equals(condition)) {
                return xml_not_well_formed;
            }
            else {
                throw new IllegalArgumentException("Condition invalid:" + condition);
            }
        }

        private String value;

        private Condition(String value) {
            this.value = value;
        }

        /**
         * Returns the error code as a valid XMPP error code string.
         *
         * @return the XMPP error code value.
         */
        public String toXMPP() {
            return value;
        }
    }
}