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 java.util.Objects.requireNonNull;
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.io.StringReader;
19 import java.io.StringWriter;
20 import java.nio.charset.StandardCharsets;
21 import java.util.Collections;
22 import java.util.LinkedHashSet;
23 import java.util.List;
24 import java.util.Optional;
26 import java.util.stream.Collectors;
27 import javax.ws.rs.core.Context;
28 import javax.ws.rs.core.HttpHeaders;
29 import javax.ws.rs.core.MediaType;
30 import javax.ws.rs.core.Response;
31 import javax.ws.rs.core.Response.Status;
32 import javax.ws.rs.ext.ExceptionMapper;
33 import javax.ws.rs.ext.Provider;
34 import javax.xml.stream.XMLOutputFactory;
35 import javax.xml.stream.XMLStreamException;
36 import javax.xml.transform.OutputKeys;
37 import javax.xml.transform.TransformerException;
38 import javax.xml.transform.TransformerFactory;
39 import javax.xml.transform.stream.StreamResult;
40 import javax.xml.transform.stream.StreamSource;
41 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
42 import org.opendaylight.restconf.nb.jaxrs.JaxRsMediaTypes;
43 import org.opendaylight.restconf.nb.rfc8040.legacy.ErrorTags;
44 import org.opendaylight.restconf.server.api.DatabindContext;
45 import org.opendaylight.restconf.server.spi.DatabindProvider;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.errors.Errors;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.errors.errors.Error;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * An {@link ExceptionMapper} that is responsible for transformation of thrown {@link RestconfDocumentedException} to
55 * {@code errors} structure that is modelled by RESTCONF module (see section 8 of RFC-8040).
59 // FIXME: NETCONF-1188: eliminate the need for this class by having a separate exception which a has a HTTP status and
60 // optionally holds an ErrorsBody -- i.e. the equivalent of Errors, perhaps as NormalizedNode,
61 // with sufficient context to send it to JSON or XML -- very similar to a NormalizedNodePayload
64 public final class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
65 private static final Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
66 private static final MediaType DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_JSON_TYPE;
67 private static final Status DEFAULT_STATUS_CODE = Status.INTERNAL_SERVER_ERROR;
68 private static final QName ERROR_TYPE_QNAME = qnameOf("error-type");
69 private static final QName ERROR_TAG_QNAME = qnameOf("error-tag");
70 private static final QName ERROR_APP_TAG_QNAME = qnameOf("error-app-tag");
71 private static final QName ERROR_MESSAGE_QNAME = qnameOf("error-message");
72 private static final QName ERROR_INFO_QNAME = qnameOf("error-info");
73 private static final QName ERROR_PATH_QNAME = qnameOf("error-path");
74 private static final int DEFAULT_INDENT_SPACES_NUM = 2;
75 private static final XMLOutputFactory XML_OUTPUT_FACTORY;
78 XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
79 XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
82 private final DatabindProvider databindProvider;
85 private HttpHeaders headers;
88 * Initialization of the exception mapper.
90 * @param databindProvider A {@link DatabindProvider}
92 public RestconfDocumentedExceptionMapper(final DatabindProvider databindProvider) {
93 this.databindProvider = requireNonNull(databindProvider);
97 @SuppressFBWarnings(value = "SLF4J_MANUALLY_PROVIDED_MESSAGE", justification = "In the debug messages "
98 + "we don't to have full stack trace - getMessage(..) method provides finer output.")
99 public Response toResponse(final RestconfDocumentedException exception) {
100 LOG.debug("Starting to map received exception to error response: {}", exception.getMessage());
101 final Status responseStatus = getResponseStatusCode(exception);
102 if (responseStatus != Response.Status.FORBIDDEN
103 && responseStatus.getFamily() == Response.Status.Family.CLIENT_ERROR
104 && exception.getErrors().isEmpty()) {
105 // There should be at least one error entry for 4xx errors except 409 according to RFC8040, but we do not
106 // have it. Issue a warning with the call trace so we can fix whoever was the originator.
107 LOG.warn("Input exception has a family of 4xx but does not contain any descriptive errors", exception);
110 final String serializedResponseBody;
111 final MediaType responseMediaType = transformToResponseMediaType(getSupportedMediaType());
112 if (JaxRsMediaTypes.APPLICATION_YANG_DATA_JSON.equals(responseMediaType)) {
113 serializedResponseBody = serializeExceptionToJson(exception, databindProvider);
115 serializedResponseBody = serializeExceptionToXml(exception, databindProvider);
118 final Response preparedResponse = Response.status(responseStatus)
119 .type(responseMediaType)
120 .entity(serializedResponseBody)
122 LOG.debug("Exception {} has been successfully mapped to response: {}",
123 exception.getMessage(), preparedResponse);
124 return preparedResponse;
128 * Serialization exceptions into JSON representation.
130 * @param exception To be serialized exception.
131 * @param databindProvider Holder of current {@code DatabindContext}.
132 * @return JSON representation of the exception.
134 private static String serializeExceptionToJson(final RestconfDocumentedException exception,
135 final DatabindProvider databindProvider) {
136 try (var outputStream = new ByteArrayOutputStream();
137 var streamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
138 var jsonWriter = JsonWriterFactory.createJsonWriter(streamWriter, DEFAULT_INDENT_SPACES_NUM)) {
139 final var currentDatabindContext = exception.modelContext() != null
140 ? DatabindContext.ofModel(exception.modelContext()) : databindProvider.currentDatabind();
141 jsonWriter.beginObject();
142 final var errors = exception.getErrors();
143 if (errors != null && !errors.isEmpty()) {
144 jsonWriter.name(Errors.QNAME.getLocalName()).beginObject();
145 jsonWriter.name(Error.QNAME.getLocalName()).beginArray();
146 for (final var error : errors) {
147 jsonWriter.beginObject()
148 .name(ERROR_TAG_QNAME.getLocalName()).value(error.getErrorTag().elementBody());
149 final var errorAppTag = error.getErrorAppTag();
150 if (errorAppTag != null) {
151 jsonWriter.name(ERROR_APP_TAG_QNAME.getLocalName()).value(errorAppTag);
153 final var errorInfo = error.getErrorInfo();
154 if (errorInfo != null) {
155 jsonWriter.name(ERROR_INFO_QNAME.getLocalName()).value(errorInfo);
157 final var errorMessage = error.getErrorMessage();
158 if (errorMessage != null) {
159 jsonWriter.name(ERROR_MESSAGE_QNAME.getLocalName()).value(errorMessage);
161 final var errorPath = error.getErrorPath();
162 if (errorPath != null) {
163 jsonWriter.name(ERROR_PATH_QNAME.getLocalName());
164 currentDatabindContext.jsonCodecs().instanceIdentifierCodec()
165 .writeValue(jsonWriter, errorPath);
167 jsonWriter.name(ERROR_TYPE_QNAME.getLocalName()).value(error.getErrorType().elementBody());
168 jsonWriter.endObject();
170 jsonWriter.endArray().endObject();
172 jsonWriter.endObject();
173 streamWriter.flush();
174 return outputStream.toString(StandardCharsets.UTF_8);
175 } catch (IOException e) {
176 throw new IllegalStateException("Error while serializing restconf exception into JSON", e);
181 * Serialization exceptions into XML representation.
183 * @param exception To be serialized exception.
184 * @param databindProvider Holder of current {@code DatabindContext}.
185 * @return XML representation of the exception.
187 private static String serializeExceptionToXml(final RestconfDocumentedException exception,
188 final DatabindProvider databindProvider) {
189 try (var outputStream = new ByteArrayOutputStream()) {
190 final var xmlWriter = XML_OUTPUT_FACTORY.createXMLStreamWriter(outputStream,
191 StandardCharsets.UTF_8.name());
192 xmlWriter.writeStartDocument();
193 xmlWriter.writeStartElement(Errors.QNAME.getLocalName());
194 xmlWriter.writeNamespace("xmlns", Errors.QNAME.getNamespace().toString());
195 if (exception.getErrors() != null && !exception.getErrors().isEmpty()) {
196 for (final var error : exception.getErrors()) {
197 xmlWriter.writeStartElement(Error.QNAME.getLocalName());
198 // Write error-type element
199 xmlWriter.writeStartElement(ERROR_TYPE_QNAME.getLocalName());
200 xmlWriter.writeCharacters(error.getErrorType().elementBody());
201 xmlWriter.writeEndElement();
203 if (error.getErrorPath() != null) {
204 xmlWriter.writeStartElement(ERROR_PATH_QNAME.getLocalName());
205 databindProvider.currentDatabind().xmlCodecs().instanceIdentifierCodec()
206 .writeValue(xmlWriter, error.getErrorPath());
207 xmlWriter.writeEndElement();
209 if (error.getErrorMessage() != null) {
210 xmlWriter.writeStartElement(ERROR_MESSAGE_QNAME.getLocalName());
211 xmlWriter.writeCharacters(error.getErrorMessage());
212 xmlWriter.writeEndElement();
215 // Write error-tag element
216 xmlWriter.writeStartElement(ERROR_TAG_QNAME.getLocalName());
217 xmlWriter.writeCharacters(error.getErrorTag().elementBody());
218 xmlWriter.writeEndElement();
220 if (error.getErrorAppTag() != null) {
221 xmlWriter.writeStartElement(ERROR_APP_TAG_QNAME.getLocalName());
222 xmlWriter.writeCharacters(error.getErrorAppTag());
223 xmlWriter.writeEndElement();
225 if (error.getErrorInfo() != null) {
226 xmlWriter.writeStartElement(ERROR_INFO_QNAME.getLocalName());
227 xmlWriter.writeCharacters(error.getErrorInfo());
228 xmlWriter.writeEndElement();
230 xmlWriter.writeEndElement();
233 xmlWriter.writeEndElement();
234 xmlWriter.writeEndDocument();
237 final var transformerFactory = TransformerFactory.newInstance();
238 final var transformer = transformerFactory.newTransformer();
239 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
240 // 2 spaces for indentation
241 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
242 String.valueOf(DEFAULT_INDENT_SPACES_NUM));
243 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
244 final var xmlSource = new StreamSource(new StringReader(outputStream.toString(StandardCharsets.UTF_8)));
245 final var stringWriter = new StringWriter();
246 final var streamResult = new StreamResult(stringWriter);
247 transformer.transform(xmlSource, streamResult);
248 return stringWriter.toString();
249 } catch (IOException | XMLStreamException | TransformerException e) {
250 throw new IllegalStateException("Error while serializing restconf exception into XML", e);
255 * Deriving of the status code from the thrown exception. At the first step, status code is tried to be read using
256 * {@link RestconfDocumentedException#getStatus()}. If it is {@code null}, status code will be derived from status
257 * codes appended to error entries (the first that will be found). If there are not any error entries,
258 * {@link RestconfDocumentedExceptionMapper#DEFAULT_STATUS_CODE} will be used.
260 * @param exception Thrown exception.
261 * @return Derived status code.
263 private static Status getResponseStatusCode(final RestconfDocumentedException exception) {
264 final var errors = exception.getErrors();
265 if (errors.isEmpty()) {
266 // if the module, that thrown exception, doesn't specify status code, it is treated as internal
268 return DEFAULT_STATUS_CODE;
271 final var allStatusCodesOfErrorEntries = errors.stream()
272 .map(restconfError -> ErrorTags.statusOf(restconfError.getErrorTag()))
273 // we would like to preserve iteration order in collected entries - hence usage of LinkedHashSet
274 .collect(Collectors.toCollection(LinkedHashSet::new));
275 // choosing of the first status code from appended errors, if there are different status codes in error
276 // entries, we should create WARN message
277 if (allStatusCodesOfErrorEntries.size() > 1) {
279 An unexpected error occurred during translation of exception {} to response: Different status codes
280 have been found in appended error entries: {}. The first error entry status code is chosen for
281 response.""", exception, allStatusCodesOfErrorEntries);
283 return allStatusCodesOfErrorEntries.iterator().next();
287 * Selection of media type that will be used for creation suffix of 'application/yang-data'. Selection criteria
288 * is described in RFC 8040, section 7.1. At the first step, accepted media-type is analyzed and only supported
289 * media-types are filtered out. If both XML and JSON media-types are accepted, JSON is selected as a default one
290 * used in RESTCONF. If accepted-media type is not specified, the media-type used in request is chosen only if it
291 * is supported one. If it is not supported or it is not specified, again, the default one (JSON) is selected.
293 * @return Media type.
295 private MediaType getSupportedMediaType() {
296 final Set<MediaType> acceptableAndSupportedMediaTypes = headers.getAcceptableMediaTypes().stream()
297 .filter(RestconfDocumentedExceptionMapper::isCompatibleMediaType)
298 .collect(Collectors.toSet());
299 if (acceptableAndSupportedMediaTypes.isEmpty()) {
300 // check content type of the request
301 final MediaType requestMediaType = headers.getMediaType();
302 return requestMediaType == null ? DEFAULT_MEDIA_TYPE
303 : chooseMediaType(Collections.singletonList(requestMediaType)).orElseGet(() -> {
304 LOG.warn("Request doesn't specify accepted media-types and the media-type '{}' used by "
305 + "request is not supported - using of default '{}' media-type.",
306 requestMediaType, DEFAULT_MEDIA_TYPE);
307 return DEFAULT_MEDIA_TYPE;
311 // at first step, fully specified types without any wildcards are considered (for example, application/json)
312 final List<MediaType> fullySpecifiedMediaTypes = acceptableAndSupportedMediaTypes.stream()
313 .filter(mediaType -> !mediaType.isWildcardType() && !mediaType.isWildcardSubtype())
314 .collect(Collectors.toList());
315 if (!fullySpecifiedMediaTypes.isEmpty()) {
316 return chooseAndCheckMediaType(fullySpecifiedMediaTypes);
319 // at the second step, only types with specified subtype are considered (for example, */json)
320 final List<MediaType> mediaTypesWithSpecifiedSubtypes = acceptableAndSupportedMediaTypes.stream()
321 .filter(mediaType -> !mediaType.isWildcardSubtype())
322 .collect(Collectors.toList());
323 if (!mediaTypesWithSpecifiedSubtypes.isEmpty()) {
324 return chooseAndCheckMediaType(mediaTypesWithSpecifiedSubtypes);
327 // at the third step, only types with specified parent are considered (for example, application/*)
328 final List<MediaType> mediaTypesWithSpecifiedParent = acceptableAndSupportedMediaTypes.stream()
329 .filter(mediaType -> !mediaType.isWildcardType())
330 .collect(Collectors.toList());
331 if (!mediaTypesWithSpecifiedParent.isEmpty()) {
332 return chooseAndCheckMediaType(mediaTypesWithSpecifiedParent);
335 // it must be fully-wildcard-ed type - */*
336 return DEFAULT_MEDIA_TYPE;
339 private static MediaType chooseAndCheckMediaType(final List<MediaType> options) {
340 return chooseMediaType(options).orElseThrow(IllegalStateException::new);
344 * This method is responsible for choosing of he media type from multiple options. At the first step,
345 * JSON-compatible types are considered, then, if there are not any JSON types, XML types are considered. The first
346 * compatible media-type is chosen.
348 * @param options Supported media types.
349 * @return Selected one media type or {@link Optional#empty()} if none of the provided options are compatible with
352 private static Optional<MediaType> chooseMediaType(final List<MediaType> options) {
353 return options.stream()
354 .filter(RestconfDocumentedExceptionMapper::isJsonCompatibleMediaType)
357 .orElse(options.stream()
358 .filter(RestconfDocumentedExceptionMapper::isXmlCompatibleMediaType)
363 * Mapping of JSON-compatible type to {@link RestconfDocumentedExceptionMapper#YANG_DATA_JSON_TYPE}
364 * or XML-compatible type to {@link RestconfDocumentedExceptionMapper#YANG_DATA_XML_TYPE}.
366 * @param mediaTypeBase Base media type from which the response media-type is built.
367 * @return Derived media type.
369 private static MediaType transformToResponseMediaType(final MediaType mediaTypeBase) {
370 if (isJsonCompatibleMediaType(mediaTypeBase)) {
371 return JaxRsMediaTypes.APPLICATION_YANG_DATA_JSON;
372 } else if (isXmlCompatibleMediaType(mediaTypeBase)) {
373 return JaxRsMediaTypes.APPLICATION_YANG_DATA_XML;
375 throw new IllegalStateException(String.format("Unexpected input media-type %s "
376 + "- it should be JSON/XML compatible type.", mediaTypeBase));
380 private static boolean isCompatibleMediaType(final MediaType mediaType) {
381 return isJsonCompatibleMediaType(mediaType) || isXmlCompatibleMediaType(mediaType);
384 private static boolean isJsonCompatibleMediaType(final MediaType mediaType) {
385 return mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE)
386 || mediaType.isCompatible(JaxRsMediaTypes.APPLICATION_YANG_DATA_JSON)
387 || mediaType.isCompatible(JaxRsMediaTypes.APPLICATION_YANG_PATCH_JSON);
390 private static boolean isXmlCompatibleMediaType(final MediaType mediaType) {
391 return mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)
392 || mediaType.isCompatible(JaxRsMediaTypes.APPLICATION_YANG_DATA_XML)
393 || mediaType.isCompatible(JaxRsMediaTypes.APPLICATION_YANG_PATCH_XML);
397 * Used just for testing purposes - simulation of HTTP headers with different accepted types and content type.
399 * @param httpHeaders Mocked HTTP headers.
402 void setHttpHeaders(final HttpHeaders httpHeaders) {
403 headers = httpHeaders;