5d85ba144427299ac659bc1c3fb30343665b68ba
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / rest / impl / NormalizedNodeJsonBodyWriter.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.gson.stream.JsonWriter;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.io.OutputStreamWriter;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16 import java.net.URISyntaxException;
17 import java.nio.charset.StandardCharsets;
18 import java.util.Map.Entry;
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.stream.XMLStreamException;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.netconf.sal.rest.api.Draft02;
28 import org.opendaylight.netconf.sal.rest.api.RestconfNormalizedNodeWriter;
29 import org.opendaylight.netconf.sal.rest.api.RestconfService;
30 import org.opendaylight.netconf.util.NetconfUtil;
31 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
32 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
33 import org.opendaylight.yangtools.yang.common.XMLNamespace;
34 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
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.gson.JSONCodecFactory;
41 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
42 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
44 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
50 import org.xml.sax.SAXException;
51
52 /**
53  * Normalized node writer for JSON.
54  *
55  * @deprecated This class will be replaced by NormalizedNodeJsonBodyWriter from restconf-nb-rfc8040
56  */
57 @Deprecated
58 @Provider
59 @Produces({
60     Draft02.MediaTypes.API + RestconfService.JSON,
61     Draft02.MediaTypes.DATA + RestconfService.JSON,
62     Draft02.MediaTypes.OPERATION + RestconfService.JSON,
63     MediaType.APPLICATION_JSON
64 })
65 public class NormalizedNodeJsonBodyWriter implements MessageBodyWriter<NormalizedNodeContext> {
66
67     private static final int DEFAULT_INDENT_SPACES_NUM = 2;
68
69     @Override
70     public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
71             final MediaType mediaType) {
72         return type.equals(NormalizedNodeContext.class);
73     }
74
75     @Override
76     public long getSize(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
77             final Annotation[] annotations, final MediaType mediaType) {
78         return -1;
79     }
80
81     @Override
82     public void writeTo(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
83             final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders,
84             final OutputStream entityStream) throws IOException, WebApplicationException {
85         if (httpHeaders != null) {
86             for (final Entry<String, Object> entry : context.getNewHeaders().entrySet()) {
87                 httpHeaders.add(entry.getKey(), entry.getValue());
88             }
89         }
90         NormalizedNode data = context.getData();
91         if (data == null) {
92             return;
93         }
94
95         @SuppressWarnings("unchecked")
96         final InstanceIdentifierContext<SchemaNode> identifierCtx =
97                 (InstanceIdentifierContext<SchemaNode>) context.getInstanceIdentifierContext();
98
99         try (JsonWriter jsonWriter = createJsonWriter(entityStream, context.getWriterParameters().isPrettyPrint())) {
100             jsonWriter.beginObject();
101             writeNormalizedNode(jsonWriter, identifierCtx, data, context.getWriterParameters().getDepth());
102             jsonWriter.endObject();
103             jsonWriter.flush();
104         }
105     }
106
107     private static void writeNormalizedNode(final JsonWriter jsonWriter,
108             final InstanceIdentifierContext<SchemaNode> context, NormalizedNode data,
109             final @Nullable Integer depth) throws IOException {
110         SchemaPath path = context.getSchemaNode().getPath();
111         final RestconfNormalizedNodeWriter nnWriter;
112         if (SchemaPath.ROOT.equals(path)) {
113             /*
114              *  Creates writer without initialNs and we write children of root data container
115              *  which is not visible in restconf
116              */
117             nnWriter = createNormalizedNodeWriter(context, path, jsonWriter, depth);
118             if (data instanceof ContainerNode) {
119                 writeChildren(nnWriter,(ContainerNode) data);
120             } else if (data instanceof DOMSourceAnyxmlNode) {
121                 try {
122                     writeChildren(nnWriter,
123                             (ContainerNode) NetconfUtil.transformDOMSourceToNormalizedNode(
124                                     context.getSchemaContext(), ((DOMSourceAnyxmlNode)data).body()).getResult());
125                 } catch (XMLStreamException | URISyntaxException | SAXException e) {
126                     throw new IOException("Cannot write anyxml.", e);
127                 }
128             }
129         } else if (context.getSchemaNode() instanceof RpcDefinition) {
130             /*
131              *  RpcDefinition is not supported as initial codec in JSONStreamWriter,
132              *  so we need to emit initial output declaratation..
133              */
134             path = ((RpcDefinition) context.getSchemaNode()).getOutput().getPath();
135             nnWriter = createNormalizedNodeWriter(context, path, jsonWriter, depth);
136             jsonWriter.name("output");
137             jsonWriter.beginObject();
138             writeChildren(nnWriter, (ContainerNode) data);
139             jsonWriter.endObject();
140         } else {
141             path = path.getParent();
142
143             if (data instanceof MapEntryNode) {
144                 data = ImmutableNodes.mapNodeBuilder(data.getIdentifier().getNodeType())
145                     .withChild((MapEntryNode) data)
146                     .build();
147             }
148             nnWriter = createNormalizedNodeWriter(context, path, jsonWriter, depth);
149             nnWriter.write(data);
150         }
151         nnWriter.flush();
152     }
153
154     private static void writeChildren(final RestconfNormalizedNodeWriter nnWriter, final ContainerNode data)
155             throws IOException {
156         for (final DataContainerChild child : data.body()) {
157             nnWriter.write(child);
158         }
159     }
160
161     private static RestconfNormalizedNodeWriter createNormalizedNodeWriter(
162             final InstanceIdentifierContext<SchemaNode> context, final SchemaPath path, final JsonWriter jsonWriter,
163             final @Nullable Integer depth) {
164
165         final SchemaNode schema = context.getSchemaNode();
166         final JSONCodecFactory codecs = getCodecFactory(context);
167
168         final XMLNamespace initialNs;
169         if (schema instanceof DataSchemaNode && !((DataSchemaNode)schema).isAugmenting()
170                 && !(schema instanceof SchemaContext) || schema instanceof RpcDefinition) {
171             initialNs = schema.getQName().getNamespace();
172         } else {
173             initialNs = null;
174         }
175         final NormalizedNodeStreamWriter streamWriter =
176                 JSONNormalizedNodeStreamWriter.createNestedWriter(codecs, path, initialNs, jsonWriter);
177         if (depth != null) {
178             return DepthAwareNormalizedNodeWriter.forStreamWriter(streamWriter, depth);
179         }
180
181         return RestconfDelegatingNormalizedNodeWriter.forStreamWriter(streamWriter);
182     }
183
184     private static JsonWriter createJsonWriter(final OutputStream entityStream, final boolean prettyPrint) {
185         if (prettyPrint) {
186             return JsonWriterFactory.createJsonWriter(new OutputStreamWriter(entityStream, StandardCharsets.UTF_8),
187                     DEFAULT_INDENT_SPACES_NUM);
188         }
189
190         return JsonWriterFactory.createJsonWriter(new OutputStreamWriter(entityStream, StandardCharsets.UTF_8));
191     }
192
193     private static JSONCodecFactory getCodecFactory(final InstanceIdentifierContext<?> context) {
194         // TODO: Performance: Cache JSON Codec factory and schema context
195         return JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(context.getSchemaContext());
196     }
197 }