Fix logout and auth specific param customization
[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_VALUE;
20
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.Set;
28 import java.util.UUID;
29
30 import org.onap.cli.fw.cmd.OnapCommand;
31 import org.onap.cli.fw.conf.OnapCommandConfig;
32 import org.onap.cli.fw.conf.OnapCommandConstants;
33 import org.onap.cli.fw.error.OnapCommandException;
34 import org.onap.cli.fw.error.OnapCommandInvalidParameterValue;
35 import org.onap.cli.fw.error.OnapCommandParameterNotFound;
36 import org.onap.cli.fw.error.OnapCommandResultEmpty;
37 import org.onap.cli.fw.input.OnapCommandParameter;
38 import org.onap.cli.fw.input.OnapCommandParameterType;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import com.jayway.jsonpath.JsonPath;
43
44 /**
45  * Provides helper method to parse Yaml files and produce required objects.
46  *
47  */
48 public class OnapCommandUtils {
49
50     static Logger LOG = LoggerFactory.getLogger(OnapCommandUtils.class);
51     /**
52      * Private constructor.
53      */
54     private OnapCommandUtils() {
55
56     }
57
58     public static void throwOrCollect(OnapCommandException ex, List<String> list, boolean shouldCollectException)
59             throws OnapCommandException {
60         if (shouldCollectException) {
61             list.add(ex.getMessage());
62         } else {
63             throw ex;
64         }
65     }
66
67     public static void validateTags(List<String> schemaErrors, Map<String, ?> yamlMap, List<String> totalParams,
68             List<String> mandatoryParams, String section) {
69         // mrkanag capture invalid entries as well
70         for (String param : totalParams) {
71             boolean isMandatory = mandatoryParams.contains(param);
72             boolean isYamlContains = yamlMap.containsKey(param);
73             if (isMandatory) {
74                 if (!isYamlContains) {
75                     schemaErrors.add("Mandatory attribute '" + param + "' is missing under '" + section + "'");
76                 } else {
77                     String value = String.valueOf(yamlMap.get(param));
78                     if (value == null || value.isEmpty()) {
79                         schemaErrors.add("Mandatory attribute '" + param + "' under '" + section
80                                 + "' shouldn't be null or empty");
81                     }
82                 }
83             }
84         }
85     }
86
87     /**
88      * Validate Boolean.
89      *
90      * @param toValidate
91      *            string
92      * @return boolean
93      */
94     public static boolean validateBoolean(String toValidate) {
95         return OnapCommandConfig.getCommaSeparatedList(BOOLEAN_VALUE).contains(toValidate.toLowerCase());
96     }
97
98     public static String emptySection(String section) {
99         return "The section '" + section + ":' cann't be null or empty";
100     }
101
102     public static String invalidBooleanValueMessage(String section, String attribute, String value) {
103         return "The value '" + value + "' of '" + attribute + "' present under '" + section + "' should be boolean";
104     }
105
106     public static void parseParameters(String line, Set<String> paramNames) {
107
108         int currentIdx = 0;
109         while (currentIdx < line.length()) {
110             int idxS = line.indexOf("${", currentIdx);
111             if (idxS == -1) {
112                 break;
113             }
114             int idxE = line.indexOf("}", idxS);
115             String paramName = line.substring(idxS + 2, idxE);
116             paramNames.add(paramName.trim());
117
118             currentIdx = idxE + 1;
119         }
120
121     }
122
123     /**
124      * Create Dict from list of Parameters.
125      *
126      * @param inputs
127      *            list of parameters
128      * @return map
129      */
130     public static Map<String, OnapCommandParameter> getInputMap(Set<OnapCommandParameter> inputs) {
131         Map<String, OnapCommandParameter> map = new HashMap<>();
132         for (OnapCommandParameter param : inputs) {
133             map.put(param.getName(), param);
134         }
135         return map;
136     }
137
138     /**
139      * sort the set.
140      *
141      * @param col
142      *            set
143      * @return list
144      */
145     public static List<String> sort(Set<String> col) {
146         List<String> results = new ArrayList<>();
147         results.addAll(col);
148         Collections.sort(results);
149         return results;
150     }
151
152     /**
153      * Flatten the json list.
154      *
155      * @param jsons
156      *            list json strings
157      * @return list
158      */
159     public static List<String> jsonFlatten(List<String> jsons) {
160         List<String> results = new ArrayList<>();
161         for (String json : jsons) {
162             try {
163                 results.add(JsonPath.parse(json).jsonString());
164             } catch (Exception e) { // NOSONAR
165                 results.add(json);
166             }
167         }
168
169         return results;
170     }
171
172     /**
173      * There are unique values like uuid is supported, so when input, output (default) values has
174      * these special entries, then it will get replaced with it's value
175      *
176      * @param line
177      * @return
178      */
179     public static String replaceLineForSpecialValues(String line) {
180         String result = "";
181
182         if (!line.contains("$s{")) {
183             return line;
184         }
185
186         int currentIdx = 0;
187         while (currentIdx < line.length()) {
188             int idxS = line.indexOf("$s{", currentIdx);
189             if (idxS == -1) {
190                 result += line.substring(currentIdx);
191                 break;
192             }
193             int idxE = line.indexOf("}", idxS);
194             String splEntry = line.substring(idxS + 3, idxE);
195             splEntry = splEntry.trim();
196
197             String value = "";
198
199             switch (splEntry) {
200                 case OnapCommandConstants.SPL_ENTRY_UUID:
201                     value = UUID.randomUUID().toString();
202                     break;
203
204                 default:
205
206                     if (splEntry.startsWith(OnapCommandConstants.SPL_ENTRY_ENV)) {
207                         //start to read after env:ENV_VAR_NAME
208                         String envVarName = splEntry.substring(4);
209                         value = System.getenv(envVarName);
210                         if (value == null) {
211                             //when env is not defined, assign the same env:ENV_VAR_NAME
212                             //so that it will given hit to user that ENV_VAR_NAME to be
213                             //defined.
214                             value = splEntry;
215                         }
216                     } else {
217                         value = splEntry;
218                     }
219             }
220
221             result += line.substring(currentIdx, idxS) + value;
222             currentIdx = idxE + 1;
223         }
224
225         return result;
226     }
227
228     public static String replaceLineFromInputParameters(String line, Map<String, OnapCommandParameter> params)
229             throws OnapCommandException {
230         String result = "";
231
232         if (!line.contains("${")) {
233             return line;
234         }
235
236         int currentIdx = 0;
237         while (currentIdx < line.length()) {
238             int idxS = line.indexOf("${", currentIdx);
239             if (idxS == -1) {
240                 result += line.substring(currentIdx);
241                 break;
242             }
243             int idxE = line.indexOf("}", idxS);
244             String paramName = line.substring(idxS + 2, idxE);
245             paramName = paramName.trim();
246             if (!params.containsKey(paramName)) {
247                 throw new OnapCommandParameterNotFound(paramName);
248             }
249
250             String value = params.get(paramName).getValue().toString();
251
252             OnapCommandParameter param = params.get(paramName);
253             if (OnapCommandParameterType.ARRAY.equals(param.getParameterType())
254                     || OnapCommandParameterType.MAP.equals(param.getParameterType())
255                     || OnapCommandParameterType.JSON.equals(param.getParameterType())
256                     || OnapCommandParameterType.YAML.equals(param.getParameterType())) {
257                 // ignore the front and back double quotes in json body
258                 result += line.substring(currentIdx, idxS - 1) + value;
259                 currentIdx = idxE + 2;
260             } else {
261                 result += line.substring(currentIdx, idxS) + value;
262                 currentIdx = idxE + 1;
263             }
264         }
265
266         return result;
267     }
268
269     /**
270      * Populate result from input parameters.
271      *
272      * @param resultMap
273      *            map
274      * @param params
275      *            Map<String, OnapCommandParameter>
276      * @return map
277      * @throws OnapCommandException
278      */
279     public static Map<String, ArrayList<String>> populateOutputsFromInputParameters(
280             Map<String, ArrayList<String>> resultMap,
281             Map<String, OnapCommandParameter> params)
282             throws OnapCommandException {
283         Map<String, ArrayList<String>> resultsProcessed = new HashMap<>();
284
285         for (Entry<String, ArrayList<String>> entry : resultMap.entrySet()) {
286             String key = entry.getKey();
287             resultsProcessed.put(key, new ArrayList<>());
288             for (String value: entry.getValue()) {
289                 try {
290                     value = replaceLineFromInputParameters(value, params);
291                 } catch(OnapCommandResultEmpty e) {
292                     // pass // NOSONAR
293                 }
294                 resultsProcessed.get(key).add(value);
295             }
296         }
297
298         return resultsProcessed;
299     }
300
301     /**
302      * Copy the parameters across the commands, mainly used for catalog, login and logout commands
303      *
304      * @throws OnapCommandInvalidParameterValue
305      */
306     public static void copyParamsFrom(OnapCommand from, OnapCommand to, Map<String, String> paramOverride) throws OnapCommandInvalidParameterValue {
307         for (OnapCommandParameter param: to.getParameters()) {
308
309             OnapCommandParameter fromParam = from.getParametersMap().get(param.getName());
310
311             if (fromParam != null) {
312                 param.setValue(fromParam.getValue());
313                 param.setDefaultValue(fromParam.getDefaultValue());
314             }
315
316             if (paramOverride.containsKey(param.getName())) {
317                  param.setValue(paramOverride.get(param.getName()));
318             }
319         }
320     }
321
322     public static void copyParamsFrom(OnapCommand from, OnapCommand to) throws OnapCommandInvalidParameterValue {
323         copyParamsFrom(from, to, new HashMap<String, String>());
324     }
325
326     /**
327      * Copy param schema from source command to destination command, useful in adding login command params into command
328      * @param from
329      * @param to
330      * @throws OnapCommandException
331      */
332     public static void copyParamSchemasFrom(OnapCommand from, OnapCommand to) throws OnapCommandException {
333         for (OnapCommandParameter param: from.getParameters()) {
334             if (!to.getParametersMap().containsKey(param.getName())) {
335                 to.getParameters().add(param);
336             }
337         }
338     }
339 }
340