Remove RestconfError.ErrorTag
[netconf.git] / restconf / restconf-common / src / main / java / org / opendaylight / restconf / common / errors / RestconfDocumentedException.java
1 /*
2  * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.restconf.common.errors;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.ImmutableList;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.List;
16 import javax.ws.rs.WebApplicationException;
17 import javax.ws.rs.core.Response.Status;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.restconf.common.ErrorTags;
21 import org.opendaylight.yangtools.yang.common.ErrorTag;
22 import org.opendaylight.yangtools.yang.common.ErrorType;
23 import org.opendaylight.yangtools.yang.common.OperationFailedException;
24 import org.opendaylight.yangtools.yang.common.RpcError;
25 import org.opendaylight.yangtools.yang.common.YangError;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.codec.YangInvalidValueException;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 /**
32  * Unchecked exception to communicate error information, as defined in the ietf restcong draft, to be sent to the
33  * client.
34  *
35  * <p>
36  * See also <a href="https://tools.ietf.org/html/draft-bierman-netconf-restconf-02">RESTCONF</a>
37  *
38  * @author Devin Avery
39  * @author Thomas Pantelis
40  */
41 public class RestconfDocumentedException extends WebApplicationException {
42     private static final Logger LOG = LoggerFactory.getLogger(RestconfDocumentedException.class);
43     private static final long serialVersionUID = 1L;
44
45     private final ImmutableList<RestconfError> errors;
46     private final Status status;
47
48     /**
49      * Constructs an instance with an error message. The error type defaults to APPLICATION and the error tag defaults
50      * to OPERATION_FAILED.
51      *
52      * @param message
53      *            A string which provides a plain text string describing the error.
54      */
55     public RestconfDocumentedException(final String message) {
56         this(message, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
57     }
58
59     /**
60      * Constructs an instance with an error message, error type, error tag and exception cause.
61      *
62      * @param message
63      *            A string which provides a plain text string describing the error.
64      * @param errorType
65      *            The enumerated type indicating the layer where the error occurred.
66      * @param errorTag
67      *            The enumerated tag representing a more specific error cause.
68      * @param cause
69      *            The underlying exception cause.
70      */
71     public RestconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
72                                        final Throwable cause) {
73         this(cause, new RestconfError(errorType, errorTag, message, null, cause.getMessage(), null));
74     }
75
76     /**
77      * Constructs an instance with an error message, error type, and error tag.
78      *
79      * @param message
80      *            A string which provides a plain text string describing the error.
81      * @param errorType
82      *            The enumerated type indicating the layer where the error occurred.
83      * @param errorTag
84      *            The enumerated tag representing a more specific error cause.
85      */
86     public RestconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag) {
87         this(null, new RestconfError(errorType, errorTag, message));
88     }
89
90     /**
91      * Constructs an instance with an error message, error type, error tag and error path.
92      *
93      * @param message
94      *            A string which provides a plain text string describing the error.
95      * @param errorType
96      *            The enumerated type indicating the layer where the error occurred.
97      * @param errorTag
98      *            The enumerated tag representing a more specific error cause.
99      * @param errorPath
100      *            The instance identifier representing error path
101      */
102     public RestconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
103                                        final YangInstanceIdentifier errorPath) {
104         this(null, new RestconfError(errorType, errorTag, message, errorPath));
105     }
106
107     /**
108      * Constructs an instance with an error message and exception cause.
109      * The underlying exception is included in the error-info.
110      *
111      * @param message
112      *            A string which provides a plain text string describing the error.
113      * @param cause
114      *            The underlying exception cause.
115      */
116     public RestconfDocumentedException(final String message, final Throwable cause) {
117         this(cause, new RestconfError(ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, message, null,
118             cause.getMessage(), null));
119     }
120
121     /**
122      * Constructs an instance with the given error.
123      */
124     public RestconfDocumentedException(final RestconfError error) {
125         this(null, error);
126     }
127
128     /**
129      * Constructs an instance with the given errors.
130      */
131     public RestconfDocumentedException(final String message, final Throwable cause, final List<RestconfError> errors) {
132         // FIXME: We override getMessage so supplied message is lost for any public access
133         // this was lost also in original code.
134         super(cause);
135         if (!errors.isEmpty()) {
136             this.errors = ImmutableList.copyOf(errors);
137         } else {
138             this.errors = ImmutableList.of(
139                 new RestconfError(ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, message));
140         }
141
142         status = null;
143     }
144
145     /**
146      * Constructs an instance with the given RpcErrors.
147      */
148     public RestconfDocumentedException(final String message, final Throwable cause,
149                                        final Collection<? extends RpcError> rpcErrors) {
150         this(message, cause, convertToRestconfErrors(rpcErrors));
151     }
152
153     /**
154      * Constructs an instance with an HTTP status and no error information.
155      *
156      * @param status
157      *            the HTTP status.
158      */
159     public RestconfDocumentedException(final Status status) {
160         errors = ImmutableList.of();
161         this.status = requireNonNull(status, "Status can't be null");
162     }
163
164     public RestconfDocumentedException(final Throwable cause, final RestconfError error) {
165         super(cause, ErrorTags.statusOf(error.getErrorTag()));
166         errors = ImmutableList.of(error);
167         status = null;
168     }
169
170     public static RestconfDocumentedException decodeAndThrow(final String message,
171             final OperationFailedException cause) {
172         for (final RpcError error : cause.getErrorList()) {
173             if (error.getErrorType() == RpcError.ErrorType.TRANSPORT
174                     && error.getTag().equals(ErrorTag.RESOURCE_DENIED.elementBody())) {
175                 throw new RestconfDocumentedException(error.getMessage(), ErrorType.TRANSPORT,
176                     ErrorTags.RESOURCE_DENIED_TRANSPORT, cause);
177             }
178         }
179         throw new RestconfDocumentedException(message, cause, cause.getErrorList());
180     }
181
182     /**
183      * Throw an instance of this exception if an expression evaluates to true. If the expression evaluates to false,
184      * this method does nothing.
185      *
186      * @param expression Expression to be evaluated
187      * @param errorType The enumerated type indicating the layer where the error occurred.
188      * @param errorTag The enumerated tag representing a more specific error cause.
189      * @param format Format string, according to {@link String#format(String, Object...)}.
190      * @param args Format string arguments, according to {@link String#format(String, Object...)}
191      * @throws RestconfDocumentedException if the expression evaluates to true.
192      */
193     public static void throwIf(final boolean expression, final ErrorType errorType, final ErrorTag errorTag,
194             final @NonNull String format, final Object... args) {
195         if (expression) {
196             throw new RestconfDocumentedException(String.format(format, args), errorType, errorTag);
197         }
198     }
199
200     /**
201      * Throw an instance of this exception if an expression evaluates to true. If the expression evaluates to false,
202      * this method does nothing.
203      *
204      * @param expression Expression to be evaluated
205      * @param message error message
206      * @param errorType The enumerated type indicating the layer where the error occurred.
207      * @param errorTag The enumerated tag representing a more specific error cause.
208      * @throws RestconfDocumentedException if the expression evaluates to true.
209      */
210     public static void throwIf(final boolean expression, final @NonNull String message,
211             final ErrorType errorType, final ErrorTag errorTag) {
212         if (expression) {
213             throw new RestconfDocumentedException(message, errorType, errorTag);
214         }
215     }
216
217     /**
218      * Throw an instance of this exception if an object is null. If the object is non-null, it will
219      * be returned as the result of this method.
220      *
221      * @param obj Object reference to be checked
222      * @param errorType The enumerated type indicating the layer where the error occurred.
223      * @param errorTag The enumerated tag representing a more specific error cause.
224      * @param format Format string, according to {@link String#format(String, Object...)}.
225      * @param args Format string arguments, according to {@link String#format(String, Object...)}
226      * @throws RestconfDocumentedException if the expression evaluates to true.
227      */
228     public static <T> @NonNull T throwIfNull(final @Nullable T obj, final ErrorType errorType, final ErrorTag errorTag,
229             final @NonNull String format, final Object... args) {
230         if (obj == null) {
231             throw new RestconfDocumentedException(String.format(format, args), errorType, errorTag);
232         }
233         return obj;
234     }
235
236     /**
237      * Throw an instance of this exception if the specified exception has a {@link YangError} attachment.
238      *
239      * @param cause Proposed cause of a RestconfDocumented exception
240      */
241     public static void throwIfYangError(final Throwable cause) {
242         if (cause instanceof YangError) {
243             final YangError error = (YangError) cause;
244             throw new RestconfDocumentedException(cause, new RestconfError(error.getErrorType().toNetconf(),
245                 // FIXME: this is a special-case until we have YangError.getTag()
246                 cause instanceof YangInvalidValueException ? ErrorTag.INVALID_VALUE : ErrorTag.MALFORMED_MESSAGE,
247                     error.getErrorMessage().orElse(null), error.getErrorAppTag().orElse(null)));
248         }
249     }
250
251     private static List<RestconfError> convertToRestconfErrors(final Collection<? extends RpcError> rpcErrors) {
252         final List<RestconfError> errorList = new ArrayList<>();
253         if (rpcErrors != null) {
254             for (RpcError rpcError : rpcErrors) {
255                 errorList.add(new RestconfError(rpcError));
256             }
257         }
258
259         return errorList;
260     }
261
262     public List<RestconfError> getErrors() {
263         return errors;
264     }
265
266     public Status getStatus() {
267         return status;
268     }
269
270     @Override
271     public String getMessage() {
272         return "errors: " + errors + (status != null ? ", status: " + status : "");
273     }
274 }