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