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 java.io.IOException;
14 import java.util.HashSet;
15 import java.util.List;
18 import javax.activation.UnsupportedDataTypeException;
20 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
21 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
22 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
23 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.IdentityValue;
24 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.Predicate;
25 import org.opendaylight.controller.sal.restconf.impl.RestCodec;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
28 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.Node;
30 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
31 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
32 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
33 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
35 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
50 import com.google.common.base.Preconditions;
51 import com.google.gson.stream.JsonWriter;
55 private final Set<LeafListSchemaNode> foundLeafLists = new HashSet<>();
56 private final Set<ListSchemaNode> foundLists = new HashSet<>();
57 private MountInstance mountPoint;
58 private final Logger logger = LoggerFactory.getLogger(JsonMapper.class);
60 public void write(final JsonWriter writer, final CompositeNode data, final DataNodeContainer schema, final MountInstance mountPoint)
62 Preconditions.checkNotNull(writer);
63 Preconditions.checkNotNull(data);
64 Preconditions.checkNotNull(schema);
65 this.mountPoint = mountPoint;
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.");
80 foundLeafLists.clear();
84 private void writeChildrenOfParent(final JsonWriter writer, final CompositeNode parent, final DataNodeContainer parentSchema)
87 checkNotNull(parentSchema);
89 for (Node<?> child : parent.getValue()) {
90 DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchema.getChildNodes());
92 if (childSchema == null) {
93 throw new UnsupportedDataTypeException("Probably the data node \"" + child.getNodeType().getLocalName()
94 + "\" is not conform to schema");
97 if (childSchema instanceof ContainerSchemaNode) {
98 Preconditions.checkState(child instanceof CompositeNode,
99 "Data representation of Container should be CompositeNode - " + child.getNodeType());
100 writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema);
101 } else if (childSchema instanceof ListSchemaNode) {
102 if (!foundLists.contains(childSchema)) {
103 Preconditions.checkState(child instanceof CompositeNode,
104 "Data representation of List should be CompositeNode - " + child.getNodeType());
105 foundLists.add((ListSchemaNode) childSchema);
106 writeList(writer, parent, (CompositeNode) child, (ListSchemaNode) childSchema);
108 } else if (childSchema instanceof LeafListSchemaNode) {
109 if (!foundLeafLists.contains(childSchema)) {
110 Preconditions.checkState(child instanceof SimpleNode<?>,
111 "Data representation of LeafList should be SimpleNode - " + child.getNodeType());
112 foundLeafLists.add((LeafListSchemaNode) childSchema);
113 writeLeafList(writer, parent, (SimpleNode<?>) child, (LeafListSchemaNode) childSchema);
115 } else if (childSchema instanceof LeafSchemaNode) {
116 Preconditions.checkState(child instanceof SimpleNode<?>,
117 "Data representation of LeafList should be SimpleNode - " + child.getNodeType());
118 writeLeaf(writer, (SimpleNode<?>) child, (LeafSchemaNode) childSchema);
120 throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, "
121 + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet.");
125 for (Node<?> child : parent.getValue()) {
126 DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchema.getChildNodes());
127 if (childSchema instanceof LeafListSchemaNode) {
128 foundLeafLists.remove(childSchema);
129 } else if (childSchema instanceof ListSchemaNode) {
130 foundLists.remove(childSchema);
135 private DataSchemaNode findFirstSchemaForNode(final Node<?> node, final Set<DataSchemaNode> dataSchemaNode) {
136 for (DataSchemaNode dsn : dataSchemaNode) {
137 if (node.getNodeType().equals(dsn.getQName())) {
139 } else if (dsn instanceof ChoiceNode) {
140 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
141 DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
142 if (foundDsn != null) {
151 private void writeContainer(final JsonWriter writer, final CompositeNode node, final ContainerSchemaNode schema) throws IOException {
152 writeName(node, schema, writer);
153 writer.beginObject();
154 writeChildrenOfParent(writer, node, schema);
158 private void writeList(final JsonWriter writer, final CompositeNode nodeParent, final CompositeNode node, final ListSchemaNode schema)
160 writeName(node, schema, writer);
163 if (nodeParent != null) {
164 List<CompositeNode> nodeLists = nodeParent.getCompositesByName(node.getNodeType());
165 for (CompositeNode nodeList : nodeLists) {
166 writer.beginObject();
167 writeChildrenOfParent(writer, nodeList, schema);
171 writer.beginObject();
172 writeChildrenOfParent(writer, node, schema);
179 private void writeLeafList(final JsonWriter writer, final CompositeNode nodeParent, final SimpleNode<?> node,
180 final LeafListSchemaNode schema) throws IOException {
181 writeName(node, schema, writer);
184 List<SimpleNode<?>> nodeLeafLists = nodeParent.getSimpleNodesByName(node.getNodeType());
185 for (SimpleNode<?> nodeLeafList : nodeLeafLists) {
186 writeValueOfNodeByType(writer, nodeLeafList, schema.getType(), schema);
191 private void writeLeaf(final JsonWriter writer, final SimpleNode<?> node, final LeafSchemaNode schema) throws IOException {
192 writeName(node, schema, writer);
193 writeValueOfNodeByType(writer, node, schema.getType(), schema);
196 private void writeValueOfNodeByType(final JsonWriter writer, final SimpleNode<?> node, final TypeDefinition<?> type,
197 final DataSchemaNode schema) throws IOException {
199 TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(type);
201 if (node.getValue() == null && !(baseType instanceof EmptyTypeDefinition)) {
202 logger.debug("While generationg JSON output null value was found for type "
203 + baseType.getClass().getSimpleName() + ".");
206 if (baseType instanceof IdentityrefTypeDefinition) {
207 if (node.getValue() instanceof QName) {
208 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
210 IdentityValue valueFromDTO = valueDTO.getValuesWithNamespaces().get(0);
212 if (mountPoint != null) {
213 moduleName = ControllerContext.getInstance().findModuleNameByNamespace(mountPoint,
214 URI.create(valueFromDTO.getNamespace()));
216 moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
217 URI.create(valueFromDTO.getNamespace()));
219 writer.value(moduleName + ":" + valueFromDTO.getValue());
221 writeStringRepresentation(writer, node, baseType, QName.class);
223 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
224 if (node.getValue() instanceof InstanceIdentifier) {
225 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
227 writeIdentityValuesDTOToJson(writer, valueDTO);
229 writeStringRepresentation(writer, node, baseType, InstanceIdentifier.class);
231 } else if (baseType instanceof DecimalTypeDefinition || baseType instanceof IntegerTypeDefinition
232 || baseType instanceof UnsignedIntegerTypeDefinition) {
233 writer.value(new NumberForJsonWriter((String) RestCodec.from(baseType, mountPoint).serialize(
235 } else if (baseType instanceof BooleanTypeDefinition) {
236 writer.value(Boolean.parseBoolean((String) RestCodec.from(baseType, mountPoint).serialize(node.getValue())));
237 } else if (baseType instanceof EmptyTypeDefinition) {
238 writeEmptyDataTypeToJson(writer);
240 String value = String.valueOf(RestCodec.from(baseType, mountPoint).serialize(node.getValue()));
242 value = String.valueOf(node.getValue());
244 writer.value(value.equals("null") ? "" : value);
248 private void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO) throws IOException {
249 StringBuilder result = new StringBuilder();
250 for (IdentityValue identityValue : valueDTO.getValuesWithNamespaces()) {
253 writeModuleNameAndIdentifier(result, identityValue);
254 if (identityValue.getPredicates() != null && !identityValue.getPredicates().isEmpty()) {
255 for (Predicate predicate : identityValue.getPredicates()) {
256 IdentityValue identityValuePredicate = predicate.getName();
258 if (identityValuePredicate == null) {
261 writeModuleNameAndIdentifier(result, identityValuePredicate);
264 result.append(predicate.getValue());
271 writer.value(result.toString());
274 private void writeModuleNameAndIdentifier(final StringBuilder result, final IdentityValue identityValue) {
275 String moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
276 URI.create(identityValue.getNamespace()));
277 if (moduleName != null && !moduleName.isEmpty()) {
278 result.append(moduleName);
281 result.append(identityValue.getValue());
284 private void writeStringRepresentation(final JsonWriter writer, final SimpleNode<?> node, final TypeDefinition<?> baseType,
285 final Class<?> requiredType) throws IOException {
286 Object value = node.getValue();
287 logger.debug("Value of " + baseType.getQName().getNamespace() + ":" + baseType.getQName().getLocalName()
288 + " is not instance of " + requiredType.getClass() + " but is " + node.getValue().getClass());
292 writer.value(String.valueOf(value));
296 private void writeEmptyDataTypeToJson(final JsonWriter writer) throws IOException {
302 private void writeName(final Node<?> node, final DataSchemaNode schema, final JsonWriter writer) throws IOException {
303 String nameForOutput = node.getNodeType().getLocalName();
304 if (schema.isAugmenting()) {
305 ControllerContext contContext = ControllerContext.getInstance();
306 CharSequence moduleName = null;
307 if (mountPoint == null) {
308 moduleName = contContext.toRestconfIdentifier(schema.getQName());
310 moduleName = contContext.toRestconfIdentifier(mountPoint, schema.getQName());
312 if (moduleName != null) {
313 nameForOutput = moduleName.toString();
315 logger.info("Module '{}' was not found in schema from mount point", schema.getQName());
318 writer.name(nameForOutput);
321 private static final class NumberForJsonWriter extends Number {
323 private static final long serialVersionUID = -3147729419814417666L;
324 private final String value;
326 public NumberForJsonWriter(final String value) {
331 public int intValue() {
332 throw new IllegalStateException("Should not be invoked");
336 public long longValue() {
337 throw new IllegalStateException("Should not be invoked");
341 public float floatValue() {
342 throw new IllegalStateException("Should not be invoked");
346 public double doubleValue() {
347 throw new IllegalStateException("Should not be invoked");
351 public String toString() {