From 268be523fb1142138a3f710642b5773453841eeb Mon Sep 17 00:00:00 2001 From: "priyanka.akhade" Date: Thu, 18 Jun 2020 15:11:08 +0530 Subject: code improvements Signed-off-by: priyanka.akhade Issue-ID: CLI-270 Change-Id: If9eab4bc8642c7c20a841d58c8a9e2bf5ae6c98b --- .../execution/OnapCommandExceutionShowCommand.java | 32 ++-- .../cli/fw/registrar/OnapCommandRegistrar.java | 4 +- .../onap/cli/fw/schema/OnapCommandSchemaInfo.java | 4 +- .../cli/fw/store/OnapCommandArtifactStore.java | 14 +- .../cli/fw/store/OnapCommandExecutionStore.java | 161 +++++++++++---------- .../onap/cli/fw/store/OnapCommandProfileStore.java | 2 +- .../cli/fw/utils/OnapCommandDiscoveryUtils.java | 20 +-- .../onap/cli/fw/utils/OnapCommandHelperUtils.java | 41 ++---- .../org/onap/cli/fw/utils/OnapCommandUtils.java | 32 ++-- .../java/org/onap/cli/fw/utils/ProcessRunner.java | 10 +- .../OnapCommandExceutionShowCommandTest.java | 23 ++- .../onap/cli/fw/utils/OnapCommandUtilsTest.java | 14 ++ 12 files changed, 194 insertions(+), 163 deletions(-) (limited to 'framework/src') diff --git a/framework/src/main/java/org/onap/cli/fw/cmd/execution/OnapCommandExceutionShowCommand.java b/framework/src/main/java/org/onap/cli/fw/cmd/execution/OnapCommandExceutionShowCommand.java index 8d29c03f..d77c021a 100644 --- a/framework/src/main/java/org/onap/cli/fw/cmd/execution/OnapCommandExceutionShowCommand.java +++ b/framework/src/main/java/org/onap/cli/fw/cmd/execution/OnapCommandExceutionShowCommand.java @@ -60,27 +60,27 @@ public class OnapCommandExceutionShowCommand extends OnapCommand { } - public String printExecution(List executions) throws OnapCommandExecutionNotFound { - String msg = "\n"; + public String printExecution(List executions) throws OnapCommandExecutionNotFound { //NOSONAR + StringBuilder msg = new StringBuilder("\n"); for (OnapCommandExecutionStore.Execution e: executions) { - msg += "\n"; + msg.append("\n"); if ( e.getId() != null) - msg += "\n" + e.getId() + "\n"; - msg += "\n" + e.getProduct() + "\n"; - msg += "\n" + e.getService() + "\n"; - msg += "\n" + e.getCommand() + "\n"; + msg.append("\n" + e.getId() + "\n"); + msg.append("\n" + e.getProduct() + "\n"); + msg.append("\n" + e.getService() + "\n"); + msg.append("\n" + e.getCommand() + "\n"); if ( e.getProfile() != null) - msg += "\n" + e.getProfile() + "\n"; - msg += "\n" + e.getInput() + "\n"; + msg.append("\n" + e.getProfile() + "\n"); + msg.append("\n" + e.getInput() + "\n"); if ( e.getOutput() != null) - msg += "\n" + e.getOutput() + "\n"; - msg += "\n" + e.getStartTime() + "\n"; - msg += "\n" + e.getEndTime() + "\n"; - msg += "\n" + e.getStatus() + "\n"; - msg += ""; + msg.append("\n" + e.getOutput() + "\n"); + msg.append("\n" + e.getStartTime() + "\n"); + msg.append("\n" + e.getEndTime() + "\n"); + msg.append("\n" + e.getStatus() + "\n"); + msg.append(""); } - msg += ""; + msg.append(""); - return msg; + return msg.toString(); } } diff --git a/framework/src/main/java/org/onap/cli/fw/registrar/OnapCommandRegistrar.java b/framework/src/main/java/org/onap/cli/fw/registrar/OnapCommandRegistrar.java index 6771bfee..c23ed2bc 100644 --- a/framework/src/main/java/org/onap/cli/fw/registrar/OnapCommandRegistrar.java +++ b/framework/src/main/java/org/onap/cli/fw/registrar/OnapCommandRegistrar.java @@ -129,7 +129,7 @@ public class OnapCommandRegistrar { } this.registry.put(name + ":" + version, cmd); - log.info("REGISITER : " + name + ":" + version + " = " + cmd.getCanonicalName()); + log.info("REGISITER : {} : {} = {}", name, version, cmd.getCanonicalName()); this.availableProductVersions.add(version); } @@ -292,7 +292,7 @@ public class OnapCommandRegistrar { for (OnapCommandSchemaInfo schema : schemas) { if (schema.isIgnore()) { - log.info("Ignoring schema " + schema.getSchemaURI()); + log.info("Ignoring schema {}", schema.getSchemaURI()); continue; } diff --git a/framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaInfo.java b/framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaInfo.java index d87f4ef9..14032ef5 100644 --- a/framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaInfo.java +++ b/framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaInfo.java @@ -47,7 +47,7 @@ public class OnapCommandSchemaInfo implements Comparable private String product; - private List sampleFiles = new ArrayList(); + private List sampleFiles = new ArrayList<>(); /** * OCS version @@ -71,7 +71,7 @@ public class OnapCommandSchemaInfo implements Comparable private List outputs = new ArrayList<>(); - private Map metadata = new HashMap(); + private Map metadata = new HashMap<>(); private String description; diff --git a/framework/src/main/java/org/onap/cli/fw/store/OnapCommandArtifactStore.java b/framework/src/main/java/org/onap/cli/fw/store/OnapCommandArtifactStore.java index fa1d50fc..5938a11d 100644 --- a/framework/src/main/java/org/onap/cli/fw/store/OnapCommandArtifactStore.java +++ b/framework/src/main/java/org/onap/cli/fw/store/OnapCommandArtifactStore.java @@ -164,7 +164,7 @@ public class OnapCommandArtifactStore { return DatatypeConverter.printHexBinary(hash); } - public Artifact createArtifact(Artifact artifact) throws OnapCommandArtifactContentNotExist, OnapCommandArtifactAlreadyExist, OnapCommandArtifactContentChecksumNotMatch { + public Artifact createArtifact(Artifact artifact) throws OnapCommandArtifactContentNotExist, OnapCommandArtifactAlreadyExist, OnapCommandArtifactContentChecksumNotMatch { //NOSONAR if (!new File(artifact.getPath()).exists()) { throw new OnapCommandArtifactContentNotExist(artifact.getPath()); } @@ -187,7 +187,7 @@ public class OnapCommandArtifactStore { FileUtils.writeStringToFile(new File(storePath), gson.toJson(artifact)); } catch (Exception e) { // NOSONAR //It is expected that this never occurs - log.error("Failed to store the artifact at " + storePath); + log.error("Failed to store the artifact at {}", storePath); } return artifact; @@ -204,13 +204,13 @@ public class OnapCommandArtifactStore { return gson.fromJson(FileUtils.readFileToString(aFile), Artifact.class); } catch (Exception e) { // NOSONAR //It is expected that this never occurs - log.error("Failed to retrieve the artifact at " + storePath); + log.error("Failed to retrieve the artifact at {}", storePath); } return null; } - public List listArtifact(String category, String namePattern) throws OnapCommandArtifactNotFound { + public List listArtifact(String category, String namePattern) throws OnapCommandArtifactNotFound { //NOSONAR List artifacts = new ArrayList<>(); String searchPattern = ""; @@ -242,7 +242,7 @@ public class OnapCommandArtifactStore { artifacts.add(gson.fromJson(jsonReader, Artifact.class)); } catch (Exception e) { // NOSONAR //It is expected that this never occurs - log.error("While seraching Failed to retrieve the artifact at " + file.getAbsolutePath()); + log.error("While seraching Failed to retrieve the artifact at {}", file.getAbsolutePath()); } } @@ -256,7 +256,7 @@ public class OnapCommandArtifactStore { throw new OnapCommandArtifactNotFound(name, category); } if(!aFile.delete()){ - log.error("Failed to delete the artifact " + aFile.getAbsolutePath()); + log.error("Failed to delete the artifact {}", aFile.getAbsolutePath()); } } @@ -316,7 +316,7 @@ public class OnapCommandArtifactStore { } } catch (Exception e) { // NOSONAR //It is expected that this never occurs - log.error("Failed to update the artifact at " + existingStorePath); + log.error("Failed to update the artifact at {}", existingStorePath); } return artifact; } diff --git a/framework/src/main/java/org/onap/cli/fw/store/OnapCommandExecutionStore.java b/framework/src/main/java/org/onap/cli/fw/store/OnapCommandExecutionStore.java index a22eb084..9e230ff3 100644 --- a/framework/src/main/java/org/onap/cli/fw/store/OnapCommandExecutionStore.java +++ b/framework/src/main/java/org/onap/cli/fw/store/OnapCommandExecutionStore.java @@ -40,6 +40,19 @@ public class OnapCommandExecutionStore { private static Logger log = LoggerFactory.getLogger(OnapCommandExecutionStore.class); private static boolean storeReady = false; + private static String REQUEST_ID = "requestId"; + private static String EXECUTION_ID = "executionId"; + private static String INPUT = "input"; + private static String STDOUT = "stdout"; + private static String STDERR = "stderr"; + private static String DEBUG = "debug"; + private static String IN_PROGRESS = "in-progress"; + private static String OUTPUT = "output"; + private static String ERROR = "error"; + private static String COMPLETED = "completed"; + private static String FAILED = "failed"; + private static String EXECUTIONID = "execution-id"; + private static String REQUESTID = "request-id"; private SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US); @@ -222,30 +235,30 @@ public class OnapCommandExecutionStore { context.setStorePath(dir.getAbsolutePath()); if (product != null) - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "product"), product); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + OnapCommandConstants.INFO_PRODUCT), product); if (service != null) - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "service"), service); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + OnapCommandConstants.INFO_SERVICE), service); if (cmd != null) - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "command"), cmd); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + OnapCommandConstants.RPC_CMD), cmd); - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "requestId"), requestId); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + REQUEST_ID), requestId); - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "executionId"), executionId); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + EXECUTION_ID), executionId); if (input != null) - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "input"), input); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + INPUT), input); if (profile != null) { context.setProfile(profile); - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "profile"), profile); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + OnapCommandConstants.RPC_PROFILE), profile); } - FileUtils.touch(new File(context.getStorePath() + File.separator + "stdout")); - FileUtils.touch(new File(context.getStorePath() + File.separator + "stderr")); - FileUtils.touch(new File(context.getStorePath() + File.separator + "debug")); + FileUtils.touch(new File(context.getStorePath() + File.separator + STDOUT)); + FileUtils.touch(new File(context.getStorePath() + File.separator + STDERR)); + FileUtils.touch(new File(context.getStorePath() + File.separator + DEBUG)); - FileUtils.touch(new File(context.getStorePath() + File.separator + "in-progress")); + FileUtils.touch(new File(context.getStorePath() + File.separator + IN_PROGRESS)); } catch (IOException e) { - log.error("Failed to store the execution start details " + storePath); + log.error("Failed to store the execution start details {}", storePath); } return context; @@ -257,21 +270,21 @@ public class OnapCommandExecutionStore { try { if (output != null) - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "output"), output); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + OUTPUT), output); if (error != null) - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "error"), error); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + ERROR), error); if (debug != null) - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "debug"), debug); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + DEBUG), debug); if (passed) - FileUtils.touch(new File(context.getStorePath() + File.separator + "completed")); + FileUtils.touch(new File(context.getStorePath() + File.separator + COMPLETED)); else - FileUtils.touch(new File(context.getStorePath() + File.separator + "failed")); + FileUtils.touch(new File(context.getStorePath() + File.separator + FAILED)); - if(!new File(context.getStorePath() + File.separator + "in-progress").delete()){ - log.error("Failed to delete "+ context.getStorePath() + File.separator + "in-progress"); + if(!new File(context.getStorePath() + File.separator + IN_PROGRESS).delete()){ + log.error("Failed to delete {}", context.getStorePath() + File.separator + IN_PROGRESS); } } catch (IOException e) { - log.error("Failed to store the execution end details " + context.storePath); + log.error("Failed to store the execution end details {}", context.storePath); } } @@ -281,13 +294,13 @@ public class OnapCommandExecutionStore { try { if (output != null) - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "output"), output); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + OUTPUT), output); if (error != null) - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "error"), error); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + ERROR), error); if (debug != null) - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "debug"), debug); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + DEBUG), debug); } catch (IOException e) { - log.error("Failed to store the execution end details " + context.storePath); + log.error("Failed to store the execution end details {}", context.storePath); } } @@ -297,10 +310,10 @@ public class OnapCommandExecutionStore { try { if (debug != null) { - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "debug"), debug); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + DEBUG), debug); } } catch (IOException e) { - log.error("Failed to store the execution debug details " + context.storePath); + log.error("Failed to store the execution debug details {}", context.storePath); } } @@ -310,10 +323,10 @@ public class OnapCommandExecutionStore { try { if (output != null) { - FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + "output"), output); + FileUtils.writeStringToFile(new File(context.getStorePath() + File.separator + OUTPUT), output); } } catch (IOException e) { - log.error("Failed to store the execution output details " + context.storePath); + log.error("Failed to store the execution output details {}", context.storePath); } } public List listExecutions(Map search) throws OnapCommandExecutionFailed { @@ -323,15 +336,15 @@ public class OnapCommandExecutionStore { List dirs = new ArrayList<>(); if (System.getProperty("os.name").toLowerCase().startsWith("windows") || SEARCH_MODE.equals(SearchMode.file)) { for (File f: new File(getBasePath()).listFiles()) { - if(search.containsKey("execution-id")) { - if (f.getName().startsWith(search.get("execution-id"))) + if(search.containsKey(EXECUTIONID)) { + if (f.getName().startsWith(search.get(EXECUTIONID))) dirs.add(f.getAbsolutePath()); continue; } - if(search.containsKey("request-id")) { - if (f.getName().startsWith(search.get("request-id"))) + if(search.containsKey(REQUESTID)) { + if (f.getName().startsWith(search.get(REQUESTID))) dirs.add(f.getAbsolutePath()); continue; @@ -344,42 +357,42 @@ public class OnapCommandExecutionStore { //find results -type d -newermt '2019-02-11 10:00:00' ! -newermt '2019-02-11 15:10:00' -name "*__*__profile-list*" //find 'results' -type d -newermt '2019-02-11T10:00:00.000' ! -newermt '2019-02-11T15:10:00.000' -name "*__*__profile*" - String searchString = "find " + new File(getBasePath()).getAbsolutePath() + " -type d "; + StringBuilder searchString = new StringBuilder("find " + new File(getBasePath()).getAbsolutePath() + " -type d "); String startTime = search.get("startTime"); if (startTime != null) { - searchString += " -newermt " + startTime ; + searchString.append(" -newermt " + startTime); } String endTime = search.get("endTime"); if (endTime != null) { - searchString += " ! -newermt " + endTime ; + searchString.append(" ! -newermt " + endTime); } - searchString += " -name \""; + searchString.append(" -name \""); - if(search.containsKey("execution-id")) { - searchString += search.get("execution-id"); - } else if(search.containsKey("request-id")) { - searchString += search.get("request-id") + "*"; + if(search.containsKey(EXECUTIONID)) { + searchString.append(search.get(EXECUTIONID)); + } else if(search.containsKey(REQUESTID)) { + searchString.append(search.get(REQUESTID) + "*"); } else { - searchString += "*"; + searchString.append("*"); } for (String term: Arrays.asList(new String []{"product", "service", "command", "profile"})) { - searchString += "__"; + searchString.append("__"); if (search.get(term) != null && !search.get(term).isEmpty()) { - searchString += search.get(term); + searchString.append(search.get(term)); } else { - searchString += "*"; + searchString.append("*"); } } - if (!searchString.endsWith("*")) - searchString += "*"; + if (!searchString.toString().endsWith("*")) + searchString.append("*"); - searchString += "\""; + searchString.append("\""); - ProcessRunner pr = new ProcessRunner(new String [] {searchString}, null, "."); + ProcessRunner pr = new ProcessRunner(new String [] {searchString.toString()}, null, "."); pr.setTimeout(10000); pr.overrideToUnix(); pr.run(); @@ -403,32 +416,32 @@ public class OnapCommandExecutionStore { private Execution makeExecution(String executionStorePath) throws IOException { OnapCommandExecutionStore.Execution exectuion = new OnapCommandExecutionStore.Execution(); - if (new File(executionStorePath + File.separator + "requestId").exists()) - exectuion.setRequestId(FileUtils.readFileToString(new File(executionStorePath + File.separator + "requestId"))); - if (new File(executionStorePath + File.separator + "executionId").exists()) - exectuion.setId(FileUtils.readFileToString(new File(executionStorePath + File.separator + "executionId"))); - exectuion.setProduct(FileUtils.readFileToString(new File(executionStorePath + File.separator + "product"))); - exectuion.setService(FileUtils.readFileToString(new File(executionStorePath + File.separator + "service"))); - exectuion.setCommand(FileUtils.readFileToString(new File(executionStorePath + File.separator + "command"))); - if (new File(executionStorePath + File.separator + "profile").exists()) - exectuion.setProfile(FileUtils.readFileToString(new File(executionStorePath + File.separator + "profile"))); - - exectuion.setInput(FileUtils.readFileToString(new File(executionStorePath + File.separator + "input"))); - exectuion.setStartTime(dateFormatter.format(new File(executionStorePath + File.separator + "input").lastModified())); - - if (new File(executionStorePath + File.separator + "in-progress").exists()) { - exectuion.setStatus("in-progress"); - } else if (new File(executionStorePath + File.separator + "completed").exists()) { - exectuion.setStatus("completed"); - if (new File(executionStorePath + File.separator + "output").exists()) { - exectuion.setOutput(FileUtils.readFileToString(new File(executionStorePath + File.separator + "output"))); - exectuion.setEndTime(dateFormatter.format(new File(executionStorePath + File.separator + "output").lastModified())); + if (new File(executionStorePath + File.separator + REQUEST_ID).exists()) + exectuion.setRequestId(FileUtils.readFileToString(new File(executionStorePath + File.separator + REQUEST_ID))); + if (new File(executionStorePath + File.separator + EXECUTION_ID).exists()) + exectuion.setId(FileUtils.readFileToString(new File(executionStorePath + File.separator + EXECUTION_ID))); + exectuion.setProduct(FileUtils.readFileToString(new File(executionStorePath + File.separator + OnapCommandConstants.INFO_PRODUCT))); + exectuion.setService(FileUtils.readFileToString(new File(executionStorePath + File.separator + OnapCommandConstants.INFO_SERVICE))); + exectuion.setCommand(FileUtils.readFileToString(new File(executionStorePath + File.separator + OnapCommandConstants.RPC_CMD))); + if (new File(executionStorePath + File.separator + OnapCommandConstants.RPC_PROFILE).exists()) + exectuion.setProfile(FileUtils.readFileToString(new File(executionStorePath + File.separator + OnapCommandConstants.RPC_PROFILE))); + + exectuion.setInput(FileUtils.readFileToString(new File(executionStorePath + File.separator + INPUT))); + exectuion.setStartTime(dateFormatter.format(new File(executionStorePath + File.separator + INPUT).lastModified())); + + if (new File(executionStorePath + File.separator + IN_PROGRESS).exists()) { + exectuion.setStatus(IN_PROGRESS); + } else if (new File(executionStorePath + File.separator + COMPLETED).exists()) { + exectuion.setStatus(COMPLETED); + if (new File(executionStorePath + File.separator + OUTPUT).exists()) { + exectuion.setOutput(FileUtils.readFileToString(new File(executionStorePath + File.separator + OUTPUT))); + exectuion.setEndTime(dateFormatter.format(new File(executionStorePath + File.separator + OUTPUT).lastModified())); } - } else if (new File(executionStorePath + File.separator + "failed").exists()) { - exectuion.setStatus("failed"); - if (new File(executionStorePath + File.separator + "error").exists()) { - exectuion.setOutput(FileUtils.readFileToString(new File(executionStorePath + File.separator + "error"))); - exectuion.setEndTime(dateFormatter.format(new File(executionStorePath + File.separator + "error").lastModified())); + } else if (new File(executionStorePath + File.separator + FAILED).exists()) { + exectuion.setStatus(FAILED); + if (new File(executionStorePath + File.separator + ERROR).exists()) { + exectuion.setOutput(FileUtils.readFileToString(new File(executionStorePath + File.separator + ERROR))); + exectuion.setEndTime(dateFormatter.format(new File(executionStorePath + File.separator + ERROR).lastModified())); } } @@ -470,7 +483,7 @@ public class OnapCommandExecutionStore { public String showExecutionDebug(String executionId) throws OnapCommandExecutionNotFound { try { - return FileUtils.readFileToString(new File (this.getExecutionDir(executionId).getAbsolutePath() + File.separator + "debug")); + return FileUtils.readFileToString(new File (this.getExecutionDir(executionId).getAbsolutePath() + File.separator + DEBUG)); } catch (IOException e) { return ""; } diff --git a/framework/src/main/java/org/onap/cli/fw/store/OnapCommandProfileStore.java b/framework/src/main/java/org/onap/cli/fw/store/OnapCommandProfileStore.java index 6455447e..139521e4 100644 --- a/framework/src/main/java/org/onap/cli/fw/store/OnapCommandProfileStore.java +++ b/framework/src/main/java/org/onap/cli/fw/store/OnapCommandProfileStore.java @@ -207,7 +207,7 @@ public class OnapCommandProfileStore { File file = new File(dataDir + File.separator + profile + DATA_PATH_PROFILE_JSON); if (file.exists()) { if(!file.delete()){ - log.error("Failed to delete profile "+file.getAbsolutePath()); + log.error("Failed to delete profile {}", file.getAbsolutePath()); } } } diff --git a/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandDiscoveryUtils.java b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandDiscoveryUtils.java index 23c825e2..7a4dc49f 100644 --- a/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandDiscoveryUtils.java +++ b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandDiscoveryUtils.java @@ -176,7 +176,7 @@ public class OnapCommandDiscoveryUtils { * @throws OnapCommandDiscoveryFailed * exception */ - public static boolean isAlreadyDiscovered() throws OnapCommandDiscoveryFailed { + public static boolean isAlreadyDiscovered() throws OnapCommandDiscoveryFailed { //NOSONAR String dataDir = OnapCommandDiscoveryUtils.getDataStorePath(); return new File(dataDir + File.separator + DISCOVERY_FILE).exists(); } @@ -338,14 +338,14 @@ public class OnapCommandDiscoveryUtils { Object obj = resourceMap.get(OPEN_CLI_SCHEMA_VERSION); if (obj == null) { - OnapCommandUtils.log.info("Invalid Schema yaml " + schema.getSchemaURI()); + OnapCommandUtils.log.info("Invalid Schema yaml {}", schema.getSchemaURI()); continue; } schema.setVersion(obj.toString()); if (!schema.getVersion().equalsIgnoreCase(OnapCommandConstants.OPEN_CLI_SCHEMA_VERSION_VALUE_1_0)) { - OnapCommandUtils.log.info("Unsupported Schema version found " + schema.getSchemaURI()); + OnapCommandUtils.log.info("Unsupported Schema version found {}", schema.getSchemaURI()); continue; } @@ -431,12 +431,12 @@ public class OnapCommandDiscoveryUtils { Object sampleVersion = infoMap.get(OPEN_CLI_SAMPLE_VERSION); if (sampleVersion == null) { - OnapCommandUtils.log.info("Invalid Sample yaml " + sampleResourse.getURI().toString()); + OnapCommandUtils.log.info("Invalid Sample yaml {}", sampleResourse.getURI()); return; } if (!sampleVersion.toString().equalsIgnoreCase(OnapCommandConstants.OPEN_CLI_SAMPLE_VERSION_VALUE_1_0)) { - OnapCommandUtils.log.info("Unsupported Sample version found " + sampleResourse.getURI().toString()); + OnapCommandUtils.log.info("Unsupported Sample version found {}", sampleResourse.getURI()); return; } @@ -485,12 +485,12 @@ public class OnapCommandDiscoveryUtils { public static List> createTestSuite(String cmd, String version) throws OnapCommandException { - ArrayList> testSamples = new ArrayList(); + ArrayList> testSamples = new ArrayList<>(); - List resources = new ArrayList(); + List resources = new ArrayList<>(); OnapCommandSchemaInfo schemaInfo = getSchemaInfo(cmd, version); - List sampleFiles = new ArrayList(); + List sampleFiles = new ArrayList<>(); if (schemaInfo != null && !schemaInfo.getSampleFiles().isEmpty()) { sampleFiles.addAll(schemaInfo.getSampleFiles()); } @@ -515,13 +515,13 @@ public class OnapCommandDiscoveryUtils { Map sample = samples.get(sampleId); - List inputArgs = new ArrayList(); + List inputArgs = new ArrayList<>(); if (sample.get(OnapCommandConstants.VERIFY_INPUT) != null) { inputArgs.addAll(Arrays.asList(sample.get(OnapCommandConstants.VERIFY_INPUT).trim().split(" "))); } inputArgs.add(OnapCommandConstants.VERIFY_LONG_OPTION); - HashMap map = new HashMap(); + HashMap map = new HashMap<>(); map.put(OnapCommandConstants.VERIFY_INPUT, inputArgs); map.put(OnapCommandConstants.VERIFY_OUPUT, sample.get(OnapCommandConstants.VERIFY_OUPUT)); map.put(OnapCommandConstants.VERIFY_MOCO, sample.get(OnapCommandConstants.VERIFY_MOCO)); diff --git a/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandHelperUtils.java b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandHelperUtils.java index 1387ea3d..323e9e76 100644 --- a/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandHelperUtils.java +++ b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandHelperUtils.java @@ -42,11 +42,8 @@ public class OnapCommandHelperUtils { */ public static String findLastBuildTime() { String impBuildDate = ""; - JarFile jar = null; - try - { - String path = OnapCommandUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath(); - jar = new JarFile(path); + String path = OnapCommandUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath(); + try(JarFile jar = new JarFile(path)){ Manifest manifest = jar.getManifest(); Attributes attributes = manifest.getMainAttributes(); @@ -56,14 +53,6 @@ public class OnapCommandHelperUtils { catch (IOException e) // NOSONAR { //Ignore it as it will never occur - } finally { - if (jar != null) { - try { - jar.close(); - } catch (IOException e) { // NOSONAR - //Ignore it as it will never occur - } - } } return impBuildDate; @@ -80,18 +69,18 @@ public class OnapCommandHelperUtils { */ public static String help(OnapCommand cmd) throws OnapCommandHelpFailed { - String help = "usage: oclip " + cmd.getName(); + StringBuilder help = new StringBuilder("usage: oclip " + cmd.getName()); // Add description - help += "\n\n" + cmd.getDescription(); + help.append("\n\n" + cmd.getDescription()); // Add info - help += "\n\nProduct: " + cmd.getInfo().getProduct(); - help += "\nService: " + cmd.getInfo().getService(); - help += "\nAuthor: " + cmd.getInfo().getAuthor(); + help.append("\n\nProduct: " + cmd.getInfo().getProduct()); + help.append("\nService: " + cmd.getInfo().getService()); + help.append("\nAuthor: " + cmd.getInfo().getAuthor()); // Add whole command - String commandOptions = ""; + StringBuilder commandOptions = new StringBuilder(); // Add parameters OnapCommandResult paramTable = new OnapCommandResult(); @@ -122,16 +111,16 @@ public class OnapCommandHelperUtils { String optFirstCol; if (newLineOptions == 3) { newLineOptions = 0; - commandOptions += "\n"; + commandOptions.append("\n"); } if (param.getShortOption() != null || param.getLongOption() != null) { optFirstCol = OnapCommandParameter.printShortOption(param.getShortOption()) + " | " + OnapCommandParameter.printLongOption(param.getLongOption()); - commandOptions += " [" + optFirstCol + "]"; + commandOptions.append(" [" + optFirstCol + "]"); } else { optFirstCol = param.getName(); - commandOptions += " <" + optFirstCol + ">"; + commandOptions.append(" <" + optFirstCol + ">"); } newLineOptions++; @@ -169,7 +158,7 @@ public class OnapCommandHelperUtils { } try { - help += "\n\nOptions::\n\n" + commandOptions + "\n\nwhere::\n\n" + paramTable.print(); + help.append("\n\nOptions::\n\n" + commandOptions.toString() + "\n\nwhere::\n\n" + paramTable.print()); } catch (OnapCommandException e) { throw new OnapCommandHelpFailed(e); } @@ -196,15 +185,15 @@ public class OnapCommandHelperUtils { if (cmd.getResult().getRecords().size() > 0) { try { - help += "\n\nResults::\n\n" + resultTable.print(); + help.append("\n\nResults::\n\n" + resultTable.print()); } catch (OnapCommandException e) { throw new OnapCommandHelpFailed(e); } } // Error - help += "\n\nError::\n\n On error, it prints ::::\n"; - return help; + help.append("\n\nError::\n\n On error, it prints ::::\n"); + return help.toString(); } } diff --git a/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandUtils.java b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandUtils.java index 2cd07ed8..814f5139 100644 --- a/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandUtils.java +++ b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandUtils.java @@ -200,7 +200,7 @@ public class OnapCommandUtils { * @return */ public static String replaceLineFromResults(String line, Map values) { - String resultLine = ""; + StringBuilder resultLine = new StringBuilder(); if (!line.contains("$r{")) { return line; @@ -210,7 +210,7 @@ public class OnapCommandUtils { while (currentIdx < line.length()) { int idxS = line.indexOf("$r{", currentIdx); if (idxS == -1) { - resultLine += line.substring(currentIdx); + resultLine.append(line.substring(currentIdx)); break; } int idxE = line.indexOf("}", idxS); @@ -225,15 +225,15 @@ public class OnapCommandUtils { value = attr; } - resultLine += line.substring(currentIdx, idxS) + value; + resultLine.append(line.substring(currentIdx, idxS) + value); currentIdx = idxE + 1; } - return resultLine; + return resultLine.toString(); } public static String replaceLineForSpecialValues(String lineSpl, Map values) { - String resultSpl = ""; + StringBuilder resultSpl = new StringBuilder(); if (!lineSpl.contains("$s{")) { return lineSpl; @@ -243,7 +243,7 @@ public class OnapCommandUtils { while (currentIdx < lineSpl.length()) { int idxS = lineSpl.indexOf("$s{", currentIdx); if (idxS == -1) { - resultSpl += lineSpl.substring(currentIdx); + resultSpl.append(lineSpl.substring(currentIdx)); break; } int idxE = lineSpl.indexOf("}", idxS); @@ -297,16 +297,16 @@ public class OnapCommandUtils { } } - resultSpl += lineSpl.substring(currentIdx, idxS) + value; + resultSpl.append(lineSpl.substring(currentIdx, idxS) + value); currentIdx = idxE + 1; } - return resultSpl; + return resultSpl.toString(); } public static String replaceLineFromInputParameters(String line, Map params) throws OnapCommandException { - String result = ""; + StringBuilder result = new StringBuilder(); if (!line.contains("${")) { return line; @@ -316,7 +316,7 @@ public class OnapCommandUtils { while (currentIdx < line.length()) { int idxS = line.indexOf("${", currentIdx); if (idxS == -1) { - result += line.substring(currentIdx); + result.append(line.substring(currentIdx)); break; } int idxE = line.indexOf("}", idxS); @@ -333,17 +333,17 @@ public class OnapCommandUtils { // ignore the front and back double quotes in json body String va_ = params.get(paramName).getValue().toString(); if (idxS > 0) - result += line.substring(currentIdx, idxS - 1) + va_; + result.append(line.substring(currentIdx, idxS - 1) + va_); else - result += va_; + result.append(va_); currentIdx = idxE + 2; } else if (OnapCommandParameterType.MAP.equals(param.getParameterType())) { try { String value = gson.toJson(params.get(paramName).getValue()); if ((idxS == 0) && (currentIdx == 0)) { - result = value; + result.replace(0, result.length(), value); } else { - result += line.substring(currentIdx, idxS - 1) + value; + result.append(line.substring(currentIdx, idxS - 1) + value); } } catch (Exception e) { // NOSONAR //never occur as map is coverted to json string here @@ -351,12 +351,12 @@ public class OnapCommandUtils { currentIdx = idxE + 2; }else { - result += line.substring(currentIdx, idxS) + params.get(paramName).getValue().toString(); + result.append(line.substring(currentIdx, idxS) + params.get(paramName).getValue().toString()); currentIdx = idxE + 1; } } - return result; + return result.toString(); } /** diff --git a/framework/src/main/java/org/onap/cli/fw/utils/ProcessRunner.java b/framework/src/main/java/org/onap/cli/fw/utils/ProcessRunner.java index 69906aba..bb37c470 100644 --- a/framework/src/main/java/org/onap/cli/fw/utils/ProcessRunner.java +++ b/framework/src/main/java/org/onap/cli/fw/utils/ProcessRunner.java @@ -99,7 +99,7 @@ public class ProcessRunner { if (this.cmd.length == 1) { p = Runtime.getRuntime().exec(this.shell + this.cmd[0], this.env, workingDirectory); //NOSONAR } else { - List list = new ArrayList(Arrays.asList(this.shell.split(" "))); + List list = new ArrayList<>(Arrays.asList(this.shell.split(" "))); list.addAll(Arrays.asList(this.cmd)); String []cmds = Arrays.copyOf(list.toArray(), list.size(), String[].class); p = Runtime.getRuntime().exec(cmds, this.env, workingDirectory); //NOSONAR @@ -160,12 +160,8 @@ public class ProcessRunner { p.destroy(); - log.debug("CMD: " + Arrays.asList(this.cmd).toString() + - "\nWORKING_DIR: " + this.cwd + - "\nENV: " + ((this.env == null) ? this.env : Arrays.asList(this.env).toString()) + - "\nOUTPUT: " + this.output + - "\nERROR: " + this.error + - "\nEXIT_CODE: " + this.exitCode); + log.debug("CMD: {} \nWORKING_DIR: {} \nENV: {} \nOUTPUT: {} \nERROR: {} \nEXIT_CODE: {}", + Arrays.asList(this.cmd), this.cwd, ((this.env == null) ? this.env : Arrays.asList(this.env)), this.output, this.error, this.exitCode); if (!completed) { throw new RuntimeException("TIMEOUT:: cmd:" + Arrays.asList(this.cmd).toString()); diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/execution/OnapCommandExceutionShowCommandTest.java b/framework/src/test/java/org/onap/cli/fw/cmd/execution/OnapCommandExceutionShowCommandTest.java index 5d83374c..741b53a1 100644 --- a/framework/src/test/java/org/onap/cli/fw/cmd/execution/OnapCommandExceutionShowCommandTest.java +++ b/framework/src/test/java/org/onap/cli/fw/cmd/execution/OnapCommandExceutionShowCommandTest.java @@ -25,7 +25,10 @@ import org.onap.cli.fw.store.OnapCommandExecutionStoreTest; import java.io.File; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; +import mockit.Mock; +import mockit.MockUp; +import org.onap.cli.fw.store.OnapCommandExecutionStore; public class OnapCommandExceutionShowCommandTest { @BeforeClass @@ -46,7 +49,23 @@ public static void setUp() throws Exception { assertTrue(oclipCommandResultAttributes.size() > 1); } - + @Test + public void runTestForStringBuilder() throws OnapCommandException { + new MockUp(){ + @Mock + public String getOutput() { + return "oclip-request-output"; + } + }; + OnapCommandExceutionShowCommand cmd=new OnapCommandExceutionShowCommand(); + cmd.initializeSchema("execution-show.yaml"); + cmd.getParametersMap().get("execution-id").setValue("requestId"); + cmd.getParametersMap().get("format").setValue("TEXT"); + cmd.execute(); + List oclipCommandResultAttributes = cmd.getResult() + .getRecords(); + assertTrue(oclipCommandResultAttributes.size() > 1); + } @AfterClass public static void tearDown() throws Exception { String dirPathForExecutions = System.getProperty("user.dir") + File.separator + "data/executions"; diff --git a/framework/src/test/java/org/onap/cli/fw/utils/OnapCommandUtilsTest.java b/framework/src/test/java/org/onap/cli/fw/utils/OnapCommandUtilsTest.java index 9c31747b..e01c3878 100644 --- a/framework/src/test/java/org/onap/cli/fw/utils/OnapCommandUtilsTest.java +++ b/framework/src/test/java/org/onap/cli/fw/utils/OnapCommandUtilsTest.java @@ -131,6 +131,20 @@ public class OnapCommandUtilsTest { assertEquals("line", replacedLine); } + @Test + public void replaceLineFromResultsTest() { + String replacedLine = OnapCommandUtils.replaceLineFromResults("line", new HashMap<>()); + assertEquals("line", replacedLine); + replacedLine = OnapCommandUtils.replaceLineFromResults("${}", new HashMap<>()); + assertEquals("${}", replacedLine); + replacedLine = OnapCommandUtils.replaceLineFromResults("$r{}", new HashMap<>()); + assertTrue( replacedLine.isEmpty()); + HashMap values = new HashMap<>(); + values.put("This is test line","This is test line"); + replacedLine = OnapCommandUtils.replaceLineFromResults("$r{This is test line}", values); + assertEquals("This is test line", replacedLine); + } + @Test public void replaceLineForSpecialValues_replacingUuid() { String replacedLine = OnapCommandUtils.replaceLineForSpecialValues("$s{uuid}"); -- cgit 1.2.3-korg