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