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