re base code
[sdc.git] / asdctool / src / main / java / org / openecomp / sdc / asdctool / utils / ReportWriter.java
1 package org.openecomp.sdc.asdctool.utils;
2
3 import com.google.gson.Gson;
4 import com.google.gson.GsonBuilder;
5 import com.google.gson.JsonObject;
6 import com.google.gson.JsonParser;
7 import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
8
9 import java.io.FileWriter;
10 import java.io.IOException;
11 import java.nio.file.Path;
12 import java.nio.file.Paths;
13
14 public class ReportWriter {
15     FileWriter file;
16     public ReportWriter(String reportName) {
17
18         StringBuilder sb = new StringBuilder();
19         Path path = Paths.get("/var/tmp/");
20         if ( path.toFile().exists() ) {
21             sb.append("/var/tmp/");
22         }
23         sb.append("report_").append(reportName).append("_").append(System.currentTimeMillis()).append(".json");
24         String fileName = sb.toString();
25         try {
26             file = new FileWriter(fileName);
27         } catch (IOException e) {
28             System.out.println("Failed to create report file. " + e.getMessage());
29         }
30     }
31
32     public void report(Object objectToWrite) throws IOException {
33         if (file != null) {
34             JsonParser parser = new JsonParser();
35             JsonObject json = parser.parse(JsonParserUtils.toJson(objectToWrite)).getAsJsonObject();
36
37             Gson gson = new GsonBuilder().setPrettyPrinting().create();
38             String prettyJson = gson.toJson(json);
39             
40             file.write(prettyJson);
41             file.flush();
42         }
43     }
44
45     public void close() throws IOException {
46         if (file != null) {
47             file.close();
48         }
49     }
50 }