Split Restconf implementations (draft02 and RFC) - base api
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / restconf / jersey / providers / NormalizedNodeXmlBodyWriter.java
1 /*
2  * Copyright (c) 2016 Cisco 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.restconf.jersey.providers;
10
11 import com.google.common.base.Throwables;
12 import java.io.IOException;
13 import java.io.OutputStream;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16 import java.nio.charset.StandardCharsets;
17 import java.util.List;
18 import java.util.Set;
19 import javanet.staxutils.IndentingXMLStreamWriter;
20 import javax.ws.rs.Produces;
21 import javax.ws.rs.WebApplicationException;
22 import javax.ws.rs.core.MediaType;
23 import javax.ws.rs.core.MultivaluedMap;
24 import javax.ws.rs.ext.MessageBodyWriter;
25 import javax.ws.rs.ext.Provider;
26 import javax.xml.XMLConstants;
27 import javax.xml.stream.FactoryConfigurationError;
28 import javax.xml.stream.XMLOutputFactory;
29 import javax.xml.stream.XMLStreamException;
30 import javax.xml.stream.XMLStreamWriter;
31 import org.opendaylight.netconf.sal.rest.api.RestconfNormalizedNodeWriter;
32 import org.opendaylight.restconf.Rfc8040;
33 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
34 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
35 import org.opendaylight.restconf.utils.RestconfConstants;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
42 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
43 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
46
47 @Provider
48 @Produces({ Rfc8040.MediaTypes.DATA + RestconfConstants.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
49 public class NormalizedNodeXmlBodyWriter implements MessageBodyWriter<NormalizedNodeContext> {
50
51     private static final XMLOutputFactory XML_FACTORY;
52
53     static {
54         XML_FACTORY = XMLOutputFactory.newFactory();
55         XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
56     }
57
58     @Override
59     public boolean isWriteable(final Class<?> type,
60                                final Type genericType,
61                                final Annotation[] annotations,
62                                final MediaType mediaType) {
63         return type.equals(NormalizedNodeContext.class);
64     }
65
66     @Override
67     public long getSize(final NormalizedNodeContext context,
68                         final Class<?> type,
69                         final Type genericType,
70                         final Annotation[] annotations,
71                         final MediaType mediaType) {
72         return -1;
73     }
74
75     @Override
76     public void writeTo(final NormalizedNodeContext context,
77                         final Class<?> type,
78                         final Type genericType,
79                         final Annotation[] annotations,
80                         final MediaType mediaType,
81                         final MultivaluedMap<String, Object> httpHeaders,
82                         final OutputStream entityStream) throws IOException, WebApplicationException {
83         final InstanceIdentifierContext<?> pathContext = context.getInstanceIdentifierContext();
84         if (context.getData() == null) {
85             return;
86         }
87
88         XMLStreamWriter xmlWriter;
89         try {
90             xmlWriter = XML_FACTORY.createXMLStreamWriter(entityStream, StandardCharsets.UTF_8.name());
91             if (context.getWriterParameters().isPrettyPrint()) {
92                 xmlWriter = new IndentingXMLStreamWriter(xmlWriter);
93             }
94         } catch (final XMLStreamException | FactoryConfigurationError e) {
95             throw new IllegalStateException(e);
96         }
97         final NormalizedNode<?, ?> data = context.getData();
98         final SchemaPath schemaPath = pathContext.getSchemaNode().getPath();
99
100         writeNormalizedNode(xmlWriter, schemaPath, pathContext, data, context.getWriterParameters().getDepth(),
101                 context.getWriterParameters().getFields());
102     }
103
104     private static void writeNormalizedNode(final XMLStreamWriter xmlWriter,
105             final SchemaPath path, final InstanceIdentifierContext<?> pathContext, final NormalizedNode<?, ?> data,
106             final Integer depth, final List<Set<QName>> fields) throws IOException {
107         final RestconfNormalizedNodeWriter nnWriter;
108         final SchemaContext schemaCtx = pathContext.getSchemaContext();
109
110         if (pathContext.getSchemaNode() instanceof RpcDefinition) {
111             /*
112              *  RpcDefinition is not supported as initial codec in XMLStreamWriter,
113              *  so we need to emit initial output declaration..
114              */
115             nnWriter = createNormalizedNodeWriter(
116                     xmlWriter,
117                     schemaCtx,
118                     ((RpcDefinition) pathContext.getSchemaNode()).getOutput().getPath(),
119                     depth,
120                     fields);
121             writeElements(xmlWriter, nnWriter, (ContainerNode) data);
122         } else {
123             if (SchemaPath.ROOT.equals(path)) {
124                 nnWriter = createNormalizedNodeWriter(xmlWriter, schemaCtx, path, depth, fields);
125             } else {
126                 nnWriter = createNormalizedNodeWriter(xmlWriter, schemaCtx, path.getParent(), depth, fields);
127             }
128
129             if (data instanceof MapEntryNode) {
130                 // Restconf allows returning one list item. We need to wrap it
131                 // in map node in order to serialize it properly
132                 nnWriter.write(ImmutableNodes.mapNodeBuilder(data.getNodeType()).addChild((MapEntryNode) data).build());
133             } else {
134                 nnWriter.write(data);
135             }
136         }
137
138         nnWriter.flush();
139     }
140
141     private static RestconfNormalizedNodeWriter createNormalizedNodeWriter(final XMLStreamWriter xmlWriter,
142             final SchemaContext schemaContext, final SchemaPath schemaPath, final Integer depth,
143             final List<Set<QName>> fields) {
144         final NormalizedNodeStreamWriter xmlStreamWriter = XMLStreamNormalizedNodeStreamWriter
145                 .create(xmlWriter, schemaContext, schemaPath);
146         return ParameterAwareNormalizedNodeWriter.forStreamWriter(xmlStreamWriter, depth, fields);
147     }
148
149     private static void writeElements(final XMLStreamWriter xmlWriter, final RestconfNormalizedNodeWriter nnWriter,
150             final ContainerNode data) throws IOException {
151         try {
152             final QName name = data.getNodeType();
153             xmlWriter.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX,
154                     name.getLocalName(), name.getNamespace().toString());
155             xmlWriter.writeDefaultNamespace(name.getNamespace().toString());
156             for (final NormalizedNode<?,?> child : data.getValue()) {
157                 nnWriter.write(child);
158             }
159             nnWriter.flush();
160             xmlWriter.writeEndElement();
161             xmlWriter.flush();
162         } catch (final XMLStreamException e) {
163             Throwables.propagate(e);
164         }
165     }
166 }