2 * Copyright 2017 Huawei Technologies Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.onap.cli.fw.utils;
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;
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;
30 import java.util.Map.Entry;
32 import java.util.UUID;
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;
47 import com.fasterxml.jackson.core.JsonProcessingException;
48 import com.fasterxml.jackson.databind.ObjectMapper;
49 import com.jayway.jsonpath.JsonPath;
52 * Provides helper method to parse Yaml files and produce required objects.
55 public class OnapCommandUtils {
57 static Logger log = LoggerFactory.getLogger(OnapCommandUtils.class);
59 * Private constructor.
61 private OnapCommandUtils() {
65 public static void throwOrCollect(OnapCommandException ex, List<String> list, boolean shouldCollectException)
66 throws OnapCommandException {
67 if (shouldCollectException) {
68 list.add(ex.getMessage());
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);
82 if (!isYamlContains && isInclude) {
83 schemaErrors.add("Mandatory attribute '" + param + "' is missing under '" + section + "'");
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");
102 public static boolean validateBoolean(String toValidate) {
103 return OnapCommandConfig.getCommaSeparatedList(BOOLEAN_VALUE).contains(toValidate.toLowerCase());
106 public static String emptySection(String section) {
107 return "The section '" + section + ":' cann't be null or empty";
110 public static String invalidBooleanValueMessage(String section, String attribute, String value) {
111 return "The value '" + value + "' of '" + attribute + "' present under '" + section + "' should be boolean";
114 public static void parseParameters(String line, Set<String> paramNames) {
117 while (currentIdx < line.length()) {
118 int idxS = line.indexOf("${", currentIdx);
122 int idxE = line.indexOf("}", idxS);
123 String paramName = line.substring(idxS + 2, idxE);
124 paramNames.add(paramName.trim());
126 currentIdx = idxE + 1;
132 * Create Dict from list of Parameters.
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);
153 public static List<String> sort(Set<String> col) {
154 List<String> results = new ArrayList<>();
156 Collections.sort(results);
161 * Flatten the json list.
167 public static List<String> jsonFlatten(List<String> jsons) {
168 List<String> results = new ArrayList<>();
169 for (String json : jsons) {
171 results.add(JsonPath.parse(json).jsonString());
172 } catch (Exception e) { // NOSONAR
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
187 public static String replaceLineForSpecialValues(String lineSpl) {
188 String resultSpl = "";
190 if (!lineSpl.contains("$s{")) {
195 while (currentIdx < lineSpl.length()) {
196 int idxS = lineSpl.indexOf("$s{", currentIdx);
198 resultSpl += lineSpl.substring(currentIdx);
201 int idxE = lineSpl.indexOf("}", idxS);
202 String splEntry = lineSpl.substring(idxS + 3, idxE);
203 splEntry = splEntry.trim();
208 case OnapCommandConstants.SPL_ENTRY_UUID:
209 value = UUID.randomUUID().toString();
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);
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
224 } else if (splEntry.startsWith(OnapCommandConstants.SPL_ENTRY_FILE)) {
225 //start to read after file:filepath
226 String fileName = splEntry.substring(5);
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
240 resultSpl += lineSpl.substring(currentIdx, idxS) + value;
241 currentIdx = idxE + 1;
247 public static String replaceLineFromInputParameters(String line, Map<String, OnapCommandParameter> params)
248 throws OnapCommandException {
251 if (!line.contains("${")) {
256 while (currentIdx < line.length()) {
257 int idxS = line.indexOf("${", currentIdx);
259 result += line.substring(currentIdx);
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);
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())) {
278 String value = new ObjectMapper().writeValueAsString(params.get(paramName).getValue());
279 if ((idxS == 0) && (currentIdx == 0)) {
282 result += line.substring(currentIdx, idxS - 1) + value;
284 } catch (JsonProcessingException e) { // NOSONAR
285 //never occur as map is coverted to json string here
288 currentIdx = idxE + 2;
290 result += line.substring(currentIdx, idxS) + params.get(paramName).getValue().toString();
291 currentIdx = idxE + 1;
299 * Populate result from input parameters.
304 * Map<String, OnapCommandParameter>
306 * @throws OnapCommandException
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<>();
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()) {
319 value = replaceLineFromInputParameters(value, params);
320 } catch(OnapCommandResultEmpty e) { // NOSONAR
323 resultsProcessed.get(key).add(value);
327 return resultsProcessed;
331 * Copy the parameters across the commands, mainly used for catalog, login and logout commands
333 * @throws OnapCommandInvalidParameterValue
335 public static void copyParamsFrom(OnapCommand from, OnapCommand to, Map<String, String> paramOverride) throws OnapCommandInvalidParameterValue {
336 for (OnapCommandParameter param: to.getParameters()) {
338 OnapCommandParameter fromParam = from.getParametersMap().get(param.getName());
340 if (fromParam != null) {
341 param.setValue(fromParam.getValue());
342 param.setDefaultValue(fromParam.getDefaultValue());
345 if (paramOverride.containsKey(param.getName())) {
346 param.setValue(paramOverride.get(param.getName()));
351 public static void copyParamsFrom(OnapCommand from, OnapCommand to) throws OnapCommandInvalidParameterValue {
352 copyParamsFrom(from, to, new HashMap<String, String>());
356 * Copy param schema from source command to destination command, useful in adding login command params into command
359 * @throws OnapCommandException
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);