2 * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. 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
9 package org.opendaylight.netconf.sal.rest.impl;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Throwables;
13 import com.google.common.collect.Iterables;
14 import com.google.gson.stream.JsonWriter;
15 import java.io.ByteArrayOutputStream;
16 import java.io.IOException;
17 import java.io.OutputStreamWriter;
18 import java.io.UnsupportedEncodingException;
20 import java.nio.charset.StandardCharsets;
21 import java.util.ArrayList;
22 import java.util.List;
23 import javax.ws.rs.core.Context;
24 import javax.ws.rs.core.HttpHeaders;
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.Response;
27 import javax.ws.rs.ext.ExceptionMapper;
28 import javax.ws.rs.ext.Provider;
29 import javax.xml.XMLConstants;
30 import javax.xml.stream.FactoryConfigurationError;
31 import javax.xml.stream.XMLOutputFactory;
32 import javax.xml.stream.XMLStreamException;
33 import javax.xml.stream.XMLStreamWriter;
34 import org.opendaylight.netconf.sal.rest.api.Draft02;
35 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
36 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
37 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
38 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
39 import org.opendaylight.restconf.common.errors.RestconfError;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
44 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
46 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.stream.ForwardingNormalizedNodeStreamWriter;
50 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
51 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
52 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
53 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
54 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
55 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
56 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
57 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
58 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
59 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
60 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
62 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
71 * This class defines an ExceptionMapper that handles RestconfDocumentedExceptions thrown by resource implementations
72 * and translates appropriately to restconf error response as defined in the RESTCONF RFC draft.
74 * @author Thomas Pantelis
77 public class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
79 private static final Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
81 private static final XMLOutputFactory XML_FACTORY;
84 XML_FACTORY = XMLOutputFactory.newFactory();
85 XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
89 private HttpHeaders headers;
91 private final ControllerContext controllerContext;
93 public RestconfDocumentedExceptionMapper(final ControllerContext controllerContext) {
94 this.controllerContext = Preconditions.checkNotNull(controllerContext);
98 public Response toResponse(final RestconfDocumentedException exception) {
100 LOG.debug("In toResponse: {}", exception.getMessage());
102 final List<MediaType> mediaTypeList = new ArrayList<>();
103 if (headers.getMediaType() != null) {
104 mediaTypeList.add(headers.getMediaType());
107 mediaTypeList.addAll(headers.getAcceptableMediaTypes());
108 final MediaType mediaType = mediaTypeList.stream().filter(type -> !type.equals(MediaType.WILDCARD_TYPE))
109 .findFirst().orElse(MediaType.APPLICATION_JSON_TYPE);
111 LOG.debug("Using MediaType: {}", mediaType);
113 final List<RestconfError> errors = exception.getErrors();
114 if (errors.isEmpty()) {
115 // We don't actually want to send any content but, if we don't set any content here,
116 // the tomcat front-end will send back an html error report. To prevent that, set a
117 // single space char in the entity.
119 return Response.status(exception.getStatus()).type(MediaType.TEXT_PLAIN_TYPE).entity(" ").build();
122 final int status = errors.iterator().next().getErrorTag().getStatusCode();
124 final DataNodeContainer errorsSchemaNode =
125 (DataNodeContainer) controllerContext.getRestconfModuleErrorsSchemaNode();
127 if (errorsSchemaNode == null) {
128 return Response.status(status).type(MediaType.TEXT_PLAIN_TYPE).entity(exception.getMessage()).build();
131 Preconditions.checkState(errorsSchemaNode instanceof ContainerSchemaNode,
132 "Found Errors SchemaNode isn't ContainerNode");
133 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> errContBuild =
134 Builders.containerBuilder((ContainerSchemaNode) errorsSchemaNode);
136 final List<DataSchemaNode> schemaList = ControllerContext.findInstanceDataChildrenByName(errorsSchemaNode,
137 Draft02.RestConfModule.ERROR_LIST_SCHEMA_NODE);
138 final DataSchemaNode errListSchemaNode = Iterables.getFirst(schemaList, null);
139 Preconditions.checkState(
140 errListSchemaNode instanceof ListSchemaNode, "Found Error SchemaNode isn't ListSchemaNode");
141 final CollectionNodeBuilder<MapEntryNode, MapNode> listErorsBuilder = Builders
142 .mapBuilder((ListSchemaNode) errListSchemaNode);
145 for (final RestconfError error : errors) {
146 listErorsBuilder.withChild(toErrorEntryNode(error, errListSchemaNode));
148 errContBuild.withChild(listErorsBuilder.build());
150 final NormalizedNodeContext errContext = new NormalizedNodeContext(new InstanceIdentifierContext<>(null,
151 (DataSchemaNode) errorsSchemaNode, null, controllerContext.getGlobalSchema()), errContBuild.build());
154 if (mediaType.getSubtype().endsWith("json")) {
155 responseBody = toJsonResponseBody(errContext, errorsSchemaNode);
157 responseBody = toXMLResponseBody(errContext, errorsSchemaNode);
160 return Response.status(status).type(mediaType).entity(responseBody).build();
163 private static MapEntryNode toErrorEntryNode(final RestconfError error, final DataSchemaNode errListSchemaNode) {
164 Preconditions.checkArgument(errListSchemaNode instanceof ListSchemaNode,
165 "errListSchemaNode has to be of type ListSchemaNode");
166 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) errListSchemaNode;
167 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> errNodeValues = Builders
168 .mapEntryBuilder(listStreamSchemaNode);
170 List<DataSchemaNode> lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
171 listStreamSchemaNode, "error-type");
172 final DataSchemaNode errTypSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
173 Preconditions.checkState(errTypSchemaNode instanceof LeafSchemaNode);
174 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTypSchemaNode)
175 .withValue(error.getErrorType().getErrorTypeTag()).build());
177 lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
178 listStreamSchemaNode, "error-tag");
179 final DataSchemaNode errTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
180 Preconditions.checkState(errTagSchemaNode instanceof LeafSchemaNode);
181 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTagSchemaNode)
182 .withValue(error.getErrorTag().getTagValue()).build());
184 if (error.getErrorAppTag() != null) {
185 lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
186 listStreamSchemaNode, "error-app-tag");
187 final DataSchemaNode errAppTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
188 Preconditions.checkState(errAppTagSchemaNode instanceof LeafSchemaNode);
189 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errAppTagSchemaNode)
190 .withValue(error.getErrorAppTag()).build());
193 lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
194 listStreamSchemaNode, "error-message");
195 final DataSchemaNode errMsgSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
196 Preconditions.checkState(errMsgSchemaNode instanceof LeafSchemaNode);
197 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errMsgSchemaNode)
198 .withValue(error.getErrorMessage()).build());
200 if (error.getErrorInfo() != null) {
201 // Oddly, error-info is defined as an empty container in the restconf yang. Apparently the
202 // intention is for implementors to define their own data content so we'll just treat it as a leaf
204 errNodeValues.withChild(ImmutableNodes.leafNode(Draft02.RestConfModule.ERROR_INFO_QNAME,
205 error.getErrorInfo()));
208 // TODO : find how could we add possible "error-path"
210 return errNodeValues.build();
213 private static Object toJsonResponseBody(final NormalizedNodeContext errorsNode,
214 final DataNodeContainer errorsSchemaNode) {
215 final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
216 NormalizedNode<?, ?> data = errorsNode.getData();
217 final InstanceIdentifierContext<?> context = errorsNode.getInstanceIdentifierContext();
218 final DataSchemaNode schema = (DataSchemaNode) context.getSchemaNode();
220 SchemaPath path = context.getSchemaNode().getPath();
221 final OutputStreamWriter outputWriter = new OutputStreamWriter(outStream, StandardCharsets.UTF_8);
223 throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
226 boolean isDataRoot = false;
227 URI initialNs = null;
228 if (SchemaPath.ROOT.equals(path)) {
231 path = path.getParent();
232 // FIXME: Add proper handling of reading root.
234 if (!schema.isAugmenting() && !(schema instanceof SchemaContext)) {
235 initialNs = schema.getQName().getNamespace();
238 final JsonWriter jsonWriter = JsonWriterFactory.createJsonWriter(outputWriter);
239 final NormalizedNodeStreamWriter jsonStreamWriter = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
240 JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(context.getSchemaContext()), path,
241 initialNs, jsonWriter);
243 // We create a delegating writer to special-case error-info as error-info is defined as an empty
244 // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
245 // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
246 // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
248 final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
250 protected NormalizedNodeStreamWriter delegate() {
251 return jsonStreamWriter;
255 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
256 if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
257 jsonWriter.name(Draft02.RestConfModule.ERROR_INFO_QNAME.getLocalName());
258 jsonWriter.value(value.toString());
260 super.leafNode(name, value);
265 final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
268 writeDataRoot(outputWriter,nnWriter,(ContainerNode) data);
270 if (data instanceof MapEntryNode) {
271 data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).withChild((MapEntryNode) data).build();
273 nnWriter.write(data);
276 outputWriter.flush();
277 } catch (final IOException e) {
278 LOG.warn("Error writing error response body", e);
282 return outStream.toString(StandardCharsets.UTF_8.name());
283 } catch (UnsupportedEncodingException e) {
285 return "Failure encoding error response: " + e;
289 private static Object toXMLResponseBody(final NormalizedNodeContext errorsNode,
290 final DataNodeContainer errorsSchemaNode) {
291 final InstanceIdentifierContext<?> pathContext = errorsNode.getInstanceIdentifierContext();
292 final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
294 final XMLStreamWriter xmlWriter;
296 xmlWriter = XML_FACTORY.createXMLStreamWriter(outStream, StandardCharsets.UTF_8.name());
297 } catch (final XMLStreamException | FactoryConfigurationError e) {
298 throw new IllegalStateException(e);
300 NormalizedNode<?, ?> data = errorsNode.getData();
301 SchemaPath schemaPath = pathContext.getSchemaNode().getPath();
303 boolean isDataRoot = false;
304 if (SchemaPath.ROOT.equals(schemaPath)) {
307 schemaPath = schemaPath.getParent();
310 final NormalizedNodeStreamWriter xmlStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
311 pathContext.getSchemaContext(), schemaPath);
313 // We create a delegating writer to special-case error-info as error-info is defined as an empty
314 // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
315 // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
316 // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
318 final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
320 protected NormalizedNodeStreamWriter delegate() {
321 return xmlStreamWriter;
325 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
326 if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
327 String ns = Draft02.RestConfModule.ERROR_INFO_QNAME.getNamespace().toString();
329 xmlWriter.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX,
330 Draft02.RestConfModule.ERROR_INFO_QNAME.getLocalName(), ns);
331 xmlWriter.writeCharacters(value.toString());
332 xmlWriter.writeEndElement();
333 } catch (XMLStreamException e) {
334 throw new IOException("Error writing error-info", e);
337 super.leafNode(name, value);
342 final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
345 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
347 if (data instanceof MapEntryNode) {
348 // Restconf allows returning one list item. We need to wrap it
349 // in map node in order to serialize it properly
350 data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).addChild((MapEntryNode) data).build();
352 nnWriter.write(data);
355 } catch (final IOException e) {
356 LOG.warn("Error writing error response body.", e);
360 return outStream.toString(StandardCharsets.UTF_8.name());
361 } catch (UnsupportedEncodingException e) {
363 return "Failure encoding error response: " + e;
367 private static void writeRootElement(final XMLStreamWriter xmlWriter, final NormalizedNodeWriter nnWriter,
368 final ContainerNode data)
371 final QName name = SchemaContext.NAME;
372 xmlWriter.writeStartElement(name.getNamespace().toString(), name.getLocalName());
373 for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
374 nnWriter.write(child);
377 xmlWriter.writeEndElement();
379 } catch (final XMLStreamException e) {
380 Throwables.propagate(e);
384 private static void writeDataRoot(final OutputStreamWriter outputWriter, final NormalizedNodeWriter nnWriter,
385 final ContainerNode data) throws IOException {
386 for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
387 nnWriter.write(child);