Added oparent to sdc main
[sdc.git] / asdctool / src / main / java / org / openecomp / sdc / asdctool / utils / ReportWriter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 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.openecomp.sdc.asdctool.utils;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonObject;
26 import com.google.gson.JsonParser;
27 import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
28
29 import java.io.FileWriter;
30 import java.io.IOException;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33
34 public class ReportWriter {
35     FileWriter file;
36     public ReportWriter(String reportName) {
37
38         StringBuilder sb = new StringBuilder();
39         Path path = Paths.get("/var/tmp/");
40         if ( path.toFile().exists() ) {
41             sb.append("/var/tmp/");
42         }
43         sb.append("report_").append(reportName).append("_").append(System.currentTimeMillis()).append(".json");
44         String fileName = sb.toString();
45         try {
46             file = new FileWriter(fileName);
47         } catch (IOException e) {
48             System.out.println("Failed to create report file. " + e.getMessage());
49         }
50     }
51
52     public void report(Object objectToWrite) throws IOException {
53         if (file != null) {
54             JsonParser parser = new JsonParser();
55             JsonObject json = parser.parse(JsonParserUtils.toJson(objectToWrite)).getAsJsonObject();
56
57             Gson gson = new GsonBuilder().setPrettyPrinting().create();
58             String prettyJson = gson.toJson(json);
59             
60             file.write(prettyJson);
61             file.flush();
62         }
63     }
64
65     public void close() throws IOException {
66         if (file != null) {
67             file.close();
68         }
69     }
70 }