c32e5b1baa4581637cf103724405cd99e78141f2
[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  *  *  ================================================================================
8  *  *  Licensed under the Apache License, Version 2.0 (the "License");
9  *  *  you may not use this file except in compliance with the License.
10  *  *  You may obtain a copy of the License at
11  *  *
12  *  *   http://www.apache.org/licenses/LICENSE-2.0
13  *  *
14  *  *  Unless required by applicable law or agreed to in writing, software
15  *  *  distributed under the License is distributed on an "AS IS" BASIS,
16  *  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  *  See the License for the specific language governing permissions and
18  *  *  limitations under the License.
19  *  *  ============LICENSE_END=========================================================
20  *
21  *
22  */
23
24 package org.onap.blueprintgenerator.service.base;
25
26 import java.io.FileReader;
27 import java.nio.file.Paths;
28 import org.onap.blueprintgenerator.model.base.Blueprint;
29 import org.onap.blueprintgenerator.model.common.Input;
30 import org.onap.blueprintgenerator.model.componentspec.base.ComponentSpec;
31 import com.fasterxml.jackson.core.JsonProcessingException;
32 import com.fasterxml.jackson.databind.ObjectMapper;
33 import org.springframework.beans.factory.annotation.Autowired;
34 import org.springframework.beans.factory.annotation.Qualifier;
35 import org.springframework.stereotype.Service;
36 import org.springframework.util.StringUtils;
37
38 import java.io.File;
39 import java.io.IOException;
40 import java.io.FileWriter;
41 import java.io.BufferedWriter;
42 import java.io.PrintWriter;
43 import java.util.LinkedHashMap;
44 import java.util.Map;
45 import java.util.regex.Pattern;
46 import java.util.Date;
47 import org.apache.maven.model.Model;
48 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
49
50 /**
51  * @author : Ravi Mantena
52  * @date 10/16/2020 Application: DCAE/ONAP - Blueprint Generator Common Module: Used by both ONAp
53  * and DCAE Blueprint Applications Service: For Adding Quotes and Converting Blueprint to
54  * Yaml/String
55  */
56 @Service
57 public class BlueprintService {
58
59     @Autowired
60     protected FixesService fixesService;
61
62     @Qualifier("objectMapper")
63     @Autowired
64     protected ObjectMapper objectMapper;
65
66     @Qualifier("yamlObjectMapper")
67     @Autowired
68     protected ObjectMapper yamlObjectMapper;
69
70     /**
71      * Convertes blueprint to Yaml for given ComponentSpec, Blueprint and input
72      *
73      * @param cs ComponentSpec
74      * @param blueprint Blueprint
75      * @param input Input
76      * @return
77      */
78     public void blueprintToYaml(ComponentSpec cs, Blueprint blueprint, Input input) {
79         String bluePrintName = input.getBluePrintName();
80         String outputPath = input.getOutputPath();
81         String comment = "# " + input.getComment() + '\n';
82
83         try {
84             File outputFile;
85             String name =
86                 StringUtils.isEmpty(bluePrintName) ? cs.getSelf().getName() : bluePrintName;
87             if (name.contains(".")) {
88                 name = name.replaceAll(Pattern.quote("."), "_");
89             }
90             if (name.contains(" ")) {
91                 name = name.replaceAll(" ", "");
92             }
93             String file = name + ".yaml";
94             outputFile = new File(outputPath, file);
95             outputFile.getParentFile().mkdirs();
96             try {
97                 outputFile.createNewFile();
98             } catch (IOException e) {
99                 throw new RuntimeException(e);
100             }
101
102             String appVersion = "";
103             try {
104                 MavenXpp3Reader reader = new MavenXpp3Reader();
105                 Model model = reader.read(new FileReader("pom.xml"));
106                 appVersion = "#bpgen_application_version: " + model.getVersion() + '\n';
107             } catch (Exception e) {
108                 e.printStackTrace();
109             }
110
111             String version = "#blueprint_version: " + cs.getSelf().getVersion() + '\n';
112             String description = "#description: " + cs.getSelf().getDescription() + '\n';
113             String date = "#blueprint_created_date: " + new Date() + '\n';
114
115             BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile, false));
116             writer.write(description);
117             writer.write(version);
118             writer.write(date);
119             writer.write(appVersion);
120
121             if (isBpTypeMatches(input)) {
122                 writer.write(comment);
123             }
124
125             writer.close();
126
127             PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outputFile, true)));
128             yamlObjectMapper.writeValue(out, blueprint);
129             out.close();
130
131             if (isBpTypeMatches(input)) {
132                 fixesService.fixDcaeSingleQuotes(outputFile);
133             } else {
134                 fixesService.fixOnapSingleQuotes(outputFile);
135             }
136
137             // new Yaml().load(new FileInputStream(outputFile));
138
139             System.out.println("Blueprint is created with valid YAML Format");
140         } catch (Exception ex) {
141             throw new RuntimeException(
142                 "Unable to generate YAML file from Blueprint  or the generated YAML is not valid",
143                 ex);
144         }
145     }
146
147     /**
148      * Add quotes for given input
149      *
150      * @param inputs Inputs
151      * @return
152      */
153     public Map<String, LinkedHashMap<String, Object>> addQuotes(
154         Map<String, LinkedHashMap<String, Object>> inputs) {
155
156         inputs.forEach(
157             (key, value) -> {
158                 if (value.get("type") != null) {
159                     if (value.get("type").equals("string")
160                         && value.get("default") != null
161                         && !key.contains("policies")) {
162                         value.replace("default", "'" + value.get("default").toString() + "'");
163                     } else if (value.get("type").equals("map") || value.get("type")
164                         .equals("list")) {
165                         // Commented the Code as we need to read the object as is for Map and List. If the
166                         // List object is to be converted to string uncomment the below code.
167               /* if(inputs.get(s).get("type").equals("list")) {
168               String temp = inputs.get(s).get("default").toString();
169               inputs.get(s).replace("default", temp);
170               }*/
171                         inputs.get(key).remove("type");
172                     }
173                 }
174             });
175
176         return inputs;
177     }
178
179     /**
180      * Converts Blueprint to String format
181      *
182      * @param componentSpec ComponentSpec
183      * @param blueprint Blueprint
184      * @param input Input
185      * @return
186      */
187     public String blueprintToString(ComponentSpec componentSpec, Blueprint blueprint, Input input) {
188         String ret = "";
189         try {
190             ret = yamlObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(blueprint);
191         } catch (JsonProcessingException e) {
192             e.printStackTrace();
193         }
194         if (isBpTypeMatches(input)) {
195             ret =
196                 "# "
197                     + componentSpec.getSelf().getDescription()
198                     + "\n"
199                     + "# "
200                     + componentSpec.getSelf().getVersion()
201                     + "\n"
202                     + "# "
203                     + input.getComment()
204                     + "\n"
205                     + ret;
206             ret = fixesService.fixStringQuotes(ret);
207         } else {
208             ret = fixesService.applyFixes(ret);
209         }
210         return ret;
211     }
212
213     private boolean isBpTypeMatches(Input input) {
214         return input.getBpType().equals("dti")
215             || input.getBpType().equals("m")
216             || input.getBpType().equals("k");
217     }
218 }