9608d65e41ca82a13e2dada78b5ce5dfeb0728e7
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / rest / impl / JsonMapper.java
1 package org.opendaylight.controller.sal.rest.impl;
2
3 import static com.google.common.base.Preconditions.checkNotNull;
4
5 import java.io.IOException;
6 import java.util.*;
7
8 import javax.activation.UnsupportedDataTypeException;
9
10 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
11 import org.opendaylight.yangtools.yang.data.api.*;
12 import org.opendaylight.yangtools.yang.model.api.*;
13 import org.opendaylight.yangtools.yang.model.api.type.*;
14
15 import com.google.common.base.Preconditions;
16 import com.google.gson.stream.JsonWriter;
17
18 class JsonMapper {
19
20     private final Set<LeafListSchemaNode> foundLeafLists = new HashSet<>();
21     private final Set<ListSchemaNode> foundLists = new HashSet<>();
22
23     public void write(JsonWriter writer, CompositeNode data, DataNodeContainer schema) throws IOException {
24         Preconditions.checkNotNull(writer);
25         Preconditions.checkNotNull(data);
26         Preconditions.checkNotNull(schema);
27
28         writer.beginObject();
29
30         if (schema instanceof ContainerSchemaNode) {
31             writeContainer(writer, data, (ContainerSchemaNode) schema);
32         } else if (schema instanceof ListSchemaNode) {
33             writeList(writer, null, data, (ListSchemaNode) schema);
34         } else {
35             throw new UnsupportedDataTypeException(
36                     "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
37         }
38
39         writer.endObject();
40
41         foundLeafLists.clear();
42         foundLists.clear();
43     }
44
45     private void writeChildrenOfParent(JsonWriter writer, CompositeNode parent, DataNodeContainer parentSchema)
46             throws IOException {
47         checkNotNull(parent);
48         checkNotNull(parentSchema);
49
50         for (Node<?> child : parent.getChildren()) {
51             DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchema.getChildNodes());
52
53             if (childSchema == null) {
54                 throw new UnsupportedDataTypeException("Probably the data node \"" + child.getNodeType().getLocalName()
55                         + "\" is not conform to schema");
56             }
57
58             if (childSchema instanceof ContainerSchemaNode) {
59                 Preconditions.checkState(child instanceof CompositeNode,
60                         "Data representation of Container should be CompositeNode - " + child.getNodeType());
61                 writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema);
62             } else if (childSchema instanceof ListSchemaNode) {
63                 if (!foundLists.contains(childSchema)) {
64                     Preconditions.checkState(child instanceof CompositeNode,
65                             "Data representation of List should be CompositeNode - " + child.getNodeType());
66                     foundLists.add((ListSchemaNode) childSchema);
67                     writeList(writer, parent, (CompositeNode) child, (ListSchemaNode) childSchema);
68                 }
69             } else if (childSchema instanceof LeafListSchemaNode) {
70                 if (!foundLeafLists.contains(childSchema)) {
71                     Preconditions.checkState(child instanceof SimpleNode<?>,
72                             "Data representation of LeafList should be SimpleNode - " + child.getNodeType());
73                     foundLeafLists.add((LeafListSchemaNode) childSchema);
74                     writeLeafList(writer, parent, (SimpleNode<?>) child, (LeafListSchemaNode) childSchema);
75                 }
76             } else if (childSchema instanceof LeafSchemaNode) {
77                 Preconditions.checkState(child instanceof SimpleNode<?>,
78                         "Data representation of LeafList should be SimpleNode - " + child.getNodeType());
79                 writeLeaf(writer, (SimpleNode<?>) child, (LeafSchemaNode) childSchema);
80             } else {
81                 throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, "
82                         + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet.");
83             }
84         }
85
86         for (Node<?> child : parent.getChildren()) {
87             DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchema.getChildNodes());
88             if (childSchema instanceof LeafListSchemaNode) {
89                 foundLeafLists.remove((LeafListSchemaNode) childSchema);
90             } else if (childSchema instanceof ListSchemaNode) {
91                 foundLists.remove((ListSchemaNode) childSchema);
92             }
93         }
94     }
95
96     private DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
97         for (DataSchemaNode dsn : dataSchemaNode) {
98             if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
99                 return dsn;
100             } else if (dsn instanceof ChoiceNode) {
101                 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
102                     DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
103                     if (foundDsn != null) {
104                         return foundDsn;
105                     }
106                 }
107             }
108         }
109         return null;
110     }
111
112     private void writeContainer(JsonWriter writer, CompositeNode node, ContainerSchemaNode schema) throws IOException {
113         writeName(node, schema, writer);
114         writer.beginObject();
115         writeChildrenOfParent(writer, node, schema);
116         writer.endObject();
117     }
118
119     private void writeList(JsonWriter writer, CompositeNode nodeParent, CompositeNode node, ListSchemaNode schema)
120             throws IOException {
121         writeName(node, schema, writer);
122         writer.beginArray();
123
124         if (nodeParent != null) {
125             List<CompositeNode> nodeLists = nodeParent.getCompositesByName(node.getNodeType());
126             for (CompositeNode nodeList : nodeLists) {
127                 writer.beginObject();
128                 writeChildrenOfParent(writer, nodeList, schema);
129                 writer.endObject();
130             }
131         } else {
132             writer.beginObject();
133             writeChildrenOfParent(writer, node, schema);
134             writer.endObject();
135         }
136
137         writer.endArray();
138     }
139
140     private void writeLeafList(JsonWriter writer, CompositeNode nodeParent, SimpleNode<?> node,
141             LeafListSchemaNode schema) throws IOException {
142         writeName(node, schema, writer);
143         writer.beginArray();
144
145         List<SimpleNode<?>> nodeLeafLists = nodeParent.getSimpleNodesByName(node.getNodeType());
146         for (SimpleNode<?> nodeLeafList : nodeLeafLists) {
147             writeValueOfNodeByType(writer, nodeLeafList, schema.getType());
148         }
149
150         writer.endArray();
151     }
152
153     private void writeLeaf(JsonWriter writer, SimpleNode<?> node, LeafSchemaNode schema) throws IOException {
154         writeName(node, schema, writer);
155         writeValueOfNodeByType(writer, node, schema.getType());
156     }
157
158     private void writeValueOfNodeByType(JsonWriter writer, SimpleNode<?> node, TypeDefinition<?> type)
159             throws IOException {
160
161         String value = String.valueOf(node.getValue());
162         // TODO check Leafref, InstanceIdentifierTypeDefinition,
163         // IdentityrefTypeDefinition, UnionTypeDefinition
164         TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
165         if (baseType instanceof InstanceIdentifierTypeDefinition) {
166             writer.value(((InstanceIdentifierTypeDefinition) baseType).getPathStatement().toString());
167         } else if (baseType instanceof UnionTypeDefinition) {
168             processTypeIsUnionType(writer, (UnionTypeDefinition) baseType, value);
169         } else if (baseType instanceof DecimalTypeDefinition || baseType instanceof IntegerTypeDefinition
170                 || baseType instanceof UnsignedIntegerTypeDefinition) {
171             writer.value(new NumberForJsonWriter(value));
172         } else if (baseType instanceof BooleanTypeDefinition) {
173             writer.value(Boolean.parseBoolean(value));
174         } else if (baseType instanceof EmptyTypeDefinition) {
175             writeEmptyDataTypeToJson(writer);
176         } else {
177             writer.value(value.equals("null") ? "" : value);
178         }
179     }
180
181     private void processTypeIsUnionType(JsonWriter writer, UnionTypeDefinition unionType, String value)
182             throws IOException {
183         if (value == null) {
184             writeEmptyDataTypeToJson(writer);
185         } else if ((isNumber(value))
186                 && containsType(unionType, UnsignedIntegerTypeDefinition.class, IntegerTypeDefinition.class,
187                         DecimalTypeDefinition.class)) {
188             writer.value(new NumberForJsonWriter(value));
189         } else if (isBoolean(value) && containsType(unionType, BooleanTypeDefinition.class)) {
190             writer.value(Boolean.parseBoolean(value));
191         } else {
192             writer.value(value);
193         }
194     }
195
196     private boolean isBoolean(String value) {
197         if (value.equals("true") || value.equals("false")) {
198             return true;
199         }
200         return false;
201     }
202
203     private void writeEmptyDataTypeToJson(JsonWriter writer) throws IOException {
204         writer.beginArray();
205         writer.nullValue();
206         writer.endArray();
207     }
208
209     private boolean isNumber(String value) {
210         try {
211             Double.valueOf(value);
212         } catch (NumberFormatException e) {
213             return false;
214         }
215         return true;
216     }
217
218     private boolean containsType(UnionTypeDefinition unionType, Class<?>... searchedTypes) {
219         List<TypeDefinition<?>> allUnionSubtypes = resolveAllUnionSubtypesFrom(unionType);
220
221         for (TypeDefinition<?> unionSubtype : allUnionSubtypes) {
222             for (Class<?> searchedType : searchedTypes) {
223                 if (searchedType.isInstance(unionSubtype)) {
224                     return true;
225                 }
226             }
227         }
228         return false;
229     }
230
231     private List<TypeDefinition<?>> resolveAllUnionSubtypesFrom(UnionTypeDefinition inputType) {
232         List<TypeDefinition<?>> result = new ArrayList<>();
233         for (TypeDefinition<?> subtype : inputType.getTypes()) {
234             TypeDefinition<?> resolvedSubtype = subtype;
235
236             resolvedSubtype = resolveBaseTypeFrom(subtype);
237
238             if (resolvedSubtype instanceof UnionTypeDefinition) {
239                 List<TypeDefinition<?>> subtypesFromRecursion = resolveAllUnionSubtypesFrom((UnionTypeDefinition) resolvedSubtype);
240                 result.addAll(subtypesFromRecursion);
241             } else {
242                 result.add(resolvedSubtype);
243             }
244         }
245
246         return result;
247     }
248
249     private TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
250         return type.getBaseType() != null ? resolveBaseTypeFrom(type.getBaseType()) : type;
251     }
252
253     private void writeName(Node<?> node, DataSchemaNode schema, JsonWriter writer) throws IOException {
254         String nameForOutput = node.getNodeType().getLocalName();
255         if (schema.isAugmenting()) {
256             ControllerContext contContext = ControllerContext.getInstance();
257             CharSequence moduleName;
258             moduleName = contContext.toRestconfIdentifier(schema.getQName());
259             if (moduleName != null) {
260                 nameForOutput = moduleName.toString();
261             }
262         }
263         writer.name(nameForOutput);
264     }
265
266     private static final class NumberForJsonWriter extends Number {
267
268         private static final long serialVersionUID = -3147729419814417666L;
269         private final String value;
270
271         public NumberForJsonWriter(String value) {
272             this.value = value;
273         }
274
275         @Override
276         public int intValue() {
277             throw new IllegalStateException("Should not be invoked");
278         }
279
280         @Override
281         public long longValue() {
282             throw new IllegalStateException("Should not be invoked");
283         }
284
285         @Override
286         public float floatValue() {
287             throw new IllegalStateException("Should not be invoked");
288         }
289
290         @Override
291         public double doubleValue() {
292             throw new IllegalStateException("Should not be invoked");
293         }
294
295         @Override
296         public String toString() {
297             return value;
298         }
299
300     }
301
302 }