Sonar Fixes
[policy/apex-pdp.git] / auth / cli-editor / src / main / java / org / onap / policy / apex / auth / clieditor / utils / CliUtils.java
1 /*-
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
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.auth.clieditor.utils;
22
23 import com.google.gson.JsonObject;
24 import java.beans.PropertyDescriptor;
25 import java.io.File;
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;
43
44 /**
45  * This class contains the utility methods specifically for Apex CLI Editor.
46  *
47  * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
48  */
49 public class CliUtils {
50     private static final Logger LOGGER = LoggerFactory.getLogger(CliUtils.class);
51
52     // Recurring string constants
53     private static final String OF_TYPE_TAG = " of type ";
54     private static final int MAX_HELP_LINE_LENGTH = 120;
55
56     /**
57      * Private constructor to prevent sub-classing.
58      */
59     private CliUtils() {
60         // This class cannot be initialized
61     }
62
63     /**
64      * Method to create apex policy in TOSCA service template.
65      *
66      * @param parameters containing paths to the apex config and tosca template skeleton file
67      * @param policyModelFilePath path of apex policy model
68      */
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);
78
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();
83
84         apexConfigJson.entrySet().forEach(entry -> {
85             if ("engineServiceParameters".equals(entry.getKey())) {
86                 entry.getValue().getAsJsonObject().add("policy_type_impl", policyModelJson);
87             }
88             toscaProperties.add(entry.getKey(), entry.getValue());
89         });
90         final String toscaPolicyString = standardCoder.encode(toscaTemplateJson);
91         final String toscaPolicyFileName = parameters.getOutputToscaPolicyFileName();
92         if (StringUtils.isNotBlank(toscaPolicyFileName)) {
93             TextFileUtils.putStringAsTextFile(toscaPolicyString, toscaPolicyFileName);
94         } else {
95             LOGGER.debug("Output file name not specified. Resulting tosca policy is {}", toscaPolicyString);
96         }
97     }
98
99     /**
100      * Validate that a file is readable.
101      *
102      * @param fileTag the file tag, a tag used for information and error messages
103      * @param fileName the file name to check
104      */
105     public static void validateReadableFile(final String fileTag, final String fileName) {
106         if (fileName == null) {
107             return;
108         }
109         final File theFile = new File(fileName);
110         final String prefixExceptionMessage = "File " + fileName + OF_TYPE_TAG + fileTag;
111
112         if (!theFile.exists()) {
113             throw new CommandLineException(prefixExceptionMessage + " does not exist");
114         }
115         if (!theFile.isFile()) {
116             throw new CommandLineException(prefixExceptionMessage + " is not a normal file");
117         }
118         if (!theFile.canRead()) {
119             throw new CommandLineException(prefixExceptionMessage + " is ureadable");
120         }
121     }
122
123     /**
124      * Validate that a file is writable.
125      *
126      * @param fileTag the file tag, a tag used for information and error messages
127      * @param fileName the file name to check
128      */
129     public static void validateWritableFile(final String fileTag, final String fileName) {
130         if (fileName == null) {
131             return;
132         }
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");
138             }
139             if (!theFile.canWrite()) {
140                 throw new CommandLineException(prefixExceptionMessage + " cannot be written");
141             }
142         } else {
143             try {
144                 if (!theFile.getParentFile().exists()) {
145                     theFile.getParentFile().mkdirs();
146                 }
147                 if (theFile.createNewFile()) {
148                     LOGGER.info("File {} does not exist. New file created.", fileName);
149                 }
150             } catch (final IOException e) {
151                 throw new CommandLineException(prefixExceptionMessage + " cannot be created: ", e);
152             }
153         }
154     }
155
156     /**
157      * Validate that a directory exists and is writable.
158      *
159      * @param directoryTag the directory tag, a tag used for information and error messages
160      * @param directoryName the directory name to check
161      */
162     public static void validateWritableDirectory(final String directoryTag, final String directoryName) {
163         if (directoryName == null) {
164             return;
165         }
166         final File theDirectory = new File(directoryName);
167         final String prefixExceptionMessage = "directory " + directoryName + OF_TYPE_TAG + directoryTag;
168
169         if (theDirectory.exists()) {
170             if (!theDirectory.isDirectory()) {
171                 throw new CommandLineException(prefixExceptionMessage + " is not a directory");
172             }
173             if (!theDirectory.canWrite()) {
174                 throw new CommandLineException(prefixExceptionMessage + " cannot be written");
175             }
176         } else {
177             if (!theDirectory.mkdir()) {
178                 throw new CommandLineException(prefixExceptionMessage + " doesn't exist and cannot be created.");
179             }
180         }
181     }
182
183     /**
184      * Print help information.
185      *
186      * @param mainClassName the main class name
187      * @param options the options for cli editor
188      */
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, "");
192     }
193
194     /**
195      * Method to generate arguments required for APEX CLI editor.
196      *
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
201      */
202     public static List<String> generateArgumentsForCliEditor(CommandLineParameters parameters,
203             Properties optionVariableMap, Class<?> class1) {
204
205         List<String> cliArgsList = new ArrayList<>();
206         PropertyDescriptor pd;
207         Method getter;
208         Object argValue;
209
210         for (Entry<Object, Object> entry : optionVariableMap.entrySet()) {
211             try {
212                 pd = new PropertyDescriptor(entry.getValue().toString(), class1);
213                 getter = pd.getReadMethod();
214                 argValue = getter.invoke(parameters);
215                 String key = entry.getKey().toString();
216
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);
222                 }
223             } catch (Exception e) {
224                 LOGGER.error("Invalid getter method for the argument specfied.", e);
225             }
226         }
227         return cliArgsList;
228     }
229 }