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