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