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