2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019-2020 Nordix Foundation.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.apex.auth.clieditor.utils;
23 import com.google.gson.JsonObject;
24 import java.beans.PropertyDescriptor;
26 import java.io.IOException;
27 import java.lang.reflect.Method;
28 import java.util.ArrayList;
29 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.Properties;
32 import org.apache.commons.cli.HelpFormatter;
33 import org.apache.commons.cli.Options;
34 import org.apache.commons.lang3.StringUtils;
35 import org.onap.policy.apex.auth.clieditor.CommandLineException;
36 import org.onap.policy.apex.auth.clieditor.CommandLineParameters;
37 import org.onap.policy.apex.auth.clieditor.tosca.ApexCliToscaParameters;
38 import org.onap.policy.common.utils.coder.CoderException;
39 import org.onap.policy.common.utils.coder.StandardCoder;
40 import org.onap.policy.common.utils.resources.TextFileUtils;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
45 * This class contains the utility methods specifically for Apex CLI Editor.
47 * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
49 public class CliUtils {
50 private static final Logger LOGGER = LoggerFactory.getLogger(CliUtils.class);
52 // Recurring string constants
53 private static final String OF_TYPE_TAG = " of type ";
54 private static final int MAX_HELP_LINE_LENGTH = 120;
57 * Private constructor to prevent sub-classing.
60 // This class cannot be initialized
64 * Method to create apex policy in TOSCA service template.
66 * @param parameters containing paths to the apex config and tosca template skeleton file
67 * @param policyModelFilePath path of apex policy model
69 public static void createToscaServiceTemplate(ApexCliToscaParameters parameters, String policyModelFilePath)
70 throws IOException, CoderException {
71 final StandardCoder standardCoder = new StandardCoder();
72 String apexConfig = TextFileUtils.getTextFileAsString(parameters.getApexConfigFileName());
73 JsonObject apexConfigJson = standardCoder.decode(apexConfig, JsonObject.class);
74 String policyModel = TextFileUtils.getTextFileAsString(policyModelFilePath);
75 JsonObject policyModelJson = standardCoder.decode(policyModel, JsonObject.class);
76 String toscaTemplate = TextFileUtils.getTextFileAsString(parameters.getInputToscaTemplateFileName());
77 JsonObject toscaTemplateJson = standardCoder.decode(toscaTemplate, JsonObject.class);
79 JsonObject toscaPolicyProperties = toscaTemplateJson.get("topology_template").getAsJsonObject();
80 JsonObject toscaPolicy = toscaPolicyProperties.get("policies").getAsJsonArray().get(0).getAsJsonObject();
81 JsonObject toscaProperties = toscaPolicy.get(toscaPolicy.keySet().toArray()[0].toString()).getAsJsonObject()
82 .get("properties").getAsJsonObject();
84 apexConfigJson.entrySet().forEach(entry -> {
85 if ("engineServiceParameters".equals(entry.getKey())) {
86 entry.getValue().getAsJsonObject().add("policy_type_impl", policyModelJson);
88 toscaProperties.add(entry.getKey(), entry.getValue());
90 final String toscaPolicyString = standardCoder.encode(toscaTemplateJson);
91 final String toscaPolicyFileName = parameters.getOutputToscaPolicyFileName();
92 if (StringUtils.isNotBlank(toscaPolicyFileName)) {
93 TextFileUtils.putStringAsTextFile(toscaPolicyString, toscaPolicyFileName);
95 LOGGER.debug("Output file name not specified. Resulting tosca policy is {}", toscaPolicyString);
100 * Validate that a file is readable.
102 * @param fileTag the file tag, a tag used for information and error messages
103 * @param fileName the file name to check
105 public static void validateReadableFile(final String fileTag, final String fileName) {
106 if (fileName == null) {
109 final File theFile = new File(fileName);
110 final String prefixExceptionMessage = "File " + fileName + OF_TYPE_TAG + fileTag;
112 if (!theFile.exists()) {
113 throw new CommandLineException(prefixExceptionMessage + " does not exist");
115 if (!theFile.isFile()) {
116 throw new CommandLineException(prefixExceptionMessage + " is not a normal file");
118 if (!theFile.canRead()) {
119 throw new CommandLineException(prefixExceptionMessage + " is ureadable");
124 * Validate that a file is writable.
126 * @param fileTag the file tag, a tag used for information and error messages
127 * @param fileName the file name to check
129 public static void validateWritableFile(final String fileTag, final String fileName) {
130 if (fileName == null) {
133 final File theFile = new File(fileName);
134 final String prefixExceptionMessage = "File " + fileName + OF_TYPE_TAG + fileTag;
135 if (theFile.exists()) {
136 if (!theFile.isFile()) {
137 throw new CommandLineException(prefixExceptionMessage + " is not a normal file");
139 if (!theFile.canWrite()) {
140 throw new CommandLineException(prefixExceptionMessage + " cannot be written");
144 if (!theFile.getParentFile().exists()) {
145 theFile.getParentFile().mkdirs();
147 if (theFile.createNewFile()) {
148 LOGGER.info("File {} does not exist. New file created.", fileName);
150 } catch (final IOException e) {
151 throw new CommandLineException(prefixExceptionMessage + " cannot be created: ", e);
157 * Validate that a directory exists and is writable.
159 * @param directoryTag the directory tag, a tag used for information and error messages
160 * @param directoryName the directory name to check
162 public static void validateWritableDirectory(final String directoryTag, final String directoryName) {
163 if (directoryName == null) {
166 final File theDirectory = new File(directoryName);
167 final String prefixExceptionMessage = "directory " + directoryName + OF_TYPE_TAG + directoryTag;
169 if (theDirectory.exists()) {
170 if (!theDirectory.isDirectory()) {
171 throw new CommandLineException(prefixExceptionMessage + " is not a directory");
173 if (!theDirectory.canWrite()) {
174 throw new CommandLineException(prefixExceptionMessage + " cannot be written");
177 if (!theDirectory.mkdir()) {
178 throw new CommandLineException(prefixExceptionMessage + " doesn't exist and cannot be created.");
184 * Print help information.
186 * @param mainClassName the main class name
187 * @param options the options for cli editor
189 public static void help(final String mainClassName, Options options) {
190 final HelpFormatter helpFormatter = new HelpFormatter();
191 helpFormatter.printHelp(MAX_HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, "");
195 * Method to generate arguments required for APEX CLI editor.
197 * @param parameters the command line parameters
198 * @param optionVariableMap the properties object containing the option and corresponding variable name
199 * @param class1 the class type in which the variable names has to be looked for
200 * @return list of arguments
202 public static List<String> generateArgumentsForCliEditor(CommandLineParameters parameters,
203 Properties optionVariableMap, Class<?> class1) {
205 List<String> cliArgsList = new ArrayList<>();
206 PropertyDescriptor pd;
210 for (Entry<Object, Object> entry : optionVariableMap.entrySet()) {
212 pd = new PropertyDescriptor(entry.getValue().toString(), class1);
213 getter = pd.getReadMethod();
214 argValue = getter.invoke(parameters);
215 String key = entry.getKey().toString();
217 if (argValue instanceof String && !key.equals("o")) {
218 cliArgsList.add("-" + key);
219 cliArgsList.add(argValue.toString());
220 } else if (argValue instanceof Boolean && (boolean) argValue) {
221 cliArgsList.add("-" + key);
223 } catch (Exception e) {
224 LOGGER.error("Invalid getter method for the argument specfied.", e);