d5f23f72a4f85b1b6b9aa774cb6fc0fb35de11e7
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / restconf / jersey / providers / NormalizedNodeJsonBodyWriter.java
1 /*
2  * Copyright (c) 2016 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
9 package org.opendaylight.restconf.jersey.providers;
10
11 import com.google.gson.stream.JsonWriter;
12 import java.io.IOException;
13 import java.io.OutputStream;
14 import java.io.OutputStreamWriter;
15 import java.lang.annotation.Annotation;
16 import java.lang.reflect.Type;
17 import java.net.URI;
18 import java.nio.charset.StandardCharsets;
19 import java.util.List;
20 import java.util.Set;
21 import javax.ws.rs.Produces;
22 import javax.ws.rs.WebApplicationException;
23 import javax.ws.rs.core.MediaType;
24 import javax.ws.rs.core.MultivaluedMap;
25 import javax.ws.rs.ext.MessageBodyWriter;
26 import javax.ws.rs.ext.Provider;
27 import org.opendaylight.netconf.sal.rest.api.RestconfNormalizedNodeWriter;
28 import org.opendaylight.restconf.Rfc8040;
29 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
31 import org.opendaylight.restconf.utils.RestconfConstants;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
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.gson.JSONCodecFactory;
40 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
42 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
43 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
48
49 /**
50  * Writer NormalizedNode to Json.
51  *
52  * @deprecated move to splitted module restconf-nb-rfc8040
53  */
54 @Deprecated
55 @Provider
56 @Produces({ Rfc8040.MediaTypes.DATA + RestconfConstants.JSON, MediaType.APPLICATION_JSON })
57 public class NormalizedNodeJsonBodyWriter implements MessageBodyWriter<NormalizedNodeContext> {
58
59     private static final int DEFAULT_INDENT_SPACES_NUM = 2;
60
61     @Override
62     public boolean isWriteable(final Class<?> type,
63                                final Type genericType,
64                                final Annotation[] annotations,
65                                final MediaType mediaType) {
66         return type.equals(NormalizedNodeContext.class);
67     }
68
69     @Override
70     public long getSize(final NormalizedNodeContext context,
71                         final Class<?> type,
72                         final Type genericType,
73                         final Annotation[] annotations,
74                         final MediaType mediaType) {
75         return -1;
76     }
77
78     @Override
79     public void writeTo(final NormalizedNodeContext context,
80                         final Class<?> type,
81                         final Type genericType,
82                         final Annotation[] annotations,
83                         final MediaType mediaType,
84                         final MultivaluedMap<String, Object> httpHeaders,
85                         final OutputStream entityStream) throws IOException, WebApplicationException {
86         final NormalizedNode<?, ?> data = context.getData();
87         if (data == null) {
88             return;
89         }
90
91         @SuppressWarnings("unchecked")
92         final InstanceIdentifierContext<SchemaNode> identifierCtx =
93                 (InstanceIdentifierContext<SchemaNode>) context.getInstanceIdentifierContext();
94         final SchemaPath path = identifierCtx.getSchemaNode().getPath();
95         final JsonWriter jsonWriter = createJsonWriter(entityStream,
96                 context.getWriterParameters().isPrettyPrint());
97
98         jsonWriter.beginObject();
99         writeNormalizedNode(jsonWriter, path, identifierCtx, data,
100                 context.getWriterParameters().getDepth(), context.getWriterParameters().getFields());
101         jsonWriter.endObject();
102         jsonWriter.flush();
103     }
104
105     private static void writeNormalizedNode(final JsonWriter jsonWriter,
106             final SchemaPath path, final InstanceIdentifierContext<SchemaNode> context, final NormalizedNode<?, ?> data,
107             final Integer depth, final List<Set<QName>> fields) throws IOException {
108         final RestconfNormalizedNodeWriter nnWriter;
109
110         if (context.getSchemaNode() instanceof RpcDefinition) {
111             /*
112              *  RpcDefinition is not supported as initial codec in JSONStreamWriter,
113              *  so we need to emit initial output declaration..
114              */
115             nnWriter = createNormalizedNodeWriter(
116                     context,
117                     ((RpcDefinition) context.getSchemaNode()).getOutput().getPath(),
118                     jsonWriter,
119                     depth,
120                     fields);
121             jsonWriter.name("output");
122             jsonWriter.beginObject();
123             writeChildren(nnWriter, (ContainerNode) data);
124             jsonWriter.endObject();
125         } else {
126             if (SchemaPath.ROOT.equals(path)) {
127                 nnWriter = createNormalizedNodeWriter(context, path, jsonWriter, depth, fields);
128             } else {
129                 nnWriter = createNormalizedNodeWriter(context, path.getParent(), jsonWriter, depth, fields);
130             }
131
132             if (data instanceof MapEntryNode) {
133                 // Restconf allows returning one list item. We need to wrap it
134                 // in map node in order to serialize it properly
135                 nnWriter.write(
136                         ImmutableNodes.mapNodeBuilder(data.getNodeType()).withChild((MapEntryNode) data).build());
137             } else {
138                 nnWriter.write(data);
139             }
140         }
141
142         nnWriter.flush();
143     }
144
145     private static void writeChildren(final RestconfNormalizedNodeWriter nnWriter,
146                                       final ContainerNode data) throws IOException {
147         for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
148             nnWriter.write(child);
149         }
150     }
151
152     private static RestconfNormalizedNodeWriter createNormalizedNodeWriter(
153             final InstanceIdentifierContext<SchemaNode> context, final SchemaPath path, final JsonWriter jsonWriter,
154             final Integer depth, final List<Set<QName>> fields) {
155
156         final SchemaNode schema = context.getSchemaNode();
157         final JSONCodecFactory codecs = getCodecFactory(context);
158
159         final URI initialNs;
160         if (schema instanceof DataSchemaNode
161                 && !((DataSchemaNode)schema).isAugmenting()
162                 && !(schema instanceof SchemaContext)) {
163             initialNs = schema.getQName().getNamespace();
164         } else if (schema instanceof RpcDefinition) {
165             initialNs = schema.getQName().getNamespace();
166         } else {
167             initialNs = null;
168         }
169         final NormalizedNodeStreamWriter streamWriter = JSONNormalizedNodeStreamWriter.createNestedWriter(
170                 codecs, path, initialNs, jsonWriter);
171         return ParameterAwareNormalizedNodeWriter.forStreamWriter(streamWriter, depth, fields);
172     }
173
174     private static JsonWriter createJsonWriter(final OutputStream entityStream, final boolean prettyPrint) {
175         if (prettyPrint) {
176             return JsonWriterFactory.createJsonWriter(
177                     new OutputStreamWriter(entityStream, StandardCharsets.UTF_8), DEFAULT_INDENT_SPACES_NUM);
178         }
179         return JsonWriterFactory.createJsonWriter(new OutputStreamWriter(entityStream, StandardCharsets.UTF_8));
180     }
181
182     private static JSONCodecFactory getCodecFactory(final InstanceIdentifierContext<?> context) {
183         // TODO: Performance: Cache JSON Codec factory and schema context
184         return JSONCodecFactory.getShared(context.getSchemaContext());
185     }
186 }