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