Merge "Use FluentFuture in DOMDataTransactionValidator"
[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 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.Map.Entry;
18 import javanet.staxutils.IndentingXMLStreamWriter;
19 import javax.ws.rs.Produces;
20 import javax.ws.rs.WebApplicationException;
21 import javax.ws.rs.core.MediaType;
22 import javax.ws.rs.core.MultivaluedMap;
23 import javax.ws.rs.ext.MessageBodyWriter;
24 import javax.ws.rs.ext.Provider;
25 import javax.xml.XMLConstants;
26 import javax.xml.stream.FactoryConfigurationError;
27 import javax.xml.stream.XMLOutputFactory;
28 import javax.xml.stream.XMLStreamException;
29 import javax.xml.stream.XMLStreamWriter;
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.restconf.common.context.InstanceIdentifierContext;
34 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
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.MapEntryNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
40 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
42 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
45
46 /**
47  * Normalized node writer for XML.
48  *
49  * @deprecated This class will be replaced by NormalizedNodeXmlBodyWriter from restconf-nb-rfc8040
50  */
51 @Deprecated
52 @Provider
53 @Produces({ Draft02.MediaTypes.API + RestconfService.XML, Draft02.MediaTypes.DATA + RestconfService.XML,
54         Draft02.MediaTypes.OPERATION + RestconfService.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
55 public class NormalizedNodeXmlBodyWriter implements MessageBodyWriter<NormalizedNodeContext> {
56
57     private static final XMLOutputFactory XML_FACTORY;
58
59     static {
60         XML_FACTORY = XMLOutputFactory.newFactory();
61         XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
62     }
63
64     @Override
65     public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
66             final MediaType mediaType) {
67         return type.equals(NormalizedNodeContext.class);
68     }
69
70     @Override
71     public long getSize(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
72             final Annotation[] annotations, final MediaType mediaType) {
73         return -1;
74     }
75
76     @Override
77     public void writeTo(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
78             final Annotation[] annotations, final MediaType mediaType,
79             final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
80             WebApplicationException {
81         for (final Entry<String, Object> entry : context.getNewHeaders().entrySet()) {
82             httpHeaders.add(entry.getKey(), entry.getValue());
83         }
84         final InstanceIdentifierContext<?> pathContext = context.getInstanceIdentifierContext();
85         if (context.getData() == null) {
86             return;
87         }
88
89         XMLStreamWriter xmlWriter;
90         try {
91             xmlWriter = XML_FACTORY.createXMLStreamWriter(entityStream, StandardCharsets.UTF_8.name());
92             if (context.getWriterParameters().isPrettyPrint()) {
93                 xmlWriter = new IndentingXMLStreamWriter(xmlWriter);
94             }
95         } catch (final XMLStreamException | FactoryConfigurationError e) {
96             throw new IllegalStateException(e);
97         }
98         final NormalizedNode<?, ?> data = context.getData();
99         final SchemaPath schemaPath = pathContext.getSchemaNode().getPath();
100
101         writeNormalizedNode(xmlWriter, schemaPath, pathContext, data,
102                 Optional.fromNullable(context.getWriterParameters().getDepth()));
103     }
104
105     private static void writeNormalizedNode(final XMLStreamWriter xmlWriter, final SchemaPath schemaPath,
106             final InstanceIdentifierContext<?> pathContext, NormalizedNode<?, ?> data, final Optional<Integer> depth)
107             throws IOException {
108         final RestconfNormalizedNodeWriter nnWriter;
109         final SchemaContext schemaCtx = pathContext.getSchemaContext();
110         if (SchemaPath.ROOT.equals(schemaPath)) {
111             nnWriter = createNormalizedNodeWriter(xmlWriter, schemaCtx, schemaPath, depth);
112             writeElements(xmlWriter, nnWriter, (ContainerNode) data);
113         }  else if (pathContext.getSchemaNode() instanceof RpcDefinition) {
114             nnWriter = createNormalizedNodeWriter(xmlWriter, schemaCtx,
115                     ((RpcDefinition) pathContext.getSchemaNode()).getOutput().getPath(), depth);
116             writeElements(xmlWriter, nnWriter, (ContainerNode) data);
117         } else {
118             nnWriter = createNormalizedNodeWriter(xmlWriter, schemaCtx, schemaPath.getParent(), depth);
119             if (data instanceof MapEntryNode) {
120                 // Restconf allows returning one list item. We need to wrap it
121                 // in map node in order to serialize it properly
122                 data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).addChild((MapEntryNode) data).build();
123             }
124             nnWriter.write(data);
125         }
126         nnWriter.flush();
127     }
128
129     private static RestconfNormalizedNodeWriter createNormalizedNodeWriter(final XMLStreamWriter xmlWriter,
130             final SchemaContext schemaContext, final SchemaPath schemaPath, final Optional<Integer> depth) {
131         final NormalizedNodeStreamWriter xmlStreamWriter =
132                 XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, schemaContext, schemaPath);
133         if (depth.isPresent()) {
134             return DepthAwareNormalizedNodeWriter.forStreamWriter(xmlStreamWriter, depth.get());
135         }
136
137         return RestconfDelegatingNormalizedNodeWriter.forStreamWriter(xmlStreamWriter);
138     }
139
140     private static void writeElements(final XMLStreamWriter xmlWriter, final RestconfNormalizedNodeWriter nnWriter,
141                                final ContainerNode data)
142             throws IOException {
143         try {
144             final QName name = data.getNodeType();
145             xmlWriter.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, name.getLocalName(),
146                     name.getNamespace().toString());
147             xmlWriter.writeDefaultNamespace(name.getNamespace().toString());
148             for (final NormalizedNode<?,?> child : data.getValue()) {
149                 nnWriter.write(child);
150             }
151             nnWriter.flush();
152             xmlWriter.writeEndElement();
153             xmlWriter.flush();
154         } catch (final XMLStreamException e) {
155             Throwables.propagate(e);
156         }
157     }
158 }