349563a22bf5e2bb32a9691c4536eae99b92c903
[netconf.git] / restconf / sal-rest-connector / src / main / java / org / opendaylight / restconf / 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.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.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.netconf.sal.rest.api.RestconfNormalizedNodeWriter;
28 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
29 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
30 import org.opendaylight.restconf.Draft17;
31 import org.opendaylight.restconf.utils.RestconfConstants;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
36 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
39 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
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.DataSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
48
49 @Provider
50 @Produces({ Draft17.MediaTypes.DATA + RestconfConstants.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 t,
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 t,
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 = t.getData();
81         if (data == null) {
82             return;
83         }
84
85         @SuppressWarnings("unchecked")
86         final InstanceIdentifierContext<SchemaNode> context =
87                 (InstanceIdentifierContext<SchemaNode>) t.getInstanceIdentifierContext();
88         final SchemaPath path = context.getSchemaNode().getPath();
89         final JsonWriter jsonWriter = createJsonWriter(entityStream,
90                 t.getWriterParameters().isPrettyPrint());
91
92         jsonWriter.beginObject();
93         writeNormalizedNode(jsonWriter, path, context, data,
94                 t.getWriterParameters().getDepth(), t.getWriterParameters().getFields());
95         jsonWriter.endObject();
96         jsonWriter.flush();
97     }
98
99     private void writeNormalizedNode(final JsonWriter jsonWriter,
100                                      final SchemaPath path,
101                                      final InstanceIdentifierContext<SchemaNode> context,
102                                      final NormalizedNode<?, ?> data,
103                                      final Integer depth,
104                                      final List<Set<QName>> fields) throws IOException {
105         final RestconfNormalizedNodeWriter nnWriter;
106
107         if (context.getSchemaNode() instanceof RpcDefinition) {
108             /*
109              *  RpcDefinition is not supported as initial codec in JSONStreamWriter,
110              *  so we need to emit initial output declaration..
111              */
112             nnWriter = createNormalizedNodeWriter(
113                     context,
114                     ((RpcDefinition) context.getSchemaNode()).getOutput().getPath(),
115                     jsonWriter,
116                     depth,
117                     fields);
118             jsonWriter.name("output");
119             jsonWriter.beginObject();
120             writeChildren(nnWriter, (ContainerNode) data);
121             jsonWriter.endObject();
122         } else {
123             if (SchemaPath.ROOT.equals(path)) {
124                 nnWriter = createNormalizedNodeWriter(context, path, jsonWriter, depth, fields);
125             } else {
126                 nnWriter = createNormalizedNodeWriter(context, path.getParent(), jsonWriter, depth, fields);
127             }
128
129             if (data instanceof MapEntryNode) {
130                 // Restconf allows returning one list item. We need to wrap it
131                 // in map node in order to serialize it properly
132                 nnWriter.write(
133                         ImmutableNodes.mapNodeBuilder(data.getNodeType()).withChild(((MapEntryNode) data)).build());
134             } else {
135                 nnWriter.write(data);
136             }
137         }
138
139         nnWriter.flush();
140     }
141
142     private void writeChildren(final RestconfNormalizedNodeWriter nnWriter,
143                                final ContainerNode data) throws IOException {
144         for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
145             nnWriter.write(child);
146         }
147     }
148
149     private RestconfNormalizedNodeWriter createNormalizedNodeWriter(final InstanceIdentifierContext<SchemaNode> context,
150                                                                     final SchemaPath path,
151                                                                     final JsonWriter jsonWriter,
152                                                                     final Integer depth,
153                                                                     final List<Set<QName>> fields) {
154
155         final SchemaNode schema = context.getSchemaNode();
156         final JSONCodecFactory codecs = getCodecFactory(context);
157
158         final URI initialNs;
159         if ((schema instanceof DataSchemaNode)
160                 && !((DataSchemaNode)schema).isAugmenting()
161                 && !(schema instanceof SchemaContext)) {
162             initialNs = schema.getQName().getNamespace();
163         } else if (schema instanceof RpcDefinition) {
164             initialNs = schema.getQName().getNamespace();
165         } else {
166             initialNs = null;
167         }
168         final NormalizedNodeStreamWriter streamWriter = JSONNormalizedNodeStreamWriter.createNestedWriter(
169                 codecs, path, initialNs, jsonWriter);
170         return ParameterAwareNormalizedNodeWriter.forStreamWriter(streamWriter, depth, fields);
171     }
172
173     private JsonWriter createJsonWriter(final OutputStream entityStream, final boolean prettyPrint) {
174         if (prettyPrint) {
175             return JsonWriterFactory.createJsonWriter(
176                     new OutputStreamWriter(entityStream, StandardCharsets.UTF_8), DEFAULT_INDENT_SPACES_NUM);
177         } else {
178             return JsonWriterFactory.createJsonWriter(new OutputStreamWriter(entityStream, StandardCharsets.UTF_8));
179         }
180     }
181
182     private JSONCodecFactory getCodecFactory(final InstanceIdentifierContext<?> context) {
183         // TODO: Performance: Cache JSON Codec factory and schema context
184         return JSONCodecFactory.create(context.getSchemaContext());
185     }
186 }