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(JsonWriter writer, CompositeNode data, DataNodeContainer schema, 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(JsonWriter writer, CompositeNode parent, DataNodeContainer parentSchema)
87 checkNotNull(parentSchema);
89 for (Node<?> child : parent.getChildren()) {
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.getChildren()) {
126 DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchema.getChildNodes());
127 if (childSchema instanceof LeafListSchemaNode) {
128 foundLeafLists.remove((LeafListSchemaNode) childSchema);
129 } else if (childSchema instanceof ListSchemaNode) {
130 foundLists.remove((ListSchemaNode) childSchema);
135 private DataSchemaNode findFirstSchemaForNode(Node<?> node, 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(JsonWriter writer, CompositeNode node, ContainerSchemaNode schema) throws IOException {
152 writeName(node, schema, writer);
153 writer.beginObject();
154 writeChildrenOfParent(writer, node, schema);
158 private void writeList(JsonWriter writer, CompositeNode nodeParent, CompositeNode node, 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(JsonWriter writer, CompositeNode nodeParent, SimpleNode<?> node,
180 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(JsonWriter writer, SimpleNode<?> node, LeafSchemaNode schema) throws IOException {
192 writeName(node, schema, writer);
193 writeValueOfNodeByType(writer, node, schema.getType(), schema);
196 private void writeValueOfNodeByType(JsonWriter writer, SimpleNode<?> node, TypeDefinition<?> type,
197 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 // TODO check InstanceIdentifierTypeDefinition
207 if (baseType instanceof IdentityrefTypeDefinition) {
208 if (node.getValue() instanceof QName) {
209 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
211 IdentityValue valueFromDTO = valueDTO.getValuesWithNamespaces().get(0);
213 if (mountPoint != null) {
214 moduleName = ControllerContext.getInstance().findModuleNameByNamespace(mountPoint,
215 URI.create(valueFromDTO.getNamespace()));
217 moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
218 URI.create(valueFromDTO.getNamespace()));
220 writer.value(moduleName + ":" + valueFromDTO.getValue());
222 writeStringRepresentation(writer, node, baseType, QName.class);
224 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
225 if (node.getValue() instanceof InstanceIdentifier) {
226 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
228 writeIdentityValuesDTOToJson(writer, valueDTO);
230 writeStringRepresentation(writer, node, baseType, InstanceIdentifier.class);
232 } else if (baseType instanceof DecimalTypeDefinition || baseType instanceof IntegerTypeDefinition
233 || baseType instanceof UnsignedIntegerTypeDefinition) {
234 writer.value(new NumberForJsonWriter((String) RestCodec.from(baseType, mountPoint).serialize(
236 } else if (baseType instanceof BooleanTypeDefinition) {
237 writer.value(Boolean.parseBoolean((String) RestCodec.from(baseType, mountPoint).serialize(node.getValue())));
238 } else if (baseType instanceof EmptyTypeDefinition) {
239 writeEmptyDataTypeToJson(writer);
241 String value = String.valueOf(RestCodec.from(baseType, mountPoint).serialize(node.getValue()));
243 value = String.valueOf(node.getValue());
245 writer.value(value.equals("null") ? "" : value);
249 private void writeIdentityValuesDTOToJson(JsonWriter writer, IdentityValuesDTO valueDTO) throws IOException {
250 StringBuilder result = new StringBuilder();
251 for (IdentityValue identityValue : valueDTO.getValuesWithNamespaces()) {
254 writeModuleNameAndIdentifier(result, identityValue);
255 if (identityValue.getPredicates() != null && !identityValue.getPredicates().isEmpty()) {
256 for (Predicate predicate : identityValue.getPredicates()) {
257 IdentityValue identityValuePredicate = predicate.getName();
259 if (identityValuePredicate == null) {
262 writeModuleNameAndIdentifier(result, identityValuePredicate);
265 result.append(predicate.getValue());
272 writer.value(result.toString());
275 private void writeModuleNameAndIdentifier(StringBuilder result, IdentityValue identityValue) {
276 String moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
277 URI.create(identityValue.getNamespace()));
278 if (moduleName != null && !moduleName.isEmpty()) {
279 result.append(moduleName);
282 result.append(identityValue.getValue());
285 private void writeStringRepresentation(JsonWriter writer, SimpleNode<?> node, TypeDefinition<?> baseType,
286 Class<?> requiredType) throws IOException {
287 Object value = node.getValue();
288 logger.debug("Value of " + baseType.getQName().getNamespace() + ":" + baseType.getQName().getLocalName()
289 + " is not instance of " + requiredType.getClass() + " but is " + node.getValue().getClass());
293 writer.value(String.valueOf(value));
297 private void writeEmptyDataTypeToJson(JsonWriter writer) throws IOException {
303 private void writeName(Node<?> node, DataSchemaNode schema, JsonWriter writer) throws IOException {
304 String nameForOutput = node.getNodeType().getLocalName();
305 if (schema.isAugmenting()) {
306 ControllerContext contContext = ControllerContext.getInstance();
307 CharSequence moduleName = null;
308 if (mountPoint == null) {
309 moduleName = contContext.toRestconfIdentifier(schema.getQName());
311 moduleName = contContext.toRestconfIdentifier(mountPoint, schema.getQName());
313 if (moduleName != null) {
314 nameForOutput = moduleName.toString();
316 logger.info("Module '{}' was not found in schema from mount point", schema.getQName());
319 writer.name(nameForOutput);
322 private static final class NumberForJsonWriter extends Number {
324 private static final long serialVersionUID = -3147729419814417666L;
325 private final String value;
327 public NumberForJsonWriter(String value) {
332 public int intValue() {
333 throw new IllegalStateException("Should not be invoked");
337 public long longValue() {
338 throw new IllegalStateException("Should not be invoked");
342 public float floatValue() {
343 throw new IllegalStateException("Should not be invoked");
347 public double doubleValue() {
348 throw new IllegalStateException("Should not be invoked");
352 public String toString() {