CVC: Add support for execution, schema, product
[cli.git] / framework / src / main / java / org / onap / cli / fw / utils / OnapCommandUtils.java
1 /*
2  * Copyright 2017 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.cli.fw.utils;
18
19 import static org.onap.cli.fw.conf.OnapCommandConstants.BOOLEAN_TRUE;
20 import static org.onap.cli.fw.conf.OnapCommandConstants.BOOLEAN_VALUE;
21 import static org.onap.cli.fw.conf.OnapCommandConstants.IS_INCLUDE;
22
23 import java.io.File;
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Set;
32 import java.util.UUID;
33
34 import org.apache.commons.io.FileUtils;
35 import org.onap.cli.fw.cmd.OnapCommand;
36 import org.onap.cli.fw.conf.OnapCommandConfig;
37 import org.onap.cli.fw.conf.OnapCommandConstants;
38 import org.onap.cli.fw.error.OnapCommandException;
39 import org.onap.cli.fw.error.OnapCommandInvalidParameterValue;
40 import org.onap.cli.fw.error.OnapCommandParameterNotFound;
41 import org.onap.cli.fw.error.OnapCommandResultEmpty;
42 import org.onap.cli.fw.input.OnapCommandParameter;
43 import org.onap.cli.fw.input.OnapCommandParameterType;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 import com.fasterxml.jackson.core.JsonProcessingException;
48 import com.fasterxml.jackson.databind.ObjectMapper;
49 import com.jayway.jsonpath.JsonPath;
50
51 /**
52  * Provides helper method to parse Yaml files and produce required objects.
53  *
54  */
55 public class OnapCommandUtils {
56
57     static Logger log = LoggerFactory.getLogger(OnapCommandUtils.class);
58     /**
59      * Private constructor.
60      */
61     private OnapCommandUtils() {
62
63     }
64
65     public static void throwOrCollect(OnapCommandException ex, List<String> list, boolean shouldCollectException)
66             throws OnapCommandException {
67         if (shouldCollectException) {
68             list.add(ex.getMessage());
69         } else {
70             throw ex;
71         }
72     }
73
74     public static void validateTags(List<String> schemaErrors, Map<String, ?> yamlMap, List<String> totalParams,
75             List<String> mandatoryParams, String section) {
76         // mrkanag capture invalid entries as well
77         for (String param : totalParams) {
78             boolean isMandatory = mandatoryParams.contains(param);
79             boolean isYamlContains = yamlMap.containsKey(param);
80             boolean isInclude = yamlMap.containsKey(IS_INCLUDE) && yamlMap.get(IS_INCLUDE).toString().equals(BOOLEAN_TRUE);
81             if (isMandatory) {
82                 if (!isYamlContains && isInclude) {
83                     schemaErrors.add("Mandatory attribute '" + param + "' is missing under '" + section + "'");
84                 } else {
85                     String value = String.valueOf(yamlMap.get(param));
86                     if (value == null || value.isEmpty()) {
87                         schemaErrors.add("Mandatory attribute '" + param + "' under '" + section
88                                 + "' shouldn't be null or empty");
89                     }
90                 }
91             }
92         }
93     }
94
95     /**
96      * Validate Boolean.
97      *
98      * @param toValidate
99      *            string
100      * @return boolean
101      */
102     public static boolean validateBoolean(String toValidate) {
103         return OnapCommandConfig.getCommaSeparatedList(BOOLEAN_VALUE).contains(toValidate.toLowerCase());
104     }
105
106     public static String emptySection(String section) {
107         return "The section '" + section + ":' cann't be null or empty";
108     }
109
110     public static String invalidBooleanValueMessage(String section, String attribute, String value) {
111         return "The value '" + value + "' of '" + attribute + "' present under '" + section + "' should be boolean";
112     }
113
114     public static void parseParameters(String line, Set<String> paramNames) {
115
116         int currentIdx = 0;
117         while (currentIdx < line.length()) {
118             int idxS = line.indexOf("${", currentIdx);
119             if (idxS == -1) {
120                 break;
121             }
122             int idxE = line.indexOf("}", idxS);
123             String paramName = line.substring(idxS + 2, idxE);
124             paramNames.add(paramName.trim());
125
126             currentIdx = idxE + 1;
127         }
128
129     }
130
131     /**
132      * Create Dict from list of Parameters.
133      *
134      * @param inputs
135      *            list of parameters
136      * @return map
137      */
138     public static Map<String, OnapCommandParameter> getInputMap(Set<OnapCommandParameter> inputs) {
139         Map<String, OnapCommandParameter> map = new HashMap<>();
140         for (OnapCommandParameter param : inputs) {
141             map.put(param.getName(), param);
142         }
143         return map;
144     }
145
146     /**
147      * sort the set.
148      *
149      * @param col
150      *            set
151      * @return list
152      */
153     public static List<String> sort(Set<String> col) {
154         List<String> results = new ArrayList<>();
155         results.addAll(col);
156         Collections.sort(results);
157         return results;
158     }
159
160     /**
161      * Flatten the json list.
162      *
163      * @param jsons
164      *            list json strings
165      * @return list
166      */
167     public static List<String> jsonFlatten(List<String> jsons) {
168         List<String> results = new ArrayList<>();
169         for (String json : jsons) {
170             try {
171                 results.add(JsonPath.parse(json).jsonString());
172             } catch (Exception e) { // NOSONAR
173                 results.add(json);
174             }
175         }
176
177         return results;
178     }
179
180     /**
181      * There are unique values like uuid is supported, so when input, output (default) values has
182      * these special entries, then it will get replaced with it's value
183      *
184      * @param lineSpl
185      * @return
186      */
187     public static String replaceLineForSpecialValues(String lineSpl) {
188         String resultSpl = "";
189
190         if (!lineSpl.contains("$s{")) {
191             return lineSpl;
192         }
193
194         int currentIdx = 0;
195         while (currentIdx < lineSpl.length()) {
196             int idxS = lineSpl.indexOf("$s{", currentIdx);
197             if (idxS == -1) {
198                 resultSpl += lineSpl.substring(currentIdx);
199                 break;
200             }
201             int idxE = lineSpl.indexOf("}", idxS);
202             String splEntry = lineSpl.substring(idxS + 3, idxE);
203             splEntry = splEntry.trim();
204
205             String value = "";
206
207             switch (splEntry) {
208                 case OnapCommandConstants.SPL_ENTRY_UUID:
209                     value = UUID.randomUUID().toString();
210                     break;
211
212                 default:
213
214                     if (splEntry.startsWith(OnapCommandConstants.SPL_ENTRY_ENV)) {
215                         //start to read after env:ENV_VAR_NAME
216                         String envVarName = splEntry.substring(4);
217                         value = System.getenv(envVarName);
218                         if (value == null) {
219                             //when env is not defined, assign the same env:ENV_VAR_NAME
220                             //so that it will given hit to user that ENV_VAR_NAME to be
221                             //defined.
222                             value = splEntry;
223                         }
224                     } else if (splEntry.startsWith(OnapCommandConstants.SPL_ENTRY_FILE)) {
225                         //start to read after file:filepath
226                         String fileName = splEntry.substring(5);
227                         try {
228                             value = FileUtils.readFileToString(new File(fileName));
229                         } catch (IOException e) {
230                             //when file is not found, assign the same file:FILE_PATH
231                             //so that it will given hit to user that FILE_PATH to be
232                             //exist.
233                             value = "";
234                         }
235                     } else {
236                         value = splEntry;
237                     }
238             }
239
240             resultSpl += lineSpl.substring(currentIdx, idxS) + value;
241             currentIdx = idxE + 1;
242         }
243
244         return resultSpl;
245     }
246
247     public static String replaceLineFromInputParameters(String line, Map<String, OnapCommandParameter> params)
248             throws OnapCommandException {
249         String result = "";
250
251         if (!line.contains("${")) {
252             return line;
253         }
254
255         int currentIdx = 0;
256         while (currentIdx < line.length()) {
257             int idxS = line.indexOf("${", currentIdx);
258             if (idxS == -1) {
259                 result += line.substring(currentIdx);
260                 break;
261             }
262             int idxE = line.indexOf("}", idxS);
263             String paramName = line.substring(idxS + 2, idxE);
264             paramName = paramName.trim();
265             if (!params.containsKey(paramName)) {
266                 throw new OnapCommandParameterNotFound(paramName);
267             }
268
269             OnapCommandParameter param = params.get(paramName);
270             if (OnapCommandParameterType.ARRAY.equals(param.getParameterType())
271                     || OnapCommandParameterType.JSON.equals(param.getParameterType())
272                     || OnapCommandParameterType.YAML.equals(param.getParameterType())) {
273                 // ignore the front and back double quotes in json body
274                 result += line.substring(currentIdx, idxS - 1) + params.get(paramName).getValue().toString();
275                 currentIdx = idxE + 2;
276             } else if (OnapCommandParameterType.MAP.equals(param.getParameterType())) {
277                 try {
278                     String value = new ObjectMapper().writeValueAsString(params.get(paramName).getValue());
279                     if ((idxS == 0) && (currentIdx == 0)) {
280                         result = value;
281                     } else {
282                         result += line.substring(currentIdx, idxS - 1) + value;
283                     }
284                 } catch (JsonProcessingException e) {  // NOSONAR
285                     //never occur as map is coverted to json string here
286                 }
287
288                 currentIdx = idxE + 2;
289             }else {
290                 result += line.substring(currentIdx, idxS) + params.get(paramName).getValue().toString();
291                 currentIdx = idxE + 1;
292             }
293         }
294
295         return result;
296     }
297
298     /**
299      * Populate result from input parameters.
300      *
301      * @param resultMap
302      *            map
303      * @param params
304      *            Map<String, OnapCommandParameter>
305      * @return map
306      * @throws OnapCommandException
307      */
308     public static Map<String, ArrayList<String>> populateOutputsFromInputParameters(
309             Map<String, ArrayList<String>> resultMap,
310             Map<String, OnapCommandParameter> params)
311             throws OnapCommandException {
312         Map<String, ArrayList<String>> resultsProcessed = new HashMap<>();
313
314         for (Entry<String, ArrayList<String>> entry : resultMap.entrySet()) {
315             String key = entry.getKey();
316             resultsProcessed.put(key, new ArrayList<>());
317             for (String value: entry.getValue()) {
318                 try {
319                     value = replaceLineFromInputParameters(value, params);
320                 } catch(OnapCommandResultEmpty e) {  // NOSONAR
321                     // pass
322                 }
323                 resultsProcessed.get(key).add(value);
324             }
325         }
326
327         return resultsProcessed;
328     }
329
330     /**
331      * Copy the parameters across the commands, mainly used for catalog, login and logout commands
332      *
333      * @throws OnapCommandInvalidParameterValue
334      */
335     public static void copyParamsFrom(OnapCommand from, OnapCommand to, Map<String, String> paramOverride) throws OnapCommandInvalidParameterValue {
336         for (OnapCommandParameter param: to.getParameters()) {
337
338             OnapCommandParameter fromParam = from.getParametersMap().get(param.getName());
339
340             if (fromParam != null) {
341                 param.setValue(fromParam.getValue());
342                 param.setDefaultValue(fromParam.getDefaultValue());
343             }
344
345             if (paramOverride.containsKey(param.getName())) {
346                  param.setValue(paramOverride.get(param.getName()));
347             }
348         }
349     }
350
351     public static void copyParamsFrom(OnapCommand from, OnapCommand to) throws OnapCommandInvalidParameterValue {
352         copyParamsFrom(from, to, new HashMap<String, String>());
353     }
354
355     /**
356      * Copy param schema from source command to destination command, useful in adding login command params into command
357      * @param from
358      * @param to
359      * @throws OnapCommandException
360      */
361     public static void copyParamSchemasFrom(OnapCommand from, OnapCommand to) {
362         for (OnapCommandParameter param: from.getParameters()) {
363             if (!to.getParametersMap().containsKey(param.getName())) {
364                 to.getParameters().add(param);
365             }
366         }
367     }
368
369 }
370
371
372