Changed to unmaintained
[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-2018 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  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.sdnc.dg.loader;
25
26 import java.io.File;
27 import java.io.IOException;
28 import java.security.InvalidParameterException;
29 import java.util.ArrayList;
30 import java.util.List;
31 import javax.script.Invocable;
32 import javax.script.ScriptEngine;
33 import javax.script.ScriptEngineManager;
34 import javax.script.ScriptException;
35 import org.apache.commons.io.FileUtils;
36 import org.apache.commons.io.IOUtils;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40
41 public class DGXMLGenerator {
42
43     private static final Logger logger = LoggerFactory.getLogger(DGXMLGenerator.class);
44
45     private static final String STRING_ENCODING = "utf-8";
46     private static final String JS_INTERFACE_DG_CONVERTOR = "dgconverter";
47     private static final String JS_METHOD_GET_NODE_TO_XML = "getNodeToXml";
48     private static final String GENERATOR_TEMPLATE_FILE = "js/dg_xml2json.js";
49
50     public void generateXMLFromJSON(String jsonPath, String xmlpath, String propertyPath) {
51         try {
52             ScriptEngineManager manager = new ScriptEngineManager();
53             ScriptEngine engine = manager.getEngineByName("JavaScript");
54             if (!(engine instanceof Invocable)) {
55                 logger.error("Invoking methods is not supported.");
56                 return;
57             }
58             Invocable inv = (Invocable) engine;
59             String js = IOUtils.toString(DGXMLGenerator.class.getClassLoader()
60                 .getResourceAsStream(GENERATOR_TEMPLATE_FILE), STRING_ENCODING);
61             engine.eval(js);
62
63             Object dgconverter = engine.get(JS_INTERFACE_DG_CONVERTOR);
64
65             List<File> files = new ArrayList<>();
66             if (dgconverter != null) {
67                 File jsonPathFile = new File(jsonPath);
68                 if (jsonPathFile.isDirectory()) {
69                     String[] extensions = new String[]{"json", "JSON"};
70                     files = (List<File>) FileUtils.listFiles(jsonPathFile, extensions, true);
71                 } else if (jsonPathFile.isFile()) {
72                     files.add(jsonPathFile);
73                 } else {
74                     throw new InvalidParameterException("Failed to get the nature of the JSON path :" + jsonPath);
75                 }
76
77                 logger.info("JSON Files identified " + files.size());
78
79                 if (!files.isEmpty()) {
80                     boolean isXmlPathDeleted = FileUtils.deleteQuietly(new File(xmlpath));
81                     logger.info("Cleaning old DG XML under : " + xmlpath + ", delete status :"
82                         + isXmlPathDeleted);
83
84                     generateXmls(xmlpath, inv, dgconverter, files);
85
86                 } else {
87                     logger.info("No JSON Files to generate XML");
88                 }
89             } else {
90                 logger.error("Couldn't get Java Script Engine..");
91             }
92         } catch (Exception e) {
93             logger.error("Failed to generate generateXMLFromJSON", e);
94         }
95     }
96
97     private void generateXmls(String xmlpath, Invocable inv, Object dgconverter, List<File> files)
98         throws IOException, ScriptException, NoSuchMethodException {
99         for (File file : files) {
100             String dgJson = FileUtils.readFileToString(file, STRING_ENCODING);
101             logger.info("Generating XML from  :" + file.getName());
102             String xmlFileName =
103                 xmlpath + "/" + file.getName().replace(".json", ".xml");
104
105             Object dgXMl =
106                 inv.invokeMethod(dgconverter, JS_METHOD_GET_NODE_TO_XML, dgJson);
107             tryWriteXml(xmlFileName, dgXMl);
108         }
109     }
110
111     private void tryWriteXml(String xmlFileName, Object dgXMl) throws IOException {
112         if (dgXMl != null) {
113             File xmlFile = new File(xmlFileName);
114             FileUtils.writeStringToFile(xmlFile, dgXMl.toString(), STRING_ENCODING);
115             logger.info("Generated XML File under  :" + xmlFile.getCanonicalPath());
116         }
117     }
118
119     public static void main(String[] args) {
120         try {
121             DGXMLGenerator application = new DGXMLGenerator();
122             String jsonPath;
123             String xmlPath;
124             String propertyPath = null;
125             // Generate, GenerateLoad, GenerateLoadActivate
126             if (args != null && args.length >= 2) {
127                 // e.g "src/main/resources/json" "src/test/resources/xml"
128                 logger.info("DGXML Conversion Started with arguments :" + args[0] + ":" + args[1]);
129                 jsonPath = args[0];
130                 xmlPath = args[1];
131             } else {
132                 throw new InvalidParameterException("Required inputs are missing <jsonPath> <xmlPath>");
133             }
134
135             application.generateXMLFromJSON(jsonPath, xmlPath, propertyPath);
136             logger.info("DGXML Conversion Completed...");
137         } catch (Exception e) {
138             logger.error("Failed in DG XML Generation", e);
139         }
140     }
141 }