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