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.HashSet;
11 import javax.activation.UnsupportedDataTypeException;
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;
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 MountInstance mountPoint;
51 private final Logger logger = LoggerFactory.getLogger(JsonMapper.class);
53 public void write(JsonWriter writer, CompositeNode data, DataNodeContainer schema, MountInstance mountPoint)
55 Preconditions.checkNotNull(writer);
56 Preconditions.checkNotNull(data);
57 Preconditions.checkNotNull(schema);
58 this.mountPoint = mountPoint;
62 if (schema instanceof ContainerSchemaNode) {
63 writeContainer(writer, data, (ContainerSchemaNode) schema);
64 } else if (schema instanceof ListSchemaNode) {
65 writeList(writer, null, data, (ListSchemaNode) schema);
67 throw new UnsupportedDataTypeException(
68 "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
73 foundLeafLists.clear();
77 private void writeChildrenOfParent(JsonWriter writer, CompositeNode parent, DataNodeContainer parentSchema)
80 checkNotNull(parentSchema);
82 for (Node<?> child : parent.getChildren()) {
83 DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchema.getChildNodes());
85 if (childSchema == null) {
86 throw new UnsupportedDataTypeException("Probably the data node \"" + child.getNodeType().getLocalName()
87 + "\" is not conform to schema");
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);
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);
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);
113 throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, "
114 + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet.");
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);
128 private DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
129 for (DataSchemaNode dsn : dataSchemaNode) {
130 if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
132 } else if (dsn instanceof ChoiceNode) {
133 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
134 DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
135 if (foundDsn != null) {
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);
151 private void writeList(JsonWriter writer, CompositeNode nodeParent, CompositeNode node, ListSchemaNode schema)
153 writeName(node, schema, writer);
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);
164 writer.beginObject();
165 writeChildrenOfParent(writer, node, schema);
172 private void writeLeafList(JsonWriter writer, CompositeNode nodeParent, SimpleNode<?> node,
173 LeafListSchemaNode schema) throws IOException {
174 writeName(node, schema, writer);
177 List<SimpleNode<?>> nodeLeafLists = nodeParent.getSimpleNodesByName(node.getNodeType());
178 for (SimpleNode<?> nodeLeafList : nodeLeafLists) {
179 writeValueOfNodeByType(writer, nodeLeafList, schema.getType(), schema);
184 private void writeLeaf(JsonWriter writer, SimpleNode<?> node, LeafSchemaNode schema) throws IOException {
185 writeName(node, schema, writer);
186 writeValueOfNodeByType(writer, node, schema.getType(), schema);
189 private void writeValueOfNodeByType(JsonWriter writer, SimpleNode<?> node, TypeDefinition<?> type,
190 DataSchemaNode schema) throws IOException {
192 TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(type);
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() + ".");
199 // TODO check InstanceIdentifierTypeDefinition
200 if (baseType instanceof IdentityrefTypeDefinition) {
201 if (node.getValue() instanceof QName) {
202 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
204 IdentityValue valueFromDTO = valueDTO.getValuesWithNamespaces().get(0);
206 if (mountPoint != null) {
207 moduleName = ControllerContext.getInstance().findModuleNameByNamespace(mountPoint,
208 URI.create(valueFromDTO.getNamespace()));
210 moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
211 URI.create(valueFromDTO.getNamespace()));
213 writer.value(moduleName + ":" + valueFromDTO.getValue());
215 writeStringRepresentation(writer, node, baseType, QName.class);
217 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
218 if (node.getValue() instanceof InstanceIdentifier) {
219 IdentityValuesDTO valueDTO = (IdentityValuesDTO) RestCodec.from(baseType, mountPoint).serialize(
221 writeIdentityValuesDTOToJson(writer, valueDTO);
223 writeStringRepresentation(writer, node, baseType, InstanceIdentifier.class);
225 } else if (baseType instanceof DecimalTypeDefinition || baseType instanceof IntegerTypeDefinition
226 || baseType instanceof UnsignedIntegerTypeDefinition) {
227 writer.value(new NumberForJsonWriter((String) RestCodec.from(baseType, mountPoint).serialize(
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);
234 String value = String.valueOf(RestCodec.from(baseType, mountPoint).serialize(node.getValue()));
236 value = String.valueOf(node.getValue());
238 writer.value(value.equals("null") ? "" : value);
242 private void writeIdentityValuesDTOToJson(JsonWriter writer, IdentityValuesDTO valueDTO) throws IOException {
243 StringBuilder result = new StringBuilder();
244 for (IdentityValue identityValue : valueDTO.getValuesWithNamespaces()) {
247 writeModuleNameAndIdentifier(result, identityValue);
248 if (identityValue.getPredicates() != null) {
249 for (Predicate predicate : identityValue.getPredicates()) {
250 IdentityValue identityValuePredicate = predicate.getName();
252 writeModuleNameAndIdentifier(result, identityValuePredicate);
253 result.append("=\"");
254 result.append(predicate.getValue());
261 writer.value(result.toString());
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);
271 result.append(identityValue.getValue());
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());
282 writer.value(String.valueOf(value));
286 private void writeEmptyDataTypeToJson(JsonWriter writer) throws IOException {
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();
302 writer.name(nameForOutput);
305 private static final class NumberForJsonWriter extends Number {
307 private static final long serialVersionUID = -3147729419814417666L;
308 private final String value;
310 public NumberForJsonWriter(String value) {
315 public int intValue() {
316 throw new IllegalStateException("Should not be invoked");
320 public long longValue() {
321 throw new IllegalStateException("Should not be invoked");
325 public float floatValue() {
326 throw new IllegalStateException("Should not be invoked");
330 public double doubleValue() {
331 throw new IllegalStateException("Should not be invoked");
335 public String toString() {