Bump MRI upstreams
[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.nio.charset.StandardCharsets;
18 import java.util.List;
19 import java.util.Map;
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.restconf.common.context.InstanceIdentifierContext;
28 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
29 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
30 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.api.RestconfNormalizedNodeWriter;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.XMLNamespace;
33 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
35 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
38 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
39 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
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.ActionDefinition;
44 import org.opendaylight.yangtools.yang.model.api.Module;
45 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
46 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
48
49 @Provider
50 @Produces({ MediaTypes.APPLICATION_YANG_DATA_JSON, MediaType.APPLICATION_JSON })
51 public class NormalizedNodeJsonBodyWriter implements MessageBodyWriter<NormalizedNodeContext> {
52
53     private static final int DEFAULT_INDENT_SPACES_NUM = 2;
54
55     @Override
56     public boolean isWriteable(final Class<?> type,
57                                final Type genericType,
58                                final Annotation[] annotations,
59                                final MediaType mediaType) {
60         return type.equals(NormalizedNodeContext.class);
61     }
62
63     @Override
64     public long getSize(final NormalizedNodeContext context,
65                         final Class<?> type,
66                         final Type genericType,
67                         final Annotation[] annotations,
68                         final MediaType mediaType) {
69         return -1;
70     }
71
72     @Override
73     public void writeTo(final NormalizedNodeContext context,
74                         final Class<?> type,
75                         final Type genericType,
76                         final Annotation[] annotations,
77                         final MediaType mediaType,
78                         final MultivaluedMap<String, Object> httpHeaders,
79                         final OutputStream entityStream) throws IOException, WebApplicationException {
80         final NormalizedNode data = context.getData();
81         if (data == null) {
82             return;
83         }
84
85         @SuppressWarnings("unchecked")
86         final InstanceIdentifierContext<SchemaNode> identifierCtx =
87                 (InstanceIdentifierContext<SchemaNode>) context.getInstanceIdentifierContext();
88         final SchemaPath path = identifierCtx.getSchemaNode().getPath();
89
90         try (JsonWriter jsonWriter = createJsonWriter(entityStream, context.getWriterParameters().isPrettyPrint())) {
91             jsonWriter.beginObject();
92             writeNormalizedNode(jsonWriter, path, identifierCtx, data,
93                     context.getWriterParameters().getDepth(), context.getWriterParameters().getFields());
94             jsonWriter.endObject();
95             jsonWriter.flush();
96         }
97
98         if (httpHeaders != null) {
99             for (final Map.Entry<String, Object> entry : context.getNewHeaders().entrySet()) {
100                 httpHeaders.add(entry.getKey(), entry.getValue());
101             }
102         }
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             final Module module = context.getSchemaContext().findModule(data.getIdentifier().getNodeType().getModule())
122                 .get();
123             jsonWriter.name(module.getName() + ":output");
124             jsonWriter.beginObject();
125             writeChildren(nnWriter, (ContainerNode) data);
126             jsonWriter.endObject();
127         } else if (context.getSchemaNode() instanceof ActionDefinition) {
128             /*
129              *  ActionDefinition is not supported as initial codec in JSONStreamWriter,
130              *  so we need to emit initial output declaration..
131              */
132             nnWriter = createNormalizedNodeWriter(context,
133                 ((ActionDefinition) context.getSchemaNode()).getOutput().getPath(), jsonWriter, depth, fields);
134             final Module module = context.getSchemaContext().findModule(data.getIdentifier().getNodeType().getModule())
135                 .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(ImmutableNodes.mapNodeBuilder(data.getIdentifier().getNodeType())
151                     .withChild((MapEntryNode) data)
152                     .build());
153             } else {
154                 nnWriter.write(data);
155             }
156         }
157
158         nnWriter.flush();
159     }
160
161     private static void writeChildren(final RestconfNormalizedNodeWriter nnWriter, final ContainerNode data)
162             throws IOException {
163         for (final DataContainerChild child : data.body()) {
164             nnWriter.write(child);
165         }
166     }
167
168     private static RestconfNormalizedNodeWriter createNormalizedNodeWriter(
169             final InstanceIdentifierContext<SchemaNode> context, final SchemaPath path, final JsonWriter jsonWriter,
170             final Integer depth, final List<Set<QName>> fields) {
171
172         final SchemaNode schema = context.getSchemaNode();
173         final JSONCodecFactory codecs = getCodecFactory(context);
174
175         final NormalizedNodeStreamWriter streamWriter = JSONNormalizedNodeStreamWriter.createNestedWriter(
176                 codecs, path, initialNamespaceFor(schema), jsonWriter);
177
178         return ParameterAwareNormalizedNodeWriter.forStreamWriter(streamWriter, depth, fields);
179     }
180
181     private static XMLNamespace initialNamespaceFor(final SchemaNode schema) {
182         if (schema instanceof RpcDefinition) {
183             return schema.getQName().getNamespace();
184         }
185         // For top-level elements we always want to use namespace prefix, hence use a null initial namespace
186         return null;
187     }
188
189     private static JsonWriter createJsonWriter(final OutputStream entityStream, final boolean prettyPrint) {
190         if (prettyPrint) {
191             return JsonWriterFactory.createJsonWriter(
192                     new OutputStreamWriter(entityStream, StandardCharsets.UTF_8), DEFAULT_INDENT_SPACES_NUM);
193         }
194         return JsonWriterFactory.createJsonWriter(new OutputStreamWriter(entityStream, StandardCharsets.UTF_8));
195     }
196
197     private static JSONCodecFactory getCodecFactory(final InstanceIdentifierContext<?> context) {
198         // TODO: Performance: Cache JSON Codec factory and schema context
199         return JSONCodecFactorySupplier.RFC7951.getShared(context.getSchemaContext());
200     }
201 }