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