2 * Copyright (c) 2013 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.yangtools.restconf.utils;
10 import java.io.IOException;
11 import java.io.InputStream;
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;
20 import java.util.Map.Entry;
23 import javax.xml.parsers.DocumentBuilder;
24 import javax.xml.parsers.DocumentBuilderFactory;
25 import javax.xml.parsers.ParserConfigurationException;
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;
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;
60 public class RestconfUtils {
62 private static final Logger logger = LoggerFactory.getLogger(RestconfUtils.class);
64 private static final BiMap<URI,String> uriToModuleName = new Functions.Function0<BiMap<URI,String>>() {
66 public BiMap<URI,String> apply() {
67 HashBiMap<URI,String> _create = HashBiMap.<URI, String>create();
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);
79 public static Entry<String,DataSchemaNode> toRestconfIdentifier(
80 InstanceIdentifier xmlInstanceIdentifier,
81 SchemaContext schemaContext) {
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) {
94 final DataSchemaNode potentialNode = node.getDataChildByName(element.getNodeType());
95 if (!isListOrContainer(potentialNode)) {
98 node = ((DataNodeContainer) potentialNode);
99 schemaNode = potentialNode;
100 ret.append(convertToRestconfIdentifier(element, node,schemaContext));
103 return new SimpleEntry<>(ret.toString(),schemaNode);
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, "");
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("/");
123 List<QName> _keyDefinition = node.getKeyDefinition();
124 boolean _hasElements = false;
125 for(final QName key : _keyDefinition) {
129 _builder.appendImmediate("/", "");
131 Object _get = keyValues.get(key);
132 String _uriString = toUriString(_get);
133 _builder.append(_uriString, "");
138 private static String toUriString(final Object object) {
139 boolean _tripleEquals = (object == null);
143 String _string = object.toString();
144 return URLEncoder.encode(_string);
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);
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) {
159 URI _namespace_2 = qname.getNamespace();
160 String _name = moduleSchema.getName();
161 uriToModuleName.put(_namespace_2, _name);
162 String _name_1 = moduleSchema.getName();
165 StringConcatenation _builder = new StringConcatenation();
166 _builder.append(module, "");
167 _builder.append(":");
168 String _localName = qname.getLocalName();
169 _builder.append(_localName, "");
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);
180 throw new IllegalArgumentException("Unhandled parameter types: " +
181 Arrays.<Object>asList(argument, node).toString());
184 private static boolean isListOrContainer(final DataSchemaNode node) {
186 if ((node instanceof ListSchemaNode)) {
189 _or = ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode));
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);
202 return _filterLatestModule;
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);
212 latestModule = module;
218 public String findModuleNameByNamespace(final URI namespace,SchemaContext schemaContext) {
219 String moduleName = uriToModuleName.get(namespace);
220 boolean _tripleEquals = (moduleName == null);
222 final Module module = findModuleByNamespace(namespace, schemaContext);
223 boolean _tripleEquals_1 = (module == null);
224 if (_tripleEquals_1) {
227 String _name = module.getName();
229 uriToModuleName.put(namespace, moduleName);
234 public static Set<Class<? extends RpcService>> rpcServicesFromInputStream(InputStream inputStream, BindingIndependentMappingService mappingService,SchemaContext schemaContext){
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();
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;
250 for (QName q:icNode.keySet()){
251 if (q.getLocalName().equals("namespace")){
254 if (q.getLocalName().equals("revision")){
257 if (q.getLocalName().equals("name")){
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());
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);
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
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
290 } catch (DeserializationException e) {
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);