Fix various warnings
[yangtools.git] / restconf / restconf-util / src / main / java / org / opendaylight / yangtools / restconf / utils / RestconfUtils.java
1 /*
2  * Copyright (c) 2013 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.yangtools.restconf.utils;
9
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.net.URI;
13 import java.net.URLEncoder;
14 import java.util.AbstractMap.SimpleEntry;
15 import java.util.Arrays;
16 import java.util.Date;
17 import java.util.HashSet;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Map.Entry;
21 import java.util.Set;
22
23 import javax.xml.parsers.DocumentBuilder;
24 import javax.xml.parsers.DocumentBuilderFactory;
25 import javax.xml.parsers.ParserConfigurationException;
26
27 import org.eclipse.xtend2.lib.StringConcatenation;
28 import org.eclipse.xtext.xbase.lib.Functions;
29 import org.eclipse.xtext.xbase.lib.IterableExtensions;
30 import org.opendaylight.yangtools.yang.binding.DataObject;
31 import org.opendaylight.yangtools.yang.binding.RpcService;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
34 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
37 import org.opendaylight.yangtools.yang.data.api.Node;
38 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
39 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
40 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
41 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
42 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
43 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.Module;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.w3c.dom.Document;
52 import org.w3c.dom.Element;
53 import org.xml.sax.SAXException;
54
55 import com.google.common.base.Optional;
56 import com.google.common.base.Preconditions;
57 import com.google.common.collect.BiMap;
58 import com.google.common.collect.HashBiMap;
59
60 public class RestconfUtils {
61
62     private static final Logger logger = LoggerFactory.getLogger(RestconfUtils.class);
63
64     private static final BiMap<URI,String> uriToModuleName = new Functions.Function0<BiMap<URI,String>>() {
65         @Override
66         public BiMap<URI,String> apply() {
67             HashBiMap<URI,String> _create = HashBiMap.<URI, String>create();
68             return _create;
69         }
70     }.apply();
71
72
73     public static Entry<String,DataSchemaNode> toRestconfIdentifier(org.opendaylight.yangtools.yang.binding.InstanceIdentifier<?> bindingIdentifier, BindingIndependentMappingService mappingService, SchemaContext schemaContext) {
74         InstanceIdentifier domIdentifier = mappingService.toDataDom(bindingIdentifier);
75         return toRestconfIdentifier(domIdentifier, schemaContext);
76
77     }
78
79     public static Entry<String,DataSchemaNode> toRestconfIdentifier(
80             InstanceIdentifier xmlInstanceIdentifier,
81             SchemaContext schemaContext) {
82
83         final List<InstanceIdentifier.PathArgument> elements = xmlInstanceIdentifier.getPath();
84         final StringBuilder ret = new StringBuilder();
85         InstanceIdentifier.PathArgument _head = IterableExtensions.<InstanceIdentifier.PathArgument>head(elements);
86         final QName startQName = _head.getNodeType();
87         URI _namespace = startQName.getNamespace();
88         Date _revision = startQName.getRevision();
89         final Module initialModule = schemaContext.findModuleByNamespaceAndRevision(_namespace, _revision);
90         DataNodeContainer node = (initialModule);
91         DataSchemaNode schemaNode = null;
92         for (final InstanceIdentifier.PathArgument element : elements) {
93             {
94                 final DataSchemaNode potentialNode = node.getDataChildByName(element.getNodeType());
95                 if (!isListOrContainer(potentialNode)) {
96                     return null;
97                 }
98                 node = ((DataNodeContainer) potentialNode);
99                 schemaNode = potentialNode;
100                 ret.append(convertToRestconfIdentifier(element, node,schemaContext));
101             }
102         }
103         return new SimpleEntry<>(ret.toString(),schemaNode);
104     }
105
106     private static CharSequence convertContainerToRestconfIdentifier(final InstanceIdentifier.NodeIdentifier argument, final ContainerSchemaNode node, SchemaContext schemaContext) {
107         StringConcatenation _builder = new StringConcatenation();
108         _builder.append("/");
109         QName _nodeType = argument.getNodeType();
110         CharSequence _restconfIdentifier = toRestconfIdentifier(_nodeType,schemaContext);
111         _builder.append(_restconfIdentifier, "");
112         return _builder;
113     }
114     private static CharSequence convertListToRestconfIdentifier(final InstanceIdentifier.NodeIdentifierWithPredicates argument, final ListSchemaNode node,SchemaContext schemaContext) {
115         QName _nodeType = argument.getNodeType();
116         final CharSequence nodeIdentifier = toRestconfIdentifier(_nodeType,schemaContext);
117         final Map<QName,Object> keyValues = argument.getKeyValues();
118         StringConcatenation _builder = new StringConcatenation();
119         _builder.append("/");
120         _builder.append(nodeIdentifier, "");
121         _builder.append("/");
122         {
123             List<QName> _keyDefinition = node.getKeyDefinition();
124             boolean _hasElements = false;
125             for(final QName key : _keyDefinition) {
126                 if (!_hasElements) {
127                     _hasElements = true;
128                 } else {
129                     _builder.appendImmediate("/", "");
130                 }
131                 Object _get = keyValues.get(key);
132                 String _uriString = toUriString(_get);
133                 _builder.append(_uriString, "");
134             }
135         }
136         return _builder;
137     }
138     private static String toUriString(final Object object) {
139         boolean _tripleEquals = (object == null);
140         if (_tripleEquals) {
141             return "";
142         }
143         String _string = object.toString();
144         return URLEncoder.encode(_string);
145     }
146
147     public static CharSequence toRestconfIdentifier(final QName qname,SchemaContext schemaContext) {
148         URI _namespace = qname.getNamespace();
149         String module = uriToModuleName.get(_namespace);
150         boolean _tripleEquals = (module == null);
151         if (_tripleEquals) {
152             URI _namespace_1 = qname.getNamespace();
153             Date _revision = qname.getRevision();
154             final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(_namespace_1, _revision);
155             boolean _tripleEquals_1 = (moduleSchema == null);
156             if (_tripleEquals_1) {
157                 return null;
158             }
159             URI _namespace_2 = qname.getNamespace();
160             String _name = moduleSchema.getName();
161             uriToModuleName.put(_namespace_2, _name);
162             String _name_1 = moduleSchema.getName();
163             module = _name_1;
164         }
165         StringConcatenation _builder = new StringConcatenation();
166         _builder.append(module, "");
167         _builder.append(":");
168         String _localName = qname.getLocalName();
169         _builder.append(_localName, "");
170         return _builder;
171     }
172     private static CharSequence convertToRestconfIdentifier(final InstanceIdentifier.PathArgument argument, final DataNodeContainer node, SchemaContext schemaContext) {
173         if (argument instanceof InstanceIdentifier.NodeIdentifier
174                 && node instanceof ContainerSchemaNode) {
175             return convertContainerToRestconfIdentifier((NodeIdentifier)argument, (ContainerSchemaNode) node,schemaContext);
176         } else if (argument instanceof InstanceIdentifier.NodeIdentifierWithPredicates
177                 && node instanceof ListSchemaNode) {
178             return convertListToRestconfIdentifier((NodeIdentifierWithPredicates) argument,(ListSchemaNode) node,schemaContext);
179         }  else {
180             throw new IllegalArgumentException("Unhandled parameter types: " +
181                     Arrays.<Object>asList(argument, node).toString());
182         }
183     }
184     private static boolean isListOrContainer(final DataSchemaNode node) {
185         boolean _or = false;
186         if ((node instanceof ListSchemaNode)) {
187             _or = true;
188         } else {
189             _or = ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode));
190         }
191         return _or;
192     }
193
194     public static Module findModuleByNamespace(final URI namespace,SchemaContext schemaContext) {
195         boolean _tripleNotEquals = (namespace != null);
196         Preconditions.checkArgument(_tripleNotEquals);
197         final Set<Module> moduleSchemas = schemaContext.findModuleByNamespace(namespace);
198         Module _filterLatestModule = null;
199         if (moduleSchemas!=null) {
200             _filterLatestModule=filterLatestModule(moduleSchemas);
201         }
202         return _filterLatestModule;
203     }
204
205     private static Module filterLatestModule(final Iterable<Module> modules) {
206         Module latestModule = IterableExtensions.<Module>head(modules);
207         for (final Module module : modules) {
208             Date _revision = module.getRevision();
209             Date _revision_1 = latestModule.getRevision();
210             boolean _after = _revision.after(_revision_1);
211             if (_after) {
212                 latestModule = module;
213             }
214         }
215         return latestModule;
216     }
217
218     public String findModuleNameByNamespace(final URI namespace,SchemaContext schemaContext) {
219         String moduleName = uriToModuleName.get(namespace);
220         boolean _tripleEquals = (moduleName == null);
221         if (_tripleEquals) {
222             final Module module = findModuleByNamespace(namespace, schemaContext);
223             boolean _tripleEquals_1 = (module == null);
224             if (_tripleEquals_1) {
225                 return null;
226             }
227             String _name = module.getName();
228             moduleName = _name;
229             uriToModuleName.put(namespace, moduleName);
230         }
231         return moduleName;
232     }
233
234     public static Set<Class<? extends RpcService>> rpcServicesFromInputStream(InputStream inputStream, BindingIndependentMappingService mappingService,SchemaContext schemaContext){
235         try {
236             DocumentBuilderFactory documentBuilder = DocumentBuilderFactory.newInstance();
237             documentBuilder.setNamespaceAware(true);
238             DocumentBuilder builder = documentBuilder.newDocumentBuilder();
239             Document doc = builder.parse(inputStream);
240             Element rootElement = doc.getDocumentElement();
241
242             List<Node<?>> domNodes = XmlDocumentUtils.toDomNodes(rootElement, Optional.of(schemaContext.getChildNodes()));
243             Set<Class<? extends RpcService>> rpcServices = new HashSet<Class<? extends RpcService>>();
244             for (Node<?> node:domNodes){
245                 if (node instanceof ImmutableCompositeNode){
246                     ImmutableCompositeNode icNode = (ImmutableCompositeNode)node;
247                     QName namespace = null;
248                     QName revision = null;
249                     QName name = null;
250                     for (QName q:icNode.keySet()){
251                         if (q.getLocalName().equals("namespace")){
252                             namespace = q;
253                         }
254                         if (q.getLocalName().equals("revision")){
255                             revision = q;
256                         }
257                         if (q.getLocalName().equals("name")){
258                             name = q;
259                         }
260
261                     }
262                     Optional<Class<? extends RpcService>> rpcService = mappingService.getRpcServiceClassFor(icNode.get(name).get(0).getValue().toString(),icNode.get(revision).get(0).getValue().toString());
263                     if (rpcService.isPresent()){
264                         rpcServices.add(rpcService.get());
265                     }
266                 }
267             }
268
269             return rpcServices;
270         } catch (ParserConfigurationException e) {
271             logger.trace("Parse configuration exception {}",e);
272         } catch (SAXException e) {
273             logger.trace("SAX exception {}",e);
274         } catch (IOException e) {
275             logger.trace("IOException {}",e);
276         }
277         return null;
278     }
279     public static DataObject dataObjectFromInputStream(org.opendaylight.yangtools.yang.binding.InstanceIdentifier<?> path, InputStream inputStream, SchemaContext schemaContext, BindingIndependentMappingService mappingService, DataSchemaNode dataSchema) {
280         // Parse stream into w3c Document
281         try {
282             DocumentBuilderFactory documentBuilder = DocumentBuilderFactory.newInstance();
283             documentBuilder.setNamespaceAware(true);
284             DocumentBuilder builder = documentBuilder.newDocumentBuilder();
285             Document doc = builder.parse(inputStream);
286             Element rootElement = doc.getDocumentElement();
287             Node<?> domNode =  XmlDocumentUtils.toDomNode(rootElement, Optional.of(dataSchema), Optional.<XmlCodecProvider>absent());
288             DataObject  dataObject = mappingService.dataObjectFromDataDom(path, (CompositeNode) domNode); //getDataFromResponse
289             return dataObject;
290         } catch (DeserializationException e) {
291
292
293         } catch (ParserConfigurationException e) {
294             logger.trace("Parse configuration exception {}",e);
295         } catch (SAXException e) {
296             logger.trace("SAX exception {}", e);
297         } catch (IOException e) {
298             logger.trace("IOException {}", e);
299         }
300         return null;
301     }
302
303 }