Create NetconfDataTreeService with base and additional operations for netconf
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / 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.nb.rfc8040.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.Map;
21 import java.util.Set;
22 import javax.ws.rs.Produces;
23 import javax.ws.rs.WebApplicationException;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.MultivaluedMap;
26 import javax.ws.rs.ext.MessageBodyWriter;
27 import javax.ws.rs.ext.Provider;
28 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
29 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
30 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
31 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.api.RestconfNormalizedNodeWriter;
32 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
33 import org.opendaylight.yangtools.yang.common.QName;
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.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.ActionDefinition;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
48 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
50
51 @Provider
52 @Produces({ Rfc8040.MediaTypes.DATA + RestconfConstants.JSON, MediaType.APPLICATION_JSON })
53 public class NormalizedNodeJsonBodyWriter implements MessageBodyWriter<NormalizedNodeContext> {
54
55     private static final int DEFAULT_INDENT_SPACES_NUM = 2;
56
57     @Override
58     public boolean isWriteable(final Class<?> type,
59                                final Type genericType,
60                                final Annotation[] annotations,
61                                final MediaType mediaType) {
62         return type.equals(NormalizedNodeContext.class);
63     }
64
65     @Override
66     public long getSize(final NormalizedNodeContext context,
67                         final Class<?> type,
68                         final Type genericType,
69                         final Annotation[] annotations,
70                         final MediaType mediaType) {
71         return -1;
72     }
73
74     @Override
75     public void writeTo(final NormalizedNodeContext context,
76                         final Class<?> type,
77                         final Type genericType,
78                         final Annotation[] annotations,
79                         final MediaType mediaType,
80                         final MultivaluedMap<String, Object> httpHeaders,
81                         final OutputStream entityStream) throws IOException, WebApplicationException {
82         final NormalizedNode<?, ?> data = context.getData();
83         if (data == null) {
84             return;
85         }
86
87         @SuppressWarnings("unchecked")
88         final InstanceIdentifierContext<SchemaNode> identifierCtx =
89                 (InstanceIdentifierContext<SchemaNode>) context.getInstanceIdentifierContext();
90         final SchemaPath path = identifierCtx.getSchemaNode().getPath();
91
92         try (JsonWriter jsonWriter = createJsonWriter(entityStream, context.getWriterParameters().isPrettyPrint())) {
93             jsonWriter.beginObject();
94             writeNormalizedNode(jsonWriter, path, identifierCtx, data,
95                     context.getWriterParameters().getDepth(), context.getWriterParameters().getFields());
96             jsonWriter.endObject();
97             jsonWriter.flush();
98         }
99
100         if (httpHeaders != null) {
101             for (final Map.Entry<String, Object> entry : context.getNewHeaders().entrySet()) {
102                 httpHeaders.add(entry.getKey(), entry.getValue());
103             }
104         }
105     }
106
107     private static void writeNormalizedNode(final JsonWriter jsonWriter,
108             final SchemaPath path, final InstanceIdentifierContext<SchemaNode> context, final NormalizedNode<?, ?> data,
109             final Integer depth, final List<Set<QName>> fields) throws IOException {
110         final RestconfNormalizedNodeWriter nnWriter;
111
112         if (context.getSchemaNode() instanceof RpcDefinition) {
113             /*
114              *  RpcDefinition is not supported as initial codec in JSONStreamWriter,
115              *  so we need to emit initial output declaration..
116              */
117             nnWriter = createNormalizedNodeWriter(
118                     context,
119                     ((RpcDefinition) context.getSchemaNode()).getOutput().getPath(),
120                     jsonWriter,
121                     depth,
122                     fields);
123             final Module module = context.getSchemaContext().findModule(data.getNodeType().getModule()).get();
124             jsonWriter.name(module.getName() + ":output");
125             jsonWriter.beginObject();
126             writeChildren(nnWriter, (ContainerNode) data);
127             jsonWriter.endObject();
128         } else if (context.getSchemaNode() instanceof ActionDefinition) {
129             /*
130              *  ActionDefinition is not supported as initial codec in JSONStreamWriter,
131              *  so we need to emit initial output declaration..
132              */
133             nnWriter = createNormalizedNodeWriter(context,
134                 ((ActionDefinition) context.getSchemaNode()).getOutput().getPath(), jsonWriter, depth, fields);
135             final Module module = context.getSchemaContext().findModule(data.getNodeType().getModule()).get();
136             jsonWriter.name(module.getName() + ":output");
137             jsonWriter.beginObject();
138             writeChildren(nnWriter, (ContainerNode) data);
139             jsonWriter.endObject();
140         } else {
141             if (SchemaPath.ROOT.equals(path)) {
142                 nnWriter = createNormalizedNodeWriter(context, path, jsonWriter, depth, fields);
143             } else {
144                 nnWriter = createNormalizedNodeWriter(context, path.getParent(), jsonWriter, depth, fields);
145             }
146
147             if (data instanceof MapEntryNode) {
148                 // Restconf allows returning one list item. We need to wrap it
149                 // in map node in order to serialize it properly
150                 nnWriter.write(
151                         ImmutableNodes.mapNodeBuilder(data.getNodeType()).withChild((MapEntryNode) data).build());
152             } else {
153                 nnWriter.write(data);
154             }
155         }
156
157         nnWriter.flush();
158     }
159
160     private static void writeChildren(final RestconfNormalizedNodeWriter nnWriter,
161                                       final ContainerNode data) throws IOException {
162         for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
163             nnWriter.write(child);
164         }
165     }
166
167     private static RestconfNormalizedNodeWriter createNormalizedNodeWriter(
168             final InstanceIdentifierContext<SchemaNode> context, final SchemaPath path, final JsonWriter jsonWriter,
169             final Integer depth, final List<Set<QName>> fields) {
170
171         final SchemaNode schema = context.getSchemaNode();
172         final JSONCodecFactory codecs = getCodecFactory(context);
173
174         final NormalizedNodeStreamWriter streamWriter = JSONNormalizedNodeStreamWriter.createNestedWriter(
175                 codecs, path, initialNamespaceFor(schema), jsonWriter);
176
177         return ParameterAwareNormalizedNodeWriter.forStreamWriter(streamWriter, depth, fields);
178     }
179
180     private static URI initialNamespaceFor(final SchemaNode schema) {
181         if (schema instanceof RpcDefinition) {
182             return schema.getQName().getNamespace();
183         }
184         // For top-level elements we always want to use namespace prefix, hence use a null initial namespace
185         return null;
186     }
187
188     private static JsonWriter createJsonWriter(final OutputStream entityStream, final boolean prettyPrint) {
189         if (prettyPrint) {
190             return JsonWriterFactory.createJsonWriter(
191                     new OutputStreamWriter(entityStream, StandardCharsets.UTF_8), DEFAULT_INDENT_SPACES_NUM);
192         }
193         return JsonWriterFactory.createJsonWriter(new OutputStreamWriter(entityStream, StandardCharsets.UTF_8));
194     }
195
196     private static JSONCodecFactory getCodecFactory(final InstanceIdentifierContext<?> context) {
197         // TODO: Performance: Cache JSON Codec factory and schema context
198         return JSONCodecFactorySupplier.RFC7951.getShared(context.getSchemaContext());
199     }
200 }