ca6751005bf6ccfec9dd4222863df2516a8a3eb2
[appc.git] / appc-directed-graph / dg-loader / provider / src / main / java / org / onap / sdnc / dg / loader / DGXMLGenerator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.sdnc.dg.loader;
26
27 import java.io.File;
28 import java.io.IOException;
29 import java.security.InvalidParameterException;
30 import java.util.ArrayList;
31 import java.util.List;
32 import javax.script.Invocable;
33 import javax.script.ScriptEngine;
34 import javax.script.ScriptEngineManager;
35 import javax.script.ScriptException;
36 import org.apache.commons.io.FileUtils;
37 import org.apache.commons.io.IOUtils;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41
42 public class DGXMLGenerator {
43
44     private static final Logger logger = LoggerFactory.getLogger(DGXMLGenerator.class);
45
46     private static final String STRING_ENCODING = "utf-8";
47     private static final String JS_INTERFACE_DG_CONVERTOR = "dgconverter";
48     private static final String JS_METHOD_GET_NODE_TO_XML = "getNodeToXml";
49     private static final String GENERATOR_TEMPLATE_FILE = "js/dg_xml2json.js";
50
51     public void generateXMLFromJSON(String jsonPath, String xmlpath, String propertyPath) {
52         try {
53             ScriptEngineManager manager = new ScriptEngineManager();
54             ScriptEngine engine = manager.getEngineByName("JavaScript");
55             if (!(engine instanceof Invocable)) {
56                 logger.error("Invoking methods is not supported.");
57                 return;
58             }
59             Invocable inv = (Invocable) engine;
60             String js = IOUtils.toString(DGXMLGenerator.class.getClassLoader()
61                 .getResourceAsStream(GENERATOR_TEMPLATE_FILE), STRING_ENCODING);
62             engine.eval(js);
63
64             Object dgconverter = engine.get(JS_INTERFACE_DG_CONVERTOR);
65
66             List<File> files = new ArrayList<>();
67             if (dgconverter != null) {
68                 File jsonPathFile = new File(jsonPath);
69                 if (jsonPathFile.isDirectory()) {
70                     String[] extensions = new String[]{"json", "JSON"};
71                     files = (List<File>) FileUtils.listFiles(jsonPathFile, extensions, true);
72                 } else if (jsonPathFile.isFile()) {
73                     files.add(jsonPathFile);
74                 } else {
75                     throw new InvalidParameterException("Failed to get the nature of the JSON path :" + jsonPath);
76                 }
77
78                 logger.info("JSON Files identified " + files.size());
79
80                 if (!files.isEmpty()) {
81                     boolean isXmlPathDeleted = FileUtils.deleteQuietly(new File(xmlpath));
82                     logger.info("Cleaning old DG XML under : " + xmlpath + ", delete status :"
83                         + isXmlPathDeleted);
84
85                     generateXmls(xmlpath, inv, dgconverter, files);
86
87                 } else {
88                     logger.info("No JSON Files to generate XML");
89                 }
90             } else {
91                 logger.error("Couldn't get Java Script Engine..");
92             }
93         } catch (Exception e) {
94             logger.error("Failed to generate generateXMLFromJSON", e);
95         }
96     }
97
98     private void generateXmls(String xmlpath, Invocable inv, Object dgconverter, List<File> files)
99         throws IOException, ScriptException, NoSuchMethodException {
100         for (File file : files) {
101             String dgJson = FileUtils.readFileToString(file, STRING_ENCODING);
102             logger.info("Generating XML from  :" + file.getName());
103             String xmlFileName =
104                 xmlpath + "/" + file.getName().replace(".json", ".xml");
105
106             Object dgXMl =
107                 inv.invokeMethod(dgconverter, JS_METHOD_GET_NODE_TO_XML, dgJson);
108             tryWriteXml(xmlFileName, dgXMl);
109         }
110     }
111
112     private void tryWriteXml(String xmlFileName, Object dgXMl) throws IOException {
113         if (dgXMl != null) {
114             File xmlFile = new File(xmlFileName);
115             FileUtils.writeStringToFile(xmlFile, dgXMl.toString(), STRING_ENCODING);
116             logger.info("Generated XML File under  :" + xmlFile.getCanonicalPath());
117         }
118     }
119
120     public static void main(String[] args) {
121         try {
122             DGXMLGenerator application = new DGXMLGenerator();
123             String jsonPath;
124             String xmlPath;
125             String propertyPath = null;
126             // Generate, GenerateLoad, GenerateLoadActivate
127             if (args != null && args.length >= 2) {
128                 // e.g "src/main/resources/json" "src/test/resources/xml"
129                 logger.info("DGXML Conversion Started with arguments :" + args[0] + ":" + args[1]);
130                 jsonPath = args[0];
131                 xmlPath = args[1];
132             } else {
133                 throw new InvalidParameterException("Required inputs are missing <jsonPath> <xmlPath>");
134             }
135
136             application.generateXMLFromJSON(jsonPath, xmlPath, propertyPath);
137             logger.info("DGXML Conversion Completed...");
138         } catch (Exception e) {
139             logger.error("Failed in DG XML Generation", e);
140         }
141     }
142 }