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