protected void run() throws OnapCommandException {
Map<String, String> map = new HashMap<>();
- for (String input: Arrays.asList(new String []{"request-id", "product", "service", "command", "profile", "start-time", "end-time"})) {
+ for (String input: Arrays.asList("request-id", "product", "service", "command", "profile", "start-time", "end-time")) {
String value = getParametersMap().get(input).getValue().toString();
if (value != null && !value.isEmpty()) {
map.put(input, value);
if (stream != null) {
Map<String, ?> map = OnapCommandDiscoveryUtils.loadYaml(stream);
Map<String, String> productMap = (Map<String, String>) map.get("product");
- String description = (String) productMap.get(OnapCommandConstants.DESCRIPTION);
+ String description = productMap.get(OnapCommandConstants.DESCRIPTION);
this.getResult().getRecordsMap().get("description").getValues().add(description.trim());
} else {
this.getResult().getRecordsMap().get("description").getValues().add("");
public List<String> getValues() {
if (this.values.isEmpty() && !this.defaultValue.isEmpty()) {
- return Arrays.asList(new String [] {this.defaultValue});
+ return Arrays.asList(this.defaultValue);
}
return values;
}
* @return boolean
*/
public static boolean isTabularForm(String type) {
- if (type.equalsIgnoreCase(TABLE.name())) {
- return true;
- }
-
- return false;
+ return type.equalsIgnoreCase(TABLE.name());
}
/**
public Object getJsonNodeOrString(String value) {
try {
- return (JSONObject) JSONValue.parse(value);
+ return JSONValue.parse(value);
} catch (Exception e) {
return value;
}
for (int cellIndex = 0; cellIndex < row.size(); cellIndex++) {
Object cell = row.get(cellIndex);
String finalCell = "";
- if (cell != null && cell instanceof List) {
+ if (cell instanceof List) {
List<String> list = (List<String>) cell;
if (splitCellIndex < list.size()) {
finalCell = list.get(splitCellIndex);
IS_OPTIONAL, String.valueOf(parameter.get(key2))));
}
- if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) {
- param.setOptional(true);
- } else {
- param.setOptional(false);
- }
+ param.setOptional(BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2))));
break;
case IS_SECURED:
}
}
- if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) {
- param.setSecured(true);
- } else {
- param.setSecured(false);
- }
+ param.setSecured(BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2))));
break;
case IS_INCLUDE:
IS_INCLUDE, String.valueOf(parameter.get(key2))));
}
- if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) {
- param.setInclude(true);
- } else {
- param.setInclude(false);
- }
+ param.setInclude(BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2))));
break;
case IS_DEFAULT_PARAM:
}
}
- if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) {
- param.setDefaultParam(true);
- } else {
- param.setDefaultParam(false);
- }
+ param.setDefaultParam(BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2))));
break;
}
}
IS_SECURED, String.valueOf(map.get(key4))));
}
}
- if (BOOLEAN_TRUE.equals(String.valueOf(map.get(key4)))) {
- attr.setSecured(true);
- } else {
- attr.setSecured(false);
- }
+ attr.setSecured(BOOLEAN_TRUE.equals(String.valueOf(map.get(key4))));
break;
case IS_DEFAULT_ATTR:
IS_DEFAULT_ATTR, String.valueOf(map.get(key4))));
}
}
- if (BOOLEAN_TRUE.equals(String.valueOf(map.get(key4)))) {
- attr.setDefaultAttr(true);
- } else {
- attr.setDefaultAttr(false);
- }
+ attr.setDefaultAttr(BOOLEAN_TRUE.equals(String.valueOf(map.get(key4))));
break;
}
private static String SEPARATOR = "__";
private enum SearchMode {
- find,
- file //for developer mode
+ FIND,
+ FILE //for developer mode
}
- private static SearchMode SEARCH_MODE = SearchMode.file;
+ private static SearchMode SEARCH_MODE = SearchMode.FILE;
static {
String mode = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_EXECUTION_SEARCH_MODE);
- if (mode.equalsIgnoreCase(SearchMode.find.name()))
- SEARCH_MODE = SearchMode.find;
+ if (mode.equalsIgnoreCase(SearchMode.FIND.name()))
+ SEARCH_MODE = SearchMode.FIND;
}
public static class ExecutionStoreContext {
try {
List <String> dirs = new ArrayList<>();
- if (System.getProperty("os.name").toLowerCase().startsWith("windows") || SEARCH_MODE.equals(SearchMode.file)) {
+ if (System.getProperty("os.name").toLowerCase().startsWith("windows") || SEARCH_MODE.equals(SearchMode.FILE)) {
for (File f: new File(getBasePath()).listFiles()) {
if(search.containsKey(EXECUTIONID)) {
if (f.getName().startsWith(search.get(EXECUTIONID)))
searchString.append("*");
}
- for (String term: Arrays.asList(new String []{"product", "service", "command", "profile"})) {
+ for (String term: Arrays.asList("product", "service", "command", "profile")) {
searchString.append("__");
if (search.get(term) != null && !search.get(term).isEmpty()) {
searchString.append(search.get(term));
@Override
public boolean accept(File dir, String name) {
- if (name.startsWith(executionId)) return true;
- return false;
+ return name.startsWith(executionId);
}
});
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import com.esotericsoftware.yamlbeans.YamlReader;
-import com.esotericsoftware.yamlbeans.YamlException;
-
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
public static OnapCommandSchemaInfo getSchemaInfo(String cmd, String version) throws OnapCommandException {
List<OnapCommandSchemaInfo> list = OnapCommandDiscoveryUtils.discoverOrLoadSchemas(false);
OnapCommandSchemaInfo schemaInfo = null;
- if (list != null) {
+ if (list != null) { //NOSONAR
for (OnapCommandSchemaInfo schema : list) {
if (cmd.equals(schema.getCmdName()) && version.equals(schema.getProduct())) {
schemaInfo = schema;
*/
public static Resource findResource(String fileName, String pattern) throws IOException {
Resource[] resources = OnapCommandDiscoveryUtils.findResources(pattern);
- if (resources != null && resources.length > 0) {
+ if (resources != null && resources.length > 0) { //NOSONAR
for (Resource res : resources) {
if (res.getFilename().equals(fileName)) {
return res;
//default_input_parameters_http.yaml
String profileName = resource.getFilename().substring(
DEAFULT_INPUT_PARAMETERS_NAME.length() + 1,
- resource.getFilename().indexOf("."));
+ resource.getFilename().indexOf('.'));
if (deafultResourceMap.containsKey(PARAMETERS)) {
List<Object> params = new ArrayList<>();
for (Map<String, ?> p: (List<Map<String, ?>>) deafultResourceMap.get(PARAMETERS)) {
OnapCommandSchemaInfo schemaInfo = getSchemaInfo(cmd, version);
List<String> sampleFiles = new ArrayList<>();
- if (schemaInfo != null && !schemaInfo.getSampleFiles().isEmpty()) {
+ if (schemaInfo != null && !schemaInfo.getSampleFiles().isEmpty()) { //NOSONAR
sampleFiles.addAll(schemaInfo.getSampleFiles());
}
try(InputStreamReader inputStreamReader = new InputStreamReader(inputStream);){
YamlReader reader = new YamlReader(inputStreamReader);
values = (Map<String, ?>) reader.read();
- } catch (YamlException e) {
- throw new OnapCommandInvalidSchema(inputStream.getClass().getName(),e.getMessage());
} catch (IOException e) {
throw new OnapCommandInvalidSchema(inputStream.getClass().getName(),e.getMessage());
}
resultTable.getRecords().add(attrHelp);
}
- if (cmd.getResult().getRecords().size() > 0) {
+ if (!cmd.getResult().getRecords().isEmpty()) {
try {
help.append("\n\nResults::\n\n" + resultTable.print());
} catch (OnapCommandException e) {
if (idxS == -1) {
break;
}
- int idxE = line.indexOf("}", idxS);
+ int idxE = line.indexOf('}', idxS);
String paramName = line.substring(idxS + 2, idxE);
paramNames.add(paramName.trim());
resultLine.append(line.substring(currentIdx));
break;
}
- int idxE = line.indexOf("}", idxS);
+ int idxE = line.indexOf('}', idxS);
String attr = line.substring(idxS + 3, idxE);
attr = attr.trim();
resultSpl.append(lineSpl.substring(currentIdx));
break;
}
- int idxE = lineSpl.indexOf("}", idxS);
+ int idxE = lineSpl.indexOf('}', idxS);
String splEntry = lineSpl.substring(idxS + 3, idxE);
splEntry = splEntry.trim();
result.append(line.substring(currentIdx));
break;
}
- int idxE = line.indexOf("}", idxS);
+ int idxE = line.indexOf('}', idxS);
String paramName = line.substring(idxS + 2, idxE);
paramName = paramName.trim();
if (!params.containsKey(paramName)) {
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.nio.charset.StandardCharsets;
public class ProcessRunner {
private static Logger log = LoggerFactory.getLogger(ProcessRunner.class);
public void run() {
try {
IOUtils.copy(stdoutP, stdout);
- } catch (IOException e) {
+ } catch (IOException e) { // NOSONAR
}
}
});
public void run() {
try {
IOUtils.copy(stderrP, stderr);
- } catch (IOException e) {
+ } catch (IOException e) { // NOSONAR
}
}
});
}
if (readOutput)
- this.output = new String(((ByteArrayOutputStream)this.getStdout()).toByteArray(), "UTF-8");
+ this.output = new String(((ByteArrayOutputStream)this.getStdout()).toByteArray(), StandardCharsets.UTF_8);
if (readError)
- this.error = new String(((ByteArrayOutputStream)this.getStderr()).toByteArray(), "UTF-8");;
+ this.error = new String(((ByteArrayOutputStream)this.getStderr()).toByteArray(), StandardCharsets.UTF_8);
p.destroy();
UUID.fromString(attrValue.substring(4));
attr = sample.getResult().getRecordsMap().get("output-2");
attrValue = attr.getValues().get(0);
- assertEquals(attrValue, "test");
+ assertEquals("test", attrValue);
} catch (IllegalArgumentException e) {
fail("Failed to replace the output default value on output-1");
} catch (OnapCommandException e) {
package org.onap.cli.fw.conf;
+import org.junit.Test;
+
public class OnapCommandConfgTest {
+ @Test
+ public void addPropertiesTest() {
+
+ OnapCommandConfig.getPropertyValue("cli.schema.profile.confs");
+ }
+
}
assertTrue(errorList5.size() == 0);
}
+
+ @Test
+ public void validateAfterRemovingIfElseTest() throws OnapCommandException {
+ OnapCommand cmd2 = new OnapCommand() {
+ @Override
+ protected void run() throws OnapCommandException {
+
+ }
+ };
+ List < String > errorList2 = OnapCommandSchemaLoader.loadSchema(cmd2,
+ "schema-validate-basic-default-attr.yaml", true, true);
+ assertTrue(errorList2.size() > 0);
+ }
+
}
public void testMd5(){
assertNotNull(OnapCommandUtils.md5("a"));
}
+
+ @Test
+ public void replaceLineFromResults() {
+ Map<String, String> mapExample = new HashMap<String, String>();
+ mapExample.put("key1", "paramA");
+ mapExample.put("key2", "paramB");
+ OnapCommandUtils.replaceLineFromResults("line $r{paramA} line $r{paramB}", mapExample);
+ assertTrue(mapExample.get("key1").equals("paramA"));
+ assertTrue(mapExample.get("key2").equals("paramB"));
+ }
+
}
--- /dev/null
+# Copyright 2018 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.
+
+open_cli_schema_version: 1.0
+description: Register microservice into Onap
+name: schema-validate
+info:
+ product: open-cli
+ service: test
+ type: cmd
+ author: Sravan Kumar sravan.kumar1@huawei.com
+parameters:
+ - name: service-name1
+ description: Oclip service name
+ type: string
+ short_option: x
+ long_option: service-name
+ is_optional: false
+ - name: service-version
+ description: Oclip service version
+ type: string
+ short_option: y
+ long_option: service-version
+ is_optional: false
+ - name: service-url
+ description: Oclip service base url
+ type: url1
+ short_option: u
+ long_option: service-url
+ is_optional: false1
+ - name: status
+ description: Oclip service status
+ type: digit
+ short_option: z
+ long_option: service-version
+ is_optional: true
+ default_value: 1
+ - name: node-ip
+ description: Oclip service running node IP
+ type: string
+ - name: node-port
+ description: Oclip service running node port
+ type: string
+ - name: create-or-update
+ description: Oclip service create or update
+ type: cfbcv
+ default_value: true
+results:
+ direction: portrait1
+ attributes:
+ - name: name
+ description: Oclip service name
+ scope: short
+ type: string
+ is_default_attr: true
+ - name: version
+ description: Oclip service version
+ scope: short
+ type: string
+ is_default_attr: true
+ - name: status
+ description: Oclip service base url
+ scope: short
+ type: url
+ is_default_attr: true
+ - name: status
+ description: Oclip service status
+ scope: short1
+ type: digit
+ is_default_attr: true
+ - name: nodes
+ description: Oclip service running nodes
+ scope: long
+ type: string
+ is_default_attr: true
+ - name: location
+ description: Oclip service location
+ scope: long
+ type: url
+ is_default_attr: true
\ No newline at end of file
OpenInterfaceGrpcClient client = new OpenInterfaceGrpcClient(
host, port, timeout);
try {
- Result result = client.remoteCli(Args.newBuilder().setRequestId(this.requestId).addAllArgs(args).build());
- return result;
+ return client.remoteCli(Args.newBuilder().setRequestId(this.requestId).addAllArgs(args).build());
} finally {
client.shutdown();
}
params.put("format", "json");
Input input = Input.newBuilder().setAction(action).setRequestId(requestId).putAllOptions(options).putAllParams(params).build();
- Output output = client.invoke(input);
- return output;
+ return client.invoke(input);
} finally {
client.shutdown();
}
host, port);
try {
- Result result = client.remoteCli(Args.newBuilder().setRequestId(reqId).addAllArgs(args).build());
- return result;
+ return client.remoteCli(Args.newBuilder().setRequestId(reqId).addAllArgs(args).build());
} finally {
client.shutdown();
}
params.put("format", "json");
Input input = Input.newBuilder().setAction(action).setRequestId(reqId).putAllOptions(options).putAllParams(params).build();
- Output output = client.invoke(input);
- return output;
+ return client.invoke(input);
} finally {
client.shutdown();
}
private String outputs = "";
+ @Override
public void print(String msg) {
outputs += msg + "\n";
}
import org.onap.cli.fw.cmd.OnapCommand;
import org.onap.cli.fw.error.OnapCommandException;
import org.onap.cli.fw.schema.OnapCommandSchema;
+import org.onap.cli.fw.input.OnapCommandParameter;
+import org.onap.cli.fw.registrar.OnapCommandRegistrar;
+import java.util.HashSet;
+import java.util.Set;
+import org.junit.Test;
+import org.onap.cli.fw.conf.OnapCommandConstants;
/**
* This command helps to test the Command functionalities.
}
+ @Test
+ public void sampleTestVersion() throws OnapCommandException {
+
+ Set < OnapCommandParameter > parameters = new HashSet < > ();
+ OnapCommandParameter version = new OnapCommandParameter();
+ version.setName(OnapCommandConstants.DEFAULT_PARAMETER_VERSION);
+ version.setValue(true);
+ parameters.add(version);
+ OnapCommandParameter hlp = new OnapCommandParameter();
+ hlp.setName(OnapCommandConstants.DEFAULT_PARAMETER_HELP);
+ hlp.setValue(false);
+ parameters.add(hlp);
+
+ OnapCommand sample = OnapCommandRegistrar.getRegistrar().get("sample-test");
+ sample.setParameters(parameters);
+ sample.execute();
+ }
+
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.onap.cli.fw.utils.OnapCommandUtils;
import org.onap.cli.fw.utils.ProcessRunner;
-import com.google.gson.Gson;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import net.minidev.json.JSONArray;
-import net.minidev.json.JSONObject;
/**
* Hello world.
ProcessRunner pr = new ProcessRunner(
cmd,
- (envs.size() > 0) ? envs.toArray(new String []{}) : null,
+ (!envs.isEmpty()) ? envs.toArray(new String []{}) : null,
cwd);
FileOutputStream stdoutStream = null;
FileOutputStream stderrStream = null;
}
//check for pass/failure
- if (!this.passCodes.isEmpty() && !this.passCodes.contains(pr.getExitCode())) {
- this.getResult().setPassed(false);
- } else {
- this.getResult().setPassed(true);
- }
+ this.getResult().setPassed(!(!this.passCodes.isEmpty() && !this.passCodes.contains(pr.getExitCode())));
}
public String getOutput() {
break;
}
- int idxE = line.indexOf("}", idxS);
+ int idxE = line.indexOf('}', idxS);
String tmpName = line.substring(idxS + 7, idxE);
tmpName = tmpName.trim();
- String tmpTkns[] = tmpName.split(":");
+ String[] tmpTkns = tmpName.split(":");
String tmpFileName;
String paramName;
if (tmpTkns.length == 2) {
break;
}
}
- int idxE = line.indexOf("}", idxS);
+ int idxE = line.indexOf('}', idxS);
String jsonPath = line.substring(idxS + 3, idxE);
jsonPath = jsonPath.trim();
Object value = new Object();
import org.onap.cli.fw.conf.OnapCommandConfig;
import org.onap.cli.fw.error.OnapCommandException;
import org.onap.cli.fw.utils.OnapCommandUtils;
+import java.util.stream.Collectors;
public class OnapCommandSchemaCmdLoader {
if (o instanceof List) {
cmd.setCommand((List<String>) o);
} else {
- cmd.setCommand(Arrays.asList(new String [] {(String) o}));
+ cmd.setCommand(Arrays.asList((String) o));
}
break;
break;
case OnapCommandCmdConstants.SUCCESS_EXIT_CODE:
- cmd.setSuccessStatusCodes((ArrayList) valMap.get(key1));
+ List<String> list = (ArrayList) valMap.get(key1);
+ cmd.setSuccessStatusCodes(list.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toList()));
break;
case OnapCommandCmdConstants.PASS_CODE:
//context param
public static final String CONTEXT = "context";
public static final String CONTEXT_REMOVE_EMPTY_JSON_NODES = "remove_empty_node";
- public static final String __BODY__ = "__body__";
+ public static final String __BODY__ = "__body__"; //NOSONAR
// moco server const
public static final String VERIFY_MOCO_HOST = "cli.verify.host";
} else {
String fileTag = (!input.getMultipartEntityName().isEmpty()) ? input.getMultipartEntityName() : "file";
File file = new File(input.getBody().trim());
- HttpEntity multipartEntity = MultipartEntityBuilder
+ return MultipartEntityBuilder
.create()
.addBinaryBody(fileTag, file, ContentType.create("application/octet-stream"), file.getName())
.build();
- return multipartEntity;
}
}
package org.onap.cli.fw.http.error;
-import org.onap.cli.fw.error.OnapCommandException;
import org.onap.cli.fw.error.OnapCommandWarning;
/**
for (Object part: multiparts ) {
HttpInput.Part partO = new HttpInput.Part();
Map<String, String> partMap = (Map<String, String>) part;
- partO.setName((String) partMap.get("name"));
- partO.setContent((String)partMap.get("content"));
+ partO.setName(partMap.get("name"));
+ partO.setContent(partMap.get("content"));
if (partMap.get("type") != null && ((String)partMap.get("type")).equalsIgnoreCase("file")) {
partO.setBinary(true);
}
values.put(param.getKey(), param.getValue().getValue().toString());
}
- if (input.getMultiparts().size() > 0) {
+ if (!input.getMultiparts().isEmpty()) {
for (HttpInput.Part part: input.getMultiparts()) {
part.setContent(OnapCommandUtils.replaceLineForSpecialValues(part.getContent(), values));
part.setContent(OnapCommandUtils.replaceLineFromInputParameters(part.getContent(), params));
headerProcessedLine.append(line.substring(currentIdx));
break;
}
- int idxE = line.indexOf("}", idxS);
+ int idxE = line.indexOf('}', idxS);
String headerName = line.substring(idxS + 3, idxE);
headerName = headerName.trim();
if (!resultHttp.getRespHeaders().containsKey(headerName)) {
import org.onap.cli.fw.error.OnapCommandResultMapProcessingFailed;
import org.onap.cli.fw.error.OnapCommandResultEmpty;
import static org.junit.Assert.assertFalse;
+import org.onap.cli.fw.http.connect.HttpInput;
+import org.onap.cli.fw.http.connect.HttpInput.Part;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OnapCommandUtilsTest {
+ "[\"3a2fb75b52a54e9c8093e7c154210f9e\"]}]}}}";
assertEquals(result, OnapCommandHttpUtils.normalizeJson(sample));
}
+
+ @Test
+ public void testPopulateParameters() throws OnapCommandException {
+ List <Part> multiparts = new ArrayList <HttpInput.Part> ();
+ Part part = new Part();
+ part.setContent("content");
+ multiparts.add(part);
+ Map <String, OnapCommandParameter> params = new HashMap <String, OnapCommandParameter> ();
+ OnapCommandParameter onapCommandParameter = new OnapCommandParameter();
+ onapCommandParameter.setName("CMD");
+ onapCommandParameter.setRawDefaultValue("value");
+ params.put("key", onapCommandParameter);
+ HttpInput httpInput = new HttpInput();
+ httpInput.setMultiparts(multiparts);
+ HttpInput input = OnapCommandHttpUtils.populateParameters(params, httpInput);
+ assertTrue(input != null);
+ }
+
}
*/
package org.onap.cli.http.mock;
-import java.io.File;
import java.io.IOException;
import java.util.Arrays;