Merge "Fix For Bug #335 Bug Description : Remove SW2 property "description" to a...
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / rest / impl / JsonMapper.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 static com.google.common.base.Preconditions.checkNotNull;
11
12 import java.io.IOException;
13 import java.net.URI;
14 import java.util.HashSet;
15 import java.util.List;
16 import java.util.Set;
17
18 import javax.activation.UnsupportedDataTypeException;
19
20 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
21 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
22 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
23 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.IdentityValue;
24 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.Predicate;
25 import org.opendaylight.controller.sal.restconf.impl.RestCodec;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
28 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.Node;
30 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
31 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
32 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
33 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
35 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 import com.google.common.base.Preconditions;
51 import com.google.gson.stream.JsonWriter;
52
53 class JsonMapper {
54
55     private final Set<LeafListSchemaNode> foundLeafLists = new HashSet<>();
56     private final Set<ListSchemaNode> foundLists = new HashSet<>();
57     private MountInstance mountPoint;
58     private final Logger logger = LoggerFactory.getLogger(JsonMapper.class);
59
60     public void write(JsonWriter writer, CompositeNode data, DataNodeContainer schema, MountInstance mountPoint)
61             throws IOException {
62         Preconditions.checkNotNull(writer);
63         Preconditions.checkNotNull(data);
64         Preconditions.checkNotNull(schema);
65         this.mountPoint = mountPoint;
66
67         writer.beginObject();
68
69         if (schema instanceof ContainerSchemaNode) {
70             writeContainer(writer, data, (ContainerSchemaNode) schema);
71         } else if (schema instanceof ListSchemaNode) {
72             writeList(writer, null, data, (ListSchemaNode) schema);
73         } else {
74             throw new UnsupportedDataTypeException(
75                     "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
76         }
77
78         writer.endObject();
79
80         foundLeafLists.clear();
81         foundLists.clear();
82     }
83
84     private void writeChildrenOfParent(JsonWriter writer, CompositeNode parent, DataNodeContainer parentSchema)
85             throws IOException {
86         checkNotNull(parent);
87         checkNotNull(parentSchema);
88
89         for (Node<?> child : parent.getChildren()) {
90             DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchema.getChildNodes());
91
92             if (childSchema == null) {
93                 throw new UnsupportedDataTypeException("Probably the data node \"" + child.getNodeType().getLocalName()
94                         + "\" is not conform to schema");
95             }
96
97             if (childSchema instanceof ContainerSchemaNode) {
98                 Preconditions.checkState(child instanceof CompositeNode,
99                         "Data representation of Container should be CompositeNode - " + child.getNodeType());
100                 writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema);
101             } else if (childSchema instanceof ListSchemaNode) {
102                 if (!foundLists.contains(childSchema)) {
103                     Preconditions.checkState(child instanceof CompositeNode,
104                             "Data representation of List should be CompositeNode - " + child.getNodeType());
105                     foundLists.add((ListSchemaNode) childSchema);
106                     writeList(writer, parent, (CompositeNode) child, (ListSchemaNode) childSchema);
107                 }
108             } else if (childSchema instanceof LeafListSchemaNode) {
109                 if (!foundLeafLists.contains(childSchema)) {
110                     Preconditions.checkState(child instanceof SimpleNode<?>,
111                             "Data representation of LeafList should be SimpleNode - " + child.getNodeType());
112                     foundLeafLists.add((LeafListSchemaNode) childSchema);
113                     writeLeafList(writer, parent, (SimpleNode<?>) child, (LeafListSchemaNode) childSchema);
114                 }
115             } else if (childSchema instanceof LeafSchemaNode) {
116                 Preconditions.checkState(child instanceof SimpleNode<?>,
117                         "Data representation of LeafList should be SimpleNode - " + child.getNodeType());
118                 writeLeaf(writer, (SimpleNode<?>) child, (LeafSchemaNode) childSchema);
119             } else {
120                 throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, "
121                         + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet.");
122             }
123         }
124
125         for (Node<?> child : parent.getChildren()) {
126             DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchema.getChildNodes());
127             if (childSchema instanceof LeafListSchemaNode) {
128                 foundLeafLists.remove((LeafListSchemaNode) childSchema);
129             } else if (childSchema instanceof ListSchemaNode) {
130                 foundLists.remove((ListSchemaNode) childSchema);
131             }
132         }
133     }
134
135     private DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
136         for (DataSchemaNode dsn : dataSchemaNode) {
137             if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
138                 return dsn;
139             } else if (dsn instanceof ChoiceNode) {
140                 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
141                     DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
142                     if (foundDsn != null) {
143                         return foundDsn;
144                     }
145                 }
146             }
147         }
148         return null;
149     }
150
151     private void writeContainer(JsonWriter writer, CompositeNode node, ContainerSchemaNode schema) throws IOException {
152         writeName(node, schema, writer);
153         writer.beginObject();
154         writeChildrenOfParent(writer, node, schema);
155         writer.endObject();
156     }
157
158     private void writeList(JsonWriter writer, CompositeNode nodeParent, CompositeNode node, ListSchemaNode schema)
159             throws IOException {
160         writeName(node, schema, writer);
161         writer.beginArray();
162
163         if (nodeParent != null) {
164             List<CompositeNode> nodeLists = nodeParent.getCompositesByName(node.getNodeType());
165             for (CompositeNode nodeList : nodeLists) {
166                 writer.beginObject();
167                 writeChildrenOfParent(writer, nodeList, schema);
168                 writer.endObject();
169             }
170         } else {
171             writer.beginObject();
172             writeChildrenOfParent(writer, node, schema);
173             writer.endObject();
174         }
175
176         writer.endArray();
177     }
178
179     private void writeLeafList(JsonWriter writer, CompositeNode nodeParent, SimpleNode<?> node,
180             LeafListSchemaNode schema) throws IOException {
181         writeName(node, schema, writer);
182         writer.beginArray();
183
184         List<SimpleNode<?>> nodeLeafLists = nodeParent.getSimpleNodesByName(node.getNodeType());
185         for (SimpleNode<?> nodeLeafList : nodeLeafLists) {
186             writeValueOfNodeByType(writer, nodeLeafList, schema.getType(), schema);
187         }
188         writer.endArray();
189     }
190
191     private void writeLeaf(JsonWriter writer, SimpleNode<?> node, LeafSchemaNode schema) throws IOException {
192         writeName(node, schema, writer);
193         writeValueOfNodeByType(writer, node, schema.getType(), schema);
194     }
195
196     private void writeValueOfNodeByType(JsonWriter writer, SimpleNode<?> node, TypeDefinition<?> type,
197             DataSchemaNode schema) throws IOException {
198
199         TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(type);
200
201         if (node.getValue() == null && !(baseType instanceof EmptyTypeDefinition)) {
202             logger.debug("While generationg JSON output null value was found for type "
203                     + baseType.getClass().getSimpleName() + ".");
204         }
205
206         // TODO check InstanceIdentifierTypeDefinition
207         if (baseType instanceof IdentityrefTypeDefinition) {
208             if (node.getValue() instanceof QName) {
209                 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
210                         node.getValue());
211                 IdentityValue valueFromDTO = valueDTO.getValuesWithNamespaces().get(0);
212                 String moduleName;
213                 if (mountPoint != null) {
214                     moduleName = ControllerContext.getInstance().findModuleNameByNamespace(mountPoint,
215                             URI.create(valueFromDTO.getNamespace()));
216                 } else {
217                     moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
218                             URI.create(valueFromDTO.getNamespace()));
219                 }
220                 writer.value(moduleName + ":" + valueFromDTO.getValue());
221             } else {
222                 writeStringRepresentation(writer, node, baseType, QName.class);
223             }
224         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
225             if (node.getValue() instanceof InstanceIdentifier) {
226                 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
227                         node.getValue());
228                 writeIdentityValuesDTOToJson(writer, valueDTO);
229             } else {
230                 writeStringRepresentation(writer, node, baseType, InstanceIdentifier.class);
231             }
232         } else if (baseType instanceof DecimalTypeDefinition || baseType instanceof IntegerTypeDefinition
233                 || baseType instanceof UnsignedIntegerTypeDefinition) {
234             writer.value(new NumberForJsonWriter((String) RestCodec.from(baseType, mountPoint).serialize(
235                     node.getValue())));
236         } else if (baseType instanceof BooleanTypeDefinition) {
237             writer.value(Boolean.parseBoolean((String) RestCodec.from(baseType, mountPoint).serialize(node.getValue())));
238         } else if (baseType instanceof EmptyTypeDefinition) {
239             writeEmptyDataTypeToJson(writer);
240         } else {
241             String value = String.valueOf(RestCodec.from(baseType, mountPoint).serialize(node.getValue()));
242             if (value == null) {
243                 value = String.valueOf(node.getValue());
244             }
245             writer.value(value.equals("null") ? "" : value);
246         }
247     }
248
249     private void writeIdentityValuesDTOToJson(JsonWriter writer, IdentityValuesDTO valueDTO) throws IOException {
250         StringBuilder result = new StringBuilder();
251         for (IdentityValue identityValue : valueDTO.getValuesWithNamespaces()) {
252             result.append("/");
253
254             writeModuleNameAndIdentifier(result, identityValue);
255             if (identityValue.getPredicates() != null) {
256                 for (Predicate predicate : identityValue.getPredicates()) {
257                     IdentityValue identityValuePredicate = predicate.getName();
258                     result.append("[");
259                     writeModuleNameAndIdentifier(result, identityValuePredicate);
260                     result.append("=\"");
261                     result.append(predicate.getValue());
262                     result.append("\"");
263                     result.append("]");
264                 }
265             }
266         }
267
268         writer.value(result.toString());
269     }
270
271     private void writeModuleNameAndIdentifier(StringBuilder result, IdentityValue identityValue) {
272         String moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
273                 URI.create(identityValue.getNamespace()));
274         if (moduleName != null && !moduleName.isEmpty()) {
275             result.append(moduleName);
276             result.append(":");
277         }
278         result.append(identityValue.getValue());
279     }
280
281     private void writeStringRepresentation(JsonWriter writer, SimpleNode<?> node, TypeDefinition<?> baseType,
282             Class<?> requiredType) throws IOException {
283         Object value = node.getValue();
284         logger.debug("Value of " + baseType.getQName().getNamespace() + ":" + baseType.getQName().getLocalName()
285                 + " is not instance of " + requiredType.getClass() + " but is " + node.getValue().getClass());
286         if (value == null) {
287             writer.value("");
288         } else {
289             writer.value(String.valueOf(value));
290         }
291     }
292
293     private void writeEmptyDataTypeToJson(JsonWriter writer) throws IOException {
294         writer.beginArray();
295         writer.nullValue();
296         writer.endArray();
297     }
298
299     private void writeName(Node<?> node, DataSchemaNode schema, JsonWriter writer) throws IOException {
300         String nameForOutput = node.getNodeType().getLocalName();
301         if (schema.isAugmenting()) {
302             ControllerContext contContext = ControllerContext.getInstance();
303             CharSequence moduleName;
304             moduleName = contContext.toRestconfIdentifier(schema.getQName());
305             if (moduleName != null) {
306                 nameForOutput = moduleName.toString();
307             }
308         }
309         writer.name(nameForOutput);
310     }
311
312     private static final class NumberForJsonWriter extends Number {
313
314         private static final long serialVersionUID = -3147729419814417666L;
315         private final String value;
316
317         public NumberForJsonWriter(String value) {
318             this.value = value;
319         }
320
321         @Override
322         public int intValue() {
323             throw new IllegalStateException("Should not be invoked");
324         }
325
326         @Override
327         public long longValue() {
328             throw new IllegalStateException("Should not be invoked");
329         }
330
331         @Override
332         public float floatValue() {
333             throw new IllegalStateException("Should not be invoked");
334         }
335
336         @Override
337         public double doubleValue() {
338             throw new IllegalStateException("Should not be invoked");
339         }
340
341         @Override
342         public String toString() {
343             return value;
344         }
345
346     }
347
348 }