Merge "Complete implementation of DataChangeListenerProxy"
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / rest / impl / JsonReader.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.sal.rest.impl;
9
10 import com.google.common.base.Splitter;
11 import com.google.common.collect.Iterators;
12 import com.google.gson.JsonElement;
13 import com.google.gson.JsonObject;
14 import com.google.gson.JsonParser;
15 import com.google.gson.JsonPrimitive;
16
17 import java.io.InputStream;
18 import java.io.InputStreamReader;
19 import java.net.URI;
20 import java.util.Iterator;
21 import java.util.Map.Entry;
22 import java.util.Set;
23
24 import org.opendaylight.controller.sal.rest.impl.RestUtil.PrefixMapingFromJson;
25 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
26 import org.opendaylight.controller.sal.restconf.impl.EmptyNodeWrapper;
27 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
28 import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 final class JsonReader {
33     private static final Logger LOG = LoggerFactory.getLogger(JsonReader.class);
34     private static final Splitter COLON_SPLITTER = Splitter.on(':');
35
36     private JsonReader() {
37
38     }
39
40     public static CompositeNodeWrapper read(final InputStream entityStream) throws UnsupportedFormatException {
41         JsonParser parser = new JsonParser();
42
43         JsonElement rootElement = parser.parse(new InputStreamReader(entityStream));
44         if (rootElement.isJsonNull()) {
45             //no content, so return null to indicate no input
46             return null;
47         }
48
49         if (!rootElement.isJsonObject()) {
50             throw new UnsupportedFormatException("Root element of Json has to be Object");
51         }
52
53         Set<Entry<String, JsonElement>> entrySetsOfRootJsonObject = rootElement.getAsJsonObject().entrySet();
54         if (entrySetsOfRootJsonObject.size() != 1) {
55             throw new UnsupportedFormatException("Json Object should contain one element");
56         }
57
58         Entry<String, JsonElement> childEntry = entrySetsOfRootJsonObject.iterator().next();
59         String firstElementName = childEntry.getKey();
60         JsonElement firstElementType = childEntry.getValue();
61         if (firstElementType.isJsonObject()) {
62             // container in yang
63             return createStructureWithRoot(firstElementName, firstElementType.getAsJsonObject());
64         }
65         if (firstElementType.isJsonArray()) {
66             // list in yang
67             if (firstElementType.getAsJsonArray().size() == 1) {
68                 JsonElement firstElementInArray = firstElementType.getAsJsonArray().get(0);
69                 if (firstElementInArray.isJsonObject()) {
70                     return createStructureWithRoot(firstElementName, firstElementInArray.getAsJsonObject());
71                 }
72                 throw new UnsupportedFormatException(
73                         "Array as the first element in Json Object can have only Object element");
74             }
75         }
76         throw new UnsupportedFormatException(
77                 "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet.");
78     }
79
80     private static CompositeNodeWrapper createStructureWithRoot(final String rootObjectName, final JsonObject rootObject) {
81         CompositeNodeWrapper firstNode = new CompositeNodeWrapper(getNamespaceFor(rootObjectName),
82                 getLocalNameFor(rootObjectName));
83         for (Entry<String, JsonElement> childOfFirstNode : rootObject.entrySet()) {
84             addChildToParent(childOfFirstNode.getKey(), childOfFirstNode.getValue(), firstNode);
85         }
86         return firstNode;
87     }
88
89     private static void addChildToParent(final String childName, final JsonElement childType, final CompositeNodeWrapper parent) {
90         if (childType.isJsonObject()) {
91             CompositeNodeWrapper child = new CompositeNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName));
92             parent.addValue(child);
93             for (Entry<String, JsonElement> childOfChild : childType.getAsJsonObject().entrySet()) {
94                 addChildToParent(childOfChild.getKey(), childOfChild.getValue(), child);
95             }
96         } else if (childType.isJsonArray()) {
97             if (childType.getAsJsonArray().size() == 1 && childType.getAsJsonArray().get(0).isJsonNull()) {
98                 parent.addValue(new EmptyNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName)));
99             } else {
100                 for (JsonElement childOfChildType : childType.getAsJsonArray()) {
101                     addChildToParent(childName, childOfChildType, parent);
102                 }
103             }
104         } else if (childType.isJsonPrimitive()) {
105             JsonPrimitive childPrimitive = childType.getAsJsonPrimitive();
106             String value = childPrimitive.getAsString().trim();
107             parent.addValue(new SimpleNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName),
108                     resolveValueOfElement(value)));
109         } else {
110             LOG.debug("Ignoring unhandled child type {}", childType);
111         }
112     }
113
114     private static URI getNamespaceFor(final String jsonElementName) {
115         final Iterator<String> it = COLON_SPLITTER.split(jsonElementName).iterator();
116
117         // The string needs to me in form "moduleName:localName"
118         if (it.hasNext()) {
119             final String maybeURI = it.next();
120             if (Iterators.size(it) == 1) {
121                 return URI.create(maybeURI);
122             }
123         }
124
125         return null;
126     }
127
128     private static String getLocalNameFor(final String jsonElementName) {
129         final Iterator<String> it = COLON_SPLITTER.split(jsonElementName).iterator();
130
131         // The string needs to me in form "moduleName:localName"
132         final String ret = Iterators.get(it, 1, null);
133         return ret != null && !it.hasNext() ? ret : jsonElementName;
134     }
135
136     private static Object resolveValueOfElement(final String value) {
137         // it could be instance-identifier Built-In Type
138         if (!value.isEmpty() && value.charAt(0) == '/') {
139             IdentityValuesDTO resolvedValue = RestUtil.asInstanceIdentifier(value, new PrefixMapingFromJson());
140             if (resolvedValue != null) {
141                 return resolvedValue;
142             }
143         }
144
145         // it could be identityref Built-In Type
146         URI namespace = getNamespaceFor(value);
147         if (namespace != null) {
148             return new IdentityValuesDTO(namespace.toString(), getLocalNameFor(value), null,value);
149         }
150         // it is not "prefix:value" but just "value"
151         return value;
152     }
153
154 }