2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.sal.rest.impl;
10 import static com.google.common.base.Preconditions.checkNotNull;
12 import com.google.common.base.Preconditions;
13 import com.google.gson.stream.JsonWriter;
14 import java.io.IOException;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.HashSet;
19 import java.util.List;
21 import javax.activation.UnsupportedDataTypeException;
22 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
23 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
24 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
25 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.IdentityValue;
26 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.Predicate;
27 import org.opendaylight.controller.sal.restconf.impl.RestCodec;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.Node;
32 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
33 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
35 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
36 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
38 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 private static final Logger LOG = LoggerFactory.getLogger(JsonMapper.class);
55 private final DOMMountPoint mountPoint;
57 public JsonMapper(final DOMMountPoint mountPoint) {
58 this.mountPoint = mountPoint;
61 public void write(final JsonWriter writer, final CompositeNode data, final DataNodeContainer schema)
63 Preconditions.checkNotNull(writer);
64 Preconditions.checkNotNull(data);
65 Preconditions.checkNotNull(schema);
69 if (schema instanceof ContainerSchemaNode) {
70 writeContainer(writer, data, (ContainerSchemaNode) schema);
71 } else if (schema instanceof ListSchemaNode) {
72 writeList(writer, null, data, (ListSchemaNode) schema);
74 throw new UnsupportedDataTypeException(
75 "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
81 private void writeChildrenOfParent(final JsonWriter writer, final CompositeNode parent,
82 final DataNodeContainer parentSchema) throws IOException {
85 final Set<QName> foundLists = new HashSet<>();
87 Collection<DataSchemaNode> parentSchemaChildNodes = parentSchema == null ? Collections.<DataSchemaNode> emptySet()
88 : parentSchema.getChildNodes();
90 for (Node<?> child : parent.getValue()) {
91 DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes);
93 if (childSchema == null) {
94 // Node may not conform to schema or allows "anyxml" - we'll process it.
96 LOG.debug("No schema found for data node \"{}\"", child.getNodeType());
98 if (!foundLists.contains(child.getNodeType())) {
99 handleNoSchemaFound(writer, child, parent);
101 // Since we don't have a schema, we don't know which nodes are supposed to be
102 // lists so treat every one as a potential list to avoid outputting duplicates.
104 foundLists.add(child.getNodeType());
106 } else if (childSchema instanceof ContainerSchemaNode) {
107 Preconditions.checkState(child instanceof CompositeNode,
108 "Data representation of Container should be CompositeNode - %s", child.getNodeType());
109 writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema);
110 } else if (childSchema instanceof ListSchemaNode) {
111 if (!foundLists.contains(child.getNodeType())) {
112 Preconditions.checkState(child instanceof CompositeNode,
113 "Data representation of List should be CompositeNode - %s", child.getNodeType());
114 foundLists.add(child.getNodeType());
115 writeList(writer, parent, (CompositeNode) child, (ListSchemaNode) childSchema);
117 } else if (childSchema instanceof LeafListSchemaNode) {
118 if (!foundLists.contains(child.getNodeType())) {
119 Preconditions.checkState(child instanceof SimpleNode<?>,
120 "Data representation of LeafList should be SimpleNode - %s", child.getNodeType());
121 foundLists.add(child.getNodeType());
122 writeLeafList(writer, parent, (SimpleNode<?>) child, (LeafListSchemaNode) childSchema);
124 } else if (childSchema instanceof LeafSchemaNode) {
125 Preconditions.checkState(child instanceof SimpleNode<?>,
126 "Data representation of LeafList should be SimpleNode - %s", child.getNodeType());
127 writeLeaf(writer, (SimpleNode<?>) child, (LeafSchemaNode) childSchema);
128 } else if (childSchema instanceof AnyXmlSchemaNode) {
129 if (child instanceof CompositeNode) {
130 writeContainer(writer, (CompositeNode) child, null);
132 handleNoSchemaFound(writer, child, parent);
135 throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, "
136 + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet.");
141 private static void writeValue(final JsonWriter writer, final Object value) throws IOException {
142 writer.value(value == null ? "" : String.valueOf(value));
145 private void handleNoSchemaFound(final JsonWriter writer, final Node<?> node, final CompositeNode parent)
147 if (node instanceof SimpleNode<?>) {
148 List<SimpleNode<?>> nodeLeafList = parent.getSimpleNodesByName(node.getNodeType());
149 if (nodeLeafList.size() == 1) {
150 writeName(node, null, writer);
151 writeValue(writer, node.getValue());
152 } else { // more than 1, write as a json array
153 writeName(node, null, writer);
155 for (SimpleNode<?> leafNode : nodeLeafList) {
156 writeValue(writer, leafNode.getValue());
161 } else { // CompositeNode
162 Preconditions.checkState(node instanceof CompositeNode,
163 "Data representation of Container should be CompositeNode - %s", node.getNodeType());
165 List<CompositeNode> nodeList = parent.getCompositesByName(node.getNodeType());
166 if (nodeList.size() == 1) {
167 writeContainer(writer, (CompositeNode) node, null);
168 } else { // more than 1, write as a json array
169 writeList(writer, parent, (CompositeNode) node, null);
174 private static DataSchemaNode findFirstSchemaForNode(final Node<?> node, final Iterable<DataSchemaNode> dataSchemaNode) {
175 for (DataSchemaNode dsn : dataSchemaNode) {
176 if (node.getNodeType().equals(dsn.getQName())) {
179 if (dsn instanceof ChoiceNode) {
180 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
181 DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
182 if (foundDsn != null) {
191 private void writeContainer(final JsonWriter writer, final CompositeNode node, final ContainerSchemaNode schema)
193 writeName(node, schema, writer);
194 writer.beginObject();
195 writeChildrenOfParent(writer, node, schema);
199 private void writeList(final JsonWriter writer, final CompositeNode nodeParent, final CompositeNode node,
200 final ListSchemaNode schema) throws IOException {
201 writeName(node, schema, writer);
204 if (nodeParent != null) {
205 List<CompositeNode> nodeLists = nodeParent.getCompositesByName(node.getNodeType());
206 for (CompositeNode nodeList : nodeLists) {
207 writer.beginObject();
208 writeChildrenOfParent(writer, nodeList, schema);
212 writer.beginObject();
213 writeChildrenOfParent(writer, node, schema);
220 private void writeLeafList(final JsonWriter writer, final CompositeNode nodeParent, final SimpleNode<?> node,
221 final LeafListSchemaNode schema) throws IOException {
222 writeName(node, schema, writer);
225 List<SimpleNode<?>> nodeLeafLists = nodeParent.getSimpleNodesByName(node.getNodeType());
226 for (SimpleNode<?> nodeLeafList : nodeLeafLists) {
227 writeValueOfNodeByType(writer, nodeLeafList, schema.getType(), schema);
232 private void writeLeaf(final JsonWriter writer, final SimpleNode<?> node, final LeafSchemaNode schema)
234 writeName(node, schema, writer);
235 writeValueOfNodeByType(writer, node, schema.getType(), schema);
238 private void writeValueOfNodeByType(final JsonWriter writer, final SimpleNode<?> node,
239 final TypeDefinition<?> type, final DataSchemaNode schema) throws IOException {
241 TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(type);
243 if (node.getValue() == null && !(baseType instanceof EmptyTypeDefinition)) {
244 LOG.debug("While generationg JSON output null value was found for type {}.", baseType.getClass()
248 if (baseType instanceof IdentityrefTypeDefinition) {
249 if (node.getValue() instanceof QName) {
250 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
252 IdentityValue valueFromDTO = valueDTO.getValuesWithNamespaces().get(0);
254 if (mountPoint != null) {
255 moduleName = ControllerContext.getInstance().findModuleNameByNamespace(mountPoint,
256 URI.create(valueFromDTO.getNamespace()));
258 moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
259 URI.create(valueFromDTO.getNamespace()));
261 writer.value(moduleName + ":" + valueFromDTO.getValue());
263 writeStringRepresentation(writer, node, baseType, QName.class);
265 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
266 if (node.getValue() instanceof YangInstanceIdentifier) {
267 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
269 writeIdentityValuesDTOToJson(writer, valueDTO);
271 writeStringRepresentation(writer, node, baseType, YangInstanceIdentifier.class);
273 } else if (baseType instanceof DecimalTypeDefinition || baseType instanceof IntegerTypeDefinition
274 || baseType instanceof UnsignedIntegerTypeDefinition) {
275 writer.value(new NumberForJsonWriter((String) RestCodec.from(baseType, mountPoint).serialize(
277 } else if (baseType instanceof BooleanTypeDefinition) {
278 writer.value(Boolean.parseBoolean((String) RestCodec.from(baseType, mountPoint).serialize(node.getValue())));
279 } else if (baseType instanceof EmptyTypeDefinition) {
280 writeEmptyDataTypeToJson(writer);
282 String value = String.valueOf(RestCodec.from(baseType, mountPoint).serialize(node.getValue()));
284 value = String.valueOf(node.getValue());
286 writer.value(value.equals("null") ? "" : value);
290 private static void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO)
292 StringBuilder result = new StringBuilder();
293 for (IdentityValue identityValue : valueDTO.getValuesWithNamespaces()) {
296 writeModuleNameAndIdentifier(result, identityValue);
297 if (identityValue.getPredicates() != null && !identityValue.getPredicates().isEmpty()) {
298 for (Predicate predicate : identityValue.getPredicates()) {
299 IdentityValue identityValuePredicate = predicate.getName();
301 if (identityValuePredicate == null) {
304 writeModuleNameAndIdentifier(result, identityValuePredicate);
307 result.append(predicate.getValue());
313 writer.value(result.toString());
316 private static void writeModuleNameAndIdentifier(final StringBuilder result, final IdentityValue identityValue) {
317 String moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
318 URI.create(identityValue.getNamespace()));
319 if (moduleName != null && !moduleName.isEmpty()) {
320 result.append(moduleName);
323 result.append(identityValue.getValue());
326 private static void writeStringRepresentation(final JsonWriter writer, final SimpleNode<?> node,
327 final TypeDefinition<?> baseType, final Class<?> requiredType) throws IOException {
328 Object value = node.getValue();
329 LOG.debug("Value of {}:{} is not instance of {} but is {}", baseType.getQName().getNamespace(), baseType
330 .getQName().getLocalName(), requiredType.getClass(), node.getValue().getClass());
334 writer.value(String.valueOf(value));
338 private void writeEmptyDataTypeToJson(final JsonWriter writer) throws IOException {
344 private void writeName(final Node<?> node, final DataSchemaNode schema, final JsonWriter writer) throws IOException {
345 String nameForOutput = node.getNodeType().getLocalName();
346 if (schema != null && schema.isAugmenting()) {
347 ControllerContext contContext = ControllerContext.getInstance();
348 CharSequence moduleName = null;
349 if (mountPoint == null) {
350 moduleName = contContext.toRestconfIdentifier(schema.getQName());
352 moduleName = contContext.toRestconfIdentifier(mountPoint, schema.getQName());
354 if (moduleName != null) {
355 nameForOutput = moduleName.toString();
357 LOG.info("Module '{}' was not found in schema from mount point", schema.getQName());
360 writer.name(nameForOutput);
363 private static final class NumberForJsonWriter extends Number {
365 private static final long serialVersionUID = -3147729419814417666L;
366 private final String value;
368 public NumberForJsonWriter(final String value) {
373 public int intValue() {
374 throw new IllegalStateException("Should not be invoked");
378 public long longValue() {
379 throw new IllegalStateException("Should not be invoked");
383 public float floatValue() {
384 throw new IllegalStateException("Should not be invoked");
388 public double doubleValue() {
389 throw new IllegalStateException("Should not be invoked");
393 public String toString() {