Split Restconf implementations (draft02 and RFC) - base api
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / rest / impl / RestconfDocumentedExceptionMapper.java
1 /*
2  * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.netconf.sal.rest.impl;
10
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.net.URI;
19 import java.nio.charset.StandardCharsets;
20 import java.util.Iterator;
21 import java.util.List;
22 import javax.ws.rs.core.Context;
23 import javax.ws.rs.core.HttpHeaders;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.Response;
26 import javax.ws.rs.ext.ExceptionMapper;
27 import javax.ws.rs.ext.Provider;
28 import javax.xml.XMLConstants;
29 import javax.xml.stream.FactoryConfigurationError;
30 import javax.xml.stream.XMLOutputFactory;
31 import javax.xml.stream.XMLStreamException;
32 import javax.xml.stream.XMLStreamWriter;
33 import org.opendaylight.netconf.sal.rest.api.Draft02;
34 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
35 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
36 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
37 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
38 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
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.YangInstanceIdentifier.NodeIdentifierWithPredicates;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
43 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
45 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.stream.ForwardingNormalizedNodeStreamWriter;
49 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
50 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
51 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
52 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
53 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
54 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
55 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
56 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
57 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
58 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
59 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
61 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
65 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 /**
70  * This class defines an ExceptionMapper that handles RestconfDocumentedExceptions thrown by resource implementations
71  * and translates appropriately to restconf error response as defined in the RESTCONF RFC draft.
72  *
73  * @author Thomas Pantelis
74  */
75 @Provider
76 public class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
77
78     private static final Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
79
80     private static final XMLOutputFactory XML_FACTORY;
81
82     static {
83         XML_FACTORY = XMLOutputFactory.newFactory();
84         XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
85     }
86
87     @Context
88     private HttpHeaders headers;
89
90     @Override
91     public Response toResponse(final RestconfDocumentedException exception) {
92
93         LOG.debug("In toResponse: {}", exception.getMessage());
94
95         final List<MediaType> accepts = headers.getAcceptableMediaTypes();
96         accepts.remove(MediaType.WILDCARD_TYPE);
97
98         LOG.debug("Accept headers: {}", accepts);
99
100         final MediaType mediaType;
101         if (accepts != null && accepts.size() > 0) {
102             mediaType = accepts.get(0); // just pick the first one
103         } else {
104             // Default to the content type if there's no Accept header
105             mediaType = MediaType.APPLICATION_JSON_TYPE;
106         }
107
108         LOG.debug("Using MediaType: {}", mediaType);
109
110         final List<RestconfError> errors = exception.getErrors();
111         if (errors.isEmpty()) {
112             // We don't actually want to send any content but, if we don't set any content here,
113             // the tomcat front-end will send back an html error report. To prevent that, set a
114             // single space char in the entity.
115
116             return Response.status(exception.getStatus()).type(MediaType.TEXT_PLAIN_TYPE).entity(" ").build();
117         }
118
119         final int status = errors.iterator().next().getErrorTag().getStatusCode();
120
121         final ControllerContext context = ControllerContext.getInstance();
122         final DataNodeContainer errorsSchemaNode = (DataNodeContainer) context.getRestconfModuleErrorsSchemaNode();
123
124         if (errorsSchemaNode == null) {
125             return Response.status(status).type(MediaType.TEXT_PLAIN_TYPE).entity(exception.getMessage()).build();
126         }
127
128         Preconditions.checkState(errorsSchemaNode instanceof ContainerSchemaNode,
129                 "Found Errors SchemaNode isn't ContainerNode");
130         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> errContBuild =
131                 Builders.containerBuilder((ContainerSchemaNode) errorsSchemaNode);
132
133         final List<DataSchemaNode> schemaList = ControllerContext.findInstanceDataChildrenByName(errorsSchemaNode,
134                 Draft02.RestConfModule.ERROR_LIST_SCHEMA_NODE);
135         final DataSchemaNode errListSchemaNode = Iterables.getFirst(schemaList, null);
136         Preconditions.checkState(
137                 errListSchemaNode instanceof ListSchemaNode, "Found Error SchemaNode isn't ListSchemaNode");
138         final CollectionNodeBuilder<MapEntryNode, MapNode> listErorsBuilder = Builders
139                 .mapBuilder((ListSchemaNode) errListSchemaNode);
140
141
142         for (final RestconfError error : errors) {
143             listErorsBuilder.withChild(toErrorEntryNode(error, errListSchemaNode));
144         }
145         errContBuild.withChild(listErorsBuilder.build());
146
147         final NormalizedNodeContext errContext =  new NormalizedNodeContext(new InstanceIdentifierContext<>(null,
148                 (DataSchemaNode) errorsSchemaNode, null, context.getGlobalSchema()), errContBuild.build());
149
150         Object responseBody;
151         if (mediaType.getSubtype().endsWith("json")) {
152             responseBody = toJsonResponseBody(errContext, errorsSchemaNode);
153         } else {
154             responseBody = toXMLResponseBody(errContext, errorsSchemaNode);
155         }
156
157         return Response.status(status).type(mediaType).entity(responseBody).build();
158     }
159
160     private static MapEntryNode toErrorEntryNode(final RestconfError error, final DataSchemaNode errListSchemaNode) {
161         Preconditions.checkArgument(errListSchemaNode instanceof ListSchemaNode,
162                 "errListSchemaNode has to be of type ListSchemaNode");
163         final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) errListSchemaNode;
164         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> errNodeValues = Builders
165                 .mapEntryBuilder(listStreamSchemaNode);
166
167         List<DataSchemaNode> lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
168                 listStreamSchemaNode, "error-type");
169         final DataSchemaNode errTypSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
170         Preconditions.checkState(errTypSchemaNode instanceof LeafSchemaNode);
171         errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTypSchemaNode)
172                 .withValue(error.getErrorType().getErrorTypeTag()).build());
173
174         lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
175                 listStreamSchemaNode, "error-tag");
176         final DataSchemaNode errTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
177         Preconditions.checkState(errTagSchemaNode instanceof LeafSchemaNode);
178         errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTagSchemaNode)
179                 .withValue(error.getErrorTag().getTagValue()).build());
180
181         if (error.getErrorAppTag() != null) {
182             lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
183                     listStreamSchemaNode, "error-app-tag");
184             final DataSchemaNode errAppTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
185             Preconditions.checkState(errAppTagSchemaNode instanceof LeafSchemaNode);
186             errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errAppTagSchemaNode)
187                     .withValue(error.getErrorAppTag()).build());
188         }
189
190         lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
191                 listStreamSchemaNode, "error-message");
192         final DataSchemaNode errMsgSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
193         Preconditions.checkState(errMsgSchemaNode instanceof LeafSchemaNode);
194         errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errMsgSchemaNode)
195                 .withValue(error.getErrorMessage()).build());
196
197         if (error.getErrorInfo() != null) {
198             // Oddly, error-info is defined as an empty container in the restconf yang. Apparently the
199             // intention is for implementors to define their own data content so we'll just treat it as a leaf
200             // with string data.
201             errNodeValues.withChild(ImmutableNodes.leafNode(Draft02.RestConfModule.ERROR_INFO_QNAME,
202                     error.getErrorInfo()));
203         }
204
205         // TODO : find how could we add possible "error-path"
206
207         return errNodeValues.build();
208     }
209
210     private static Object toJsonResponseBody(final NormalizedNodeContext errorsNode,
211                                              final DataNodeContainer errorsSchemaNode) {
212         final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
213         NormalizedNode<?, ?> data = errorsNode.getData();
214         final InstanceIdentifierContext<?> context = errorsNode.getInstanceIdentifierContext();
215         final DataSchemaNode schema = (DataSchemaNode) context.getSchemaNode();
216
217         SchemaPath path = context.getSchemaNode().getPath();
218         final OutputStreamWriter outputWriter = new OutputStreamWriter(outStream, StandardCharsets.UTF_8);
219         if (data == null) {
220             throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
221         }
222
223         boolean isDataRoot = false;
224         URI initialNs = null;
225         if (SchemaPath.ROOT.equals(path)) {
226             isDataRoot = true;
227         } else {
228             path = path.getParent();
229             // FIXME: Add proper handling of reading root.
230         }
231         if (!schema.isAugmenting() && !(schema instanceof SchemaContext)) {
232             initialNs = schema.getQName().getNamespace();
233         }
234
235         final JsonWriter jsonWriter = JsonWriterFactory.createJsonWriter(outputWriter);
236         final NormalizedNodeStreamWriter jsonStreamWriter = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
237                 JSONCodecFactory.getShared(context.getSchemaContext()), path, initialNs, jsonWriter);
238
239         // We create a delegating writer to special-case error-info as error-info is defined as an empty
240         // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
241         // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
242         // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
243         // for error-info.
244         final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
245             @Override
246             protected NormalizedNodeStreamWriter delegate() {
247                 return jsonStreamWriter;
248             }
249
250             @Override
251             public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
252                 if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
253                     jsonWriter.name(Draft02.RestConfModule.ERROR_INFO_QNAME.getLocalName());
254                     jsonWriter.value(value.toString());
255                 } else {
256                     super.leafNode(name, value);
257                 }
258             }
259         };
260
261         final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
262         try {
263             if (isDataRoot) {
264                 writeDataRoot(outputWriter,nnWriter,(ContainerNode) data);
265             } else {
266                 if (data instanceof MapEntryNode) {
267                     data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).withChild((MapEntryNode) data).build();
268                 }
269                 nnWriter.write(data);
270             }
271             nnWriter.flush();
272             outputWriter.flush();
273         } catch (final IOException e) {
274             LOG.warn("Error writing error response body", e);
275         }
276
277         return outStream.toString();
278
279     }
280
281     private static Object toXMLResponseBody(final NormalizedNodeContext errorsNode,
282                                             final DataNodeContainer errorsSchemaNode) {
283         final InstanceIdentifierContext<?> pathContext = errorsNode.getInstanceIdentifierContext();
284         final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
285
286         final XMLStreamWriter xmlWriter;
287         try {
288             xmlWriter = XML_FACTORY.createXMLStreamWriter(outStream, StandardCharsets.UTF_8.name());
289         } catch (final XMLStreamException e) {
290             throw new IllegalStateException(e);
291         } catch (final FactoryConfigurationError e) {
292             throw new IllegalStateException(e);
293         }
294         NormalizedNode<?, ?> data = errorsNode.getData();
295         SchemaPath schemaPath = pathContext.getSchemaNode().getPath();
296
297         boolean isDataRoot = false;
298         if (SchemaPath.ROOT.equals(schemaPath)) {
299             isDataRoot = true;
300         } else {
301             schemaPath = schemaPath.getParent();
302         }
303
304         final NormalizedNodeStreamWriter xmlStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
305                 pathContext.getSchemaContext(), schemaPath);
306
307         // We create a delegating writer to special-case error-info as error-info is defined as an empty
308         // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
309         // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
310         // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
311         // for error-info.
312         final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
313             @Override
314             protected NormalizedNodeStreamWriter delegate() {
315                 return xmlStreamWriter;
316             }
317
318             @Override
319             public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
320                 if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
321                     String ns = Draft02.RestConfModule.ERROR_INFO_QNAME.getNamespace().toString();
322                     try {
323                         xmlWriter.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX,
324                                 Draft02.RestConfModule.ERROR_INFO_QNAME.getLocalName(), ns);
325                         xmlWriter.writeCharacters(value.toString());
326                         xmlWriter.writeEndElement();
327                     } catch (XMLStreamException e) {
328                         throw new IOException("Error writing error-info", e);
329                     }
330                 } else {
331                     super.leafNode(name, value);
332                 }
333             }
334         };
335
336         final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
337         try {
338             if (isDataRoot) {
339                 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
340             } else {
341                 if (data instanceof MapEntryNode) {
342                     // Restconf allows returning one list item. We need to wrap it
343                     // in map node in order to serialize it properly
344                     data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).addChild((MapEntryNode) data).build();
345                 }
346                 nnWriter.write(data);
347                 nnWriter.flush();
348             }
349         } catch (final IOException e) {
350             LOG.warn("Error writing error response body.", e);
351         }
352
353         return outStream.toString();
354     }
355
356     private static void writeRootElement(final XMLStreamWriter xmlWriter, final NormalizedNodeWriter nnWriter,
357                                          final ContainerNode data)
358             throws IOException {
359         try {
360             final QName name = SchemaContext.NAME;
361             xmlWriter.writeStartElement(name.getNamespace().toString(), name.getLocalName());
362             for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
363                 nnWriter.write(child);
364             }
365             nnWriter.flush();
366             xmlWriter.writeEndElement();
367             xmlWriter.flush();
368         } catch (final XMLStreamException e) {
369             Throwables.propagate(e);
370         }
371     }
372
373     private static void writeDataRoot(final OutputStreamWriter outputWriter, final NormalizedNodeWriter nnWriter,
374                                       final ContainerNode data) throws IOException {
375         final Iterator<DataContainerChild<? extends PathArgument, ?>> iterator = data.getValue().iterator();
376         while (iterator.hasNext()) {
377             final DataContainerChild<? extends PathArgument, ?> child = iterator.next();
378             nnWriter.write(child);
379             nnWriter.flush();
380         }
381     }
382 }