1 package org.opendaylight.controller.sal.rest.impl;
3 import static com.google.common.base.Preconditions.checkNotNull;
5 import java.io.IOException;
7 import java.util.ArrayList;
8 import java.util.HashSet;
12 import javax.activation.UnsupportedDataTypeException;
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;
43 import com.google.common.base.Preconditions;
44 import com.google.gson.stream.JsonWriter;
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);
52 public void write(JsonWriter writer, CompositeNode data, DataNodeContainer schema) throws IOException {
53 Preconditions.checkNotNull(writer);
54 Preconditions.checkNotNull(data);
55 Preconditions.checkNotNull(schema);
59 if (schema instanceof ContainerSchemaNode) {
60 writeContainer(writer, data, (ContainerSchemaNode) schema);
61 } else if (schema instanceof ListSchemaNode) {
62 writeList(writer, null, data, (ListSchemaNode) schema);
64 throw new UnsupportedDataTypeException(
65 "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
70 foundLeafLists.clear();
74 private void writeChildrenOfParent(JsonWriter writer, CompositeNode parent, DataNodeContainer parentSchema)
77 checkNotNull(parentSchema);
79 for (Node<?> child : parent.getChildren()) {
80 DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchema.getChildNodes());
82 if (childSchema == null) {
83 throw new UnsupportedDataTypeException("Probably the data node \"" + child.getNodeType().getLocalName()
84 + "\" is not conform to schema");
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);
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);
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);
110 throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, "
111 + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet.");
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);
125 private DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
126 for (DataSchemaNode dsn : dataSchemaNode) {
127 if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
129 } else if (dsn instanceof ChoiceNode) {
130 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
131 DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
132 if (foundDsn != null) {
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);
148 private void writeList(JsonWriter writer, CompositeNode nodeParent, CompositeNode node, ListSchemaNode schema)
150 writeName(node, schema, writer);
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);
161 writer.beginObject();
162 writeChildrenOfParent(writer, node, schema);
169 private void writeLeafList(JsonWriter writer, CompositeNode nodeParent, SimpleNode<?> node,
170 LeafListSchemaNode schema) throws IOException {
171 writeName(node, schema, writer);
174 List<SimpleNode<?>> nodeLeafLists = nodeParent.getSimpleNodesByName(node.getNodeType());
175 for (SimpleNode<?> nodeLeafList : nodeLeafLists) {
176 writeValueOfNodeByType(writer, nodeLeafList, schema.getType(), schema);
181 private void writeLeaf(JsonWriter writer, SimpleNode<?> node, LeafSchemaNode schema) throws IOException {
182 writeName(node, schema, writer);
183 writeValueOfNodeByType(writer, node, schema.getType(), schema);
186 private void writeValueOfNodeByType(JsonWriter writer, SimpleNode<?> node, TypeDefinition<?> type,
187 DataSchemaNode schema) throws IOException {
189 String value = String.valueOf(node.getValue());
190 TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
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());
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()));
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);
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);
224 writer.value(value.equals("null") ? "" : value);
228 private void processTypeIsUnionType(JsonWriter writer, UnionTypeDefinition unionType, String value)
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));
243 private boolean isBoolean(String value) {
244 if (value.equals("true") || value.equals("false")) {
250 private void writeEmptyDataTypeToJson(JsonWriter writer) throws IOException {
256 private boolean isNumber(String value) {
258 Double.valueOf(value);
259 } catch (NumberFormatException e) {
265 private boolean containsType(UnionTypeDefinition unionType, Class<?>... searchedTypes) {
266 List<TypeDefinition<?>> allUnionSubtypes = resolveAllUnionSubtypesFrom(unionType);
268 for (TypeDefinition<?> unionSubtype : allUnionSubtypes) {
269 for (Class<?> searchedType : searchedTypes) {
270 if (searchedType.isInstance(unionSubtype)) {
278 private List<TypeDefinition<?>> resolveAllUnionSubtypesFrom(UnionTypeDefinition inputType) {
279 List<TypeDefinition<?>> result = new ArrayList<>();
280 for (TypeDefinition<?> subtype : inputType.getTypes()) {
281 TypeDefinition<?> resolvedSubtype = subtype;
283 resolvedSubtype = resolveBaseTypeFrom(subtype);
285 if (resolvedSubtype instanceof UnionTypeDefinition) {
286 List<TypeDefinition<?>> subtypesFromRecursion = resolveAllUnionSubtypesFrom((UnionTypeDefinition) resolvedSubtype);
287 result.addAll(subtypesFromRecursion);
289 result.add(resolvedSubtype);
296 private TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
297 return type.getBaseType() != null ? resolveBaseTypeFrom(type.getBaseType()) : type;
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();
310 writer.name(nameForOutput);
313 private static final class NumberForJsonWriter extends Number {
315 private static final long serialVersionUID = -3147729419814417666L;
316 private final String value;
318 public NumberForJsonWriter(String value) {
323 public int intValue() {
324 throw new IllegalStateException("Should not be invoked");
328 public long longValue() {
329 throw new IllegalStateException("Should not be invoked");
333 public float floatValue() {
334 throw new IllegalStateException("Should not be invoked");
338 public double doubleValue() {
339 throw new IllegalStateException("Should not be invoked");
343 public String toString() {