434233caf79afc2e0b33dc0c4ffac0d9be87eb52
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / rest / impl / NormalizedNodeJsonBodyWriter.java
1 /*
2  * Copyright (c) 2014 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.netconf.sal.rest.impl;
9
10 import com.google.common.base.Optional;
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.Map.Entry;
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.MessageBodyWriter;
25 import javax.ws.rs.ext.Provider;
26 import org.opendaylight.netconf.sal.rest.api.Draft02;
27 import org.opendaylight.netconf.sal.rest.api.RestconfNormalizedNodeWriter;
28 import org.opendaylight.netconf.sal.rest.api.RestconfService;
29 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
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.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.DataSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
46
47 /**
48  * Normalized node writer for JSON.
49  *
50  * @deprecated This class will be replaced by NormalizedNodeJsonBodyWriter from restconf-nb-rfc8040
51  */
52 @Deprecated
53 @Provider
54 @Produces({ Draft02.MediaTypes.API + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
55         Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON })
56 public class NormalizedNodeJsonBodyWriter implements MessageBodyWriter<NormalizedNodeContext> {
57
58     private static final int DEFAULT_INDENT_SPACES_NUM = 2;
59
60     @Override
61     public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
62             final MediaType mediaType) {
63         return type.equals(NormalizedNodeContext.class);
64     }
65
66     @Override
67     public long getSize(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
68             final Annotation[] annotations, final MediaType mediaType) {
69         return -1;
70     }
71
72     @Override
73     public void writeTo(final NormalizedNodeContext context, final Class<?> type, final Type genericType,
74             final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders,
75             final OutputStream entityStream) throws IOException, WebApplicationException {
76         for (final Entry<String, Object> entry : context.getNewHeaders().entrySet()) {
77             httpHeaders.add(entry.getKey(), entry.getValue());
78         }
79         final NormalizedNode<?, ?> data = context.getData();
80         if (data == null) {
81             return;
82         }
83
84         @SuppressWarnings("unchecked")
85         final InstanceIdentifierContext<SchemaNode> identifierCtx =
86                 (InstanceIdentifierContext<SchemaNode>) context.getInstanceIdentifierContext();
87
88         final SchemaPath path = identifierCtx.getSchemaNode().getPath();
89         final JsonWriter jsonWriter = createJsonWriter(entityStream, context.getWriterParameters().isPrettyPrint());
90         jsonWriter.beginObject();
91         writeNormalizedNode(
92                 jsonWriter,path,identifierCtx,data, Optional.fromNullable(context.getWriterParameters().getDepth()));
93         jsonWriter.endObject();
94         jsonWriter.flush();
95     }
96
97     private static void writeNormalizedNode(final JsonWriter jsonWriter, SchemaPath path,
98             final InstanceIdentifierContext<SchemaNode> context, NormalizedNode<?, ?> data,
99             final Optional<Integer> depth) throws IOException {
100         final RestconfNormalizedNodeWriter nnWriter;
101         if (SchemaPath.ROOT.equals(path)) {
102             /*
103              *  Creates writer without initialNs and we write children of root data container
104              *  which is not visible in restconf
105              */
106             nnWriter = createNormalizedNodeWriter(context,path,jsonWriter, depth);
107             writeChildren(nnWriter,(ContainerNode) data);
108         } else if (context.getSchemaNode() instanceof RpcDefinition) {
109             /*
110              *  RpcDefinition is not supported as initial codec in JSONStreamWriter,
111              *  so we need to emit initial output declaratation..
112              */
113             path = ((RpcDefinition) context.getSchemaNode()).getOutput().getPath();
114             nnWriter = createNormalizedNodeWriter(context,path,jsonWriter, depth);
115             jsonWriter.name("output");
116             jsonWriter.beginObject();
117             writeChildren(nnWriter, (ContainerNode) data);
118             jsonWriter.endObject();
119         } else {
120             path = path.getParent();
121
122             if (data instanceof MapEntryNode) {
123                 data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).withChild((MapEntryNode) data).build();
124             }
125             nnWriter = createNormalizedNodeWriter(context,path,jsonWriter, depth);
126             nnWriter.write(data);
127         }
128         nnWriter.flush();
129     }
130
131     private static void writeChildren(final RestconfNormalizedNodeWriter nnWriter, final ContainerNode data)
132             throws IOException {
133         for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
134             nnWriter.write(child);
135         }
136     }
137
138     private static RestconfNormalizedNodeWriter createNormalizedNodeWriter(
139             final InstanceIdentifierContext<SchemaNode> context, final SchemaPath path, final JsonWriter jsonWriter,
140             final Optional<Integer> depth) {
141
142         final SchemaNode schema = context.getSchemaNode();
143         final JSONCodecFactory codecs = getCodecFactory(context);
144
145         final URI initialNs;
146         if (schema instanceof DataSchemaNode && !((DataSchemaNode)schema).isAugmenting()
147                 && !(schema instanceof SchemaContext)) {
148             initialNs = schema.getQName().getNamespace();
149         } else if (schema instanceof RpcDefinition) {
150             initialNs = schema.getQName().getNamespace();
151         } else {
152             initialNs = null;
153         }
154         final NormalizedNodeStreamWriter streamWriter =
155                 JSONNormalizedNodeStreamWriter.createNestedWriter(codecs, path, initialNs, jsonWriter);
156         if (depth.isPresent()) {
157             return DepthAwareNormalizedNodeWriter.forStreamWriter(streamWriter, depth.get());
158         }
159
160         return RestconfDelegatingNormalizedNodeWriter.forStreamWriter(streamWriter);
161     }
162
163     private static JsonWriter createJsonWriter(final OutputStream entityStream, final boolean prettyPrint) {
164         if (prettyPrint) {
165             return JsonWriterFactory.createJsonWriter(new OutputStreamWriter(entityStream, StandardCharsets.UTF_8),
166                     DEFAULT_INDENT_SPACES_NUM);
167         }
168
169         return JsonWriterFactory.createJsonWriter(new OutputStreamWriter(entityStream, StandardCharsets.UTF_8));
170     }
171
172     private static JSONCodecFactory getCodecFactory(final InstanceIdentifierContext<?> context) {
173         // TODO: Performance: Cache JSON Codec factory and schema context
174         return JSONCodecFactory.getShared(context.getSchemaContext());
175     }
176 }