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;
11 import static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.$YangModuleInfoImpl.qnameOf;
13 import com.google.common.annotations.VisibleForTesting;
14 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
15 import java.io.ByteArrayOutputStream;
16 import java.io.IOException;
17 import java.io.OutputStreamWriter;
18 import java.nio.charset.StandardCharsets;
19 import java.util.Collections;
20 import java.util.LinkedHashSet;
21 import java.util.List;
22 import java.util.Optional;
24 import java.util.stream.Collectors;
25 import javax.ws.rs.core.Context;
26 import javax.ws.rs.core.HttpHeaders;
27 import javax.ws.rs.core.MediaType;
28 import javax.ws.rs.core.Response;
29 import javax.ws.rs.core.Response.Status;
30 import javax.ws.rs.ext.ExceptionMapper;
31 import javax.ws.rs.ext.Provider;
32 import org.opendaylight.restconf.common.ErrorTags;
33 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
34 import org.opendaylight.restconf.common.errors.RestconfError;
35 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
36 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.errors.Errors;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.errors.errors.Error;
39 import org.opendaylight.yangtools.yang.common.QName;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
45 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
46 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
51 * Mapper that is responsible for transformation of thrown {@link RestconfDocumentedException} to errors structure
52 * that is modelled by RESTCONF module (see section 8 of RFC-8040).
55 public final class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
56 private static final Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
57 private static final MediaType DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_JSON_TYPE;
58 private static final Status DEFAULT_STATUS_CODE = Status.INTERNAL_SERVER_ERROR;
59 private static final QName ERROR_TYPE_QNAME = qnameOf("error-type");
60 private static final QName ERROR_TAG_QNAME = qnameOf("error-tag");
61 private static final QName ERROR_APP_TAG_QNAME = qnameOf("error-app-tag");
62 private static final QName ERROR_MESSAGE_QNAME = qnameOf("error-message");
63 private static final QName ERROR_PATH_QNAME = qnameOf("error-path");
64 static final QName ERROR_INFO_QNAME = qnameOf("error-info");
67 private HttpHeaders headers;
68 private final SchemaContextHandler schemaContextHandler;
71 * Initialization of the exception mapper.
73 * @param schemaContextHandler Handler that provides actual schema context.
75 public RestconfDocumentedExceptionMapper(final SchemaContextHandler schemaContextHandler) {
76 this.schemaContextHandler = schemaContextHandler;
80 @SuppressFBWarnings(value = "SLF4J_MANUALLY_PROVIDED_MESSAGE", justification = "In the debug messages "
81 + "we don't to have full stack trace - getMessage(..) method provides finer output.")
82 public Response toResponse(final RestconfDocumentedException exception) {
83 LOG.debug("Starting to map received exception to error response: {}", exception.getMessage());
84 final Status responseStatus = getResponseStatusCode(exception);
85 if (responseStatus != Response.Status.FORBIDDEN
86 && responseStatus.getFamily() == Response.Status.Family.CLIENT_ERROR
87 && exception.getErrors().isEmpty()) {
88 // There should be at least one error entry for 4xx errors except 409 according to RFC8040, but we do not
89 // have it. Issue a warning with the call trace so we can fix whoever was the originator.
90 LOG.warn("Input exception has a family of 4xx but does not contain any descriptive errors", exception);
93 final ContainerNode errorsContainer = buildErrorsContainer(exception);
94 final String serializedResponseBody;
95 final MediaType responseMediaType = transformToResponseMediaType(getSupportedMediaType());
96 if (MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE.equals(responseMediaType)) {
97 serializedResponseBody = serializeErrorsContainerToJson(errorsContainer);
99 serializedResponseBody = serializeErrorsContainerToXml(errorsContainer);
102 final Response preparedResponse = Response.status(responseStatus)
103 .type(responseMediaType)
104 .entity(serializedResponseBody)
106 LOG.debug("Exception {} has been successfully mapped to response: {}",
107 exception.getMessage(), preparedResponse);
108 return preparedResponse;
112 * Filling up of the errors container with data from input {@link RestconfDocumentedException}.
114 * @param exception Thrown exception.
115 * @return Built errors container.
117 private static ContainerNode buildErrorsContainer(final RestconfDocumentedException exception) {
118 return Builders.containerBuilder()
119 .withNodeIdentifier(NodeIdentifier.create(Errors.QNAME))
120 .withChild(Builders.unkeyedListBuilder()
121 .withNodeIdentifier(NodeIdentifier.create(Error.QNAME))
122 .withValue(exception.getErrors().stream()
123 .map(RestconfDocumentedExceptionMapper::createErrorEntry)
124 .collect(Collectors.toList()))
130 * Building of one error entry using provided {@link RestconfError}.
132 * @param restconfError Error details.
133 * @return Built list entry.
135 private static UnkeyedListEntryNode createErrorEntry(final RestconfError restconfError) {
136 // filling in mandatory leafs
137 final var entryBuilder = Builders.unkeyedListEntryBuilder()
138 .withNodeIdentifier(NodeIdentifier.create(Error.QNAME))
139 .withChild(ImmutableNodes.leafNode(ERROR_TYPE_QNAME, restconfError.getErrorType().elementBody()))
140 .withChild(ImmutableNodes.leafNode(ERROR_TAG_QNAME, restconfError.getErrorTag().elementBody()));
142 // filling in optional fields
143 if (restconfError.getErrorMessage() != null) {
144 entryBuilder.withChild(ImmutableNodes.leafNode(ERROR_MESSAGE_QNAME, restconfError.getErrorMessage()));
146 if (restconfError.getErrorAppTag() != null) {
147 entryBuilder.withChild(ImmutableNodes.leafNode(ERROR_APP_TAG_QNAME, restconfError.getErrorAppTag()));
149 if (restconfError.getErrorInfo() != null) {
150 // Oddly, error-info is defined as an empty container in the restconf yang. Apparently the
151 // intention is for implementors to define their own data content so we'll just treat it as a leaf
153 entryBuilder.withChild(ImmutableNodes.leafNode(ERROR_INFO_QNAME, restconfError.getErrorInfo()));
156 if (restconfError.getErrorPath() != null) {
157 entryBuilder.withChild(ImmutableNodes.leafNode(ERROR_PATH_QNAME, restconfError.getErrorPath()));
159 return entryBuilder.build();
163 * Serialization of the errors container into JSON representation.
165 * @param errorsContainer To be serialized errors container.
166 * @return JSON representation of the errors container.
168 private String serializeErrorsContainerToJson(final ContainerNode errorsContainer) {
169 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
170 OutputStreamWriter streamStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
172 return writeNormalizedNode(errorsContainer, outputStream,
173 new JsonStreamWriterWithDisabledValidation(schemaContextHandler, streamStreamWriter));
174 } catch (IOException e) {
175 throw new IllegalStateException("Cannot close some of the output JSON writers", e);
180 * Serialization of the errors container into XML representation.
182 * @param errorsContainer To be serialized errors container.
183 * @return XML representation of the errors container.
185 private String serializeErrorsContainerToXml(final ContainerNode errorsContainer) {
186 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
187 return writeNormalizedNode(errorsContainer, outputStream,
188 new XmlStreamWriterWithDisabledValidation(schemaContextHandler, outputStream));
189 } catch (IOException e) {
190 throw new IllegalStateException("Cannot close some of the output XML writers", e);
194 private static String writeNormalizedNode(final NormalizedNode errorsContainer,
195 final ByteArrayOutputStream outputStream, final StreamWriterWithDisabledValidation streamWriter) {
196 try (NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter)) {
197 nnWriter.write(errorsContainer);
198 } catch (IOException e) {
199 throw new IllegalStateException("Cannot write error response body", e);
201 return outputStream.toString(StandardCharsets.UTF_8);
205 * Deriving of the status code from the thrown exception. At the first step, status code is tried to be read using
206 * {@link RestconfDocumentedException#getStatus()}. If it is {@code null}, status code will be derived from status
207 * codes appended to error entries (the first that will be found). If there are not any error entries,
208 * {@link RestconfDocumentedExceptionMapper#DEFAULT_STATUS_CODE} will be used.
210 * @param exception Thrown exception.
211 * @return Derived status code.
213 private static Status getResponseStatusCode(final RestconfDocumentedException exception) {
214 final Status status = exception.getStatus();
215 if (status != null) {
216 // status code that is specified directly as field in exception has the precedence over error entries
220 final List<RestconfError> errors = exception.getErrors();
221 if (errors.isEmpty()) {
222 // if the module, that thrown exception, doesn't specify status code, it is treated as internal
224 return DEFAULT_STATUS_CODE;
227 final Set<Status> allStatusCodesOfErrorEntries = errors.stream()
228 .map(restconfError -> ErrorTags.statusOf(restconfError.getErrorTag()))
229 // we would like to preserve iteration order in collected entries - hence usage of LinkedHashSet
230 .collect(Collectors.toCollection(LinkedHashSet::new));
231 // choosing of the first status code from appended errors, if there are different status codes in error
232 // entries, we should create WARN message
233 if (allStatusCodesOfErrorEntries.size() > 1) {
234 LOG.warn("An unexpected error occurred during translation of exception {} to response: "
235 + "Different status codes have been found in appended error entries: {}. The first error "
236 + "entry status code is chosen for response.", exception, allStatusCodesOfErrorEntries);
238 return allStatusCodesOfErrorEntries.iterator().next();
242 * Selection of media type that will be used for creation suffix of 'application/yang-data'. Selection criteria
243 * is described in RFC 8040, section 7.1. At the first step, accepted media-type is analyzed and only supported
244 * media-types are filtered out. If both XML and JSON media-types are accepted, JSON is selected as a default one
245 * used in RESTCONF. If accepted-media type is not specified, the media-type used in request is chosen only if it
246 * is supported one. If it is not supported or it is not specified, again, the default one (JSON) is selected.
248 * @return Media type.
250 private MediaType getSupportedMediaType() {
251 final Set<MediaType> acceptableAndSupportedMediaTypes = headers.getAcceptableMediaTypes().stream()
252 .filter(RestconfDocumentedExceptionMapper::isCompatibleMediaType)
253 .collect(Collectors.toSet());
254 if (acceptableAndSupportedMediaTypes.isEmpty()) {
255 // check content type of the request
256 final MediaType requestMediaType = headers.getMediaType();
257 return requestMediaType == null ? DEFAULT_MEDIA_TYPE
258 : chooseMediaType(Collections.singletonList(requestMediaType)).orElseGet(() -> {
259 LOG.warn("Request doesn't specify accepted media-types and the media-type '{}' used by "
260 + "request is not supported - using of default '{}' media-type.",
261 requestMediaType, DEFAULT_MEDIA_TYPE);
262 return DEFAULT_MEDIA_TYPE;
266 // at first step, fully specified types without any wildcards are considered (for example, application/json)
267 final List<MediaType> fullySpecifiedMediaTypes = acceptableAndSupportedMediaTypes.stream()
268 .filter(mediaType -> !mediaType.isWildcardType() && !mediaType.isWildcardSubtype())
269 .collect(Collectors.toList());
270 if (!fullySpecifiedMediaTypes.isEmpty()) {
271 return chooseAndCheckMediaType(fullySpecifiedMediaTypes);
274 // at the second step, only types with specified subtype are considered (for example, */json)
275 final List<MediaType> mediaTypesWithSpecifiedSubtypes = acceptableAndSupportedMediaTypes.stream()
276 .filter(mediaType -> !mediaType.isWildcardSubtype())
277 .collect(Collectors.toList());
278 if (!mediaTypesWithSpecifiedSubtypes.isEmpty()) {
279 return chooseAndCheckMediaType(mediaTypesWithSpecifiedSubtypes);
282 // at the third step, only types with specified parent are considered (for example, application/*)
283 final List<MediaType> mediaTypesWithSpecifiedParent = acceptableAndSupportedMediaTypes.stream()
284 .filter(mediaType -> !mediaType.isWildcardType())
285 .collect(Collectors.toList());
286 if (!mediaTypesWithSpecifiedParent.isEmpty()) {
287 return chooseAndCheckMediaType(mediaTypesWithSpecifiedParent);
290 // it must be fully-wildcard-ed type - */*
291 return DEFAULT_MEDIA_TYPE;
294 private static MediaType chooseAndCheckMediaType(final List<MediaType> options) {
295 final Optional<MediaType> mediaTypeOpt = chooseMediaType(options);
296 checkState(mediaTypeOpt.isPresent());
297 return mediaTypeOpt.get();
301 * This method is responsible for choosing of he media type from multiple options. At the first step,
302 * JSON-compatible types are considered, then, if there are not any JSON types, XML types are considered. The first
303 * compatible media-type is chosen.
305 * @param options Supported media types.
306 * @return Selected one media type or {@link Optional#empty()} if none of the provided options are compatible with
309 private static Optional<MediaType> chooseMediaType(final List<MediaType> options) {
310 return options.stream()
311 .filter(RestconfDocumentedExceptionMapper::isJsonCompatibleMediaType)
314 .orElse(options.stream()
315 .filter(RestconfDocumentedExceptionMapper::isXmlCompatibleMediaType)
320 * Mapping of JSON-compatible type to {@link RestconfDocumentedExceptionMapper#YANG_DATA_JSON_TYPE}
321 * or XML-compatible type to {@link RestconfDocumentedExceptionMapper#YANG_DATA_XML_TYPE}.
323 * @param mediaTypeBase Base media type from which the response media-type is built.
324 * @return Derived media type.
326 private static MediaType transformToResponseMediaType(final MediaType mediaTypeBase) {
327 if (isJsonCompatibleMediaType(mediaTypeBase)) {
328 return MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE;
329 } else if (isXmlCompatibleMediaType(mediaTypeBase)) {
330 return MediaTypes.APPLICATION_YANG_DATA_XML_TYPE;
332 throw new IllegalStateException(String.format("Unexpected input media-type %s "
333 + "- it should be JSON/XML compatible type.", mediaTypeBase));
337 private static boolean isCompatibleMediaType(final MediaType mediaType) {
338 return isJsonCompatibleMediaType(mediaType) || isXmlCompatibleMediaType(mediaType);
341 private static boolean isJsonCompatibleMediaType(final MediaType mediaType) {
342 return mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE)
343 || mediaType.isCompatible(MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE)
344 || mediaType.isCompatible(MediaTypes.APPLICATION_YANG_PATCH_JSON_TYPE);
347 private static boolean isXmlCompatibleMediaType(final MediaType mediaType) {
348 return mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)
349 || mediaType.isCompatible(MediaTypes.APPLICATION_YANG_DATA_XML_TYPE)
350 || mediaType.isCompatible(MediaTypes.APPLICATION_YANG_PATCH_XML_TYPE);
354 * Used just for testing purposes - simulation of HTTP headers with different accepted types and content type.
356 * @param httpHeaders Mocked HTTP headers.
359 void setHttpHeaders(final HttpHeaders httpHeaders) {
360 headers = httpHeaders;