Merge "Introducing the Modification classses"
[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
54     private MountInstance mountPoint;
55     private final Logger logger = LoggerFactory.getLogger(JsonMapper.class);
56
57     public void write(final JsonWriter writer, final CompositeNode data, final DataNodeContainer schema, final MountInstance mountPoint)
58             throws IOException {
59         Preconditions.checkNotNull(writer);
60         Preconditions.checkNotNull(data);
61         Preconditions.checkNotNull(schema);
62         this.mountPoint = mountPoint;
63
64         writer.beginObject();
65
66         if (schema instanceof ContainerSchemaNode) {
67             writeContainer(writer, data, (ContainerSchemaNode) schema);
68         } else if (schema instanceof ListSchemaNode) {
69             writeList(writer, null, data, (ListSchemaNode) schema);
70         } else {
71             throw new UnsupportedDataTypeException(
72                     "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
73         }
74
75         writer.endObject();
76     }
77
78     private void writeChildrenOfParent(final JsonWriter writer, final CompositeNode parent, final DataNodeContainer parentSchema)
79             throws IOException {
80         checkNotNull(parent);
81
82         final Set<QName> foundLists = new HashSet<>();
83
84         Set<DataSchemaNode> parentSchemaChildNodes = parentSchema == null ?
85                                    Collections.<DataSchemaNode>emptySet() : parentSchema.getChildNodes();
86
87
88         for (Node<?> child : parent.getValue()) {
89             DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes);
90
91             if (childSchema == null) {
92                 // Node may not conform to schema or allows "anyxml" - we'll process it.
93
94                 logger.debug( "No schema found for data node \"" + child.getNodeType() );
95
96                 if( !foundLists.contains( child.getNodeType() ) ) {
97                     handleNoSchemaFound( writer, child, parent );
98
99                     // Since we don't have a schema, we don't know which nodes are supposed to be
100                     // lists so treat every one as a potential list to avoid outputting duplicates.
101
102                     foundLists.add( child.getNodeType() );
103                 }
104             }
105             else if (childSchema instanceof ContainerSchemaNode) {
106                 Preconditions.checkState(child instanceof CompositeNode,
107                         "Data representation of Container should be CompositeNode - " + 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 - " + 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 - " + 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 - " + 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                 }
131                 else {
132                     handleNoSchemaFound( writer, child, parent );
133                 }
134             } else {
135                 throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, "
136                         + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet.");
137             }
138         }
139     }
140
141     private void writeValue( final JsonWriter writer, Object value ) throws IOException {
142         if( value != null ) {
143             writer.value( String.valueOf( value ) );
144         }
145         else {
146             writer.value( "" );
147         }
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 - " + 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 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             } else if (dsn instanceof ChoiceNode) {
186                 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
187                     DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
188                     if (foundDsn != null) {
189                         return foundDsn;
190                     }
191                 }
192             }
193         }
194         return null;
195     }
196
197     private void writeContainer(final JsonWriter writer, final CompositeNode node, final ContainerSchemaNode schema) throws IOException {
198         writeName(node, schema, writer);
199         writer.beginObject();
200         writeChildrenOfParent(writer, node, schema);
201         writer.endObject();
202     }
203
204     private void writeList(final JsonWriter writer, final CompositeNode nodeParent, final CompositeNode node, final ListSchemaNode schema)
205             throws IOException {
206         writeName(node, schema, writer);
207         writer.beginArray();
208
209         if (nodeParent != null) {
210             List<CompositeNode> nodeLists = nodeParent.getCompositesByName(node.getNodeType());
211             for (CompositeNode nodeList : nodeLists) {
212                 writer.beginObject();
213                 writeChildrenOfParent(writer, nodeList, schema);
214                 writer.endObject();
215             }
216         } else {
217             writer.beginObject();
218             writeChildrenOfParent(writer, node, schema);
219             writer.endObject();
220         }
221
222         writer.endArray();
223     }
224
225     private void writeLeafList(final JsonWriter writer, final CompositeNode nodeParent, final SimpleNode<?> node,
226             final LeafListSchemaNode schema) throws IOException {
227         writeName(node, schema, writer);
228         writer.beginArray();
229
230         List<SimpleNode<?>> nodeLeafLists = nodeParent.getSimpleNodesByName(node.getNodeType());
231         for (SimpleNode<?> nodeLeafList : nodeLeafLists) {
232             writeValueOfNodeByType(writer, nodeLeafList, schema.getType(), schema);
233         }
234         writer.endArray();
235     }
236
237     private void writeLeaf(final JsonWriter writer, final SimpleNode<?> node, final LeafSchemaNode schema) throws IOException {
238         writeName(node, schema, writer);
239         writeValueOfNodeByType(writer, node, schema.getType(), schema);
240     }
241
242     private void writeValueOfNodeByType(final JsonWriter writer, final SimpleNode<?> node, final TypeDefinition<?> type,
243             final DataSchemaNode schema) throws IOException {
244
245         TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(type);
246
247         if (node.getValue() == null && !(baseType instanceof EmptyTypeDefinition)) {
248             logger.debug("While generationg JSON output null value was found for type "
249                     + baseType.getClass().getSimpleName() + ".");
250         }
251
252         if (baseType instanceof IdentityrefTypeDefinition) {
253             if (node.getValue() instanceof QName) {
254                 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
255                         node.getValue());
256                 IdentityValue valueFromDTO = valueDTO.getValuesWithNamespaces().get(0);
257                 String moduleName;
258                 if (mountPoint != null) {
259                     moduleName = ControllerContext.getInstance().findModuleNameByNamespace(mountPoint,
260                             URI.create(valueFromDTO.getNamespace()));
261                 } else {
262                     moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
263                             URI.create(valueFromDTO.getNamespace()));
264                 }
265                 writer.value(moduleName + ":" + valueFromDTO.getValue());
266             } else {
267                 writeStringRepresentation(writer, node, baseType, QName.class);
268             }
269         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
270             if (node.getValue() instanceof InstanceIdentifier) {
271                 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
272                         node.getValue());
273                 writeIdentityValuesDTOToJson(writer, valueDTO);
274             } else {
275                 writeStringRepresentation(writer, node, baseType, InstanceIdentifier.class);
276             }
277         } else if (baseType instanceof DecimalTypeDefinition || baseType instanceof IntegerTypeDefinition
278                 || baseType instanceof UnsignedIntegerTypeDefinition) {
279             writer.value(new NumberForJsonWriter((String) RestCodec.from(baseType, mountPoint).serialize(
280                     node.getValue())));
281         } else if (baseType instanceof BooleanTypeDefinition) {
282             writer.value(Boolean.parseBoolean((String) RestCodec.from(baseType, mountPoint).serialize(node.getValue())));
283         } else if (baseType instanceof EmptyTypeDefinition) {
284             writeEmptyDataTypeToJson(writer);
285         } else {
286             String value = String.valueOf(RestCodec.from(baseType, mountPoint).serialize(node.getValue()));
287             if (value == null) {
288                 value = String.valueOf(node.getValue());
289             }
290             writer.value(value.equals("null") ? "" : value);
291         }
292     }
293
294     private void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO) throws IOException {
295         StringBuilder result = new StringBuilder();
296         for (IdentityValue identityValue : valueDTO.getValuesWithNamespaces()) {
297             result.append("/");
298
299             writeModuleNameAndIdentifier(result, identityValue);
300             if (identityValue.getPredicates() != null && !identityValue.getPredicates().isEmpty()) {
301                 for (Predicate predicate : identityValue.getPredicates()) {
302                     IdentityValue identityValuePredicate = predicate.getName();
303                     result.append("[");
304                     if (identityValuePredicate == null) {
305                         result.append(".");
306                     } else {
307                         writeModuleNameAndIdentifier(result, identityValuePredicate);
308                     }
309                     result.append("='");
310                     result.append(predicate.getValue());
311                     result.append("'");
312                     result.append("]");
313                 }
314             }
315         }
316
317         writer.value(result.toString());
318     }
319
320     private 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 void writeStringRepresentation(final JsonWriter writer, final SimpleNode<?> node, final TypeDefinition<?> baseType,
331             final Class<?> requiredType) throws IOException {
332         Object value = node.getValue();
333         logger.debug("Value of " + baseType.getQName().getNamespace() + ":" + baseType.getQName().getLocalName()
334                 + " is not instance of " + requiredType.getClass() + " but is " + node.getValue().getClass());
335         if (value == null) {
336             writer.value("");
337         } else {
338             writer.value(String.valueOf(value));
339         }
340     }
341
342     private void writeEmptyDataTypeToJson(final JsonWriter writer) throws IOException {
343         writer.beginArray();
344         writer.nullValue();
345         writer.endArray();
346     }
347
348     private void writeName(final Node<?> node, final DataSchemaNode schema, final JsonWriter writer) throws IOException {
349         String nameForOutput = node.getNodeType().getLocalName();
350         if ( schema != null && schema.isAugmenting()) {
351             ControllerContext contContext = ControllerContext.getInstance();
352             CharSequence moduleName = null;
353             if (mountPoint == null) {
354                 moduleName = contContext.toRestconfIdentifier(schema.getQName());
355             } else {
356                 moduleName = contContext.toRestconfIdentifier(mountPoint, schema.getQName());
357             }
358             if (moduleName != null) {
359                 nameForOutput = moduleName.toString();
360             } else {
361                 logger.info("Module '{}' was not found in schema from mount point", schema.getQName());
362             }
363         }
364         writer.name(nameForOutput);
365     }
366
367     private static final class NumberForJsonWriter extends Number {
368
369         private static final long serialVersionUID = -3147729419814417666L;
370         private final String value;
371
372         public NumberForJsonWriter(final String value) {
373             this.value = value;
374         }
375
376         @Override
377         public int intValue() {
378             throw new IllegalStateException("Should not be invoked");
379         }
380
381         @Override
382         public long longValue() {
383             throw new IllegalStateException("Should not be invoked");
384         }
385
386         @Override
387         public float floatValue() {
388             throw new IllegalStateException("Should not be invoked");
389         }
390
391         @Override
392         public double doubleValue() {
393             throw new IllegalStateException("Should not be invoked");
394         }
395
396         @Override
397         public String toString() {
398             return value;
399         }
400
401     }
402
403 }