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