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