Fix sonar issues
[dcaegen2/platform.git] / mod / bpgenerator / common / src / main / java / org / onap / blueprintgenerator / service / base / BlueprintService.java
1 /*
2  *
3  *  * ============LICENSE_START=======================================================
4  *  *  org.onap.dcae
5  *  *  ================================================================================
6  *  *  Copyright (c) 2020  AT&T Intellectual Property. All rights reserved.
7  *  *  Copyright (c) 2021 Nokia. All rights reserved.
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  *  *  ============LICENSE_END=========================================================
21  *
22  *
23  */
24
25 package org.onap.blueprintgenerator.service.base;
26
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import java.io.FileReader;
30 import org.onap.blueprintgenerator.model.base.Blueprint;
31 import org.onap.blueprintgenerator.model.common.Input;
32 import org.onap.blueprintgenerator.model.componentspec.base.ComponentSpec;
33 import com.fasterxml.jackson.core.JsonProcessingException;
34 import com.fasterxml.jackson.databind.ObjectMapper;
35 import org.springframework.beans.factory.annotation.Autowired;
36 import org.springframework.beans.factory.annotation.Qualifier;
37 import org.springframework.stereotype.Service;
38 import org.springframework.util.StringUtils;
39
40 import java.io.File;
41 import java.io.IOException;
42 import java.io.FileWriter;
43 import java.io.BufferedWriter;
44 import java.io.PrintWriter;
45 import java.util.LinkedHashMap;
46 import java.util.Map;
47 import java.util.regex.Pattern;
48 import java.util.Date;
49 import org.apache.maven.model.Model;
50 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
51
52 /**
53  * @author : Ravi Mantena
54  * @date 10/16/2020 Application: DCAE/ONAP - Blueprint Generator Common Module: Used by both ONAp
55  * and DCAE Blueprint Applications Service: For Adding Quotes and Converting Blueprint to
56  * Yaml/String
57  */
58 @Service
59 public class BlueprintService {
60
61     private static final String TYPE_KEY = "type";
62     private static final String DEFAULT_KEY = "default";
63     private static final Logger logger = LoggerFactory.getLogger(BlueprintService.class);
64
65     @Autowired
66     protected FixesService fixesService;
67
68     @Qualifier("objectMapper")
69     @Autowired
70     protected ObjectMapper objectMapper;
71
72     @Qualifier("yamlObjectMapper")
73     @Autowired
74     protected ObjectMapper yamlObjectMapper;
75
76     /**
77      * Convertes blueprint to Yaml for given ComponentSpec, Blueprint and input
78      *
79      * @param cs ComponentSpec
80      * @param blueprint Blueprint
81      * @param input Input
82      * @return
83      */
84     public void blueprintToYaml(ComponentSpec cs, Blueprint blueprint, Input input) {
85         String bluePrintName = input.getBluePrintName();
86         String outputPath = input.getOutputPath();
87         String comment = "# " + input.getComment() + '\n';
88
89         try {
90             String name =
91                 StringUtils.isEmpty(bluePrintName) ? cs.getSelf().getName() : bluePrintName;
92             if (name.contains(".")) {
93                 name = name.replaceAll(Pattern.quote("."), "_");
94             }
95             if (name.contains(" ")) {
96                 name = name.replace(" ", "");
97             }
98
99             File outputFile = createFile(outputPath, name);
100             String appVersion = readAppVersion();
101
102             String version = "#blueprint_version: " + cs.getSelf().getVersion() + '\n';
103             String description = "#description: " + cs.getSelf().getDescription() + '\n';
104             String date = "#blueprint_created_date: " + new Date() + '\n';
105
106             BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile, false));
107             writer.write(description);
108             writer.write(version);
109             writer.write(date);
110             writer.write(appVersion);
111
112             if (isBpTypeMatches(input)) {
113                 writer.write(comment);
114             }
115
116             writer.close();
117
118             PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outputFile, true)));
119             yamlObjectMapper.writeValue(out, blueprint);
120             out.close();
121
122             if (isBpTypeMatches(input)) {
123                 fixesService.fixDcaeSingleQuotes(outputFile);
124             } else {
125                 fixesService.fixOnapSingleQuotes(outputFile);
126             }
127
128             logger.debug("Blueprint is created with valid YAML Format");
129         } catch (Exception ex) {
130             throw new RuntimeException(
131                 "Unable to generate YAML file from Blueprint  or the generated YAML is not valid",
132                 ex);
133         }
134     }
135
136     /**
137      * Add quotes for given input
138      *
139      * @param inputs Inputs
140      * @return
141      */
142     public Map<String, LinkedHashMap<String, Object>> addQuotes(
143         Map<String, LinkedHashMap<String, Object>> inputs) {
144
145         inputs.forEach(
146             (key, value) -> {
147                 if (value.get(TYPE_KEY) != null) {
148                     if (value.get(TYPE_KEY).equals("string")
149                         && value.get(DEFAULT_KEY) != null
150                         && !key.contains("policies")) {
151                         value.replace(DEFAULT_KEY, "'" + value.get(DEFAULT_KEY).toString() + "'");
152                     } else if (value.get(TYPE_KEY).equals("map") || value.get(TYPE_KEY)
153                         .equals("list")) {
154                         // Commented the Code as we need to read the object as is for Map and List. If the
155                         // List object is to be converted to string uncomment the below code.
156               /* if(inputs.get(s).get("type").equals("list")) {
157               String temp = inputs.get(s).get("default").toString();
158               inputs.get(s).replace("default", temp);
159               }*/
160                         inputs.get(key).remove(TYPE_KEY);
161                     }
162                 }
163             });
164
165         return inputs;
166     }
167
168     /**
169      * Converts Blueprint to String format
170      *
171      * @param componentSpec ComponentSpec
172      * @param blueprint Blueprint
173      * @param input Input
174      * @return
175      */
176     public String blueprintToString(ComponentSpec componentSpec, Blueprint blueprint, Input input) {
177         String ret = "";
178         try {
179             ret = yamlObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(blueprint);
180         } catch (JsonProcessingException e) {
181             e.printStackTrace();
182         }
183         if (isBpTypeMatches(input)) {
184             ret =
185                 "# "
186                     + componentSpec.getSelf().getDescription()
187                     + "\n"
188                     + "# "
189                     + componentSpec.getSelf().getVersion()
190                     + "\n"
191                     + "# "
192                     + input.getComment()
193                     + "\n"
194                     + ret;
195             ret = fixesService.fixStringQuotes(ret);
196         } else {
197             ret = fixesService.applyFixes(ret);
198         }
199         return ret;
200     }
201
202     private boolean isBpTypeMatches(Input input) {
203         return input.getBpType().equals("dti")
204             || input.getBpType().equals("m")
205             || input.getBpType().equals("k");
206     }
207
208     private File createFile(String outputPath, String name) {
209         File outputFile;
210         String file = name + ".yaml";
211         outputFile = new File(outputPath, file);
212         outputFile.getParentFile().mkdirs();
213         try {
214             boolean isCreated = outputFile.createNewFile();
215             if (isCreated) {
216                 logger.debug("The file " + file + " was successfully created.");
217             } else {
218                 logger.debug("The file " + file + " already existed.");
219             }
220         } catch (IOException e) {
221             throw new RuntimeException(e);
222         }
223         return outputFile;
224     }
225
226     private String readAppVersion() {
227         String appVersion = "";
228         try {
229             MavenXpp3Reader reader = new MavenXpp3Reader();
230             Model model = reader.read(new FileReader("pom.xml"));
231             appVersion = "#bpgen_application_version: " + model.getVersion() + '\n';
232         } catch (Exception e) {
233             e.printStackTrace();
234         }
235         return appVersion;
236     }
237 }