@Override
protected void run() throws OnapCommandException {
-
+ // Dummy Method
}
}
--- /dev/null
+/*
+ * Copyright 2020 Huawei Technologies Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onap.cli.fw.error;
+
+public class OnapCommandTimeOutException extends RuntimeException {
+ private static final long serialVersionUID = -4280521008892487435L;
+
+ public OnapCommandTimeOutException(String message) {
+ super(message);
+ }
+}
try {
return new JsonParser().parse(array.toJSONString()).toString();
} catch (Exception e) { // NOSONAR
- // TODO Auto-generated catch block
return array.toJSONString();
}
private static Logger log = LoggerFactory.getLogger(OnapCommandArtifactStore.class);
private static Gson gson = new GsonBuilder().serializeNulls().create();
- private static boolean storeReady = false;
+ private static boolean storeReady = false; //NOSONAR
private SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
searchPattern += ".json";
- final String SP = searchPattern;
+ final String SP = searchPattern; //NOSONAR
for (File file: new File(getBasePath()).listFiles(/*new FilenameFilter() {
@Override
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());
+ String fileAbsPath = file.getAbsolutePath();
+ log.error("While seraching Failed to retrieve the artifact at {}", fileAbsPath);
}
}
try {
Files.delete(Paths.get(storePath));
} catch (IOException e) {
- log.error("Failed to delete the artifact " + aFile.getAbsolutePath());
+ log.error("Failed to delete the artifact {}", aFile.getAbsolutePath());
}
}
else
FileUtils.touch(new File(context.getStorePath() + File.separator + FAILED));
Path path= Paths.get(context.getStorePath() + File.separator + IN_PROGRESS);
- try {
- Files.delete(path);
- } catch (IOException e) {
- log.error("Failed to delete "+ context.getStorePath() + File.separator + IN_PROGRESS);
- }
+ deleteFile(context, path);
} catch (IOException e) {
log.error("Failed to store the execution end details {}", context.storePath);
}
}
+ private void deleteFile(ExecutionStoreContext context, Path path){
+ try {
+ Files.delete(path);
+ } catch (IOException e) {
+ String contextPath = context.getStorePath() + File.separator + IN_PROGRESS;
+ log.error("Failed to delete {}", contextPath);
+ }
+ }
+
public void storeExectutionProgress(
ExecutionStoreContext context,
String output, String error, String debug) {
try {
Files.delete(Paths.get(dataDir + File.separator + profile + DATA_PATH_PROFILE_JSON));
} catch (IOException e) {
- log.error("Failed to delete profile {}"+file.getAbsolutePath());
- }
+ String fileAbsPath = file.getAbsolutePath();
+ log.error("Failed to delete profile {}", fileAbsPath);
+ }
}
public List<String> getProfiles() {
Map<String, ?> deafultResourceMap;
for (Resource resource : deafultRres) {
- try {
- deafultResourceMap = loadYaml(resource);
- } catch (OnapCommandException e) {
- OnapCommandUtils.log.error("Ignores invalid schema " + resource.getURI().toString(), e);
- continue;
- }
+ deafultResourceMap = loadYaml(resource, true);
if (deafultResourceMap != null && deafultResourceMap.size() > 0) {
//default_input_parameters_http.yaml
if (res != null && res.length > 0) {
for (Resource resource : res) {
Map<String, ?> resourceMap;
- try {
+ try { //NOSONAR
resourceMap = loadYaml(resource);
} catch (OnapCommandException e) {
- OnapCommandUtils.log.error("Ignores invalid schema " + resource.getURI().toString(), e);
+ String resourceURI = resource.getURI().toString();
+ OnapCommandUtils.log.error("Ignores invalid schema {} {}", resourceURI, e);
continue;
}
Object obj = resourceMap.get(OPEN_CLI_SCHEMA_VERSION);
if (obj == null) {
- OnapCommandUtils.log.info("Invalid Schema yaml {}" + schema.getSchemaURI());
+ String schemaURI = schema.getSchemaURI();
+ OnapCommandUtils.log.info("Invalid Schema yaml {}", schemaURI);
}
else{
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());
+ String schemaURI = schema.getSchemaURI();
+ OnapCommandUtils.log.info("Unsupported Schema version found {} " + schemaURI);
}
else{
return values;
}
+ /**
+ * Get schema map.
+ *
+ * @param resource
+ * resource obj
+ * ignoreInvalidSchema boolean
+ * @return map
+ * @throws OnapCommandInvalidSchema
+ * exception
+ */
+ public static Map<String, ?> loadYaml(Resource resource, boolean ignoreInvalidSchema) throws OnapCommandInvalidSchema, IOException {
+ Map<String, ?> values = null;
+ try {
+ values = loadYaml(resource.getInputStream());
+ } catch (OnapCommandException | IOException e) {
+ OnapCommandUtils.log.error("Ignores invalid schema {} {}", resource.getURI(), e);
+ }
+ return values;
+ }
+
/**
* Get schema map.
*
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
+import org.onap.cli.fw.error.OnapCommandTimeOutException;
public class ProcessRunner {
private static Logger log = LoggerFactory.getLogger(ProcessRunner.class);
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());
+ throw new OnapCommandTimeOutException("TIMEOUT:: cmd:" + Arrays.asList(this.cmd).toString());
}
}
import org.onap.cli.fw.output.OnapCommandResultAttribute;
import org.onap.cli.fw.registrar.OnapCommandRegistrar;
+import org.onap.cli.fw.output.OnapCommandResult;
+import static org.junit.Assert.assertNotNull;
+
public class OnapCommandSampleTest {
@Test
public void sampleTestVersion() {
OnapCommand sample = OnapCommandRegistrar.getRegistrar().get("sample-test");
sample.setParameters(parameters);
sample.execute();
+ OnapCommandResult onapCommandResult = sample.execute();
+ assertEquals("open-cli::test",onapCommandResult.getOutput());
} catch (OnapCommandException e) {
}
}
OnapCommandSample sample = new OnapCommandSample();
sample.setParameters(parameters);
sample.execute();
+ OnapCommandResult onapCommandResult = sample.execute();
+ assertNotNull(onapCommandResult);
} catch (OnapCommandException e) {
}
}
import org.onap.cli.fw.registrar.OnapCommandRegistrar;
import org.onap.cli.fw.schema.ValidateSchemaTest;
+import org.onap.cli.fw.output.OnapCommandResult;
+import static org.junit.Assert.assertNotNull;
public class OnapSchemaValidateCommandTest {
cmd.getParametersMap().get("schema-location").setValue("schema-validate-pass.yaml");
cmd.getParametersMap().get("internal-schema").setValue("true");
cmd.execute();
+ OnapCommandResult onapCommandResult = cmd.execute();
+ assertNotNull(onapCommandResult.getOutput());
}
@Ignore
ValidateSchemaTest.class.getClassLoader().getResource("schema-validate-pass.yaml").getFile());
cmd.getParametersMap().get("internal-schema").setValue("true");
cmd.execute();
+ OnapCommandResult onapCommandResult = cmd.execute();
+ assertNotNull(onapCommandResult);
}
}
import org.junit.Test;
import org.onap.cli.fw.store.OnapCommandProfileStore;
+import static org.junit.Assert.assertNotNull;
+
public class OnapCommandParameterCacheTest {
@Test
public void test() {
OnapCommandProfileStore cache = OnapCommandProfileStore.getInstance();
+ assertNotNull(cache);
}
package org.onap.cli.fw.input.cache;
-import static org.junit.Assert.assertTrue;
-
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
+import static org.junit.Assert.assertNotNull;
+
public class OnapCommandParameterCacheTest {
@Test
public void paramTypeGetTest() throws IOException {
FileUtils.forceMkdir(new File("data"));
FileUtils.touch(new File("data" + File.separator + "test-profile.json"));
+ File test_profile = new File("data" + File.separator + "test-profile.json");
+ FileUtils.touch(test_profile);
+ assertNotNull(test_profile.lastModified());
//assertTrue(OnapCommandProfileStore.getInstance().getProfiles().contains("test"));
// FileUtils.cleanDirectory(new File("data"));
}
// Will be handled after the json print is implemented
String result = res.print();
+ assertEquals("[{\"param\":{\"id\":\"0001\",\"value\":\"result\"}}]",result);
// String expRes = "+--------+\n|param |\n+--------+\n|value
// |\n+--------+\n";
// assertEquals(expRes,result);
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
import java.io.File;
@Test
public void oclipCommandNotFoundTest() throws OnapCommandException {
+ registerar = OnapCommandRegistrar.getRegistrar();
try {
- registerar = OnapCommandRegistrar.getRegistrar();
registerar.get("Test1");
fail("This should have thrown an exception");
} catch (OnapCommandNotFound e) {
@Test
public void listTest() {
- registerar.listCommands();
+ assertFalse(registerar.listCommands().isEmpty());
}
@Test
OnapCommandRegistrar registrar = OnapCommandRegistrar.getRegistrar();
OnapCommand cmd = registrar.get("sample-test");
cmd.printVersion();
- registrar.listCommands();
+ assertFalse(registerar.listCommands().isEmpty());
}
@Test
public void getTestSuiteTest() throws OnapCommandException {
import org.onap.cli.fw.error.OnapCommandInvalidSchema;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
public class ValidateSchemaTest {
@Test(expected = OnapCommandInvalidSchema.class)
@Override
protected void run() throws OnapCommandException {}
};
- cmd.initializeSchema("test-command-to-valdiate-merge.yaml", true);
+ assertTrue(cmd.initializeSchema("test-command-to-valdiate-merge.yaml", true).isEmpty());
}
@Test(expected = OnapCommandInvalidSchema.class)
protected void run() throws OnapCommandException {}
};
OnapCommandSchemaLoader.loadSchema(cmd, "schema-invalid-file-null.yaml", true, true);
+ fail("OnapCommandInvalidSchema exception occurs");
}
@Test
protected void run() throws OnapCommandException {}
};
OnapCommandSchemaLoader.loadSchema(cmd, "schema-validate-pass.yaml", true, true);
-
+ List<String> list = OnapCommandSchemaLoader.loadSchema(cmd, "schema-validate-pass.yaml", true, true);
+ assertTrue(list.isEmpty());
}
@Test(expected = OnapCommandInvalidSchema.class)
@Test
public void addTest() {
onapCommandProfileStore.add("abc", "abc", "abc");
+ assertNotNull(onapCommandProfileStore. getParams("abc"));
}
@Test
String actualResult = OnapCommandHelperUtils.help(cmd);
String expectedHelp = FileUtil.loadResource("sample-cmd-test-help.txt");
-
+ assertNotNull(actualResult);
//mrkanag compare the result
}
OnapCommandSampleInfo cmd = new OnapCommandSampleInfo();
OnapCommandSchemaLoader.loadSchema(cmd, "sample-test-info.yaml", true, false);
OnapCommandInfo info = cmd.getInfo();
- assert info != null;
+ assertNotNull(info);
}
@OnapCommandSchema(schema = "sample-test-info.yaml")
System.out.println(pr.getOutput());
System.out.println(pr.getError());
System.out.println(pr.getExitCode());
+ assertEquals(0, pr.getExitCode());
pr = new ProcessRunner(new String [] {"dir", "c:"}, null);
pr.run();
}
public Result remoteCli(Args args) throws OpenInterfaceGrpcTimeoutExecption {
- logger.info(args.toString());
+ logger.info("{}", args);
Result result = Result.newBuilder().setExitCode(1).build();
try {
}
- public Result run (List <String> args) throws Exception {
+ public Result run (List <String> args) throws Exception { //NOSONAR
OpenInterfaceGrpcClient client = new OpenInterfaceGrpcClient(
host, port, timeout);
try {
}
}
- public Output invoke (String product, String profile, String action, Map <String, String> params) throws Exception {
+ public Output invoke (String product, String profile, String action, Map <String, String> params) throws Exception { //NOSONAR
OpenInterfaceGrpcClient client = new OpenInterfaceGrpcClient(
host, port, timeout);
try {
* @return
* @throws Exception
*/
- public static Result run (String host, int port, String reqId, List <String> args) throws Exception {
+ public static Result run (String host, int port, String reqId, List <String> args) throws Exception { //NOSONAR
OpenInterfaceGrpcClient client = new OpenInterfaceGrpcClient(
host, port);
* @return
* @throws Exception
*/
- public static Output invoke (String host, int port, String product, String profile, String action, String reqId, Map <String, String> params) throws Exception {
+ public static Output invoke (String host, int port, String product, String profile, String action, String reqId, Map <String, String> params) throws Exception { //NOSONAR
OpenInterfaceGrpcClient client = new OpenInterfaceGrpcClient(
host, port);
// use the status from the plugin.
reply.setSuccess(cmd.getResult().isPassed());
- try {
- reply.putAttrs(OnapCommandConstants.RESULTS, new JsonParser().parse(printOut).toString());
- } catch (Exception e) { // NOSONAR
- reply.putAttrs(OnapCommandConstants.RESULTS, printOut);
- }
+ setOutputAttr(reply, printOut);
output = reply.build();
logger.info("{}", output);
responseObserver.onCompleted();
}
+ public static void setOutputAttr(Builder reply, String printOut){
+ try {
+ reply.putAttrs(OnapCommandConstants.RESULTS, new JsonParser().parse(printOut).toString());
+ } catch (Exception e) { // NOSONAR
+ reply.putAttrs(OnapCommandConstants.RESULTS, printOut);
+ }
+ }
+
@Override
public void remoteCli(Args req, StreamObserver<Result> responseObserver) {
logger.info("{}", req);
</execution>
</executions>
</plugin>
- <!-- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-enforcer-plugin</artifactId>
- <version>1.4.1</version>
- <executions>
- <execution>
- <id>enforce</id>
- <goals>
- <goal>enforce</goal>
- </goals>
- <configuration>
- <rules>
- <requireUpperBoundDeps/>
- </rules>
- </configuration>
- </execution>
- </executions>
- </plugin> -->
</plugins>
<pluginManagement>
<plugins>
* Handles batch command. --param-file
*/
public void handleBatchCommand() {
- try {
+ try { //NOSONAR
if (this.paramFile != null) {
//Read YAML and loop thru it
// one
this.args = new ArrayList<>();
this.args.addAll(Arrays.asList(line.split(OnapCliConstants.PARAM_INTERACTIVE_ARG_SPLIT_PATTERN)));
- if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_USE)) {
- if (args.size() == 1) {
- this.print("Please use it in the form of use <product-version>.\nSupported versions: " +
- OnapCommandRegistrar.getRegistrar().getAvailableProductVersions());
- } else {
- try {
+ if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_USE)) {
+ if (args.size() == 1) {
+ this.print("Please use it in the form of use <product-version>.\nSupported versions: " +
+ OnapCommandRegistrar.getRegistrar().getAvailableProductVersions());
+ } else {
OnapCommandRegistrar.getRegistrar().setEnabledProductVersion(args.get(1));
console = createConsoleReader();
- } catch (OnapCommandException e) {
- this.print(e);
}
- }
- } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_HELP)) {
- this.print(OnapCommandRegistrar.getRegistrar().getHelpForEnabledProductVersion());
- this.print(OnapCli.getDirectiveHelp());
+ } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_HELP)) {
+ this.print(OnapCommandRegistrar.getRegistrar().getHelpForEnabledProductVersion());
+ this.print(OnapCli.getDirectiveHelp());
} else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_VERSION)) {
this.printVersion = true;
handleVersion();
}
int positionalIdx = 0;
- for (int i = 0; i < args.size(); i++) {
+ int i = 0;
+ while ( i < args.size()) {
String paramName = null;
if (shortOptionMap.containsKey(args.get(i))) {
paramName = shortOptionMap.get(args.get(i));
if ((i + 1) == args.size() || args.get(i + 1).startsWith("-")) {
if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.BOOL)) {
paramMap.get(paramName).setValue(true);
+ i+=2;
continue;
}
throw new OnapCliArgumentValueMissing(args.get(i));
if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.JSON)) {
paramMap.get(paramName).setValue(readJsonStringFromUrl(args.get(i + 1),
paramMap.get(paramName).getName()));
- i++;
+ i+=2;
continue;
} else if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.TEXT)) {
paramMap.get(paramName).setValue(readTextStringFromUrl(args.get(i + 1),
paramMap.get(paramName).getName()));
- i++;
+ i+=2;
continue;
} else if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.YAML)) {
String value = readYamlStringFromUrl(args.get(i + 1),
paramMap.get(paramName).getName());
paramMap.get(paramName).setValue(value);
- i++;
+ i+=2;
continue;
} else if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.BYTE)) {
paramMap.get(paramName).setValue(readBytesFromUrl(args.get(i + 1),
paramMap.get(paramName).getName()));
- i++;
+ i+=2;
continue;
} else if (paramMap.get(paramName).getParameterType()
list.add(readTextStringFromUrl(args.get(i + 1), paramMap.get(paramName).getName()));
paramMap.get(paramName).setValue(list);
- i++;
+ i+=2;
continue;
} else if (paramMap.get(paramName).getParameterType()
//map.put(argArr[0], readTextStringFromUrl(argArr[1], paramMap.get(paramName).getName()));
map.put(argArr[0], argArr[1]);
paramMap.get(paramName).setValue(map);
- i++;
+ i+=2;
continue;
}
paramMap.get(paramName).setValue(args.get(i + 1));
- i++;
+ i+=2;
continue;
}
paramMap.get(positionArgs.get(positionalIdx)).setValue(args.get(i));
positionalIdx++;
+ i+=2;
}
params.clear();
*/
public class OnapHttpConnection {
- private static Logger log = LoggerFactory.getLogger(OnapHttpConnection.class);
+ private static Logger log = LoggerFactory.getLogger(OnapHttpConnection.class); //NOSONAR
private CloseableHttpClient httpClient = null;
Map<String, ?> map = (Map<String, ?>) valMap.get(key1);
for (Map.Entry<String, ?> entry2 : map.entrySet()) {
- try {
+ try { //NOSONAR
String key2 = entry2.getKey();
switch (key2) {
<version>2.6</version>
</dependency>
</dependencies>
-<!-- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <version>2.9</version>
- <configuration>
- <useManifestOnlyJar>false</useManifestOnlyJar>
- <useSystemClassLoader>false</useSystemClassLoader>
- <additionalClasspathElements>
- <additionalClasspathElement>
- ${project.build.directory}/../../deployment/zip/target/deployunzip/lib/*.jar
- </additionalClasspathElement>
- </additionalClasspathElements>
- </configuration>
- </plugin>
- </plugins>
- </build> -->
<build><plugins>
<!--Step-2:- SonarCloud migration from SonarQube -->
<plugin>
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
+import static org.junit.Assert.assertFalse;
public class OnapValidationTest {
}
}
}
+ assertFalse(OnapCommandRegistrar.getRegistrar().getAvailableProductVersions().isEmpty());
}
@Test
}
}
}
+ assertFalse(OnapCommandRegistrar.getRegistrar().getAvailableProductVersions().isEmpty());
}
@Test