a77977e3222a9783b9c2cec8287c6dabe4113842
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.mso.yangDecoder.transform.impl;
22
23 import com.google.common.base.Charsets;
24 import com.google.common.base.Preconditions;
25 import com.google.common.collect.Lists;
26 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
27 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
28 import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
31 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
32 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
33 import org.opendaylight.yangtools.yang.model.api.*;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.w3c.dom.Document;
37 import org.w3c.dom.Element;
38 import org.xml.sax.SAXException;
39
40 import javax.xml.parsers.DocumentBuilder;
41 import javax.xml.parsers.DocumentBuilderFactory;
42 import javax.xml.parsers.ParserConfigurationException;
43 import javax.xml.stream.XMLOutputFactory;
44 import java.io.ByteArrayInputStream;
45 import java.io.IOException;
46 import java.io.InputStream;
47 import java.util.AbstractMap.SimpleEntry;
48 import java.util.ArrayList;
49 import java.util.Collections;
50 import java.util.List;
51 import java.util.Map;
52
53 import static org.openecomp.mso.yangDecoder.transform.impl.JsonParserStream.getWrapSchemaNode;
54
55 public class YangDataTransformNN2XMLServiceImpl {
56     private static final XMLOutputFactory XML_FACTORY;
57     private static final DocumentBuilderFactory BUILDERFACTORY;
58     static {
59         XML_FACTORY = XMLOutputFactory.newFactory();
60         XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false);
61         final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
62         factory.setNamespaceAware(true);
63         factory.setCoalescing(true);
64         factory.setIgnoringElementContentWhitespace(true);
65         factory.setIgnoringComments(true);
66         BUILDERFACTORY = factory;
67     }
68     BindingNormalizedNodeSerializer mappingservice;
69     SchemaContext schemaContext;
70     private static final Logger LOG = LoggerFactory.getLogger(YangDataTransformNN2XMLServiceImpl.class);
71
72     public YangDataTransformNN2XMLServiceImpl(BindingNormalizedNodeSerializer mappingservice, SchemaContext context ) {
73
74         this.schemaContext = context;
75         this.mappingservice=mappingservice;
76     }
77
78     public String transformNNToString(NormalizedNode nn)
79     {
80         StringBuilder stringBuilder = new StringBuilder();
81         stringBuilder.append(YangOdlNNC2XMLImpl.getXMLHeader());
82         new NormalizedNodeNavigator(new NormalizedNodePrinter(stringBuilder)).navigate(null, nn);
83         return stringBuilder.toString();
84     }
85
86
87     public static DataSchemaNode getSchemaNodebyNs(final SchemaContext context, final String ns, final String childNodeName) {
88         for (Module module : context.getModules()) {
89             if (module.getNamespace().toString().equals(ns)) {
90                 DataSchemaNode found = findChildNode(module.getChildNodes(), childNodeName);
91                 Preconditions.checkState(found != null, "Unable to find %s", childNodeName);
92                 return found;
93             }
94         }
95         throw new IllegalStateException("Unable to find child node " + childNodeName);
96     }
97     private static DataSchemaNode findChildNode(final Iterable<DataSchemaNode> children, final String name) {
98         List<DataNodeContainer> containers = Lists.newArrayList();
99
100         for (DataSchemaNode dataSchemaNode : children) {
101             if (dataSchemaNode.getQName().getLocalName().equals(name)) {
102                 return dataSchemaNode;
103             }
104             if (dataSchemaNode instanceof DataNodeContainer) {
105                 containers.add((DataNodeContainer) dataSchemaNode);
106             } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
107                 containers.addAll(((ChoiceSchemaNode) dataSchemaNode).getCases());
108             }
109         }
110
111         for (DataNodeContainer container : containers) {
112             DataSchemaNode retVal = findChildNode(container.getChildNodes(), name);
113             if (retVal != null) {
114                 return retVal;
115             }
116         }
117
118         return null;
119     }
120     public NormalizedNode transformNNFromString(String sxml) throws Exception {
121         InputStream in_nocode = new ByteArrayInputStream(sxml.getBytes(Charsets.UTF_8));//.getBytes("UTF-8")
122          //xml2nn
123             final Document docxml = readXmlToDocument(in_nocode);
124             Element element0 = docxml.getDocumentElement();
125             String localname = element0.getNodeName();
126             String ns = element0.getAttribute("xmlns");
127            // final ContainerSchemaNode containerNodex = (ContainerSchemaNode)null;
128            final DataSchemaNode dsn=getSchemaNodebyNs(schemaContext, ns, localname);
129             //cn.getNodeType().getNamespace().toString(), cn.getNodeType().getLocalName());
130         DomToNormalizedNodeParserFactory parserFactory =DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(), schemaContext);
131         NormalizedNode parsed = null;
132         final List<Element> elements = Collections.singletonList(docxml.getDocumentElement());
133         if (dsn instanceof ContainerSchemaNode) {
134             parsed= parserFactory.getContainerNodeParser().parse(elements, (ContainerSchemaNode)dsn);
135         }else   if (dsn instanceof ListSchemaNode) {
136             final ListSchemaNode casted = (ListSchemaNode) dsn;
137             parsed=parserFactory.getMapEntryNodeParser().parse(elements, casted);
138         }
139         return parsed;
140
141     }
142
143
144
145     public NormalizedNode transformNotificationNNfromString(String sxml, final InstanceIdentifierContext<?> iicontext) throws Exception
146     {
147         SchemaNode schemaNode = getWrapSchemaNode(iicontext.getSchemaNode());
148         InputStream in_nocode = new ByteArrayInputStream(sxml.getBytes(Charsets.UTF_8));//.getBytes("UTF-8")
149         //xml2nn
150         final Document docxml = readXmlToDocument(in_nocode);
151         Element element0 = docxml.getDocumentElement();
152         String localname = element0.getNodeName();
153         String ns = element0.getAttribute("xmlns");
154         // final ContainerSchemaNode containerNodex = (ContainerSchemaNode)null;
155         //  final DataSchemaNode dsn=(DataSchemaNode)schemaNode;/*getSchemaNodebyNs(schemaContext, ns, localname);*/
156         //cn.getNodeType().getNamespace().toString(), cn.getNodeType().getLocalName());
157         DomToNormalizedNodeParserFactory parserFactory =DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(), schemaContext);
158         NormalizedNode parsed = null;
159         final List<Element> elements = Collections.singletonList(docxml.getDocumentElement());
160         if (schemaNode instanceof ContainerSchemaNode) {
161             parsed= parserFactory.getContainerNodeParser().parse(elements, (ContainerSchemaNode)schemaNode);
162         }else   if (schemaNode instanceof ListSchemaNode) {
163             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
164             parsed=parserFactory.getMapEntryNodeParser().parse(elements, casted);
165         }
166         return parsed;
167     }
168     public NormalizedNode transformNotificationStringtoNN(String sxml,String notficationName) throws Exception {
169         final InstanceIdentifierContext<?> iicontext= ControllerContext.getInstance().toInstanceIdentifier(notficationName);
170          return transformNotificationNNfromString(sxml,iicontext);
171     }
172     public Map.Entry<DataSchemaNode, NormalizedNode>  transformRpcNNEntryfromString(String sxml, final InstanceIdentifierContext<?> iirpccontext) throws Exception{
173         InputStream in_nocode = new ByteArrayInputStream(sxml.getBytes(Charsets.UTF_8));//.getBytes("UTF-8")
174         //xml2nn
175         final Document docxml = readXmlToDocument(in_nocode);
176         Element element0 = docxml.getDocumentElement();
177         String localname = element0.getNodeName();
178         String ns = element0.getAttribute("xmlns");
179         DataSchemaNode schemaNode;
180         final SchemaNode schemaNode0 = iirpccontext.getSchemaNode();
181         boolean isInput = false;
182         if (schemaNode0 instanceof RpcDefinition) {
183             if (docxml.getDocumentElement().getLocalName().contains("output")) {
184                 schemaNode = ((RpcDefinition) schemaNode0).getOutput();
185                 isInput = false;
186             } else {
187                 schemaNode = ((RpcDefinition) schemaNode0).getInput();
188                 isInput = true;
189             }
190
191         } else if (docxml instanceof DataSchemaNode) {
192             schemaNode = (DataSchemaNode) docxml;
193         } else {
194             throw new IllegalStateException("Unknow SchemaNode");
195         }
196
197         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
198         InstanceIdentifierContext<? extends SchemaNode> outIIContext;
199         // final ContainerSchemaNode containerNodex = (ContainerSchemaNode)null;
200         //  final DataSchemaNode dsn=(DataSchemaNode)schemaNode;/*getSchemaNodebyNs(schemaContext, ns, localname);*/
201         //cn.getNodeType().getNamespace().toString(), cn.getNodeType().getLocalName());
202         DomToNormalizedNodeParserFactory parserFactory =DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(), schemaContext);
203         NormalizedNode parsed = null;
204         final List<Element> elements = Collections.singletonList(docxml.getDocumentElement());
205         if (schemaNode instanceof ContainerSchemaNode) {
206             parsed= parserFactory.getContainerNodeParser().parse(elements, (ContainerSchemaNode)schemaNode);
207         }else   if (schemaNode instanceof ListSchemaNode) {
208             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
209             parsed=parserFactory.getMapEntryNodeParser().parse(elements, casted);
210         }
211         return new SimpleEntry<DataSchemaNode, NormalizedNode>(schemaNode,parsed);
212     }
213     public NormalizedNode transformRpcNNfromString(String sxml, final InstanceIdentifierContext<?> iirpccontext) throws Exception{
214
215         InputStream in_nocode = new ByteArrayInputStream(sxml.getBytes(Charsets.UTF_8));//.getBytes("UTF-8")
216         //xml2nn
217         final Document docxml = readXmlToDocument(in_nocode);
218         Element element0 = docxml.getDocumentElement();
219         String localname = element0.getNodeName();
220         String ns = element0.getAttribute("xmlns");
221         DataSchemaNode schemaNode;
222         final SchemaNode schemaNode0 = iirpccontext.getSchemaNode();
223         boolean isInput = false;
224         if (schemaNode0 instanceof RpcDefinition) {
225             if (docxml.getDocumentElement().getLocalName().contains("output")) {
226                 schemaNode = ((RpcDefinition) schemaNode0).getOutput();
227                 isInput = false;
228             } else {
229                 schemaNode = ((RpcDefinition) schemaNode0).getInput();
230                 isInput = true;
231             }
232
233         } else if (docxml instanceof DataSchemaNode) {
234             schemaNode = (DataSchemaNode) docxml;
235         } else {
236             throw new IllegalStateException("Unknow SchemaNode");
237         }
238
239         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
240         InstanceIdentifierContext<? extends SchemaNode> outIIContext;
241         // final ContainerSchemaNode containerNodex = (ContainerSchemaNode)null;
242         //  final DataSchemaNode dsn=(DataSchemaNode)schemaNode;/*getSchemaNodebyNs(schemaContext, ns, localname);*/
243         //cn.getNodeType().getNamespace().toString(), cn.getNodeType().getLocalName());
244         DomToNormalizedNodeParserFactory parserFactory =DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(), schemaContext);
245         NormalizedNode parsed = null;
246         final List<Element> elements = Collections.singletonList(docxml.getDocumentElement());
247         if (schemaNode instanceof ContainerSchemaNode) {
248             parsed= parserFactory.getContainerNodeParser().parse(elements, (ContainerSchemaNode)schemaNode);
249         }else   if (schemaNode instanceof ListSchemaNode) {
250             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
251             parsed=parserFactory.getMapEntryNodeParser().parse(elements, casted);
252         }
253         return parsed;
254     }
255     public NormalizedNode transformRpcNNfromString(String sxml, String rpcName) throws Exception {
256         final InstanceIdentifierContext<?> iicontext= ControllerContext.getInstance().toInstanceIdentifier(rpcName);
257         return this.transformRpcNNfromString(sxml,iicontext);
258
259     }
260     public static Document readXmlToDocument(final InputStream xmlContent) throws IOException, SAXException {
261         final DocumentBuilder dBuilder;
262         try {
263             dBuilder = BUILDERFACTORY.newDocumentBuilder();
264         } catch (final ParserConfigurationException e) {
265             throw new RuntimeException("Failed to parse XML document", e);
266         }
267         final Document doc = dBuilder.parse(xmlContent);
268
269         doc.getDocumentElement().normalize();
270         return doc;
271     }
272
273 }