diff options
75 files changed, 2332 insertions, 635 deletions
diff --git a/deployment/docker/src/main/docker/docker-compose.yaml b/deployment/docker/src/main/docker/docker-compose.yaml index dfd3bb20..9ca3cf49 100644 --- a/deployment/docker/src/main/docker/docker-compose.yaml +++ b/deployment/docker/src/main/docker/docker-compose.yaml @@ -6,8 +6,8 @@ services: environment: OPEN_CLI_MODE: 'daemon' ports: - - 8080:80 - - 9090:8080 + - 30260:80 + - 30261:8080 cli: stdin_open: true @@ -25,3 +25,15 @@ services: OPEN_CLI_DEBUG: "true" ports: - 5005:5005 + + all: + image: onap/cli + environment: + OPEN_CLI_MODE: 'daemon' + OPEN_CLI_DEBUG: "true" + ports: + - 30260:80 + - 30261:8080 + - 5005:5005 + + diff --git a/deployment/zip/src/main/release/conf/open-cli.properties b/deployment/zip/src/main/release/conf/open-cli.properties index c15a84ce..9b5bceeb 100644 --- a/deployment/zip/src/main/release/conf/open-cli.properties +++ b/deployment/zip/src/main/release/conf/open-cli.properties @@ -28,5 +28,4 @@ cli.schema.profile.available=http,snmp #other properties to load (it should be hanled when plugins are made as externally register-able #when command plugin management support is enabled in oclip -cli.schema.profile.confs=open-cli-http.properties,open-cli-snmp.properties - +cli.schema.profile.confs=open-cli-http.properties,open-cli-snmp.properties
\ No newline at end of file diff --git a/deployment/zip/src/main/release/data/onap-beijing-profile.json b/deployment/zip/src/main/release/data/onap-beijing-profile.json new file mode 100644 index 00000000..0c186e11 --- /dev/null +++ b/deployment/zip/src/main/release/data/onap-beijing-profile.json @@ -0,0 +1,52 @@ +[ + { + "product" : "onap-beijing", + "name" : "aai:host-url", + "value" : "" + }, + { + "product" : "onap-beijing", + "name" : "aai:host-username", + "value" : "AAI" + }, + { + "product" : "onap-beijing", + "name" : "aai:host-password", + "value" : "AAI" + }, + { + "product" : "onap-beijing", + "name" : "msb:host-url", + "value" : "" + }, + { + "product" : "onap-beijing", + "name" : "sdc:host-url", + "value" : "" + }, + { + "product" : "onap-beijing", + "name" : "sdc:host-username", + "value" : "cs_0008" + }, + { + "product" : "onap-beijing", + "name" : "sdc:host-password", + "value" : "demo123456!" + }, + { + "product" : "onap-beijing", + "name" : "so:host-url", + "value" : "" + }, + { + "product" : "onap-beijing", + "name" : "so:host-username", + "value" : "InfraPortalClien" + }, + { + "product" : "onap-beijing", + "name" : "so:host-password", + "value" : "password1$" + } +]
\ No newline at end of file diff --git a/docs/open_cli_schema_version_1_0.rst b/docs/open_cli_schema_version_1_0.rst index 92e6bab2..15bfe201 100644 --- a/docs/open_cli_schema_version_1_0.rst +++ b/docs/open_cli_schema_version_1_0.rst @@ -775,6 +775,21 @@ the sample queries : q2: value2 + +context +^^^^^^^ +*context* entry allows to customize the HTTP request and response processing. + +Following are the supported customization parameters: + +*remove_empty_node* : By default, OCLIP does not remove the empty json entries + in request body. Otherwise set this entry to true as below. + + request: + + context: + remove_empty_node: true + success_codes ~~~~~~~~~~~~~ Every REST API has set of success codes and OCLIP will treat the HTTP request diff --git a/docs/user_guide.rst b/docs/user_guide.rst index a4203959..f4bde4b7 100644 --- a/docs/user_guide.rst +++ b/docs/user_guide.rst @@ -18,11 +18,11 @@ Configure the following environment variables, before using it: To Run a command ----------------- -Type **onap <command>** from linux console. +Type **oclip <command>** from linux console. To Run in Interactive mode -------------------------- -Type **onap** from linux/web console. +Type **oclip** from linux/web console. And use the directive set to set the values for following parameters: @@ -39,16 +39,82 @@ time. so to choose the product version, set environment variable NOTE: In interactive mode, product version can be selected using typing **use <product-version>** -Run *onap [-v|--version]* to see the CLI and available product version details +Run *oclip [-v|--version]* to see the CLI and available product version details -Set the parameter values ------------------------- -Use the directive 'set' for setting the values for parameters and 'unset' for reseting the values. +Profiling arguments +------------------- +In interactive mode, user can use profiles for for “set arguments value once and use it ever”. + +Please follow the steps given below for setting profiles: + +1. Open the CLI interactive console + +2. Create the profile, say ‘onap-deployment-1’ by running ‘profile onap-deployment-1’ +There is no limit in number of profiles. OCLIP will create a profile if not exist already, +otherwise on typing 'profile' on the console, corresponding profiles will be effective. +So you can switch across profiles by using this directive 'profile'. + +3. For example, to add the credentials, Run following steps: + +a. set host-url=<aai-url> + +b. set host-username=AAI + +c. set host-pasword=AAI + +d. Type 'set' to print all these arguments stored so far. + +NOTE: Profiles are not limited to set only credentials, you can set any frequently using +common arguments, which are listed in command help. + +NOTE: For setting service specific parameters, use in the form of <service-name>:<param-name>=<param-value>. +For example, following setting will be used only for aai service: + +a. set aai:host-url=<aai-url> + +b. set aai:host-username=AAI + +c. set aai:host-pasword=AAI + + +4. You can override these stored arguments by providing them as arguments directly while +running the CLI. + +5. Profile information is persisted, so when you disconnect and connect again the CLI console, +you can start use the same profile again. + +NOTE: Use the directive 'set' for setting the values for parameters and 'unset' for reseting the values. + +In Beijing release, new default profile named as 'onap-beijing' is delivered with all default ONAP service +credentials. so user could use this profile to avoid setting the credentials every time. + +Batching support & Parameter file +--------------------------------- +For a given scenario where, user wants to run a command with different set of inputs, this feature could be used. + +For example, in ONAP, user wants to register multiple clouds at a given time, so user can create a parameter file +as given below and capture inputs for one or more clouds: + +parameter file name: /usr/mrkanag/cloud-list.yaml + +cloud-1: + - name: cloud-region-1 + - description: Provides the test cloud environment +cloud-2: + - name: cloud-region-2 + - description: Provides the production cloud environment + +To register all these clouds in ONAP execute the cloud-register command with parameter file in inputs as below: + +onap -p /usr/mrkanag/cloud-list.yaml cloud-register + +Now OCLIP will iterate the command cloud-register for every cloud mentioned in the parameter file /usr/mrkanag/cloud-list.yaml. +When user use this approach to execute the command with multiple entries in parameter file is called as *batching*. Help ---- -*onap [-h|--help]* -*onap <command> [-h|--help]* +*oclip [-h|--help]* +*oclip <command> [-h|--help]* Debug Mode ---------- diff --git a/framework/src/main/java/org/onap/cli/fw/cmd/OnapCommand.java b/framework/src/main/java/org/onap/cli/fw/cmd/OnapCommand.java index 8db3ab79..2a5956cc 100644 --- a/framework/src/main/java/org/onap/cli/fw/cmd/OnapCommand.java +++ b/framework/src/main/java/org/onap/cli/fw/cmd/OnapCommand.java @@ -16,11 +16,13 @@ package org.onap.cli.fw.cmd; +import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; import org.onap.cli.fw.conf.OnapCommandConstants; import org.onap.cli.fw.error.OnapCommandException; @@ -32,12 +34,16 @@ import org.onap.cli.fw.output.OnapCommandResult; import org.onap.cli.fw.output.OnapCommandResultAttribute; import org.onap.cli.fw.output.OnapCommandResultAttributeScope; import org.onap.cli.fw.output.OnapCommandResultType; +import org.onap.cli.fw.schema.OnapCommandSchemaInfo; import org.onap.cli.fw.schema.OnapCommandSchemaLoader; import org.onap.cli.fw.schema.OnapCommandSchemaMerger; +import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils; import org.onap.cli.fw.utils.OnapCommandHelperUtils; import org.onap.cli.fw.utils.OnapCommandUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; /** * Oclip Command. @@ -149,7 +155,6 @@ public abstract class OnapCommand { return this.initializeSchema(schema, false); } - public List<String> initializeSchema(String schema, boolean validate) throws OnapCommandException { this.setSchemaName(schema); @@ -178,6 +183,13 @@ public abstract class OnapCommand { } } + protected void preRun() throws OnapCommandException { + LOG.debug("CMD: " + this.getName() + "pre run."); + } + + protected void postRun() throws OnapCommandException { + LOG.debug("CMD: " + this.getName() + "post run."); + } /** * Oclip command execute with given parameters on service. Before calling this method, its mandatory to set all * parameters value. @@ -197,14 +209,14 @@ public abstract class OnapCommand { LOG.info("INPUT: " + paramMap); // -h or --help is always higher precedence !, user can set this value to get help message - if (OnapCommandConstants.BOOLEAN_TRUE.equals(paramMap.get(OnapCommandConstants.DEFAULT_PARAMETER_HELP).getValue())) { + if ((Boolean)(paramMap.get(OnapCommandConstants.DEFAULT_PARAMETER_HELP).getValue())) { this.cmdResult.setType(OnapCommandResultType.TEXT); this.cmdResult.setOutput(this.printHelp()); return this.cmdResult; } // -v or --version is next higher precedence !, user can set this value to get help message - if (OnapCommandConstants.BOOLEAN_TRUE.equals(paramMap.get(OnapCommandConstants.DEFAULT_PARAMETER_VERSION).getValue())) { + if ((Boolean)(paramMap.get(OnapCommandConstants.DEFAULT_PARAMETER_VERSION).getValue())) { this.cmdResult.setType(OnapCommandResultType.TEXT); this.cmdResult.setOutput(this.printVersion()); return this.cmdResult; @@ -220,12 +232,12 @@ public abstract class OnapCommand { this.cmdResult.setScope(OnapCommandResultAttributeScope.LONG); } // --no-title - if (OnapCommandConstants.BOOLEAN_TRUE.equals(paramMap.get(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_NO_TITLE).getValue())) { + if ((Boolean)paramMap.get(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_NO_TITLE).getValue()) { this.cmdResult.setIncludeTitle(false); } // --debug - if (OnapCommandConstants.BOOLEAN_TRUE.equals(paramMap.get(OnapCommandConstants.DEFAULT_PARAMETER_DEBUG).getValue())) { + if ((Boolean)(paramMap.get(OnapCommandConstants.DEFAULT_PARAMETER_DEBUG).getValue())) { this.cmdResult.setDebug(true); } @@ -238,10 +250,13 @@ public abstract class OnapCommand { } } + preRun(); + this.run(); LOG.info("OUTPUT: " + this.cmdResult.getRecords()); + postRun(); return this.cmdResult; } @@ -270,6 +285,5 @@ public abstract class OnapCommand { public String printHelp() throws OnapCommandHelpFailed { return OnapCommandHelperUtils.help(this); } - // (mrkanag) Add toString for all command, parameter, result, etc objects in JSON format } diff --git a/framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConstants.java b/framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConstants.java index 408f4f69..c2bfc1d5 100644 --- a/framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConstants.java +++ b/framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConstants.java @@ -114,8 +114,10 @@ public class OnapCommandConstants { public static final String DATA_DIRECTORY = "data"; public static final String DISCOVERY_FILE = "cli-schema.json"; public static final String DATA_PATH_JSON_PATTERN = DATA_DIRECTORY + JSON_PATTERN; + public static final String DATA_PATH_PROFILE_JSON = "-profile.json"; + public static final String DATA_PATH_PROFILE_JSON_PATTERN = DATA_DIRECTORY + "/**/*" + DATA_PATH_PROFILE_JSON; public static final String DISCOVER_ALWAYS = "discover_always"; - public static final String PARAM_CACHE_FILE_NAME = "global-profile"; + public static final String PARAM_CACHE_FILE_NAME = "default"; //normal public static final String BASIC_SCHEMA_PROFILE = "basic"; @@ -146,6 +148,26 @@ public class OnapCommandConstants { public static final String SAMPLE_GEN_ENABLED = "cli.sample.gen.enable"; public static final String SAMPLE_GEN_TARGET_FOLDER = "cli.sample.gen.target"; + public static final String VERIFY_SAMPLES_DIRECTORY = "open-cli-sample"; + public static final String VERIFY_SAMPLES_FILE_PATTERN = VERIFY_SAMPLES_DIRECTORY + YAML_PATTERN; + public static final String VERIFY_SAMPLES_MOCK_PATTERN = VERIFY_SAMPLES_DIRECTORY + JSON_PATTERN; + public static final String VERIFY_SAMPLES = "samples"; + public static final String VERIFY_CMD_NAME = "name"; + public static final String VERIFY_CMD_VERSION = "version"; + public static final String VERIFY_OUPUT = "output"; + public static final String VERIFY_INPUT = "input"; + public static final String VERIFY_MOCO = "moco"; + public static final String VERIFY_SAMPLE_FILE_ID = "samplefileid"; + public static final String VERIFY_SAMPLE_ID = "sampleid"; + public static final String VERIFY_RESULT_PASS = "pass"; + public static final String VERIFY_RESULT_FAIL = "fail"; + public static final String VERIFY_CONTEXT_PARAM = "context"; + + + + public static final String VERIFY_LONG_OPTION = "--verify"; + public static final String VERIFY_SHORT_OPTION = "-V"; + private OnapCommandConstants() { } diff --git a/framework/src/main/java/org/onap/cli/fw/input/OnapCommandParameter.java b/framework/src/main/java/org/onap/cli/fw/input/OnapCommandParameter.java index 465dffa4..df0265e6 100644 --- a/framework/src/main/java/org/onap/cli/fw/input/OnapCommandParameter.java +++ b/framework/src/main/java/org/onap/cli/fw/input/OnapCommandParameter.java @@ -16,18 +16,20 @@ package org.onap.cli.fw.input; -import java.io.File; -import java.util.List; -import java.util.Map; -import java.util.UUID; - +import com.fasterxml.jackson.databind.ObjectMapper; import org.onap.cli.fw.error.OnapCommandException; import org.onap.cli.fw.error.OnapCommandInvalidParameterValue; import org.onap.cli.fw.error.OnapCommandParameterMissing; import org.onap.cli.fw.utils.OnapCommandUtils; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; /** * Oclip Command's input parameter. @@ -63,7 +65,7 @@ public class OnapCommandParameter { /* * Default value */ - private String defaultValue = ""; + private Object defaultValue; /* * raw default value, stored with out processing it. @@ -150,12 +152,24 @@ public class OnapCommandParameter { public void setParameterType(OnapCommandParameterType parameterType) { this.parameterType = parameterType; - if (this.defaultValue.isEmpty()) { - if (this.getParameterType().equals(OnapCommandParameterType.BOOL)) { - // For bool type always the default param is false - this.defaultValue = "false"; - } else if (this.getParameterType().equals(OnapCommandParameterType.UUID)) { - this.defaultValue = UUID.randomUUID().toString(); + if (defaultValue == null) { + + switch (getParameterType()) { + case MAP: + this.defaultValue = new HashMap<String, String>(); + break; + case ARRAY: + defaultValue = new ArrayList<String>(); + break; + case BOOL: + defaultValue = Boolean.FALSE; + break; + case UUID: + this.defaultValue = UUID.randomUUID().toString(); + break; + default: + this.defaultValue = new String(""); + break; } } } @@ -165,7 +179,7 @@ public class OnapCommandParameter { * * @return string */ - public String getDefaultValue() { + public Object getDefaultValue() { return defaultValue; } @@ -187,9 +201,63 @@ public class OnapCommandParameter { return this.rawDefaultValue.trim().substring(7, this.rawDefaultValue.length() - 1); } - public void setDefaultValue(String defaultValue) { - this.rawDefaultValue = defaultValue; - this.defaultValue = OnapCommandUtils.replaceLineForSpecialValues(this.rawDefaultValue); + public void setRawDefaultValue(String value) throws OnapCommandInvalidParameterValue { + this.rawDefaultValue = value; + String processedValue= OnapCommandUtils.replaceLineForSpecialValues(value); + + switch (parameterType) { + case MAP: + try { + defaultValue = new ObjectMapper().readValue(processedValue, Map.class); + } catch (IOException e) { + throw new OnapCommandInvalidParameterValue("Invalid default value for " + this.getName(), e); + } + break; + + case ARRAY: + try { + defaultValue = new ObjectMapper().readValue(processedValue, List.class); + } catch (IOException e) { + throw new OnapCommandInvalidParameterValue("Invalid default value for " + this.getName(), e); + } + break; + + case BOOL: + defaultValue = Boolean.valueOf(processedValue); + break; + + default: + defaultValue = processedValue; + break; + } + } + + public void setDefaultValue(Object defaultValue) throws OnapCommandInvalidParameterValue { + //check type + Class<?> clz; + switch (parameterType) { + case BOOL: + clz = Boolean.class; + break; + + case MAP: + clz = Map.class; + break; + + case ARRAY: + clz = Collection.class; + break; + + default: + clz = String.class; + break; + } + + if (clz.isInstance(defaultValue)) { + this.defaultValue = defaultValue; + } else { + throw new OnapCommandInvalidParameterValue("Invalid default value for parameter: " + this.getName()); + } } /** @@ -212,34 +280,27 @@ public class OnapCommandParameter { if (OnapCommandParameterType.URL.equals(parameterType) && !value.toString().isEmpty() && !value.toString().startsWith("http") && !value.toString().startsWith("/")) { - this.value = "/" + value; + value = "/" + value; } else if (OnapCommandParameterType.ARRAY.equals(parameterType)) { if (!(value instanceof List)) { throw new OnapCommandInvalidParameterValue(this.getName()); } - List<String> list = (List<String>) value; - ObjectMapper mapper = new ObjectMapper(); - try { - this.value = mapper.writeValueAsString(list); - } catch (JsonProcessingException e) { - throw new OnapCommandInvalidParameterValue(this.getName(), e); - } } else if (OnapCommandParameterType.MAP.equals(parameterType)) { if (!(value instanceof Map)) { throw new OnapCommandInvalidParameterValue(this.getName()); } + } else if (OnapCommandParameterType.BOOL.equals(parameterType)) { + if (!(value instanceof Boolean)) { + if (value instanceof String) { + value = Boolean.valueOf((String)value); + } else { + throw new OnapCommandInvalidParameterValue(this.getName()); + } - Map<String, String> map = (Map<String, String>) value; - ObjectMapper mapper = new ObjectMapper(); - try { - this.value = mapper.writeValueAsString(map); - } catch (JsonProcessingException e) { - throw new OnapCommandInvalidParameterValue(this.getName(), e); } - } else { - this.value = value; } + this.value = value; } public boolean isOptional() { diff --git a/framework/src/main/java/org/onap/cli/fw/input/cache/OnapCommandParameterCache.java b/framework/src/main/java/org/onap/cli/fw/input/cache/OnapCommandParameterCache.java index 55833167..19533ef7 100644 --- a/framework/src/main/java/org/onap/cli/fw/input/cache/OnapCommandParameterCache.java +++ b/framework/src/main/java/org/onap/cli/fw/input/cache/OnapCommandParameterCache.java @@ -18,6 +18,8 @@ package org.onap.cli.fw.input.cache; import static org.onap.cli.fw.conf.OnapCommandConstants.DATA_DIRECTORY; import static org.onap.cli.fw.conf.OnapCommandConstants.DATA_PATH_JSON_PATTERN; +import static org.onap.cli.fw.conf.OnapCommandConstants.DATA_PATH_PROFILE_JSON; +import static org.onap.cli.fw.conf.OnapCommandConstants.DATA_PATH_PROFILE_JSON_PATTERN; import java.io.File; import java.io.IOException; @@ -37,7 +39,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class OnapCommandParameterCache { - public Map<String, Map<String, String>> paramCache = new HashMap<>(); + private Map<String, Map<String, String>> paramCache = new HashMap<>(); private static OnapCommandParameterCache single = null; @@ -56,6 +58,13 @@ public class OnapCommandParameterCache { return single; } + public void includeProfile(String profile) { + this.load(profile, true); + } + + public void excludeProfile(String profile) { + this.load(profile, false); + } public void add(String productVersion, String paramName, String paramValue) { @@ -109,20 +118,29 @@ public class OnapCommandParameterCache { } private void load() { + this.load(this.profileName, true); + } + + private void load(String profileName, boolean include) { List<OnapCommandParamEntity> params= new ArrayList<>(); try { - params = this.loadParamFromCache(this.profileName); + params = this.loadParamFromCache(profileName); } catch (OnapCommandLoadProfileFailed e) { throw new RuntimeException(e); // NOSONAR } for (OnapCommandParamEntity p : params) { - this.add(p.getProduct(), p.getName(), p.getValue()); + if (include) { + this.add(p.getProduct(), p.getName(), p.getValue()); + } else { + this.remove(p.getProduct(), p.getName()); + } } } public void setProfile(String profileName) { this.profileName = profileName; + this.paramCache.clear(); this.load(); } @@ -132,7 +150,7 @@ public class OnapCommandParameterCache { Resource[] resources = OnapCommandDiscoveryUtils.findResources(DATA_DIRECTORY); if (resources != null && resources.length == 1) { String path = resources[0].getURI().getPath(); - File file = new File(path + File.separator + profileName + ".json"); + File file = new File(path + File.separator + profileName + DATA_PATH_PROFILE_JSON); ObjectMapper mapper = new ObjectMapper(); mapper.writerWithDefaultPrettyPrinter().writeValue(file, params); } @@ -146,7 +164,7 @@ public class OnapCommandParameterCache { List<OnapCommandParamEntity> params = new ArrayList<>(); try { - Resource resource = OnapCommandDiscoveryUtils.findResource(profileName + ".json", + Resource resource = OnapCommandDiscoveryUtils.findResource(profileName + DATA_PATH_PROFILE_JSON, DATA_PATH_JSON_PATTERN); if (resource != null) { File file = new File(resource.getURI().getPath()); @@ -160,4 +178,24 @@ public class OnapCommandParameterCache { return params; } + + public List<String> getProfiles() { + List<String> profiles = new ArrayList<>(); + + Resource[] resources; + try { + resources = OnapCommandDiscoveryUtils.findResources(DATA_PATH_PROFILE_JSON_PATTERN); + } catch (IOException e) { + throw new RuntimeException(e); // NOSONAR + } + + if (resources != null && resources.length > 0) { + for (Resource res : resources) { + String profile = res.getFilename().substring(0, res.getFilename().indexOf(DATA_PATH_PROFILE_JSON)); + profiles.add(profile); + } + } + + return profiles; + } } 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 854b55be..15a086c7 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 @@ -16,13 +16,6 @@ package org.onap.cli.fw.registrar; -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - import org.apache.commons.io.IOUtils; import org.onap.cli.fw.cmd.OnapCommand; import org.onap.cli.fw.conf.OnapCommandConfig; @@ -48,6 +41,13 @@ import org.onap.cli.fw.utils.OnapCommandUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + /** * Oclip Command registrar provides a common place, where every command would get registered automatically when its @@ -90,8 +90,20 @@ public class OnapCommandRegistrar { paramCache.remove(this.getEnabledProductVersion(), paramName); } - public void setProfile(String profileName) { + public void setProfile(String profileName, List<String> includes, List<String> excludes) { this.paramCache.setProfile(profileName); + + for (String profile : includes) { + this.paramCache.includeProfile(profile); + } + + for (String profile : excludes) { + this.paramCache.excludeProfile(profile); + } + } + + public List<String> getUserProfiles() { + return paramCache.getProfiles(); } private static OnapCommandRegistrar registrar = null; @@ -99,12 +111,9 @@ public class OnapCommandRegistrar { /** * Register the command into registrar and throws OnapInvalidCommandRegistration for invalid command. * - * @param name - * Command Name - * @param cmd - * Command Class - * @throws OnapCommandInvalidRegistration - * Invalid registration exception + * @param name Command Name + * @param cmd Command Class + * @throws OnapCommandInvalidRegistration Invalid registration exception * @throws OnapCommandRegistrationProductInfoMissing */ private void register(String name, String version, Class<? extends OnapCommand> cmd) throws OnapCommandInvalidRegistration, OnapCommandRegistrationProductInfoMissing { @@ -123,16 +132,15 @@ public class OnapCommandRegistrar { private OnapCommandRegistrar() { this.enabledProductVersion = System.getenv(OnapCommandConstants.OPEN_CLI_PRODUCT_IN_USE_ENV_NAME); - if (this.enabledProductVersion == null) { - this.enabledProductVersion = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_PRODUCT_NAME); + if (this.enabledProductVersion == null) { + this.enabledProductVersion = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_PRODUCT_NAME); } } /** * Get global registrar. * - * @throws OnapCommandException - * exception + * @throws OnapCommandException exception */ public static OnapCommandRegistrar getRegistrar() throws OnapCommandException { if (registrar == null) { @@ -165,7 +173,7 @@ public class OnapCommandRegistrar { return cmds; } - for (String cmd: this.registry.keySet()) { + for (String cmd : this.registry.keySet()) { if (cmd.split(":")[1].equalsIgnoreCase(version)) { cmds.add(cmd.split(":")[0]); } @@ -201,8 +209,7 @@ public class OnapCommandRegistrar { * Returns command details. * * @return map - * @throws OnapCommandException - * exception + * @throws OnapCommandException exception */ public List<OnapCommandSchemaInfo> listCommandInfo() throws OnapCommandException { return OnapCommandDiscoveryUtils.discoverSchemas(); @@ -211,11 +218,9 @@ public class OnapCommandRegistrar { /** * Get the OnapCommand, which CLI main would use to find the command based on the command name. * - * @param cmdName - * Name of command + * @param cmdName Name of command * @return OnapCommand - * @throws OnapCommandException - * Exception + * @throws OnapCommandException Exception */ public OnapCommand get(String cmdName) throws OnapCommandException { return this.get(cmdName, this.getEnabledProductVersion()); @@ -224,13 +229,10 @@ public class OnapCommandRegistrar { /** * Get the OnapCommand, which CLI main would use to find the command based on the command name. * - * @param cmdName - * Name of command - * @param version - * product version + * @param cmdName Name of command + * @param version product version * @return OnapCommand - * @throws OnapCommandException - * Exception + * @throws OnapCommandException Exception */ public OnapCommand get(String cmdName, String version) throws OnapCommandException { Class<? extends OnapCommand> cls = registry.get(cmdName + ":" + version); @@ -281,9 +283,9 @@ public class OnapCommandRegistrar { } //First check if there is an specific plugin exist, otherwise check for profile plugin - if (plugins.containsKey(schema.getSchemaName())) { - this.register(schema.getCmdName(), schema.getProduct(), plugins.get(schema.getSchemaName())); - } else if (plugins.containsKey(schema.getSchemaProfile())) { + if (plugins.containsKey(schema.getSchemaName())) { + this.register(schema.getCmdName(), schema.getProduct(), plugins.get(schema.getSchemaName())); + } else if (plugins.containsKey(schema.getSchemaProfile())) { this.register(schema.getCmdName(), schema.getProduct(), plugins.get(schema.getSchemaProfile())); } else { LOG.info("Ignoring schema " + schema.getSchemaURI()); @@ -303,7 +305,7 @@ public class OnapCommandRegistrar { } String buildTime = OnapCommandHelperUtils.findLastBuildTime(); - if (buildTime!= null && !buildTime.isEmpty()) { + if (buildTime != null && !buildTime.isEmpty()) { buildTime = " [" + buildTime + "]"; } else { buildTime = ""; @@ -329,8 +331,7 @@ public class OnapCommandRegistrar { * Provides the help message in tabular format for all commands registered in this registrar. * * @return string - * @throws OnapCommandHelpFailed - * Help cmd failed + * @throws OnapCommandHelpFailed Help cmd failed */ public String getHelp() throws OnapCommandHelpFailed { return this.getHelp(false); @@ -375,7 +376,7 @@ public class OnapCommandRegistrar { OnapCommand cmd; try { if (!isEnabledProductVersionOnly) { - String []cmdVer = cmdName.split(":"); + String[] cmdVer = cmdName.split(":"); cmd = this.get(cmdVer[0], cmdVer[1]); attr.getValues().add(cmdVer[0]); attrVer.getValues().add(cmdVer[1]); @@ -397,4 +398,8 @@ public class OnapCommandRegistrar { throw new OnapCommandHelpFailed(e); } } + + public List<Map<String, ?>> getTestSuite(String cmd) throws OnapCommandException { + return OnapCommandDiscoveryUtils.createTestSuite(cmd, enabledProductVersion); + } } 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 67675480..af444b8f 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 @@ -19,6 +19,9 @@ package org.onap.cli.fw.schema; import org.onap.cli.fw.cmd.OnapCommandType; import org.onap.cli.fw.conf.OnapCommandConstants; +import java.util.ArrayList; +import java.util.List; + /** * OnapCommandSchemaInfo is used in discovery caching. * @@ -39,6 +42,8 @@ public class OnapCommandSchemaInfo { private String product; + private List<String> sampleFiles = new ArrayList(); + /** * OCS version */ @@ -118,5 +123,7 @@ public class OnapCommandSchemaInfo { this.ignore = ignore; } - + public List<String> getSampleFiles() { + return sampleFiles; + } } diff --git a/framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaLoader.java b/framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaLoader.java index b47000a1..628ddf3a 100644 --- a/framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaLoader.java +++ b/framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaLoader.java @@ -67,6 +67,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.commons.io.FileUtils; import org.onap.cli.fw.cmd.OnapCommand; import org.onap.cli.fw.cmd.OnapCommandType; import org.onap.cli.fw.conf.OnapCommandConfig; @@ -318,7 +319,7 @@ public class OnapCommandSchemaLoader { case DEFAULT_VALUE: Object obj = parameter.get(key2); - param.setDefaultValue(obj.toString()); + param.setRawDefaultValue(obj.toString()); break; case TYPE: @@ -524,26 +525,8 @@ public class OnapCommandSchemaLoader { /** * Get schema map. * - * @param resource - * resource obj - * @return map - * @throws OnapCommandInvalidSchema - * exception - */ - public static Map<String, ?> loadSchema(Resource resource) throws OnapCommandInvalidSchema { - try { - return loadSchema(resource.getInputStream(), resource.getFilename()); - } catch (IOException e) { - throw new OnapCommandInvalidSchema(resource.getFilename(), e); - } - - } - - /** - * Get schema map. - * - * @param resource - * resource obj + * @param stream + * @param schemaName * @return map * @throws OnapCommandInvalidSchema * exception 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 b878503a..2b3cf941 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 @@ -16,33 +16,13 @@ package org.onap.cli.fw.utils; -import static org.onap.cli.fw.conf.OnapCommandConstants.DATA_DIRECTORY; -import static org.onap.cli.fw.conf.OnapCommandConstants.DATA_PATH_JSON_PATTERN; -import static org.onap.cli.fw.conf.OnapCommandConstants.DISCOVERY_FILE; -import static org.onap.cli.fw.conf.OnapCommandConstants.NAME; -import static org.onap.cli.fw.conf.OnapCommandConstants.OPEN_CLI_SCHEMA_VERSION; -import static org.onap.cli.fw.conf.OnapCommandConstants.SCHEMA_DIRECTORY; -import static org.onap.cli.fw.conf.OnapCommandConstants.SCHEMA_PATH_PATERN; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.ServiceLoader; -import java.util.Map.Entry; - +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.io.FileUtils; import org.onap.cli.fw.cmd.OnapCommand; import org.onap.cli.fw.conf.OnapCommandConfig; import org.onap.cli.fw.conf.OnapCommandConstants; -import org.onap.cli.fw.error.OnapCommandDiscoveryFailed; -import org.onap.cli.fw.error.OnapCommandException; -import org.onap.cli.fw.error.OnapCommandInstantiationFailed; -import org.onap.cli.fw.error.OnapCommandInvalidSchema; +import org.onap.cli.fw.error.*; +import org.onap.cli.fw.registrar.OnapCommandRegistrar; import org.onap.cli.fw.schema.OnapCommandSchemaInfo; import org.onap.cli.fw.schema.OnapCommandSchemaLoader; import org.springframework.core.io.Resource; @@ -50,7 +30,13 @@ import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.yaml.snakeyaml.Yaml; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.*; + +import static org.onap.cli.fw.conf.OnapCommandConstants.*; public class OnapCommandDiscoveryUtils { @@ -248,7 +234,7 @@ public class OnapCommandDiscoveryUtils { for (Resource resource : res) { try { - resourceMap = OnapCommandSchemaLoader.loadSchema(resource); + resourceMap = loadYaml(resource); } catch (OnapCommandException e) { OnapCommandUtils.LOG.error("Ignores invalid schema " + resource.getURI().toString(), e); continue; @@ -297,9 +283,34 @@ public class OnapCommandDiscoveryUtils { throw new OnapCommandDiscoveryFailed(SCHEMA_DIRECTORY, e); } + try { + Resource[] samples = findResources(OnapCommandConstants.VERIFY_SAMPLES_FILE_PATTERN); + for (Resource sample : samples) { + updateSchemaInfoWithSample(sample, extSchemas); + } + } catch (IOException e) { + throw new OnapCommandDiscoveryFailed(OnapCommandConstants.VERIFY_SAMPLES_DIRECTORY, e); + } + return extSchemas; } + private static void updateSchemaInfoWithSample(Resource sampleResourse, + List<OnapCommandSchemaInfo> schemaInfos) throws OnapCommandInvalidSchema, IOException { + Map<String, ?> infoMap = loadSchema(sampleResourse); + String cmdName = (String) infoMap.get(OnapCommandConstants.VERIFY_CMD_NAME); + String version = (String) infoMap.get(OnapCommandConstants.VERIFY_CMD_VERSION); + + Optional<OnapCommandSchemaInfo> optSchemaInfo = schemaInfos.stream() + .filter(e -> e.getCmdName().equals(cmdName) && e.getProduct().equals(version)) + .findFirst(); + + if (optSchemaInfo.isPresent()) { + OnapCommandSchemaInfo onapCommandSchemaInfo = optSchemaInfo.get(); + onapCommandSchemaInfo.getSampleFiles().add(sampleResourse.getFilename()); + } + } + /** * Discover the Oclip commands. * @@ -329,4 +340,92 @@ public class OnapCommandDiscoveryUtils { } } + + public static List<Map<String, ?>> createTestSuite(String cmd, String version) throws OnapCommandException { + + ArrayList<Map<String, ?>> testSamples = new ArrayList(); + + List<Resource> resources = new ArrayList(); + OnapCommandSchemaInfo schemaInfo = getSchemaInfo(cmd, version); + + List<String> sampleFiles = new ArrayList(); + if (schemaInfo != null && !schemaInfo.getSampleFiles().isEmpty()) { + sampleFiles.addAll(schemaInfo.getSampleFiles()); + } + + for (String sampleFile : sampleFiles) { + try { + Resource resource = OnapCommandDiscoveryUtils.findResource(sampleFile, + OnapCommandConstants.VERIFY_SAMPLES_FILE_PATTERN); + resources.add(resource); + } catch (IOException e) { + throw new OnapCommandInvalidSample("Sample file does not exist : " + sampleFile , e); + } + } + + for (Resource resource : resources) { + + Map<String, ?> stringMap = OnapCommandDiscoveryUtils.loadYaml(resource); + Map<String, Map<String, String>> samples = (Map<String, Map<String, String>>) stringMap + .get(OnapCommandConstants.VERIFY_SAMPLES); + + for (String sampleId : samples.keySet()) { + + Map<String, String> sample = samples.get(sampleId); + + List<String> inputArgs = new ArrayList(); + inputArgs.add(cmd); + 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(); + 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)); + map.put(OnapCommandConstants.VERIFY_SAMPLE_FILE_ID, resource.getFilename()); + map.put(OnapCommandConstants.VERIFY_SAMPLE_ID, sampleId); + testSamples.add(map); + } + } + return testSamples; + } + + /** + * Get schema map. + * + * @param resource + * resource obj + * @return map + * @throws OnapCommandInvalidSchema + * exception + */ + public static Map<String, ?> loadYaml(Resource resource) throws OnapCommandInvalidSchema { + Map<String, ?> values = null; + try { + values = (Map<String, ?>) new Yaml().load(resource.getInputStream()); + } catch (Exception e) { + throw new OnapCommandInvalidSchema(resource.getFilename(), e); + } + return values; + } + + /** + * Get schema map. + * + * @param filePath + * @return map + * @throws OnapCommandInvalidSchema + * exception + */ + public static Map<String, ?> loadYaml(String filePath) throws OnapCommandInvalidSchema { + Map<String, ?> values = null; + try { + values = (Map<String, Object>) new Yaml().load(FileUtils.readFileToString(new File(filePath))); + } catch (Exception e) { + throw new OnapCommandInvalidSchema(filePath, e); + } + return values; + } } 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 e9ea81d4..1387ea3d 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 @@ -157,7 +157,7 @@ public class OnapCommandHelperUtils { if (param.isRawDefaultValueAnEnv()) { optSecondCol += defaultMsg + "read from environment variable " + param.getEnvVarNameFromrRawDefaultValue() + "."; - } else if (param.getDefaultValue() != null && !((String)param.getDefaultValue()).isEmpty()) { + } else if (param.getDefaultValue() != null && param.getDefaultValue().toString().isEmpty()) { optSecondCol += defaultMsg + param.getDefaultValue() + "."; } diff --git a/framework/src/main/resources/open-cli-schema/default_input_parameters.yaml b/framework/src/main/resources/open-cli-schema/default_input_parameters.yaml index bb35ac26..652401e3 100644 --- a/framework/src/main/resources/open-cli-schema/default_input_parameters.yaml +++ b/framework/src/main/resources/open-cli-schema/default_input_parameters.yaml @@ -42,4 +42,21 @@ parameters: short_option: t long_option: no-title default_value: false - is_default_param: true
\ No newline at end of file + is_default_param: true + - name: verify + type: bool + description: verify the command using available command sample file and mocking file + short_option: V + long_option: verify + default_value: false + is_default_param: true + is_include: false + is_optional: true + - name: context + type: map + description: command context + short_option: D + long_option: context + is_default_param: true + is_optional: true + is_optional: true
\ No newline at end of file diff --git a/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSampleTest.java b/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSampleTest.java index a83cda52..4009dcb0 100644 --- a/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSampleTest.java +++ b/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSampleTest.java @@ -45,11 +45,11 @@ public class OnapCommandSampleTest { Set<OnapCommandParameter> parameters = new HashSet(); OnapCommandParameter v = new OnapCommandParameter(); v.setName(OnapCommandConstants.DEFAULT_PARAMETER_VERSION); - v.setValue("true"); + v.setValue(true); parameters.add(v); OnapCommandParameter h = new OnapCommandParameter(); h.setName(OnapCommandConstants.DEFAULT_PARAMETER_HELP); - h.setValue("false"); + h.setValue(false); parameters.add(h); sample.setParameters(parameters); sample.execute(); @@ -64,7 +64,7 @@ public class OnapCommandSampleTest { Set<OnapCommandParameter> parameters = new HashSet(); OnapCommandParameter v = new OnapCommandParameter(); v.setName(OnapCommandConstants.DEFAULT_PARAMETER_HELP); - v.setValue("true"); + v.setValue(true); v.setParameterType(OnapCommandParameterType.BOOL); parameters.add(v); sample.setParameters(parameters); @@ -81,11 +81,11 @@ public class OnapCommandSampleTest { Set<OnapCommandParameter> parameters = new HashSet(); OnapCommandParameter v = new OnapCommandParameter(); v.setName(OnapCommandConstants.DEFAULT_PARAMETER_VERSION); - v.setValue("false"); + v.setValue(false); parameters.add(v); OnapCommandParameter h = new OnapCommandParameter(); h.setName(OnapCommandConstants.DEFAULT_PARAMETER_HELP); - h.setValue("false"); + h.setValue(false); parameters.add(h); OnapCommandParameter f = new OnapCommandParameter(); f.setName(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_FORMAT); @@ -93,15 +93,15 @@ public class OnapCommandSampleTest { parameters.add(f); OnapCommandParameter l = new OnapCommandParameter(); l.setName(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_ATTR_LONG); - l.setValue("true"); + l.setValue(true); parameters.add(l); OnapCommandParameter t = new OnapCommandParameter(); t.setName(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_NO_TITLE); - t.setValue("true"); + t.setValue(true); parameters.add(t); OnapCommandParameter d = new OnapCommandParameter(); d.setName(OnapCommandConstants.DEFAULT_PARAMETER_DEBUG); - d.setValue("true"); + d.setValue(true); parameters.add(d); sample.setParameters(parameters); @@ -128,11 +128,11 @@ public class OnapCommandSampleTest { Set<OnapCommandParameter> parameters = new HashSet(); OnapCommandParameter v = new OnapCommandParameter(); v.setName(OnapCommandConstants.DEFAULT_PARAMETER_VERSION); - v.setValue("false"); + v.setValue(false); parameters.add(v); OnapCommandParameter h = new OnapCommandParameter(); h.setName(OnapCommandConstants.DEFAULT_PARAMETER_HELP); - h.setValue("false"); + h.setValue(false); parameters.add(h); OnapCommandParameter f = new OnapCommandParameter(); f.setName(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_FORMAT); @@ -140,15 +140,15 @@ public class OnapCommandSampleTest { parameters.add(f); OnapCommandParameter l = new OnapCommandParameter(); l.setName(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_ATTR_LONG); - l.setValue("true"); + l.setValue(true); parameters.add(l); OnapCommandParameter t = new OnapCommandParameter(); t.setName(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_NO_TITLE); - t.setValue("true"); + t.setValue(true); parameters.add(t); OnapCommandParameter d = new OnapCommandParameter(); d.setName(OnapCommandConstants.DEFAULT_PARAMETER_DEBUG); - d.setValue("true"); + d.setValue(true); parameters.add(d); sample.setParameters(parameters); sample.execute(); diff --git a/framework/src/test/java/org/onap/cli/fw/input/OnapCommandParameterCacheTest.java b/framework/src/test/java/org/onap/cli/fw/input/OnapCommandParameterCacheTest.java index ea06ea1b..302d280b 100644 --- a/framework/src/test/java/org/onap/cli/fw/input/OnapCommandParameterCacheTest.java +++ b/framework/src/test/java/org/onap/cli/fw/input/OnapCommandParameterCacheTest.java @@ -27,7 +27,7 @@ public class OnapCommandParameterCacheTest { cache.add("1.0", "a", "b"); cache.remove("1.0", "a"); - cache.setProfile("test"); + cache.setProfile("test123"); cache.getParams("1.0"); } diff --git a/framework/src/test/java/org/onap/cli/fw/input/OnapCommandParameterTest.java b/framework/src/test/java/org/onap/cli/fw/input/OnapCommandParameterTest.java index 82781b43..5a6e6458 100644 --- a/framework/src/test/java/org/onap/cli/fw/input/OnapCommandParameterTest.java +++ b/framework/src/test/java/org/onap/cli/fw/input/OnapCommandParameterTest.java @@ -20,6 +20,7 @@ import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.Map; import org.junit.Test; @@ -49,8 +50,13 @@ public class OnapCommandParameterTest { assertTrue("value".equals(param.getValue())); param.setParameterType(OnapCommandParameterType.ARRAY); - param.setValue(Arrays.asList("1", "2", "3")); - assertTrue("[\"1\",\"2\",\"3\"]".equals(param.getValue())); + List<String> list = Arrays.asList("1", "2", "3"); + param.setValue(list); + assertTrue(((List)param.getValue()).containsAll(list)); + + param.setRawDefaultValue("[\"1\", \"2\", \"3\", \"4\"]"); + assertTrue(((List<String>)param.getDefaultValue()) + .containsAll(Arrays.asList("1", "2", "3", "4"))); param.setParameterType(OnapCommandParameterType.MAP); Map<String, String> map = new HashMap<>(); @@ -58,16 +64,20 @@ public class OnapCommandParameterTest { map.put("Two", "2"); map.put("Three", "3"); param.setValue(map); - assertTrue("{\"One\":\"1\",\"Two\":\"2\",\"Three\":\"3\"}".equals(param.getValue())); - - param.setDefaultValue("$s{env:defaultValue}"); - assertTrue("env:defaultValue".equals(param.getDefaultValue())); + HashMap<String, String> value = (HashMap<String, String>) param.getValue(); + assertTrue(value.keySet().containsAll(Arrays.asList("One", "Two", "Three"))); + assertTrue(value.values().containsAll(Arrays.asList("1", "2", "3"))); + + param.setRawDefaultValue("{\"key1\":\"$s{env:defaultValue}\"}"); + assertTrue(((Map<String, String>)param.getDefaultValue()).values().containsAll( + Arrays.asList("env:defaultValue") + )); } @Test - public void parameterEnvDefaultValueObjTest() { + public void parameterEnvDefaultValueObjTest() throws OnapCommandInvalidParameterValue { OnapCommandParameter param = new OnapCommandParameter(); - param.setDefaultValue("$s{env:DAFAULT_VALUE}"); + param.setRawDefaultValue("$s{env:DAFAULT_VALUE}"); boolean isDefaultValueAnEnv = param.isRawDefaultValueAnEnv(); assertTrue(isDefaultValueAnEnv); diff --git a/framework/src/test/java/org/onap/cli/fw/input/cache/OnapCommandParameterCacheTest.java b/framework/src/test/java/org/onap/cli/fw/input/cache/OnapCommandParameterCacheTest.java new file mode 100644 index 00000000..be539946 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/input/cache/OnapCommandParameterCacheTest.java @@ -0,0 +1,33 @@ +/* + * Copyright 2017 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.input.cache; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + + +public class OnapCommandParameterCacheTest { + @Test + public void paramTypeGetTest() { + + assertTrue(OnapCommandParameterCache.getInstance().getProfiles().contains("test")); + + + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/registrar/OnapCommandRegistrarTest.java b/framework/src/test/java/org/onap/cli/fw/registrar/OnapCommandRegistrarTest.java index 539ec245..d70c1521 100644 --- a/framework/src/test/java/org/onap/cli/fw/registrar/OnapCommandRegistrarTest.java +++ b/framework/src/test/java/org/onap/cli/fw/registrar/OnapCommandRegistrarTest.java @@ -23,6 +23,7 @@ import static org.junit.Assert.fail; import java.io.File; import java.net.URL; +import java.util.ArrayList; import org.junit.Before; import org.junit.Test; @@ -90,7 +91,7 @@ public class OnapCommandRegistrarTest { @Test public void testProfile() throws OnapCommandException { try { - OnapCommandRegistrar.getRegistrar().setProfile("test"); + OnapCommandRegistrar.getRegistrar().setProfile("test234", new ArrayList<String>(), new ArrayList<String>()); OnapCommandRegistrar.getRegistrar().addParamCache("a", "b"); OnapCommandRegistrar.getRegistrar().getParamCache(); OnapCommandRegistrar.getRegistrar().removeParamCache("a"); 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 317920f8..1d7c2422 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 @@ -17,18 +17,9 @@ package org.onap.cli.fw.utils; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - +import mockit.Invocation; +import mockit.Mock; +import mockit.MockUp; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; @@ -48,9 +39,19 @@ import org.onap.cli.fw.schema.OnapCommandSchema; import org.onap.cli.fw.schema.OnapCommandSchemaInfo; import org.onap.cli.fw.schema.OnapCommandSchemaLoader; -import mockit.Invocation; -import mockit.Mock; -import mockit.MockUp; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class OnapCommandUtilsTest { @@ -119,7 +120,7 @@ public class OnapCommandUtilsTest { public void loadOnapCommandSchemaWithOutDefaultTest() throws OnapCommandException { OnapCommand cmd = new OnapCommandSample(); OnapCommandSchemaLoader.loadSchema(cmd, "sample-test-schema.yaml", false, false); - assertTrue("sample-test".equals(cmd.getName()) && cmd.getParameters().size() == 9); + assertTrue("sample-test".equals(cmd.getName()) && cmd.getParameters().size() == 10); } @Test(expected = OnapCommandParameterNameConflict.class) @@ -147,13 +148,81 @@ public class OnapCommandUtilsTest { assertTrue("sample-test".equals(cmd.getName()) && cmd.getParameters().size() > 9); for (OnapCommandParameter com : cmd.getParameters()) { - com.setValue("value"); + switch (com.getParameterType()) { + case STRING: + com.setValue("value"); + break; + + case ARRAY: + com.setValue(Collections.EMPTY_LIST); + break; + + case MAP: + com.setValue(new HashMap<String, String>()); + break; + + case BOOL: + com.setValue(true); + break; + + case TEXT: + com.setValue("value"); + break; + + case URL: + com.setValue("http:localhost/test"); + break; + + case JSON: + com.setValue("json"); + break; + + default: + break; + } } Map<String, OnapCommandParameter> map = OnapCommandUtils.getInputMap(cmd.getParameters()); - assertTrue(map.size() == 15); + assertTrue(map.size() == 18); } + @Test + public void contextParameterTest() throws OnapCommandException { + OnapCommand cmd = new OnapCommandSample(); + OnapCommandSchemaLoader.loadSchema(cmd, "sample-test-schema.yaml", true, false); + Optional<OnapCommandParameter> contextOpt = cmd.getParameters().stream() + .filter(e -> e.getName().equals("context")) + .findFirst(); + + if (contextOpt.isPresent()) { + OnapCommandParameter context = contextOpt.get(); + assertTrue(context.getDefaultValue() instanceof HashMap); + } else { + fail("context parameter is not available"); + } + } + + @Test + public void contextParameterSetAndGetTest() throws OnapCommandException { + OnapCommand cmd = new OnapCommandSample(); + OnapCommandSchemaLoader.loadSchema(cmd, "sample-test-schema.yaml", true, false); + Optional<OnapCommandParameter> contextOpt = cmd.getParameters().stream() + .filter(e -> e.getName().equals("context")) + .findFirst(); + + if (contextOpt.isPresent()) { + OnapCommandParameter context = contextOpt.get(); + HashMap<String, String> map = new HashMap(); + map.put("a", "b"); + context.setValue(map); + + map = (HashMap<String, String>) context.getValue(); + assertTrue(map.keySet().contains("a")); + assertTrue(map.values().contains("b")); + } else { + fail("context parameter is not available"); + } + } @Test public void helpCommandTest() throws IOException, OnapCommandException { diff --git a/framework/src/test/resources/data/test-profile.json b/framework/src/test/resources/data/test-profile.json new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/framework/src/test/resources/data/test-profile.json diff --git a/framework/src/test/resources/data/test2-profile.json b/framework/src/test/resources/data/test2-profile.json new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/framework/src/test/resources/data/test2-profile.json diff --git a/framework/src/test/resources/open-cli-schema/sample-test-schema.yaml b/framework/src/test/resources/open-cli-schema/sample-test-schema.yaml index 3c4ace83..f4894b3f 100644 --- a/framework/src/test/resources/open-cli-schema/sample-test-schema.yaml +++ b/framework/src/test/resources/open-cli-schema/sample-test-schema.yaml @@ -69,6 +69,12 @@ parameters: description: Oclip positional args, if no short option and no long option given for it is_optional: true default_value: http://localhost:8082/file.txt + - name: array-param + type: array + description: list parameter + long_option: list-param + short_option: q + is_optional: true results: direction: portrait attributes: diff --git a/main/pom.xml b/main/pom.xml index 9e14e63c..dcd42e37 100644 --- a/main/pom.xml +++ b/main/pom.xml @@ -48,14 +48,9 @@ <version>${project.parent.version}</version> </dependency> <dependency> - <groupId>commons-io</groupId> - <artifactId>commons-io</artifactId> - <version>1.3.2</version> - </dependency> - <dependency> <groupId>jline</groupId> <artifactId>jline</artifactId> - <version>2.14.3</version> + <version>2.6</version> </dependency> <dependency> <groupId>org.jmockit</groupId> diff --git a/main/src/main/java/org/onap/cli/main/OnapCli.java b/main/src/main/java/org/onap/cli/main/OnapCli.java index 443b86f2..e70c7186 100644 --- a/main/src/main/java/org/onap/cli/main/OnapCli.java +++ b/main/src/main/java/org/onap/cli/main/OnapCli.java @@ -16,11 +16,8 @@ package org.onap.cli.main; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - +import jline.TerminalFactory; +import jline.console.ConsoleReader; import org.apache.commons.io.IOUtils; import org.onap.cli.fw.cmd.OnapCommand; import org.onap.cli.fw.conf.OnapCommandConfig; @@ -36,6 +33,7 @@ import org.onap.cli.fw.output.OnapCommandResultAttribute; import org.onap.cli.fw.output.OnapCommandResultAttributeScope; import org.onap.cli.fw.output.OnapCommandResultType; import org.onap.cli.fw.registrar.OnapCommandRegistrar; +import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils; import org.onap.cli.main.conf.OnapCliConstants; import org.onap.cli.main.interactive.StringCompleter; import org.onap.cli.main.utils.OnapCliArgsParser; @@ -43,8 +41,14 @@ import org.onap.cli.sample.yaml.SampleYamlGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import jline.TerminalFactory; -import jline.console.ConsoleReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; /** * Oclip Command Line Interface (CLI). @@ -61,7 +65,7 @@ public class OnapCli { private int exitCode = -1; public OnapCli(String[] args) { - this.args = Arrays.asList(args); + this.args.addAll(Arrays.asList(args)); } public OnapCli(String product, String[] args) { @@ -104,7 +108,7 @@ public class OnapCli { public void handleHelp() { try { if ((args.size() == 1) && (this.getLongOption(OnapCliConstants.PARAM_HELP_LOGN).equals(args.get(0)) - || this.getShortOption(OnapCliConstants.PARAM_HELP_SHORT).equals(args.get(0)))) { + || this.getShortOption(OnapCliConstants.PARAM_HELP_SHORT).equals(args.get(0)))) { this.print(IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("oclip-readme.txt"))); String help = OnapCommandRegistrar.getRegistrar().getHelp(); this.print(help); @@ -139,12 +143,74 @@ public class OnapCli { */ public void handleProfile() { try { - if ((args.size() == 2) && (this.getLongOption(OnapCliConstants.PARAM_PROFILE_LONG).equals(args.get(0)) - || this.getShortOption(OnapCliConstants.PARAM_PROFILE_SHORT).equals(args.get(0)))) { + if ((this.args.size() >= 2) && (this.getLongOption(OnapCliConstants.PARAM_PROFILE_LONG).equals(this.args.get(0)) + || this.getShortOption(OnapCliConstants.PARAM_PROFILE_SHORT).equals(this.args.get(0)))) { + + OnapCommandRegistrar.getRegistrar().setProfile( + this.args.get(1), + new ArrayList<String>(), + new ArrayList<String>()); + //Make space of interactive mode/command mode + this.args.remove(0); //--profile or -c + this.args.remove(0); //profile name + } + } catch (Exception e) { + this.print(e); + this.exitFailure(); + } + } + + /** + * Handles batch command. --param-file or -p + * CAUTION: This option should be passed after --profile always. + */ + public void handleBatchCommand() { + try { + if ((this.args.size() >= 3) && (this.getLongOption(OnapCliConstants.PARAM_PARAM_FILE_LONG).equals(this.args.get(0)) + || this.getShortOption(OnapCliConstants.PARAM_PARAM_FILE_SHORT).equals(this.args.get(0)))) { + + String paramFilePath = this.args.get(1); + + //Make space of interactive mode/command mode + this.args.remove(0); //--param-file or -p + this.args.remove(0); //file name + + //Read YAML and loop thru it + // one + // - param-long-option-1: value + // - param-long-option-1: value + // - positional-arg1 + // - positional-arg2 + // two + // - param-long-option-1: value + // - param-long-option-1: value + // - positional-arg1 + // - positional-arg2 + try { + Map<String, Object> values = (Map<String, Object>) OnapCommandDiscoveryUtils.loadYaml(paramFilePath); + + for (Entry<String, Object> cmdsParam: values.entrySet()) { + List<String> args = new ArrayList<>(); + args.add(this.args.get(0)); + for (Object param: (List)cmdsParam.getValue()) { + if (param instanceof Map) { //optional args + Map <String, String> paramMap = (Map<String, String>) param; + String paramName = paramMap.keySet().iterator().next(); + Object paramValue = paramMap.get(paramName); + args.add("--" + paramName); + args.add(paramValue.toString()); + } else { //positional args + args.add(param.toString()); + } + } - OnapCommandRegistrar.getRegistrar().setProfile(args.get(1)); - //Make space of interactive mode - this.args = new ArrayList<>(); + this.handleCommand(args); + } + + } catch (Exception e) { // NOSONAR + this.print("Failed to read param file " + paramFilePath); + this.print(e); + } } } catch (Exception e) { this.print(e); @@ -152,51 +218,57 @@ public class OnapCli { } } - public static String getDirectiveHelp() throws OnapCommandHelpFailed { - OnapCommandResult help = new OnapCommandResult(); - help.setType(OnapCommandResultType.TABLE); - help.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE); + public void verifyCommand(OnapCommand cmd) throws OnapCommandException { + List<Map<String, ?>> testSuite = OnapCommandRegistrar.getRegistrar().getTestSuite(cmd.getName()); - OnapCommandResultAttribute attr = new OnapCommandResultAttribute(); - attr.setName(OnapCommandConstants.NAME.toUpperCase()); - attr.setDescription(OnapCommandConstants.DESCRIPTION); - attr.setScope(OnapCommandResultAttributeScope.SHORT); - help.getRecords().add(attr); + OnapCommandResult testSuiteResult = new OnapCommandResult(); + testSuiteResult.setType(OnapCommandResultType.TABLE); + testSuiteResult.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE); + testSuiteResult.setIncludeTitle(true); - OnapCommandResultAttribute attrDesc = new OnapCommandResultAttribute(); - attrDesc.setName(OnapCommandConstants.DESCRIPTION.toUpperCase()); - attrDesc.setDescription(OnapCommandConstants.DESCRIPTION); - attrDesc.setScope(OnapCommandResultAttributeScope.SHORT); - help.getRecords().add(attrDesc); + OnapCommandResultAttribute sampleFileAtt = new OnapCommandResultAttribute(); + OnapCommandResultAttribute sampleIdAtt = new OnapCommandResultAttribute(); + OnapCommandResultAttribute resultAtt = new OnapCommandResultAttribute(); - attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_CLEAR); - attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_CLEAR_MSG); + sampleFileAtt.setName("Test"); + sampleIdAtt.setName("SampleId"); + resultAtt.setName("Result"); - attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_EXIT); - attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_EXIT_MSG); + testSuiteResult.setRecords(Arrays.asList(sampleFileAtt, + sampleIdAtt, + resultAtt)); - attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_VERSION); - attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_VERSION_MSG); + for (Map<String, ?> sampleTest : testSuite) { - attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_USE); - attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_USE_MSG); + sampleFileAtt.getValues().add((String) sampleTest.get(OnapCommandConstants.VERIFY_SAMPLE_FILE_ID)); + sampleIdAtt.getValues().add((String) sampleTest.get(OnapCommandConstants.VERIFY_SAMPLE_ID)); - attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_SET); - attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_SET_MSG); + cmd = OnapCommandRegistrar.getRegistrar().get(args.get(0)); + OnapCliArgsParser.populateParams(cmd.getParameters(), (List<String>) sampleTest.get(OnapCommandConstants.VERIFY_INPUT)); - attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_UNSET); - attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_UNSET_MSG); - attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_HELP); - attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_HELP_MSG); + Optional<OnapCommandParameter> contextOpt = cmd.getParameters().stream() + .filter(e -> e.getName().equals(OnapCommandConstants.VERIFY_CONTEXT_PARAM)) + .findFirst(); - attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_PROFILE); - attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_PROFILE_MSG); - try { - return "\n\nDirectives:\n" + help.print(); - } catch (OnapCommandException e) { - throw new OnapCommandHelpFailed(e); + if (contextOpt.isPresent()) { + HashMap map = new HashMap(); + map.put(OnapCommandConstants.VERIFY_MOCO, sampleTest.get(OnapCommandConstants.VERIFY_MOCO)); + contextOpt.get().setValue(map); + } + + OnapCommandResult testResult = cmd.execute(); + String actualOutput = testResult.print().trim(); + String expectedOutput = (String) sampleTest.get(OnapCommandConstants.VERIFY_OUPUT); + expectedOutput = expectedOutput == null ? "" : expectedOutput.trim(); + + if (actualOutput.equals(expectedOutput)) { + resultAtt.getValues().add(OnapCommandConstants.VERIFY_RESULT_PASS); + } else { + resultAtt.getValues().add(OnapCommandConstants.VERIFY_RESULT_FAIL); + } } + this.print(testSuiteResult.print()); } /** * Handles Interactive Mode. @@ -217,51 +289,56 @@ public class OnapCli { console.clearScreen(); continue; } - this.args = Arrays.asList(line.split(OnapCliConstants.PARAM_INTERACTIVE_ARG_SPLIT_PATTERN)); + this.args.clear(); + 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 input the product version to use, supported versions: " + + this.print("Please use it in the form of use <product-version>.\nSupported versions: " + OnapCommandRegistrar.getRegistrar().getAvailableProductVersions()); } else { try { OnapCommandRegistrar.getRegistrar().setEnabledProductVersion(args.get(1)); - console.close(); console = createConsoleReader(); } catch (OnapCommandException e) { this.print(e); } } + } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_HELP)) { try { this.print(OnapCommandRegistrar.getRegistrar().getHelpForEnabledProductVersion()); - this.print(this.getDirectiveHelp()); + this.print(OnapCli.getDirectiveHelp()); } catch (OnapCommandException e) { this.print(e); } + } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_VERSION)) { this.args = Arrays.asList(new String [] {this.getLongOption(OnapCliConstants.PARAM_VERSION_LONG)}); handleVersion(); + } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_PROFILE)) { if (args.size() == 1) { - this.print("Please use it in the form of 'profile <profile-name>'"); + this.print("Please use it in the form of 'profile <profile-name>'\n"); + this.print("Available profiles: "); + this.print(OnapCommandRegistrar.getRegistrar().getUserProfiles().toString()); } else { - this.args = Arrays.asList(new String [] { - this.getLongOption(OnapCliConstants.PARAM_PROFILE_LONG), - this.args.get(1)}); + this.args.set(0, this.getLongOption(OnapCliConstants.PARAM_PROFILE_LONG)); handleProfile(); } + } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_SET)) { if (args.size() > 1) { - String [] paramEntry = args.get(1).trim().split("="); - if (paramEntry.length >= 2) { + String [] paramEntry = args.get(1).trim().split("=", 2); + if (paramEntry.length == 2) { OnapCommandRegistrar.getRegistrar().addParamCache(paramEntry[0].trim(), paramEntry[1].trim()); } else { - this.print("Please use it in the form of 'set param-name=param-value'"); + this.print("Please use it in the form of 'set <param-name>=<param-value>'"); } } else { this.print(OnapCommandRegistrar.getRegistrar().getParamCache().toString()); } + } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_UNSET)) { if (args.size() > 1) { for (int i = 1; i <args.size(); i++) { @@ -274,7 +351,7 @@ public class OnapCli { continue; } - handleCommand(); + handleCommand(new ArrayList<>()); } } } catch (IOException e) { // NOSONAR @@ -287,46 +364,15 @@ public class OnapCli { TerminalFactory.get().restore(); } catch (Exception e) { // NOSONAR } - if (console != null) { - console.close(); - } this.exitSuccessfully(); } } } /** - * Creates console reader object. - * - * @return ConsoleReader - * @throws IOException - * exception - */ - private ConsoleReader createConsoleReader() throws IOException { - try(ConsoleReader console = new ConsoleReader()){ - try { - StringCompleter strCompleter = new StringCompleter(OnapCommandRegistrar.getRegistrar().listCommandsForEnabledProductVersion()); - strCompleter.add(OnapCliConstants.PARAM_INTERACTIVE_EXIT, - OnapCliConstants.PARAM_INTERACTIVE_CLEAR, - OnapCliConstants.PARAM_INTERACTIVE_USE, - OnapCliConstants.PARAM_INTERACTIVE_HELP, - OnapCliConstants.PARAM_INTERACTIVE_VERSION, - OnapCliConstants.PARAM_INTERACTIVE_SET, - OnapCliConstants.PARAM_INTERACTIVE_UNSET, - OnapCliConstants.PARAM_INTERACTIVE_PROFILE); - console.addCompleter(strCompleter); - console.setPrompt(OnapCliConstants.PARAM_INTERACTIVE_PROMPT + ":" + OnapCommandRegistrar.getRegistrar().getEnabledProductVersion() + ">"); - } catch (OnapCommandException e) { // NOSONAR - this.print("Failed to load oclip commands," + e.getMessage()); - } - return console; - } - } - - /** * Handles command. */ - public void handleCommand() { + public void handleCommand(List<String> params) { OnapCommand cmd; if (!args.isEmpty()) { try { @@ -340,7 +386,16 @@ public class OnapCli { this.exitFailure(); return; } + try { + + // verify + if(args.contains(OnapCommandConstants.VERIFY_LONG_OPTION) + || args.contains(OnapCommandConstants.VERIFY_SHORT_OPTION)) { + verifyCommand(cmd); + this.exitSuccessfully(); + return; + } // check for help or version if (args.size() == 2) { if (this.getLongOption(OnapCliConstants.PARAM_HELP_LOGN).equals(args.get(1)) @@ -358,6 +413,7 @@ public class OnapCli { } } + //refer params from profile for (OnapCommandParameter param: cmd.getParameters()) { if (OnapCommandRegistrar.getRegistrar().getParamCache().containsKey( cmd.getInfo().getService() + ":" + param.getLongOption())) { @@ -368,7 +424,13 @@ public class OnapCli { } } + //load the parameters value from the map read from param-file + if (params != null && !params.isEmpty()) { + OnapCliArgsParser.populateParams(cmd.getParameters(), params); + } + OnapCliArgsParser.populateParams(cmd.getParameters(), args); + OnapCommandResult result = cmd.execute(); this.print(result.getDebugInfo()); @@ -388,19 +450,6 @@ public class OnapCli { } } - private void generateSmapleYaml(OnapCommand cmd) throws OnapCommandException { - if (Boolean.parseBoolean(OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_ENABLED)) && this.getExitCode() == OnapCliConstants.EXIT_SUCCESS) { - try { - SampleYamlGenerator.generateSampleYaml(args, cmd.getResult().print(), - OnapCommandRegistrar.getRegistrar().getEnabledProductVersion(), - OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_TARGET_FOLDER) + "/" + cmd.getSchemaName().replaceAll(".yaml", "") + "-sample.yaml", - cmd.getResult().isDebug()); - } catch (IOException error) { - throw new OnapCommandInvalidSample(args.get(0), error); - } - } - } - /** * Handles all client input. */ @@ -416,11 +465,104 @@ public class OnapCli { } if (this.exitCode == -1) { + this.handleBatchCommand(); + } + + if (this.exitCode == -1) { this.handleInteractive(); } if (this.exitCode == -1) { - this.handleCommand(); + this.handleCommand(new ArrayList<>()); + } + } + + public static String getDirectiveHelp() throws OnapCommandHelpFailed { + OnapCommandResult help = new OnapCommandResult(); + help.setType(OnapCommandResultType.TABLE); + help.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE); + + OnapCommandResultAttribute attr = new OnapCommandResultAttribute(); + attr.setName(OnapCommandConstants.NAME.toUpperCase()); + attr.setDescription(OnapCommandConstants.DESCRIPTION); + attr.setScope(OnapCommandResultAttributeScope.SHORT); + help.getRecords().add(attr); + + OnapCommandResultAttribute attrDesc = new OnapCommandResultAttribute(); + attrDesc.setName(OnapCommandConstants.DESCRIPTION.toUpperCase()); + attrDesc.setDescription(OnapCommandConstants.DESCRIPTION); + attrDesc.setScope(OnapCommandResultAttributeScope.SHORT); + help.getRecords().add(attrDesc); + + attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_CLEAR); + attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_CLEAR_MSG); + + attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_EXIT); + attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_EXIT_MSG); + + attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_VERSION); + attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_VERSION_MSG); + + attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_USE); + attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_USE_MSG); + + attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_SET); + attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_SET_MSG); + + attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_UNSET); + attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_UNSET_MSG); + + attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_HELP); + attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_HELP_MSG); + + attr.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_PROFILE); + attrDesc.getValues().add(OnapCliConstants.PARAM_INTERACTIVE_PROFILE_MSG); + try { + return "\n\nDirectives:\n" + help.print(); + } catch (OnapCommandException e) { + throw new OnapCommandHelpFailed(e); + } + } + + /** + * Creates console reader object. + * + * @return ConsoleReader + * @throws IOException + * exception + */ + private ConsoleReader createConsoleReader() throws IOException { + ConsoleReader console = new ConsoleReader(); // NOSONAR + try { + StringCompleter strCompleter = new StringCompleter(OnapCommandRegistrar.getRegistrar().listCommandsForEnabledProductVersion()); + strCompleter.add(OnapCliConstants.PARAM_INTERACTIVE_EXIT, + OnapCliConstants.PARAM_INTERACTIVE_CLEAR, + OnapCliConstants.PARAM_INTERACTIVE_USE, + OnapCliConstants.PARAM_INTERACTIVE_HELP, + OnapCliConstants.PARAM_INTERACTIVE_VERSION, + OnapCliConstants.PARAM_INTERACTIVE_SET, + OnapCliConstants.PARAM_INTERACTIVE_UNSET, + OnapCliConstants.PARAM_INTERACTIVE_PROFILE); + console.addCompleter(strCompleter); + console.setPrompt(OnapCliConstants.PARAM_INTERACTIVE_PROMPT + ":" + OnapCommandRegistrar.getRegistrar().getEnabledProductVersion() + ">"); + } catch (OnapCommandException e) { // NOSONAR + this.print("Failed to load oclip commands," + e.getMessage()); + } + + return console; + } + + + private void generateSmapleYaml(OnapCommand cmd) throws OnapCommandException { + if (Boolean.parseBoolean(OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_ENABLED)) && this.getExitCode() == OnapCliConstants.EXIT_SUCCESS) { + try { + SampleYamlGenerator.generateSampleYaml(args, cmd.getResult().print(), + OnapCommandRegistrar.getRegistrar().getEnabledProductVersion(), + OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_TARGET_FOLDER) + "/" + cmd.getSchemaName().replaceAll(".yaml", "") + "-sample.yaml", + cmd.getResult().isDebug()); + } catch (IOException error) { + throw new OnapCommandInvalidSample(args.get(0), error); + } } } @@ -436,4 +578,4 @@ public class OnapCli { System.exit(cli.getExitCode()); } -} +}
\ No newline at end of file diff --git a/main/src/main/java/org/onap/cli/main/conf/OnapCliConstants.java b/main/src/main/java/org/onap/cli/main/conf/OnapCliConstants.java index c4a21614..4389a8cc 100644 --- a/main/src/main/java/org/onap/cli/main/conf/OnapCliConstants.java +++ b/main/src/main/java/org/onap/cli/main/conf/OnapCliConstants.java @@ -27,6 +27,9 @@ public final class OnapCliConstants { public static final String PARAM_PROFILE_SHORT = "c"; public static final String PARAM_PROFILE_LONG = "profile"; + public static final String PARAM_PARAM_FILE_SHORT = "p"; + public static final String PARAM_PARAM_FILE_LONG = "param-file"; + public static final int EXIT_SUCCESS = 0; public static final int EXIT_FAILURE = 1; diff --git a/main/src/main/java/org/onap/cli/main/utils/OnapCliArgsParser.java b/main/src/main/java/org/onap/cli/main/utils/OnapCliArgsParser.java index fdf6d5b8..d5807d79 100644 --- a/main/src/main/java/org/onap/cli/main/utils/OnapCliArgsParser.java +++ b/main/src/main/java/org/onap/cli/main/utils/OnapCliArgsParser.java @@ -105,7 +105,7 @@ public class OnapCliArgsParser { // end of the list or if its option rather than a value if ((i + 1) == args.size() || args.get(i + 1).startsWith("-")) { if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.BOOL)) { - paramMap.get(paramName).setValue("true"); + paramMap.get(paramName).setValue(true); continue; } throw new OnapCliArgumentValueMissing(args.get(i)); @@ -116,45 +116,40 @@ public class OnapCliArgsParser { paramMap.get(paramName).getName())); i++; continue; + } if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.TEXT)) { paramMap.get(paramName).setValue(readTextStringFromUrl(args.get(i + 1), paramMap.get(paramName).getName())); i++; continue; + } else if (paramMap.get(paramName).getParameterType() .equals(OnapCommandParameterType.ARRAY)) { Object value = paramMap.get(paramName).getValue(); - List<String> list; - if (value == "") { - list = new ArrayList<>(); - } else { - list = convertJsonToListString(paramMap.get(paramName).getName(), - value.toString()); - } - list.add(args.get(i + 1)); + List<String> list = (List<String>) value; + + list.add(readTextStringFromUrl(args.get(i + 1), paramMap.get(paramName).getName())); paramMap.get(paramName).setValue(list); i++; continue; - } else if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.MAP)) { - Object value = paramMap.get(paramName).getValue(); - Map<String, String> map; + } else if (paramMap.get(paramName).getParameterType() + .equals(OnapCommandParameterType.MAP)) { + Object value = paramMap.get(paramName).getValue(); - if (value == "") { - map = new HashMap<>(); - } else { - map = convertJsonToMapString(paramMap.get(paramName).getName(), - value.toString()); - } + Map<String, String> map = (Map<String, String>) value; String arg = args.get(i + 1); - String[] argArr = arg.split("="); + String[] argArr = arg.split("=", 2); if (argArr.length != 2) { - throw new OnapCliInvalidArgument(paramMap.get(paramName).getName()); + throw new OnapCliInvalidArgument( + paramMap.get(paramName).getName(), + "it should be in the form of <key>=<value>"); } - map.put(argArr[0], argArr[1]); + //Make sure to read values from file, in case file path is given. + map.put(argArr[0], readTextStringFromUrl(argArr[1], paramMap.get(paramName).getName())); paramMap.get(paramName).setValue(map); i++; continue; @@ -169,7 +164,9 @@ public class OnapCliArgsParser { // it is positional option // Positional arg is missing from the params if (positionalIdx >= positionArgs.size()) { - throw new OnapCliInvalidArgument(args.get(i)); + throw new OnapCliInvalidArgument( + args.get(i), + "No positional argument is defined for this one"); } paramMap.get(positionArgs.get(positionalIdx)).setValue(args.get(i)); diff --git a/main/src/test/java/org/onap/cli/main/OnapCliMainTest.java b/main/src/test/java/org/onap/cli/main/OnapCliMainTest.java index f7401904..6d7dbdd2 100644 --- a/main/src/test/java/org/onap/cli/main/OnapCliMainTest.java +++ b/main/src/test/java/org/onap/cli/main/OnapCliMainTest.java @@ -16,19 +16,22 @@ package org.onap.cli.main; -import static org.junit.Assert.fail; - -import java.io.IOException; - +import jline.console.ConsoleReader; +import mockit.Invocation; +import mockit.Mock; +import mockit.MockUp; import org.junit.Test; +import org.onap.cli.fw.cmd.OnapCommand; import org.onap.cli.fw.error.OnapCommandException; import org.onap.cli.fw.error.OnapCommandHelpFailed; import org.onap.cli.fw.registrar.OnapCommandRegistrar; +import org.onap.cli.fw.schema.OnapCommandSchemaLoader; -import jline.console.ConsoleReader; -import mockit.Invocation; -import mockit.Mock; -import mockit.MockUp; +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; public class OnapCliMainTest { @@ -152,6 +155,13 @@ public class OnapCliMainTest { } cli = new OnapCli(new String[] {}); + mockConsole("profile"); + try { + cli.handleInteractive(); + } catch (Exception e) { + } + + cli = new OnapCli(new String[] {}); mockConsole("version"); try { cli.handleInteractive(); diff --git a/main/src/test/java/org/onap/cli/main/utils/OnapCliUtilsTest.java b/main/src/test/java/org/onap/cli/main/utils/OnapCliUtilsTest.java index eb2ca294..c3627ca2 100644 --- a/main/src/test/java/org/onap/cli/main/utils/OnapCliUtilsTest.java +++ b/main/src/test/java/org/onap/cli/main/utils/OnapCliUtilsTest.java @@ -21,6 +21,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.Optional; import java.util.Set; import org.junit.Assert; @@ -255,7 +257,7 @@ public class OnapCliUtilsTest { OnapCliArgsParser.populateParams(paramslist, Arrays.asList("show", "--map", "param1=value1", "--map", "param2=value2")); - Assert.assertEquals("{\"param1\":\"value1\",\"param2\":\"value2\"}", paramslist.iterator().next().getValue().toString()); + Assert.assertEquals("{param1=value1, param2=value2}", paramslist.iterator().next().getValue().toString()); } @Test(expected = OnapCliInvalidArgument.class) @@ -360,4 +362,19 @@ public class OnapCliUtilsTest { Assert.assertEquals("--json-param", paramslist.iterator().next().getValue()); } + + @Test + public void testArrayCommandArg() throws OnapCommandException { + OnapCommandParameter arrParam = new OnapCommandParameter(); + arrParam.setShortOption("q"); + arrParam.setParameterType(OnapCommandParameterType.ARRAY); + arrParam.setName("array-param"); + Set<OnapCommandParameter> paramslist = new HashSet<>(); + paramslist.add(arrParam); + String[] args = new String[] { "sample-create", "-q", "test1", "-q", "test2" }; + + OnapCliArgsParser.populateParams(paramslist, Arrays.asList(args)); + Assert.assertTrue(((List<String>) arrParam.getValue()) + .containsAll(Arrays.asList("test1", "test2"))); + } }
\ No newline at end of file diff --git a/main/src/test/resources/schema-validate-param-file.yaml b/main/src/test/resources/schema-validate-param-file.yaml new file mode 100644 index 00000000..0da20116 --- /dev/null +++ b/main/src/test/resources/schema-validate-param-file.yaml @@ -0,0 +1,3 @@ +one: + - internal-schema: true + - schema-location: catalog.yaml
\ No newline at end of file @@ -20,7 +20,7 @@ <parent> <groupId>org.onap.oparent</groupId> <artifactId>oparent</artifactId> - <version>1.0.0-SNAPSHOT</version> + <version>1.1.0</version> </parent> <groupId>org.onap.cli</groupId> diff --git a/products/onap-amsterdam/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-create-schema-1.1-moco.json b/products/onap-amsterdam/features/aai/src/main/resources/open-cli-sample/cloud-region/cloud-create-schema-1.1-moco.json index 223ebd26..223ebd26 100644 --- a/products/onap-amsterdam/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-create-schema-1.1-moco.json +++ b/products/onap-amsterdam/features/aai/src/main/resources/open-cli-sample/cloud-region/cloud-create-schema-1.1-moco.json diff --git a/products/onap-amsterdam/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-create-schema-1.1-sample.yaml b/products/onap-amsterdam/features/aai/src/main/resources/open-cli-sample/cloud-region/cloud-create-schema-1.1-sample.yaml index 6a665584..211fecbb 100644 --- a/products/onap-amsterdam/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-create-schema-1.1-sample.yaml +++ b/products/onap-amsterdam/features/aai/src/main/resources/open-cli-sample/cloud-region/cloud-create-schema-1.1-sample.yaml @@ -20,5 +20,5 @@ samples: name: cloud-create input: --cloud-name huawei-cloud --region-name bangalore moco: cloud-create-schema-1.1-moco.json - output: | + output: diff --git a/products/onap-amsterdam/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-list-schema-1.1-moco.json b/products/onap-amsterdam/features/aai/src/main/resources/open-cli-sample/cloud-region/cloud-list-schema-1.1-moco.json index 2e5b1db0..f5e4e444 100644 --- a/products/onap-amsterdam/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-list-schema-1.1-moco.json +++ b/products/onap-amsterdam/features/aai/src/main/resources/open-cli-sample/cloud-region/cloud-list-schema-1.1-moco.json @@ -1,4 +1,4 @@ -[ { +[{ "request" : { "method" : "get", "uri" : "/aai/v11/cloud-infrastructure/cloud-regions", @@ -31,4 +31,4 @@ } ] } } -} ]
\ No newline at end of file +}]
\ No newline at end of file diff --git a/products/onap-amsterdam/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-list-schema-1.1-sample.yaml b/products/onap-amsterdam/features/aai/src/main/resources/open-cli-sample/cloud-region/cloud-list-schema-1.1-sample.yaml index d64a1833..d64a1833 100644 --- a/products/onap-amsterdam/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-list-schema-1.1-sample.yaml +++ b/products/onap-amsterdam/features/aai/src/main/resources/open-cli-sample/cloud-region/cloud-list-schema-1.1-sample.yaml diff --git a/products/onap-beijing/auth/pom.xml b/products/onap-beijing/auth/pom.xml new file mode 100644 index 00000000..0edd52c4 --- /dev/null +++ b/products/onap-beijing/auth/pom.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + 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. + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 + http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.onap.cli</groupId> + <artifactId>cli-products-onap-beijing</artifactId> + <version>2.0.0</version> + </parent> + + <artifactId>cli-products-onap-beijing-auth</artifactId> + <name>cli/products/onap-beijing/auth</name> + <packaging>jar</packaging> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + </plugin> + </plugins> + </build> +</project> diff --git a/products/onap-beijing/auth/src/main/java/org/onap/cli/cmd/auth/OnapBasicAuthLoginCommandBeijing.java b/products/onap-beijing/auth/src/main/java/org/onap/cli/cmd/auth/OnapBasicAuthLoginCommandBeijing.java new file mode 100644 index 00000000..07dcab09 --- /dev/null +++ b/products/onap-beijing/auth/src/main/java/org/onap/cli/cmd/auth/OnapBasicAuthLoginCommandBeijing.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.onap.cli.cmd.auth; + +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.http.cmd.BasicAuthLoginCommand; +import org.onap.cli.fw.schema.OnapCommandSchema; + +@OnapCommandSchema(schema = "basic-login-onap-beijing.yaml") +public class OnapBasicAuthLoginCommandBeijing extends BasicAuthLoginCommand { + + @Override + protected void run() throws OnapCommandException { + super.run(); + } +} diff --git a/products/onap-beijing/auth/src/main/java/org/onap/cli/cmd/auth/OnapBasicAuthLogoutCommandBeijing.java b/products/onap-beijing/auth/src/main/java/org/onap/cli/cmd/auth/OnapBasicAuthLogoutCommandBeijing.java new file mode 100644 index 00000000..ea866ff6 --- /dev/null +++ b/products/onap-beijing/auth/src/main/java/org/onap/cli/cmd/auth/OnapBasicAuthLogoutCommandBeijing.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.onap.cli.cmd.auth; + +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.http.cmd.BasicAuthLogoutCommand; +import org.onap.cli.fw.schema.OnapCommandSchema; + +@OnapCommandSchema(schema = "basic-logout-onap-beijing.yaml") +public class OnapBasicAuthLogoutCommandBeijing extends BasicAuthLogoutCommand { + + @Override + protected void run() throws OnapCommandException { + super.run(); + } +} diff --git a/products/onap-beijing/auth/src/main/java/org/onap/cli/cmd/auth/OnapSdcBasicAuthLoginCommandBeijing.java b/products/onap-beijing/auth/src/main/java/org/onap/cli/cmd/auth/OnapSdcBasicAuthLoginCommandBeijing.java new file mode 100644 index 00000000..6b8fc14a --- /dev/null +++ b/products/onap-beijing/auth/src/main/java/org/onap/cli/cmd/auth/OnapSdcBasicAuthLoginCommandBeijing.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.onap.cli.cmd.auth; + +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.http.cmd.BasicAuthLoginCommand; +import org.onap.cli.fw.schema.OnapCommandSchema; + +@OnapCommandSchema(schema = "basic-login-onap-sdc-beijing.yaml") +public class OnapSdcBasicAuthLoginCommandBeijing extends BasicAuthLoginCommand { + + @Override + protected void run() throws OnapCommandException { + super.run(); + } +} diff --git a/products/onap-beijing/auth/src/main/resources/META-INF/services/org.onap.cli.fw.cmd.OnapCommand b/products/onap-beijing/auth/src/main/resources/META-INF/services/org.onap.cli.fw.cmd.OnapCommand new file mode 100644 index 00000000..59c02928 --- /dev/null +++ b/products/onap-beijing/auth/src/main/resources/META-INF/services/org.onap.cli.fw.cmd.OnapCommand @@ -0,0 +1,3 @@ +org.onap.cli.cmd.auth.OnapBasicAuthLoginCommandBeijing +org.onap.cli.cmd.auth.OnapSdcBasicAuthLoginCommandBeijing +org.onap.cli.cmd.auth.OnapBasicAuthLogoutCommandBeijing
\ No newline at end of file diff --git a/products/onap-beijing/auth/src/main/resources/open-cli-schema/basic-login-onap-beijing.yaml b/products/onap-beijing/auth/src/main/resources/open-cli-schema/basic-login-onap-beijing.yaml new file mode 100644 index 00000000..9e80c3e6 --- /dev/null +++ b/products/onap-beijing/auth/src/main/resources/open-cli-schema/basic-login-onap-beijing.yaml @@ -0,0 +1,43 @@ +# 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 + +name: basic-login + +description: ONAP basic login auth command + +info: + product: onap-beijing + service: basic-auth + type: auth + author: ONAP CLI Team onap-discuss@lists.onap.org + +results: + direction: portrait + attributes: + - name: Authorization + description: Authorization + scope: short + type: string + - name: X-TransactionId + description: X-TransactionId + scope: short + type: string + default_value: req-$s{uuid} + - name: X-FromAppId + description: X-FromAppId + scope: short + type: string + default_value: ONAP CLI diff --git a/products/onap-beijing/auth/src/main/resources/open-cli-schema/basic-login-onap-sdc-beijing.yaml b/products/onap-beijing/auth/src/main/resources/open-cli-schema/basic-login-onap-sdc-beijing.yaml new file mode 100644 index 00000000..b57ca5d9 --- /dev/null +++ b/products/onap-beijing/auth/src/main/resources/open-cli-schema/basic-login-onap-sdc-beijing.yaml @@ -0,0 +1,50 @@ +# 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 + +name: sdc-basic-login + +description: ONAP basic login auth command + + +info: + product: onap-beijing + service: sdc-basic-auth + type: auth + author: ONAP CLI Team onap-discuss@lists.onap.org + + +results: + direction: portrait + attributes: + - name: Authorization + description: Authorization + scope: short + type: string + - name: X-TransactionId + description: X-TransactionId + scope: short + type: string + default_value: req-$s{uuid} + - name: X-FromAppId + description: X-FromAppId + scope: short + type: string + default_value: ONAP CLI + - name: USER_ID + description: USER_ID for sdc + scope: short + type: string + default_value: ${host-username}
\ No newline at end of file diff --git a/products/onap-beijing/auth/src/main/resources/open-cli-schema/basic-logout-onap-beijing.yaml b/products/onap-beijing/auth/src/main/resources/open-cli-schema/basic-logout-onap-beijing.yaml new file mode 100644 index 00000000..1f90cfaa --- /dev/null +++ b/products/onap-beijing/auth/src/main/resources/open-cli-schema/basic-logout-onap-beijing.yaml @@ -0,0 +1,34 @@ +# 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 + +name: basic-logout + +description: ONAP basic logout auth command + +info: + product: onap-beijing + service: basic-auth + type: auth + author: ONAP CLI Team onap-discuss@lists.onap.org + + +parameters: + - name: host-username + is_include: false + - name: host-password + is_include: false + - name: no-auth + is_include: false
\ No newline at end of file diff --git a/products/onap-beijing/catalog/pom.xml b/products/onap-beijing/catalog/pom.xml new file mode 100644 index 00000000..57562f59 --- /dev/null +++ b/products/onap-beijing/catalog/pom.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + 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. + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 + http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.onap.cli</groupId> + <artifactId>cli-products-onap-beijing</artifactId> + <version>2.0.0</version> + </parent> + + <artifactId>cli-products-onap-beijing-catalog</artifactId> + <name>cli/products/onap-beijing/catalog</name> + <packaging>jar</packaging> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + </plugin> + </plugins> + </build> +</project> diff --git a/products/onap-beijing/catalog/src/main/resources/open-cli-schema/catalog-onap-beijing.yaml b/products/onap-beijing/catalog/src/main/resources/open-cli-schema/catalog-onap-beijing.yaml new file mode 100644 index 00000000..0c8b5974 --- /dev/null +++ b/products/onap-beijing/catalog/src/main/resources/open-cli-schema/catalog-onap-beijing.yaml @@ -0,0 +1,69 @@ +# 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 + +name: catalog + +description: ONAP catalog command to find the base path for service. + + +info: + product: onap-beijing + service: msb + type: catalog + author: ONAP CLI Team onap-discuss@lists.onap.org + + +parameters: + - name: catalog-service-name + type: string + description: service name registered in catalog service + short_option: l + long_option: catalog-service-name + is_optional: false + - name: catalog-service-version + type: string + description: service version registered in catalog service + short_option: i + long_option: catalog-service-version + is_optional: false +results: + direction: portrait + attributes: + - name: catalog-service-host-url + description: Service connection url + scope: short + type: string + default_value: ${host-url} + - name: catalog-service-base-path + description: service base path, to append with host-url for connecting the service. + scope: short + type: string + default_value: / +http: + service: + mode: direct + auth: none + request: + uri: /services/${catalog-service-name}/version/${catalog-service-version} + method: GET + success_codes: + - 201 + - 200 + result_map: + catalog-service-base-path: $b{$.url} + catalog-service-host-url: ${host-url} + sample_response: + body: '{"serviceName":"test","version":"v1","url":"/api/test/v1","protocol":"REST","visualRange":"1","lb_policy":"hash","nodes":[{"ip":"127.0.0.1","port":"8012","ttl":0,"nodeId":"test_127.0.0.1_8012","expiration":"2017-02-10T05:33:25Z","created_at":"2017-02-10T05:33:25Z","updated_at":"2017-02-10T05:33:25Z"}],"status":"1"}' diff --git a/products/onap-beijing/features/aai/pom.xml b/products/onap-beijing/features/aai/pom.xml new file mode 100644 index 00000000..539a141f --- /dev/null +++ b/products/onap-beijing/features/aai/pom.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Copyright 2017 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. + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 + http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.onap.cli</groupId> + <artifactId>cli-products-onap-beijing-features</artifactId> + <version>2.0.0</version> + </parent> + + <artifactId>cli-products-onap-beijing-features-aai</artifactId> + <name>cli/products/onap-beijing/features/aai</name> + <packaging>jar</packaging> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + </plugin> + </plugins> + </build> +</project> diff --git a/products/onap-beijing/features/aai/src/main/resources/open-cli-schema/cloud-region/cloud-list-schema-beijing.yaml b/products/onap-beijing/features/aai/src/main/resources/open-cli-schema/cloud-region/cloud-list-schema-beijing.yaml new file mode 100644 index 00000000..4da0661d --- /dev/null +++ b/products/onap-beijing/features/aai/src/main/resources/open-cli-schema/cloud-region/cloud-list-schema-beijing.yaml @@ -0,0 +1,73 @@ +# Copyright 2017-18 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 +name: cloud-list +description: List the configured clouds and Onap service subscriptions + +info: + product: onap-beijing + service: aai + author: ONAP CLI Team onap-discuss@lists.onap.org + +results: + direction: landscape + attributes: + - name: cloud + description: Onap cloud + scope: short + type: string + - name: region + description: Onap cloud region + scope: short + type: string + - name: tenant + description: Onap cloud tenat + scope: long + type: string + - name: tenant-id + description: Onap cloud tenat id + scope: long + type: string + - name: customer + description: Onap cloud customer + scope: long + type: string + - name: service + description: Onap cloud service + scope: long + type: string + - name: resource-version + description: Onap cloud resource version + scope: short + type: string +http: + service: + auth: basic + mode: direct + request: + uri: /aai/v12/cloud-infrastructure/cloud-regions + method: GET + success_codes: + - 200 + result_map: + cloud: $b{cloud-region.[*].cloud-owner} + region: $b{cloud-region.[*].cloud-region-id} + resource-version: $b{cloud-region.[*].resource-version} + tenant: $b{cloud-region.[*].tenants.tenant.[*].tenant-name} + tenant-id: $b{cloud-region.[*].tenants.tenant.[*].tenant-id} + customer: $b{cloud-region.[*].tenants.tenant.[*].relationship-list.relationship.[*].relationship-data.[?(@.relationship-key == 'customer.global-customer-id')].relationship-value} + service: $b{cloud-region.[*].tenants.tenant.[*].relationship-list.relationship.[*].relationship-data.[?(@.relationship-key == 'service-subscription.service-type')].relationship-value} + sample_response: + body: '{"cloud-region":[{"cloud-owner":"Rackspace","cloud-region-id":"RegionOne","cloud-type":"SharedNode","owner-defined-type":"OwnerType","cloud-region-version":"v1","cloud-zone":"CloudZone","resource-version":"1500729864","tenants":{"tenant":[{"tenant-id":"e69e6d64b44347509c3fc512391f34a6","tenant-name":"onap","resource-version":"1500729865","relationship-list":{"relationship":[{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Demonstration/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Demonstration"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Demonstration123/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Demonstration123"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/u1/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"u1"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/u2/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"u2"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/DemoCust_7151e36a-1a57-4993-b513-54134f2b8f19/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"DemoCust_7151e36a-1a57-4993-b513-54134f2b8f19"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Demonstration/service-subscriptions/service-subscription/vLB/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Demonstration"},{"relationship-key":"service-subscription.service-type","relationship-value":"vLB"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Linan/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Linan"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Linan/service-subscriptions/service-subscription/vLB/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Linan"},{"relationship-key":"service-subscription.service-type","relationship-value":"vLB"}]}]}}]}}]}' diff --git a/products/onap-beijing/features/aai/src/main/resources/open-cli-schema/pnf/.gitkeep b/products/onap-beijing/features/aai/src/main/resources/open-cli-schema/pnf/.gitkeep new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/products/onap-beijing/features/aai/src/main/resources/open-cli-schema/pnf/.gitkeep @@ -0,0 +1 @@ + diff --git a/products/onap-beijing/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-list-schema-beijing-moco.json b/products/onap-beijing/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-list-schema-beijing-moco.json new file mode 100644 index 00000000..9162bb59 --- /dev/null +++ b/products/onap-beijing/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-list-schema-beijing-moco.json @@ -0,0 +1,34 @@ +[ { + "request" : { + "method" : "get", + "uri" : "/aai/v12/cloud-infrastructure/cloud-regions", + "headers" : { + "Authorization" : "Basic QUFJOkFBSQ==", + "X-FromAppId" : "onap-cli", + "Accept" : "application/json", + "X-TransactionId" : "req-77c08aa0-662e-4d32-9206-bd569c3bf61b", + "Content-Type" : "application/json" + }, + "json" : null + }, + "response" : { + "status" : 200, + "json" : { + "cloud-region" : [ { + "cloud-owner" : "huawei-cloud", + "cloud-region-id" : "bangalore", + "sriov-automation" : false, + "resource-version" : "1509027332165" + }, { + "cloud-owner" : "Rackspace", + "cloud-region-id" : "RegionOne", + "cloud-type" : "SharedNode", + "owner-defined-type" : "OwnerType", + "cloud-region-version" : "v1", + "cloud-zone" : "CloudZone", + "sriov-automation" : false, + "resource-version" : "1508827902543" + } ] + } + } +} ]
\ No newline at end of file diff --git a/products/onap-beijing/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-list-schema-beijing-sample.yaml b/products/onap-beijing/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-list-schema-beijing-sample.yaml new file mode 100644 index 00000000..21ce62f3 --- /dev/null +++ b/products/onap-beijing/features/aai/src/test/resources/open-cli-sample/cloud-region/cloud-list-schema-beijing-sample.yaml @@ -0,0 +1,30 @@ +# Copyright 2017-18 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_sample_version: 1.0 +name: cloud-list +version: onap-amsterdam +samples: + sample1: + name: cloud-list + input: + moco: cloud-list-schema-beijing-moco.json + output: | + +--------------+------------+------------------+ + |cloud |region |resource-version | + +--------------+------------+------------------+ + |huawei-cloud |bangalore |1509027332165 | + +--------------+------------+------------------+ + |Rackspace |RegionOne |1508827902543 | + +--------------+------------+------------------+ diff --git a/products/onap-beijing/features/aai/src/test/resources/open-cli-sample/pnf/.gitkeep b/products/onap-beijing/features/aai/src/test/resources/open-cli-sample/pnf/.gitkeep new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/products/onap-beijing/features/aai/src/test/resources/open-cli-sample/pnf/.gitkeep @@ -0,0 +1 @@ + diff --git a/products/onap-beijing/features/pom.xml b/products/onap-beijing/features/pom.xml new file mode 100644 index 00000000..856d0f91 --- /dev/null +++ b/products/onap-beijing/features/pom.xml @@ -0,0 +1,69 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Copyright 2017 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. + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 + http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.onap.cli</groupId> + <artifactId>cli-products-onap-beijing</artifactId> + <version>2.0.0</version> + </parent> + + <artifactId>cli-products-onap-beijing-features</artifactId> + <name>cli/products/onap-beijing/features</name> + <packaging>pom</packaging> + + <modules> + <module>aai</module> + </modules> + + <build> + <pluginManagement> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + <executions> + <execution> + <id>copy-artifact</id> + <phase>package</phase> + <goals> + <goal>copy</goal> + </goals> + <configuration> + <artifactItems> + <artifactItem> + <groupId>${project.groupId}</groupId> + <artifactId>${project.artifactId}</artifactId> + <version>${project.version}</version> + <type>${project.packaging}</type> + </artifactItem> + </artifactItems> + <!-- copy to products dependencies --> + <outputDirectory>../../../../products/target/lib</outputDirectory> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </pluginManagement> + </build> +</project> diff --git a/products/onap-beijing/pom.xml b/products/onap-beijing/pom.xml new file mode 100644 index 00000000..a2a8258a --- /dev/null +++ b/products/onap-beijing/pom.xml @@ -0,0 +1,70 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + 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. + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 + http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.onap.cli</groupId> + <artifactId>cli-products</artifactId> + <version>2.0.0</version> + </parent> + + <artifactId>cli-products-onap-beijing</artifactId> + <name>cli/products/onap-beijing</name> + <packaging>pom</packaging> + + <modules> + <module>features</module> + <module>auth</module> + <module>catalog</module> + </modules> + <build> + <pluginManagement> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + <executions> + <execution> + <id>copy-artifact</id> + <phase>package</phase> + <goals> + <goal>copy</goal> + </goals> + <configuration> + <artifactItems> + <artifactItem> + <groupId>${project.groupId}</groupId> + <artifactId>${project.artifactId}</artifactId> + <version>${project.version}</version> + <type>${project.packaging}</type> + </artifactItem> + </artifactItems> + <!-- copy to products dependencies --> + <outputDirectory>../../../products/target/lib</outputDirectory> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </pluginManagement> + </build> +</project> diff --git a/products/pom.xml b/products/pom.xml index 0ddfeef1..1f607ca1 100644 --- a/products/pom.xml +++ b/products/pom.xml @@ -59,11 +59,19 @@ <activeByDefault>true</activeByDefault> </activation> <modules> - <module>openecomp</module> <module>onap-amsterdam</module> + <module>onap-beijing</module> + </modules> + </profile> + <profile> + <id>eol</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <modules> + <module>openecomp</module> </modules> </profile> - </profiles> <build> <pluginManagement> diff --git a/profiles/http/pom.xml b/profiles/http/pom.xml index 1c9e037f..913c8cec 100644 --- a/profiles/http/pom.xml +++ b/profiles/http/pom.xml @@ -59,7 +59,22 @@ <version>1.19</version> <scope>test</scope> </dependency> - </dependencies> + <dependency> + <groupId>com.github.dreamhead</groupId> + <artifactId>moco-runner</artifactId> + <version>0.12.0</version> + <exclusions> + <exclusion> + <groupId>log4j</groupId> + <artifactId>log4j</artifactId> + </exclusion> + <exclusion> + <groupId>ch.qos.logback</groupId> + <artifactId>logback-classic</artifactId> + </exclusion> + </exclusions> + </dependency> + </dependencies> <build> <plugins> <plugin> diff --git a/profiles/http/src/main/java/org/onap/cli/fw/http/cmd/OnapHttpCommand.java b/profiles/http/src/main/java/org/onap/cli/fw/http/cmd/OnapHttpCommand.java index 17d9c731..9477cfa9 100644 --- a/profiles/http/src/main/java/org/onap/cli/fw/http/cmd/OnapHttpCommand.java +++ b/profiles/http/src/main/java/org/onap/cli/fw/http/cmd/OnapHttpCommand.java @@ -16,13 +16,6 @@ package org.onap.cli.fw.http.cmd; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - import org.onap.cli.fw.cmd.OnapCommand; import org.onap.cli.fw.cmd.OnapCommandType; import org.onap.cli.fw.conf.OnapCommandConfig; @@ -35,8 +28,10 @@ import org.onap.cli.fw.http.conf.OnapCommandHttpConstants; import org.onap.cli.fw.http.connect.HttpInput; import org.onap.cli.fw.http.connect.HttpResult; import org.onap.cli.fw.http.error.OnapCommandFailedMocoGenerate; +import org.onap.cli.fw.http.mock.MocoServer; import org.onap.cli.fw.http.schema.OnapCommandSchemaHttpLoader; import org.onap.cli.fw.http.utils.OnapCommandHttpUtils; +import org.onap.cli.fw.input.OnapCommandParameter; import org.onap.cli.fw.output.OnapCommandResultAttribute; import org.onap.cli.fw.schema.OnapCommandSchema; import org.onap.cli.fw.utils.OnapCommandUtils; @@ -44,6 +39,14 @@ import org.onap.cli.http.mock.MockJsonGenerator; import org.onap.cli.http.mock.MockRequest; import org.onap.cli.http.mock.MockResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; + /** * Oclip http Command. * @@ -61,6 +64,10 @@ public class OnapHttpCommand extends OnapCommand { private OnapCommandHttpService oclipService = new OnapCommandHttpService(); + private MocoServer mocoServer; + + boolean shouldVerify = false; + public OnapHttpCommand() { super.addDefaultSchemas(OnapCommandHttpConstants.DEFAULT_PARAMETER_HTTP_FILE_NAME); } @@ -126,11 +133,64 @@ public class OnapHttpCommand extends OnapCommand { private boolean isAuthRequired() { return !this.getService().isNoAuth() - && "false".equals(this.getParametersMap().get(OnapCommandHttpConstants.DEFAULT_PARAMETER_NO_AUTH).getValue()) + && !(Boolean) (this.getParametersMap().get(OnapCommandHttpConstants.DEFAULT_PARAMETER_NO_AUTH).getValue()) && (this.getInfo().getCommandType().equals(OnapCommandType.CMD) || this.getInfo().getCommandType().equals(OnapCommandType.CATALOG)); } + private Optional<OnapCommandParameter> findParameterByName(String parameterName) { + return this.getParameters().stream() + .filter(e -> e.getName().equals(parameterName)) + .findFirst(); + } + + @Override + protected void preRun() throws OnapCommandException { + Optional<OnapCommandParameter> verifyOpt = this.getParameters().stream() + .filter(e -> e.getName().equals("verify")) + .findFirst(); + if(verifyOpt.isPresent()) { + shouldVerify = (boolean) verifyOpt.get().getValue(); + } + + if (shouldVerify) { + Optional<OnapCommandParameter> hostUrlParamOpt = findParameterByName(OnapCommandHttpConstants.VERIFY_HOST_PARAMETER_OPT); + Optional<OnapCommandParameter> noAuthParamOpt = findParameterByName(OnapCommandHttpConstants.VERIFY_NO_AUTH_PARAMETER_OPT); + + if (hostUrlParamOpt.isPresent()) { + OnapCommandParameter onapCommandParameter = hostUrlParamOpt.get(); + onapCommandParameter.setValue( + OnapCommandConfig.getPropertyValue(OnapCommandHttpConstants.VERIFY_MOCO_HOST) + + ":" + OnapCommandConfig.getPropertyValue(OnapCommandHttpConstants.VERIFY_MOCO_PORT)); + } + + if (noAuthParamOpt.isPresent()) { + OnapCommandParameter onapCommandParameter = noAuthParamOpt.get(); + onapCommandParameter.setValue(true); + } + + + Optional<OnapCommandParameter> contextOpt = this.getParameters().stream() + .filter(e -> e.getName().equals(OnapCommandConstants.VERIFY_CONTEXT_PARAM)) + .findFirst(); + + if (contextOpt.isPresent()) { + OnapCommandParameter context = contextOpt.get(); + String mockedFile = ((Map<String, String>)context.getValue()).get(OnapCommandConstants.VERIFY_MOCO); + + mocoServer = new MocoServer(mockedFile); + mocoServer.start(); + } + } + } + + @Override + protected void postRun() throws OnapCommandException { + if (shouldVerify) { + mocoServer.stop(); + } + } + @Override protected void run() throws OnapCommandException { try { diff --git a/profiles/http/src/main/java/org/onap/cli/fw/http/conf/OnapCommandHttpConstants.java b/profiles/http/src/main/java/org/onap/cli/fw/http/conf/OnapCommandHttpConstants.java index b18545cb..185582cb 100644 --- a/profiles/http/src/main/java/org/onap/cli/fw/http/conf/OnapCommandHttpConstants.java +++ b/profiles/http/src/main/java/org/onap/cli/fw/http/conf/OnapCommandHttpConstants.java @@ -83,12 +83,31 @@ public class OnapCommandHttpConstants { public static final String CATALOG_SERVICE_BASE_PATH = "catalog-service-base-path"; public static final String CATALOG_SERVICE_HOST_URL = "catalog-service-host-url"; - public static final String AUTH_VALUES = "cli.schema.auth_values"; - public static final String MODE_VALUES = "cli.schema.mode_values"; - public static final String SERVICE_PARAMS_LIST = "cli.schema.service_params_list"; - public static final String SERVICE_PARAMS_MANDATORY_LIST = "cli.schema.service_params_mandatory_list"; + public static final String AUTH_VALUES = "cli.schema.http.service.auth.values"; + public static final String MODE_VALUES = "cli.schema.http.service.mode.values"; + public static final String SERVICE_PARAMS_LIST = "cli.schema.http.service.sections"; + public static final String SERVICE_PARAMS_MANDATORY_LIST = "cli.schema.http.service.sections.mandatory"; public static final String DEFAULT_PARAMETER_NO_CATALOG = "no-catalog"; + + //context param + public static final String CONTEXT = "context"; + public static final String CONTEXT_REMOVE_EMPTY_JSON_NODES = "remove_empty_node"; + + // moco server const + public static final String VERIFY_MOCO_HOST = "cli.verify.host"; + public static final String VERIFY_MOCO_PORT = "cli.verify.port"; + + public static final String VERIFY_HOST_PARAMETER_OPT = DEAFULT_PARAMETER_HOST_URL; + public static final String VERIFY_NO_AUTH_PARAMETER_OPT = DEFAULT_PARAMETER_NO_AUTH; + + public static final String VERIFY_REQUEST_URI = URI; + public static final String VERIFY_RESPONSE_STATUS = "status"; + public static final String VERIFY_RESPONSE_JSON = "json"; + public static final String VERIFY_REQUEST = REQUEST; + public static final String VERIFY_RESPONSE = "response"; + public static final String VERIFY_CONTENT_TYPE = "Content-Type"; + public static final String VERIFY_CONTENT_TYPE_VALUE = APPLICATION_JSON; } diff --git a/profiles/http/src/main/java/org/onap/cli/fw/http/connect/HttpInput.java b/profiles/http/src/main/java/org/onap/cli/fw/http/connect/HttpInput.java index 722dd12e..f5922796 100644 --- a/profiles/http/src/main/java/org/onap/cli/fw/http/connect/HttpInput.java +++ b/profiles/http/src/main/java/org/onap/cli/fw/http/connect/HttpInput.java @@ -38,6 +38,8 @@ public class HttpInput { private Map<String, String> reqCookies = new HashMap<>(); + private Map<String, String> context = new HashMap<>(); + private boolean binaryData; public String getUri() { @@ -116,6 +118,10 @@ public class HttpInput { return reqCookies; } + public Map<String, String> getContext() { + return context; + } + public HttpInput setReqCookies(Map<String, String> reqCookies) { this.reqCookies = reqCookies; return this; @@ -134,6 +140,6 @@ public class HttpInput { return "\nURL: " + this.getUri() + "\nMethod: " + this.getMethod() + "\nRequest Queries: " + this.getReqQueries() + "\nRequest Body: " + this.getBody() + "\nRequest Headers: " + this.getReqHeaders().toString() + "\nRequest Cookies: " + this.getReqCookies().toString() - + "\nbinaryData=" + this.binaryData; + + "\nbinaryData=" + this.binaryData + "\nContext=" + this.context; } } diff --git a/profiles/http/src/main/java/org/onap/cli/fw/http/error/OnapCommandHttpInvalidRequestBody.java b/profiles/http/src/main/java/org/onap/cli/fw/http/error/OnapCommandHttpInvalidRequestBody.java new file mode 100644 index 00000000..73c721e3 --- /dev/null +++ b/profiles/http/src/main/java/org/onap/cli/fw/http/error/OnapCommandHttpInvalidRequestBody.java @@ -0,0 +1,43 @@ +/* + * Copyright 2017 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.http.error; + +import org.onap.cli.fw.error.OnapCommandException; + +/** + * OnapCommandParameterNotFound. + * + */ +public class OnapCommandHttpInvalidRequestBody extends OnapCommandException { + + private static final long serialVersionUID = 6676137916079057963L; + + private static final String ERROR_CODE = "0x3008"; + private static final String ERR_MSG = "Http request body does not have valid json "; + + public OnapCommandHttpInvalidRequestBody(String name, String error) { + super(ERROR_CODE, ERR_MSG + name + ", " + error); + } + + public OnapCommandHttpInvalidRequestBody(String name, Throwable throwable) { + super(ERROR_CODE, ERR_MSG + name, throwable); + } + + public OnapCommandHttpInvalidRequestBody(Throwable e) { + this(ERROR_CODE, e.getMessage()); + } +} diff --git a/profiles/http/src/main/java/org/onap/cli/fw/http/mock/MocoServer.java b/profiles/http/src/main/java/org/onap/cli/fw/http/mock/MocoServer.java new file mode 100644 index 00000000..f6e58757 --- /dev/null +++ b/profiles/http/src/main/java/org/onap/cli/fw/http/mock/MocoServer.java @@ -0,0 +1,105 @@ +/* + * Copyright 2017 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.http.mock; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.dreamhead.moco.HttpServer; +import com.github.dreamhead.moco.Moco; +import com.github.dreamhead.moco.ResponseHandler; +import com.github.dreamhead.moco.Runner; +import org.onap.cli.fw.conf.OnapCommandConfig; +import org.onap.cli.fw.conf.OnapCommandConstants; +import org.onap.cli.fw.error.OnapCommandDiscoveryFailed; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandInvalidSchema; +import org.onap.cli.fw.http.conf.OnapCommandHttpConstants; +import org.onap.cli.fw.schema.OnapCommandSchemaLoader; +import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils; +import org.springframework.core.io.Resource; +import org.yaml.snakeyaml.Yaml; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.github.dreamhead.moco.Runner.runner; + +public class MocoServer { + + private Runner runner; + private Map<String, Object> mocoServerConfigs = new HashMap(); + + public MocoServer(String mockFile) throws OnapCommandException { + Resource resource = null; + + try { + resource = OnapCommandDiscoveryUtils.findResource(mockFile, + OnapCommandConstants.VERIFY_SAMPLES_MOCK_PATTERN); + } catch (IOException e) { + throw new OnapCommandDiscoveryFailed(mockFile, e); + } + + List<Map<String, ?>> stringMap = null; + try { + stringMap = (List<Map<String, ?>>) new Yaml().load(resource.getInputStream()); + } catch (IOException e) { + throw new OnapCommandException("Invalid mocking file" + mockFile, e); + } + if(!stringMap.isEmpty()) { + Map<String, ?> jsonConfigs = stringMap.get(0); + Map<String, String> request = (Map<String, String>) jsonConfigs.get(OnapCommandHttpConstants.VERIFY_REQUEST); + mocoServerConfigs.put(OnapCommandHttpConstants.VERIFY_REQUEST_URI, request.get(OnapCommandHttpConstants.VERIFY_REQUEST_URI)); + + Map<String, String> response = (Map<String, String>) jsonConfigs.get(OnapCommandHttpConstants.VERIFY_RESPONSE); + mocoServerConfigs.put(OnapCommandHttpConstants.VERIFY_RESPONSE_STATUS, response.get(OnapCommandHttpConstants.VERIFY_RESPONSE_STATUS)); + + if(response.get(OnapCommandHttpConstants.VERIFY_RESPONSE_JSON) != null) { + try { + mocoServerConfigs.put(OnapCommandHttpConstants.VERIFY_RESPONSE_JSON, + new ObjectMapper().writeValueAsString(response.get(OnapCommandHttpConstants.VERIFY_RESPONSE_JSON))); + } catch (JsonProcessingException e) { + throw new OnapCommandException("Invalid mocking file" + mockFile, e); + } + } + } + } + + public void start() { + HttpServer server = Moco.httpServer(Integer.parseInt( + OnapCommandConfig.getPropertyValue(OnapCommandHttpConstants.VERIFY_MOCO_PORT))); + + List<ResponseHandler> responseHandlers = new ArrayList<>(); + + if (mocoServerConfigs.containsKey(OnapCommandHttpConstants.VERIFY_RESPONSE_JSON)) { + responseHandlers.add(Moco.with(mocoServerConfigs.get(OnapCommandHttpConstants.VERIFY_RESPONSE_JSON).toString())); + } + responseHandlers.add(Moco.status((Integer) mocoServerConfigs.get(OnapCommandHttpConstants.VERIFY_RESPONSE_STATUS))); + + server.request(Moco.by(Moco.uri((String) mocoServerConfigs.get(OnapCommandHttpConstants.VERIFY_REQUEST_URI)))) + .response(Moco.header(OnapCommandHttpConstants.VERIFY_CONTENT_TYPE, OnapCommandHttpConstants.VERIFY_CONTENT_TYPE_VALUE), + responseHandlers.toArray(new ResponseHandler[responseHandlers.size()])); + + runner = runner(server); + runner.start(); + } + + public void stop() { + runner.stop(); + } +} diff --git a/profiles/http/src/main/java/org/onap/cli/fw/http/schema/OnapCommandSchemaHttpLoader.java b/profiles/http/src/main/java/org/onap/cli/fw/http/schema/OnapCommandSchemaHttpLoader.java index 8e01b585..52b7571d 100644 --- a/profiles/http/src/main/java/org/onap/cli/fw/http/schema/OnapCommandSchemaHttpLoader.java +++ b/profiles/http/src/main/java/org/onap/cli/fw/http/schema/OnapCommandSchemaHttpLoader.java @@ -132,6 +132,20 @@ public class OnapCommandSchemaHttpLoader { cmd.getInput().setReqQueries(query); break; + case OnapCommandHttpConstants.CONTEXT: + Map<String, Object> context = (Map<String, Object>) map.get(key2); + + for (String key: context.keySet()) { + switch (key) { + case OnapCommandHttpConstants.CONTEXT_REMOVE_EMPTY_JSON_NODES: + Boolean flag = (Boolean) context.get(OnapCommandHttpConstants.CONTEXT_REMOVE_EMPTY_JSON_NODES); + cmd.getInput().getContext().put(OnapCommandHttpConstants.CONTEXT_REMOVE_EMPTY_JSON_NODES, flag.toString()); + break; + } + } + + + break; case OnapCommandHttpConstants.MULTIPART_ENTITY_NAME: Object multipartEntityName = map.get(key2); cmd.getInput().setMultipartEntityName(multipartEntityName.toString()); @@ -371,15 +385,17 @@ public class OnapCommandSchemaHttpLoader { } String body = String.valueOf(bodyString); - JSONObject obj = null; - try { - obj = new ObjectMapper().readValue(body, JSONObject.class); - } catch (IOException e1) { // NOSONAR - errorList.add(OnapCommandHttpConstants.HTTP_BODY_FAILED_PARSING); - } - if (obj == null || "".equals(obj.toString())) { + + if (body == null || "".equals(body)) { errorList.add(OnapCommandHttpConstants.HTTP_BODY_JSON_EMPTY); + } else { + try { + new ObjectMapper().readValue(body, JSONObject.class); + } catch (IOException e1) { // NOSONAR + errorList.add(OnapCommandHttpConstants.HTTP_BODY_FAILED_PARSING); + } } + OnapCommandUtils.parseParameters(body, bodyParamNames); return bodyParamNames; diff --git a/profiles/http/src/main/java/org/onap/cli/fw/http/utils/OnapCommandHttpUtils.java b/profiles/http/src/main/java/org/onap/cli/fw/http/utils/OnapCommandHttpUtils.java index 7b10dbce..b77b85da 100644 --- a/profiles/http/src/main/java/org/onap/cli/fw/http/utils/OnapCommandHttpUtils.java +++ b/profiles/http/src/main/java/org/onap/cli/fw/http/utils/OnapCommandHttpUtils.java @@ -18,6 +18,7 @@ package org.onap.cli.fw.http.utils; import java.util.ArrayList; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -27,9 +28,11 @@ import org.onap.cli.fw.error.OnapCommandInvalidParameterValue; import org.onap.cli.fw.error.OnapCommandParameterNotFound; import org.onap.cli.fw.error.OnapCommandResultEmpty; import org.onap.cli.fw.error.OnapCommandResultMapProcessingFailed; +import org.onap.cli.fw.http.conf.OnapCommandHttpConstants; import org.onap.cli.fw.http.connect.HttpInput; import org.onap.cli.fw.http.connect.HttpResult; import org.onap.cli.fw.http.error.OnapCommandHttpHeaderNotFound; +import org.onap.cli.fw.http.error.OnapCommandHttpInvalidRequestBody; import org.onap.cli.fw.http.error.OnapCommandHttpInvalidResponseBody; import org.onap.cli.fw.input.OnapCommandParameter; import org.onap.cli.fw.input.OnapCommandParameterType; @@ -37,6 +40,8 @@ import org.onap.cli.fw.utils.OnapCommandUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.PathNotFoundException; @@ -81,6 +86,12 @@ public class OnapCommandHttpUtils { inp.getReqQueries().put(h, OnapCommandUtils.replaceLineFromInputParameters(value, params)); } + boolean isRemoveEmptyNodes = Boolean.parseBoolean(input.getContext().getOrDefault(OnapCommandHttpConstants.CONTEXT_REMOVE_EMPTY_JSON_NODES, "false")); + + if (isRemoveEmptyNodes) { + inp.setBody(OnapCommandHttpUtils.normalizeJson(input.getBody())); + } + return inp; } @@ -235,5 +246,30 @@ public class OnapCommandHttpUtils { } } + public static void normalizeJson(JsonNode node) { + Iterator<JsonNode> it = node.iterator(); + while (it.hasNext()) { + JsonNode child = it.next(); + if (child.isTextual() && child.asText().equals("")) + it.remove(); + else if (child.isNull()) + it.remove(); + else + normalizeJson(child); + } + } + + public static String normalizeJson(String json) throws OnapCommandHttpInvalidRequestBody { + ObjectMapper mapper = new ObjectMapper(); + JsonNode node; + try { + node = mapper.readTree(json); + normalizeJson(node); + return mapper.writeValueAsString(node); + } catch (Exception e) { //NOSONAR + throw new OnapCommandHttpInvalidRequestBody(e); + } + + } } diff --git a/profiles/http/src/main/resources/open-cli-http.properties b/profiles/http/src/main/resources/open-cli-http.properties index db19d088..8cde793e 100644 --- a/profiles/http/src/main/resources/open-cli-http.properties +++ b/profiles/http/src/main/resources/open-cli-http.properties @@ -6,7 +6,7 @@ cli.http.api_key_use_cookies=true cli.schema.http.sections=request,service,success_codes,result_map,sample_response cli.schema.http.sections.mandatory=request, success_codes -cli.schema.http.request.sections=uri,method,body,headers,queries,multipart_entity_name +cli.schema.http.request.sections=uri,method,body,headers,queries,multipart_entity_name,context cli.schema.http.request.sections.mandatory=uri,method cli.schema.http.service.sections=name,version,auth,mode @@ -16,3 +16,7 @@ cli.schema.http.request.method.values=post,get,delete,put,head cli.schema.http.service.auth.values=none,basic cli.schema.http.service.mode.values=direct,catalog + +#verify properties +cli.verify.host=http://localhost +cli.verify.port=8585
\ No newline at end of file diff --git a/profiles/http/src/main/resources/open-cli-schema/http/default_input_parameters_http.yaml b/profiles/http/src/main/resources/open-cli-schema/http/default_input_parameters_http.yaml index 6721b207..6ac0ded2 100644 --- a/profiles/http/src/main/resources/open-cli-schema/http/default_input_parameters_http.yaml +++ b/profiles/http/src/main/resources/open-cli-schema/http/default_input_parameters_http.yaml @@ -40,4 +40,10 @@ parameters: long_option: no-catalog is_optional: true is_default_param: true - default_value: false
\ No newline at end of file + default_value: false + - name: verify + type: bool + description: verify the command using available command sample file and mocking file + default_value: false + is_include: true + is_optional: true
\ No newline at end of file diff --git a/profiles/http/src/test/java/org/onap/cli/fw/http/HttpInputOutputTest.java b/profiles/http/src/test/java/org/onap/cli/fw/http/HttpInputOutputTest.java index 99ee3d34..7a7a31c7 100644 --- a/profiles/http/src/test/java/org/onap/cli/fw/http/HttpInputOutputTest.java +++ b/profiles/http/src/test/java/org/onap/cli/fw/http/HttpInputOutputTest.java @@ -44,7 +44,7 @@ public class HttpInputOutputTest { inp.setReqQueries(new HashMap<String, String>()); assertTrue( - "\nURL: uri\nMethod: method\nRequest Queries: {}\nRequest Body: body\nRequest Headers: {}\nRequest Cookies: {}\nbinaryData=false" + "\nURL: uri\nMethod: method\nRequest Queries: {}\nRequest Body: body\nRequest Headers: {}\nRequest Cookies: {}\nbinaryData=false\nContext={}" .equals(inp.toString())); } diff --git a/profiles/http/src/test/java/org/onap/cli/fw/http/utils/OnapCommandUtilsTest.java b/profiles/http/src/test/java/org/onap/cli/fw/http/utils/OnapCommandUtilsTest.java index 12920515..13b2db42 100644 --- a/profiles/http/src/test/java/org/onap/cli/fw/http/utils/OnapCommandUtilsTest.java +++ b/profiles/http/src/test/java/org/onap/cli/fw/http/utils/OnapCommandUtilsTest.java @@ -42,6 +42,7 @@ import org.onap.cli.fw.error.OnapCommandSchemaNotFound; import org.onap.cli.fw.http.cmd.OnapHttpCommand; import org.onap.cli.fw.http.connect.HttpResult; import org.onap.cli.fw.http.error.OnapCommandHttpHeaderNotFound; +import org.onap.cli.fw.http.error.OnapCommandHttpInvalidRequestBody; import org.onap.cli.fw.http.error.OnapCommandHttpInvalidResponseBody; import org.onap.cli.fw.http.schema.OnapCommandSchemaHttpLoader; import org.onap.cli.fw.input.OnapCommandParameter; @@ -93,7 +94,7 @@ public class OnapCommandUtilsTest { assertTrue("sample-test".equals(cmd.getName())); Map<String, OnapCommandParameter> map = OnapCommandUtils.getInputMap(cmd.getParameters()); - assertTrue(map.size() == 7); + assertTrue(map.size() == 9); } @Test(expected = OnapCommandHttpHeaderNotFound.class) @@ -136,4 +137,11 @@ public class OnapCommandUtilsTest { protected void run() throws OnapCommandException { } } + + @Test + public void testJsonEmptyCheck() throws OnapCommandHttpInvalidRequestBody { + String sample = "{\"request\":{\"method\":\"\",\"uri\":\"/onboarding-api/v1.0/vendor-license-models/cf2d907d998e44698ce3b4cded5f66a7/versions/2.0/license-agreements\",\"headers\":{\"Authorization\":\"Basic Y3MwMDA4OmRlbW8xMjM0NTYh\",\"X-FromAppId\":\"onap-cli\",\"Accept\":\"application/json\",\"USER_ID\":\"cs0008\",\"X-TransactionId\":\"req-66a37478-d840-44f8-b436-56f4a3b6f640\",\"Content-Type\":\"application/json\"},\"json\":null},\"response\":{\"status\":200,\"json\":{\"listCount\":2,\"results\":[{\"name\":\"sf\",\"description\":\"sdfgdf\",\"licenseTerm\":{\"choice\":\"Fixed_Term\",\"other\":null},\"id\":\"1e2edfccaca847f896070d0fac26667a\",\"featureGroupsIds\":[\"3a2fb75b52a54e9c8093e7c154210f9e\"]},{\"name\":\"kanag-cli-la\",\"description\":\"kanag cli la\",\"licenseTerm\":{\"choice\":\"Fixed_Term\",\"other\":\"\"},\"id\":\"77e151d0503b45ecb7e40f5f5f1a887e\",\"featureGroupsIds\":[\"3a2fb75b52a54e9c8093e7c154210f9e\"]}]}}}"; + String result = "{\"request\":{\"uri\":\"/onboarding-api/v1.0/vendor-license-models/cf2d907d998e44698ce3b4cded5f66a7/versions/2.0/license-agreements\",\"headers\":{\"Authorization\":\"Basic Y3MwMDA4OmRlbW8xMjM0NTYh\",\"X-FromAppId\":\"onap-cli\",\"Accept\":\"application/json\",\"USER_ID\":\"cs0008\",\"X-TransactionId\":\"req-66a37478-d840-44f8-b436-56f4a3b6f640\",\"Content-Type\":\"application/json\"}},\"response\":{\"status\":200,\"json\":{\"listCount\":2,\"results\":[{\"name\":\"sf\",\"description\":\"sdfgdf\",\"licenseTerm\":{\"choice\":\"Fixed_Term\"},\"id\":\"1e2edfccaca847f896070d0fac26667a\",\"featureGroupsIds\":[\"3a2fb75b52a54e9c8093e7c154210f9e\"]},{\"name\":\"kanag-cli-la\",\"description\":\"kanag cli la\",\"licenseTerm\":{\"choice\":\"Fixed_Term\"},\"id\":\"77e151d0503b45ecb7e40f5f5f1a887e\",\"featureGroupsIds\":[\"3a2fb75b52a54e9c8093e7c154210f9e\"]}]}}}"; + assertEquals(result, OnapCommandHttpUtils.normalizeJson(sample)); + } } diff --git a/profiles/http/src/test/resources/open-cli-schema/sample-test1-schema-http.yaml b/profiles/http/src/test/resources/open-cli-schema/sample-test1-schema-http.yaml index f162231f..f7da6da2 100644 --- a/profiles/http/src/test/resources/open-cli-schema/sample-test1-schema-http.yaml +++ b/profiles/http/src/test/resources/open-cli-schema/sample-test1-schema-http.yaml @@ -75,6 +75,8 @@ http: method: POST body: '{"name":"${name}","vendor":"${vendor}","version":"${vim-version}","description":"${description}","type":"${type}","url":"${url}","userName":"${username}","password":"${password}","domain":"${domain}","tenant":"${tenant}"}' headers: + context: + remove_empty_node: true success_codes: - 201 - 200 diff --git a/profiles/http/src/test/resources/sample-test-schema-swagger.yaml b/profiles/http/src/test/resources/sample-test-schema-swagger.yaml deleted file mode 100644 index 4108d4e6..00000000 --- a/profiles/http/src/test/resources/sample-test-schema-swagger.yaml +++ /dev/null @@ -1,28 +0,0 @@ -open_cli_schema_version: 1.0 -name: sample-test-swagger -description: Sample swagger command test. -info: - product: open-cli - service: test - type: cmd - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com -parameters: - - name: user - type: string - description: Oclip user - short_option: n - long_option: username - is_optional: false -results: - direction: portrait - attributes: - - name: name - description: Oclip user - scope: short - type: string -exec: - api: org.onap.common_services.auth.auth_service.client.api.DefaultApi - client: org.onap.common_services.auth.auth_service.client.invoker.ApiClient - entity: org.onap.common_services.auth.auth_service.client.model.User, username(userName), password, description - method: create - exception: org.onap.common_services.auth.auth_service.client.invoker.ApiException
\ No newline at end of file diff --git a/validate/validation/pom.xml b/validate/validation/pom.xml index 26f507d6..3dbe456f 100644 --- a/validate/validation/pom.xml +++ b/validate/validation/pom.xml @@ -31,12 +31,6 @@ <name>cli/validate/validation</name> <packaging>jar</packaging> <dependencies> - <dependency> - <groupId>com.github.dreamhead</groupId> - <artifactId>moco-runner</artifactId> - <version>0.11.1</version> - <scope>test</scope> - </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> @@ -83,6 +77,11 @@ <artifactId>cli-products-onap-amsterdam-features-aai</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + <version>2.6</version> + </dependency> </dependencies> <!-- <build> <plugins> diff --git a/validate/validation/src/test/java/org/onap/cli/moco/OnapCommandHttpMocoServer.java b/validate/validation/src/test/java/org/onap/cli/moco/OnapCommandHttpMocoServer.java deleted file mode 100644 index b1f18681..00000000 --- a/validate/validation/src/test/java/org/onap/cli/moco/OnapCommandHttpMocoServer.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright 2017 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.moco; - -import static com.github.dreamhead.moco.Moco.pathResource; -import static com.github.dreamhead.moco.MocoJsonRunner.jsonHttpServer; -import static com.github.dreamhead.moco.Runner.runner; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; - -import org.onap.cli.fw.error.OnapCommandException; -import org.onap.cli.fw.error.OnapCommandInvalidSample; -import org.onap.cli.fw.registrar.OnapCommandRegistrar; -import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils; -import org.onap.cli.main.OnapCli; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.Resource; -import org.yaml.snakeyaml.Yaml; - -import com.github.dreamhead.moco.HttpServer; -import com.github.dreamhead.moco.Runner; - -public class OnapCommandHttpMocoServer { - - public static final String SAMPLE_PATTERN = "onap-cli-sample/**/"; - - public static final String SAMPLE_VERSION = "open_cli_sample_version"; - public static final String SAMPLE_VERSION_1_0 = "1.0"; - - public static final String SAMPLE_COMMAND_NAME = "name"; - public static final String SAMPLE_PRODUCT = "version"; - public static final String SAMPLE_LIST = "samples"; - public static final String SAMPLE_DESCRIPTION = "name"; - public static final String SAMPLE_INPUT = "input"; - public static final String SAMPLE_OUTPUT = "output"; - public static final String SAMPLE_MOCO = "moco"; - - private static Logger LOG = LoggerFactory.getLogger(OnapCommandHttpMocoServer.class); - - private String samplesToTest = "*.yaml"; - - private int port = 8141; - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public OnapCommandHttpMocoServer(String samplesToTest) { - this.samplesToTest = samplesToTest; - } - - public OnapCommandHttpMocoServer() { - } - - public static Map<String, List<OnapCommandSample>> discoverYamls(File path) throws IOException { - Map<String, List<OnapCommandSample>> cliProductSamples = new HashMap<>(); - - Stream<Path> walk = Files.walk(path.toPath()); - walk.filter(p -> (p.toString().contains("src/test/resources/onap-cli-sample"))) - .filter(p -> p.toString().endsWith("sample.yaml")) - .forEach(p -> { - collectSamples(new File(p.toUri()), cliProductSamples); - }); - - return cliProductSamples; - } - - private static void collectSamples(File file, Map<String, List<OnapCommandSample>> result) { - OnapCommandHttpMocoServer onapCommandHttpMocoServer = new OnapCommandHttpMocoServer(); - List<OnapCommandSample> loadSamples; - try { - loadSamples = onapCommandHttpMocoServer.loadSamples(file); - loadSamples.stream().forEach(sample -> { - if (!result.containsKey(sample.getProduct())) { - result.put(sample.getProduct(), new ArrayList<>()); - } - result.get(sample.getProduct()).add(sample); - }); - } catch (OnapCommandInvalidSample e) { - LOG.error("Failed to read sample file", e); - } - } - - private List<Resource> dicoverSampleYamls() { - Resource[] resources = new Resource [] {}; - try { - resources = OnapCommandDiscoveryUtils.findResources(SAMPLE_PATTERN + this.samplesToTest); - } catch (IOException e) { - LOG.error("Failed to discover the samples", e); - } - - return Arrays.asList(resources); - } - - private String getValue(Map<String, ?> map, String prpName) { - Object o = map.get(prpName); - if (o != null) { - return o.toString(); - } - - return ""; - } - - public List<OnapCommandSample> loadSamples(InputStream inputStream, String fileName) throws OnapCommandInvalidSample { - List<OnapCommandSample> samples = new ArrayList<>(); - Map<String, ?> values = null; - try { - values = (Map<String, ?>) new Yaml().load(inputStream); - } catch (Exception e) { - throw new OnapCommandInvalidSample(fileName, e); - } - - OnapCommandSample sample = new OnapCommandSample(); - - if (!this.getValue(values, SAMPLE_VERSION).equals(SAMPLE_VERSION_1_0)) { - throw new OnapCommandInvalidSample(fileName, "Invalid sample version " + this.getValue(values, SAMPLE_VERSION)); - } - - sample.setCommandName(this.getValue(values, SAMPLE_COMMAND_NAME)); - sample.setProduct(this.getValue(values, SAMPLE_PRODUCT)); - - //Retrieve the samples - values = (Map<String, Map<String, String>>) values.get(SAMPLE_LIST); - - for (String s: values.keySet()) { - Map<String, ?> sMap = (Map<String, ?>)values.get(s); - sample.setDescription(this.getValue(sMap, SAMPLE_DESCRIPTION)); - sample.setInput(this.getValue(sMap, SAMPLE_INPUT)); - sample.setOutput(this.getValue(sMap, SAMPLE_OUTPUT)); - sample.setMoco(this.getValue(sMap, SAMPLE_MOCO)); - samples.add(sample); - } - - return samples; - } - - public List<OnapCommandSample> loadSamples(Resource file) throws OnapCommandInvalidSample { - try { - return loadSamples(file.getInputStream(), file.getFilename()); - } catch (IOException e) { - throw new OnapCommandInvalidSample(file.getFilename(), e); - } - } - - public List<OnapCommandSample> loadSamples(File file) throws OnapCommandInvalidSample { - try { - return loadSamples(new FileInputStream(file), file.getName()); - } catch (FileNotFoundException e) { - throw new OnapCommandInvalidSample(file.getName(), e); - } - } - private void verifySample(OnapCommandSample sample) throws OnapCommandException { - - List <String> args = new ArrayList<>(); - args.add(sample.getCommandName()); - args.addAll(Arrays.asList(sample.getInput().split(" "))); - - ByteArrayOutputStream bo = new ByteArrayOutputStream(); - System.setOut(new PrintStream(bo)); - - OnapCli cli = new OnapCli(args.toArray(new String []{})); - OnapCommandRegistrar.getRegistrar().setEnabledProductVersion(sample.getProduct()); - cli.handle(); - - String output = new String(bo.toByteArray()); - - assert cli.getExitCode() == 0; - - assert sample.getOutput().equals(output); - } - - public void verifySamples() throws OnapCommandException { - for (Resource rsc : this.dicoverSampleYamls()) { - for(OnapCommandSample sample: this.loadSamples(rsc)) { - - if (!sample.getMoco().isEmpty()) { - HttpServer server = jsonHttpServer(this.getPort(), pathResource(sample.getMoco())); - Runner r = runner(server); - r.start(); - - this.verifySample(sample); - - r.stop(); - } - } - } - } -}
\ No newline at end of file diff --git a/validate/validation/src/test/java/org/onap/cli/validation/OnapValidationTest.java b/validate/validation/src/test/java/org/onap/cli/validation/OnapValidationTest.java index 6f84c953..a631e3d2 100644 --- a/validate/validation/src/test/java/org/onap/cli/validation/OnapValidationTest.java +++ b/validate/validation/src/test/java/org/onap/cli/validation/OnapValidationTest.java @@ -16,28 +16,54 @@ package org.onap.cli.validation; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.Map; - import org.apache.commons.io.FileUtils; -import org.junit.Ignore; import org.junit.Test; +import org.onap.cli.fw.conf.OnapCommandConstants; import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandInvalidSample; import org.onap.cli.fw.registrar.OnapCommandRegistrar; import org.onap.cli.fw.schema.OnapCommandSchemaInfo; import org.onap.cli.main.OnapCli; -import org.onap.cli.moco.OnapCommandHttpMocoServer; +import org.onap.cli.main.conf.OnapCliConstants; import org.onap.cli.moco.OnapCommandSample; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; public class OnapValidationTest { + public static final String SAMPLE_VERSION = "open_cli_sample_version"; + public static final String SAMPLE_VERSION_1_0 = "1.0"; + + public static final String SAMPLE_COMMAND_NAME = "name"; + public static final String SAMPLE_PRODUCT = "version"; + public static final String SAMPLE_LIST = "samples"; + public static final String SAMPLE_DESCRIPTION = "name"; + public static final String SAMPLE_INPUT = "input"; + public static final String SAMPLE_OUTPUT = "output"; + public static final String SAMPLE_MOCO = "moco"; + OnapCli cli = null; + private static Logger LOG = LoggerFactory.getLogger(OnapValidationTest.class); + private void handle(String[] args) { cli = new OnapCli(args); cli.handle(); @@ -84,13 +110,6 @@ public class OnapValidationTest { } } - @Ignore - @Test - public void verifyCommandResults() throws OnapCommandException { - OnapCommandHttpMocoServer server = new OnapCommandHttpMocoServer(); - server.verifySamples(); - } - @Test public void collectSampleYamlTest() { try { @@ -98,7 +117,7 @@ public class OnapValidationTest { String sampleFileName = "target/sample.rst"; FileUtils.deleteQuietly(new File(sampleFileName)); - Map<String, List<OnapCommandSample>> discoveredYamls = OnapCommandHttpMocoServer.discoverYamls(root); + Map<String, List<OnapCommandSample>> discoveredYamls = discoverYamls(root); writeSamples(new File(sampleFileName), discoveredYamls); } catch (IOException e) { @@ -127,4 +146,89 @@ public class OnapValidationTest { } } + public static Map<String, List<OnapCommandSample>> discoverYamls(File path) throws IOException { + Map<String, List<OnapCommandSample>> cliProductSamples = new HashMap<>(); + + Stream<Path> walk = Files.walk(path.toPath()); + walk.filter(p -> (p.toString().contains("src/test/resources/onap-cli-sample"))) + .filter(p -> p.toString().endsWith("sample.yaml")) + .forEach(p -> { + collectSamples(new File(p.toUri()), cliProductSamples); + }); + + return cliProductSamples; + } + + private static void collectSamples(File file, Map<String, List<OnapCommandSample>> result) { + List<OnapCommandSample> loadSamples; + try { + loadSamples = loadSamples(file); + loadSamples.stream().forEach(sample -> { + if (!result.containsKey(sample.getProduct())) { + result.put(sample.getProduct(), new ArrayList<>()); + } + result.get(sample.getProduct()).add(sample); + }); + } catch (OnapCommandInvalidSample e) { + LOG.error("Failed to read sample file", e); + } + } + + private static List<OnapCommandSample> loadSamples(File file) throws OnapCommandInvalidSample { + try { + return loadSamples(new FileInputStream(file), file.getName()); + } catch (FileNotFoundException e) { + throw new OnapCommandInvalidSample(file.getName(), e); + } + } + + private static List<OnapCommandSample> loadSamples(InputStream inputStream, String fileName) throws OnapCommandInvalidSample { + List<OnapCommandSample> samples = new ArrayList<>(); + Map<String, ?> values = null; + try { + values = (Map<String, ?>) new Yaml().load(inputStream); + } catch (Exception e) { + throw new OnapCommandInvalidSample(fileName, e); + } + + OnapCommandSample sample = new OnapCommandSample(); + + if (!getValue(values, SAMPLE_VERSION).equals(SAMPLE_VERSION_1_0)) { + throw new OnapCommandInvalidSample(fileName, "Invalid sample version " + getValue(values, SAMPLE_VERSION)); + } + + sample.setCommandName(getValue(values, SAMPLE_COMMAND_NAME)); + sample.setProduct(getValue(values, SAMPLE_PRODUCT)); + + //Retrieve the samples + values = (Map<String, Map<String, String>>) values.get(SAMPLE_LIST); + + for (String s: values.keySet()) { + Map<String, ?> sMap = (Map<String, ?>)values.get(s); + sample.setDescription(getValue(sMap, SAMPLE_DESCRIPTION)); + sample.setInput(getValue(sMap, SAMPLE_INPUT)); + sample.setOutput(getValue(sMap, SAMPLE_OUTPUT)); + sample.setMoco(getValue(sMap, SAMPLE_MOCO)); + samples.add(sample); + } + + return samples; + } + + private static String getValue(Map<String, ?> map, String prpName) { + Object o = map.get(prpName); + if (o != null) { + return o.toString(); + } + + return ""; + } + + @Test + public void testVerify() throws OnapCommandException { + OnapCommandRegistrar.getRegistrar().setEnabledProductVersion("open-cli"); + OnapCli onapCli = new OnapCli(new String[]{"sample-test-verify", "--verify"}); + onapCli.handle(); + assertEquals(OnapCliConstants.EXIT_SUCCESS, onapCli.getExitCode()); + } } diff --git a/validate/validation/src/test/resources/open-cli-sample/sample/sample-test-verify-schema-1.1-moco.json b/validate/validation/src/test/resources/open-cli-sample/sample/sample-test-verify-schema-1.1-moco.json new file mode 100644 index 00000000..f5e4e444 --- /dev/null +++ b/validate/validation/src/test/resources/open-cli-sample/sample/sample-test-verify-schema-1.1-moco.json @@ -0,0 +1,34 @@ +[{ + "request" : { + "method" : "get", + "uri" : "/aai/v11/cloud-infrastructure/cloud-regions", + "headers" : { + "Authorization" : "Basic QUFJOkFBSQ==", + "X-FromAppId" : "onap-cli", + "Accept" : "application/json", + "X-TransactionId" : "req-77c08aa0-662e-4d32-9206-bd569c3bf61b", + "Content-Type" : "application/json" + }, + "json" : null + }, + "response" : { + "status" : 200, + "json" : { + "cloud-region" : [ { + "cloud-owner" : "huawei-cloud", + "cloud-region-id" : "bangalore", + "sriov-automation" : false, + "resource-version" : "1509027332165" + }, { + "cloud-owner" : "Rackspace", + "cloud-region-id" : "RegionOne", + "cloud-type" : "SharedNode", + "owner-defined-type" : "OwnerType", + "cloud-region-version" : "v1", + "cloud-zone" : "CloudZone", + "sriov-automation" : false, + "resource-version" : "1508827902543" + } ] + } + } +}]
\ No newline at end of file diff --git a/validate/validation/src/test/resources/open-cli-sample/sample/sample-test-verify-schema-1.1-sample.yaml b/validate/validation/src/test/resources/open-cli-sample/sample/sample-test-verify-schema-1.1-sample.yaml new file mode 100644 index 00000000..ffc59961 --- /dev/null +++ b/validate/validation/src/test/resources/open-cli-sample/sample/sample-test-verify-schema-1.1-sample.yaml @@ -0,0 +1,43 @@ +# Copyright 2017-18 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_sample_version: 1.0 +name: sample-test-verify +version: open-cli +samples: + sample1: + name: sample-test-verify + input: + moco: sample-test-verify-schema-1.1-moco.json + output: | + +--------------+------------+------------------+ + |cloud |region |resource-version | + +--------------+------------+------------------+ + |huawei-cloud |bangalore |1509027332165 | + +--------------+------------+------------------+ + |Rackspace |RegionOne |1508827902543 | + +--------------+------------+------------------+ + + sample2: + name: sample-test-verify + input: + moco: sample-test-verify-schema-1.1-moco.json + output: | + +--------------+------------+------------------+ + |cloud |region |resource-version | + +--------------+------------+------------------+ + |huawei-cloud |bangalore |1509027332165 | + +--------------+------------+------------------+ + |Rackspace |RegionOne |1508827902543 | + +--------------+------------+------------------+ diff --git a/validate/validation/src/test/resources/open-cli-schema/sample-test-verify-schema-1.1.yaml b/validate/validation/src/test/resources/open-cli-schema/sample-test-verify-schema-1.1.yaml new file mode 100644 index 00000000..5e3548ed --- /dev/null +++ b/validate/validation/src/test/resources/open-cli-schema/sample-test-verify-schema-1.1.yaml @@ -0,0 +1,72 @@ +# Copyright 2017-18 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 +name: sample-test-verify +description: Oclip sample command to test the command features +info: + product: open-cli + service: test + type: cmd + +results: + direction: landscape + attributes: + - name: cloud + description: Onap cloud + scope: short + type: string + - name: region + description: Onap cloud region + scope: short + type: string + - name: tenant + description: Onap cloud tenat + scope: long + type: string + - name: tenant-id + description: Onap cloud tenat id + scope: long + type: string + - name: customer + description: Onap cloud customer + scope: long + type: string + - name: service + description: Onap cloud service + scope: long + type: string + - name: resource-version + description: Onap cloud resource version + scope: short + type: string +http: + service: + auth: basic + mode: direct + request: + uri: /aai/v11/cloud-infrastructure/cloud-regions + method: GET + success_codes: + - 200 + result_map: + cloud: $b{cloud-region.[*].cloud-owner} + region: $b{cloud-region.[*].cloud-region-id} + resource-version: $b{cloud-region.[*].resource-version} + tenant: $b{cloud-region.[*].tenants.tenant.[*].tenant-name} + tenant-id: $b{cloud-region.[*].tenants.tenant.[*].tenant-id} + customer: $b{cloud-region.[*].tenants.tenant.[*].relationship-list.relationship.[*].relationship-data.[?(@.relationship-key == 'customer.global-customer-id')].relationship-value} + service: $b{cloud-region.[*].tenants.tenant.[*].relationship-list.relationship.[*].relationship-data.[?(@.relationship-key == 'service-subscription.service-type')].relationship-value} + sample_response: + body: '{"cloud-region":[{"cloud-owner":"Rackspace","cloud-region-id":"RegionOne","cloud-type":"SharedNode","owner-defined-type":"OwnerType","cloud-region-version":"v1","cloud-zone":"CloudZone","resource-version":"1500729864","tenants":{"tenant":[{"tenant-id":"e69e6d64b44347509c3fc512391f34a6","tenant-name":"onap","resource-version":"1500729865","relationship-list":{"relationship":[{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Demonstration/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Demonstration"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Demonstration123/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Demonstration123"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/u1/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"u1"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/u2/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"u2"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/DemoCust_7151e36a-1a57-4993-b513-54134f2b8f19/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"DemoCust_7151e36a-1a57-4993-b513-54134f2b8f19"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Demonstration/service-subscriptions/service-subscription/vLB/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Demonstration"},{"relationship-key":"service-subscription.service-type","relationship-value":"vLB"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Linan/service-subscriptions/service-subscription/vFW/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Linan"},{"relationship-key":"service-subscription.service-type","relationship-value":"vFW"}]},{"related-to":"service-subscription","related-link":"https://192.168.17.12:8443/aai/v8/business/customers/customer/Linan/service-subscriptions/service-subscription/vLB/","relationship-data":[{"relationship-key":"customer.global-customer-id","relationship-value":"Linan"},{"relationship-key":"service-subscription.service-type","relationship-value":"vLB"}]}]}}]}}]}' |