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