14824f51ef42728299736e8d7c46cffeb0f5b646
[ccsdk/sli.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - CCSDK
4  * ================================================================================
5  * Copyright (C) 2018 Huawei Technologies Co., Ltd. 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.onap.ccsdk.sli.plugins.yangserializers.dfserializer;
22
23 import static javax.xml.transform.OutputKeys.INDENT;
24 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.XmlNodeType.OBJECT_NODE;
25 import static org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.XmlNodeType.TEXT_NODE;
26 import static org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.MdsalPropertiesNodeUtils.getRevision;
27 import java.io.IOException;
28 import java.io.StringReader;
29 import java.io.StringWriter;
30 import java.io.Writer;
31 import java.net.URI;
32 import java.net.URISyntaxException;
33 import java.util.Iterator;
34 import javax.xml.parsers.DocumentBuilder;
35 import javax.xml.parsers.DocumentBuilderFactory;
36 import javax.xml.parsers.ParserConfigurationException;
37 import javax.xml.transform.Transformer;
38 import javax.xml.transform.TransformerException;
39 import javax.xml.transform.TransformerFactory;
40 import javax.xml.transform.dom.DOMSource;
41 import javax.xml.transform.stream.StreamResult;
42 import org.dom4j.Element;
43 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
44 import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.Namespace;
45 import org.onap.ccsdk.sli.plugins.yangserializers.pnserializer.PropertiesNode;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
49 import org.w3c.dom.Document;
50 import org.xml.sax.InputSource;
51 import org.xml.sax.SAXException;
52
53 /**
54  * Utilities for data format serializer.
55  */
56 public final class DfSerializerUtil {
57
58     static final String JSON_WRITE_ERR = "Unable to write to JSON from " +
59             "properties.";
60
61     static final String NODE_TYPE_ERR = "The node type %s is not supported.";
62
63     static final String JSON_LIS_ERR = "The JSON serializer doesn't have " +
64             "JSON listener";
65
66     static final String XML_LIS_ERR = "The XML serializer doesn't have XML " +
67             "listener";
68
69     static final String PROP_NODE_ERR = "The property node doesn't have " +
70             "schema node bound to it.";
71
72     static final String DF_ERR = "Type mismatch for the node %s. The schema " +
73             "node does not match with the data format node type %s.";
74
75     static final String XML_PREFIX = "yangid";
76
77     private static final String YES = "yes";
78
79     private static final String INDENT_XMLNS = "{http://xml.apache" +
80             ".org/xslt}indent-amount";
81
82     private static final String XML_PARSE_ERR = "Unable to parse the xml to " +
83             "document : \n";
84
85     private static final String URI_ERR = "Unable to parse the URI";
86
87     /**
88      * Data format error message for unsupported types.
89      */
90     public static final String FORMAT_ERR = "Only JSON and XML formats are " +
91             "supported. %s is not supported";
92
93     /**
94      * UTF header message for XML data format message.
95      */
96     public static final String UTF_HEADER = "<?xml version=\"1.0\" " +
97             "encoding=\"UTF-8\"?>";
98
99     /**
100      * Error message when a JSON tree creation fails.
101      */
102     public static final String JSON_TREE_ERR = "Unable to form JSON tree " +
103             "object from the JSON body provided.";
104
105     /**
106      * Error message when a XML tree creation fails.
107      */
108     public static final String XML_TREE_ERR = "Unable to form XML tree object" +
109             " from the XML body provided.";
110
111     //No instantiation.
112     private DfSerializerUtil() {
113     }
114
115     /**
116      * Returns the writer which contains the pretty formatted XML string.
117      *
118      * @param input  input XML
119      * @param indent indentation level
120      * @return writer with XML
121      * @throws SvcLogicException when transformation of source fails
122      */
123     public static Writer getXmlWriter(String input, String indent)
124             throws SvcLogicException {
125         try {
126             Transformer transformer = TransformerFactory.newInstance()
127                     .newTransformer();
128             transformer.setOutputProperty(INDENT, YES);
129             transformer.setOutputProperty(INDENT_XMLNS, indent);
130             StreamResult result = new StreamResult(new StringWriter());
131             DOMSource source = new DOMSource(parseXml(input));
132             transformer.transform(source, result);
133             return result.getWriter();
134         } catch (TransformerException e) {
135             throw new SvcLogicException(XML_PARSE_ERR + input, e);
136         }
137     }
138
139     /**
140      * Parses the XML and converts it into dom document which can be used for
141      * formatting the XML.
142      *
143      * @param in input XML
144      * @return dom document of XML
145      * @throws SvcLogicException when document building fails
146      */
147     private static Document parseXml(String in) throws SvcLogicException {
148         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
149         DocumentBuilder db;
150         try {
151             db = dbf.newDocumentBuilder();
152             InputSource is = new InputSource(new StringReader(in));
153             return db.parse(is);
154         } catch (SAXException | IOException | ParserConfigurationException e) {
155             throw new SvcLogicException(XML_PARSE_ERR + in, e);
156         }
157     }
158
159     /**
160      * Returns the resolved namespace object from the input received from the
161      * abstract data format.
162      *
163      * @param mName  module name
164      * @param mUri   module URI
165      * @param ctx    schema context
166      * @param parent parent properties node
167      * @return namespace
168      * @throws SvcLogicException when resolving namespace fails
169      */
170     static Namespace getResolvedNamespace(String mName, String mUri,
171                                           SchemaContext ctx,
172                                           PropertiesNode parent)
173             throws SvcLogicException {
174         if (mName == null && mUri == null) {
175             Namespace parentNs = parent.namespace();
176             return new Namespace(parentNs.moduleName(), parentNs.moduleNs(),
177                                  parentNs.revision());
178         }
179
180         Iterator<? extends Module> it;
181         Module mod;
182         if (mName != null) {
183             it = ctx.findModules(mName).iterator();
184         } else {
185             URI modUri = null;
186             try {
187                modUri = new URI(mUri);
188             } catch (URISyntaxException e) {
189                 throw new SvcLogicException(URI_ERR, e);
190             }
191             it = ctx.findModules(modUri).iterator();
192         }
193
194         if (!it.hasNext()) {
195             return null;
196         }
197         mod = it.next();
198
199         return new Namespace(mod.getName(), mod.getQNameModule().getNamespace(),
200                              getRevision(mod.getRevision()));
201     }
202
203     /**
204      * Returns the node type of a XML element.
205      *
206      * @param element XML element
207      * @return node type of the XML element
208      */
209     static XmlNodeType getXmlNodeType(Element element) {
210         Element newElement = element.createCopy();
211         newElement.remove(element.getNamespace());
212         return newElement.hasContent() && newElement.isTextOnly() ?
213                 TEXT_NODE : OBJECT_NODE;
214     }
215
216     /**
217      * Resolves the super type to the base type from type definition.
218      *
219      * @param type super type
220      * @return base type definition
221      */
222     static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
223         TypeDefinition superType = type;
224         while (superType.getBaseType() != null) {
225             superType = superType.getBaseType();
226         }
227         return superType;
228     }
229 }