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