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