Hide NormalizedNodeContext and WriterParameters
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / rest / impl / NormalizedNodeXmlBodyWriter.java
1 /*
2  * Copyright (c) 2014 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 package org.opendaylight.netconf.sal.rest.impl;
9
10 import java.io.IOException;
11 import java.io.OutputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14 import java.net.URISyntaxException;
15 import java.nio.charset.StandardCharsets;
16 import java.util.Map.Entry;
17 import javanet.staxutils.IndentingXMLStreamWriter;
18 import javax.ws.rs.Produces;
19 import javax.ws.rs.WebApplicationException;
20 import javax.ws.rs.core.MediaType;
21 import javax.ws.rs.core.MultivaluedMap;
22 import javax.ws.rs.ext.MessageBodyWriter;
23 import javax.ws.rs.ext.Provider;
24 import javax.xml.XMLConstants;
25 import javax.xml.stream.FactoryConfigurationError;
26 import javax.xml.stream.XMLOutputFactory;
27 import javax.xml.stream.XMLStreamException;
28 import javax.xml.stream.XMLStreamWriter;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.opendaylight.netconf.sal.rest.api.Draft02;
31 import org.opendaylight.netconf.sal.rest.api.RestconfNormalizedNodeWriter;
32 import org.opendaylight.netconf.sal.rest.api.RestconfService;
33 import org.opendaylight.netconf.util.NetconfUtil;
34 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
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.EffectiveModelContext;
44 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
45 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
46 import org.xml.sax.SAXException;
47
48 /**
49  * Normalized node writer for XML.
50  *
51  * @deprecated This class will be replaced by NormalizedNodeXmlBodyWriter from restconf-nb-rfc8040
52  */
53 @Deprecated
54 @Provider
55 @Produces({
56     Draft02.MediaTypes.API + RestconfService.XML,
57     Draft02.MediaTypes.DATA + RestconfService.XML,
58     Draft02.MediaTypes.OPERATION + RestconfService.XML,
59     MediaType.APPLICATION_XML,
60     MediaType.TEXT_XML
61 })
62 public class NormalizedNodeXmlBodyWriter implements MessageBodyWriter<NormalizedNodeContext> {
63
64     private static final XMLOutputFactory XML_FACTORY;
65
66     static {
67         XML_FACTORY = XMLOutputFactory.newFactory();
68         XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
69     }
70
71     @Override
72     public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
73             final MediaType mediaType) {
74         return type.equals(NormalizedNodeContext.class);
75     }
76
77     @Override
78     public long getSize(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
79             final Annotation[] annotations, final MediaType mediaType) {
80         return -1;
81     }
82
83     @Override
84     public void writeTo(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
85             final Annotation[] annotations, final MediaType mediaType,
86             final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
87             WebApplicationException {
88         for (final Entry<String, Object> entry : context.getNewHeaders().entrySet()) {
89             httpHeaders.add(entry.getKey(), entry.getValue());
90         }
91         final InstanceIdentifierContext<?> pathContext = context.getInstanceIdentifierContext();
92         if (context.getData() == null) {
93             return;
94         }
95
96         XMLStreamWriter xmlWriter;
97         try {
98             xmlWriter = XML_FACTORY.createXMLStreamWriter(entityStream, StandardCharsets.UTF_8.name());
99             if (context.getWriterParameters().isPrettyPrint()) {
100                 xmlWriter = new IndentingXMLStreamWriter(xmlWriter);
101             }
102         } catch (final XMLStreamException | FactoryConfigurationError e) {
103             throw new IllegalStateException(e);
104         }
105         final NormalizedNode data = context.getData();
106         final SchemaPath schemaPath = pathContext.getSchemaNode().getPath();
107
108         writeNormalizedNode(xmlWriter, schemaPath, pathContext, data, context.getWriterParameters().getDepth());
109     }
110
111     private static void writeNormalizedNode(final XMLStreamWriter xmlWriter, final SchemaPath schemaPath,
112             final InstanceIdentifierContext<?> pathContext, NormalizedNode data, final @Nullable Integer depth)
113             throws IOException {
114         final RestconfNormalizedNodeWriter nnWriter;
115         final EffectiveModelContext schemaCtx = pathContext.getSchemaContext();
116         if (SchemaPath.ROOT.equals(schemaPath)) {
117             nnWriter = createNormalizedNodeWriter(xmlWriter, schemaCtx, schemaPath, depth);
118             if (data instanceof DOMSourceAnyxmlNode) {
119                 try {
120                     writeElements(xmlWriter, nnWriter,
121                             (ContainerNode) NetconfUtil.transformDOMSourceToNormalizedNode(schemaCtx,
122                                     ((DOMSourceAnyxmlNode)data).body()).getResult());
123                 } catch (XMLStreamException | URISyntaxException | SAXException e) {
124                     throw new IOException("Cannot write anyxml", e);
125                 }
126             } else {
127                 writeElements(xmlWriter, nnWriter, (ContainerNode) data);
128             }
129         }  else if (pathContext.getSchemaNode() instanceof RpcDefinition) {
130             nnWriter = createNormalizedNodeWriter(xmlWriter, schemaCtx,
131                     ((RpcDefinition) pathContext.getSchemaNode()).getOutput().getPath(), depth);
132             writeElements(xmlWriter, nnWriter, (ContainerNode) data);
133         } else {
134             nnWriter = createNormalizedNodeWriter(xmlWriter, schemaCtx, schemaPath.getParent(), depth);
135             if (data instanceof MapEntryNode) {
136                 // Restconf allows returning one list item. We need to wrap it
137                 // in map node in order to serialize it properly
138                 data = ImmutableNodes.mapNodeBuilder(data.getIdentifier().getNodeType())
139                     .addChild((MapEntryNode) data)
140                     .build();
141             }
142             nnWriter.write(data);
143         }
144         nnWriter.flush();
145     }
146
147     private static RestconfNormalizedNodeWriter createNormalizedNodeWriter(final XMLStreamWriter xmlWriter,
148             final EffectiveModelContext schemaContext, final SchemaPath schemaPath, final @Nullable Integer depth) {
149         final NormalizedNodeStreamWriter xmlStreamWriter =
150                 XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, schemaContext, schemaPath);
151         if (depth != null) {
152             return DepthAwareNormalizedNodeWriter.forStreamWriter(xmlStreamWriter, depth);
153         }
154
155         return RestconfDelegatingNormalizedNodeWriter.forStreamWriter(xmlStreamWriter);
156     }
157
158     private static void writeElements(final XMLStreamWriter xmlWriter, final RestconfNormalizedNodeWriter nnWriter,
159             final ContainerNode data) throws IOException {
160         final QName name = data.getIdentifier().getNodeType();
161         try {
162             xmlWriter.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, name.getLocalName(),
163                     name.getNamespace().toString());
164             xmlWriter.writeDefaultNamespace(name.getNamespace().toString());
165             for (final NormalizedNode child : data.body()) {
166                 nnWriter.write(child);
167             }
168             nnWriter.flush();
169             xmlWriter.writeEndElement();
170             xmlWriter.flush();
171         } catch (final XMLStreamException e) {
172             throw new IOException("Failed to write elements", e);
173         }
174     }
175 }