001/**
002 *
003 * Copyright 2003-2007 Jive Software.
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.smack.packet;
018
019import java.util.Arrays;
020import java.util.HashMap;
021import java.util.List;
022import java.util.Locale;
023import java.util.Map;
024import java.util.logging.Logger;
025
026import org.jivesoftware.smack.util.StringUtils;
027import org.jivesoftware.smack.util.XmlStringBuilder;
028
029/**
030 * Represents an XMPP error sub-packet. Typically, a server responds to a request that has
031 * problems by sending the stanza(/packet) back and including an error packet. Each error has a type,
032 * error condition as well as as an optional text explanation. Typical errors are:<p>
033 *
034 * <table border=1>
035 *      <hr><td><b>XMPP Error Condition</b></td><td><b>Type</b></td><td><b>RFC 6120 Section</b></td></hr>
036 *      <tr><td>bad-request</td><td>MODIFY</td><td>8.3.3.1</td></tr>
037 *      <tr><td>conflict</td><td>CANCEL</td><td>8.3.3.2</td></tr>
038 *      <tr><td>feature-not-implemented</td><td>CANCEL</td><td>8.3.3.3</td></tr>
039 *      <tr><td>forbidden</td><td>AUTH</td><td>8.3.3.4</td></tr>
040 *      <tr><td>gone</td><td>MODIFY</td><td>8.3.3.5</td></tr>
041 *      <tr><td>internal-server-error</td><td>WAIT</td><td>8.3.3.6</td></tr>
042 *      <tr><td>item-not-found</td><td>CANCEL</td><td>8.3.3.7</td></tr>
043 *      <tr><td>jid-malformed</td><td>MODIFY</td><td>8.3.3.8</td></tr>
044 *      <tr><td>not-acceptable</td><td> MODIFY</td><td>8.3.3.9</td></tr>
045 *      <tr><td>not-allowed</td><td>CANCEL</td><td>8.3.3.10</td></tr>
046 *      <tr><td>not-authorized</td><td>AUTH</td><td>8.3.3.11</td></tr>
047 *      <tr><td>policy-violation</td><td>AUTH</td><td>8.3.3.12</td></tr>
048 *      <tr><td>recipient-unavailable</td><td>WAIT</td><td>8.3.3.13</td></tr>
049 *      <tr><td>redirect</td><td>MODIFY</td><td>8.3.3.14</td></tr>
050 *      <tr><td>registration-required</td><td>AUTH</td><td>8.3.3.15</td></tr>
051 *      <tr><td>remote-server-not-found</td><td>CANCEL</td><td>8.3.3.16</td></tr>
052 *      <tr><td>remote-server-timeout</td><td>WAIT</td><td>8.3.3.17</td></tr>
053 *      <tr><td>resource-constraint</td><td>WAIT</td><td>8.3.3.18</td></tr>
054 *      <tr><td>service-unavailable</td><td>CANCEL</td><td>8.3.3.19</td></tr>
055 *      <tr><td>subscription-required</td><td>AUTH</td><td>8.3.3.20</td></tr>
056 *      <tr><td>undefined-condition</td><td>WAIT</td><td>8.3.3.21</td></tr>
057 *      <tr><td>unexpected-request</td><td>WAIT</td><td>8.3.3.22</td></tr>
058 * </table>
059 *
060 * @author Matt Tucker
061 * @see <a href="http://xmpp.org/rfcs/rfc6120.html#stanzas-error-syntax">RFC 6120 - 8.3.2 Syntax: The Syntax of XMPP error stanzas</a>
062 */
063public class XMPPError extends AbstractError {
064
065    public static final String NAMESPACE = "urn:ietf:params:xml:ns:xmpp-stanzas";
066    public static final String ERROR = "error";
067
068    private static final Logger LOGGER = Logger.getLogger(XMPPError.class.getName());
069    private static final Map<Condition, Type> CONDITION_TO_TYPE = new HashMap<Condition, Type>();
070
071    static {
072        CONDITION_TO_TYPE.put(Condition.bad_request, Type.MODIFY);
073        CONDITION_TO_TYPE.put(Condition.conflict, Type.CANCEL);
074        CONDITION_TO_TYPE.put(Condition.feature_not_implemented, Type.CANCEL);
075        CONDITION_TO_TYPE.put(Condition.forbidden, Type.AUTH);
076        CONDITION_TO_TYPE.put(Condition.gone, Type.CANCEL);
077        CONDITION_TO_TYPE.put(Condition.internal_server_error, Type.CANCEL);
078        CONDITION_TO_TYPE.put(Condition.item_not_found, Type.CANCEL);
079        CONDITION_TO_TYPE.put(Condition.jid_malformed, Type.MODIFY);
080        CONDITION_TO_TYPE.put(Condition.not_acceptable, Type.MODIFY);
081        CONDITION_TO_TYPE.put(Condition.not_allowed, Type.CANCEL);
082        CONDITION_TO_TYPE.put(Condition.not_authorized, Type.AUTH);
083        CONDITION_TO_TYPE.put(Condition.policy_violation, Type.MODIFY);
084        CONDITION_TO_TYPE.put(Condition.recipient_unavailable, Type.WAIT);
085        CONDITION_TO_TYPE.put(Condition.redirect, Type.MODIFY);
086        CONDITION_TO_TYPE.put(Condition.registration_required, Type.AUTH);
087        CONDITION_TO_TYPE.put(Condition.remote_server_not_found, Type.CANCEL);
088        CONDITION_TO_TYPE.put(Condition.remote_server_timeout, Type.WAIT);
089        CONDITION_TO_TYPE.put(Condition.resource_constraint, Type.WAIT);
090        CONDITION_TO_TYPE.put(Condition.service_unavailable, Type.WAIT);
091        CONDITION_TO_TYPE.put(Condition.subscription_required, Type.WAIT);
092        CONDITION_TO_TYPE.put(Condition.unexpected_request, Type.MODIFY);
093    }
094    private final Condition condition;
095    private final String conditionText;
096    private final String errorGenerator;
097    private final Type type;
098
099    public XMPPError(Condition condition) {
100        this(condition, null, null, null, null, null);
101    }
102
103    public XMPPError(Condition condition, ExtensionElement applicationSpecificCondition) {
104        this(condition, null, null, null, null, Arrays.asList(applicationSpecificCondition));
105    }
106
107    /**
108     * Creates a new error with the specified type, condition and message.
109     * This constructor is used when the condition is not recognized automatically by XMPPError
110     * i.e. there is not a defined instance of ErrorCondition or it does not apply the default 
111     * specification.
112     * 
113     * @param type the error type.
114     * @param condition the error condition.
115     * @param descriptiveTexts 
116     * @param extensions list of stanza(/packet) extensions
117     */
118    public XMPPError(Condition condition, String conditionText, String errorGenerator, Type type, Map<String, String> descriptiveTexts,
119            List<ExtensionElement> extensions) {
120        super(descriptiveTexts, NAMESPACE, extensions);
121        this.condition = condition;
122        // Some implementations may send the condition as non-empty element containing the empty string, that is
123        // <condition xmlns='foo'></condition>, in this case the parser may calls this constructor with the empty string
124        // as conditionText, therefore reset it to null if it's the empty string
125        if (StringUtils.isNullOrEmpty(conditionText)) {
126            conditionText = null;
127        }
128        if (conditionText != null) {
129            switch (condition) {
130            case gone:
131            case redirect:
132                break;
133            default:
134                throw new IllegalArgumentException(
135                                "Condition text can only be set with condtion types 'gone' and 'redirect', not "
136                                                + condition);
137            }
138        }
139        this.conditionText = conditionText;
140        this.errorGenerator = errorGenerator;
141        if (type == null) {
142            Type determinedType = CONDITION_TO_TYPE.get(condition);
143            if (determinedType == null) {
144                LOGGER.warning("Could not determine type for condition: " + condition);
145                determinedType = Type.CANCEL;
146            }
147            this.type = determinedType;
148        } else {
149            this.type = type;
150        }
151    }
152
153    /**
154     * Returns the error condition.
155     *
156     * @return the error condition.
157     */
158    public Condition getCondition() {
159        return condition;
160    }
161
162    /**
163     * Returns the error type.
164     *
165     * @return the error type.
166     */
167    public Type getType() {
168        return type;
169    }
170
171    public String getErrorGenerator() {
172        return errorGenerator;
173    }
174
175    public String getConditionText() {
176        return conditionText;
177    }
178
179    @Override
180    public String toString() {
181        StringBuilder sb = new StringBuilder("XMPPError: ");
182        sb.append(condition.toString()).append(" - ").append(type.toString());
183        if (errorGenerator != null) {
184            sb.append(". Generated by ").append(errorGenerator);
185        }
186        return sb.toString();
187    }
188
189    /**
190     * Returns the error as XML.
191     *
192     * @return the error as XML.
193     */
194    public XmlStringBuilder toXML() {
195        XmlStringBuilder xml = new XmlStringBuilder();
196        xml.halfOpenElement(ERROR);
197        xml.attribute("type", type.toString());
198        xml.optAttribute("by", errorGenerator);
199        xml.rightAngleBracket();
200
201        xml.halfOpenElement(condition.toString());
202        xml.xmlnsAttribute(NAMESPACE);
203        if (conditionText != null) {
204            xml.rightAngleBracket();
205            xml.escape(conditionText);
206            xml.closeElement(condition.toString());
207        }
208        else {
209            xml.closeEmptyElement();
210        }
211
212        addDescriptiveTextsAndExtensions(xml);
213
214        xml.closeElement(ERROR);
215        return xml;
216    }
217
218    public static XMPPError from(Condition condition, String descriptiveText) {
219        Map<String, String> descriptiveTexts = new HashMap<String, String>();
220        descriptiveTexts.put("en", descriptiveText);
221        return new XMPPError(condition, null, null, null, descriptiveTexts, null);
222    }
223
224    /**
225     * A class to represent the type of the Error. The types are:
226     *
227     * <ul>
228     *      <li>XMPPError.Type.WAIT - retry after waiting (the error is temporary)
229     *      <li>XMPPError.Type.CANCEL - do not retry (the error is unrecoverable)
230     *      <li>XMPPError.Type.MODIFY - retry after changing the data sent
231     *      <li>XMPPError.Type.AUTH - retry after providing credentials
232     *      <li>XMPPError.Type.CONTINUE - proceed (the condition was only a warning)
233     * </ul>
234     */
235    public static enum Type {
236        WAIT,
237        CANCEL,
238        MODIFY,
239        AUTH,
240        CONTINUE;
241
242        @Override
243        public String toString() {
244            return name().toLowerCase(Locale.US);
245        }
246
247        public static Type fromString(String string) {
248            string = string.toUpperCase(Locale.US);
249            return Type.valueOf(string);
250        }
251    }
252
253    public enum Condition {
254        bad_request,
255        conflict,
256        feature_not_implemented,
257        forbidden,
258        gone,
259        internal_server_error,
260        item_not_found,
261        jid_malformed,
262        not_acceptable,
263        not_allowed,
264        not_authorized,
265        policy_violation,
266        recipient_unavailable,
267        redirect,
268        registration_required,
269        remote_server_not_found,
270        remote_server_timeout,
271        resource_constraint,
272        service_unavailable,
273        subscription_required,
274        undefined_condition,
275        unexpected_request;
276
277        @Override
278        public String toString() {
279            return this.name().replace('_', '-');
280        }
281
282        public static Condition fromString(String string) {
283            // Backwards compatibility for older implementations still using RFC 3920. RFC 6120
284            // changed 'xml-not-well-formed' to 'not-well-formed'.
285            if ("xml-not-well-formed".equals(string)) {
286                string = "not-well-formed";
287            }
288            string = string.replace('-', '_');
289            Condition condition = null;
290            try {
291                condition = Condition.valueOf(string);
292            } catch (Exception e) {
293                throw new IllegalStateException("Could not transform string '" + string + "' to XMPPErrorCondition", e);
294            }
295            return condition;
296        }
297    }
298
299}