2 * Copyright © 2019 FRINX s.r.o. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.jersey.providers.errors;
10 import static com.google.common.base.Preconditions.checkState;
12 import com.google.common.annotations.VisibleForTesting;
13 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import java.io.ByteArrayOutputStream;
15 import java.io.IOException;
16 import java.io.OutputStreamWriter;
17 import java.nio.charset.StandardCharsets;
18 import java.util.Collections;
19 import java.util.LinkedHashSet;
20 import java.util.List;
21 import java.util.Optional;
23 import java.util.stream.Collectors;
24 import javax.ws.rs.core.Context;
25 import javax.ws.rs.core.HttpHeaders;
26 import javax.ws.rs.core.MediaType;
27 import javax.ws.rs.core.Response;
28 import javax.ws.rs.core.Response.Status;
29 import javax.ws.rs.ext.ExceptionMapper;
30 import javax.ws.rs.ext.Provider;
31 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
32 import org.opendaylight.restconf.common.errors.RestconfError;
33 import org.opendaylight.restconf.nb.rfc8040.Rfc8040.MediaTypes;
34 import org.opendaylight.restconf.nb.rfc8040.Rfc8040.RestconfModule;
35 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
36 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
43 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
44 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
45 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
46 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUnkeyedListEntryNodeBuilder;
47 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUnkeyedListNodeBuilder;
48 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 * Mapper that is responsible for transformation of thrown {@link RestconfDocumentedException} to errors structure
54 * that is modelled by RESTCONF module (see section 8 of RFC-8040).
57 public final class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
59 static final MediaType YANG_DATA_JSON_TYPE = MediaType.valueOf(MediaTypes.DATA + RestconfConstants.JSON);
61 static final MediaType YANG_DATA_XML_TYPE = MediaType.valueOf(MediaTypes.DATA + RestconfConstants.XML);
63 static final MediaType YANG_PATCH_JSON_TYPE = MediaType.valueOf(MediaTypes.YANG_PATCH + RestconfConstants.JSON);
65 static final MediaType YANG_PATCH_XML_TYPE = MediaType.valueOf(MediaTypes.YANG_PATCH + RestconfConstants.XML);
67 private static final Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
68 private static final MediaType DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_JSON_TYPE;
69 private static final Status DEFAULT_STATUS_CODE = Status.INTERNAL_SERVER_ERROR;
70 private static final SchemaPath ERRORS_GROUPING_PATH = SchemaPath.create(true,
71 RestconfModule.ERRORS_GROUPING_QNAME);
74 private HttpHeaders headers;
75 private final SchemaContextHandler schemaContextHandler;
78 * Initialization of the exception mapper.
80 * @param schemaContextHandler Handler that provides actual schema context.
82 public RestconfDocumentedExceptionMapper(final SchemaContextHandler schemaContextHandler) {
83 this.schemaContextHandler = schemaContextHandler;
87 @SuppressFBWarnings(value = "SLF4J_MANUALLY_PROVIDED_MESSAGE", justification = "In the debug messages "
88 + "we don't to have full stack trace - getMessage(..) method provides finer output.")
89 public Response toResponse(final RestconfDocumentedException exception) {
90 LOG.debug("Starting to map received exception to error response: {}", exception.getMessage());
91 final Status responseStatus = getResponseStatusCode(exception);
92 if (responseStatus != Response.Status.FORBIDDEN
93 && responseStatus.getFamily() == Response.Status.Family.CLIENT_ERROR) {
94 // there should be at least one error entry for 4xx errors except 409 according to the RFC 8040
95 // - creation of WARN log that something went wrong way on the server side
96 LOG.warn("Input exception has a family of 4xx but doesn't contain any descriptive errors: {}",
97 exception.getMessage());
100 final ContainerNode errorsContainer = buildErrorsContainer(exception);
101 final String serializedResponseBody;
102 final MediaType responseMediaType = transformToResponseMediaType(getSupportedMediaType());
103 if (YANG_DATA_JSON_TYPE.equals(responseMediaType)) {
104 serializedResponseBody = serializeErrorsContainerToJson(errorsContainer);
106 serializedResponseBody = serializeErrorsContainerToXml(errorsContainer);
109 final Response preparedResponse = Response.status(responseStatus)
110 .type(responseMediaType)
111 .entity(serializedResponseBody)
113 LOG.debug("Exception {} has been successfully mapped to response: {}",
114 exception.getMessage(), preparedResponse);
115 return preparedResponse;
119 * Filling up of the errors container with data from input {@link RestconfDocumentedException}.
121 * @param exception Thrown exception.
122 * @return Built errors container.
124 private ContainerNode buildErrorsContainer(final RestconfDocumentedException exception) {
125 final List<UnkeyedListEntryNode> errorEntries = exception.getErrors().stream()
126 .map(this::createErrorEntry)
127 .collect(Collectors.toList());
128 return ImmutableContainerNodeBuilder.create()
129 .withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(
130 RestconfModule.ERRORS_CONTAINER_QNAME))
131 .withChild(ImmutableUnkeyedListNodeBuilder.create()
132 .withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(
133 RestconfModule.ERROR_LIST_QNAME))
134 .withValue(errorEntries)
140 * Building of one error entry using provided {@link RestconfError}.
142 * @param restconfError Error details.
143 * @return Built list entry.
145 private UnkeyedListEntryNode createErrorEntry(final RestconfError restconfError) {
146 // filling in mandatory leafs
147 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> entryBuilder
148 = ImmutableUnkeyedListEntryNodeBuilder.create()
149 .withNodeIdentifier(NodeIdentifier.create(RestconfModule.ERROR_LIST_QNAME))
150 .withChild(ImmutableNodes.leafNode(RestconfModule.ERROR_TYPE_QNAME,
151 restconfError.getErrorType().getErrorTypeTag()))
152 .withChild(ImmutableNodes.leafNode(RestconfModule.ERROR_TAG_QNAME,
153 restconfError.getErrorTag().getTagValue()));
155 // filling in optional fields
156 if (restconfError.getErrorMessage() != null) {
157 entryBuilder.withChild(ImmutableNodes.leafNode(
158 RestconfModule.ERROR_MESSAGE_QNAME, restconfError.getErrorMessage()));
160 if (restconfError.getErrorAppTag() != null) {
161 entryBuilder.withChild(ImmutableNodes.leafNode(
162 RestconfModule.ERROR_APP_TAG_QNAME, restconfError.getErrorAppTag()));
164 if (restconfError.getErrorInfo() != null) {
165 // Oddly, error-info is defined as an empty container in the restconf yang. Apparently the
166 // intention is for implementors to define their own data content so we'll just treat it as a leaf
168 entryBuilder.withChild(ImmutableNodes.leafNode(
169 RestconfModule.ERROR_INFO_QNAME, restconfError.getErrorInfo()));
172 if (restconfError.getErrorPath() != null) {
173 entryBuilder.withChild(ImmutableNodes.leafNode(
174 RestconfModule.ERROR_PATH_QNAME, restconfError.getErrorPath()));
176 return entryBuilder.build();
180 * Serialization of the errors container into JSON representation.
182 * @param errorsContainer To be serialized errors container.
183 * @return JSON representation of the errors container.
185 private String serializeErrorsContainerToJson(final ContainerNode errorsContainer) {
186 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
187 OutputStreamWriter streamStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
189 return writeNormalizedNode(errorsContainer, outputStream, new JsonStreamWriterWithDisabledValidation(
190 RestconfModule.ERROR_INFO_QNAME, streamStreamWriter, ERRORS_GROUPING_PATH,
191 RestconfModule.URI_MODULE, schemaContextHandler));
192 } catch (IOException e) {
193 throw new IllegalStateException("Cannot close some of the output JSON writers", e);
198 * Serialization of the errors container into XML representation.
200 * @param errorsContainer To be serialized errors container.
201 * @return XML representation of the errors container.
203 private String serializeErrorsContainerToXml(final ContainerNode errorsContainer) {
204 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
205 return writeNormalizedNode(errorsContainer, outputStream, new XmlStreamWriterWithDisabledValidation(
206 RestconfModule.ERROR_INFO_QNAME, outputStream, ERRORS_GROUPING_PATH, schemaContextHandler));
207 } catch (IOException e) {
208 throw new IllegalStateException("Cannot close some of the output XML writers", e);
212 private static String writeNormalizedNode(final NormalizedNode<?, ?> errorsContainer,
213 final ByteArrayOutputStream outputStream, final StreamWriterWithDisabledValidation streamWriter) {
214 try (NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter)) {
215 nnWriter.write(errorsContainer);
216 } catch (IOException e) {
217 throw new IllegalStateException("Cannot write error response body", e);
219 return outputStream.toString(StandardCharsets.UTF_8);
223 * Deriving of the status code from the thrown exception. At the first step, status code is tried to be read using
224 * {@link RestconfDocumentedException#getStatus()}. If it is {@code null}, status code will be derived from status
225 * codes appended to error entries (the first that will be found). If there are not any error entries,
226 * {@link RestconfDocumentedExceptionMapper#DEFAULT_STATUS_CODE} will be used.
228 * @param exception Thrown exception.
229 * @return Derived status code.
231 private static Status getResponseStatusCode(final RestconfDocumentedException exception) {
232 final Status status = exception.getStatus();
233 if (status != null) {
234 // status code that is specified directly as field in exception has the precedence over error entries
238 final List<RestconfError> errors = exception.getErrors();
239 if (errors.isEmpty()) {
240 // if the module, that thrown exception, doesn't specify status code, it is treated as internal
242 return DEFAULT_STATUS_CODE;
245 final Set<Integer> allStatusCodesOfErrorEntries = errors.stream()
246 .map(restconfError -> restconfError.getErrorTag().getStatusCode())
247 // we would like to preserve iteration order in collected entries - hence usage of LinkedHashSet
248 .collect(Collectors.toCollection(LinkedHashSet::new));
249 // choosing of the first status code from appended errors, if there are different status codes in error
250 // entries, we should create WARN message
251 if (allStatusCodesOfErrorEntries.size() > 1) {
252 LOG.warn("An unexpected error occurred during translation of exception {} to response: "
253 + "Different status codes have been found in appended error entries: {}. The first error "
254 + "entry status code is chosen for response.", exception, allStatusCodesOfErrorEntries);
256 return Status.fromStatusCode(allStatusCodesOfErrorEntries.iterator().next());
260 * Selection of media type that will be used for creation suffix of 'application/yang-data'. Selection criteria
261 * is described in RFC 8040, section 7.1. At the first step, accepted media-type is analyzed and only supported
262 * media-types are filtered out. If both XML and JSON media-types are accepted, JSON is selected as a default one
263 * used in RESTCONF. If accepted-media type is not specified, the media-type used in request is chosen only if it
264 * is supported one. If it is not supported or it is not specified, again, the default one (JSON) is selected.
266 * @return Media type.
268 private MediaType getSupportedMediaType() {
269 final Set<MediaType> acceptableAndSupportedMediaTypes = headers.getAcceptableMediaTypes().stream()
270 .filter(RestconfDocumentedExceptionMapper::isCompatibleMediaType)
271 .collect(Collectors.toSet());
272 if (acceptableAndSupportedMediaTypes.size() == 0) {
273 // check content type of the request
274 final MediaType requestMediaType = headers.getMediaType();
275 return requestMediaType == null ? DEFAULT_MEDIA_TYPE
276 : chooseMediaType(Collections.singletonList(requestMediaType)).orElseGet(() -> {
277 LOG.warn("Request doesn't specify accepted media-types and the media-type '{}' used by "
278 + "request is not supported - using of default '{}' media-type.",
279 requestMediaType, DEFAULT_MEDIA_TYPE);
280 return DEFAULT_MEDIA_TYPE;
284 // at first step, fully specified types without any wildcards are considered (for example, application/json)
285 final List<MediaType> fullySpecifiedMediaTypes = acceptableAndSupportedMediaTypes.stream()
286 .filter(mediaType -> !mediaType.isWildcardType() && !mediaType.isWildcardSubtype())
287 .collect(Collectors.toList());
288 if (!fullySpecifiedMediaTypes.isEmpty()) {
289 return chooseAndCheckMediaType(fullySpecifiedMediaTypes);
292 // at the second step, only types with specified subtype are considered (for example, */json)
293 final List<MediaType> mediaTypesWithSpecifiedSubtypes = acceptableAndSupportedMediaTypes.stream()
294 .filter(mediaType -> !mediaType.isWildcardSubtype())
295 .collect(Collectors.toList());
296 if (!mediaTypesWithSpecifiedSubtypes.isEmpty()) {
297 return chooseAndCheckMediaType(mediaTypesWithSpecifiedSubtypes);
300 // at the third step, only types with specified parent are considered (for example, application/*)
301 final List<MediaType> mediaTypesWithSpecifiedParent = acceptableAndSupportedMediaTypes.stream()
302 .filter(mediaType -> !mediaType.isWildcardType())
303 .collect(Collectors.toList());
304 if (!mediaTypesWithSpecifiedParent.isEmpty()) {
305 return chooseAndCheckMediaType(mediaTypesWithSpecifiedParent);
308 // it must be fully-wildcard-ed type - */*
309 return DEFAULT_MEDIA_TYPE;
312 private static MediaType chooseAndCheckMediaType(final List<MediaType> options) {
313 final Optional<MediaType> mediaTypeOpt = chooseMediaType(options);
314 checkState(mediaTypeOpt.isPresent());
315 return mediaTypeOpt.get();
319 * This method is responsible for choosing of he media type from multiple options. At the first step,
320 * JSON-compatible types are considered, then, if there are not any JSON types, XML types are considered. The first
321 * compatible media-type is chosen.
323 * @param options Supported media types.
324 * @return Selected one media type or {@link Optional#empty()} if none of the provided options are compatible with
327 private static Optional<MediaType> chooseMediaType(final List<MediaType> options) {
328 return options.stream()
329 .filter(RestconfDocumentedExceptionMapper::isJsonCompatibleMediaType)
332 .orElse(options.stream()
333 .filter(RestconfDocumentedExceptionMapper::isXmlCompatibleMediaType)
338 * Mapping of JSON-compatible type to {@link RestconfDocumentedExceptionMapper#YANG_DATA_JSON_TYPE}
339 * or XML-compatible type to {@link RestconfDocumentedExceptionMapper#YANG_DATA_XML_TYPE}.
341 * @param mediaTypeBase Base media type from which the response media-type is built.
342 * @return Derived media type.
344 private static MediaType transformToResponseMediaType(final MediaType mediaTypeBase) {
345 if (isJsonCompatibleMediaType(mediaTypeBase)) {
346 return YANG_DATA_JSON_TYPE;
347 } else if (isXmlCompatibleMediaType(mediaTypeBase)) {
348 return YANG_DATA_XML_TYPE;
350 throw new IllegalStateException(String.format("Unexpected input media-type %s "
351 + "- it should be JSON/XML compatible type.", mediaTypeBase));
355 private static boolean isCompatibleMediaType(final MediaType mediaType) {
356 return isJsonCompatibleMediaType(mediaType) || isXmlCompatibleMediaType(mediaType);
359 private static boolean isJsonCompatibleMediaType(final MediaType mediaType) {
360 return mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE)
361 || mediaType.isCompatible(YANG_DATA_JSON_TYPE) || mediaType.isCompatible(YANG_PATCH_JSON_TYPE);
364 private static boolean isXmlCompatibleMediaType(final MediaType mediaType) {
365 return mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)
366 || mediaType.isCompatible(YANG_DATA_XML_TYPE) || mediaType.isCompatible(YANG_PATCH_XML_TYPE);
370 * Used just for testing purposes - simulation of HTTP headers with different accepted types and content type.
372 * @param httpHeaders Mocked HTTP headers.
375 void setHttpHeaders(final HttpHeaders httpHeaders) {
376 this.headers = httpHeaders;