ea0f149d296887f4c713ba32e675ee8e4b8fbf54
[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(final JsonWriter writer, final CompositeNode data, final DataNodeContainer schema, final 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(final JsonWriter writer, final CompositeNode parent, final DataNodeContainer parentSchema)
85             throws IOException {
86         checkNotNull(parent);
87         checkNotNull(parentSchema);
88
89         for (Node<?> child : parent.getValue()) {
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.getValue()) {
126             DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchema.getChildNodes());
127             if (childSchema instanceof LeafListSchemaNode) {
128                 foundLeafLists.remove(childSchema);
129             } else if (childSchema instanceof ListSchemaNode) {
130                 foundLists.remove(childSchema);
131             }
132         }
133     }
134
135     private DataSchemaNode findFirstSchemaForNode(final Node<?> node, final Set<DataSchemaNode> dataSchemaNode) {
136         for (DataSchemaNode dsn : dataSchemaNode) {
137             if (node.getNodeType().equals(dsn.getQName())) {
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(final JsonWriter writer, final CompositeNode node, final 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(final JsonWriter writer, final CompositeNode nodeParent, final CompositeNode node, final 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(final JsonWriter writer, final CompositeNode nodeParent, final SimpleNode<?> node,
180             final 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(final JsonWriter writer, final SimpleNode<?> node, final LeafSchemaNode schema) throws IOException {
192         writeName(node, schema, writer);
193         writeValueOfNodeByType(writer, node, schema.getType(), schema);
194     }
195
196     private void writeValueOfNodeByType(final JsonWriter writer, final SimpleNode<?> node, final TypeDefinition<?> type,
197             final 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         if (baseType instanceof IdentityrefTypeDefinition) {
207             if (node.getValue() instanceof QName) {
208                 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
209                         node.getValue());
210                 IdentityValue valueFromDTO = valueDTO.getValuesWithNamespaces().get(0);
211                 String moduleName;
212                 if (mountPoint != null) {
213                     moduleName = ControllerContext.getInstance().findModuleNameByNamespace(mountPoint,
214                             URI.create(valueFromDTO.getNamespace()));
215                 } else {
216                     moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
217                             URI.create(valueFromDTO.getNamespace()));
218                 }
219                 writer.value(moduleName + ":" + valueFromDTO.getValue());
220             } else {
221                 writeStringRepresentation(writer, node, baseType, QName.class);
222             }
223         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
224             if (node.getValue() instanceof InstanceIdentifier) {
225                 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
226                         node.getValue());
227                 writeIdentityValuesDTOToJson(writer, valueDTO);
228             } else {
229                 writeStringRepresentation(writer, node, baseType, InstanceIdentifier.class);
230             }
231         } else if (baseType instanceof DecimalTypeDefinition || baseType instanceof IntegerTypeDefinition
232                 || baseType instanceof UnsignedIntegerTypeDefinition) {
233             writer.value(new NumberForJsonWriter((String) RestCodec.from(baseType, mountPoint).serialize(
234                     node.getValue())));
235         } else if (baseType instanceof BooleanTypeDefinition) {
236             writer.value(Boolean.parseBoolean((String) RestCodec.from(baseType, mountPoint).serialize(node.getValue())));
237         } else if (baseType instanceof EmptyTypeDefinition) {
238             writeEmptyDataTypeToJson(writer);
239         } else {
240             String value = String.valueOf(RestCodec.from(baseType, mountPoint).serialize(node.getValue()));
241             if (value == null) {
242                 value = String.valueOf(node.getValue());
243             }
244             writer.value(value.equals("null") ? "" : value);
245         }
246     }
247
248     private void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO) throws IOException {
249         StringBuilder result = new StringBuilder();
250         for (IdentityValue identityValue : valueDTO.getValuesWithNamespaces()) {
251             result.append("/");
252
253             writeModuleNameAndIdentifier(result, identityValue);
254             if (identityValue.getPredicates() != null && !identityValue.getPredicates().isEmpty()) {
255                 for (Predicate predicate : identityValue.getPredicates()) {
256                     IdentityValue identityValuePredicate = predicate.getName();
257                     result.append("[");
258                     if (identityValuePredicate == null) {
259                         result.append(".");
260                     } else {
261                         writeModuleNameAndIdentifier(result, identityValuePredicate);
262                     }
263                     result.append("='");
264                     result.append(predicate.getValue());
265                     result.append("'");
266                     result.append("]");
267                 }
268             }
269         }
270
271         writer.value(result.toString());
272     }
273
274     private void writeModuleNameAndIdentifier(final StringBuilder result, final IdentityValue identityValue) {
275         String moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
276                 URI.create(identityValue.getNamespace()));
277         if (moduleName != null && !moduleName.isEmpty()) {
278             result.append(moduleName);
279             result.append(":");
280         }
281         result.append(identityValue.getValue());
282     }
283
284     private void writeStringRepresentation(final JsonWriter writer, final SimpleNode<?> node, final TypeDefinition<?> baseType,
285             final Class<?> requiredType) throws IOException {
286         Object value = node.getValue();
287         logger.debug("Value of " + baseType.getQName().getNamespace() + ":" + baseType.getQName().getLocalName()
288                 + " is not instance of " + requiredType.getClass() + " but is " + node.getValue().getClass());
289         if (value == null) {
290             writer.value("");
291         } else {
292             writer.value(String.valueOf(value));
293         }
294     }
295
296     private void writeEmptyDataTypeToJson(final JsonWriter writer) throws IOException {
297         writer.beginArray();
298         writer.nullValue();
299         writer.endArray();
300     }
301
302     private void writeName(final Node<?> node, final DataSchemaNode schema, final JsonWriter writer) throws IOException {
303         String nameForOutput = node.getNodeType().getLocalName();
304         if (schema.isAugmenting()) {
305             ControllerContext contContext = ControllerContext.getInstance();
306             CharSequence moduleName = null;
307             if (mountPoint == null) {
308                 moduleName = contContext.toRestconfIdentifier(schema.getQName());
309             } else {
310                 moduleName = contContext.toRestconfIdentifier(mountPoint, schema.getQName());
311             }
312             if (moduleName != null) {
313                 nameForOutput = moduleName.toString();
314             } else {
315                 logger.info("Module '{}' was not found in schema from mount point", schema.getQName());
316             }
317         }
318         writer.name(nameForOutput);
319     }
320
321     private static final class NumberForJsonWriter extends Number {
322
323         private static final long serialVersionUID = -3147729419814417666L;
324         private final String value;
325
326         public NumberForJsonWriter(final String value) {
327             this.value = value;
328         }
329
330         @Override
331         public int intValue() {
332             throw new IllegalStateException("Should not be invoked");
333         }
334
335         @Override
336         public long longValue() {
337             throw new IllegalStateException("Should not be invoked");
338         }
339
340         @Override
341         public float floatValue() {
342             throw new IllegalStateException("Should not be invoked");
343         }
344
345         @Override
346         public double doubleValue() {
347             throw new IllegalStateException("Should not be invoked");
348         }
349
350         @Override
351         public String toString() {
352             return value;
353         }
354
355     }
356
357 }