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