f4c1ec0af1d7338009bc23a96864fb391ba07686
[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 com.google.common.base.Optional;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.lang.annotation.Annotation;
14 import java.lang.reflect.Type;
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.opendaylight.netconf.sal.rest.api.Draft02;
30 import org.opendaylight.netconf.sal.rest.api.RestconfNormalizedNodeWriter;
31 import org.opendaylight.netconf.sal.rest.api.RestconfService;
32 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
33 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
34 import org.opendaylight.yangtools.yang.common.QName;
35 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
39 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
40 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
41 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
42 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
43 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
44
45 /**
46  * Normalized node writer for XML.
47  *
48  * @deprecated This class will be replaced by NormalizedNodeXmlBodyWriter from restconf-nb-rfc8040
49  */
50 @Deprecated
51 @Provider
52 @Produces({ Draft02.MediaTypes.API + RestconfService.XML, Draft02.MediaTypes.DATA + RestconfService.XML,
53         Draft02.MediaTypes.OPERATION + RestconfService.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
54 public class NormalizedNodeXmlBodyWriter implements MessageBodyWriter<NormalizedNodeContext> {
55
56     private static final XMLOutputFactory XML_FACTORY;
57
58     static {
59         XML_FACTORY = XMLOutputFactory.newFactory();
60         XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
61     }
62
63     @Override
64     public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
65             final MediaType mediaType) {
66         return type.equals(NormalizedNodeContext.class);
67     }
68
69     @Override
70     public long getSize(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
71             final Annotation[] annotations, final MediaType mediaType) {
72         return -1;
73     }
74
75     @Override
76     public void writeTo(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
77             final Annotation[] annotations, final MediaType mediaType,
78             final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
79             WebApplicationException {
80         for (final Entry<String, Object> entry : context.getNewHeaders().entrySet()) {
81             httpHeaders.add(entry.getKey(), entry.getValue());
82         }
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,
101                 Optional.fromNullable(context.getWriterParameters().getDepth()));
102     }
103
104     private static void writeNormalizedNode(final XMLStreamWriter xmlWriter, final SchemaPath schemaPath,
105             final InstanceIdentifierContext<?> pathContext, NormalizedNode<?, ?> data, final Optional<Integer> depth)
106             throws IOException {
107         final RestconfNormalizedNodeWriter nnWriter;
108         final SchemaContext schemaCtx = pathContext.getSchemaContext();
109         if (SchemaPath.ROOT.equals(schemaPath)) {
110             nnWriter = createNormalizedNodeWriter(xmlWriter, schemaCtx, schemaPath, depth);
111             writeElements(xmlWriter, nnWriter, (ContainerNode) data);
112         }  else if (pathContext.getSchemaNode() instanceof RpcDefinition) {
113             nnWriter = createNormalizedNodeWriter(xmlWriter, schemaCtx,
114                     ((RpcDefinition) pathContext.getSchemaNode()).getOutput().getPath(), depth);
115             writeElements(xmlWriter, nnWriter, (ContainerNode) data);
116         } else {
117             nnWriter = createNormalizedNodeWriter(xmlWriter, schemaCtx, schemaPath.getParent(), depth);
118             if (data instanceof MapEntryNode) {
119                 // Restconf allows returning one list item. We need to wrap it
120                 // in map node in order to serialize it properly
121                 data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).addChild((MapEntryNode) data).build();
122             }
123             nnWriter.write(data);
124         }
125         nnWriter.flush();
126     }
127
128     private static RestconfNormalizedNodeWriter createNormalizedNodeWriter(final XMLStreamWriter xmlWriter,
129             final SchemaContext schemaContext, final SchemaPath schemaPath, final Optional<Integer> depth) {
130         final NormalizedNodeStreamWriter xmlStreamWriter =
131                 XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, schemaContext, schemaPath);
132         if (depth.isPresent()) {
133             return DepthAwareNormalizedNodeWriter.forStreamWriter(xmlStreamWriter, depth.get());
134         }
135
136         return RestconfDelegatingNormalizedNodeWriter.forStreamWriter(xmlStreamWriter);
137     }
138
139     private static void writeElements(final XMLStreamWriter xmlWriter, final RestconfNormalizedNodeWriter nnWriter,
140             final ContainerNode data) throws IOException {
141         final QName name = data.getNodeType();
142         try {
143             xmlWriter.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, name.getLocalName(),
144                     name.getNamespace().toString());
145             xmlWriter.writeDefaultNamespace(name.getNamespace().toString());
146             for (final NormalizedNode<?,?> child : data.getValue()) {
147                 nnWriter.write(child);
148             }
149             nnWriter.flush();
150             xmlWriter.writeEndElement();
151             xmlWriter.flush();
152         } catch (final XMLStreamException e) {
153             throw new IOException("Failed to write elements", e);
154         }
155     }
156 }