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