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.errors.RestconfDocumentedException;
33 import org.opendaylight.restconf.common.errors.RestconfError;
34 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
35 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.errors.Errors;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.errors.errors.Error;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.common.XMLNamespace;
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.builder.DataContainerNodeBuilder;
45 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
46 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
47 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
48 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUnkeyedListEntryNodeBuilder;
49 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUnkeyedListNodeBuilder;
50 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
55 * Mapper that is responsible for transformation of thrown {@link RestconfDocumentedException} to errors structure
56 * that is modelled by RESTCONF module (see section 8 of RFC-8040).
59 public final class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
60 private static final Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
61 private static final MediaType DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_JSON_TYPE;
62 private static final Status DEFAULT_STATUS_CODE = Status.INTERNAL_SERVER_ERROR;
63 // Note: we are using container's QName reference to trim imports
64 private static final SchemaPath ERRORS_GROUPING_PATH = SchemaPath.create(true, Errors.QNAME);
65 private static final QName ERROR_TYPE_QNAME = qnameOf("error-type");
66 private static final QName ERROR_TAG_QNAME = qnameOf("error-tag");
67 private static final QName ERROR_APP_TAG_QNAME = qnameOf("error-app-tag");
68 private static final QName ERROR_MESSAGE_QNAME = qnameOf("error-message");
69 private static final QName ERROR_INFO_QNAME = qnameOf("error-info");
70 private static final QName ERROR_PATH_QNAME = qnameOf("error-path");
71 private static final XMLNamespace IETF_RESTCONF_URI = Errors.QNAME.getModule().getNamespace();
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 && exception.getErrors().isEmpty()) {
95 // there should be at least one error entry for 4xx errors except 409 according to the RFC 8040
96 // - creation of WARN log that something went wrong way on the server side
97 LOG.warn("Input exception has a family of 4xx but doesn't contain any descriptive errors: {}",
98 exception.getMessage());
101 final ContainerNode errorsContainer = buildErrorsContainer(exception);
102 final String serializedResponseBody;
103 final MediaType responseMediaType = transformToResponseMediaType(getSupportedMediaType());
104 if (MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE.equals(responseMediaType)) {
105 serializedResponseBody = serializeErrorsContainerToJson(errorsContainer);
107 serializedResponseBody = serializeErrorsContainerToXml(errorsContainer);
110 final Response preparedResponse = Response.status(responseStatus)
111 .type(responseMediaType)
112 .entity(serializedResponseBody)
114 LOG.debug("Exception {} has been successfully mapped to response: {}",
115 exception.getMessage(), preparedResponse);
116 return preparedResponse;
120 * Filling up of the errors container with data from input {@link RestconfDocumentedException}.
122 * @param exception Thrown exception.
123 * @return Built errors container.
125 private static ContainerNode buildErrorsContainer(final RestconfDocumentedException exception) {
126 return ImmutableContainerNodeBuilder.create()
127 .withNodeIdentifier(NodeIdentifier.create(Errors.QNAME))
128 .withChild(ImmutableUnkeyedListNodeBuilder.create()
129 .withNodeIdentifier(NodeIdentifier.create(Error.QNAME))
130 .withValue(exception.getErrors().stream()
131 .map(RestconfDocumentedExceptionMapper::createErrorEntry)
132 .collect(Collectors.toList()))
138 * Building of one error entry using provided {@link RestconfError}.
140 * @param restconfError Error details.
141 * @return Built list entry.
143 private static UnkeyedListEntryNode createErrorEntry(final RestconfError restconfError) {
144 // filling in mandatory leafs
145 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> entryBuilder =
146 ImmutableUnkeyedListEntryNodeBuilder.create()
147 .withNodeIdentifier(NodeIdentifier.create(Error.QNAME))
148 .withChild(ImmutableNodes.leafNode(ERROR_TYPE_QNAME, restconfError.getErrorType().getErrorTypeTag()))
149 .withChild(ImmutableNodes.leafNode(ERROR_TAG_QNAME, restconfError.getErrorTag().getTagValue()));
151 // filling in optional fields
152 if (restconfError.getErrorMessage() != null) {
153 entryBuilder.withChild(ImmutableNodes.leafNode(ERROR_MESSAGE_QNAME, restconfError.getErrorMessage()));
155 if (restconfError.getErrorAppTag() != null) {
156 entryBuilder.withChild(ImmutableNodes.leafNode(ERROR_APP_TAG_QNAME, restconfError.getErrorAppTag()));
158 if (restconfError.getErrorInfo() != null) {
159 // Oddly, error-info is defined as an empty container in the restconf yang. Apparently the
160 // intention is for implementors to define their own data content so we'll just treat it as a leaf
162 entryBuilder.withChild(ImmutableNodes.leafNode(ERROR_INFO_QNAME, restconfError.getErrorInfo()));
165 if (restconfError.getErrorPath() != null) {
166 entryBuilder.withChild(ImmutableNodes.leafNode(ERROR_PATH_QNAME, restconfError.getErrorPath()));
168 return entryBuilder.build();
172 * Serialization of the errors container into JSON representation.
174 * @param errorsContainer To be serialized errors container.
175 * @return JSON representation of the errors container.
177 private String serializeErrorsContainerToJson(final ContainerNode errorsContainer) {
178 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
179 OutputStreamWriter streamStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
181 return writeNormalizedNode(errorsContainer, outputStream, new JsonStreamWriterWithDisabledValidation(
182 ERROR_INFO_QNAME, streamStreamWriter, ERRORS_GROUPING_PATH, IETF_RESTCONF_URI, schemaContextHandler));
183 } catch (IOException e) {
184 throw new IllegalStateException("Cannot close some of the output JSON writers", e);
189 * Serialization of the errors container into XML representation.
191 * @param errorsContainer To be serialized errors container.
192 * @return XML representation of the errors container.
194 private String serializeErrorsContainerToXml(final ContainerNode errorsContainer) {
195 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
196 return writeNormalizedNode(errorsContainer, outputStream, new XmlStreamWriterWithDisabledValidation(
197 ERROR_INFO_QNAME, outputStream, ERRORS_GROUPING_PATH, schemaContextHandler));
198 } catch (IOException e) {
199 throw new IllegalStateException("Cannot close some of the output XML writers", e);
203 private static String writeNormalizedNode(final NormalizedNode errorsContainer,
204 final ByteArrayOutputStream outputStream, final StreamWriterWithDisabledValidation streamWriter) {
205 try (NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter)) {
206 nnWriter.write(errorsContainer);
207 } catch (IOException e) {
208 throw new IllegalStateException("Cannot write error response body", e);
210 return outputStream.toString(StandardCharsets.UTF_8);
214 * Deriving of the status code from the thrown exception. At the first step, status code is tried to be read using
215 * {@link RestconfDocumentedException#getStatus()}. If it is {@code null}, status code will be derived from status
216 * codes appended to error entries (the first that will be found). If there are not any error entries,
217 * {@link RestconfDocumentedExceptionMapper#DEFAULT_STATUS_CODE} will be used.
219 * @param exception Thrown exception.
220 * @return Derived status code.
222 private static Status getResponseStatusCode(final RestconfDocumentedException exception) {
223 final Status status = exception.getStatus();
224 if (status != null) {
225 // status code that is specified directly as field in exception has the precedence over error entries
229 final List<RestconfError> errors = exception.getErrors();
230 if (errors.isEmpty()) {
231 // if the module, that thrown exception, doesn't specify status code, it is treated as internal
233 return DEFAULT_STATUS_CODE;
236 final Set<Integer> allStatusCodesOfErrorEntries = errors.stream()
237 .map(restconfError -> restconfError.getErrorTag().getStatusCode())
238 // we would like to preserve iteration order in collected entries - hence usage of LinkedHashSet
239 .collect(Collectors.toCollection(LinkedHashSet::new));
240 // choosing of the first status code from appended errors, if there are different status codes in error
241 // entries, we should create WARN message
242 if (allStatusCodesOfErrorEntries.size() > 1) {
243 LOG.warn("An unexpected error occurred during translation of exception {} to response: "
244 + "Different status codes have been found in appended error entries: {}. The first error "
245 + "entry status code is chosen for response.", exception, allStatusCodesOfErrorEntries);
247 return Status.fromStatusCode(allStatusCodesOfErrorEntries.iterator().next());
251 * Selection of media type that will be used for creation suffix of 'application/yang-data'. Selection criteria
252 * is described in RFC 8040, section 7.1. At the first step, accepted media-type is analyzed and only supported
253 * media-types are filtered out. If both XML and JSON media-types are accepted, JSON is selected as a default one
254 * used in RESTCONF. If accepted-media type is not specified, the media-type used in request is chosen only if it
255 * is supported one. If it is not supported or it is not specified, again, the default one (JSON) is selected.
257 * @return Media type.
259 private MediaType getSupportedMediaType() {
260 final Set<MediaType> acceptableAndSupportedMediaTypes = headers.getAcceptableMediaTypes().stream()
261 .filter(RestconfDocumentedExceptionMapper::isCompatibleMediaType)
262 .collect(Collectors.toSet());
263 if (acceptableAndSupportedMediaTypes.isEmpty()) {
264 // check content type of the request
265 final MediaType requestMediaType = headers.getMediaType();
266 return requestMediaType == null ? DEFAULT_MEDIA_TYPE
267 : chooseMediaType(Collections.singletonList(requestMediaType)).orElseGet(() -> {
268 LOG.warn("Request doesn't specify accepted media-types and the media-type '{}' used by "
269 + "request is not supported - using of default '{}' media-type.",
270 requestMediaType, DEFAULT_MEDIA_TYPE);
271 return DEFAULT_MEDIA_TYPE;
275 // at first step, fully specified types without any wildcards are considered (for example, application/json)
276 final List<MediaType> fullySpecifiedMediaTypes = acceptableAndSupportedMediaTypes.stream()
277 .filter(mediaType -> !mediaType.isWildcardType() && !mediaType.isWildcardSubtype())
278 .collect(Collectors.toList());
279 if (!fullySpecifiedMediaTypes.isEmpty()) {
280 return chooseAndCheckMediaType(fullySpecifiedMediaTypes);
283 // at the second step, only types with specified subtype are considered (for example, */json)
284 final List<MediaType> mediaTypesWithSpecifiedSubtypes = acceptableAndSupportedMediaTypes.stream()
285 .filter(mediaType -> !mediaType.isWildcardSubtype())
286 .collect(Collectors.toList());
287 if (!mediaTypesWithSpecifiedSubtypes.isEmpty()) {
288 return chooseAndCheckMediaType(mediaTypesWithSpecifiedSubtypes);
291 // at the third step, only types with specified parent are considered (for example, application/*)
292 final List<MediaType> mediaTypesWithSpecifiedParent = acceptableAndSupportedMediaTypes.stream()
293 .filter(mediaType -> !mediaType.isWildcardType())
294 .collect(Collectors.toList());
295 if (!mediaTypesWithSpecifiedParent.isEmpty()) {
296 return chooseAndCheckMediaType(mediaTypesWithSpecifiedParent);
299 // it must be fully-wildcard-ed type - */*
300 return DEFAULT_MEDIA_TYPE;
303 private static MediaType chooseAndCheckMediaType(final List<MediaType> options) {
304 final Optional<MediaType> mediaTypeOpt = chooseMediaType(options);
305 checkState(mediaTypeOpt.isPresent());
306 return mediaTypeOpt.get();
310 * This method is responsible for choosing of he media type from multiple options. At the first step,
311 * JSON-compatible types are considered, then, if there are not any JSON types, XML types are considered. The first
312 * compatible media-type is chosen.
314 * @param options Supported media types.
315 * @return Selected one media type or {@link Optional#empty()} if none of the provided options are compatible with
318 private static Optional<MediaType> chooseMediaType(final List<MediaType> options) {
319 return options.stream()
320 .filter(RestconfDocumentedExceptionMapper::isJsonCompatibleMediaType)
323 .orElse(options.stream()
324 .filter(RestconfDocumentedExceptionMapper::isXmlCompatibleMediaType)
329 * Mapping of JSON-compatible type to {@link RestconfDocumentedExceptionMapper#YANG_DATA_JSON_TYPE}
330 * or XML-compatible type to {@link RestconfDocumentedExceptionMapper#YANG_DATA_XML_TYPE}.
332 * @param mediaTypeBase Base media type from which the response media-type is built.
333 * @return Derived media type.
335 private static MediaType transformToResponseMediaType(final MediaType mediaTypeBase) {
336 if (isJsonCompatibleMediaType(mediaTypeBase)) {
337 return MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE;
338 } else if (isXmlCompatibleMediaType(mediaTypeBase)) {
339 return MediaTypes.APPLICATION_YANG_DATA_XML_TYPE;
341 throw new IllegalStateException(String.format("Unexpected input media-type %s "
342 + "- it should be JSON/XML compatible type.", mediaTypeBase));
346 private static boolean isCompatibleMediaType(final MediaType mediaType) {
347 return isJsonCompatibleMediaType(mediaType) || isXmlCompatibleMediaType(mediaType);
350 private static boolean isJsonCompatibleMediaType(final MediaType mediaType) {
351 return mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE)
352 || mediaType.isCompatible(MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE)
353 || mediaType.isCompatible(MediaTypes.APPLICATION_YANG_PATCH_JSON_TYPE);
356 private static boolean isXmlCompatibleMediaType(final MediaType mediaType) {
357 return mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)
358 || mediaType.isCompatible(MediaTypes.APPLICATION_YANG_DATA_XML_TYPE)
359 || mediaType.isCompatible(MediaTypes.APPLICATION_YANG_PATCH_XML_TYPE);
363 * Used just for testing purposes - simulation of HTTP headers with different accepted types and content type.
365 * @param httpHeaders Mocked HTTP headers.
368 void setHttpHeaders(final HttpHeaders httpHeaders) {
369 this.headers = httpHeaders;