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