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.Iterator;
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.JSONCodecFactory;
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(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> accepts = headers.getAcceptableMediaTypes();
103 if (accepts != null) {
104 accepts.remove(MediaType.WILDCARD_TYPE);
107 LOG.debug("Accept headers: {}", accepts);
109 final MediaType mediaType;
110 if (accepts != null && accepts.size() > 0) {
111 mediaType = accepts.get(0); // just pick the first one
113 // Default to the content type if there's no Accept header
114 mediaType = MediaType.APPLICATION_JSON_TYPE;
117 LOG.debug("Using MediaType: {}", mediaType);
119 final List<RestconfError> errors = exception.getErrors();
120 if (errors.isEmpty()) {
121 // We don't actually want to send any content but, if we don't set any content here,
122 // the tomcat front-end will send back an html error report. To prevent that, set a
123 // single space char in the entity.
125 return Response.status(exception.getStatus()).type(MediaType.TEXT_PLAIN_TYPE).entity(" ").build();
128 final int status = errors.iterator().next().getErrorTag().getStatusCode();
130 final DataNodeContainer errorsSchemaNode =
131 (DataNodeContainer) controllerContext.getRestconfModuleErrorsSchemaNode();
133 if (errorsSchemaNode == null) {
134 return Response.status(status).type(MediaType.TEXT_PLAIN_TYPE).entity(exception.getMessage()).build();
137 Preconditions.checkState(errorsSchemaNode instanceof ContainerSchemaNode,
138 "Found Errors SchemaNode isn't ContainerNode");
139 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> errContBuild =
140 Builders.containerBuilder((ContainerSchemaNode) errorsSchemaNode);
142 final List<DataSchemaNode> schemaList = ControllerContext.findInstanceDataChildrenByName(errorsSchemaNode,
143 Draft02.RestConfModule.ERROR_LIST_SCHEMA_NODE);
144 final DataSchemaNode errListSchemaNode = Iterables.getFirst(schemaList, null);
145 Preconditions.checkState(
146 errListSchemaNode instanceof ListSchemaNode, "Found Error SchemaNode isn't ListSchemaNode");
147 final CollectionNodeBuilder<MapEntryNode, MapNode> listErorsBuilder = Builders
148 .mapBuilder((ListSchemaNode) errListSchemaNode);
151 for (final RestconfError error : errors) {
152 listErorsBuilder.withChild(toErrorEntryNode(error, errListSchemaNode));
154 errContBuild.withChild(listErorsBuilder.build());
156 final NormalizedNodeContext errContext = new NormalizedNodeContext(new InstanceIdentifierContext<>(null,
157 (DataSchemaNode) errorsSchemaNode, null, controllerContext.getGlobalSchema()), errContBuild.build());
160 if (mediaType.getSubtype().endsWith("json")) {
161 responseBody = toJsonResponseBody(errContext, errorsSchemaNode);
163 responseBody = toXMLResponseBody(errContext, errorsSchemaNode);
166 return Response.status(status).type(mediaType).entity(responseBody).build();
169 private static MapEntryNode toErrorEntryNode(final RestconfError error, final DataSchemaNode errListSchemaNode) {
170 Preconditions.checkArgument(errListSchemaNode instanceof ListSchemaNode,
171 "errListSchemaNode has to be of type ListSchemaNode");
172 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) errListSchemaNode;
173 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> errNodeValues = Builders
174 .mapEntryBuilder(listStreamSchemaNode);
176 List<DataSchemaNode> lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
177 listStreamSchemaNode, "error-type");
178 final DataSchemaNode errTypSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
179 Preconditions.checkState(errTypSchemaNode instanceof LeafSchemaNode);
180 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTypSchemaNode)
181 .withValue(error.getErrorType().getErrorTypeTag()).build());
183 lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
184 listStreamSchemaNode, "error-tag");
185 final DataSchemaNode errTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
186 Preconditions.checkState(errTagSchemaNode instanceof LeafSchemaNode);
187 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTagSchemaNode)
188 .withValue(error.getErrorTag().getTagValue()).build());
190 if (error.getErrorAppTag() != null) {
191 lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
192 listStreamSchemaNode, "error-app-tag");
193 final DataSchemaNode errAppTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
194 Preconditions.checkState(errAppTagSchemaNode instanceof LeafSchemaNode);
195 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errAppTagSchemaNode)
196 .withValue(error.getErrorAppTag()).build());
199 lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
200 listStreamSchemaNode, "error-message");
201 final DataSchemaNode errMsgSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
202 Preconditions.checkState(errMsgSchemaNode instanceof LeafSchemaNode);
203 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errMsgSchemaNode)
204 .withValue(error.getErrorMessage()).build());
206 if (error.getErrorInfo() != null) {
207 // Oddly, error-info is defined as an empty container in the restconf yang. Apparently the
208 // intention is for implementors to define their own data content so we'll just treat it as a leaf
210 errNodeValues.withChild(ImmutableNodes.leafNode(Draft02.RestConfModule.ERROR_INFO_QNAME,
211 error.getErrorInfo()));
214 // TODO : find how could we add possible "error-path"
216 return errNodeValues.build();
219 private static Object toJsonResponseBody(final NormalizedNodeContext errorsNode,
220 final DataNodeContainer errorsSchemaNode) {
221 final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
222 NormalizedNode<?, ?> data = errorsNode.getData();
223 final InstanceIdentifierContext<?> context = errorsNode.getInstanceIdentifierContext();
224 final DataSchemaNode schema = (DataSchemaNode) context.getSchemaNode();
226 SchemaPath path = context.getSchemaNode().getPath();
227 final OutputStreamWriter outputWriter = new OutputStreamWriter(outStream, StandardCharsets.UTF_8);
229 throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
232 boolean isDataRoot = false;
233 URI initialNs = null;
234 if (SchemaPath.ROOT.equals(path)) {
237 path = path.getParent();
238 // FIXME: Add proper handling of reading root.
240 if (!schema.isAugmenting() && !(schema instanceof SchemaContext)) {
241 initialNs = schema.getQName().getNamespace();
244 final JsonWriter jsonWriter = JsonWriterFactory.createJsonWriter(outputWriter);
245 final NormalizedNodeStreamWriter jsonStreamWriter = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
246 JSONCodecFactory.getShared(context.getSchemaContext()), path, initialNs, jsonWriter);
248 // We create a delegating writer to special-case error-info as error-info is defined as an empty
249 // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
250 // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
251 // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
253 final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
255 protected NormalizedNodeStreamWriter delegate() {
256 return jsonStreamWriter;
260 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
261 if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
262 jsonWriter.name(Draft02.RestConfModule.ERROR_INFO_QNAME.getLocalName());
263 jsonWriter.value(value.toString());
265 super.leafNode(name, value);
270 final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
273 writeDataRoot(outputWriter,nnWriter,(ContainerNode) data);
275 if (data instanceof MapEntryNode) {
276 data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).withChild((MapEntryNode) data).build();
278 nnWriter.write(data);
281 outputWriter.flush();
282 } catch (final IOException e) {
283 LOG.warn("Error writing error response body", e);
287 return outStream.toString(StandardCharsets.UTF_8.name());
288 } catch (UnsupportedEncodingException e) {
290 return "Failure encoding error response: " + e;
294 private static Object toXMLResponseBody(final NormalizedNodeContext errorsNode,
295 final DataNodeContainer errorsSchemaNode) {
296 final InstanceIdentifierContext<?> pathContext = errorsNode.getInstanceIdentifierContext();
297 final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
299 final XMLStreamWriter xmlWriter;
301 xmlWriter = XML_FACTORY.createXMLStreamWriter(outStream, StandardCharsets.UTF_8.name());
302 } catch (final XMLStreamException e) {
303 throw new IllegalStateException(e);
304 } catch (final FactoryConfigurationError e) {
305 throw new IllegalStateException(e);
307 NormalizedNode<?, ?> data = errorsNode.getData();
308 SchemaPath schemaPath = pathContext.getSchemaNode().getPath();
310 boolean isDataRoot = false;
311 if (SchemaPath.ROOT.equals(schemaPath)) {
314 schemaPath = schemaPath.getParent();
317 final NormalizedNodeStreamWriter xmlStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
318 pathContext.getSchemaContext(), schemaPath);
320 // We create a delegating writer to special-case error-info as error-info is defined as an empty
321 // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
322 // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
323 // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
325 final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
327 protected NormalizedNodeStreamWriter delegate() {
328 return xmlStreamWriter;
332 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
333 if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
334 String ns = Draft02.RestConfModule.ERROR_INFO_QNAME.getNamespace().toString();
336 xmlWriter.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX,
337 Draft02.RestConfModule.ERROR_INFO_QNAME.getLocalName(), ns);
338 xmlWriter.writeCharacters(value.toString());
339 xmlWriter.writeEndElement();
340 } catch (XMLStreamException e) {
341 throw new IOException("Error writing error-info", e);
344 super.leafNode(name, value);
349 final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
352 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
354 if (data instanceof MapEntryNode) {
355 // Restconf allows returning one list item. We need to wrap it
356 // in map node in order to serialize it properly
357 data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).addChild((MapEntryNode) data).build();
359 nnWriter.write(data);
362 } catch (final IOException e) {
363 LOG.warn("Error writing error response body.", e);
367 return outStream.toString(StandardCharsets.UTF_8.name());
368 } catch (UnsupportedEncodingException e) {
370 return "Failure encoding error response: " + e;
374 private static void writeRootElement(final XMLStreamWriter xmlWriter, final NormalizedNodeWriter nnWriter,
375 final ContainerNode data)
378 final QName name = SchemaContext.NAME;
379 xmlWriter.writeStartElement(name.getNamespace().toString(), name.getLocalName());
380 for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
381 nnWriter.write(child);
384 xmlWriter.writeEndElement();
386 } catch (final XMLStreamException e) {
387 Throwables.propagate(e);
391 private static void writeDataRoot(final OutputStreamWriter outputWriter, final NormalizedNodeWriter nnWriter,
392 final ContainerNode data) throws IOException {
393 final Iterator<DataContainerChild<? extends PathArgument, ?>> iterator = data.getValue().iterator();
394 while (iterator.hasNext()) {
395 final DataContainerChild<? extends PathArgument, ?> child = iterator.next();
396 nnWriter.write(child);