From 0d97a835fa2052ded5a31e8921baf641c8e9bb57 Mon Sep 17 00:00:00 2001 From: Kanagaraj Manickam k00365106 Date: Mon, 11 Dec 2017 20:34:44 +0530 Subject: Make Http as separate plugin Issue-ID: CLI-66 Change-Id: I8ad78f417f6dbb00e29effdd3ed8ec1939aee81d Signed-off-by: Kanagaraj Manickam k00365106 --- .../src/main/java/org/onap/cli/fw/OnapCommand.java | 282 -------- .../java/org/onap/cli/fw/OnapCommandRegistrar.java | 384 ---------- .../java/org/onap/cli/fw/OnapCommandSchema.java | 46 -- .../java/org/onap/cli/fw/ad/OnapAuthClient.java | 161 ----- .../main/java/org/onap/cli/fw/ad/OnapService.java | 101 --- .../org/onap/cli/fw/cmd/BasicAuthLoginCommand.java | 48 -- .../onap/cli/fw/cmd/BasicAuthLogoutCommand.java | 29 - .../java/org/onap/cli/fw/cmd/CatalogCommand.java | 28 - .../main/java/org/onap/cli/fw/cmd/CommandType.java | 52 -- .../main/java/org/onap/cli/fw/cmd/OnapCommand.java | 243 +++++++ .../java/org/onap/cli/fw/cmd/OnapCommandType.java | 52 ++ .../java/org/onap/cli/fw/cmd/OnapHttpCommand.java | 199 ------ .../onap/cli/fw/cmd/OnapSchemaRefreshCommand.java | 11 +- .../onap/cli/fw/cmd/OnapSchemaValidateCommand.java | 13 +- .../main/java/org/onap/cli/fw/conf/Constants.java | 227 ------ .../org/onap/cli/fw/conf/OnapCommandConfg.java | 139 ---- .../org/onap/cli/fw/conf/OnapCommandConfig.java | 71 ++ .../org/onap/cli/fw/conf/OnapCommandConstants.java | 147 ++++ .../fw/error/OnapCommandFailedMocoGenerate.java | 39 -- .../onap/cli/fw/error/OnapCommandHttpFailure.java | 44 -- .../fw/error/OnapCommandHttpHeaderNotFound.java | 30 - .../error/OnapCommandHttpInvalidResponseBody.java | 37 - .../fw/error/OnapCommandHttpInvalidResultMap.java | 32 - .../fw/error/OnapCommandInvalidRegistration.java | 2 +- .../onap/cli/fw/error/OnapCommandLoginFailed.java | 41 -- .../onap/cli/fw/error/OnapCommandLogoutFailed.java | 40 -- .../cli/fw/error/OnapCommandServiceNotFound.java | 30 - .../main/java/org/onap/cli/fw/http/HttpInput.java | 139 ---- .../main/java/org/onap/cli/fw/http/HttpResult.java | 77 -- .../org/onap/cli/fw/http/OnapHttpConnection.java | 349 ---------- .../java/org/onap/cli/fw/info/OnapCommandInfo.java | 8 +- .../onap/cli/fw/input/OnapCommandParameter.java | 57 +- .../cli/fw/input/OnapCommandParameterType.java | 75 ++ .../java/org/onap/cli/fw/input/ParameterType.java | 75 -- .../cli/fw/input/cache/OnapCommandParamEntity.java | 45 ++ .../fw/input/cache/OnapCommandParameterCache.java | 62 +- .../java/org/onap/cli/fw/input/cache/Param.java | 45 -- .../cli/fw/output/OnapCommandPrintDirection.java | 45 ++ .../org/onap/cli/fw/output/OnapCommandResult.java | 30 +- .../cli/fw/output/OnapCommandResultAttribute.java | 8 +- .../onap/cli/fw/output/OnapCommandResultType.java | 63 ++ .../org/onap/cli/fw/output/PrintDirection.java | 45 -- .../java/org/onap/cli/fw/output/ResultType.java | 63 -- .../onap/cli/fw/output/print/OnapCommandPrint.java | 8 +- .../cli/fw/registrar/OnapCommandRegistrar.java | 393 +++++++++++ .../org/onap/cli/fw/schema/OnapCommandSchema.java | 46 ++ .../onap/cli/fw/schema/OnapCommandSchemaInfo.java | 122 ++++ .../cli/fw/schema/OnapCommandSchemaLoader.java | 550 +++++++++++++++ .../cli/fw/utils/OnapCommandDiscoveryUtils.java | 95 +-- .../onap/cli/fw/utils/OnapCommandHelperUtils.java | 26 +- .../onap/cli/fw/utils/OnapCommandProfileUtils.java | 72 -- .../cli/fw/utils/OnapCommandSchemaLoaderUtils.java | 772 --------------------- .../org/onap/cli/fw/utils/OnapCommandUtils.java | 444 +----------- .../java/org/onap/cli/fw/utils/SchemaInfo.java | 122 ---- .../META-INF/services/org.onap.cli.fw.OnapCommand | 6 - .../services/org.onap.cli.fw.cmd.OnapCommand | 2 + framework/src/main/resources/log4j.properties | 2 +- .../open-cli-schema/http/basic-login.yaml | 19 - .../open-cli-schema/http/basic-logout.yaml | 19 - .../resources/open-cli-schema/http/catalog.yaml | 44 -- .../http/default_input_parameters_http.yaml | 36 - framework/src/main/resources/open-cli.properties | 29 +- .../org/onap/cli/cmd/sample/OnapCommandSample.java | 4 +- .../onap/cli/cmd/sample/OnapCommandSampleTest.java | 69 +- .../org/onap/cli/fw/OnapCommandRegistrarTest.java | 139 ---- .../cli/fw/ad/OnapAuthClientCommandBasedTest.java | 134 ---- .../java/org/onap/cli/fw/ad/OnapServiceTest.java | 38 - .../org/onap/cli/fw/cmd/OnapHttpCommandTest.java | 81 --- .../cli/fw/cmd/OnapSchemaValidateCommandTest.java | 3 +- .../org/onap/cli/fw/conf/OnapCommandConfgTest.java | 22 - .../onap/cli/fw/error/OnapCommandErrorTest.java | 54 +- .../org/onap/cli/fw/http/HttpInputOutputTest.java | 67 -- .../onap/cli/fw/http/OnapHttpConnectionTest.java | 205 ------ .../cli/fw/input/OnapCommandParameterTest.java | 16 +- .../org/onap/cli/fw/input/ParameterTypeTest.java | 22 +- .../OnapCommandResultAttributeScopeTest.java | 6 +- .../onap/cli/fw/output/OnapCommandResultTest.java | 44 +- .../org/onap/cli/fw/output/PrintDirectionTest.java | 6 +- .../org/onap/cli/fw/output/ResultTypeTest.java | 10 +- .../cli/fw/output/print/OnapCommandPrintTest.java | 10 +- .../cli/fw/registrar/OnapCommandRegistrarTest.java | 150 ++++ .../org/onap/cli/fw/schema/ValidateSchemaTest.java | 39 +- .../onap/cli/fw/utils/OnapCommandUtilsTest.java | 214 +----- .../cli/fw/utils/OpenCommandRegistrarTest.java | 41 -- .../META-INF/services/org.onap.cli.fw.OnapCommand | 1 - .../services/org.onap.cli.fw.cmd.OnapCommand | 1 + .../open-cli-schema/sample-test1-schema-http.yaml | 95 --- .../resources/open-cli-schema/testauth-login.yaml | 28 - .../resources/open-cli-schema/testauth-logout.yaml | 19 - framework/src/test/resources/open-cli.properties | 39 -- .../sample-test-schema-auth-required.yaml | 16 - .../test/resources/sample-test-schema-http.yaml | 92 --- .../sample-test-schema-no-auth-no-catalog.yaml | 26 - .../sample-test-schema-no-auth-yes-catalog.yaml | 28 - .../test/resources/sample-test-schema-swagger.yaml | 28 - .../sample-test-schema-yes-auth-no-catalog.yaml | 26 - ...yes-auth-with-additional-params-no-catalog.yaml | 28 - .../sample-test-schema-yes-auth-yes-catalog.yaml | 28 - .../src/test/resources/schema-validate-http.yaml | 98 --- 99 files changed, 2338 insertions(+), 6110 deletions(-) delete mode 100644 framework/src/main/java/org/onap/cli/fw/OnapCommand.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/OnapCommandRegistrar.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/OnapCommandSchema.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/ad/OnapAuthClient.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/ad/OnapService.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/cmd/BasicAuthLoginCommand.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/cmd/BasicAuthLogoutCommand.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/cmd/CatalogCommand.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/cmd/CommandType.java create mode 100644 framework/src/main/java/org/onap/cli/fw/cmd/OnapCommand.java create mode 100644 framework/src/main/java/org/onap/cli/fw/cmd/OnapCommandType.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/cmd/OnapHttpCommand.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/conf/Constants.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConfg.java create mode 100644 framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConfig.java create mode 100644 framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConstants.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/error/OnapCommandFailedMocoGenerate.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpFailure.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpHeaderNotFound.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpInvalidResponseBody.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpInvalidResultMap.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/error/OnapCommandLoginFailed.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/error/OnapCommandLogoutFailed.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/error/OnapCommandServiceNotFound.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/http/HttpInput.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/http/HttpResult.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/http/OnapHttpConnection.java create mode 100644 framework/src/main/java/org/onap/cli/fw/input/OnapCommandParameterType.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/input/ParameterType.java create mode 100644 framework/src/main/java/org/onap/cli/fw/input/cache/OnapCommandParamEntity.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/input/cache/Param.java create mode 100644 framework/src/main/java/org/onap/cli/fw/output/OnapCommandPrintDirection.java create mode 100644 framework/src/main/java/org/onap/cli/fw/output/OnapCommandResultType.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/output/PrintDirection.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/output/ResultType.java create mode 100644 framework/src/main/java/org/onap/cli/fw/registrar/OnapCommandRegistrar.java create mode 100644 framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchema.java create mode 100644 framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaInfo.java create mode 100644 framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaLoader.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/utils/OnapCommandProfileUtils.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/utils/OnapCommandSchemaLoaderUtils.java delete mode 100644 framework/src/main/java/org/onap/cli/fw/utils/SchemaInfo.java delete mode 100644 framework/src/main/resources/META-INF/services/org.onap.cli.fw.OnapCommand create mode 100644 framework/src/main/resources/META-INF/services/org.onap.cli.fw.cmd.OnapCommand delete mode 100644 framework/src/main/resources/open-cli-schema/http/basic-login.yaml delete mode 100644 framework/src/main/resources/open-cli-schema/http/basic-logout.yaml delete mode 100644 framework/src/main/resources/open-cli-schema/http/catalog.yaml delete mode 100644 framework/src/main/resources/open-cli-schema/http/default_input_parameters_http.yaml delete mode 100644 framework/src/test/java/org/onap/cli/fw/OnapCommandRegistrarTest.java delete mode 100644 framework/src/test/java/org/onap/cli/fw/ad/OnapAuthClientCommandBasedTest.java delete mode 100644 framework/src/test/java/org/onap/cli/fw/ad/OnapServiceTest.java delete mode 100644 framework/src/test/java/org/onap/cli/fw/cmd/OnapHttpCommandTest.java delete mode 100644 framework/src/test/java/org/onap/cli/fw/http/HttpInputOutputTest.java delete mode 100644 framework/src/test/java/org/onap/cli/fw/http/OnapHttpConnectionTest.java create mode 100644 framework/src/test/java/org/onap/cli/fw/registrar/OnapCommandRegistrarTest.java delete mode 100644 framework/src/test/java/org/onap/cli/fw/utils/OpenCommandRegistrarTest.java delete mode 100644 framework/src/test/resources/META-INF/services/org.onap.cli.fw.OnapCommand create mode 100644 framework/src/test/resources/META-INF/services/org.onap.cli.fw.cmd.OnapCommand delete mode 100644 framework/src/test/resources/open-cli-schema/sample-test1-schema-http.yaml delete mode 100644 framework/src/test/resources/open-cli-schema/testauth-login.yaml delete mode 100644 framework/src/test/resources/open-cli-schema/testauth-logout.yaml delete mode 100644 framework/src/test/resources/open-cli.properties delete mode 100644 framework/src/test/resources/sample-test-schema-auth-required.yaml delete mode 100644 framework/src/test/resources/sample-test-schema-http.yaml delete mode 100644 framework/src/test/resources/sample-test-schema-no-auth-no-catalog.yaml delete mode 100644 framework/src/test/resources/sample-test-schema-no-auth-yes-catalog.yaml delete mode 100644 framework/src/test/resources/sample-test-schema-swagger.yaml delete mode 100644 framework/src/test/resources/sample-test-schema-yes-auth-no-catalog.yaml delete mode 100644 framework/src/test/resources/sample-test-schema-yes-auth-with-additional-params-no-catalog.yaml delete mode 100644 framework/src/test/resources/sample-test-schema-yes-auth-yes-catalog.yaml delete mode 100644 framework/src/test/resources/schema-validate-http.yaml (limited to 'framework/src') diff --git a/framework/src/main/java/org/onap/cli/fw/OnapCommand.java b/framework/src/main/java/org/onap/cli/fw/OnapCommand.java deleted file mode 100644 index d931aaf3..00000000 --- a/framework/src/main/java/org/onap/cli/fw/OnapCommand.java +++ /dev/null @@ -1,282 +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.fw; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.onap.cli.fw.conf.Constants; -import org.onap.cli.fw.error.OnapCommandException; -import org.onap.cli.fw.error.OnapCommandHelpFailed; -import org.onap.cli.fw.error.OnapCommandInvalidParameterType; -import org.onap.cli.fw.error.OnapCommandInvalidPrintDirection; -import org.onap.cli.fw.error.OnapCommandInvalidResultAttributeScope; -import org.onap.cli.fw.error.OnapCommandInvalidSchema; -import org.onap.cli.fw.error.OnapCommandInvalidSchemaVersion; -import org.onap.cli.fw.error.OnapCommandNotInitialized; -import org.onap.cli.fw.error.OnapCommandParameterNameConflict; -import org.onap.cli.fw.error.OnapCommandParameterOptionConflict; -import org.onap.cli.fw.error.OnapCommandRegistrationFailed; -import org.onap.cli.fw.error.OnapCommandSchemaNotFound; -import org.onap.cli.fw.info.OnapCommandInfo; -import org.onap.cli.fw.input.OnapCommandParameter; -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.ResultType; -import org.onap.cli.fw.utils.OnapCommandHelperUtils; -import org.onap.cli.fw.utils.OnapCommandSchemaLoaderUtils; -import org.onap.cli.fw.utils.OnapCommandUtils; - -/** - * Oclip Command. - * - */ -public abstract class OnapCommand { - - private String cmdDescription; - - private String cmdName; - - private String cmdSchemaName; - - private OnapCommandInfo info = new OnapCommandInfo(); - - private List cmdParameters = new ArrayList<>(); - - private OnapCommandResult cmdResult = new OnapCommandResult(); - - protected boolean isInitialzied = false; - - public String getSchemaVersion() { - return Constants.OPEN_CLI_SCHEMA_VERSION_VALUE_1_0; - } - - /** - * Oclip command description, defined by derived command. - */ - public String getDescription() { - return this.cmdDescription; - } - - public void setDescription(String description) { - this.cmdDescription = description; - } - - /* - * Oclip command name like user-create, ns-list, etc , defined by derived command - */ - public String getName() { - return this.cmdName; - } - - public void setName(String name) { - this.cmdName = name; - } - - public OnapCommandInfo getInfo() { - return info; - } - - public void setInfo(OnapCommandInfo info) { - this.info = info; - } - - public void setParameters(List parameters) { - this.cmdParameters = parameters; - } - - /* - * Oclip command input parameters, defined by derived command - */ - public List getParameters() { - return this.cmdParameters; - } - - /* - * Oclip command input parameters, defined by derived command - */ - public Map getParametersMap() { - return OnapCommandUtils.getInputMap(this.getParameters()); - } - - /* - * Oclip command output results, defined by derived command - */ - public OnapCommandResult getResult() { - return this.cmdResult; - } - - public void setResult(OnapCommandResult result) { - this.cmdResult = result; - } - - public String getSchemaName() { - return cmdSchemaName; - } - - protected void setSchemaName(String schemaName) { - this.cmdSchemaName = schemaName; - } - - /** - * Initialize this command from command schema and assumes schema is already validated. - * - * @throws OnapCommandRegistrationFailed - * Command Registration Exception - * @throws OnapCommandInvalidResultAttributeScope - * InvalidResultAttribute Exception - * @throws OnapCommandInvalidPrintDirection - * InvalidPrintDirection Exception - * @throws OnapCommandInvalidParameterType - * InvalidParameterType Exception - * @throws OnapCommandSchemaNotFound - * SchemaNotFound Exception - * @throws OnapCommandInvalidSchema - * InvalidSchema Exception - * @throws OnapCommandParameterOptionConflict - * ParameterOptionConflict Exception - * @throws OnapCommandParameterNameConflict - * ParameterNameConflict Exception - * @throws OnapCommandInvalidSchemaVersion - * InvalidSchemaVersion Exception - * - * @return List of error strings - */ - public List initializeSchema(String schema) throws OnapCommandException { - return this.initializeSchema(schema, false); - } - - public List initializeSchema(String schema, boolean validate) throws OnapCommandException { - this.setSchemaName(schema); - - List errors = OnapCommandSchemaLoaderUtils.loadSchema(this, schema, true, validate); - errors.addAll(this.initializeProfileSchema()); - this.isInitialzied = true; - - return errors; - } - /** - * Any additional profile based such as http schema could be initialized. - */ - protected List initializeProfileSchema() throws OnapCommandException { - return new ArrayList<>(); - } - - /* - * Validate input parameters. This can be overridden in derived commands - */ - protected void validate() throws OnapCommandException { - for (OnapCommandParameter param : this.getParameters()) { - if (param.isInclude()) { - param.validate(); - } - } - } - - /** - * Oclip command execute with given parameters on service. Before calling this method, its mandatory to set all - * parameters value. - * - * @throws OnapCommandException - * : General Command Exception - */ - public OnapCommandResult execute() throws OnapCommandException { - if (!this.isInitialzied) { - throw new OnapCommandNotInitialized(this.getClass().getName()); - } - - Map paramMap = this.getParametersMap(); - - // -h or --help is always higher precedence !, user can set this value to get help message - if (Constants.BOOLEAN_TRUE.equals(paramMap.get(Constants.DEFAULT_PARAMETER_HELP).getValue())) { - OnapCommandResult result = new OnapCommandResult(); - result.setType(ResultType.TEXT); - result.setOutput(this.printHelp()); - return result; - } - - // -v or --version is next higher precedence !, user can set this value to get help message - if (Constants.BOOLEAN_TRUE.equals(paramMap.get(Constants.DEFAULT_PARAMETER_VERSION).getValue())) { - OnapCommandResult result = new OnapCommandResult(); - result.setType(ResultType.TEXT); - result.setOutput(this.printVersion()); - return result; - } - - // validate - this.validate(); - - // -f or --format - this.cmdResult.setType( - ResultType.get(paramMap.get(Constants.DEFAULT_PARAMETER_OUTPUT_FORMAT).getValue().toString())); - if (Constants.BOOLEAN_TRUE.equals(paramMap.get(Constants.DEFAULT_PARAMETER_OUTPUT_ATTR_LONG).getValue())) { - this.cmdResult.setScope(OnapCommandResultAttributeScope.LONG); - } - // --no-title - if (Constants.BOOLEAN_TRUE.equals(paramMap.get(Constants.DEFAULT_PARAMETER_OUTPUT_NO_TITLE).getValue())) { - this.cmdResult.setIncludeTitle(false); - } - - // --debug - if (Constants.BOOLEAN_TRUE.equals(paramMap.get(Constants.DEFAULT_PARAMETER_DEBUG).getValue())) { - this.cmdResult.setDebug(true); - } - - //pre-process result attributes for spl entries and input parameters - for (OnapCommandResultAttribute attr: this.cmdResult.getRecords()) { - if (!attr.getDefaultValue().isEmpty()) { - attr.setDefaultValue(OnapCommandUtils.replaceLineForSpecialValues(attr.getDefaultValue())); - attr.setDefaultValue(OnapCommandUtils.replaceLineFromInputParameters( - attr.getDefaultValue(), this.getParametersMap())); - } - } - - this.run(); - - return this.cmdResult; - } - - /* - * Each command implements run method to executing the command. - * - */ - protected abstract void run() throws OnapCommandException; - - /** - * Returns the service service version it supports. - * - * @return version - */ - public String printVersion() { - return this.getInfo().getService(); - } - - /** - * Provides help message for this command. - * - * @return help message - * @throws OnapCommandHelpFailed - * Failed to execute Help command. - */ - 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/OnapCommandRegistrar.java b/framework/src/main/java/org/onap/cli/fw/OnapCommandRegistrar.java deleted file mode 100644 index d50ff464..00000000 --- a/framework/src/main/java/org/onap/cli/fw/OnapCommandRegistrar.java +++ /dev/null @@ -1,384 +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.fw; - -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.conf.Constants; -import org.onap.cli.fw.conf.OnapCommandConfg; -import org.onap.cli.fw.error.OnapCommandException; -import org.onap.cli.fw.error.OnapCommandHelpFailed; -import org.onap.cli.fw.error.OnapCommandInvalidRegistration; -import org.onap.cli.fw.error.OnapCommandNotFound; -import org.onap.cli.fw.error.OnapCommandProductVersionInvalid; -import org.onap.cli.fw.error.OnapCommandRegistrationProductInfoMissing; -import org.onap.cli.fw.error.OnapUnsupportedSchemaProfile; -import org.onap.cli.fw.input.cache.OnapCommandParameterCache; -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.PrintDirection; -import org.onap.cli.fw.output.ResultType; -import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils; -import org.onap.cli.fw.utils.OnapCommandHelperUtils; -import org.onap.cli.fw.utils.OnapCommandUtils; -import org.onap.cli.fw.utils.SchemaInfo; - - -/** - * Oclip Command registrar provides a common place, where every command would get registered automatically when its - * loaded into JVM. - * - */ -public class OnapCommandRegistrar { - private Map> registry = new HashMap<>(); - - private Map> registryProfilePlugins = new HashMap<>(); - - private Set availableProductVersions = new HashSet<>(); - - private String enabledProductVersion = OnapCommandConfg.getEnabledProductVersion(); - - private boolean isInteractiveMode = false; - - private OnapCommandParameterCache paramCache = OnapCommandParameterCache.getInstance(); - - public boolean isInteractiveMode() { - return isInteractiveMode; - } - - public void setInteractiveMode(boolean isInteractiveMode) { - this.isInteractiveMode = isInteractiveMode; - } - - public Map getParamCache() { - return paramCache.getParams(this.getEnabledProductVersion()); - } - - public void addParamCache(String paramName, String paramValue) { - paramCache.add(this.getEnabledProductVersion(), paramName, paramValue); - } - - public void removeParamCache(String paramName) { - paramCache.remove(this.getEnabledProductVersion(), paramName); - } - - public void setProfile(String profileName) { - this.paramCache.setProfile(profileName); - } - - private static OnapCommandRegistrar registrar = null; - - /** - * Register the command into registrar and throws OnapInvalidCommandRegistration for invalid command. - * - * @param name - * Command Name - * @param cmd - * Command Class - * @throws OnapCommandInvalidRegistration - * Invalid registration exception - * @throws OnapCommandRegistrationProductInfoMissing - */ - private void register(String name, String version, Class cmd) throws OnapCommandInvalidRegistration, OnapCommandRegistrationProductInfoMissing { - if (version == null || version.isEmpty()) { - throw new OnapCommandRegistrationProductInfoMissing(name); - } - - this.registry.put(name + ":" + version, cmd); - this.availableProductVersions.add(version); - - } - - private void registerProfilePlugin(String profile, Class cmd) { - this.registryProfilePlugins.put(profile, cmd); - } - - /** - * Get global registrar. - * - * @throws OnapCommandException - * exception - */ - public static OnapCommandRegistrar getRegistrar() throws OnapCommandException { - if (registrar == null) { - registrar = new OnapCommandRegistrar(); - registrar.autoDiscoverSchemas(); - } - - return registrar; - } - - /** - * Get the list of discovered commands by registrar. - * - * @return set - */ - public Set listCommands() { - return this.registry.keySet(); - } - - /** - * Get the list of discovered commands for a given product version in registrar. - * - * @return set - */ - public Set listCommandsForEnabledProductVersion() { - String version = this.getEnabledProductVersion(); - - Set cmds = new HashSet<>(); - if (!this.availableProductVersions.contains(version)) { - return cmds; - } - - for (String cmd: this.registry.keySet()) { - if (cmd.split(":")[1].equalsIgnoreCase(version)) { - cmds.add(cmd.split(":")[0]); - } - } - return cmds; - } - - public Class getProfilePlugin(String profile) throws OnapUnsupportedSchemaProfile { - if (!this.registryProfilePlugins.containsKey(profile)) { - throw new OnapUnsupportedSchemaProfile(profile); - } - - return this.registryProfilePlugins.get(profile); - } - - public Set getAvailableProductVersions() { - return this.availableProductVersions; - } - - public void setEnabledProductVersion(String version) throws OnapCommandProductVersionInvalid { - if (!this.availableProductVersions.contains(version)) { - throw new OnapCommandProductVersionInvalid(version, availableProductVersions); - } - - this.enabledProductVersion = version; - } - - public String getEnabledProductVersion() { - return this.enabledProductVersion; - } - - /** - * Returns command details. - * - * @return map - * @throws OnapCommandException - * exception - */ - public List listCommandInfo() throws OnapCommandException { - return OnapCommandDiscoveryUtils.discoverSchemas(); - } - - /** - * Get the OnapCommand, which CLI main would use to find the command based on the command name. - * - * @param cmdName - * Name of command - * @return OnapCommand - * @throws OnapCommandException - * Exception - */ - public OnapCommand get(String cmdName) throws OnapCommandException { - return this.get(cmdName, this.getEnabledProductVersion()); - } - - /** - * 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 - * @return OnapCommand - * @throws OnapCommandException - * Exception - */ - public OnapCommand get(String cmdName, String version) throws OnapCommandException { - Class cls = registry.get(cmdName + ":" + version); - //mrkanag: Restrict auth/catalog type commands only available during devMode. in production - //don't expose the auth type and catalog type commands - - if (cls == null) { - throw new OnapCommandNotFound(cmdName, version); - } - - OnapCommand cmd = OnapCommandDiscoveryUtils.loadCommandClass(cls); - String schemaName = OnapCommandDiscoveryUtils.getSchemaInfo(cmdName, version).getSchemaName(); - cmd.initializeSchema(schemaName); - - return cmd; - } - - private Map> autoDiscoverCommandPlugins() throws OnapCommandException { - List> cmds = OnapCommandDiscoveryUtils.discoverCommandPlugins(); - Map> map = new HashMap<>(); - - for (Class cmd : cmds) { - if (cmd.isAnnotationPresent(OnapCommandSchema.class)) { - OnapCommandSchema ano = cmd.getAnnotation(OnapCommandSchema.class); - if (ano.schema() != null && !ano.schema().isEmpty()) { - map.put(ano.schema(), cmd); - } else if (ano.type() != null && !ano.type().isEmpty()) { - this.registerProfilePlugin(ano.type(), cmd); - map.put(ano.type(), cmd); - } else { - throw new OnapUnsupportedSchemaProfile(ano.schema()); - } - } - } - - return map; - } - - private void autoDiscoverSchemas() throws OnapCommandException { - List schemas = OnapCommandDiscoveryUtils.discoverOrLoadSchemas(true); - - Map> plugins = this.autoDiscoverCommandPlugins(); - - for (SchemaInfo schema : schemas) { - if (schema.isIgnore()) { - continue; - } - - 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 { - throw new OnapUnsupportedSchemaProfile(schema.getSchemaURI()); - } - } - } - - /** - * Helps to find the Oclip CLI version, could be used with --version or -v option. - * - * @return string - */ - public String getVersion() { - String version = this.getClass().getPackage().getImplementationVersion(); - if (version == null) { - version = OnapCommandConfg.getVersion(); - } - - String buildTime = OnapCommandHelperUtils.findLastBuildTime(); - if (buildTime!= null && !buildTime.isEmpty()) { - buildTime = " [" + buildTime + "]"; - } else { - buildTime = ""; - } - - String configuredProductVersion = this.getEnabledProductVersion(); - - String versionInfo = ""; - try { - versionInfo = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(Constants.VERSION_INFO)); - } catch (IOException e) { - //Never occurs // NOSONAR - } - - versionInfo = versionInfo.replaceAll(Constants.VERSION_INFO_PLACE_HOLDER_ENB_PRD_VER, configuredProductVersion); - versionInfo = versionInfo.replaceAll(Constants.VERSION_INFO_PLACE_HOLDER_AVL_PRD_VER, this.availableProductVersions.toString()); - versionInfo = versionInfo.replaceAll(Constants.VERSION_INFO_PLACE_HOLDER_VERSION + "", version + buildTime); - - return versionInfo; - } - - /** - * Provides the help message in tabular format for all commands registered in this registrar. - * - * @return string - * @throws OnapCommandHelpFailed - * Help cmd failed - */ - public String getHelp() throws OnapCommandHelpFailed { - return this.getHelp(false); - } - - public String getHelpForEnabledProductVersion() throws OnapCommandHelpFailed { - return this.getHelp(true); - } - - private String getHelp(boolean isEnabledProductVersionOnly) throws OnapCommandHelpFailed { - OnapCommandResult help = new OnapCommandResult(); - help.setType(ResultType.TABLE); - help.setPrintDirection(PrintDirection.LANDSCAPE); - - OnapCommandResultAttribute attr = new OnapCommandResultAttribute(); - attr.setName(Constants.NAME.toUpperCase()); - attr.setDescription(Constants.DESCRIPTION); - attr.setScope(OnapCommandResultAttributeScope.SHORT); - help.getRecords().add(attr); - - OnapCommandResultAttribute attrVer = new OnapCommandResultAttribute(); - if (!isEnabledProductVersionOnly) { - attrVer.setName(Constants.INFO_PRODUCT.toUpperCase()); - attrVer.setDescription(Constants.DESCRIPTION); - attrVer.setScope(OnapCommandResultAttributeScope.SHORT); - help.getRecords().add(attrVer); - } - - OnapCommandResultAttribute attrSrv = new OnapCommandResultAttribute(); - attrSrv.setName(Constants.SERVICE.toUpperCase()); - attrSrv.setDescription(Constants.SERVICE); - attrSrv.setScope(OnapCommandResultAttributeScope.SHORT); - help.getRecords().add(attrSrv); - - OnapCommandResultAttribute attrDesc = new OnapCommandResultAttribute(); - attrDesc.setName(Constants.DESCRIPTION.toUpperCase()); - attrDesc.setDescription(Constants.DESCRIPTION); - attrDesc.setScope(OnapCommandResultAttributeScope.SHORT); - help.getRecords().add(attrDesc); - - for (String cmdName : isEnabledProductVersionOnly ? OnapCommandUtils.sort(this.listCommandsForEnabledProductVersion()) : OnapCommandUtils.sort(this.listCommands())) { - OnapCommand cmd; - try { - if (!isEnabledProductVersionOnly) { - String []cmdVer = cmdName.split(":"); - cmd = this.get(cmdVer[0], cmdVer[1]); - attr.getValues().add(cmdVer[0]); - attrVer.getValues().add(cmdVer[1]); - } else { - cmd = this.get(cmdName); - attr.getValues().add(cmdName); - } - - attrSrv.getValues().add(cmd.printVersion()); - attrDesc.getValues().add(cmd.getDescription()); - } catch (OnapCommandException e) { - throw new OnapCommandHelpFailed(e); - } - } - - try { - return "\n\nCommands:\n" + help.print() + (isEnabledProductVersionOnly ? "" : "\n" + this.getVersion()); - } catch (OnapCommandException e) { - throw new OnapCommandHelpFailed(e); - } - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/OnapCommandSchema.java b/framework/src/main/java/org/onap/cli/fw/OnapCommandSchema.java deleted file mode 100644 index d5f71044..00000000 --- a/framework/src/main/java/org/onap/cli/fw/OnapCommandSchema.java +++ /dev/null @@ -1,46 +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.fw; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Provide command name and schema file location, which is placed in the main resources folder (in classpath). It is - * recommended to keep the name for schema, in the form of oclip-[command-name]-schema.yaml, considered this format as - * default if the schema declaration is missing for a command abc-create, schema file name could be - * abc-create-schema.yaml, corresponding command would like as below - * - * @OnapCommandSchema(type="http", schema="onap-abc-create-schema.yaml") public class AbcCreate extends - * OnapCommand { ... } - */ -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface OnapCommandSchema { - /** - * Schema file name placed under class path - * - * @return - */ - String schema() default ""; - - /** - * Schema type - */ - String type() default ""; -} diff --git a/framework/src/main/java/org/onap/cli/fw/ad/OnapAuthClient.java b/framework/src/main/java/org/onap/cli/fw/ad/OnapAuthClient.java deleted file mode 100644 index 6a324808..00000000 --- a/framework/src/main/java/org/onap/cli/fw/ad/OnapAuthClient.java +++ /dev/null @@ -1,161 +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.fw.ad; - -import java.util.HashMap; -import java.util.Map; - -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.OnapCommandRegistrar; -import org.onap.cli.fw.cmd.OnapHttpCommand; -import org.onap.cli.fw.conf.Constants; -import org.onap.cli.fw.conf.OnapCommandConfg; -import org.onap.cli.fw.error.OnapCommandException; -import org.onap.cli.fw.error.OnapCommandHttpFailure; -import org.onap.cli.fw.error.OnapCommandInvalidParameterValue; -import org.onap.cli.fw.error.OnapCommandNotFound; -import org.onap.cli.fw.http.HttpInput; -import org.onap.cli.fw.http.HttpResult; -import org.onap.cli.fw.http.OnapHttpConnection; -import org.onap.cli.fw.output.OnapCommandResultAttribute; -import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils; -import org.onap.cli.fw.utils.OnapCommandUtils; - -/** - * Oclip Auth client helps to do login and logout. - * - */ -public class OnapAuthClient { - - private OnapHttpCommand cmd = null; - - private OnapHttpConnection http = null; - - public OnapAuthClient(OnapHttpCommand cmd, boolean debug) throws OnapCommandHttpFailure, OnapCommandInvalidParameterValue { - this.cmd = cmd; - this.http = new OnapHttpConnection(debug); - } - - /** - * Login. - * - * @throws OnapCommandException - * exception - */ - public void login() throws OnapCommandException { - - // For development purpose, its introduced and is not supported for production - if (OnapCommandConfg.isAuthIgnored()) { - return; - } - - OnapCommand login = OnapCommandDiscoveryUtils.findAuthCommand(this.cmd, "login"); - - OnapCommandUtils.copyParamsFrom(this.cmd, login); - login.execute(); - - //It is safely assumed that all outputs are considered as common http headers. - Map headers = new HashMap<>(); - for (OnapCommandResultAttribute attr: login.getResult().getRecords()) { - String headerValue = attr.getValues().get(0); - if (headerValue != null && !headerValue.isEmpty()) { - headers.put(attr.getName(), attr.getValues().get(0)); - } - } - - this.http.setCommonHeaders(headers); - } - - /** - * Logout. - * - * @throws OnapCommandException - * exception - */ - public void logout() throws OnapCommandException { - // For development purpose, its introduced and is not supported for production - if (OnapCommandConfg.isAuthIgnored()) { - return; - } - - OnapCommand logout = OnapCommandDiscoveryUtils.findAuthCommand(this.cmd, "logout"); - - OnapCommandUtils.copyParamsFrom(this.cmd, logout); - - logout.execute(); - - this.http.close(); - } - - /** - * Find given service base path. - * - * @throws OnapCommandException - * exception - */ - public String getServiceUrl() throws OnapCommandException { - return this.getServiceUrl(this.cmd); - } - - private String getServiceUrl(OnapHttpCommand cmd) throws OnapCommandException { - if (cmd.getService().isModeDirect()){ - return cmd.getParametersMap().get(Constants.DEAFULT_PARAMETER_HOST_URL).getValue().toString(); - } else { //Catalog mode - OnapCommand catalog = OnapCommandRegistrar.getRegistrar().get("catalog"); - - Map paramsOverrides = new HashMap<>(); - paramsOverrides.put(Constants.CATALOG_SERVICE_NAME, cmd.getService().getName()); - paramsOverrides.put(Constants.CATALOG_SERVICE_VERSION, cmd.getService().getVersion()); - - OnapCommandUtils.copyParamsFrom(cmd, catalog, paramsOverrides); - - catalog.execute(); - - String hostUrl = catalog.getResult().getRecordsMap().get(Constants.CATALOG_SERVICE_HOST_URL).getValues().get(0); - hostUrl = hostUrl.trim(); - if (hostUrl.endsWith("/")) { - hostUrl = hostUrl.substring(0, hostUrl.length()-1); - } - - String basePath = catalog.getResult().getRecordsMap().get(Constants.CATALOG_SERVICE_BASE_PATH).getValues().get(0); - basePath = basePath.trim(); - if (basePath.startsWith("/")) { - basePath = basePath.substring(1); - } - - return hostUrl + "/" + basePath; - } - } - - - public String getDebugInfo() { - return this.http.getDebugInfo(); - } - - /** - * Http call to external service. - * - * @param input - * http input - * @return http result - * @throws OnapCommandHttpFailure - * exception - */ - public HttpResult run(HttpInput input) throws OnapCommandHttpFailure { - return this.http.request(input); - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/ad/OnapService.java b/framework/src/main/java/org/onap/cli/fw/ad/OnapService.java deleted file mode 100644 index a16c4434..00000000 --- a/framework/src/main/java/org/onap/cli/fw/ad/OnapService.java +++ /dev/null @@ -1,101 +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.fw.ad; - -import org.onap.cli.fw.conf.Constants; - -/** - * Oclip Service as reported in api catalog. - */ -public class OnapService { - /* - * Oclip Service name like aai. - */ - private String serviceName; - - /* - * Oclip Service API version like v1, v2, etc - */ - private String serviceVersion; - - private String basePath; - - /** - * Mode of service consideration. By default, it goes with - * 'catalog' mode, where basePath will be discovered by - * the framework using serviceName and serviceVersion - * Another mode is 'direct', in which bastPath will be - * same as OnapCredentails.ServiceUrl. - */ - private String mode = Constants.MODE_DIRECT; - - private String authType = Constants.AUTH_NONE; - - public String getMode() { - return mode; - } - - public void setMode(String mode) { - this.mode = mode; - } - - public boolean isModeDirect() { - return this.getMode().equals(Constants.MODE_DIRECT); - } - - public String getAuthType() { - return this.authType; - } - - public void setAuthType(String auth) { - this.authType = auth; - } - - public boolean isNoAuth() { - return this.authType.equalsIgnoreCase(Constants.AUTH_NONE); - } - - public String getName() { - return serviceName; - } - - public void setName(String name) { - this.serviceName = name; - } - - public String getVersion() { - return serviceVersion; - } - - public void setVersion(String version) { - this.serviceVersion = version; - } - - public String getBasePath() { - return basePath; - } - - public void setBasePath(String basePath) { - this.basePath = basePath; - } - - @Override - public String toString() { - return this.getName() + " " + this.getVersion(); - } - -} \ No newline at end of file diff --git a/framework/src/main/java/org/onap/cli/fw/cmd/BasicAuthLoginCommand.java b/framework/src/main/java/org/onap/cli/fw/cmd/BasicAuthLoginCommand.java deleted file mode 100644 index 28a86a9b..00000000 --- a/framework/src/main/java/org/onap/cli/fw/cmd/BasicAuthLoginCommand.java +++ /dev/null @@ -1,48 +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.fw.cmd; - -import java.util.Map; - -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.impl.auth.BasicScheme; -import org.onap.cli.fw.OnapCommandSchema; -import org.onap.cli.fw.conf.Constants; -import org.onap.cli.fw.error.OnapCommandException; -import org.onap.cli.fw.input.OnapCommandParameter; - -@OnapCommandSchema(schema = "basic-login.yaml") -public class BasicAuthLoginCommand extends OnapHttpCommand { - - @Override - protected void run() throws OnapCommandException { - - //get the input arguments - Map paramMap = getParametersMap(); - OnapCommandParameter usernameParam = paramMap.get(Constants.DEAFULT_PARAMETER_USERNAME); - String username = usernameParam.getValue().toString(); - OnapCommandParameter usernamePassword = paramMap.get(Constants.DEAFULT_PARAMETER_PASSWORD); - String password = usernamePassword.getValue().toString(); - - //Execute the command to get token - String authToken = BasicScheme.authenticate(new UsernamePasswordCredentials( - username, password), "UTF-8", false).getValue(); - - //Fill out the result part - this.getResult().getRecordsMap().get(Constants.AUTH_SERVICE_AUTHORIZATION).getValues().add(authToken); - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/cmd/BasicAuthLogoutCommand.java b/framework/src/main/java/org/onap/cli/fw/cmd/BasicAuthLogoutCommand.java deleted file mode 100644 index 553b28f8..00000000 --- a/framework/src/main/java/org/onap/cli/fw/cmd/BasicAuthLogoutCommand.java +++ /dev/null @@ -1,29 +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.fw.cmd; - -import org.onap.cli.fw.OnapCommandSchema; -import org.onap.cli.fw.error.OnapCommandException; - -@OnapCommandSchema(schema = "basic-logout.yaml") -public class BasicAuthLogoutCommand extends OnapHttpCommand { - - @Override - protected void run() throws OnapCommandException { - //do nothing // NOSONAR - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/cmd/CatalogCommand.java b/framework/src/main/java/org/onap/cli/fw/cmd/CatalogCommand.java deleted file mode 100644 index 34bf90c2..00000000 --- a/framework/src/main/java/org/onap/cli/fw/cmd/CatalogCommand.java +++ /dev/null @@ -1,28 +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.fw.cmd; - -import org.onap.cli.fw.OnapCommandSchema; -import org.onap.cli.fw.error.OnapCommandException; - -@OnapCommandSchema(schema = "catalog.yaml") -public class CatalogCommand extends OnapHttpCommand { - - @Override - protected void run() throws OnapCommandException { - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/cmd/CommandType.java b/framework/src/main/java/org/onap/cli/fw/cmd/CommandType.java deleted file mode 100644 index baaf7e12..00000000 --- a/framework/src/main/java/org/onap/cli/fw/cmd/CommandType.java +++ /dev/null @@ -1,52 +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.fw.cmd; - -import org.onap.cli.fw.error.OnapCommandInvalidCommandType; -import org.onap.cli.fw.error.OnapCommandInvalidParameterType; - -/** - * Command type supported by Oclip CLI. - * - */ -public enum CommandType { - - AUTH, - CATALOG, - CMD; - - /** - * Get parameter type. - * - * @param name - * type name - * @return type - * @throws OnapCommandInvalidParameterType - * exception - */ - public static CommandType get(String name) throws OnapCommandInvalidCommandType { - if (AUTH.name().equalsIgnoreCase(name)) { - return AUTH; - } else if (CATALOG.name().equalsIgnoreCase(name)) { - return CATALOG; - } else if (CMD.name().equalsIgnoreCase(name)) { - return CMD; - } else { - throw new OnapCommandInvalidCommandType(name); - } - } -} 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 new file mode 100644 index 00000000..4b7fe976 --- /dev/null +++ b/framework/src/main/java/org/onap/cli/fw/cmd/OnapCommand.java @@ -0,0 +1,243 @@ +/* + * 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.cmd; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.onap.cli.fw.conf.OnapCommandConstants; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandHelpFailed; +import org.onap.cli.fw.error.OnapCommandNotInitialized; +import org.onap.cli.fw.info.OnapCommandInfo; +import org.onap.cli.fw.input.OnapCommandParameter; +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.OnapCommandSchemaLoader; +import org.onap.cli.fw.utils.OnapCommandHelperUtils; +import org.onap.cli.fw.utils.OnapCommandUtils; + +/** + * Oclip Command. + * + */ +public abstract class OnapCommand { + + private String cmdDescription; + + private String cmdName; + + private String cmdSchemaName; + + private OnapCommandInfo info = new OnapCommandInfo(); + + private Set cmdParameters = new HashSet<>(); + + private OnapCommandResult cmdResult = new OnapCommandResult(); + + protected boolean isInitialzied = false; + + public String getSchemaVersion() { + return OnapCommandConstants.OPEN_CLI_SCHEMA_VERSION_VALUE_1_0; + } + + public String getDescription() { + return this.cmdDescription; + } + + public void setDescription(String description) { + this.cmdDescription = description; + } + + public String getName() { + return this.cmdName; + } + + public void setName(String name) { + this.cmdName = name; + } + + public OnapCommandInfo getInfo() { + return info; + } + + public void setInfo(OnapCommandInfo info) { + this.info = info; + } + + public void setParameters(Set parameters) { + this.cmdParameters = parameters; + } + + public Set getParameters() { + return this.cmdParameters; + } + + public Map getParametersMap() { + return OnapCommandUtils.getInputMap(this.getParameters()); + } + + public OnapCommandResult getResult() { + return this.cmdResult; + } + + public void setResult(OnapCommandResult result) { + this.cmdResult = result; + } + + public String getSchemaName() { + return cmdSchemaName; + } + + protected void setSchemaName(String schemaName) { + this.cmdSchemaName = schemaName; + } + + /** + * Initialize this command from command schema and assumes schema is already validated. + * + * @throws OnapCommandException + * + * @return List of error strings + */ + public List initializeSchema(String schema) throws OnapCommandException { + return this.initializeSchema(schema, false); + } + + public List initializeSchema(String schema, boolean validate) throws OnapCommandException { + this.setSchemaName(schema); + + List errors = OnapCommandSchemaLoader.loadSchema(this, schema, true, validate); + errors.addAll(this.initializeProfileSchema()); + this.isInitialzied = true; + + return errors; + } + /** + * Any additional profile based such as http schema could be initialized. + */ + protected List initializeProfileSchema() throws OnapCommandException { + return new ArrayList<>(); + } + + /* + * Validate input parameters. This can be overridden in derived commands + */ + protected void validate() throws OnapCommandException { + for (OnapCommandParameter param : this.getParameters()) { + if (param.isInclude()) { + param.validate(); + } + } + } + + /** + * Oclip command execute with given parameters on service. Before calling this method, its mandatory to set all + * parameters value. + * + * @throws OnapCommandException + * : General Command Exception + */ + public OnapCommandResult execute() throws OnapCommandException { + if (!this.isInitialzied) { + throw new OnapCommandNotInitialized(this.getClass().getName()); + } + + Map paramMap = this.getParametersMap(); + + // -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())) { + OnapCommandResult result = new OnapCommandResult(); + result.setType(OnapCommandResultType.TEXT); + result.setOutput(this.printHelp()); + return result; + } + + // -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())) { + OnapCommandResult result = new OnapCommandResult(); + result.setType(OnapCommandResultType.TEXT); + result.setOutput(this.printVersion()); + return result; + } + + // validate + this.validate(); + + // -f or --format + this.cmdResult.setType( + OnapCommandResultType.get(paramMap.get(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_FORMAT).getValue().toString())); + if (OnapCommandConstants.BOOLEAN_TRUE.equals(paramMap.get(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_ATTR_LONG).getValue())) { + this.cmdResult.setScope(OnapCommandResultAttributeScope.LONG); + } + // --no-title + if (OnapCommandConstants.BOOLEAN_TRUE.equals(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())) { + this.cmdResult.setDebug(true); + } + + //pre-process result attributes for spl entries and input parameters + for (OnapCommandResultAttribute attr: this.cmdResult.getRecords()) { + if (!attr.getDefaultValue().isEmpty()) { + attr.setDefaultValue(OnapCommandUtils.replaceLineForSpecialValues(attr.getDefaultValue())); + attr.setDefaultValue(OnapCommandUtils.replaceLineFromInputParameters( + attr.getDefaultValue(), this.getParametersMap())); + } + } + + this.run(); + + return this.cmdResult; + } + + /* + * Each command implements run method to executing the command. + * + */ + protected abstract void run() throws OnapCommandException; + + /** + * Returns the service service version it supports. + * + * @return version + */ + public String printVersion() { + return this.getInfo().getService(); + } + + /** + * Provides help message for this command. + * + * @return help message + * @throws OnapCommandHelpFailed + * Failed to execute Help command. + */ + 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/cmd/OnapCommandType.java b/framework/src/main/java/org/onap/cli/fw/cmd/OnapCommandType.java new file mode 100644 index 00000000..e874a14e --- /dev/null +++ b/framework/src/main/java/org/onap/cli/fw/cmd/OnapCommandType.java @@ -0,0 +1,52 @@ +/* + * 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.cmd; + +import org.onap.cli.fw.error.OnapCommandInvalidCommandType; +import org.onap.cli.fw.error.OnapCommandInvalidParameterType; + +/** + * Command type supported by Oclip CLI. + * + */ +public enum OnapCommandType { + + AUTH, + CATALOG, + CMD; + + /** + * Get parameter type. + * + * @param name + * type name + * @return type + * @throws OnapCommandInvalidParameterType + * exception + */ + public static OnapCommandType get(String name) throws OnapCommandInvalidCommandType { + if (AUTH.name().equalsIgnoreCase(name)) { + return AUTH; + } else if (CATALOG.name().equalsIgnoreCase(name)) { + return CATALOG; + } else if (CMD.name().equalsIgnoreCase(name)) { + return CMD; + } else { + throw new OnapCommandInvalidCommandType(name); + } + } +} diff --git a/framework/src/main/java/org/onap/cli/fw/cmd/OnapHttpCommand.java b/framework/src/main/java/org/onap/cli/fw/cmd/OnapHttpCommand.java deleted file mode 100644 index 892f367a..00000000 --- a/framework/src/main/java/org/onap/cli/fw/cmd/OnapHttpCommand.java +++ /dev/null @@ -1,199 +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.fw.cmd; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.OnapCommandSchema; -import org.onap.cli.fw.ad.OnapAuthClient; -import org.onap.cli.fw.ad.OnapService; -import org.onap.cli.fw.conf.Constants; -import org.onap.cli.fw.conf.OnapCommandConfg; -import org.onap.cli.fw.error.OnapCommandException; -import org.onap.cli.fw.error.OnapCommandExecutionFailed; -import org.onap.cli.fw.error.OnapCommandFailedMocoGenerate; -import org.onap.cli.fw.http.HttpInput; -import org.onap.cli.fw.http.HttpResult; -import org.onap.cli.fw.output.OnapCommandResultAttribute; -import org.onap.cli.fw.utils.OnapCommandSchemaLoaderUtils; -import org.onap.cli.fw.utils.OnapCommandUtils; -import org.onap.cli.http.mock.MockJsonGenerator; -import org.onap.cli.http.mock.MockRequest; -import org.onap.cli.http.mock.MockResponse; - -/** - * Oclip http Command. - * - */ -@OnapCommandSchema(type = Constants.HTTP_SCHEMA_PROFILE) -public class OnapHttpCommand extends OnapCommand { - - private HttpInput input = new HttpInput(); - - private List successStatusCodes = new ArrayList<>(); - - private Map resultMap = new HashMap<>(); - - protected OnapAuthClient authClient; - - private OnapService oclipService = new OnapService(); - - public void setInput(HttpInput input) { - this.input = input; - } - - @Override - public String getSchemaVersion() { - return Constants.OPEN_CLI_SCHEMA_VERSION_VALUE_1_0; - } - - public void setSuccessStatusCodes(List successStatusCodes) { - this.successStatusCodes = successStatusCodes; - } - - public void setResultMap(Map resultMap) { - this.resultMap = resultMap; - } - - public HttpInput getInput() { - return input; - } - - public List getSuccessStatusCodes() { - return successStatusCodes; - } - - public Map getResultMap() { - return resultMap; - } - - /* - * Oclip service, this command uses to execute it. - */ - public OnapService getService() { - return this.oclipService; - } - - public void setService(OnapService service) { - this.oclipService = service; - } - - @Override - protected List initializeProfileSchema() throws OnapCommandException { - return OnapCommandSchemaLoaderUtils.loadHttpSchema(this, this.getSchemaName(), true, false); - } - - @Override - protected void validate() throws OnapCommandException { - if (! this.isAuthRequired()) { - if (this.getParametersMap().containsKey(Constants.DEAFULT_PARAMETER_USERNAME)) { - this.getParametersMap().get(Constants.DEAFULT_PARAMETER_USERNAME).setOptional(true); - } - if (this.getParametersMap().containsKey(Constants.DEAFULT_PARAMETER_PASSWORD)) { - this.getParametersMap().get(Constants.DEAFULT_PARAMETER_PASSWORD).setOptional(true); - } - } - - super.validate(); - } - - private boolean isAuthRequired() { - return !this.getService().isNoAuth() - && "false".equals(this.getParametersMap().get(Constants.DEFAULT_PARAMETER_NO_AUTH).getValue()) - && this.getInfo().getCommandType().equals(CommandType.CMD); - } - - @Override - protected void run() throws OnapCommandException { - try { - // For auth/catalog type commands, login and logout logic is not required - boolean isAuthRequired = this.isAuthRequired(); - - this.authClient = new OnapAuthClient( - this, - this.getResult().isDebug()); - - if (isAuthRequired) { - this.authClient.login(); - } - - this.processRequest(); - - if (isAuthRequired) { - this.authClient.logout(); - } - - if (this.getResult().isDebug() && authClient != null) { - this.getResult().setDebugInfo(this.authClient.getDebugInfo()); - } - } catch (OnapCommandException e) { - if (this.getResult().isDebug() && authClient != null) { - this.getResult().setDebugInfo(this.authClient.getDebugInfo()); - } - throw e; - } - } - - protected void processRequest() throws OnapCommandException { - - HttpInput httpInput = OnapCommandUtils.populateParameters(this.getParametersMap(), this.getInput()); - httpInput.setUri(this.authClient.getServiceUrl() + httpInput.getUri()); - - HttpResult output = this.authClient.run(httpInput); - - this.getResult().setOutput(output); - if (!this.getSuccessStatusCodes().contains(output.getStatus())) { - throw new OnapCommandExecutionFailed(this.getName(), output.getBody(), output.getStatus()); - } - - Map> results = OnapCommandUtils.populateOutputs(this.getResultMap(), output); - results = OnapCommandUtils.populateOutputsFromInputParameters(results, this.getParametersMap()); - - for (OnapCommandResultAttribute attr : this.getResult().getRecords()) { - attr.setValues(results.get(attr.getName())); - } - generateJsonMock(httpInput, output, this.getSchemaName()); - } - - private void generateJsonMock(HttpInput httpInput, HttpResult httpResult, String schemaName) - throws OnapCommandFailedMocoGenerate { - - if (OnapCommandConfg.isSampleGenerateEnabled()) { - try { - MockRequest mockRequest = new MockRequest(); - mockRequest.setMethod(httpInput.getMethod()); - mockRequest.setUri(httpInput.getUri()); - mockRequest.setHeaders(httpInput.getReqHeaders()); - mockRequest.setJson(httpInput.getBody()); - - MockResponse mockResponse = new MockResponse(); - mockResponse.setStatus(httpResult.getStatus()); - mockResponse.setJson(httpResult.getBody()); - - MockJsonGenerator.generateMocking(mockRequest, mockResponse, OnapCommandConfg.getSampleGenerateTargetFolder() - + "/" + schemaName.replace(".yaml", "") + "-moco.json"); - } catch (IOException error) { - throw new OnapCommandFailedMocoGenerate(schemaName, error); - } - } - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/cmd/OnapSchemaRefreshCommand.java b/framework/src/main/java/org/onap/cli/fw/cmd/OnapSchemaRefreshCommand.java index 40d8eee5..2458a141 100644 --- a/framework/src/main/java/org/onap/cli/fw/cmd/OnapSchemaRefreshCommand.java +++ b/framework/src/main/java/org/onap/cli/fw/cmd/OnapSchemaRefreshCommand.java @@ -18,11 +18,10 @@ package org.onap.cli.fw.cmd; import java.util.List; -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.OnapCommandSchema; import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.schema.OnapCommandSchema; +import org.onap.cli.fw.schema.OnapCommandSchemaInfo; import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils; -import org.onap.cli.fw.utils.SchemaInfo; /** * Refresh external schema. @@ -34,13 +33,13 @@ public class OnapSchemaRefreshCommand extends OnapCommand { @Override protected void run() throws OnapCommandException { - List schemas = OnapCommandDiscoveryUtils.discoverOrLoadSchemas(true); + List schemas = OnapCommandDiscoveryUtils.discoverOrLoadSchemas(true); int i = 0; - for (SchemaInfo schema : schemas) { + for (OnapCommandSchemaInfo schema : schemas) { if (schema.isIgnore()) { continue; } - + i++; this.getResult().getRecordsMap().get("sr.no").getValues().add(String.valueOf(i)); this.getResult().getRecordsMap().get("command").getValues().add(schema.getCmdName()); diff --git a/framework/src/main/java/org/onap/cli/fw/cmd/OnapSchemaValidateCommand.java b/framework/src/main/java/org/onap/cli/fw/cmd/OnapSchemaValidateCommand.java index ff3f1c98..8448276b 100644 --- a/framework/src/main/java/org/onap/cli/fw/cmd/OnapSchemaValidateCommand.java +++ b/framework/src/main/java/org/onap/cli/fw/cmd/OnapSchemaValidateCommand.java @@ -20,14 +20,13 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.OnapCommandRegistrar; -import org.onap.cli.fw.OnapCommandSchema; -import org.onap.cli.fw.conf.Constants; +import org.onap.cli.fw.conf.OnapCommandConstants; import org.onap.cli.fw.error.OnapCommandException; import org.onap.cli.fw.input.OnapCommandParameter; +import org.onap.cli.fw.registrar.OnapCommandRegistrar; +import org.onap.cli.fw.schema.OnapCommandSchema; +import org.onap.cli.fw.schema.OnapCommandSchemaLoader; import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils; -import org.onap.cli.fw.utils.OnapCommandSchemaLoaderUtils; /** * Validate schema command. @@ -52,10 +51,10 @@ public class OnapSchemaValidateCommand extends OnapCommand { String ocsVersion = String.valueOf(versionParam.getValue()); String type = OnapCommandDiscoveryUtils.identitySchemaProfileType( - OnapCommandSchemaLoaderUtils.validateSchemaVersion(location, ocsVersion)); + OnapCommandSchemaLoader.validateSchemaVersion(location, ocsVersion)); OnapCommand cmd = null; - if (type.equals(Constants.BASIC_SCHEMA_PROFILE)) { + if (type.equals(OnapCommandConstants.BASIC_SCHEMA_PROFILE)) { cmd = new OnapCommand() { @Override protected void run() throws OnapCommandException { diff --git a/framework/src/main/java/org/onap/cli/fw/conf/Constants.java b/framework/src/main/java/org/onap/cli/fw/conf/Constants.java deleted file mode 100644 index 4c7581b7..00000000 --- a/framework/src/main/java/org/onap/cli/fw/conf/Constants.java +++ /dev/null @@ -1,227 +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.fw.conf; - -/** - * Constants. - * - */ -public class Constants { - - //config - public static final String CONF = "open-cli.properties"; - public static final String OPEN_IGNORE_AUTH = "cli.ignore_auth"; - public static final String OPEN_CLI_VERSION = "cli.version"; - public static final String HTTP_API_KEY_USE_COOKIES = "cli.http.api_key_use_cookies"; - - public static final String TOP_LEVEL_PARAMS_LIST = "cli.schema.top_level_params_list"; - public static final String TOP_LEVEL_MANDATORY_LIST = "cli.schema.top_level_mandatory_list"; - 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 INFO_PARAMS_LIST = "cli.schema.info_params_list"; - public static final String INFO_PARAMS_MANDATORY_LIST = "cli.schema.info_params_mandatory_list"; - public static final String INPUT_PARAMS_LIST = "cli.schema.input_params_list"; - public static final String INPUT_PARAMS_MANDATORY_LIST = "cli.schema.input_params_mandatory_list"; - public static final String RESULT_PARAMS_LIST = "cli.schema.result_params_list"; - public static final String RESULT_PARAMS_MANDATORY_LIST = "cli.schema.result_params_mandatory_list"; - public static final String HTTP_SECTIONS = "cli.schema.http_sections"; - public static final String HTTP_MANDATORY_SECTIONS = "cli.schema.http_mandatory_sections"; - public static final String HTTP_REQUEST_PARAMS = "cli.schema.http_request_params"; - public static final String HTTP_REQUEST_MANDATORY_PARAMS = "cli.schema.http_request_mandatory_params"; - public static final String HTTP_METHODS = "cli.schema.http_methods"; - public static final String BOOLEAN_VALUE = "cli.schema.boolean_values"; - public static final String AUTH_VALUES = "cli.schema.auth_values"; - public static final String MODE_VALUES = "cli.schema.mode_values"; - public static final String COMMAND_TYPE_VALUES = "cli.command.type"; - public static final String SCHEMA_TYPES_SUPPORTED = "cli.schema.type.supported"; - //http connection - public static final String SSLCONTEST_TLS = "TLSV1.2"; - public static final String APPLICATION_JSON = "application/json"; - - public static final String OPEN_CLI_PRODUCT_NAME = "cli.product_name"; - - //schema - public static final String OPEN_CLI_SCHEMA_VERSION = "open_cli_schema_version"; - public static final String OPEN_CLI_SCHEMA_VERSION_VALUE_1_0 = "1.0"; - - public static final String NAME = "name"; - - public static final String DESCRIPTION = "description"; - - //Info - public static final String INFO = "info"; - - public static final String INFO_PRODUCT = "product"; - public static final String OPEN_OPEN_CLI_PRODUCT_IN_USE_ENV_NAME = "OPEN_CLI_PRODUCT_IN_USE"; - - public static final String INFO_SERVICE = "service"; - public static final String INFO_TYPE = "type"; - public static final String INFO_AUTHOR = "author"; - public static final String INFO_IGNORE = "ignore"; - - //parameters - public static final String PARAMETERS = "parameters"; - public static final String SHORT_OPTION = "short_option"; - public static final String LONG_OPTION = "long_option"; - public static final String TYPE = "type"; - public static final String IS_OPTIONAL = "is_optional"; - public static final String DEFAULT_VALUE = "default_value"; - public static final String IS_SECURED = "is_secured"; - public static final String IS_INCLUDE = "is_include"; - - public static final String PARAMETER_TYPE_JSON = "json"; - public static final String PARAMETER_TYPE_YAML = "yaml"; - public static final String PARAMETER_TYPE_STRING = "string"; - public static final String PARAMETER_TYPE_LONG = "long"; - public static final String PARAMETER_TYPE_URL = "url"; - public static final String PARAMETER_TYPE_BOOL = "bool"; - public static final String PARAMETER_TYPE_ARRAY = "array"; - public static final String PARAMETER_TYPE_BINARY = "binary"; - public static final String PARAMETER_TYPE_MAP = "map"; - - public static final String DEFAULT_PARAMETER_FILE_NAME = "default_input_parameters.yaml"; - public static final String DEFAULT_PARAMETER_HTTP_FILE_NAME = "default_input_parameters_http.yaml"; - - public static final String DEAFULT_PARAMETER_USERNAME = "host-username"; - public static final String DEAFULT_PARAMETER_PASSWORD = "host-password"; - public static final String DEAFULT_PARAMETER_HOST_URL = "host-url"; - public static final String DEFAULT_PARAMETER_HELP = "help"; - public static final String DEFAULT_PARAMETER_VERSION = "version"; - public static final String DEFAULT_PARAMETER_DEBUG = "debug"; - public static final String DEFAULT_PARAMETER_OUTPUT_FORMAT = "format"; - public static final String DEFAULT_PARAMETER_OUTPUT_ATTR_LONG = "long"; - public static final String DEFAULT_PARAMETER_OUTPUT_NO_TITLE = "no-title"; - public static final String DEFAULT_PARAMETER_NO_AUTH = "no-auth"; - - //results - public static final String RESULTS = "results"; - - public static final String DIRECTION = "direction"; - public static final String DIRECTION_PORTRAIT = "portrait"; - public static final String DIRECTION_LANDSCAPE = "landscape"; - - public static final String ATTRIBUTES = "attributes"; - - public static final String SCOPE = "scope"; - public static final String RESULT_SCOPE_SHORT = "short"; - public static final String RESULT_SCOPE_LONG = "long"; - - //print - public static final String PORTRAINT_COLUMN_NAME_PROPERTY = "property"; - public static final String PORTRAINT_COLUMN_NAME_VALUE = "value"; - - public static final String SCHEMA_DIRECTORY = "open-cli-schema"; - public static final String YAML_PATTERN = "/**/*.yaml"; - public static final String JSON_PATTERN = "/**/*.json"; - public static final String SCHEMA_PATH_PATERN = SCHEMA_DIRECTORY + YAML_PATTERN; - 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 DISCOVER_ALWAYS = "discover_always"; - public static final String PARAM_CACHE_FILE_NAME = "global-profile"; - - //normal - public static final String BASIC_SCHEMA_PROFILE = "basic"; - public static final String HTTP_SCHEMA_PROFILE = "http"; - - //http - public static final String HTTP = "http"; - - public static final String SERVICE = "service"; - public static final String VERSION = "version"; - public static final String BASE_PATH = "base_path"; - public static final String AUTH = "auth"; - public static final String AUTH_NONE = "none"; - public static final String AUTH_BASIC = "basic"; - public static final String MODE = "mode"; - public static final String MODE_DIRECT = "direct"; - public static final String MODE_CATALOG = "catalog"; - - public static final String REQUEST = "request"; - public static final String URI = "uri"; - public static final String BODY = "body"; - - public static final String METHOD_TYPE = "method"; - public static final String POST = "post"; - public static final String GET = "get"; - public static final String DELETE = "delete"; - public static final String PUT = "put"; - public static final String HEAD = "delete"; - - public static final String HEADERS = "headers"; - public static final String QUERIES = "queries"; - public static final String COOKIES = "cookies"; - - public static final String SUCCESS_CODES = "success_codes"; - - public static final String RESULT_MAP = "result_map"; - - public static final String SAMPLE_RESPONSE = "sample_response"; - - //swagger - public static final String EXECUTOR = "exec"; - - public static final String API = "api"; - public static final String CLIENT = "client"; - public static final String ENTITY = "entity"; - public static final String METHOD = "method"; - public static final String MULTIPART_ENTITY_NAME = "multipart_entity_name"; - public static final String EXCEPTION = "exception"; - public static final String BOOLEAN_TRUE = "true"; - public static final String BOOLEAN_FALSE = "false"; - - // Error message - public static final String SCHEMA_INVALID_DEFAULT_PARAMS_SECTION = "Invalid default_parameter section"; - public static final String SCHEMA_FILE_EMPTY = "The schema file cann't be null or empty"; - public static final String SCHEMA_FILE_WRONG_EXTN = "Schema file should be '.yaml' extension"; - public static final String SCHEMA_FILE_NOT_EXIST = "Schema file doesn't exist"; - public static final String HTTP_SECTION_EMPTY = "Http Section cann't be null or empty"; - public static final String HTTP_BODY_SECTION_EMPTY = "http body section under 'request:' cann't be null or empty"; - public static final String HTTP_BODY_FAILED_PARSING = "The http body json is failed to parse"; - public static final String HTTP_BODY_JSON_EMPTY = "The http body json cann't be null or empty"; - public static final String HTTP_SUCCESS_CODE_INVALID = "Invalid http success code."; - public static final String HTTP_SAMPLE_RESPONSE_EMPTY = "Sample response cann't be null or empty"; - public static final String HTTP_SAMPLE_RESPONSE_FAILED_PARSING = "The http Sample response json is failed to parse."; - public static final String USE_DIRECTIVE = "use"; - - - 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 SPL_ENTRY_UUID = "uuid"; - public static final String SPL_ENTRY_ENV = "env:"; - - //auth plugin - public static final String AUTH_SERVICE_AUTHORIZATION = "Authorization"; - - //catalog plugin - public static final String CATALOG_SERVICE_NAME = "catalog-service-name"; - public static final String CATALOG_SERVICE_VERSION = "catalog-service-version"; - 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 VERSION_INFO = "version.info"; - public static final String VERSION_INFO_PLACE_HOLDER_VERSION = "__VERSION__"; - public static final String VERSION_INFO_PLACE_HOLDER_AVL_PRD_VER = "__AVAILABLE_PRODUCT_VERSIONS__"; - public static final String VERSION_INFO_PLACE_HOLDER_ENB_PRD_VER = "__ENABLED_PRODUCT_VERSIONS__"; - - private Constants() { - } - -} - - diff --git a/framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConfg.java b/framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConfg.java deleted file mode 100644 index 19e7b48b..00000000 --- a/framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConfg.java +++ /dev/null @@ -1,139 +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.fw.conf; - -import java.io.IOException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.UUID; -import java.util.stream.Collectors; - -/** - * Oclip command constants. - * - */ -public final class OnapCommandConfg { - - private static Properties prps = new Properties(); - - /** - * Private constructor. - */ - private OnapCommandConfg() { - - } - - static { - try { - prps.load(OnapCommandConfg.class.getClassLoader().getResourceAsStream(Constants.CONF)); - } catch (IOException e) { - throw new RuntimeException(e); // NOSONAR - } - } - - /** - * is auth service ignored. - * - * @return boolean - */ - public static boolean isAuthIgnored() { - if ("true".equals(prps.getProperty(Constants.OPEN_IGNORE_AUTH))) { - return true; - } - - return false; - } - - /** - * is discovery should do every time. - * - * @return boolean - */ - public static boolean isDiscoverAlways() { - if ("true".equals(prps.getProperty(Constants.DISCOVER_ALWAYS))) { - return true; - } - - return false; - } - - public static String getVersion() { - return prps.getProperty(Constants.OPEN_CLI_VERSION); - } - - public static String getEnabledProductVersion() { - String version = System.getenv(Constants.OPEN_OPEN_CLI_PRODUCT_IN_USE_ENV_NAME); - if (version == null) { - version = prps.getProperty(Constants.OPEN_CLI_PRODUCT_NAME); - } - return version; - } - - /** - * checks if cookies based auth. - * - * @return boolean - */ - public static boolean isCookiesBasedAuth() { - if ("true".equals(prps.getProperty(Constants.HTTP_API_KEY_USE_COOKIES))) { - return true; - } - - return false; - } - - public static String getProductName() { - return prps.getProperty(Constants.OPEN_CLI_PRODUCT_NAME); - } - - private static Map getHeaderValues(String headerKey, Map paramMap) { - Map mapHeaders = new HashMap (); - if (prps.containsKey(headerKey)) { - Arrays.stream(prps.getProperty(headerKey) // NOSONAR - .split(",")).map(String::trim).forEach(header -> { - String headerName = prps.getProperty(headerKey+ "." + header); - String headerValue = prps.getProperty(headerKey + "." + header + ".value", null); - if (headerValue != null) { - headerValue = headerValue.replaceAll("uuid", UUID.randomUUID().toString()); - if (headerValue.contains("${")) { - String param = headerValue.substring(headerValue.indexOf("${")+2 ,headerValue.indexOf("}")); - String pattern = "${"+param+"}"; - headerValue = headerValue.replace(pattern, paramMap.getOrDefault(param, param)); - } - } - mapHeaders.put(headerName, headerValue); - }); - } - return mapHeaders; - } - - //mrkanag move this utils class - public static List getSchemaAttrInfo(String key) { - return Arrays.stream(prps.getProperty(key).split(",")).map(String::trim).collect(Collectors.toList()); // NOSONAR - } - - public static String getSampleGenerateTargetFolder() { - return prps.getProperty(Constants.SAMPLE_GEN_TARGET_FOLDER, "."); - } - - public static boolean isSampleGenerateEnabled() { - return "true".equals(prps.getProperty(Constants.SAMPLE_GEN_ENABLED)); - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConfig.java b/framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConfig.java new file mode 100644 index 00000000..079a4410 --- /dev/null +++ b/framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConfig.java @@ -0,0 +1,71 @@ +/* + * 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.conf; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; +import java.util.stream.Collectors; + +/** + * Oclip command constants. + * + */ +public final class OnapCommandConfig { + + private static Properties prps = new Properties(); + + /** + * Private constructor. + */ + private OnapCommandConfig() { + + } + + static { + loadProperties(prps, OnapCommandConstants.CONF); + for (String prpFile: getCommaSeparatedList(OnapCommandConstants.OPEN_CLI_PLUGIN_PRPS)) { + addProperties(prpFile); + } + } + + private static void loadProperties(Properties prps, String fileName) { + try { + prps.load(OnapCommandConfig.class.getClassLoader().getResourceAsStream(fileName)); + } catch (Exception e) { // NOSONAR + throw new RuntimeException(e); // NOSONAR + } + } + + private static void addProperties(String fileName) { + Properties ps = new Properties(); + loadProperties(ps, fileName); + + for (Object key: ps.keySet()) { + prps.put(key, ps.get(key)); + } + } + + public static String getPropertyValue(String propertyName) { + return prps.getProperty(propertyName); + } + + public static List getCommaSeparatedList(String key) { + return Arrays.stream(getPropertyValue(key).split(",")).map(String::trim).collect(Collectors.toList()); // NOSONAR + } +} 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 new file mode 100644 index 00000000..6f911c29 --- /dev/null +++ b/framework/src/main/java/org/onap/cli/fw/conf/OnapCommandConstants.java @@ -0,0 +1,147 @@ +/* + * 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.conf; + +/** + * OnapCommandHttpConstants. + * + */ +public class OnapCommandConstants { + + //config + public static final String CONF = "open-cli.properties"; + public static final String OPEN_CLI_VERSION = "cli.version"; + public static final String TOP_LEVEL_PARAMS_LIST = "cli.schema.top_level_params_list"; + public static final String TOP_LEVEL_MANDATORY_LIST = "cli.schema.top_level_mandatory_list"; + 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 INFO_PARAMS_LIST = "cli.schema.info_params_list"; + public static final String INFO_PARAMS_MANDATORY_LIST = "cli.schema.info_params_mandatory_list"; + public static final String INPUT_PARAMS_LIST = "cli.schema.input_params_list"; + public static final String INPUT_PARAMS_MANDATORY_LIST = "cli.schema.input_params_mandatory_list"; + public static final String RESULT_PARAMS_LIST = "cli.schema.result_params_list"; + public static final String RESULT_PARAMS_MANDATORY_LIST = "cli.schema.result_params_mandatory_list"; + public static final String BOOLEAN_VALUE = "cli.schema.boolean_values"; + + public static final String COMMAND_TYPE_VALUES = "cli.command.type"; + public static final String SCHEMA_TYPES_SUPPORTED = "cli.schema.type.supported"; + public static final String OPEN_CLI_PRODUCT_NAME = "cli.product_name"; + public static final String OPEN_CLI_PLUGIN_PRPS = "cli.plugins-prps"; + + //schema + public static final String OPEN_CLI_SCHEMA_VERSION = "open_cli_schema_version"; + public static final String OPEN_CLI_SCHEMA_VERSION_VALUE_1_0 = "1.0"; + public static final String NAME = "name"; + public static final String DESCRIPTION = "description"; + + //Info + public static final String INFO = "info"; + public static final String INFO_PRODUCT = "product"; + public static final String OPEN_CLI_PRODUCT_IN_USE_ENV_NAME = "OPEN_CLI_PRODUCT_IN_USE"; + + public static final String INFO_SERVICE = "service"; + public static final String INFO_TYPE = "type"; + public static final String INFO_AUTHOR = "author"; + public static final String INFO_IGNORE = "ignore"; + + //parameters + public static final String PARAMETERS = "parameters"; + public static final String SHORT_OPTION = "short_option"; + public static final String LONG_OPTION = "long_option"; + public static final String TYPE = "type"; + public static final String IS_OPTIONAL = "is_optional"; + public static final String DEFAULT_VALUE = "default_value"; + public static final String IS_SECURED = "is_secured"; + public static final String IS_INCLUDE = "is_include"; + + public static final String PARAMETER_TYPE_JSON = "json"; + public static final String PARAMETER_TYPE_YAML = "yaml"; + public static final String PARAMETER_TYPE_STRING = "string"; + public static final String PARAMETER_TYPE_LONG = "long"; + public static final String PARAMETER_TYPE_URL = "url"; + public static final String PARAMETER_TYPE_BOOL = "bool"; + public static final String PARAMETER_TYPE_ARRAY = "array"; + public static final String PARAMETER_TYPE_BINARY = "binary"; + public static final String PARAMETER_TYPE_MAP = "map"; + + public static final String DEFAULT_PARAMETER_FILE_NAME = "default_input_parameters.yaml"; + public static final String DEFAULT_PARAMETER_HELP = "help"; + public static final String DEFAULT_PARAMETER_VERSION = "version"; + public static final String DEFAULT_PARAMETER_DEBUG = "debug"; + public static final String DEFAULT_PARAMETER_OUTPUT_FORMAT = "format"; + public static final String DEFAULT_PARAMETER_OUTPUT_ATTR_LONG = "long"; + public static final String DEFAULT_PARAMETER_OUTPUT_NO_TITLE = "no-title"; + + //results + public static final String RESULTS = "results"; + + public static final String DIRECTION = "direction"; + public static final String DIRECTION_PORTRAIT = "portrait"; + public static final String DIRECTION_LANDSCAPE = "landscape"; + + public static final String ATTRIBUTES = "attributes"; + + public static final String SCOPE = "scope"; + public static final String RESULT_SCOPE_SHORT = "short"; + public static final String RESULT_SCOPE_LONG = "long"; + + //print + public static final String PORTRAINT_COLUMN_NAME_PROPERTY = "property"; + public static final String PORTRAINT_COLUMN_NAME_VALUE = "value"; + + //discovery + public static final String SCHEMA_DIRECTORY = "open-cli-schema"; + public static final String YAML_PATTERN = "/**/*.yaml"; + public static final String JSON_PATTERN = "/**/*.json"; + public static final String SCHEMA_PATH_PATERN = SCHEMA_DIRECTORY + YAML_PATTERN; + 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 DISCOVER_ALWAYS = "discover_always"; + public static final String PARAM_CACHE_FILE_NAME = "global-profile"; + + //normal + public static final String BASIC_SCHEMA_PROFILE = "basic"; + public static final String EXCEPTION = "exception"; + public static final String BOOLEAN_TRUE = "true"; + public static final String BOOLEAN_FALSE = "false"; + + // Error message + public static final String SCHEMA_INVALID_DEFAULT_PARAMS_SECTION = "Invalid default_parameter section"; + public static final String SCHEMA_FILE_EMPTY = "The schema file cann't be null or empty"; + public static final String SCHEMA_FILE_WRONG_EXTN = "Schema file should be '.yaml' extension"; + public static final String SCHEMA_FILE_NOT_EXIST = "Schema file doesn't exist"; + public static final String USE_DIRECTIVE = "use"; + + + public static final String SPL_ENTRY_UUID = "uuid"; + public static final String SPL_ENTRY_ENV = "env:"; + + public static final String VERSION_INFO = "version.info"; + public static final String VERSION_INFO_PLACE_HOLDER_VERSION = "__VERSION__"; + public static final String VERSION_INFO_PLACE_HOLDER_AVL_PRD_VER = "__AVAILABLE_PRODUCT_VERSIONS__"; + public static final String VERSION_INFO_PLACE_HOLDER_ENB_PRD_VER = "__ENABLED_PRODUCT_VERSIONS__"; + + public static final String SAMPLE_GEN_ENABLED = "cli.sample.gen.enable"; + public static final String SAMPLE_GEN_TARGET_FOLDER = "cli.sample.gen.target"; + + private OnapCommandConstants() { + } + +} + + diff --git a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandFailedMocoGenerate.java b/framework/src/main/java/org/onap/cli/fw/error/OnapCommandFailedMocoGenerate.java deleted file mode 100644 index 37e8fb35..00000000 --- a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandFailedMocoGenerate.java +++ /dev/null @@ -1,39 +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.fw.error; - -/** - * Invalid data for generating moco json . - * - */ -public class OnapCommandFailedMocoGenerate extends OnapCommandException { - - private static final long serialVersionUID = -5386652726982792831L; - - private static final String ERROR_CODE = "0xf002"; - - private static final String ERROR_MSG = "Failed to generate moco json "; - - public OnapCommandFailedMocoGenerate(String cmdName, String error) { - super(ERROR_CODE, ERROR_MSG + cmdName + ", " + error); - } - - public OnapCommandFailedMocoGenerate(String cmdName, Throwable throwable) { - super(ERROR_CODE, ERROR_MSG + cmdName , throwable); - } - -} \ No newline at end of file diff --git a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpFailure.java b/framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpFailure.java deleted file mode 100644 index bec8dd0b..00000000 --- a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpFailure.java +++ /dev/null @@ -1,44 +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.fw.error; - -/** - * Command execution failed. - * - */ -public class OnapCommandHttpFailure extends OnapCommandException { - private static final long serialVersionUID = 488775545436993345L; - - private static final String ERROR_CODE = "0x3001"; - - public OnapCommandHttpFailure(String error, long httpStatus) { - super(ERROR_CODE, error, httpStatus); - } - - public OnapCommandHttpFailure(String error) { - super(ERROR_CODE, error); - } - - public OnapCommandHttpFailure(Throwable throwable) { - super(ERROR_CODE, throwable); - } - - public OnapCommandHttpFailure(Throwable throwable, long httpStatus) { - super(ERROR_CODE, throwable, httpStatus); - } - -} diff --git a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpHeaderNotFound.java b/framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpHeaderNotFound.java deleted file mode 100644 index 58fcdfd9..00000000 --- a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpHeaderNotFound.java +++ /dev/null @@ -1,30 +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.fw.error; - -/** - * OnapCommandParameterNotFound. - * - */ -public class OnapCommandHttpHeaderNotFound extends OnapCommandException { - - private static final long serialVersionUID = 6676137916079057963L; - - public OnapCommandHttpHeaderNotFound(String name) { - super("0x3003", "Http header " + name + " is not returned from the service"); - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpInvalidResponseBody.java b/framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpInvalidResponseBody.java deleted file mode 100644 index 3e98d07d..00000000 --- a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpInvalidResponseBody.java +++ /dev/null @@ -1,37 +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.fw.error; - -/** - * OnapCommandParameterNotFound. - * - */ -public class OnapCommandHttpInvalidResponseBody extends OnapCommandException { - - private static final long serialVersionUID = 6676137916079057963L; - - private static final String ERROR_CODE = "0x3004"; - private static final String ERR_MSG = "Http response body does not have json entry "; - - public OnapCommandHttpInvalidResponseBody(String name, String error) { - super(ERROR_CODE, ERR_MSG + name + ", " + error); - } - - public OnapCommandHttpInvalidResponseBody(String name, Throwable throwable) { - super(ERROR_CODE, ERR_MSG + name, throwable); - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpInvalidResultMap.java b/framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpInvalidResultMap.java deleted file mode 100644 index 9303c6b2..00000000 --- a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandHttpInvalidResultMap.java +++ /dev/null @@ -1,32 +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.fw.error; - -import java.util.List; - -/** - * Invalid result map in HTTP section. - * - */ -public class OnapCommandHttpInvalidResultMap extends OnapCommandException { - - private static final long serialVersionUID = 6676137916023457963L; - - public OnapCommandHttpInvalidResultMap(List invalidParams) { - super("0x3005", "Invalide result map parameters : " + invalidParams.toString()); - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandInvalidRegistration.java b/framework/src/main/java/org/onap/cli/fw/error/OnapCommandInvalidRegistration.java index db4c8e6a..1c90e9a0 100644 --- a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandInvalidRegistration.java +++ b/framework/src/main/java/org/onap/cli/fw/error/OnapCommandInvalidRegistration.java @@ -16,7 +16,7 @@ package org.onap.cli.fw.error; -import org.onap.cli.fw.OnapCommand; +import org.onap.cli.fw.cmd.OnapCommand; /** * Command class invalid. diff --git a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandLoginFailed.java b/framework/src/main/java/org/onap/cli/fw/error/OnapCommandLoginFailed.java deleted file mode 100644 index e9c82259..00000000 --- a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandLoginFailed.java +++ /dev/null @@ -1,41 +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.fw.error; - -/** - * Login failed. - * - */ -public class OnapCommandLoginFailed extends OnapCommandException { - - private static final long serialVersionUID = 5518154493762956959L; - - private static final String ERROR_CODE = "0x4001"; - private static final String ERROR_MESSAGE1 = "Login failed"; - - public OnapCommandLoginFailed(String error) { - super(ERROR_CODE, ERROR_MESSAGE1 + ", " + error); - } - - public OnapCommandLoginFailed(String error, int httpStatus) { - super(ERROR_CODE, ERROR_MESSAGE1 + ", " + error, httpStatus); - } - - public OnapCommandLoginFailed(Throwable throwable) { - super(ERROR_CODE, ERROR_MESSAGE1, throwable); - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandLogoutFailed.java b/framework/src/main/java/org/onap/cli/fw/error/OnapCommandLogoutFailed.java deleted file mode 100644 index df879021..00000000 --- a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandLogoutFailed.java +++ /dev/null @@ -1,40 +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.fw.error; - -/** - * Logout failed. - * - */ -public class OnapCommandLogoutFailed extends OnapCommandException { - - private static final long serialVersionUID = 1150649507734289032L; - private static final String ERROR_CODE = "0x4002"; - private static final String ERROR_MESSAGE1 = "Logout failed"; - - public OnapCommandLogoutFailed(String error) { - super(ERROR_CODE, ERROR_MESSAGE1 +", " + error); - } - - public OnapCommandLogoutFailed(Throwable throwable) { - super(ERROR_CODE, ERROR_MESSAGE1, throwable); - } - - public OnapCommandLogoutFailed(int statusCode) { - super(ERROR_CODE, ERROR_MESSAGE1, statusCode); - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandServiceNotFound.java b/framework/src/main/java/org/onap/cli/fw/error/OnapCommandServiceNotFound.java deleted file mode 100644 index 9cc0e45f..00000000 --- a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandServiceNotFound.java +++ /dev/null @@ -1,30 +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.fw.error; - -/** - * Command not registered in MSB. - * - */ -public class OnapCommandServiceNotFound extends OnapCommandException { - - private static final long serialVersionUID = 8580121615330415065L; - - public OnapCommandServiceNotFound(String service) { - super("0xd001", "Service " + service + " is not found in MSB"); - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/http/HttpInput.java b/framework/src/main/java/org/onap/cli/fw/http/HttpInput.java deleted file mode 100644 index 69439bd4..00000000 --- a/framework/src/main/java/org/onap/cli/fw/http/HttpInput.java +++ /dev/null @@ -1,139 +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.fw.http; - -import java.util.HashMap; -import java.util.Map; - -/** - * Captures HTTP request URI, body and request &query parameters.
- */ -public class HttpInput { - - private String reqUri = ""; - - private String reqBody = ""; - - private String reqMethod = ""; - - private String multipartEntityName = ""; - - private Map reqHeaders = new HashMap<>(); - - private Map reqQueries = new HashMap<>(); - - private Map reqCookies = new HashMap<>(); - - private boolean binaryData; - - public String getUri() { - return this.reqUri; - } - - public HttpInput setUri(String uri) { - this.reqUri = uri; - return this; - } - - public String getBody() { - return this.reqBody; - } - - public HttpInput setBody(String body) { - this.reqBody = body; - return this; - } - - public Map getReqHeaders() { - return this.reqHeaders; - } - - /** - * header parameter setter. - * - * @param reqHeaders - * header map - * @return HttpInput - */ - public HttpInput setReqHeaders(Map reqHeaders) { - if (reqHeaders != null) { - this.reqHeaders = reqHeaders; - } - return this; - } - - public String getMethod() { - return this.reqMethod; - } - - public HttpInput setMethod(String method) { - this.reqMethod = method; - return this; - } - - public String getMultipartEntityName() { - return this.multipartEntityName; - } - - public HttpInput setMultipartEntityName(String multipartEntityName) { - this.multipartEntityName = multipartEntityName; - return this; - } - - public Map getReqQueries() { - return reqQueries; - } - - /** - * Request query parameters. - * - * @param reqQueries - * request queries - * @return HttpInput - */ - public HttpInput setReqQueries(Map reqQueries) { - if (reqQueries != null) { - this.reqQueries = reqQueries; - } - return this; - } - - public Map getReqCookies() { - return reqCookies; - } - - public HttpInput setReqCookies(Map reqCookies) { - this.reqCookies = reqCookies; - return this; - } - - public boolean isBinaryData() { - return binaryData; - } - - public void setBinaryData(boolean binaryData) { - this.binaryData = binaryData; - } - - @Override - public String toString() { - 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; - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/http/HttpResult.java b/framework/src/main/java/org/onap/cli/fw/http/HttpResult.java deleted file mode 100644 index e000ee15..00000000 --- a/framework/src/main/java/org/onap/cli/fw/http/HttpResult.java +++ /dev/null @@ -1,77 +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.fw.http; - -import java.util.HashMap; -import java.util.Map; - -/** - * Captures HTTP response status, body and headers.
- * - */ -public class HttpResult { - - private int status; - - private String resBody; - - private Map respHeaders = new HashMap<>(); - - private Map respCookies = new HashMap<>(); - - public int getStatus() { - return this.status; - } - - public void setStatus(int status) { - this.status = status; - } - - public String getBody() { - return this.resBody; - } - - public void setBody(String body) { - this.resBody = body; - } - - public void setRespHeaders(Map respHeaders) { - this.respHeaders = respHeaders; - } - - public Map getRespHeaders() { - return this.respHeaders; - } - - public Map getRespCookies() { - return respCookies; - } - - public void setRespCookies(Map respCookies) { - this.respCookies = respCookies; - } - - public boolean isSuccess() { - return this.getStatus() >= 200 && this.getStatus() <= 300; - } - - @Override - public String toString() { - return "\nHTTP Status: " + this.getStatus() + "\nResponse Body: " + this.getBody() + "\nResponse Headers: " - + this.getRespHeaders() + "\nResponse Cookies: " + this.getRespCookies(); - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/http/OnapHttpConnection.java b/framework/src/main/java/org/onap/cli/fw/http/OnapHttpConnection.java deleted file mode 100644 index 6fdf7046..00000000 --- a/framework/src/main/java/org/onap/cli/fw/http/OnapHttpConnection.java +++ /dev/null @@ -1,349 +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.fw.http; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.security.cert.X509Certificate; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.ParseException; -import org.apache.http.client.CookieStore; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.protocol.ClientContext; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.ssl.AllowAllHostnameVerifier; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.X509HostnameVerifier; -import org.apache.http.cookie.Cookie; -import org.apache.http.entity.StringEntity; -import org.apache.http.entity.mime.MultipartEntity; -import org.apache.http.entity.mime.content.FileBody; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.client.LaxRedirectStrategy; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.impl.cookie.BasicClientCookie; -import org.apache.http.protocol.BasicHttpContext; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.EntityUtils; -import org.onap.cli.fw.conf.Constants; -import org.onap.cli.fw.error.OnapCommandHttpFailure; - -/** - * Helps to make http connection.
- */ -public class OnapHttpConnection { - - private HttpClient httpClient = null; - - Map mapCommonHeaders = new HashMap (); - - protected boolean debug = false; - - private String debugDetails = ""; - - public static class TrustAllX509TrustManager implements X509TrustManager { - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { - // No need to implement. - } - - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { - // No need to implement. - } - } - - /** - * OnapHttpConnection Constructor. - * - * @param debug - * boolean - * @throws OnapCommandHttpFailure - * exception - */ - public OnapHttpConnection(boolean debug) throws OnapCommandHttpFailure { - this.debug = debug; - } - - private void initHttpClient(boolean isSecured) throws OnapCommandHttpFailure { - if (this.httpClient == null) { - try { - if (isSecured) { - SSLContext sslContext = SSLContext.getInstance(Constants.SSLCONTEST_TLS); - sslContext.init(null, new TrustManager[] { new TrustAllX509TrustManager() }, - new java.security.SecureRandom()); - X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier(); - Registry socketFactoryRegistry = RegistryBuilder - .create() - .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build(); - HttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); - - this.httpClient = HttpClients.custom().setConnectionManager(connManager) - .setRedirectStrategy(new LaxRedirectStrategy()).build(); - } else { - this.httpClient = HttpClients.createDefault(); - } - } catch (Exception e) { - throw new OnapCommandHttpFailure(e); - } - } - } - - public String getDebugInfo() { - return this.debugDetails; - } - - private Map getHttpHeaders(HttpResponse resp) { - Map result = new HashMap<>(); - - Header[] hs = resp.getAllHeaders(); - for (int i = 0; i < hs.length; i++) { - result.put(hs[i].getName(), hs[i].getValue()); - } - - return result; - } - - private String getResponseBody(HttpResponse resp) throws OnapCommandHttpFailure { - if (resp.getEntity() == null) { - return null; - } - try { - String body = EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8); - EntityUtils.consume(resp.getEntity()); - return body; - } catch (IOException e) { - throw new OnapCommandHttpFailure(e); - } - } - - private StringEntity getStringEntity(HttpInput input) { - return new StringEntity(input.getBody(), StandardCharsets.UTF_8); - } - - /** - * Post.
- * - * @param input - * HttpInput Obj - * @return HttpResult - * @throws OnapCommandHttpFailure - * http failure - */ - public HttpResult post(final HttpInput input) throws OnapCommandHttpFailure { - input.setMethod("post"); - return this.request(input); - } - - /** - * Get.
- * - * @param input - * input request - * @return HttpResult - * @throws OnapCommandHttpFailure - * excpetion - */ - public HttpResult get(final HttpInput input) throws OnapCommandHttpFailure { - input.setMethod("get"); - return this.request(input); - } - - /** - * Put.
- * - * @param input - * input request - * @return HttpResult - * @throws OnapCommandHttpFailure - * Exception - */ - public HttpResult put(final HttpInput input) throws OnapCommandHttpFailure { - input.setMethod("put"); - return this.request(input); - } - - /** - * Delete.
- * - * @param input - * input request - * @return HttpResult - * @throws OnapCommandHttpFailure - * exception - */ - public HttpResult delete(final HttpInput input) throws OnapCommandHttpFailure { - input.setMethod("delete"); - return this.request(input); - } - - public void setCommonHeaders(Map headers) { - this.mapCommonHeaders = headers; - } - - private void addCommonHeaders(HttpInput input) { - if (!input.isBinaryData()) { - input.getReqHeaders().put("Content-Type", Constants.APPLICATION_JSON); - } - input.getReqHeaders().put("Accept", Constants.APPLICATION_JSON); - - for (String headerName : this.mapCommonHeaders.keySet()) { - input.getReqHeaders().put(headerName, this.mapCommonHeaders.get(headerName)); - } - } - - private void addCommonCookies(CookieStore cookieStore) { - for (String headerName : this.mapCommonHeaders.keySet()) { - Cookie cookie = new BasicClientCookie(headerName, this.mapCommonHeaders.get(headerName)); - cookieStore.addCookie(cookie); - } - } - - private void updateResultFromCookies(HttpResult result, List cookies) { - for (Cookie cookie : cookies) { - result.getRespCookies().put(cookie.getName(), cookie.getValue()); - } - } - - private String getDomain(String url) { - try { - return new URL(url).getHost(); - } catch (MalformedURLException e) { - // url is always proper !! - return url; - } - } - - private void updateInputFromCookies(HttpInput input, CookieStore cookieStore) { - addCommonCookies(cookieStore); - for (String cookieName : input.getReqCookies().keySet()) { - BasicClientCookie cookie = new BasicClientCookie(cookieName, input.getReqCookies().get(cookieName)); - cookie.setDomain(this.getDomain(input.getUri())); - cookieStore.addCookie(cookie); - } - - } - - /** - * Handles http method requests. - * - * @param input - * HttpInput - * @return HttpResult - * @throws OnapCommandHttpFailure - * exception - */ - public HttpResult request(HttpInput input) throws OnapCommandHttpFailure { - this.addCommonHeaders(input); - - HttpRequestBase requestBase = null; - if ("post".equals(input.getMethod())) { - HttpPost httpPost = new HttpPost(); - if (input.isBinaryData()) { - httpPost.setEntity(getMultipartEntity(input)); - } else { - httpPost.setEntity(this.getStringEntity(input)); - } - requestBase = httpPost; - } else if ("put".equals(input.getMethod())) { - HttpPut httpPut = new HttpPut(); - httpPut.setEntity(this.getStringEntity(input)); - requestBase = httpPut; - } else if ("get".equals(input.getMethod())) { - requestBase = new HttpGet(); - } else if ("delete".equals(input.getMethod())) { - requestBase = new HttpDelete(); - } else { - throw new IllegalArgumentException("Invalid HTTP method"); - } - - requestBase.setURI(URI.create(input.getUri())); - - for (Entry h : input.getReqHeaders().entrySet()) { - requestBase.addHeader(h.getKey(), h.getValue()); - } - - HttpResult result = new HttpResult(); - - try { - this.debugDetails = ""; - CookieStore cookieStore = new BasicCookieStore(); - updateInputFromCookies(input, cookieStore); - HttpContext localContext = new BasicHttpContext(); - localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); - - this.initHttpClient(input.getUri().startsWith("https")); - - HttpResponse resp = this.httpClient.execute(requestBase, localContext); - String respContent = this.getResponseBody(resp); - result.setBody(respContent); - result.setStatus(resp.getStatusLine().getStatusCode()); - result.setRespHeaders(this.getHttpHeaders(resp)); - this.updateResultFromCookies(result, cookieStore.getCookies()); - } catch (ParseException | IOException e) { - throw new OnapCommandHttpFailure(e); - } finally { - if (this.debug) { - this.debugDetails = input + "" + result; - } - } - - return result; - } - - public void close() { - this.mapCommonHeaders.clear(); - } - - private HttpEntity getMultipartEntity(HttpInput input) { - FileBody fileBody = new FileBody(new File(input.getBody().trim())); - MultipartEntity multipartEntity = new MultipartEntity(); - String fileName = input.getMultipartEntityName() != "" ? input.getMultipartEntityName() : "upload"; - multipartEntity.addPart(fileName, fileBody); - return multipartEntity; - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/info/OnapCommandInfo.java b/framework/src/main/java/org/onap/cli/fw/info/OnapCommandInfo.java index c52965f9..1496bcbb 100644 --- a/framework/src/main/java/org/onap/cli/fw/info/OnapCommandInfo.java +++ b/framework/src/main/java/org/onap/cli/fw/info/OnapCommandInfo.java @@ -16,7 +16,7 @@ package org.onap.cli.fw.info; -import org.onap.cli.fw.cmd.CommandType; +import org.onap.cli.fw.cmd.OnapCommandType; /** * Oclip Command info like product version, service, contact, etc. @@ -29,7 +29,7 @@ public class OnapCommandInfo { private String author; - private CommandType type = CommandType.CMD; + private OnapCommandType type = OnapCommandType.CMD; private boolean ignore = false; @@ -57,11 +57,11 @@ public class OnapCommandInfo { this.author = email; } - public CommandType getCommandType() { + public OnapCommandType getCommandType() { return type; } - public void setCommandType(CommandType type) { + public void setCommandType(OnapCommandType type) { this.type = type; } 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 ac2e8521..4b21ed4f 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 @@ -58,7 +58,7 @@ public class OnapCommandParameter { /* * Parameter type such as int, json, yaml, string, etc */ - private ParameterType parameterType; + private OnapCommandParameterType parameterType; /* * Default value @@ -130,18 +130,18 @@ public class OnapCommandParameter { this.longOption = longOption; } - public ParameterType getParameterType() { + public OnapCommandParameterType getParameterType() { return parameterType; } - public void setParameterType(ParameterType parameterType) { + public void setParameterType(OnapCommandParameterType parameterType) { this.parameterType = parameterType; if (this.defaultValue.isEmpty()) { - if (this.getParameterType().equals(ParameterType.BOOL)) { + if (this.getParameterType().equals(OnapCommandParameterType.BOOL)) { // For bool type always the default param is false this.defaultValue = "false"; - } else if (this.getParameterType().equals(ParameterType.UUID)) { + } else if (this.getParameterType().equals(OnapCommandParameterType.UUID)) { this.defaultValue = UUID.randomUUID().toString(); } } @@ -197,10 +197,10 @@ public class OnapCommandParameter { public void setValue(Object value) throws OnapCommandInvalidParameterValue { this.rawValue = value; - if (ParameterType.URL.equals(parameterType) && !value.toString().isEmpty() && !value.toString().startsWith("http") + if (OnapCommandParameterType.URL.equals(parameterType) && !value.toString().isEmpty() && !value.toString().startsWith("http") && !value.toString().startsWith("/")) { this.value = "/" + value; - } else if (ParameterType.ARRAY.equals(parameterType)) { + } else if (OnapCommandParameterType.ARRAY.equals(parameterType)) { if (!(value instanceof List)) { throw new OnapCommandInvalidParameterValue(this.getName()); } @@ -212,7 +212,7 @@ public class OnapCommandParameter { } catch (JsonProcessingException e) { throw new OnapCommandInvalidParameterValue(this.getName(), e); } - } else if (ParameterType.MAP.equals(parameterType)) { + } else if (OnapCommandParameterType.MAP.equals(parameterType)) { if (!(value instanceof Map)) { throw new OnapCommandInvalidParameterValue(this.getName()); } @@ -275,13 +275,50 @@ public class OnapCommandParameter { throw new OnapCommandParameterMissing(this.getName()); } - if (!this.isOptional() && ParameterType.BINARY.equals(parameterType)) { + if (!this.isOptional() && OnapCommandParameterType.BINARY.equals(parameterType)) { File file = new File(value.toString()); if (!file.isFile()) { throw new OnapCommandInvalidParameterValue(this.getName()); } } - // (mrkanag) validate for type supported ParameterType using constraints + // (mrkanag) validate for type supported OnapCommandParameterType using constraints + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((cmdName == null) ? 0 : cmdName.hashCode()); + result = prime * result + ((longOption == null) ? 0 : longOption.hashCode()); + result = prime * result + ((shortOption == null) ? 0 : shortOption.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OnapCommandParameter other = (OnapCommandParameter) obj; + if (cmdName == null) { + if (other.cmdName != null) + return false; + } else if (!cmdName.equals(other.cmdName)) + return false; + if (longOption == null) { + if (other.longOption != null) + return false; + } else if (!longOption.equals(other.longOption)) + return false; + if (shortOption == null) { + if (other.shortOption != null) + return false; + } else if (!shortOption.equals(other.shortOption)) + return false; + return true; } } diff --git a/framework/src/main/java/org/onap/cli/fw/input/OnapCommandParameterType.java b/framework/src/main/java/org/onap/cli/fw/input/OnapCommandParameterType.java new file mode 100644 index 00000000..85ace4a6 --- /dev/null +++ b/framework/src/main/java/org/onap/cli/fw/input/OnapCommandParameterType.java @@ -0,0 +1,75 @@ +/* + * 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; + +import org.onap.cli.fw.error.OnapCommandInvalidParameterType; + +/** + * Parameter type supported by Oclip CLI. + * + */ +public enum OnapCommandParameterType { + /** + * JSON file. + */ + JSON, + /** + * YAML file. + */ + YAML, STRING, TEXT, DIGIT, + /** + * URL location. + */ + URL, BOOL, ARRAY, MAP, BINARY, UUID; + + /** + * Get parameter type. + * + * @param name + * type name + * @return type + * @throws OnapCommandInvalidParameterType + * exception + */ + public static OnapCommandParameterType get(String name) throws OnapCommandInvalidParameterType { + if (JSON.name().equalsIgnoreCase(name)) { + return JSON; + } else if (YAML.name().equalsIgnoreCase(name)) { + return YAML; + } else if (STRING.name().equalsIgnoreCase(name)) { + return STRING; + } else if (DIGIT.name().equalsIgnoreCase(name)) { + return DIGIT; + } else if (URL.name().equalsIgnoreCase(name)) { + return URL; + } else if (BOOL.name().equalsIgnoreCase(name)) { + return BOOL; + } else if (ARRAY.name().equalsIgnoreCase(name)) { + return ARRAY; + } else if (MAP.name().equalsIgnoreCase(name)) { + return MAP; + } else if (BINARY.name().equalsIgnoreCase(name)) { + return BINARY; + } else if (UUID.name().equalsIgnoreCase(name)) { + return UUID; + } else if (TEXT.name().equalsIgnoreCase(name)) { + return TEXT; + } else { + throw new OnapCommandInvalidParameterType(name); + } + } +} diff --git a/framework/src/main/java/org/onap/cli/fw/input/ParameterType.java b/framework/src/main/java/org/onap/cli/fw/input/ParameterType.java deleted file mode 100644 index 6a9254f5..00000000 --- a/framework/src/main/java/org/onap/cli/fw/input/ParameterType.java +++ /dev/null @@ -1,75 +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.fw.input; - -import org.onap.cli.fw.error.OnapCommandInvalidParameterType; - -/** - * Parameter type supported by Oclip CLI. - * - */ -public enum ParameterType { - /** - * JSON file. - */ - JSON, - /** - * YAML file. - */ - YAML, STRING, TEXT, DIGIT, - /** - * URL location. - */ - URL, BOOL, ARRAY, MAP, BINARY, UUID; - - /** - * Get parameter type. - * - * @param name - * type name - * @return type - * @throws OnapCommandInvalidParameterType - * exception - */ - public static ParameterType get(String name) throws OnapCommandInvalidParameterType { - if (JSON.name().equalsIgnoreCase(name)) { - return JSON; - } else if (YAML.name().equalsIgnoreCase(name)) { - return YAML; - } else if (STRING.name().equalsIgnoreCase(name)) { - return STRING; - } else if (DIGIT.name().equalsIgnoreCase(name)) { - return DIGIT; - } else if (URL.name().equalsIgnoreCase(name)) { - return URL; - } else if (BOOL.name().equalsIgnoreCase(name)) { - return BOOL; - } else if (ARRAY.name().equalsIgnoreCase(name)) { - return ARRAY; - } else if (MAP.name().equalsIgnoreCase(name)) { - return MAP; - } else if (BINARY.name().equalsIgnoreCase(name)) { - return BINARY; - } else if (UUID.name().equalsIgnoreCase(name)) { - return UUID; - } else if (TEXT.name().equalsIgnoreCase(name)) { - return TEXT; - } else { - throw new OnapCommandInvalidParameterType(name); - } - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/input/cache/OnapCommandParamEntity.java b/framework/src/main/java/org/onap/cli/fw/input/cache/OnapCommandParamEntity.java new file mode 100644 index 00000000..85473d84 --- /dev/null +++ b/framework/src/main/java/org/onap/cli/fw/input/cache/OnapCommandParamEntity.java @@ -0,0 +1,45 @@ +/* + * 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; + +public class OnapCommandParamEntity { + + private String product; + + private String name; + + private String value; + + public String getProduct() { + return product; + } + public void setProduct(String product) { + this.product = product; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } +} 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 0b70b5c1..55833167 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 @@ -16,15 +16,24 @@ 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 java.io.File; +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 org.onap.cli.fw.conf.Constants; +import org.onap.cli.fw.conf.OnapCommandConstants; import org.onap.cli.fw.error.OnapCommandLoadProfileFailed; import org.onap.cli.fw.error.OnapCommandPersistProfileFailed; -import org.onap.cli.fw.utils.OnapCommandProfileUtils; +import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils; +import org.springframework.core.io.Resource; + +import com.fasterxml.jackson.databind.ObjectMapper; public class OnapCommandParameterCache { @@ -32,7 +41,7 @@ public class OnapCommandParameterCache { private static OnapCommandParameterCache single = null; - private String profileName = Constants.PARAM_CACHE_FILE_NAME; + private String profileName = OnapCommandConstants.PARAM_CACHE_FILE_NAME; private OnapCommandParameterCache() { @@ -78,12 +87,12 @@ public class OnapCommandParameterCache { } private void persist() { - List params = new ArrayList<>(); + List params = new ArrayList<>(); for (String p: this.paramCache.keySet()) { for (String name: this.paramCache.get(p).keySet()) { - Param param = new Param(); + OnapCommandParamEntity param = new OnapCommandParamEntity(); param.setProduct(p); param.setName(name); param.setValue(this.paramCache.get(p).get(name)); @@ -93,21 +102,21 @@ public class OnapCommandParameterCache { } try { - OnapCommandProfileUtils.persistProfile(params, this.profileName); + this.persistProfile(params, this.profileName); } catch (OnapCommandPersistProfileFailed e) { throw new RuntimeException(e); // NOSONAR } } private void load() { - List params= new ArrayList<>(); + List params= new ArrayList<>(); try { - params = OnapCommandProfileUtils.loadParamFromCache(this.profileName); + params = this.loadParamFromCache(this.profileName); } catch (OnapCommandLoadProfileFailed e) { throw new RuntimeException(e); // NOSONAR } - for (Param p : params) { + for (OnapCommandParamEntity p : params) { this.add(p.getProduct(), p.getName(), p.getValue()); } } @@ -116,4 +125,39 @@ public class OnapCommandParameterCache { this.profileName = profileName; this.load(); } + + private void persistProfile(List params, String profileName) throws OnapCommandPersistProfileFailed { + if (params != null) { + try { + 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"); + ObjectMapper mapper = new ObjectMapper(); + mapper.writerWithDefaultPrettyPrinter().writeValue(file, params); + } + } catch (IOException e1) { + throw new OnapCommandPersistProfileFailed(e1); + } + } + } + + private List loadParamFromCache(String profileName) throws OnapCommandLoadProfileFailed { + List params = new ArrayList<>(); + + try { + Resource resource = OnapCommandDiscoveryUtils.findResource(profileName + ".json", + DATA_PATH_JSON_PATTERN); + if (resource != null) { + File file = new File(resource.getURI().getPath()); + ObjectMapper mapper = new ObjectMapper(); + OnapCommandParamEntity[] list = mapper.readValue(file, OnapCommandParamEntity[].class); + params.addAll(Arrays.asList(list)); + } + } catch (IOException e) { + throw new OnapCommandLoadProfileFailed(e); + } + + return params; + } } diff --git a/framework/src/main/java/org/onap/cli/fw/input/cache/Param.java b/framework/src/main/java/org/onap/cli/fw/input/cache/Param.java deleted file mode 100644 index 5a32e886..00000000 --- a/framework/src/main/java/org/onap/cli/fw/input/cache/Param.java +++ /dev/null @@ -1,45 +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.fw.input.cache; - -public class Param { - - private String product; - - private String name; - - private String value; - - public String getProduct() { - return product; - } - public void setProduct(String product) { - this.product = product; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getValue() { - return value; - } - public void setValue(String value) { - this.value = value; - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/output/OnapCommandPrintDirection.java b/framework/src/main/java/org/onap/cli/fw/output/OnapCommandPrintDirection.java new file mode 100644 index 00000000..5a8e6657 --- /dev/null +++ b/framework/src/main/java/org/onap/cli/fw/output/OnapCommandPrintDirection.java @@ -0,0 +1,45 @@ +/* + * 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.output; + +import org.onap.cli.fw.error.OnapCommandInvalidPrintDirection; + +/** + * How to print the result. + * + */ +public enum OnapCommandPrintDirection { + LANDSCAPE, PORTRAIT; + /** + * Get print direction. + * + * @param name + * direction + * @return type + * @throws OnapCommandInvalidPrintDirection + * exception + */ + public static OnapCommandPrintDirection get(String name) throws OnapCommandInvalidPrintDirection { + if (LANDSCAPE.name().equalsIgnoreCase(name)) { + return LANDSCAPE; + } else if (PORTRAIT.name().equalsIgnoreCase(name)) { + return PORTRAIT; + } else { + throw new OnapCommandInvalidPrintDirection(name); + } + } +} diff --git a/framework/src/main/java/org/onap/cli/fw/output/OnapCommandResult.java b/framework/src/main/java/org/onap/cli/fw/output/OnapCommandResult.java index ae5d86ca..4eaab81a 100644 --- a/framework/src/main/java/org/onap/cli/fw/output/OnapCommandResult.java +++ b/framework/src/main/java/org/onap/cli/fw/output/OnapCommandResult.java @@ -21,11 +21,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.onap.cli.fw.conf.Constants; +import org.onap.cli.fw.conf.OnapCommandConstants; import org.onap.cli.fw.error.OnapCommandException; import org.onap.cli.fw.error.OnapCommandOutputFormatNotsupported; import org.onap.cli.fw.error.OnapCommandOutputPrintingFailed; -import org.onap.cli.fw.input.ParameterType; +import org.onap.cli.fw.input.OnapCommandParameterType; import org.onap.cli.fw.output.print.OnapCommandPrint; import org.onap.cli.fw.utils.OnapCommandUtils; @@ -47,7 +47,7 @@ public class OnapCommandResult { /* * Type requested by user */ - private ResultType type = ResultType.TABLE; + private OnapCommandResultType type = OnapCommandResultType.TABLE; /* * Scope requested by user @@ -65,7 +65,7 @@ public class OnapCommandResult { * * loaded from schema file */ - private PrintDirection printDirection = PrintDirection.LANDSCAPE; + private OnapCommandPrintDirection printDirection = OnapCommandPrintDirection.LANDSCAPE; private String debugInfo = ""; @@ -84,11 +84,11 @@ public class OnapCommandResult { */ private boolean isDebug = false; - public PrintDirection getPrintDirection() { + public OnapCommandPrintDirection getPrintDirection() { return printDirection; } - public void setPrintDirection(PrintDirection printDirection) { + public void setPrintDirection(OnapCommandPrintDirection printDirection) { this.printDirection = printDirection; } @@ -123,11 +123,11 @@ public class OnapCommandResult { return recordMap; } - public ResultType getType() { + public OnapCommandResultType getType() { return type; } - public void setType(ResultType type) { + public void setType(OnapCommandResultType type) { this.type = type; } @@ -189,9 +189,9 @@ public class OnapCommandResult { OnapCommandPrint print = new OnapCommandPrint(); print.setPrintTitle(this.isIncludeTitle()); - if (this.getPrintDirection().equals(PrintDirection.LANDSCAPE)) { + if (this.getPrintDirection().equals(OnapCommandPrintDirection.LANDSCAPE)) { for (OnapCommandResultAttribute record : this.getScopedRecords()) { - if (record.getType().equals(ParameterType.JSON)) { + if (record.getType().equals(OnapCommandParameterType.JSON)) { print.addColumn(record.getName(), OnapCommandUtils.jsonFlatten(record.getValues())); } else { print.addColumn(record.getName(), record.getValues()); @@ -200,11 +200,11 @@ public class OnapCommandResult { } else { // Add property column OnapCommandResultAttribute prp = new OnapCommandResultAttribute(); - prp.setName(Constants.PORTRAINT_COLUMN_NAME_PROPERTY); + prp.setName(OnapCommandConstants.PORTRAINT_COLUMN_NAME_PROPERTY); prp.setScope(OnapCommandResultAttributeScope.SHORT); // Add value column OnapCommandResultAttribute val = new OnapCommandResultAttribute(); - val.setName(Constants.PORTRAINT_COLUMN_NAME_VALUE); + val.setName(OnapCommandConstants.PORTRAINT_COLUMN_NAME_VALUE); val.setScope(OnapCommandResultAttributeScope.SHORT); for (OnapCommandResultAttribute record : this.getScopedRecords()) { @@ -224,11 +224,11 @@ public class OnapCommandResult { printOutput = this.getDebugInfo() + "\n"; } - if (this.getType().equals(ResultType.JSON)) { + if (this.getType().equals(OnapCommandResultType.JSON)) { return printOutput + print.printJson(); - } else if (this.getType().equals(ResultType.TABLE)) { + } else if (this.getType().equals(OnapCommandResultType.TABLE)) { return printOutput + print.printTable(this.isIncludeSeparator()); - } else if (this.getType().equals(ResultType.CSV)) { + } else if (this.getType().equals(OnapCommandResultType.CSV)) { return printOutput + print.printCsv(); } diff --git a/framework/src/main/java/org/onap/cli/fw/output/OnapCommandResultAttribute.java b/framework/src/main/java/org/onap/cli/fw/output/OnapCommandResultAttribute.java index fe4ed32e..c00c88b1 100644 --- a/framework/src/main/java/org/onap/cli/fw/output/OnapCommandResultAttribute.java +++ b/framework/src/main/java/org/onap/cli/fw/output/OnapCommandResultAttribute.java @@ -20,7 +20,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.onap.cli.fw.input.ParameterType; +import org.onap.cli.fw.input.OnapCommandParameterType; /** * Oclip command output records, helps to define the title and its description while command is defined and during run @@ -53,7 +53,7 @@ public class OnapCommandResultAttribute { */ private OnapCommandResultAttributeScope outScope = OnapCommandResultAttributeScope.SHORT; - private ParameterType paramType = ParameterType.STRING; + private OnapCommandParameterType paramType = OnapCommandParameterType.STRING; private boolean isSecured = false; @@ -92,11 +92,11 @@ public class OnapCommandResultAttribute { this.outScope = scope; } - public ParameterType getType() { + public OnapCommandParameterType getType() { return paramType; } - public void setType(ParameterType type) { + public void setType(OnapCommandParameterType type) { this.paramType = type; } diff --git a/framework/src/main/java/org/onap/cli/fw/output/OnapCommandResultType.java b/framework/src/main/java/org/onap/cli/fw/output/OnapCommandResultType.java new file mode 100644 index 00000000..ebd13ebd --- /dev/null +++ b/framework/src/main/java/org/onap/cli/fw/output/OnapCommandResultType.java @@ -0,0 +1,63 @@ +/* + * 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.output; + +/** + * Oclip command result format. + * + */ +public enum OnapCommandResultType { + TABLE, CSV, JSON, YAML, TEXT; + + /** + * Check whether the output to be formatted in tabular format. + * + * @param type + * output format type + * @return boolean + */ + public static boolean isTabularForm(String type) { + if (type.equalsIgnoreCase(TABLE.name())) { + return true; + } + + return false; + } + + /** + * Get OnapCommandResultType. + * + * @param name + * format name + * @return OnapCommandResultType + */ + public static OnapCommandResultType get(String name) { + if (TABLE.name().equalsIgnoreCase(name)) { + return TABLE; + } + if (CSV.name().equalsIgnoreCase(name)) { + return CSV; + } + if (JSON.name().equalsIgnoreCase(name)) { + return JSON; + } + if (YAML.name().equalsIgnoreCase(name)) { + return YAML; + } + return TEXT; + } +} diff --git a/framework/src/main/java/org/onap/cli/fw/output/PrintDirection.java b/framework/src/main/java/org/onap/cli/fw/output/PrintDirection.java deleted file mode 100644 index 96ad713f..00000000 --- a/framework/src/main/java/org/onap/cli/fw/output/PrintDirection.java +++ /dev/null @@ -1,45 +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.fw.output; - -import org.onap.cli.fw.error.OnapCommandInvalidPrintDirection; - -/** - * How to print the result. - * - */ -public enum PrintDirection { - LANDSCAPE, PORTRAIT; - /** - * Get print direction. - * - * @param name - * direction - * @return type - * @throws OnapCommandInvalidPrintDirection - * exception - */ - public static PrintDirection get(String name) throws OnapCommandInvalidPrintDirection { - if (LANDSCAPE.name().equalsIgnoreCase(name)) { - return LANDSCAPE; - } else if (PORTRAIT.name().equalsIgnoreCase(name)) { - return PORTRAIT; - } else { - throw new OnapCommandInvalidPrintDirection(name); - } - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/output/ResultType.java b/framework/src/main/java/org/onap/cli/fw/output/ResultType.java deleted file mode 100644 index 49ddf457..00000000 --- a/framework/src/main/java/org/onap/cli/fw/output/ResultType.java +++ /dev/null @@ -1,63 +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.fw.output; - -/** - * Oclip command result format. - * - */ -public enum ResultType { - TABLE, CSV, JSON, YAML, TEXT; - - /** - * Check whether the output to be formatted in tabular format. - * - * @param type - * output format type - * @return boolean - */ - public static boolean isTabularForm(String type) { - if (type.equalsIgnoreCase(TABLE.name())) { - return true; - } - - return false; - } - - /** - * Get ResultType. - * - * @param name - * format name - * @return ResultType - */ - public static ResultType get(String name) { - if (TABLE.name().equalsIgnoreCase(name)) { - return TABLE; - } - if (CSV.name().equalsIgnoreCase(name)) { - return CSV; - } - if (JSON.name().equalsIgnoreCase(name)) { - return JSON; - } - if (YAML.name().equalsIgnoreCase(name)) { - return YAML; - } - return TEXT; - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/output/print/OnapCommandPrint.java b/framework/src/main/java/org/onap/cli/fw/output/print/OnapCommandPrint.java index 96ce59b2..3946c5da 100644 --- a/framework/src/main/java/org/onap/cli/fw/output/print/OnapCommandPrint.java +++ b/framework/src/main/java/org/onap/cli/fw/output/print/OnapCommandPrint.java @@ -29,7 +29,7 @@ import java.util.StringTokenizer; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.onap.cli.fw.error.OnapCommandOutputPrintingFailed; -import org.onap.cli.fw.output.PrintDirection; +import org.onap.cli.fw.output.OnapCommandPrintDirection; /** * Oclip Command Table print. @@ -39,17 +39,17 @@ public class OnapCommandPrint { public static final int MAX_COLUMN_LENGTH = 50; - private PrintDirection direction; + private OnapCommandPrintDirection direction; private Map> data = new LinkedHashMap<>(); private boolean printTitle = true; - public PrintDirection getDirection() { + public OnapCommandPrintDirection getDirection() { return direction; } - public void setDirection(PrintDirection direction) { + public void setDirection(OnapCommandPrintDirection direction) { this.direction = direction; } 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 new file mode 100644 index 00000000..f8fb73fd --- /dev/null +++ b/framework/src/main/java/org/onap/cli/fw/registrar/OnapCommandRegistrar.java @@ -0,0 +1,393 @@ +/* + * 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.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; +import org.onap.cli.fw.conf.OnapCommandConstants; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandHelpFailed; +import org.onap.cli.fw.error.OnapCommandInvalidRegistration; +import org.onap.cli.fw.error.OnapCommandNotFound; +import org.onap.cli.fw.error.OnapCommandProductVersionInvalid; +import org.onap.cli.fw.error.OnapCommandRegistrationProductInfoMissing; +import org.onap.cli.fw.error.OnapUnsupportedSchemaProfile; +import org.onap.cli.fw.input.cache.OnapCommandParameterCache; +import org.onap.cli.fw.output.OnapCommandPrintDirection; +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.OnapCommandSchema; +import org.onap.cli.fw.schema.OnapCommandSchemaInfo; +import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils; +import org.onap.cli.fw.utils.OnapCommandHelperUtils; +import org.onap.cli.fw.utils.OnapCommandUtils; + + +/** + * Oclip Command registrar provides a common place, where every command would get registered automatically when its + * loaded into JVM. + * + */ +public class OnapCommandRegistrar { + private Map> registry = new HashMap<>(); + + private Map> registryProfilePlugins = new HashMap<>(); + + private Set availableProductVersions = new HashSet<>(); + + private String enabledProductVersion = null; + + private boolean isInteractiveMode = false; + + private OnapCommandParameterCache paramCache = OnapCommandParameterCache.getInstance(); + + public boolean isInteractiveMode() { + return isInteractiveMode; + } + + public void setInteractiveMode(boolean isInteractiveMode) { + this.isInteractiveMode = isInteractiveMode; + } + + public Map getParamCache() { + return paramCache.getParams(this.getEnabledProductVersion()); + } + + public void addParamCache(String paramName, String paramValue) { + paramCache.add(this.getEnabledProductVersion(), paramName, paramValue); + } + + public void removeParamCache(String paramName) { + paramCache.remove(this.getEnabledProductVersion(), paramName); + } + + public void setProfile(String profileName) { + this.paramCache.setProfile(profileName); + } + + private static OnapCommandRegistrar registrar = null; + + /** + * Register the command into registrar and throws OnapInvalidCommandRegistration for invalid command. + * + * @param name + * Command Name + * @param cmd + * Command Class + * @throws OnapCommandInvalidRegistration + * Invalid registration exception + * @throws OnapCommandRegistrationProductInfoMissing + */ + private void register(String name, String version, Class cmd) throws OnapCommandInvalidRegistration, OnapCommandRegistrationProductInfoMissing { + if (version == null || version.isEmpty()) { + throw new OnapCommandRegistrationProductInfoMissing(name); + } + + this.registry.put(name + ":" + version, cmd); + this.availableProductVersions.add(version); + + } + + private void registerProfilePlugin(String profile, Class cmd) { + this.registryProfilePlugins.put(profile, cmd); + } + + 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); + } + } + + /** + * Get global registrar. + * + * @throws OnapCommandException + * exception + */ + public static OnapCommandRegistrar getRegistrar() throws OnapCommandException { + if (registrar == null) { + registrar = new OnapCommandRegistrar(); + registrar.autoDiscoverSchemas(); + } + + return registrar; + } + + /** + * Get the list of discovered commands by registrar. + * + * @return set + */ + public Set listCommands() { + return this.registry.keySet(); + } + + /** + * Get the list of discovered commands for a given product version in registrar. + * + * @return set + */ + public Set listCommandsForEnabledProductVersion() { + String version = this.getEnabledProductVersion(); + + Set cmds = new HashSet<>(); + if (!this.availableProductVersions.contains(version)) { + return cmds; + } + + for (String cmd: this.registry.keySet()) { + if (cmd.split(":")[1].equalsIgnoreCase(version)) { + cmds.add(cmd.split(":")[0]); + } + } + return cmds; + } + + public Class getProfilePlugin(String profile) throws OnapUnsupportedSchemaProfile { + if (!this.registryProfilePlugins.containsKey(profile)) { + throw new OnapUnsupportedSchemaProfile(profile); + } + + return this.registryProfilePlugins.get(profile); + } + + public Set getAvailableProductVersions() { + return this.availableProductVersions; + } + + public void setEnabledProductVersion(String version) throws OnapCommandProductVersionInvalid { + if (!this.availableProductVersions.contains(version)) { + throw new OnapCommandProductVersionInvalid(version, availableProductVersions); + } + + this.enabledProductVersion = version; + } + + public String getEnabledProductVersion() { + return this.enabledProductVersion; + } + + /** + * Returns command details. + * + * @return map + * @throws OnapCommandException + * exception + */ + public List listCommandInfo() throws OnapCommandException { + return OnapCommandDiscoveryUtils.discoverSchemas(); + } + + /** + * Get the OnapCommand, which CLI main would use to find the command based on the command name. + * + * @param cmdName + * Name of command + * @return OnapCommand + * @throws OnapCommandException + * Exception + */ + public OnapCommand get(String cmdName) throws OnapCommandException { + return this.get(cmdName, this.getEnabledProductVersion()); + } + + /** + * 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 + * @return OnapCommand + * @throws OnapCommandException + * Exception + */ + public OnapCommand get(String cmdName, String version) throws OnapCommandException { + Class cls = registry.get(cmdName + ":" + version); + //mrkanag: Restrict auth/catalog type commands only available during devMode. in production + //don't expose the auth type and catalog type commands + + if (cls == null) { + throw new OnapCommandNotFound(cmdName, version); + } + + OnapCommand cmd = OnapCommandDiscoveryUtils.loadCommandClass(cls); + String schemaName = OnapCommandDiscoveryUtils.getSchemaInfo(cmdName, version).getSchemaName(); + cmd.initializeSchema(schemaName); + + return cmd; + } + + private Map> autoDiscoverCommandPlugins() throws OnapCommandException { + List> cmds = OnapCommandDiscoveryUtils.discoverCommandPlugins(); + Map> map = new HashMap<>(); + + for (Class cmd : cmds) { + if (cmd.isAnnotationPresent(OnapCommandSchema.class)) { + OnapCommandSchema ano = cmd.getAnnotation(OnapCommandSchema.class); + if (ano.schema() != null && !ano.schema().isEmpty()) { + map.put(ano.schema(), cmd); + } else if (ano.type() != null && !ano.type().isEmpty()) { + this.registerProfilePlugin(ano.type(), cmd); + map.put(ano.type(), cmd); + } else { + throw new OnapUnsupportedSchemaProfile(ano.schema()); + } + } + } + + return map; + } + + private void autoDiscoverSchemas() throws OnapCommandException { + List schemas = OnapCommandDiscoveryUtils.discoverOrLoadSchemas(true); + + Map> plugins = this.autoDiscoverCommandPlugins(); + + for (OnapCommandSchemaInfo schema : schemas) { + if (schema.isIgnore()) { + continue; + } + + 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 { + throw new OnapUnsupportedSchemaProfile(schema.getSchemaURI()); + } + } + } + + /** + * Helps to find the Oclip CLI version, could be used with --version or -v option. + * + * @return string + */ + public String getVersion() { + String version = this.getClass().getPackage().getImplementationVersion(); + if (version == null) { + version = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_VERSION); + } + + String buildTime = OnapCommandHelperUtils.findLastBuildTime(); + if (buildTime!= null && !buildTime.isEmpty()) { + buildTime = " [" + buildTime + "]"; + } else { + buildTime = ""; + } + + String configuredProductVersion = this.getEnabledProductVersion(); + + String versionInfo = ""; + try { + versionInfo = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(OnapCommandConstants.VERSION_INFO)); + } catch (IOException e) { + //Never occurs // NOSONAR + } + + versionInfo = versionInfo.replaceAll(OnapCommandConstants.VERSION_INFO_PLACE_HOLDER_ENB_PRD_VER, configuredProductVersion); + versionInfo = versionInfo.replaceAll(OnapCommandConstants.VERSION_INFO_PLACE_HOLDER_AVL_PRD_VER, this.availableProductVersions.toString()); + versionInfo = versionInfo.replaceAll(OnapCommandConstants.VERSION_INFO_PLACE_HOLDER_VERSION + "", version + buildTime); + + return versionInfo; + } + + /** + * Provides the help message in tabular format for all commands registered in this registrar. + * + * @return string + * @throws OnapCommandHelpFailed + * Help cmd failed + */ + public String getHelp() throws OnapCommandHelpFailed { + return this.getHelp(false); + } + + public String getHelpForEnabledProductVersion() throws OnapCommandHelpFailed { + return this.getHelp(true); + } + + private String getHelp(boolean isEnabledProductVersionOnly) 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 attrVer = new OnapCommandResultAttribute(); + if (!isEnabledProductVersionOnly) { + attrVer.setName(OnapCommandConstants.INFO_PRODUCT.toUpperCase()); + attrVer.setDescription(OnapCommandConstants.DESCRIPTION); + attrVer.setScope(OnapCommandResultAttributeScope.SHORT); + help.getRecords().add(attrVer); + } + + OnapCommandResultAttribute attrSrv = new OnapCommandResultAttribute(); + attrSrv.setName(OnapCommandConstants.INFO_SERVICE.toUpperCase()); + attrSrv.setDescription(OnapCommandConstants.INFO_SERVICE); + attrSrv.setScope(OnapCommandResultAttributeScope.SHORT); + help.getRecords().add(attrSrv); + + OnapCommandResultAttribute attrDesc = new OnapCommandResultAttribute(); + attrDesc.setName(OnapCommandConstants.DESCRIPTION.toUpperCase()); + attrDesc.setDescription(OnapCommandConstants.DESCRIPTION); + attrDesc.setScope(OnapCommandResultAttributeScope.SHORT); + help.getRecords().add(attrDesc); + + for (String cmdName : isEnabledProductVersionOnly ? OnapCommandUtils.sort(this.listCommandsForEnabledProductVersion()) : OnapCommandUtils.sort(this.listCommands())) { + OnapCommand cmd; + try { + if (!isEnabledProductVersionOnly) { + String []cmdVer = cmdName.split(":"); + cmd = this.get(cmdVer[0], cmdVer[1]); + attr.getValues().add(cmdVer[0]); + attrVer.getValues().add(cmdVer[1]); + } else { + cmd = this.get(cmdName); + attr.getValues().add(cmdName); + } + + attrSrv.getValues().add(cmd.printVersion()); + attrDesc.getValues().add(cmd.getDescription()); + } catch (OnapCommandException e) { + throw new OnapCommandHelpFailed(e); + } + } + + try { + return "\n\nCommands:\n" + help.print() + (isEnabledProductVersionOnly ? "" : "\n" + this.getVersion()); + } catch (OnapCommandException e) { + throw new OnapCommandHelpFailed(e); + } + } +} diff --git a/framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchema.java b/framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchema.java new file mode 100644 index 00000000..12eede74 --- /dev/null +++ b/framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchema.java @@ -0,0 +1,46 @@ +/* + * 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.schema; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Provide command name and schema file location, which is placed in the main resources folder (in classpath). It is + * recommended to keep the name for schema, in the form of oclip-[command-name]-schema.yaml, considered this format as + * default if the schema declaration is missing for a command abc-create, schema file name could be + * abc-create-schema.yaml, corresponding command would like as below + * + * @OnapCommandSchema(type="http", schema="onap-abc-create-schema.yaml") public class AbcCreate extends + * OnapCommand { ... } + */ +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface OnapCommandSchema { + /** + * Schema file name placed under class path + * + * @return + */ + String schema() default ""; + + /** + * Schema type + */ + String type() default ""; +} 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 new file mode 100644 index 00000000..67675480 --- /dev/null +++ b/framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaInfo.java @@ -0,0 +1,122 @@ +/* + * 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.schema; + +import org.onap.cli.fw.cmd.OnapCommandType; +import org.onap.cli.fw.conf.OnapCommandConstants; + +/** + * OnapCommandSchemaInfo is used in discovery caching. + * + */ +public class OnapCommandSchemaInfo { + + /** + * Name of the schema file name + */ + private String schemaName; + + /** + * Schema location in complete path + */ + private String schemaURI; + + private String cmdName; + + private String product; + + /** + * OCS version + */ + private String version; + + private String type = OnapCommandType.CMD.name(); + + private String schemaProfile = OnapCommandConstants.BASIC_SCHEMA_PROFILE; + + private String ignore = OnapCommandConstants.BOOLEAN_FALSE; + + public String getSchemaName() { + return schemaName; + } + + public void setSchemaName(String schemaName) { + this.schemaName = schemaName; + } + + public String getCmdName() { + return cmdName; + } + + public void setCmdName(String cmdName) { + this.cmdName = cmdName; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getProduct() { + return product; + } + + public void setProduct(String cmdVersion) { + this.product = cmdVersion; + } + + public String getSchemaURI() { + return schemaURI; + } + + public void setSchemaURI(String schemaURI) { + this.schemaURI = schemaURI; + } + + public String getSchemaProfile() { + return schemaProfile; + } + + public void setSchemaProfile(String internal) { + this.schemaProfile = internal; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public boolean isIgnore() { + return OnapCommandConstants.BOOLEAN_TRUE.equalsIgnoreCase(this.getIgnore()); + } + + public String getIgnore() { + return ignore; + } + + public void setIgnore(String ignore) { + this.ignore = ignore; + } + + +} 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 new file mode 100644 index 00000000..8aea883e --- /dev/null +++ b/framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaLoader.java @@ -0,0 +1,550 @@ +/* + * 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.schema; + +import static org.onap.cli.fw.conf.OnapCommandConstants.ATTRIBUTES; +import static org.onap.cli.fw.conf.OnapCommandConstants.BOOLEAN_TRUE; +import static org.onap.cli.fw.conf.OnapCommandConstants.COMMAND_TYPE_VALUES; +import static org.onap.cli.fw.conf.OnapCommandConstants.DEFAULT_PARAMETER_FILE_NAME; +import static org.onap.cli.fw.conf.OnapCommandConstants.DEFAULT_VALUE; +import static org.onap.cli.fw.conf.OnapCommandConstants.DESCRIPTION; +import static org.onap.cli.fw.conf.OnapCommandConstants.DIRECTION; +import static org.onap.cli.fw.conf.OnapCommandConstants.INFO; +import static org.onap.cli.fw.conf.OnapCommandConstants.INFO_AUTHOR; +import static org.onap.cli.fw.conf.OnapCommandConstants.INFO_IGNORE; +import static org.onap.cli.fw.conf.OnapCommandConstants.INFO_PARAMS_LIST; +import static org.onap.cli.fw.conf.OnapCommandConstants.INFO_PARAMS_MANDATORY_LIST; +import static org.onap.cli.fw.conf.OnapCommandConstants.INFO_PRODUCT; +import static org.onap.cli.fw.conf.OnapCommandConstants.INFO_SERVICE; +import static org.onap.cli.fw.conf.OnapCommandConstants.INFO_TYPE; +import static org.onap.cli.fw.conf.OnapCommandConstants.INPUT_PARAMS_LIST; +import static org.onap.cli.fw.conf.OnapCommandConstants.INPUT_PARAMS_MANDATORY_LIST; +import static org.onap.cli.fw.conf.OnapCommandConstants.IS_INCLUDE; +import static org.onap.cli.fw.conf.OnapCommandConstants.IS_OPTIONAL; +import static org.onap.cli.fw.conf.OnapCommandConstants.IS_SECURED; +import static org.onap.cli.fw.conf.OnapCommandConstants.LONG_OPTION; +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.PARAMETERS; +import static org.onap.cli.fw.conf.OnapCommandConstants.RESULTS; +import static org.onap.cli.fw.conf.OnapCommandConstants.RESULT_PARAMS_LIST; +import static org.onap.cli.fw.conf.OnapCommandConstants.RESULT_PARAMS_MANDATORY_LIST; +import static org.onap.cli.fw.conf.OnapCommandConstants.SCHEMA_FILE_NOT_EXIST; +import static org.onap.cli.fw.conf.OnapCommandConstants.SCHEMA_FILE_WRONG_EXTN; +import static org.onap.cli.fw.conf.OnapCommandConstants.SCHEMA_PATH_PATERN; +import static org.onap.cli.fw.conf.OnapCommandConstants.SCOPE; +import static org.onap.cli.fw.conf.OnapCommandConstants.SHORT_OPTION; +import static org.onap.cli.fw.conf.OnapCommandConstants.TOP_LEVEL_MANDATORY_LIST; +import static org.onap.cli.fw.conf.OnapCommandConstants.TOP_LEVEL_PARAMS_LIST; +import static org.onap.cli.fw.conf.OnapCommandConstants.TYPE; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.onap.cli.fw.cmd.OnapCommand; +import org.onap.cli.fw.cmd.OnapCommandType; +import org.onap.cli.fw.conf.OnapCommandConfig; +import org.onap.cli.fw.conf.OnapCommandConstants; +import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.error.OnapCommandInvalidSchema; +import org.onap.cli.fw.error.OnapCommandInvalidSchemaVersion; +import org.onap.cli.fw.error.OnapCommandParameterNameConflict; +import org.onap.cli.fw.error.OnapCommandParameterOptionConflict; +import org.onap.cli.fw.error.OnapCommandSchemaNotFound; +import org.onap.cli.fw.info.OnapCommandInfo; +import org.onap.cli.fw.input.OnapCommandParameter; +import org.onap.cli.fw.input.OnapCommandParameterType; +import org.onap.cli.fw.output.OnapCommandPrintDirection; +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.utils.OnapCommandDiscoveryUtils; +import org.onap.cli.fw.utils.OnapCommandUtils; +import org.springframework.core.io.Resource; +import org.yaml.snakeyaml.Yaml; + +public class OnapCommandSchemaLoader { + + /** + * Validates schema version. + * + * @param schemaName schema name + * @param version schema version + * @return map + * @throws OnapCommandInvalidSchemaVersion invalid schema version exception + * @throws OnapCommandInvalidSchema invalid schema + * @throws OnapCommandSchemaNotFound schema not found + */ + public static Map validateSchemaVersion(String schemaName, String version) throws OnapCommandException { + InputStream inputStream = OnapCommandUtils.class.getClassLoader().getResourceAsStream(schemaName); + + try { + Resource resource = OnapCommandDiscoveryUtils.findResource(schemaName, SCHEMA_PATH_PATERN); + + if (resource != null) { + inputStream = resource.getInputStream(); + } + + } catch (IOException e) { + throw new OnapCommandSchemaNotFound(schemaName, e); + } + if (inputStream == null) { + inputStream = OnapCommandSchemaLoader.loadSchemaFromFile(schemaName); + } + + Map values = OnapCommandSchemaLoader.loadSchema(inputStream, schemaName); + String schemaVersion = ""; + if (values.keySet().contains(OPEN_CLI_SCHEMA_VERSION)) { + Object obj = values.get(OPEN_CLI_SCHEMA_VERSION); + schemaVersion = obj.toString(); + } + + if (!version.equals(schemaVersion)) { + throw new OnapCommandInvalidSchemaVersion(schemaVersion); + } + + return values; + } + + /** + * Retrieve OnapCommand from schema. + * + * @param cmd OnapCommand + * @param schemaName schema name + * @param includeDefault include if default + * @param validateSchema flag to represent validation + * @throws OnapCommandException on error + */ + public static List loadSchema(OnapCommand cmd, String schemaName, boolean includeDefault, + boolean validateSchema) throws OnapCommandException { + try { + List errors = new ArrayList<>(); + if (includeDefault) { + Map defaultParameterMap = includeDefault ? + validateSchemaVersion(DEFAULT_PARAMETER_FILE_NAME, cmd.getSchemaVersion()) : new HashMap<>(); + //mrkanag default_parameter is supported only for parameters. + if (defaultParameterMap.containsKey(INFO)) { + defaultParameterMap.remove(OnapCommandConstants.INFO); + } + + errors.addAll(OnapCommandSchemaLoader.parseSchema(cmd, defaultParameterMap, validateSchema)); + } + + Map>> commandYamlMap = + (Map>>)validateSchemaVersion(schemaName, cmd.getSchemaVersion()); + + errors.addAll(OnapCommandSchemaLoader.parseSchema(cmd, commandYamlMap, validateSchema)); + + return errors; + } catch (OnapCommandException e) { + throw e; + } catch (Exception e) { + throw new OnapCommandInvalidSchema(schemaName, e); + } + } + + public static List parseSchema(OnapCommand cmd, + final Map values, + boolean validate) throws OnapCommandException { + + List exceptionList = new ArrayList<>(); + List shortOptions = new ArrayList<>(); + List longOptions = new ArrayList<>(); + + if (validate) { + OnapCommandUtils.validateTags(exceptionList, (Map) values, OnapCommandConfig.getCommaSeparatedList(TOP_LEVEL_PARAMS_LIST), + OnapCommandConfig.getCommaSeparatedList(TOP_LEVEL_MANDATORY_LIST), "root level"); + } + + + List sections = Arrays.asList(NAME, DESCRIPTION, INFO, PARAMETERS, RESULTS); + + for (String key : sections) { + + switch (key) { + case NAME: + Object val = values.get(key); + if (val != null) { + cmd.setName(val.toString()); + } + break; + + case DESCRIPTION: + Object description = values.get(key); + if (description != null) { + cmd.setDescription(description.toString()); + } + break; + + case INFO: + Map infoMap = (Map) values.get(key); + + if (infoMap != null) { + if (validate) { + OnapCommandUtils.validateTags(exceptionList, (Map) values.get(key), + OnapCommandConfig.getCommaSeparatedList(INFO_PARAMS_LIST), + OnapCommandConfig.getCommaSeparatedList(INFO_PARAMS_MANDATORY_LIST), INFO); + + HashMap validationMap = new HashMap<>(); + validationMap.put(INFO_TYPE, COMMAND_TYPE_VALUES); + + for (String secKey : validationMap.keySet()) { + if (infoMap.containsKey(secKey)) { + Object obj = infoMap.get(secKey); + if (obj == null) { + exceptionList.add("Attribute '" + secKey + "' under '" + INFO + "' is empty"); + } else { + String value = String.valueOf(obj); + if (!OnapCommandConfig.getCommaSeparatedList(validationMap.get(secKey)).contains(value)) { + exceptionList.add("Attribute '" + secKey + "' contains invalid value. Valide values are " + + OnapCommandConfig.getCommaSeparatedList(validationMap.get(key))); // + } + } + } + } + } + + OnapCommandInfo info = new OnapCommandInfo(); + + for (Map.Entry entry1 : infoMap.entrySet()) { + String key1 = entry1.getKey(); + + switch (key1) { + case INFO_PRODUCT: + info.setProduct(infoMap.get(key1)); + break; + + case INFO_SERVICE: + info.setService(infoMap.get(key1).toString()); + break; + + case INFO_TYPE: + Object obj = infoMap.get(key1); + info.setCommandType(OnapCommandType.get(obj.toString())); + break; + + case INFO_AUTHOR: + Object mode = infoMap.get(key1); + info.setAuthor(mode.toString()); + break; + + case INFO_IGNORE: + Object ignore = infoMap.get(key1); + info.setIgnore(ignore.toString().equalsIgnoreCase(OnapCommandConstants.BOOLEAN_TRUE)); + break; + } + } + + cmd.setInfo(info); + } + break; + + case PARAMETERS: + + List> parameters = (List) values.get(key); + + if (parameters != null) { + Set names = new HashSet<>(); + + //To support overriding of the parameters, if command is already + //having the same named parameters, means same parameter is + //Overridden from included template into current template + Set existingParamNames = cmd.getParametersMap().keySet(); + + for (Map parameter : parameters) { + boolean isOverriding = false; + OnapCommandParameter param = new OnapCommandParameter(); + + //Override the parameters from its base such as default parameters list + if (existingParamNames.contains(parameter.getOrDefault(NAME, ""))) { + param = cmd.getParametersMap().get(parameter.getOrDefault(NAME, "")); + isOverriding = true; + } + + if (validate) { + OnapCommandUtils.validateTags(exceptionList, parameter, OnapCommandConfig.getCommaSeparatedList(INPUT_PARAMS_LIST), + OnapCommandConfig.getCommaSeparatedList(INPUT_PARAMS_MANDATORY_LIST), PARAMETERS); + } + + for (Map.Entry entry1 : parameter.entrySet()) { + String key2 = entry1.getKey(); + + switch (key2) { + case NAME: + if (names.contains(parameter.get(key2))) { + OnapCommandUtils.throwOrCollect(new OnapCommandParameterNameConflict(parameter.get(key2)), exceptionList, validate); + } else { + names.add(parameter.get(key2)); + } + + param.setName(parameter.get(key2)); + break; + + case DESCRIPTION: + param.setDescription(parameter.get(key2)); + break; + + case SHORT_OPTION: + if (shortOptions.contains(parameter.get(key2))) { + OnapCommandUtils.throwOrCollect(new OnapCommandParameterOptionConflict( + cmd.getSchemaName(), + parameter.get(key2)), exceptionList, validate); + } + shortOptions.add(parameter.get(key2)); + param.setShortOption(parameter.get(key2)); + break; + + case LONG_OPTION: + if (longOptions.contains(parameter.get(key2))) { + OnapCommandUtils.throwOrCollect(new OnapCommandParameterOptionConflict( + cmd.getSchemaName(), + parameter.get(key2)), exceptionList, validate); + } + longOptions.add(parameter.get(key2)); + param.setLongOption(parameter.get(key2)); + break; + + case DEFAULT_VALUE: + Object obj = parameter.get(key2); + param.setDefaultValue(obj.toString()); + break; + + case TYPE: + try { + param.setParameterType(OnapCommandParameterType.get(parameter.get(key2))); + } catch (OnapCommandException ex) { + OnapCommandUtils.throwOrCollect(ex, exceptionList, validate); + } + break; + + case IS_OPTIONAL: + if (validate) { + if (!OnapCommandUtils.validateBoolean(String.valueOf(parameter.get(key2)))) { + exceptionList.add(OnapCommandUtils.invalidBooleanValueMessage(parameter.get(NAME), + IS_SECURED, parameter.get(key2))); + } + } + if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) { + param.setOptional(true); + } else { + param.setOptional(false); + } + break; + + case IS_SECURED: + if (validate) { + if (!OnapCommandUtils.validateBoolean(String.valueOf(parameter.get(key2)))) { + exceptionList.add(OnapCommandUtils.invalidBooleanValueMessage(parameter.get(NAME), + IS_SECURED, parameter.get(key2))); + } + } + + if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) { + param.setSecured(true); + } else { + param.setSecured(false); + } + break; + + case IS_INCLUDE: + if (validate) { + if (!OnapCommandUtils.validateBoolean(String.valueOf(parameter.get(key2)))) { + exceptionList.add(OnapCommandUtils.invalidBooleanValueMessage(parameter.get(NAME), + IS_INCLUDE, parameter.get(key2))); + } + } + + if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) { + param.setInclude(true); + } else { + param.setInclude(false); + } + break; + } + } + + if ( !isOverriding) { + cmd.getParameters().add(param); + } else { + cmd.getParametersMap().replace(param.getName(), param); + } + } + } + break; + + case RESULTS: + Map valueMap = (Map) values.get(key); + if (valueMap != null) { + OnapCommandResult result = new OnapCommandResult(); + for (Map.Entry entry1 : valueMap.entrySet()) { + String key3 = entry1.getKey(); + + switch (key3) { + case DIRECTION: + try { + result.setPrintDirection(OnapCommandPrintDirection.get((String) valueMap.get(key3))); + } catch (OnapCommandException ex) { + OnapCommandUtils.throwOrCollect(ex, exceptionList, validate); + } + break; + + case ATTRIBUTES: + List> attrs = (ArrayList) valueMap.get(key3); + + for (Map map : attrs) { + OnapCommandResultAttribute attr = new OnapCommandResultAttribute(); + if (validate) { + OnapCommandUtils.validateTags(exceptionList, map, OnapCommandConfig.getCommaSeparatedList(RESULT_PARAMS_LIST), + OnapCommandConfig.getCommaSeparatedList(RESULT_PARAMS_MANDATORY_LIST), ATTRIBUTES); + } + + Set resultParamNames = new HashSet<>(); + + for (Map.Entry entry4 : map.entrySet()) { + String key4 = entry4.getKey(); + + switch (key4) { + case NAME: + if (resultParamNames.contains(map.get(key4))) { + exceptionList.add("Attribute name='" + map.get(key4) + "' under '" + + ATTRIBUTES + ":' is already used, Take different one."); + + } else { + attr.setName(map.get(key4)); + resultParamNames.add(map.get(key4)); + } + break; + + case DESCRIPTION: + attr.setDescription(map.get(key4)); + break; + + case SCOPE: + try { + attr.setScope(OnapCommandResultAttributeScope.get(map.get(key4))); + } catch (OnapCommandException ex) { + OnapCommandUtils.throwOrCollect(ex, exceptionList, validate); + } + break; + + case TYPE: + try { + attr.setType(OnapCommandParameterType.get(map.get(key4))); + } catch (OnapCommandException ex) { + OnapCommandUtils.throwOrCollect(ex, exceptionList, validate); + } + break; + + case DEFAULT_VALUE: + Object obj = map.get(key4); + attr.setDefaultValue(obj.toString()); + break; + + case IS_SECURED: + if (validate) { + if (!OnapCommandUtils.validateBoolean(String.valueOf(map.get(key4)))) { + exceptionList.add(OnapCommandUtils.invalidBooleanValueMessage(ATTRIBUTES, + IS_SECURED, map.get(key4))); + } + } + if (BOOLEAN_TRUE.equals(String.valueOf(map.get(key4)))) { + attr.setSecured(true); + } else { + attr.setSecured(false); + } + break; + } + + } + result.getRecords().add(attr); + } + break; + } + } + cmd.setResult(result); + } + break; + } + } + return exceptionList; + } + + public static InputStream loadSchemaFromFile(String schemaLocation) throws OnapCommandInvalidSchema { + File schemaFile = new File(schemaLocation); + try { + FileInputStream inputFileStream = new FileInputStream(schemaFile); + if (!schemaFile.isFile()) { + throw new OnapCommandInvalidSchema(schemaFile.getName(), SCHEMA_FILE_NOT_EXIST); + } + + if (!schemaFile.getName().endsWith(".yaml")) { + throw new OnapCommandInvalidSchema(schemaFile.getName(), SCHEMA_FILE_WRONG_EXTN); + } + return inputFileStream; + }catch (FileNotFoundException e) { + throw new OnapCommandInvalidSchema(schemaFile.getName(), e); + } + } + + /** + * Get schema map. + * + * @param resource + * resource obj + * @return map + * @throws OnapCommandInvalidSchema + * exception + */ + public static Map loadSchema(Resource resource) throws OnapCommandInvalidSchema { + try { + return OnapCommandSchemaLoader.loadSchema(resource.getInputStream(), resource.getFilename()); + } catch (IOException e) { + throw new OnapCommandInvalidSchema(resource.getFilename(), e); + } + + } + + /** + * Get schema map. + * + * @param resource + * resource obj + * @return map + * @throws OnapCommandInvalidSchema + * exception + */ + public static Map loadSchema(InputStream stream, String schemaName) throws OnapCommandInvalidSchema { + Map values = null; + try { + values = (Map) new Yaml().load(stream); + } catch (Exception e) { + throw new OnapCommandInvalidSchema(schemaName, e); + } + + return values; + } +} 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 e1b3ea2b..7d305a86 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,13 +16,13 @@ package org.onap.cli.fw.utils; -import static org.onap.cli.fw.conf.Constants.DATA_DIRECTORY; -import static org.onap.cli.fw.conf.Constants.DATA_PATH_JSON_PATTERN; -import static org.onap.cli.fw.conf.Constants.DISCOVERY_FILE; -import static org.onap.cli.fw.conf.Constants.NAME; -import static org.onap.cli.fw.conf.Constants.OPEN_CLI_SCHEMA_VERSION; -import static org.onap.cli.fw.conf.Constants.SCHEMA_DIRECTORY; -import static org.onap.cli.fw.conf.Constants.SCHEMA_PATH_PATERN; +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; @@ -34,16 +34,15 @@ import java.util.List; import java.util.Map; import java.util.ServiceLoader; -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.OnapCommandRegistrar; -import org.onap.cli.fw.cmd.OnapHttpCommand; -import org.onap.cli.fw.conf.Constants; -import org.onap.cli.fw.conf.OnapCommandConfg; +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.OnapCommandNotFound; +import org.onap.cli.fw.schema.OnapCommandSchemaInfo; +import org.onap.cli.fw.schema.OnapCommandSchemaLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; @@ -64,11 +63,11 @@ public class OnapCommandDiscoveryUtils { * @throws OnapCommandDiscoveryFailed * exception */ - public static SchemaInfo getSchemaInfo(String cmd, String version) throws OnapCommandException { - List list = OnapCommandDiscoveryUtils.discoverOrLoadSchemas(false); - SchemaInfo schemaInfo = null; + public static OnapCommandSchemaInfo getSchemaInfo(String cmd, String version) throws OnapCommandException { + List list = OnapCommandDiscoveryUtils.discoverOrLoadSchemas(false); + OnapCommandSchemaInfo schemaInfo = null; if (list != null) { - for (SchemaInfo schema : list) { + for (OnapCommandSchemaInfo schema : list) { if (cmd.equals(schema.getCmdName()) && version.equals(schema.getProduct())) { schemaInfo = schema; break; @@ -87,9 +86,10 @@ public class OnapCommandDiscoveryUtils { * @throws OnapCommandDiscoveryFailed * exception */ - public static List discoverOrLoadSchemas(boolean forceRefresh) throws OnapCommandException { - List schemas = new ArrayList<>(); - if (forceRefresh || OnapCommandConfg.isDiscoverAlways() || !OnapCommandDiscoveryUtils.isAlreadyDiscovered()) { + public static List discoverOrLoadSchemas(boolean forceRefresh) throws OnapCommandException { + List schemas = new ArrayList<>(); + if (forceRefresh || Boolean.parseBoolean(OnapCommandConfig.getPropertyValue(OnapCommandConstants.DISCOVER_ALWAYS)) + || !OnapCommandDiscoveryUtils.isAlreadyDiscovered()) { schemas = OnapCommandDiscoveryUtils.discoverSchemas(); if (!schemas.isEmpty()) { OnapCommandDiscoveryUtils.persistSchemaInfo(schemas); @@ -101,7 +101,7 @@ public class OnapCommandDiscoveryUtils { if (resource != null) { File file = new File(resource.getURI().getPath()); ObjectMapper mapper = new ObjectMapper(); - SchemaInfo[] list = mapper.readValue(file, SchemaInfo[].class); + OnapCommandSchemaInfo[] list = mapper.readValue(file, OnapCommandSchemaInfo[].class); schemas.addAll(Arrays.asList(list)); } } catch (IOException e) { @@ -144,7 +144,7 @@ public class OnapCommandDiscoveryUtils { * @throws OnapCommandDiscoveryFailed * exception */ - public static void persistSchemaInfo(List schemas) throws OnapCommandDiscoveryFailed { + public static void persistSchemaInfo(List schemas) throws OnapCommandDiscoveryFailed { if (schemas != null) { try { Resource[] resources = OnapCommandDiscoveryUtils.findResources(DATA_DIRECTORY); @@ -219,13 +219,13 @@ public class OnapCommandDiscoveryUtils { public static String identitySchemaProfileType(Map schemaYamlMap) { - for (String schemeType : OnapCommandConfg.getSchemaAttrInfo(Constants.SCHEMA_TYPES_SUPPORTED)) { + for (String schemeType : OnapCommandConfig.getCommaSeparatedList(OnapCommandConstants.SCHEMA_TYPES_SUPPORTED)) { if (schemaYamlMap.get(schemeType) != null) { return schemeType; } } - return Constants.BASIC_SCHEMA_PROFILE; + return OnapCommandConstants.BASIC_SCHEMA_PROFILE; } /** @@ -237,8 +237,8 @@ public class OnapCommandDiscoveryUtils { * @throws OnapCommandInvalidSchema * exception */ - public static List discoverSchemas() throws OnapCommandException { - List extSchemas = new ArrayList<>(); + public static List discoverSchemas() throws OnapCommandException { + List extSchemas = new ArrayList<>(); try { Resource[] res = findResources(SCHEMA_PATH_PATERN); if (res != null && res.length > 0) { @@ -246,21 +246,21 @@ public class OnapCommandDiscoveryUtils { for (Resource resource : res) { try { - resourceMap = OnapCommandSchemaLoaderUtils.loadSchema(resource); + resourceMap = OnapCommandSchemaLoader.loadSchema(resource); } catch (OnapCommandException e) { OnapCommandUtils.LOG.error("Ignores invalid schema " + resource.getURI().toString(), e); continue; } if (resourceMap != null && resourceMap.size() > 0) { - SchemaInfo schema = new SchemaInfo(); + OnapCommandSchemaInfo schema = new OnapCommandSchemaInfo(); schema.setSchemaURI(resource.getURI().toString()); Object obj = resourceMap.get(OPEN_CLI_SCHEMA_VERSION); schema.setVersion(obj.toString()); - if (!schema.getVersion().equalsIgnoreCase(Constants.OPEN_CLI_SCHEMA_VERSION_VALUE_1_0)) { + if (!schema.getVersion().equalsIgnoreCase(OnapCommandConstants.OPEN_CLI_SCHEMA_VERSION_VALUE_1_0)) { OnapCommandUtils.LOG.info("Unsupported Schema version found " + schema.getSchemaURI()); continue; } @@ -268,17 +268,17 @@ public class OnapCommandDiscoveryUtils { schema.setSchemaName(resource.getFilename()); schema.setCmdName((String) resourceMap.get(NAME)); - Map infoMap = (Map) resourceMap.get(Constants.INFO); - if (infoMap != null && infoMap.get(Constants.INFO_TYPE) != null) { - schema.setType(infoMap.get(Constants.INFO_TYPE).toString()); + Map infoMap = (Map) resourceMap.get(OnapCommandConstants.INFO); + if (infoMap != null && infoMap.get(OnapCommandConstants.INFO_TYPE) != null) { + schema.setType(infoMap.get(OnapCommandConstants.INFO_TYPE).toString()); } - if (infoMap != null && infoMap.get(Constants.INFO_PRODUCT) != null) { - schema.setProduct(infoMap.get(Constants.INFO_PRODUCT).toString()); + if (infoMap != null && infoMap.get(OnapCommandConstants.INFO_PRODUCT) != null) { + schema.setProduct(infoMap.get(OnapCommandConstants.INFO_PRODUCT).toString()); } - if (infoMap != null && infoMap.get(Constants.INFO_IGNORE) != null) { - schema.setIgnore(infoMap.get(Constants.INFO_IGNORE).toString()); + if (infoMap != null && infoMap.get(OnapCommandConstants.INFO_IGNORE) != null) { + schema.setIgnore(infoMap.get(OnapCommandConstants.INFO_IGNORE).toString()); } schema.setSchemaProfile(identitySchemaProfileType(resourceMap)); @@ -322,27 +322,4 @@ public class OnapCommandDiscoveryUtils { } } - - /** - * - * @param authAction login/logout - * @return - * @throws OnapCommandException - */ - public static OnapCommand findAuthCommand(OnapHttpCommand forCmd, String authAction) throws OnapCommandException { - OnapCommand auth = null; - try { - //mrkanag: fix this to discover the auth command by matching info->product & service - auth = OnapCommandRegistrar.getRegistrar().get( - forCmd.getInfo().getService() + "-" + - forCmd.getService().getAuthType() + "-" + authAction, - forCmd.getInfo().getProduct()); - } catch (OnapCommandNotFound e) { - auth = OnapCommandRegistrar.getRegistrar().get( - forCmd.getService().getAuthType() + "-" + authAction, - forCmd.getInfo().getProduct()); - } - - return auth; - } } 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 f5ac764b..5e8c3f52 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 @@ -16,24 +16,24 @@ package org.onap.cli.fw.utils; -import static org.onap.cli.fw.conf.Constants.DESCRIPTION; -import static org.onap.cli.fw.conf.Constants.NAME; +import static org.onap.cli.fw.conf.OnapCommandConstants.DESCRIPTION; +import static org.onap.cli.fw.conf.OnapCommandConstants.NAME; import java.io.IOException; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; -import org.onap.cli.fw.OnapCommand; +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.input.OnapCommandParameter; -import org.onap.cli.fw.input.ParameterType; +import org.onap.cli.fw.input.OnapCommandParameterType; +import org.onap.cli.fw.output.OnapCommandPrintDirection; 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.PrintDirection; -import org.onap.cli.fw.output.ResultType; +import org.onap.cli.fw.output.OnapCommandResultType; public class OnapCommandHelperUtils { @@ -87,8 +87,8 @@ public class OnapCommandHelperUtils { // Add parameters OnapCommandResult paramTable = new OnapCommandResult(); - paramTable.setPrintDirection(PrintDirection.LANDSCAPE); - paramTable.setType(ResultType.TABLE); + paramTable.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE); + paramTable.setType(OnapCommandResultType.TABLE); paramTable.setIncludeTitle(false); paramTable.setIncludeSeparator(false); @@ -137,8 +137,8 @@ public class OnapCommandHelperUtils { } optSecondCol += " It is of type " + param.getParameterType().name() + "."; - if (param.getParameterType().equals(ParameterType.JSON) - || param.getParameterType().equals(ParameterType.YAML)) { + if (param.getParameterType().equals(OnapCommandParameterType.JSON) + || param.getParameterType().equals(OnapCommandParameterType.YAML)) { optSecondCol += " It's recommended to input the complete path of the file, which is having the value for it."; } if (param.isOptional()) { @@ -168,8 +168,8 @@ public class OnapCommandHelperUtils { // Add results OnapCommandResult resultTable = new OnapCommandResult(); - resultTable.setPrintDirection(PrintDirection.PORTRAIT); - resultTable.setType(ResultType.TABLE); + resultTable.setPrintDirection(OnapCommandPrintDirection.PORTRAIT); + resultTable.setType(OnapCommandResultType.TABLE); resultTable.setIncludeTitle(false); resultTable.setIncludeSeparator(false); @@ -195,7 +195,7 @@ public class OnapCommandHelperUtils { } // Error - help += "\n\nError::\n\n On error, it prints ::::\n"; + help += "\n\nError::\n\n On error, it prints ::::\n"; return help; } diff --git a/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandProfileUtils.java b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandProfileUtils.java deleted file mode 100644 index b1fff95d..00000000 --- a/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandProfileUtils.java +++ /dev/null @@ -1,72 +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.fw.utils; - -import static org.onap.cli.fw.conf.Constants.DATA_DIRECTORY; -import static org.onap.cli.fw.conf.Constants.DATA_PATH_JSON_PATTERN; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.onap.cli.fw.error.OnapCommandLoadProfileFailed; -import org.onap.cli.fw.error.OnapCommandPersistProfileFailed; -import org.onap.cli.fw.input.cache.Param; -import org.springframework.core.io.Resource; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class OnapCommandProfileUtils { - - public static List loadParamFromCache(String profileName) throws OnapCommandLoadProfileFailed { - List params = new ArrayList<>(); - - try { - Resource resource = OnapCommandDiscoveryUtils.findResource(profileName + ".json", - DATA_PATH_JSON_PATTERN); - if (resource != null) { - File file = new File(resource.getURI().getPath()); - ObjectMapper mapper = new ObjectMapper(); - Param[] list = mapper.readValue(file, Param[].class); - params.addAll(Arrays.asList(list)); - } - } catch (IOException e) { - throw new OnapCommandLoadProfileFailed(e); - } - - return params; - } - - public static void persistProfile(List params, String profileName) throws OnapCommandPersistProfileFailed { - if (params != null) { - try { - 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"); - ObjectMapper mapper = new ObjectMapper(); - mapper.writerWithDefaultPrettyPrinter().writeValue(file, params); - } - } catch (IOException e1) { - throw new OnapCommandPersistProfileFailed(e1); - } - } - } - -} diff --git a/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandSchemaLoaderUtils.java b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandSchemaLoaderUtils.java deleted file mode 100644 index 04bfd23c..00000000 --- a/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandSchemaLoaderUtils.java +++ /dev/null @@ -1,772 +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.fw.utils; - -import static org.onap.cli.fw.conf.Constants.ATTRIBUTES; -import static org.onap.cli.fw.conf.Constants.AUTH; -import static org.onap.cli.fw.conf.Constants.AUTH_VALUES; -import static org.onap.cli.fw.conf.Constants.BODY; -import static org.onap.cli.fw.conf.Constants.BOOLEAN_TRUE; -import static org.onap.cli.fw.conf.Constants.COMMAND_TYPE_VALUES; -import static org.onap.cli.fw.conf.Constants.DEAFULT_PARAMETER_PASSWORD; -import static org.onap.cli.fw.conf.Constants.DEAFULT_PARAMETER_USERNAME; -import static org.onap.cli.fw.conf.Constants.DEFAULT_PARAMETER_FILE_NAME; -import static org.onap.cli.fw.conf.Constants.DEFAULT_PARAMETER_HTTP_FILE_NAME; -import static org.onap.cli.fw.conf.Constants.DEFAULT_PARAMETER_NO_AUTH; -import static org.onap.cli.fw.conf.Constants.DEFAULT_VALUE; -import static org.onap.cli.fw.conf.Constants.DESCRIPTION; -import static org.onap.cli.fw.conf.Constants.DIRECTION; -import static org.onap.cli.fw.conf.Constants.HEADERS; -import static org.onap.cli.fw.conf.Constants.HTTP; -import static org.onap.cli.fw.conf.Constants.HTTP_MANDATORY_SECTIONS; -import static org.onap.cli.fw.conf.Constants.HTTP_SECTIONS; -import static org.onap.cli.fw.conf.Constants.INFO; -import static org.onap.cli.fw.conf.Constants.INFO_AUTHOR; -import static org.onap.cli.fw.conf.Constants.INFO_IGNORE; -import static org.onap.cli.fw.conf.Constants.INFO_PARAMS_LIST; -import static org.onap.cli.fw.conf.Constants.INFO_PARAMS_MANDATORY_LIST; -import static org.onap.cli.fw.conf.Constants.INFO_PRODUCT; -import static org.onap.cli.fw.conf.Constants.INFO_SERVICE; -import static org.onap.cli.fw.conf.Constants.INFO_TYPE; -import static org.onap.cli.fw.conf.Constants.INPUT_PARAMS_LIST; -import static org.onap.cli.fw.conf.Constants.INPUT_PARAMS_MANDATORY_LIST; -import static org.onap.cli.fw.conf.Constants.IS_INCLUDE; -import static org.onap.cli.fw.conf.Constants.IS_OPTIONAL; -import static org.onap.cli.fw.conf.Constants.IS_SECURED; -import static org.onap.cli.fw.conf.Constants.LONG_OPTION; -import static org.onap.cli.fw.conf.Constants.METHOD_TYPE; -import static org.onap.cli.fw.conf.Constants.MODE; -import static org.onap.cli.fw.conf.Constants.MODE_VALUES; -import static org.onap.cli.fw.conf.Constants.MULTIPART_ENTITY_NAME; -import static org.onap.cli.fw.conf.Constants.NAME; -import static org.onap.cli.fw.conf.Constants.OPEN_CLI_SCHEMA_VERSION; -import static org.onap.cli.fw.conf.Constants.PARAMETERS; -import static org.onap.cli.fw.conf.Constants.QUERIES; -import static org.onap.cli.fw.conf.Constants.REQUEST; -import static org.onap.cli.fw.conf.Constants.RESULTS; -import static org.onap.cli.fw.conf.Constants.RESULT_MAP; -import static org.onap.cli.fw.conf.Constants.RESULT_PARAMS_LIST; -import static org.onap.cli.fw.conf.Constants.RESULT_PARAMS_MANDATORY_LIST; -import static org.onap.cli.fw.conf.Constants.SAMPLE_RESPONSE; -import static org.onap.cli.fw.conf.Constants.SCHEMA_FILE_NOT_EXIST; -import static org.onap.cli.fw.conf.Constants.SCHEMA_FILE_WRONG_EXTN; -import static org.onap.cli.fw.conf.Constants.SCHEMA_PATH_PATERN; -import static org.onap.cli.fw.conf.Constants.SCOPE; -import static org.onap.cli.fw.conf.Constants.SERVICE; -import static org.onap.cli.fw.conf.Constants.SERVICE_PARAMS_LIST; -import static org.onap.cli.fw.conf.Constants.SERVICE_PARAMS_MANDATORY_LIST; -import static org.onap.cli.fw.conf.Constants.SHORT_OPTION; -import static org.onap.cli.fw.conf.Constants.SUCCESS_CODES; -import static org.onap.cli.fw.conf.Constants.TOP_LEVEL_MANDATORY_LIST; -import static org.onap.cli.fw.conf.Constants.TOP_LEVEL_PARAMS_LIST; -import static org.onap.cli.fw.conf.Constants.TYPE; -import static org.onap.cli.fw.conf.Constants.URI; -import static org.onap.cli.fw.conf.Constants.VERSION; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.ad.OnapService; -import org.onap.cli.fw.cmd.CommandType; -import org.onap.cli.fw.cmd.OnapHttpCommand; -import org.onap.cli.fw.conf.Constants; -import org.onap.cli.fw.conf.OnapCommandConfg; -import org.onap.cli.fw.error.OnapCommandException; -import org.onap.cli.fw.error.OnapCommandInvalidSchema; -import org.onap.cli.fw.error.OnapCommandInvalidSchemaVersion; -import org.onap.cli.fw.error.OnapCommandParameterNameConflict; -import org.onap.cli.fw.error.OnapCommandParameterOptionConflict; -import org.onap.cli.fw.error.OnapCommandSchemaNotFound; -import org.onap.cli.fw.info.OnapCommandInfo; -import org.onap.cli.fw.input.OnapCommandParameter; -import org.onap.cli.fw.input.ParameterType; -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.PrintDirection; -import org.springframework.core.io.Resource; -import org.yaml.snakeyaml.Yaml; - -public class OnapCommandSchemaLoaderUtils { - - /** - * Validates schema version. - * - * @param schemaName schema name - * @param version schema version - * @return map - * @throws OnapCommandInvalidSchemaVersion invalid schema version exception - * @throws OnapCommandInvalidSchema invalid schema - * @throws OnapCommandSchemaNotFound schema not found - */ - public static Map validateSchemaVersion(String schemaName, String version) throws OnapCommandException { - InputStream inputStream = OnapCommandUtils.class.getClassLoader().getResourceAsStream(schemaName); - - try { - Resource resource = OnapCommandDiscoveryUtils.findResource(schemaName, SCHEMA_PATH_PATERN); - - if (resource != null) { - inputStream = resource.getInputStream(); - } - - } catch (IOException e) { - throw new OnapCommandSchemaNotFound(schemaName, e); - } - if (inputStream == null) { - inputStream = OnapCommandSchemaLoaderUtils.loadSchemaFromFile(schemaName); - } - - Map values = OnapCommandSchemaLoaderUtils.loadSchema(inputStream, schemaName); - String schemaVersion = ""; - if (values.keySet().contains(OPEN_CLI_SCHEMA_VERSION)) { - Object obj = values.get(OPEN_CLI_SCHEMA_VERSION); - schemaVersion = obj.toString(); - } - - if (!version.equals(schemaVersion)) { - throw new OnapCommandInvalidSchemaVersion(schemaVersion); - } - - return values; - } - - /** - * Retrieve OnapCommand from schema. - * - * @param cmd OnapCommand - * @param schemaName schema name - * @param includeDefault include if default - * @param validateSchema flag to represent validation - * @throws OnapCommandException on error - */ - public static List loadSchema(OnapCommand cmd, String schemaName, boolean includeDefault, - boolean validateSchema) throws OnapCommandException { - try { - List errors = new ArrayList<>(); - if (includeDefault) { - Map defaultParameterMap = includeDefault ? - validateSchemaVersion(DEFAULT_PARAMETER_FILE_NAME, cmd.getSchemaVersion()) : new HashMap<>(); - //mrkanag default_parameter is supported only for parameters. - if (defaultParameterMap.containsKey(INFO)) { - defaultParameterMap.remove(Constants.INFO); - } - - errors.addAll(OnapCommandSchemaLoaderUtils.parseSchema(cmd, defaultParameterMap, validateSchema)); - } - - Map>> commandYamlMap = - (Map>>)validateSchemaVersion(schemaName, cmd.getSchemaVersion()); - - errors.addAll(OnapCommandSchemaLoaderUtils.parseSchema(cmd, commandYamlMap, validateSchema)); - - return errors; - } catch (OnapCommandException e) { - throw e; - } catch (Exception e) { - throw new OnapCommandInvalidSchema(schemaName, e); - } - } - - public static List loadHttpSchema(OnapHttpCommand cmd, String schemaName, boolean includeDefault, - boolean validateSchema) throws OnapCommandException { - try { - List errors = new ArrayList<>(); - if (includeDefault) { - Map defaultParameterMap = includeDefault ? - validateSchemaVersion(DEFAULT_PARAMETER_HTTP_FILE_NAME, cmd.getSchemaVersion()) : new HashMap<>(); - - //mrkanag default_parameter is supported only for parameters. - if (defaultParameterMap.containsKey(INFO)) { - defaultParameterMap.remove(Constants.INFO); - } - - errors.addAll(OnapCommandSchemaLoaderUtils.parseSchema(cmd, defaultParameterMap, validateSchema)); - } - - Map>> commandYamlMap = - (Map>>)validateSchemaVersion(schemaName, cmd.getSchemaVersion()); - - errors.addAll(OnapCommandSchemaLoaderUtils.parseHttpSchema(cmd, commandYamlMap, validateSchema)); - - return errors; - - } catch (OnapCommandException e) { - throw e; - } catch (Exception e) { - throw new OnapCommandInvalidSchema(schemaName, e); - } - } - - static List parseSchema(OnapCommand cmd, - final Map values, - boolean validate) throws OnapCommandException { - - List exceptionList = new ArrayList<>(); - List shortOptions = new ArrayList<>(); - List longOptions = new ArrayList<>(); - - if (validate) { - OnapCommandUtils.validateTags(exceptionList, (Map) values, OnapCommandConfg.getSchemaAttrInfo(TOP_LEVEL_PARAMS_LIST), - OnapCommandConfg.getSchemaAttrInfo(TOP_LEVEL_MANDATORY_LIST), "root level"); - } - - - List sections = Arrays.asList(NAME, DESCRIPTION, INFO, PARAMETERS, RESULTS); - - for (String key : sections) { - - switch (key) { - case NAME: - Object val = values.get(key); - if (val != null) { - cmd.setName(val.toString()); - } - break; - - case DESCRIPTION: - Object description = values.get(key); - if (description != null) { - cmd.setDescription(description.toString()); - } - break; - - case INFO: - Map infoMap = (Map) values.get(key); - - if (infoMap != null) { - if (validate) { - OnapCommandUtils.validateTags(exceptionList, (Map) values.get(key), - OnapCommandConfg.getSchemaAttrInfo(INFO_PARAMS_LIST), - OnapCommandConfg.getSchemaAttrInfo(INFO_PARAMS_MANDATORY_LIST), INFO); - - HashMap validationMap = new HashMap<>(); - validationMap.put(INFO_TYPE, COMMAND_TYPE_VALUES); - - for (String secKey : validationMap.keySet()) { - if (infoMap.containsKey(secKey)) { - Object obj = infoMap.get(secKey); - if (obj == null) { - exceptionList.add("Attribute '" + secKey + "' under '" + INFO + "' is empty"); - } else { - String value = String.valueOf(obj); - if (!OnapCommandConfg.getSchemaAttrInfo(validationMap.get(secKey)).contains(value)) { - exceptionList.add("Attribute '" + secKey + "' contains invalid value. Valide values are " - + OnapCommandConfg.getSchemaAttrInfo(validationMap.get(key))); // - } - } - } - } - } - - OnapCommandInfo info = new OnapCommandInfo(); - - for (Map.Entry entry1 : infoMap.entrySet()) { - String key1 = entry1.getKey(); - - switch (key1) { - case INFO_PRODUCT: - info.setProduct(infoMap.get(key1)); - break; - - case INFO_SERVICE: - info.setService(infoMap.get(key1).toString()); - break; - - case INFO_TYPE: - Object obj = infoMap.get(key1); - info.setCommandType(CommandType.get(obj.toString())); - break; - - case INFO_AUTHOR: - Object mode = infoMap.get(key1); - info.setAuthor(mode.toString()); - break; - - case INFO_IGNORE: - Object ignore = infoMap.get(key1); - info.setIgnore(ignore.toString().equalsIgnoreCase(Constants.BOOLEAN_TRUE)); - break; - } - } - - cmd.setInfo(info); - } - break; - - case PARAMETERS: - - List> parameters = (List) values.get(key); - - if (parameters != null) { - Set names = new HashSet<>(); - - //To support overriding of the parameters, if command is already - //having the same named parameters, means same parameter is - //Overridden from included template into current template - Set existingParamNames = cmd.getParametersMap().keySet(); - - for (Map parameter : parameters) { - boolean isOverriding = false; - OnapCommandParameter param = new OnapCommandParameter(); - - //Override the parameters from its base such as default parameters list - if (existingParamNames.contains(parameter.getOrDefault(NAME, ""))) { - param = cmd.getParametersMap().get(parameter.getOrDefault(NAME, "")); - isOverriding = true; - } - - if (validate) { - OnapCommandUtils.validateTags(exceptionList, parameter, OnapCommandConfg.getSchemaAttrInfo(INPUT_PARAMS_LIST), - OnapCommandConfg.getSchemaAttrInfo(INPUT_PARAMS_MANDATORY_LIST), PARAMETERS); - } - - for (Map.Entry entry1 : parameter.entrySet()) { - String key2 = entry1.getKey(); - - switch (key2) { - case NAME: - if (names.contains(parameter.get(key2))) { - OnapCommandUtils.throwOrCollect(new OnapCommandParameterNameConflict(parameter.get(key2)), exceptionList, validate); - } else { - names.add(parameter.get(key2)); - } - - param.setName(parameter.get(key2)); - break; - - case DESCRIPTION: - param.setDescription(parameter.get(key2)); - break; - - case SHORT_OPTION: - if (shortOptions.contains(parameter.get(key2))) { - OnapCommandUtils.throwOrCollect(new OnapCommandParameterOptionConflict( - cmd.getSchemaName(), - parameter.get(key2)), exceptionList, validate); - } - shortOptions.add(parameter.get(key2)); - param.setShortOption(parameter.get(key2)); - break; - - case LONG_OPTION: - if (longOptions.contains(parameter.get(key2))) { - OnapCommandUtils.throwOrCollect(new OnapCommandParameterOptionConflict( - cmd.getSchemaName(), - parameter.get(key2)), exceptionList, validate); - } - longOptions.add(parameter.get(key2)); - param.setLongOption(parameter.get(key2)); - break; - - case DEFAULT_VALUE: - Object obj = parameter.get(key2); - param.setDefaultValue(obj.toString()); - break; - - case TYPE: - try { - param.setParameterType(ParameterType.get(parameter.get(key2))); - } catch (OnapCommandException ex) { - OnapCommandUtils.throwOrCollect(ex, exceptionList, validate); - } - break; - - case IS_OPTIONAL: - if (validate) { - if (!OnapCommandUtils.validateBoolean(String.valueOf(parameter.get(key2)))) { - exceptionList.add(OnapCommandUtils.invalidBooleanValueMessage(parameter.get(NAME), - IS_SECURED, parameter.get(key2))); - } - } - if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) { - param.setOptional(true); - } else { - param.setOptional(false); - } - break; - - case IS_SECURED: - if (validate) { - if (!OnapCommandUtils.validateBoolean(String.valueOf(parameter.get(key2)))) { - exceptionList.add(OnapCommandUtils.invalidBooleanValueMessage(parameter.get(NAME), - IS_SECURED, parameter.get(key2))); - } - } - - if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) { - param.setSecured(true); - } else { - param.setSecured(false); - } - break; - - case IS_INCLUDE: - if (validate) { - if (!OnapCommandUtils.validateBoolean(String.valueOf(parameter.get(key2)))) { - exceptionList.add(OnapCommandUtils.invalidBooleanValueMessage(parameter.get(NAME), - IS_INCLUDE, parameter.get(key2))); - } - } - - if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) { - param.setInclude(true); - } else { - param.setInclude(false); - } - break; - } - } - - if ( !isOverriding) { - cmd.getParameters().add(param); - } else { - cmd.getParametersMap().replace(param.getName(), param); - } - } - } - break; - - case RESULTS: - Map valueMap = (Map) values.get(key); - if (valueMap != null) { - OnapCommandResult result = new OnapCommandResult(); - for (Map.Entry entry1 : valueMap.entrySet()) { - String key3 = entry1.getKey(); - - switch (key3) { - case DIRECTION: - try { - result.setPrintDirection(PrintDirection.get((String) valueMap.get(key3))); - } catch (OnapCommandException ex) { - OnapCommandUtils.throwOrCollect(ex, exceptionList, validate); - } - break; - - case ATTRIBUTES: - List> attrs = (ArrayList) valueMap.get(key3); - - for (Map map : attrs) { - OnapCommandResultAttribute attr = new OnapCommandResultAttribute(); - if (validate) { - OnapCommandUtils.validateTags(exceptionList, map, OnapCommandConfg.getSchemaAttrInfo(RESULT_PARAMS_LIST), - OnapCommandConfg.getSchemaAttrInfo(RESULT_PARAMS_MANDATORY_LIST), ATTRIBUTES); - } - - Set resultParamNames = new HashSet<>(); - - for (Map.Entry entry4 : map.entrySet()) { - String key4 = entry4.getKey(); - - switch (key4) { - case NAME: - if (resultParamNames.contains(map.get(key4))) { - exceptionList.add("Attribute name='" + map.get(key4) + "' under '" - + ATTRIBUTES + ":' is already used, Take different one."); - - } else { - attr.setName(map.get(key4)); - resultParamNames.add(map.get(key4)); - } - break; - - case DESCRIPTION: - attr.setDescription(map.get(key4)); - break; - - case SCOPE: - try { - attr.setScope(OnapCommandResultAttributeScope.get(map.get(key4))); - } catch (OnapCommandException ex) { - OnapCommandUtils.throwOrCollect(ex, exceptionList, validate); - } - break; - - case TYPE: - try { - attr.setType(ParameterType.get(map.get(key4))); - } catch (OnapCommandException ex) { - OnapCommandUtils.throwOrCollect(ex, exceptionList, validate); - } - break; - - case DEFAULT_VALUE: - Object obj = map.get(key4); - attr.setDefaultValue(obj.toString()); - break; - - case IS_SECURED: - if (validate) { - if (!OnapCommandUtils.validateBoolean(String.valueOf(map.get(key4)))) { - exceptionList.add(OnapCommandUtils.invalidBooleanValueMessage(ATTRIBUTES, - IS_SECURED, map.get(key4))); - } - } - if (BOOLEAN_TRUE.equals(String.valueOf(map.get(key4)))) { - attr.setSecured(true); - } else { - attr.setSecured(false); - } - break; - } - - } - result.getRecords().add(attr); - } - break; - } - } - cmd.setResult(result); - } - break; - } - } - return exceptionList; - } - - /** - * Load the schema. - * - * @param cmd - * OnapHttpCommand - * @param schemaName - * schema name - * @throws OnapCommandException - * on error - */ - static ArrayList parseHttpSchema(OnapHttpCommand cmd, - final Map values, - boolean validate) throws OnapCommandException { - ArrayList errorList = new ArrayList<>(); - try { - Map valMap = (Map) values.get(HTTP); - - if (valMap != null) { - if (validate) { - OnapCommandUtils.validateTags(errorList, valMap, OnapCommandConfg.getSchemaAttrInfo(HTTP_SECTIONS), - OnapCommandConfg.getSchemaAttrInfo(HTTP_MANDATORY_SECTIONS), PARAMETERS); - errorList.addAll(OnapCommandUtils.validateHttpSchemaSection(values)); - } - for (Map.Entry entry1 : valMap.entrySet()) { - String key1 = entry1.getKey(); - - switch (key1) { - case REQUEST: - Map map = (Map) valMap.get(key1); - - for (Map.Entry entry2 : map.entrySet()) { - try { - String key2 = entry2.getKey(); - - switch (key2) { - case URI: - Object obj = map.get(key2); - cmd.getInput().setUri(obj.toString()); - break; - case METHOD_TYPE: - Object method = map.get(key2); - cmd.getInput().setMethod(method.toString()); - break; - case BODY: - Object body = map.get(key2); - cmd.getInput().setBody(body.toString()); - break; - case HEADERS: - Map head = (Map) map.get(key2); - cmd.getInput().setReqHeaders(head); - break; - case QUERIES: - Map query = (Map) map.get(key2); - - cmd.getInput().setReqQueries(query); - break; - case MULTIPART_ENTITY_NAME: - Object multipartEntityName = map.get(key2); - cmd.getInput().setMultipartEntityName(multipartEntityName.toString()); - break; - } - }catch (Exception ex) { - OnapCommandUtils.throwOrCollect(new OnapCommandInvalidSchema(cmd.getSchemaName(), ex), errorList, validate); - } - } - break; - - case SERVICE: - Map serviceMap = (Map) valMap.get(key1); - - if (serviceMap != null) { - if (validate) { - OnapCommandUtils.validateTags(errorList, (Map) valMap.get(key1), - OnapCommandConfg.getSchemaAttrInfo(SERVICE_PARAMS_LIST), - OnapCommandConfg.getSchemaAttrInfo(SERVICE_PARAMS_MANDATORY_LIST), SERVICE); - - HashMap validationMap = new HashMap<>(); - validationMap.put(AUTH, AUTH_VALUES); - validationMap.put(MODE, MODE_VALUES); - - for (String secKey : validationMap.keySet()) { - if (serviceMap.containsKey(secKey)) { - Object obj = serviceMap.get(secKey); - if (obj == null) { - errorList.add("Attribute '" + secKey + "' under '" + SERVICE + "' is empty"); - } else { - String value = String.valueOf(obj); - if (!OnapCommandConfg.getSchemaAttrInfo(validationMap.get(secKey)).contains(value)) { - errorList.add("Attribute '" + secKey + "' contains invalid value. Valide values are " - + OnapCommandConfg.getSchemaAttrInfo(validationMap.get(key1))); // - } - } - } - } - } - - OnapService srv = new OnapService(); - - for (Map.Entry entry : serviceMap.entrySet()) { - String key = entry.getKey(); - - switch (key) { - case NAME: - srv.setName(serviceMap.get(key)); - break; - - case VERSION: - srv.setVersion(serviceMap.get(key).toString()); - break; - - case AUTH: - Object obj = serviceMap.get(key); - srv.setAuthType(obj.toString()); - - //On None type, username, password and no_auth are invalid - if (srv.isNoAuth()) { - cmd.getParametersMap().get(DEAFULT_PARAMETER_USERNAME).setInclude(false); - cmd.getParametersMap().get(DEAFULT_PARAMETER_PASSWORD).setInclude(false); - cmd.getParametersMap().get(DEFAULT_PARAMETER_NO_AUTH).setInclude(false); - } - break; - - //mrkanag: from auth command, add the parameters to the command's parameters list - - case MODE: - Object mode = serviceMap.get(key); - srv.setMode(mode.toString()); - break; - } - } - cmd.setService(srv); - } - break; - - case SUCCESS_CODES: - if (validate) { - OnapCommandUtils.validateHttpSccessCodes(errorList, (List) valMap.get(key1)); - } - cmd.setSuccessStatusCodes((ArrayList) valMap.get(key1)); - break; - - case RESULT_MAP: - if (validate) { - OnapCommandUtils.validateHttpResultMap(errorList, values); - } - cmd.setResultMap((Map) valMap.get(key1)); - break; - - case SAMPLE_RESPONSE: - // (mrkanag) implement sample response handling - break; - } - } - } - }catch (OnapCommandException e) { - OnapCommandUtils.throwOrCollect(e, errorList, validate); - } - - //Handle the parameters for auth - if (!cmd.getService().isNoAuth()) { - OnapCommand login = OnapCommandDiscoveryUtils.findAuthCommand(cmd, "login"); - OnapCommandUtils.copyParamSchemasFrom(login, cmd); - } - - return errorList; - } - - public static InputStream loadSchemaFromFile(String schemaLocation) throws OnapCommandInvalidSchema { - File schemaFile = new File(schemaLocation); - try { - FileInputStream inputFileStream = new FileInputStream(schemaFile); - if (!schemaFile.isFile()) { - throw new OnapCommandInvalidSchema(schemaFile.getName(), SCHEMA_FILE_NOT_EXIST); - } - - if (!schemaFile.getName().endsWith(".yaml")) { - throw new OnapCommandInvalidSchema(schemaFile.getName(), SCHEMA_FILE_WRONG_EXTN); - } - return inputFileStream; - }catch (FileNotFoundException e) { - throw new OnapCommandInvalidSchema(schemaFile.getName(), e); - } - } - - /** - * Get schema map. - * - * @param resource - * resource obj - * @return map - * @throws OnapCommandInvalidSchema - * exception - */ - public static Map loadSchema(Resource resource) throws OnapCommandInvalidSchema { - try { - return OnapCommandSchemaLoaderUtils.loadSchema(resource.getInputStream(), resource.getFilename()); - } catch (IOException e) { - throw new OnapCommandInvalidSchema(resource.getFilename(), e); - } - - } - - /** - * Get schema map. - * - * @param resource - * resource obj - * @return map - * @throws OnapCommandInvalidSchema - * exception - */ - public static Map loadSchema(InputStream stream, String schemaName) throws OnapCommandInvalidSchema { - Map values = null; - try { - values = (Map) new Yaml().load(stream); - } catch (Exception e) { - throw new OnapCommandInvalidSchema(schemaName, e); - } - - return values; - } -} diff --git a/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandUtils.java b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandUtils.java index 57a2e303..ad739cd7 100644 --- a/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandUtils.java +++ b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandUtils.java @@ -16,63 +16,31 @@ package org.onap.cli.fw.utils; -import static org.onap.cli.fw.conf.Constants.ATTRIBUTES; -import static org.onap.cli.fw.conf.Constants.BODY; -import static org.onap.cli.fw.conf.Constants.BOOLEAN_VALUE; -import static org.onap.cli.fw.conf.Constants.HEADERS; -import static org.onap.cli.fw.conf.Constants.HTTP; -import static org.onap.cli.fw.conf.Constants.HTTP_BODY_FAILED_PARSING; -import static org.onap.cli.fw.conf.Constants.HTTP_BODY_JSON_EMPTY; -import static org.onap.cli.fw.conf.Constants.HTTP_METHODS; -import static org.onap.cli.fw.conf.Constants.HTTP_REQUEST_MANDATORY_PARAMS; -import static org.onap.cli.fw.conf.Constants.HTTP_REQUEST_PARAMS; -import static org.onap.cli.fw.conf.Constants.HTTP_SUCCESS_CODE_INVALID; -import static org.onap.cli.fw.conf.Constants.METHOD; -import static org.onap.cli.fw.conf.Constants.NAME; -import static org.onap.cli.fw.conf.Constants.PARAMETERS; -import static org.onap.cli.fw.conf.Constants.QUERIES; -import static org.onap.cli.fw.conf.Constants.REQUEST; -import static org.onap.cli.fw.conf.Constants.RESULTS; -import static org.onap.cli.fw.conf.Constants.RESULT_MAP; -import static org.onap.cli.fw.conf.Constants.URI; - -import java.io.IOException; +import static org.onap.cli.fw.conf.OnapCommandConstants.BOOLEAN_VALUE; + import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; -import java.util.stream.Collectors; -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.cmd.OnapHttpCommand; -import org.onap.cli.fw.conf.Constants; -import org.onap.cli.fw.conf.OnapCommandConfg; +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.OnapCommandException; -import org.onap.cli.fw.error.OnapCommandHttpHeaderNotFound; -import org.onap.cli.fw.error.OnapCommandHttpInvalidResponseBody; -import org.onap.cli.fw.error.OnapCommandHttpInvalidResultMap; 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.HttpInput; -import org.onap.cli.fw.http.HttpResult; import org.onap.cli.fw.input.OnapCommandParameter; -import org.onap.cli.fw.input.ParameterType; +import org.onap.cli.fw.input.OnapCommandParameterType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.JsonPath; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; - /** * Provides helper method to parse Yaml files and produce required objects. * @@ -87,7 +55,7 @@ public class OnapCommandUtils { } - static void throwOrCollect(OnapCommandException ex, List list, boolean shouldCollectException) + public static void throwOrCollect(OnapCommandException ex, List list, boolean shouldCollectException) throws OnapCommandException { if (shouldCollectException) { list.add(ex.getMessage()); @@ -96,7 +64,7 @@ public class OnapCommandUtils { } } - static void validateTags(List schemaErrors, Map yamlMap, List totalParams, + public static void validateTags(List schemaErrors, Map yamlMap, List totalParams, List mandatoryParams, String section) { // mrkanag capture invalid entries as well for (String param : totalParams) { @@ -123,76 +91,19 @@ public class OnapCommandUtils { * string * @return boolean */ - static boolean validateBoolean(String toValidate) { - return OnapCommandConfg.getSchemaAttrInfo(BOOLEAN_VALUE).contains(toValidate.toLowerCase()); + public static boolean validateBoolean(String toValidate) { + return OnapCommandConfig.getCommaSeparatedList(BOOLEAN_VALUE).contains(toValidate.toLowerCase()); } - private static String emptySection(String section) { + public static String emptySection(String section) { return "The section '" + section + ":' cann't be null or empty"; } - static String invalidBooleanValueMessage(String section, String attribute, String value) { + public static String invalidBooleanValueMessage(String section, String attribute, String value) { return "The value '" + value + "' of '" + attribute + "' present under '" + section + "' should be boolean"; } - private static Set validateHttpQueries(Map requestMap) { - Map queries = (Map) requestMap.get(QUERIES); - Set queryParamNames = new HashSet<>(); - if (queries != null) { - for (Entry entry : queries.entrySet()) { - parseParameters(String.valueOf(entry.getValue()), queryParamNames); - } - } - return queryParamNames; - } - - - private static Set validateHttpHeaders(Map requestMap) { - - Map headers = (Map) requestMap.get(HEADERS); - Set headerParamNames = new HashSet<>(); - if (headers != null) { - for (Entry entry : headers.entrySet()) { - parseParameters(String.valueOf(entry.getValue()), headerParamNames); - } - } - return headerParamNames; - } - - private static Set validateHttpBody(List errorList, Map requestMap) { - Set bodyParamNames = new HashSet<>(); - Object bodyString = requestMap.get(BODY); - if (bodyString == null) { - return bodyParamNames; - } - - String body = String.valueOf(bodyString); - JSONObject obj = null; - try { - obj = new ObjectMapper().readValue(body, JSONObject.class); - } catch (IOException e1) { // NOSONAR - errorList.add(HTTP_BODY_FAILED_PARSING); - } - if (obj == null || "".equals(obj.toString())) { - errorList.add(HTTP_BODY_JSON_EMPTY); - } - parseParameters(body, bodyParamNames); - - return bodyParamNames; - } - - private static Set validateHttpUri(List errorList, Map requestMap) { - Set uriParamNames = new HashSet<>(); - String uri = (String) requestMap.get(URI); - if (uri == null || uri.isEmpty()) { - errorList.add(emptySection(URI)); - return uriParamNames; - } - parseParameters(uri, uriParamNames); - return uriParamNames; - } - - private static void parseParameters(String line, Set paramNames) { + public static void parseParameters(String line, Set paramNames) { int currentIdx = 0; while (currentIdx < line.length()) { @@ -209,108 +120,6 @@ public class OnapCommandUtils { } - private static Set getRequestParams(Map yamlMap) { - - Set set = new HashSet<>(); - - @SuppressWarnings("unchecked") - List> inputParams = (List>) yamlMap.get(PARAMETERS); - - if (inputParams != null) { - for (Map map : inputParams) { - for (Entry entry : map.entrySet()) { - Object key = entry.getKey(); - - if (NAME.equals(key)) { - set.add(String.valueOf(entry.getValue())); - break; - } - } - } - } - - return set; - } - - static void validateHttpResultMap(List errorList, Map values) throws OnapCommandException { - Map valMap = (Map) values.get(HTTP); - List> attributes = (List>) ((Map)values.get(RESULTS)).get(ATTRIBUTES); - Set resultMapParams = ((Map) valMap.get(RESULT_MAP)).keySet(); - - Set resultAttNames = attributes.stream().map(map -> map.get(NAME)) - .collect(Collectors.toSet()); - - List invaliResultMapParams = resultMapParams.stream() - .filter(p -> !resultAttNames.contains(p)).collect(Collectors.toList()); - - if (!invaliResultMapParams.isEmpty()) { - throwOrCollect(new OnapCommandHttpInvalidResultMap(invaliResultMapParams), errorList, true); - } - } - - static void validateHttpSccessCodes(List errorList, List requestSuccessCodes) { - - if (requestSuccessCodes == null || requestSuccessCodes.isEmpty()) { - errorList.add(HTTP_SUCCESS_CODE_INVALID); - return; - } - - for (Object successCode : requestSuccessCodes) { - Integer code = (Integer) successCode; - if (code < 200 || code >= 300) { - if ( code != 404) { - errorList.add(HTTP_SUCCESS_CODE_INVALID); - } - } - } - - } - - static ArrayList validateHttpSchemaSection(Map values) { - ArrayList errorList = new ArrayList<>(); - Map map = (Map) values.get(HTTP); - Map requestMap = (Map) map.get(REQUEST); - - if (requestMap != null && !requestMap.isEmpty()) { - validateTags(errorList, requestMap, OnapCommandConfg.getSchemaAttrInfo(HTTP_REQUEST_PARAMS), - OnapCommandConfg.getSchemaAttrInfo(HTTP_REQUEST_MANDATORY_PARAMS), REQUEST); - String method = (String) requestMap.get(METHOD); - if (method != null && !method.isEmpty()) { - if (!OnapCommandConfg.getSchemaAttrInfo(HTTP_METHODS).contains(method.toLowerCase())) { - errorList.add("Attribute '" + METHOD + "' under '" + REQUEST + "' is invalid, correct types are " - + OnapCommandConfg.getSchemaAttrInfo(HTTP_METHODS).toString()); - } - } else { - errorList.add("Http request method cann't be null or empty"); - } - - Set requestParams = getRequestParams(values); - - Set uriParams = validateHttpUri(errorList, requestMap); - - Set bodyParams = validateHttpBody(errorList, requestMap); - - Set headerParams = validateHttpHeaders(requestMap); - - Set queryParams = validateHttpQueries(requestMap); - - HashSet totoalParams = new HashSet<>(uriParams); - totoalParams.addAll(bodyParams); - totoalParams.addAll(headerParams); - totoalParams.addAll(queryParams); - - List nonDeclaredParams = totoalParams.stream().filter(param -> !requestParams.contains(param)) - .collect(Collectors.toList()); - - nonDeclaredParams.stream().forEach(p -> errorList.add("The parameter '" + p - + "' declared under 'parameters:' section is not mapped into request section.")); - } else { - errorList.add(emptySection(REQUEST)); - } - return errorList; - } - - /** * Create Dict from list of Parameters. * @@ -318,7 +127,7 @@ public class OnapCommandUtils { * list of parameters * @return map */ - public static Map getInputMap(List inputs) { + public static Map getInputMap(Set inputs) { Map map = new HashMap<>(); for (OnapCommandParameter param : inputs) { map.put(param.getName(), param); @@ -360,28 +169,6 @@ public class OnapCommandUtils { return results; } - /** - * Construct method name. - * - * @param name - * name - * @param prefix - * prefix - * @return string - */ - public static String formMethodNameFromAttributeName(String name, String prefix) { - if (name == null || name.isEmpty()) { - return name; - } - - String methodName = prefix; - for (String tk : name.split("-")) { - methodName += Character.toString(tk.charAt(0)).toUpperCase(); - methodName += tk.substring(1); - } - return methodName; - } - /** * There are unique values like uuid is supported, so when input, output (default) values has * these special entries, then it will get replaced with it's value @@ -410,13 +197,13 @@ public class OnapCommandUtils { String value = ""; switch (splEntry) { - case Constants.SPL_ENTRY_UUID: + case OnapCommandConstants.SPL_ENTRY_UUID: value = UUID.randomUUID().toString(); break; default: - if (splEntry.startsWith(Constants.SPL_ENTRY_ENV)) { + if (splEntry.startsWith(OnapCommandConstants.SPL_ENTRY_ENV)) { //start to read after env:ENV_VAR_NAME String envVarName = splEntry.substring(4); value = System.getenv(envVarName); @@ -463,10 +250,10 @@ public class OnapCommandUtils { String value = params.get(paramName).getValue().toString(); OnapCommandParameter param = params.get(paramName); - if (ParameterType.ARRAY.equals(param.getParameterType()) - || ParameterType.MAP.equals(param.getParameterType()) - || ParameterType.JSON.equals(param.getParameterType()) - || ParameterType.YAML.equals(param.getParameterType())) { + if (OnapCommandParameterType.ARRAY.equals(param.getParameterType()) + || OnapCommandParameterType.MAP.equals(param.getParameterType()) + || OnapCommandParameterType.JSON.equals(param.getParameterType()) + || OnapCommandParameterType.YAML.equals(param.getParameterType())) { // ignore the front and back double quotes in json body result += line.substring(currentIdx, idxS - 1) + value; currentIdx = idxE + 2; @@ -479,190 +266,6 @@ public class OnapCommandUtils { return result; } - private static ArrayList replaceLineFromOutputResults(String line, HttpResult resultHttp) - throws OnapCommandHttpHeaderNotFound, OnapCommandHttpInvalidResponseBody, - OnapCommandResultMapProcessingFailed, OnapCommandResultEmpty { - String headerProcessedLine = ""; - - ArrayList result = new ArrayList<>(); - if (!line.contains("$b{") && !line.contains("$h{")) { - result.add(line); - return result; - } - - /** - * In case of empty response body [] or {} - **/ - if (resultHttp.getBody().length() <= 2) { - return result; - } - - /** - * Process headers macros : line: $h{abc}-$b{$.[*].xyz} , After processing line will be [abc's - * value]-$b{$.[*].xyz} - **/ - int currentIdx = 0; - while (currentIdx < line.length()) { - int idxS = line.indexOf("$h{", currentIdx); - if (idxS == -1) { - headerProcessedLine += line.substring(currentIdx); - break; - } - int idxE = line.indexOf("}", idxS); - String headerName = line.substring(idxS + 3, idxE); - headerName = headerName.trim(); - if (!resultHttp.getRespHeaders().containsKey(headerName)) { - throw new OnapCommandHttpHeaderNotFound(headerName); - } - String value = resultHttp.getRespHeaders().get(headerName); - - headerProcessedLine += line.substring(currentIdx, idxS) + value; - currentIdx = idxE + 1; - } - - // Process body jsonpath macros - List values = new ArrayList<>(); - String bodyProcessedPattern = ""; - currentIdx = 0; - int maxRows = 1; // in normal case, only one row will be there - while (currentIdx < headerProcessedLine.length()) { - int idxS = headerProcessedLine.indexOf("$b{", currentIdx); - if (idxS == -1) { - bodyProcessedPattern += headerProcessedLine.substring(currentIdx); - break; - } - int idxE = headerProcessedLine.indexOf("}", idxS); - String jsonPath = headerProcessedLine.substring(idxS + 3, idxE); - jsonPath = jsonPath.trim(); - try { - // JSONArray or String - Object value = JsonPath.read(resultHttp.getBody(), jsonPath); - if (value instanceof JSONArray) { - JSONArray arr = (JSONArray) value; - if (arr.size() > maxRows) { - maxRows = arr.size(); - } - } - bodyProcessedPattern += headerProcessedLine.substring(currentIdx, idxS) + "%s"; - values.add(value); - currentIdx = idxE + 1; - } catch (Exception e) { - throw new OnapCommandHttpInvalidResponseBody(jsonPath, e); - } - } - - if (bodyProcessedPattern.isEmpty()) { - result.add(headerProcessedLine); - return result; - } else { - for (int i = 0; i < maxRows; i++) { - currentIdx = 0; - String bodyProcessedLine = ""; - int positionalIdx = 0; // %s positional idx - while (currentIdx < bodyProcessedPattern.length()) { - int idxS = bodyProcessedPattern.indexOf("%s", currentIdx); - if (idxS == -1) { - bodyProcessedLine += bodyProcessedPattern.substring(currentIdx); - break; - } - int idxE = idxS + 2; // %s - try { - Object value = values.get(positionalIdx); - String valueS = String.valueOf(value); - if (value instanceof JSONArray) { - JSONArray arr = (JSONArray) value; - if (!arr.isEmpty()) { - valueS = arr.get(i).toString(); - } else { - throw new OnapCommandResultEmpty(); - } - } - - bodyProcessedLine += bodyProcessedPattern.substring(currentIdx, idxS) + valueS; - currentIdx = idxE; - positionalIdx++; - } catch (OnapCommandResultEmpty e) { - throw e; - } catch (Exception e) { - throw new OnapCommandResultMapProcessingFailed(line, e); - } - } - result.add(bodyProcessedLine); - } - - return result; - } - } - - /** - * Set argument to param value. - * - * @param params - * map - * @param input - * HttpInput - * @return HttpInput - * @throws OnapCommandParameterNotFound - * exception - * @throws OnapCommandInvalidParameterValue - * exception - */ - public static HttpInput populateParameters(Map params, HttpInput input) - throws OnapCommandException { - HttpInput inp = new HttpInput(); - for (OnapCommandParameter param : params.values()) { - if (ParameterType.BINARY.equals(param.getParameterType())) { - inp.setBinaryData(true); - break; - } - } - inp.setBody(replaceLineFromInputParameters(input.getBody(), params)); - inp.setUri(replaceLineFromInputParameters(input.getUri(), params)); - inp.setMethod(input.getMethod().toLowerCase()); - for (String h : input.getReqHeaders().keySet()) { - String value = input.getReqHeaders().get(h); - inp.getReqHeaders().put(h, replaceLineFromInputParameters(value, params)); - } - - for (String h : input.getReqQueries().keySet()) { - String value = input.getReqQueries().get(h); - inp.getReqQueries().put(h, replaceLineFromInputParameters(value, params)); - } - - return inp; - } - - /** - * Populate result. - * - * @param resultMap - * map - * @param resultHttp - * HttpResult - * @return map - * @throws OnapCommandHttpHeaderNotFound - * header not found exception - * @throws OnapCommandHttpInvalidResponseBody - * invalid response body exception - * @throws OnapCommandResultMapProcessingFailed - * map processing failed exception - */ - public static Map> populateOutputs(Map resultMap, HttpResult resultHttp) - throws OnapCommandException { - Map> resultsProcessed = new HashMap<>(); - - for (Entry entry : resultMap.entrySet()) { - String key = entry.getKey(); - try { - resultsProcessed.put(key, replaceLineFromOutputResults(resultMap.get(key), resultHttp)); - } catch(OnapCommandResultEmpty e) { - // pass // NOSONAR - } - } - - return resultsProcessed; - } - /** * Populate result from input parameters. * @@ -671,12 +274,7 @@ public class OnapCommandUtils { * @param params * Map * @return map - * @throws OnapCommandHttpHeaderNotFound - * header not found exception - * @throws OnapCommandHttpInvalidResponseBody - * invalid response body exception - * @throws OnapCommandResultMapProcessingFailed - * map processing failed exception + * @throws OnapCommandException */ public static Map> populateOutputsFromInputParameters( Map> resultMap, diff --git a/framework/src/main/java/org/onap/cli/fw/utils/SchemaInfo.java b/framework/src/main/java/org/onap/cli/fw/utils/SchemaInfo.java deleted file mode 100644 index beb02a37..00000000 --- a/framework/src/main/java/org/onap/cli/fw/utils/SchemaInfo.java +++ /dev/null @@ -1,122 +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.fw.utils; - -import org.onap.cli.fw.cmd.CommandType; -import org.onap.cli.fw.conf.Constants; - -/** - * SchemaInfo is used in discovery caching. - * - */ -public class SchemaInfo { - - /** - * Name of the schema file name - */ - private String schemaName; - - /** - * Schema location in complete path - */ - private String schemaURI; - - private String cmdName; - - private String product; - - /** - * OCS version - */ - private String version; - - private String type = CommandType.CMD.name(); - - private String schemaProfile = Constants.BASIC_SCHEMA_PROFILE; - - private String ignore = Constants.BOOLEAN_FALSE; - - public String getSchemaName() { - return schemaName; - } - - public void setSchemaName(String schemaName) { - this.schemaName = schemaName; - } - - public String getCmdName() { - return cmdName; - } - - public void setCmdName(String cmdName) { - this.cmdName = cmdName; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getProduct() { - return product; - } - - public void setProduct(String cmdVersion) { - this.product = cmdVersion; - } - - public String getSchemaURI() { - return schemaURI; - } - - public void setSchemaURI(String schemaURI) { - this.schemaURI = schemaURI; - } - - public String getSchemaProfile() { - return schemaProfile; - } - - public void setSchemaProfile(String internal) { - this.schemaProfile = internal; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public boolean isIgnore() { - return Constants.BOOLEAN_TRUE.equalsIgnoreCase(this.getIgnore()); - } - - public String getIgnore() { - return ignore; - } - - public void setIgnore(String ignore) { - this.ignore = ignore; - } - - -} diff --git a/framework/src/main/resources/META-INF/services/org.onap.cli.fw.OnapCommand b/framework/src/main/resources/META-INF/services/org.onap.cli.fw.OnapCommand deleted file mode 100644 index 1993bcb6..00000000 --- a/framework/src/main/resources/META-INF/services/org.onap.cli.fw.OnapCommand +++ /dev/null @@ -1,6 +0,0 @@ -org.onap.cli.fw.cmd.OnapSchemaValidateCommand -org.onap.cli.fw.cmd.OnapSchemaRefreshCommand -org.onap.cli.fw.cmd.BasicAuthLoginCommand -org.onap.cli.fw.cmd.BasicAuthLogoutCommand -org.onap.cli.fw.cmd.CatalogCommand -org.onap.cli.fw.cmd.OnapHttpCommand \ No newline at end of file diff --git a/framework/src/main/resources/META-INF/services/org.onap.cli.fw.cmd.OnapCommand b/framework/src/main/resources/META-INF/services/org.onap.cli.fw.cmd.OnapCommand new file mode 100644 index 00000000..89648bf5 --- /dev/null +++ b/framework/src/main/resources/META-INF/services/org.onap.cli.fw.cmd.OnapCommand @@ -0,0 +1,2 @@ +org.onap.cli.fw.cmd.OnapSchemaValidateCommand +org.onap.cli.fw.cmd.OnapSchemaRefreshCommand \ No newline at end of file diff --git a/framework/src/main/resources/log4j.properties b/framework/src/main/resources/log4j.properties index f117ef6e..419faf30 100644 --- a/framework/src/main/resources/log4j.properties +++ b/framework/src/main/resources/log4j.properties @@ -1,4 +1,4 @@ -log4j.rootLogger=ERROR, file +log4j.rootLogger=ALL, file # Redirect log messages to a log file, support file rolling. log4j.appender.file=org.apache.log4j.RollingFileAppender diff --git a/framework/src/main/resources/open-cli-schema/http/basic-login.yaml b/framework/src/main/resources/open-cli-schema/http/basic-login.yaml deleted file mode 100644 index 36473df7..00000000 --- a/framework/src/main/resources/open-cli-schema/http/basic-login.yaml +++ /dev/null @@ -1,19 +0,0 @@ -open_cli_schema_version: 1.0 - -name: basic-login - -description: basic login auth command - -info: - product: open-cli - service: basic-auth - type: auth - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com - -results: - direction: portrait - attributes: - - name: Authorization - description: Authorization - scope: short - type: string diff --git a/framework/src/main/resources/open-cli-schema/http/basic-logout.yaml b/framework/src/main/resources/open-cli-schema/http/basic-logout.yaml deleted file mode 100644 index f4acc0ae..00000000 --- a/framework/src/main/resources/open-cli-schema/http/basic-logout.yaml +++ /dev/null @@ -1,19 +0,0 @@ -open_cli_schema_version: 1.0 - -name: basic-logout - -description: basic logout auth command - -info: - product: open-cli - service: basic-auth - type: auth - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com - -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/framework/src/main/resources/open-cli-schema/http/catalog.yaml b/framework/src/main/resources/open-cli-schema/http/catalog.yaml deleted file mode 100644 index 508955f5..00000000 --- a/framework/src/main/resources/open-cli-schema/http/catalog.yaml +++ /dev/null @@ -1,44 +0,0 @@ -open_cli_schema_version: 1.0 - -name: catalog - -description: cli catalog command to find the base path for service. - -info: - product: open-cli - service: catalog - type: catalog - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com - -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 - - name: host-username - is_include: false - - name: host-password - is_include: false - - name: no-auth - is_include: 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: / \ No newline at end of file diff --git a/framework/src/main/resources/open-cli-schema/http/default_input_parameters_http.yaml b/framework/src/main/resources/open-cli-schema/http/default_input_parameters_http.yaml deleted file mode 100644 index d7fbe03c..00000000 --- a/framework/src/main/resources/open-cli-schema/http/default_input_parameters_http.yaml +++ /dev/null @@ -1,36 +0,0 @@ -open_cli_schema_version: 1.0 - -info: - product: open-cli - service: default-param - ignore: true - -parameters: - - name: host-username - type: string - description: Host user name - short_option: u - long_option: host-username - default_value: $s{env:OPEN_CLI_HOST_USERNAME} - is_optional: false - - name: host-password - type: string - description: Host user password - short_option: p - long_option: host-password - default_value: $s{env:OPEN_CLI_HOST_PASSWORD} - is_secured: true - is_optional: false - - name: host-url - type: url - description: host url in http(s) - short_option: m - long_option: host-url - is_optional: false - default_value: $s{env:OPEN_CLI_HOST_URL} - - name: no-auth - type: bool - description: whether to authenticate user or not - short_option: a - long_option: no-auth - default_value: false \ No newline at end of file diff --git a/framework/src/main/resources/open-cli.properties b/framework/src/main/resources/open-cli.properties index b009472b..c8792835 100644 --- a/framework/src/main/resources/open-cli.properties +++ b/framework/src/main/resources/open-cli.properties @@ -1,8 +1,6 @@ -cli.ignore_auth=false -cli.http.api_key_use_cookies=true -cli.discover_always=false cli.product_name=open-cli cli.version=1.0 +cli.discover_always=false #schema validation cli.schema.top_level_params_list=open_cli_schema_version,name,description,parameters,results,http,info @@ -17,29 +15,16 @@ cli.schema.input_params_mandatory_list=name,description,type cli.schema.result_params_list=name,description,scope,type,is_secured, default_value cli.schema.result_params_mandatory_list=name, description, type, scope -#http -cli.schema.http_sections=request,service,success_codes,result_map,sample_response -cli.schema.http_mandatory_sections=request, success_codes - -cli.schema.http_request_params=uri,method,body,headers,queries,multipart_entity_name -cli.schema.http_request_mandatory_params=uri,method - -cli.schema.service_params_list=name,version,auth,mode -cli.schema.service_params_mandatory_list=auth,mode - -cli.schema.http_methods=post,get,delete,put,head - cli.schema.boolean_values=true,false -cli.schema.auth_values=none,basic -cli.schema.mode_values=direct,catalog cli.command.type=cmd,auth,catalog -#product version -cli.product.version=open-cli - # moco properties -cli.sample.gen.enable=false +cli.sample.gen.enable=true cli.sample.gen.target=. # mrkanag Move this to db, once exteranl command registration is supported in place of discovery -cli.schema.type.supported=http +cli.schema.type.supported= + +#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.plugins-prps= \ No newline at end of file diff --git a/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSample.java b/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSample.java index c76df290..b225a3a0 100644 --- a/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSample.java +++ b/framework/src/test/java/org/onap/cli/cmd/sample/OnapCommandSample.java @@ -16,10 +16,10 @@ package org.onap.cli.cmd.sample; -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.OnapCommandSchema; +import org.onap.cli.fw.cmd.OnapCommand; import org.onap.cli.fw.error.OnapCommandException; import org.onap.cli.fw.error.OnapCommandExecutionFailed; +import org.onap.cli.fw.schema.OnapCommandSchema; /** * This command helps to test the Command functionalities. 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 51ed776f..a83cda52 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 @@ -19,20 +19,20 @@ package org.onap.cli.cmd.sample; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; -import java.util.ArrayList; -import java.util.List; +import java.util.HashSet; +import java.util.Set; import java.util.UUID; import org.junit.Test; -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.OnapCommandRegistrar; -import org.onap.cli.fw.conf.Constants; +import org.onap.cli.fw.cmd.OnapCommand; +import org.onap.cli.fw.conf.OnapCommandConstants; import org.onap.cli.fw.error.OnapCommandException; import org.onap.cli.fw.error.OnapCommandExecutionFailed; import org.onap.cli.fw.error.OnapCommandNotInitialized; import org.onap.cli.fw.input.OnapCommandParameter; -import org.onap.cli.fw.input.ParameterType; +import org.onap.cli.fw.input.OnapCommandParameterType; import org.onap.cli.fw.output.OnapCommandResultAttribute; +import org.onap.cli.fw.registrar.OnapCommandRegistrar; public class OnapCommandSampleTest { @Test @@ -42,13 +42,13 @@ public class OnapCommandSampleTest { OnapCommand sample = OnapCommandRegistrar.getRegistrar().get("sample-test"); - List parameters = new ArrayList(); + Set parameters = new HashSet(); OnapCommandParameter v = new OnapCommandParameter(); - v.setName(Constants.DEFAULT_PARAMETER_VERSION); + v.setName(OnapCommandConstants.DEFAULT_PARAMETER_VERSION); v.setValue("true"); parameters.add(v); OnapCommandParameter h = new OnapCommandParameter(); - h.setName(Constants.DEFAULT_PARAMETER_HELP); + h.setName(OnapCommandConstants.DEFAULT_PARAMETER_HELP); h.setValue("false"); parameters.add(h); sample.setParameters(parameters); @@ -61,11 +61,11 @@ public class OnapCommandSampleTest { public void sampleTestHelp() { OnapCommandSample sample = new OnapCommandSample(); try { - List parameters = new ArrayList(); + Set parameters = new HashSet(); OnapCommandParameter v = new OnapCommandParameter(); - v.setName(Constants.DEFAULT_PARAMETER_HELP); + v.setName(OnapCommandConstants.DEFAULT_PARAMETER_HELP); v.setValue("true"); - v.setParameterType(ParameterType.BOOL); + v.setParameterType(OnapCommandParameterType.BOOL); parameters.add(v); sample.setParameters(parameters); sample.execute(); @@ -78,39 +78,32 @@ public class OnapCommandSampleTest { try { OnapCommand sample = OnapCommandRegistrar.getRegistrar().get("sample-test"); - List parameters = new ArrayList(); + Set parameters = new HashSet(); OnapCommandParameter v = new OnapCommandParameter(); - v.setName(Constants.DEFAULT_PARAMETER_VERSION); + v.setName(OnapCommandConstants.DEFAULT_PARAMETER_VERSION); v.setValue("false"); parameters.add(v); OnapCommandParameter h = new OnapCommandParameter(); - h.setName(Constants.DEFAULT_PARAMETER_HELP); + h.setName(OnapCommandConstants.DEFAULT_PARAMETER_HELP); h.setValue("false"); parameters.add(h); OnapCommandParameter f = new OnapCommandParameter(); - f.setName(Constants.DEFAULT_PARAMETER_OUTPUT_FORMAT); + f.setName(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_FORMAT); f.setValue("table"); parameters.add(f); OnapCommandParameter l = new OnapCommandParameter(); - l.setName(Constants.DEFAULT_PARAMETER_OUTPUT_ATTR_LONG); + l.setName(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_ATTR_LONG); l.setValue("true"); parameters.add(l); OnapCommandParameter t = new OnapCommandParameter(); - t.setName(Constants.DEFAULT_PARAMETER_OUTPUT_NO_TITLE); + t.setName(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_NO_TITLE); t.setValue("true"); parameters.add(t); - OnapCommandParameter a = new OnapCommandParameter(); - a.setName(Constants.DEFAULT_PARAMETER_NO_AUTH); - a.setValue("true"); - parameters.add(a); OnapCommandParameter d = new OnapCommandParameter(); - d.setName(Constants.DEFAULT_PARAMETER_DEBUG); + d.setName(OnapCommandConstants.DEFAULT_PARAMETER_DEBUG); d.setValue("true"); parameters.add(d); - OnapCommandParameter m = new OnapCommandParameter(); - m.setName(Constants.DEAFULT_PARAMETER_HOST_URL); - m.setValue("http://localhost"); - parameters.add(m); + sample.setParameters(parameters); sample.execute(); @@ -132,39 +125,31 @@ public class OnapCommandSampleTest { OnapCommandSample sample = new OnapCommandSample(); sample.failCase = true; - List parameters = new ArrayList(); + Set parameters = new HashSet(); OnapCommandParameter v = new OnapCommandParameter(); - v.setName(Constants.DEFAULT_PARAMETER_VERSION); + v.setName(OnapCommandConstants.DEFAULT_PARAMETER_VERSION); v.setValue("false"); parameters.add(v); OnapCommandParameter h = new OnapCommandParameter(); - h.setName(Constants.DEFAULT_PARAMETER_HELP); + h.setName(OnapCommandConstants.DEFAULT_PARAMETER_HELP); h.setValue("false"); parameters.add(h); OnapCommandParameter f = new OnapCommandParameter(); - f.setName(Constants.DEFAULT_PARAMETER_OUTPUT_FORMAT); + f.setName(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_FORMAT); f.setValue("table"); parameters.add(f); OnapCommandParameter l = new OnapCommandParameter(); - l.setName(Constants.DEFAULT_PARAMETER_OUTPUT_ATTR_LONG); + l.setName(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_ATTR_LONG); l.setValue("true"); parameters.add(l); OnapCommandParameter t = new OnapCommandParameter(); - t.setName(Constants.DEFAULT_PARAMETER_OUTPUT_NO_TITLE); + t.setName(OnapCommandConstants.DEFAULT_PARAMETER_OUTPUT_NO_TITLE); t.setValue("true"); parameters.add(t); - OnapCommandParameter a = new OnapCommandParameter(); - a.setName(Constants.DEFAULT_PARAMETER_NO_AUTH); - a.setValue("true"); - parameters.add(a); OnapCommandParameter d = new OnapCommandParameter(); - d.setName(Constants.DEFAULT_PARAMETER_DEBUG); + d.setName(OnapCommandConstants.DEFAULT_PARAMETER_DEBUG); d.setValue("true"); parameters.add(d); - OnapCommandParameter m = new OnapCommandParameter(); - m.setName(Constants.DEAFULT_PARAMETER_HOST_URL); - m.setValue("http://localhost"); - parameters.add(m); sample.setParameters(parameters); sample.execute(); } diff --git a/framework/src/test/java/org/onap/cli/fw/OnapCommandRegistrarTest.java b/framework/src/test/java/org/onap/cli/fw/OnapCommandRegistrarTest.java deleted file mode 100644 index 3f9f780d..00000000 --- a/framework/src/test/java/org/onap/cli/fw/OnapCommandRegistrarTest.java +++ /dev/null @@ -1,139 +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.fw; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.File; -import java.net.URL; - -import org.junit.Before; -import org.junit.Test; -import org.onap.cli.fw.error.OnapCommandException; -import org.onap.cli.fw.error.OnapCommandHelpFailed; -import org.onap.cli.fw.error.OnapCommandNotFound; - -public class OnapCommandRegistrarTest { - - OnapCommandRegistrar registerar; - - @Before - public void setup() throws OnapCommandException { - registerar = OnapCommandRegistrar.getRegistrar(); - createDir(); - } - - private void createDir() { - URL url = OnapCommandRegistrarTest.class.getClassLoader().getResource("open-cli-schema"); - if (url != null) { - String path = url.getPath(); - path = path.replaceFirst("open-cli-schema", "data"); - File file = new File(path); - if (!file.exists()) { - file.mkdir(); - } else { - File f1 = new File(path + "/cli-schema.json"); - f1.delete(); - } - } - } - - @Test - public void oclipCommandNotFoundTest() throws OnapCommandException { - try { - registerar = OnapCommandRegistrar.getRegistrar(); - registerar.get("Test1"); - fail("This should have thrown an exception"); - } catch (OnapCommandNotFound e) { - //pass // NOSONAR - } catch (Exception e) { - fail("This should have thrown an OnapCommandNotFound exception"); - } - } - - @Test - public void helpTest() throws OnapCommandException { - String help = registerar.getHelp(); - assertNotNull(help); - } - - @Test - public void versionTest() throws OnapCommandHelpFailed { - String version = registerar.getVersion(); - assertNotNull(version); - } - - @Test - public void listTest() { - registerar.listCommands(); - } - - @Test - public void testProfile() throws OnapCommandException { - try { - OnapCommandRegistrar.getRegistrar().setProfile("test"); - OnapCommandRegistrar.getRegistrar().addParamCache("a", "b"); - OnapCommandRegistrar.getRegistrar().getParamCache(); - OnapCommandRegistrar.getRegistrar().removeParamCache("a"); - - OnapCommandRegistrar.getRegistrar().setInteractiveMode(false); - assertTrue(!OnapCommandRegistrar.getRegistrar().isInteractiveMode()); - - OnapCommandRegistrar.getRegistrar().setEnabledProductVersion("open-cli"); - assertEquals("open-cli", OnapCommandRegistrar.getRegistrar().getEnabledProductVersion()); - OnapCommandRegistrar.getRegistrar().getAvailableProductVersions(); - assertTrue(OnapCommandRegistrar.getRegistrar().listCommandsForEnabledProductVersion().contains("schema-refresh")); - - assertTrue(OnapCommandRegistrar.getRegistrar().listCommandInfo().size() > 2); - } catch (Exception e) { - fail("failed to test the profile"); - } - } -} - -@OnapCommandSchema(schema = "sample-test-schema.yaml") -class OnapCommandTest extends OnapCommand { - - public OnapCommandTest() { - - } - - public static final String CMD_NAME = "test"; - - protected void run() throws OnapCommandException { - - } - -} - -@OnapCommandSchema(schema = "test-schema.yaml") -class OnapCommandTest1 extends OnapCommand { - - public OnapCommandTest1() { - - } - - public static final String CMD_NAME = "test1"; - - protected void run() throws OnapCommandException { - - } - -} diff --git a/framework/src/test/java/org/onap/cli/fw/ad/OnapAuthClientCommandBasedTest.java b/framework/src/test/java/org/onap/cli/fw/ad/OnapAuthClientCommandBasedTest.java deleted file mode 100644 index 58b44f4a..00000000 --- a/framework/src/test/java/org/onap/cli/fw/ad/OnapAuthClientCommandBasedTest.java +++ /dev/null @@ -1,134 +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.fw.ad; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.Before; -import org.junit.Test; -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.OnapCommandRegistrar; -import org.onap.cli.fw.cmd.OnapHttpCommand; -import org.onap.cli.fw.conf.Constants; -import org.onap.cli.fw.conf.OnapCommandConfg; -import org.onap.cli.fw.error.OnapCommandException; -import org.onap.cli.fw.error.OnapCommandProductVersionInvalid; - -public class OnapAuthClientCommandBasedTest { - - @Before - public void setup() throws OnapCommandProductVersionInvalid, OnapCommandException { - OnapCommandRegistrar.getRegistrar().setEnabledProductVersion(OnapCommandConfg.getProductName()); - } - - @Test - public void internalCommandTest() { - try { - OnapCommand cmd = OnapCommandRegistrar.getRegistrar().get("sample-test"); - cmd.getInfo().setService(OnapCommandConfg.getProductName()); - - cmd.execute(); - } catch (OnapCommandException e) { - fail("Internal command failed to run"); - e.printStackTrace(System.out); - } - } - - @Test - public void yesCatalogYesAuthTest() throws OnapCommandException { - try { - OnapHttpCommand cmd = getCommand("sample-test-schema-yes-auth-yes-catalog.yaml"); - cmd.getParametersMap().get(Constants.DEAFULT_PARAMETER_HOST_URL).setValue("http://localhost:8080"); - cmd.getParametersMap().get(Constants.DEAFULT_PARAMETER_USERNAME).setValue("test"); - cmd.getParametersMap().get(Constants.DEAFULT_PARAMETER_PASSWORD).setValue("password"); - - cmd.execute(); - } catch (OnapCommandException e) { - fail("External command Yes Auth Yes Catalog failed to run"); - e.printStackTrace(System.out); - } - } - - @Test - public void yesCatalogNoAuthTest() throws OnapCommandException { - try { - OnapHttpCommand cmd = getCommand("sample-test-schema-no-auth-yes-catalog.yaml"); - cmd.getParametersMap().get(Constants.DEAFULT_PARAMETER_HOST_URL).setValue("http://localhost:8080"); - - cmd.execute(); - } catch (OnapCommandException e) { - fail("External command Yes Auth No Catalog failed to run " + e.getMessage()); - e.printStackTrace(System.out); - } - } - - @Test - public void noCatalogYesAuthTest() throws OnapCommandException { - try { - OnapHttpCommand cmd = getCommand("sample-test-schema-yes-auth-no-catalog.yaml"); - cmd.getParametersMap().get(Constants.DEAFULT_PARAMETER_HOST_URL).setValue("http://localhost:8080"); - cmd.getParametersMap().get(Constants.DEAFULT_PARAMETER_USERNAME).setValue("test"); - cmd.getParametersMap().get(Constants.DEAFULT_PARAMETER_PASSWORD).setValue("password"); - - cmd.execute(); - } catch (OnapCommandException e) { - fail("External command Yes Auth No Catalog failed to run"); - e.printStackTrace(System.out); - } - } - - @Test - public void noCatalogYesAuthWithAdditionalParamsTest() throws OnapCommandException { - try { - OnapHttpCommand cmd = getCommand("sample-test-schema-yes-auth-with-additional-params-no-catalog.yaml"); - assertTrue(cmd.getParametersMap().containsKey("string-param")); - } catch (OnapCommandException e) { - fail("External command Yes Auth No Catalog failed to run"); - e.printStackTrace(System.out); - } - } - - @Test - public void noCatalogNoAuthTest() throws OnapCommandException { - try { - OnapHttpCommand cmd = getCommand("sample-test-schema-no-auth-no-catalog.yaml"); - cmd.getParametersMap().get(Constants.DEAFULT_PARAMETER_HOST_URL).setValue("http://localhost:8080"); - - cmd.execute(); - } catch (OnapCommandException e) { - fail("External command No Auth No Catalog failed to run"); - e.printStackTrace(System.out); - } - } - - private OnapHttpCommand getCommand(String yaml) throws OnapCommandException { - OnapHttpCommand cmd = new OnapHttpCommand() { - @Override - protected void processRequest() throws OnapCommandException { - if (!this.getService().isModeDirect()) { - String url = this.authClient.getServiceUrl(); - assert url.equals(this.getParametersMap().get(Constants.DEAFULT_PARAMETER_HOST_URL).getValue() + "/"); - } - } - }; - - cmd.initializeSchema(yaml); - - return cmd; - } - } diff --git a/framework/src/test/java/org/onap/cli/fw/ad/OnapServiceTest.java b/framework/src/test/java/org/onap/cli/fw/ad/OnapServiceTest.java deleted file mode 100644 index 9ceba67d..00000000 --- a/framework/src/test/java/org/onap/cli/fw/ad/OnapServiceTest.java +++ /dev/null @@ -1,38 +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.fw.ad; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.onap.cli.fw.conf.Constants; - -public class OnapServiceTest { - - @Test - public void serviceTest() { - OnapService ser = new OnapService(); - ser.setName("name"); - ser.setVersion("1.0"); - ser.setBasePath("basePath"); - ser.setAuthType(Constants.AUTH_NONE); - assertTrue(ser.getName().equals("name") && ser.getVersion().equals("1.0") - && ser.getBasePath().equals("basePath") && ser.isNoAuth()); - - } - -} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapHttpCommandTest.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapHttpCommandTest.java deleted file mode 100644 index 3fced8ab..00000000 --- a/framework/src/test/java/org/onap/cli/fw/cmd/OnapHttpCommandTest.java +++ /dev/null @@ -1,81 +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.fw.cmd; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import org.junit.Ignore; -import org.junit.Test; -import org.onap.cli.fw.error.OnapCommandException; -import org.onap.cli.fw.http.HttpInput; -import org.onap.cli.fw.input.OnapCommandParameter; -import org.onap.cli.fw.input.ParameterType; - -public class OnapHttpCommandTest { - - @Ignore - @Test(expected = OnapCommandException.class) - public void runTest() throws OnapCommandException { - OnapCommandParameter param1 = new OnapCommandParameter(); - param1.setLongOption("host-username"); - param1.setName("host-username"); - param1.setParameterType(ParameterType.STRING); - OnapCommandParameter param2 = new OnapCommandParameter(); - param2.setLongOption("host-password"); - param2.setName("host-password"); - param2.setParameterType(ParameterType.STRING); - OnapCommandParameter param3 = new OnapCommandParameter(); - param3.setLongOption("host-url"); - param3.setName("host-url"); - param3.setParameterType(ParameterType.STRING); - OnapCommandParameter param4 = new OnapCommandParameter(); - param4.setLongOption("string-param"); - param4.setName("string-param"); - param4.setParameterType(ParameterType.STRING); - OnapCommandParameter param5 = new OnapCommandParameter(); - param5.setLongOption("long-opt"); - param5.setName("long-opt"); - param5.setParameterType(ParameterType.STRING); - - List paramslist = new ArrayList<>(); - paramslist.add(param1); - paramslist.add(param2); - paramslist.add(param3); - paramslist.add(param4); - paramslist.add(param5); - - HttpInput inp = new HttpInput(); - inp.setBody("body"); - inp.setMethod("method"); - inp.setReqCookies(new HashMap()); - inp.setReqHeaders(new HashMap()); - inp.setReqQueries(new HashMap()); - inp.setUri("uri"); - - OnapHttpCommand com = new OnapHttpCommand(); - com.setParameters(paramslist); - com.getParameters(); - com.getParametersMap(); - com.setInput(inp); - com.initializeSchema("sample-test-schema.yaml"); - com.execute(); - - } - -} diff --git a/framework/src/test/java/org/onap/cli/fw/cmd/OnapSchemaValidateCommandTest.java b/framework/src/test/java/org/onap/cli/fw/cmd/OnapSchemaValidateCommandTest.java index 8d8de2f7..f094203b 100644 --- a/framework/src/test/java/org/onap/cli/fw/cmd/OnapSchemaValidateCommandTest.java +++ b/framework/src/test/java/org/onap/cli/fw/cmd/OnapSchemaValidateCommandTest.java @@ -18,9 +18,8 @@ package org.onap.cli.fw.cmd; import org.junit.Ignore; import org.junit.Test; -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.OnapCommandRegistrar; import org.onap.cli.fw.error.OnapCommandException; +import org.onap.cli.fw.registrar.OnapCommandRegistrar; import org.onap.cli.fw.schema.ValidateSchemaTest; diff --git a/framework/src/test/java/org/onap/cli/fw/conf/OnapCommandConfgTest.java b/framework/src/test/java/org/onap/cli/fw/conf/OnapCommandConfgTest.java index 2c25991b..d6ef3a34 100644 --- a/framework/src/test/java/org/onap/cli/fw/conf/OnapCommandConfgTest.java +++ b/framework/src/test/java/org/onap/cli/fw/conf/OnapCommandConfgTest.java @@ -16,28 +16,6 @@ package org.onap.cli.fw.conf; -import java.io.IOException; -import java.util.Properties; - -import org.junit.Assert; -import org.junit.Test; - public class OnapCommandConfgTest { - @Test - public void versionTest() { - String str = OnapCommandConfg.getVersion(); - Assert.assertTrue(str != null); - } - - @Test - public void isAuthIgnoredTest() throws IOException { - Properties prps = new Properties(); - prps.load(OnapCommandConfg.class.getClassLoader().getResourceAsStream("open-cli.properties")); - boolean auth = OnapCommandConfg.isAuthIgnored(); - Assert.assertTrue(auth == Boolean.valueOf(prps.getProperty("cli.ignore_auth"))); - Assert.assertTrue(OnapCommandConfg.isCookiesBasedAuth() == Boolean - .valueOf(prps.getProperty("cli.http.api_key_use_cookies"))); - } - } diff --git a/framework/src/test/java/org/onap/cli/fw/error/OnapCommandErrorTest.java b/framework/src/test/java/org/onap/cli/fw/error/OnapCommandErrorTest.java index 899f2e3b..58c0f432 100644 --- a/framework/src/test/java/org/onap/cli/fw/error/OnapCommandErrorTest.java +++ b/framework/src/test/java/org/onap/cli/fw/error/OnapCommandErrorTest.java @@ -44,12 +44,6 @@ public class OnapCommandErrorTest { assertEquals("0x3002::Failed to parse the result format of command name, failed", failed.getMessage()); } - @Test - public void oclipCommandHttpHeaderNotFoundTest() { - OnapCommandHttpHeaderNotFound failed = new OnapCommandHttpHeaderNotFound("name"); - assertEquals("0x3003::Http header name is not returned from the service", failed.getMessage()); - } - @Test public void oclipCommandClientInitialzationFailedTest() { OnapCommandClientInitialzationFailed failed = new OnapCommandClientInitialzationFailed("Test", @@ -106,22 +100,6 @@ public class OnapCommandErrorTest { assertEquals("0x9001::Command failed to print help message, Failed", failed.getMessage()); } - @Test - public void oclipCommandHttpFailureTest1() { - OnapCommandHttpFailure failed = new OnapCommandHttpFailure("Failed"); - assertEquals("0x3001::Failed", failed.getMessage()); - - failed = new OnapCommandHttpFailure(new Exception("failed"), 201); - assertEquals("201::0x3001::failed", failed.getMessage()); - } - - @Test - public void oclipCommandHttpFailureTest2() { - OnapCommandHttpFailure failed = new OnapCommandHttpFailure("Failed", 203); - - assertEquals("203::0x3001::Failed", failed.getMessage()); - } - @Test public void oclipCommandInvalidParameterTypeTest() { OnapCommandInvalidParameterType failed = new OnapCommandInvalidParameterType("Failed"); @@ -141,7 +119,7 @@ public class OnapCommandErrorTest { OnapCommandInvalidRegistration failed = new OnapCommandInvalidRegistration(OnapCommandErrorTest.class); assertEquals("0x2001::Invalid commad class org.onap.cli.fw.error.OnapCommandErrorTest registration, " - + "it should be derived from org.onap.cli.fw.OnapCommand", failed.getMessage()); + + "it should be derived from org.onap.cli.fw.cmd.OnapCommand", failed.getMessage()); } @Test @@ -165,29 +143,6 @@ public class OnapCommandErrorTest { assertEquals("0xb003::Command schema open_cli_schema_version 1.0 is invalid or missing", failed.getMessage()); } - @Test - public void oclipCommandLoginFailedTest1() { - OnapCommandLoginFailed failed = new OnapCommandLoginFailed(new Exception("Failed")); - - assertEquals("0x4001::Login failed, Failed", failed.getMessage()); - } - - @Test - public void oclipCommandLoginFailedTest2() { - OnapCommandLoginFailed failed = new OnapCommandLoginFailed("Failed", 201); - - assertEquals("201::0x4001::Login failed, Failed", failed.getMessage()); - } - - @Test - public void oclipCommandLogoutFailedTest() { - OnapCommandLogoutFailed failed = new OnapCommandLogoutFailed(new Exception("Failed")); - assertEquals("0x4002::Logout failed, Failed", failed.getMessage()); - - failed = new OnapCommandLogoutFailed(200); - assertEquals("200::0x4002::Logout failed", failed.getMessage()); - } - @Test public void oclipCommandNotFoundTest() { OnapCommandNotFound failed = new OnapCommandNotFound("Test", "1.0"); @@ -253,13 +208,6 @@ public class OnapCommandErrorTest { assertEquals("0xb002::Command schema is missing for command Test", failed.getMessage()); } - @Test - public void oclipCommandServiceNotFoundTest() { - OnapCommandServiceNotFound failed = new OnapCommandServiceNotFound("Service"); - - assertEquals("0xd001::Service Service is not found in MSB", failed.getMessage()); - } - @Test public void oclipCommandOutputFormatNotsupportedTest() { OnapCommandOutputFormatNotsupported failed = new OnapCommandOutputFormatNotsupported("Format"); diff --git a/framework/src/test/java/org/onap/cli/fw/http/HttpInputOutputTest.java b/framework/src/test/java/org/onap/cli/fw/http/HttpInputOutputTest.java deleted file mode 100644 index 0a3a817e..00000000 --- a/framework/src/test/java/org/onap/cli/fw/http/HttpInputOutputTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2016-17 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; - -import static org.junit.Assert.assertTrue; - -import java.util.HashMap; - -import org.junit.Test; - -public class HttpInputOutputTest { - - @Test - public void httpInputTest() { - HttpInput inp = new HttpInput(); - inp.setBody("body"); - inp.setMethod("method"); - inp.setReqCookies(null); - inp.setReqHeaders(null); - inp.setReqQueries(null); - inp.setUri("uri"); - - assertTrue("body".equals(inp.getBody()) && "method".equals(inp.getMethod()) && null == inp.getReqCookies() - && inp.getReqHeaders().isEmpty() && inp.getReqQueries().isEmpty() && "uri".equals(inp.getUri())); - - inp.setReqCookies(new HashMap()); - inp.setReqHeaders(new HashMap()); - inp.setReqQueries(new HashMap()); - - assertTrue( - "\nURL: uri\nMethod: method\nRequest Queries: {}\nRequest Body: body\nRequest Headers: {}\nRequest Cookies: {}\nbinaryData=false" - .equals(inp.toString())); - } - - @Test - public void httpResultTest() { - HttpResult out = new HttpResult(); - out.setBody("body"); - out.setRespCookies(null); - out.setRespHeaders(null); - out.setStatus(205); - - assertTrue("body".equals(out.getBody()) && null == out.getRespCookies() && null == out.getRespHeaders() - && 205 == out.getStatus()); - - out.setRespCookies(new HashMap()); - out.setRespHeaders(new HashMap()); - out.setStatus(200); - assertTrue("\nHTTP Status: 200\nResponse Body: body\nResponse Headers: {}\nResponse Cookies: {}" - .equals(out.toString())); - } - -} diff --git a/framework/src/test/java/org/onap/cli/fw/http/OnapHttpConnectionTest.java b/framework/src/test/java/org/onap/cli/fw/http/OnapHttpConnectionTest.java deleted file mode 100644 index 785092c2..00000000 --- a/framework/src/test/java/org/onap/cli/fw/http/OnapHttpConnectionTest.java +++ /dev/null @@ -1,205 +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.fw.http; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.protocol.HttpContext; -import org.junit.Before; -import org.junit.Test; -import org.onap.cli.fw.error.OnapCommandHttpFailure; - -import mockit.Invocation; -import mockit.Mock; -import mockit.MockUp; - -public class OnapHttpConnectionTest { - HttpInput inp = null; - OnapHttpConnection con = null; - - @Before - public void setup() { - mockHttpRequest(null); - inp = new HttpInput(); - inp.setMethod("get"); - inp.setBody("body"); - Map map1 = new HashMap<>(); - map1.put("header1", "value1"); - inp.setReqHeaders(map1); - Map map2 = new HashMap<>(); - map2.put("query1", "value1"); - inp.setReqQueries(map2); - Map map = new HashMap<>(); - map.put("cookie1", "value1"); - inp.setReqCookies(map); - inp.setUri("http://192.168.99.10:80"); - } - - @Test(expected = OnapCommandHttpFailure.class) - public void httpUnSecuredGetExceptionTest() throws OnapCommandHttpFailure { - new MockUp() { - @Mock - public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) - throws IOException, ClientProtocolException { - - throw new IOException("IO Exception"); - } - }; - inp.setMethod("get"); - con = new OnapHttpConnection(true); - con.getDebugInfo(); - con.get(inp); - - } - - @Test(expected = OnapCommandHttpFailure.class) - public void httpUnSecuredPostExceptionTest() throws OnapCommandHttpFailure { - new MockUp() { - @Mock - public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) - throws IOException, ClientProtocolException { - - throw new IOException("IO Exception"); - } - }; - - inp.setMethod("post"); - con = new OnapHttpConnection(true); - con.post(inp); - } - - - @Test(expected = OnapCommandHttpFailure.class) - public void httpUnSecuredPostExceptionTest1() throws OnapCommandHttpFailure { - new MockUp() { - @Mock - public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) - throws IOException, ClientProtocolException { - - throw new IOException("IO Exception"); - } - }; - - inp.setMethod("post"); - inp.setBinaryData(true); - con = new OnapHttpConnection(true); - con.post(inp); - } - - @Test(expected = OnapCommandHttpFailure.class) - public void httpUnSecuredPutExceptionTest() throws OnapCommandHttpFailure { - new MockUp() { - @Mock - public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) - throws IOException, ClientProtocolException { - - throw new IOException("IO Exception"); - } - }; - inp.setMethod("put"); - con = new OnapHttpConnection(true); - con.put(inp); - } - - @Test(expected = OnapCommandHttpFailure.class) - public void httpUnSecuredDeleteExceptionTest() throws OnapCommandHttpFailure { - new MockUp() { - @Mock - public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) - throws IOException, ClientProtocolException { - - throw new IOException("IO Exception"); - } - }; - inp.setMethod("delete"); - con = new OnapHttpConnection(true); - con.delete(inp); - } - - @Test(expected = IllegalArgumentException.class) - public void httpUnSecuredOtherExceptionTest() throws OnapCommandHttpFailure { - new MockUp() { - @Mock - public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) - throws IOException, ClientProtocolException { - - throw new IOException("IO Exception"); - } - }; - inp.setMethod("other"); - con = new OnapHttpConnection(true); - con.request(inp); - } - - @Test() - public void httpUnSecuredCloseExceptionTest() throws OnapCommandHttpFailure { - inp.setMethod("other"); - con = new OnapHttpConnection(true); - con.close(); - } - - @Test - public void httpSecuredGetExceptionTest() { - - // ProtocolVersion p = new ProtocolVersion("http",1,0); - // HttpResponse hr = DefaultHttpResponseFactory.INSTANCE.newHttpResponse(p, 200 , null) ; - - new MockUp() { - @Mock - public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) - throws IOException, ClientProtocolException { - - throw new IOException("IO Exception"); - } - }; - try { - HttpInput inp = new HttpInput(); - inp.setMethod("get"); - inp.setBody("body"); - inp.setReqHeaders(new HashMap()); - inp.setReqQueries(new HashMap()); - inp.setUri("https://192.168.99.10:80"); - OnapHttpConnection con = new OnapHttpConnection(false); - con.get(inp); - } catch (OnapCommandHttpFailure e) { - assertEquals("0x3001::IO Exception", e.getMessage()); - } - } - - private static void mockHttpRequest(HttpResult result) { - new MockUp() { - boolean isMock = false; - - @Mock - public HttpResult request(Invocation inv, HttpInput input) throws OnapCommandHttpFailure { - if (isMock) { - return result; - } else { - return inv.proceed(input); - } - } - }; - } -} 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 44656f9f..82781b43 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 @@ -36,7 +36,7 @@ public class OnapCommandParameterTest { param.setLongOption("longOption"); param.setName("name"); param.setOptional(true); - param.setParameterType(ParameterType.JSON); + param.setParameterType(OnapCommandParameterType.JSON); param.setSecured(false); param.setShortOption("shortOption"); param.setValue("value"); @@ -44,15 +44,15 @@ public class OnapCommandParameterTest { assertTrue(param.getDefaultValue().equals("defaultValue") && param.getDescription().equals("description") && param.getLongOption().equals("longOption") && param.getName().equals("name") && param.getShortOption().equals("shortOption") && param.getValue().equals("value") - && param.isOptional() && !param.isSecured() && param.getParameterType().equals(ParameterType.JSON)); + && param.isOptional() && !param.isSecured() && param.getParameterType().equals(OnapCommandParameterType.JSON)); assertTrue("value".equals(param.getValue())); - param.setParameterType(ParameterType.ARRAY); + param.setParameterType(OnapCommandParameterType.ARRAY); param.setValue(Arrays.asList("1", "2", "3")); assertTrue("[\"1\",\"2\",\"3\"]".equals(param.getValue())); - param.setParameterType(ParameterType.MAP); + param.setParameterType(OnapCommandParameterType.MAP); Map map = new HashMap<>(); map.put("One", "1"); map.put("Two", "2"); @@ -82,7 +82,7 @@ public class OnapCommandParameterTest { param.setOptional(false); param.setValue(""); param.setDefaultValue(""); - param.setParameterType(ParameterType.STRING); + param.setParameterType(OnapCommandParameterType.STRING); try { param.validate(); } catch (OnapCommandException e) { @@ -94,7 +94,7 @@ public class OnapCommandParameterTest { public void oclipCommandInvalidParameterValueArrayExeceptionTest() throws OnapCommandInvalidParameterValue { OnapCommandParameter param = new OnapCommandParameter(); param.setName("name"); - param.setParameterType(ParameterType.ARRAY); + param.setParameterType(OnapCommandParameterType.ARRAY); param.setValue("value"); assertTrue("[\"1\",\"2\",\"3\"]".equals(param.getValue())); @@ -104,7 +104,7 @@ public class OnapCommandParameterTest { public void oclipCommandInvalidParameterValueMapExeceptionTest() throws OnapCommandInvalidParameterValue { OnapCommandParameter param = new OnapCommandParameter(); param.setName("name"); - param.setParameterType(ParameterType.MAP); + param.setParameterType(OnapCommandParameterType.MAP); param.setValue("value"); assertTrue("{\"One\":\"1\",\"Two\":\"2\",\"Three\":\"3\"}".equals(param.getValue())); } @@ -113,7 +113,7 @@ public class OnapCommandParameterTest { public void oclipCommandInvalidParameterValueBinaryExeceptionTest() throws OnapCommandException { OnapCommandParameter param = new OnapCommandParameter(); param.setName("name"); - param.setParameterType(ParameterType.BINARY); + param.setParameterType(OnapCommandParameterType.BINARY); param.setValue("value"); param.validate(); } diff --git a/framework/src/test/java/org/onap/cli/fw/input/ParameterTypeTest.java b/framework/src/test/java/org/onap/cli/fw/input/ParameterTypeTest.java index 877f08f5..a42b9120 100644 --- a/framework/src/test/java/org/onap/cli/fw/input/ParameterTypeTest.java +++ b/framework/src/test/java/org/onap/cli/fw/input/ParameterTypeTest.java @@ -27,22 +27,22 @@ public class ParameterTypeTest { public void paramTypeGetTest() { try { - assertTrue(ParameterType.JSON.equals(ParameterType.get("json")) - && ParameterType.YAML.equals(ParameterType.get("yaml")) - && ParameterType.STRING.equals(ParameterType.get("string")) - && ParameterType.DIGIT.equals(ParameterType.get("digit")) - && ParameterType.URL.equals(ParameterType.get("url")) - && ParameterType.BOOL.equals(ParameterType.get("bool")) - && ParameterType.MAP.equals(ParameterType.get("map")) - && ParameterType.BINARY.equals(ParameterType.get("binary")) - && ParameterType.TEXT.equals(ParameterType.get("text")) - && ParameterType.ARRAY.equals(ParameterType.get("array"))); + assertTrue(OnapCommandParameterType.JSON.equals(OnapCommandParameterType.get("json")) + && OnapCommandParameterType.YAML.equals(OnapCommandParameterType.get("yaml")) + && OnapCommandParameterType.STRING.equals(OnapCommandParameterType.get("string")) + && OnapCommandParameterType.DIGIT.equals(OnapCommandParameterType.get("digit")) + && OnapCommandParameterType.URL.equals(OnapCommandParameterType.get("url")) + && OnapCommandParameterType.BOOL.equals(OnapCommandParameterType.get("bool")) + && OnapCommandParameterType.MAP.equals(OnapCommandParameterType.get("map")) + && OnapCommandParameterType.BINARY.equals(OnapCommandParameterType.get("binary")) + && OnapCommandParameterType.TEXT.equals(OnapCommandParameterType.get("text")) + && OnapCommandParameterType.ARRAY.equals(OnapCommandParameterType.get("array"))); } catch (OnapCommandInvalidParameterType e) { fail("Shouldn't have thrown this exception : " + e.getMessage()); } try { - ParameterType.get("name"); + OnapCommandParameterType.get("name"); } catch (OnapCommandInvalidParameterType e) { assertTrue("0x7001::Parameter type name is invalid".equals(e.getMessage())); } diff --git a/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultAttributeScopeTest.java b/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultAttributeScopeTest.java index 7ab3fe52..8f5f861a 100644 --- a/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultAttributeScopeTest.java +++ b/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultAttributeScopeTest.java @@ -21,7 +21,7 @@ import static org.junit.Assert.assertTrue; import java.util.Collections; import org.junit.Test; -import org.onap.cli.fw.input.ParameterType; +import org.onap.cli.fw.input.OnapCommandParameterType; public class OnapCommandResultAttributeScopeTest { @Test @@ -31,11 +31,11 @@ public class OnapCommandResultAttributeScopeTest { att.setName("name"); att.setScope(OnapCommandResultAttributeScope.LONG); att.setSecured(true); - att.setType(ParameterType.DIGIT); + att.setType(OnapCommandParameterType.DIGIT); att.setValues(Collections.emptyList()); assertTrue("description".equals(att.getDescription()) && "name".equals(att.getName()) && OnapCommandResultAttributeScope.LONG.equals(att.getScope()) - && ParameterType.DIGIT.equals(att.getType()) && att.getValues().isEmpty()); + && OnapCommandParameterType.DIGIT.equals(att.getType()) && att.getValues().isEmpty()); } } diff --git a/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultTest.java b/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultTest.java index 9c832c24..667ed02a 100644 --- a/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultTest.java +++ b/framework/src/test/java/org/onap/cli/fw/output/OnapCommandResultTest.java @@ -26,7 +26,7 @@ import java.util.List; import org.junit.Ignore; import org.junit.Test; import org.onap.cli.fw.error.OnapCommandException; -import org.onap.cli.fw.input.ParameterType; +import org.onap.cli.fw.input.OnapCommandParameterType; public class OnapCommandResultTest { @@ -37,16 +37,16 @@ public class OnapCommandResultTest { res.setIncludeSeparator(true); res.setIncludeTitle(true); res.setOutput("Output"); - res.setPrintDirection(PrintDirection.LANDSCAPE); + res.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE); res.setRecords(new ArrayList()); res.setScope(OnapCommandResultAttributeScope.LONG); - res.setType(ResultType.TABLE); + res.setType(OnapCommandResultType.TABLE); res.setDebug(true); assertTrue("debugInfo".equals(res.getDebugInfo()) && res.isIncludeSeparator() - && "Output".equals(res.getOutput()) && PrintDirection.LANDSCAPE.equals(res.getPrintDirection()) + && "Output".equals(res.getOutput()) && OnapCommandPrintDirection.LANDSCAPE.equals(res.getPrintDirection()) && res.getRecords().isEmpty() && OnapCommandResultAttributeScope.LONG.equals(res.getScope()) - && ResultType.TABLE.equals(res.getType())); + && OnapCommandResultType.TABLE.equals(res.getType())); String help = res.print(); @@ -61,18 +61,18 @@ public class OnapCommandResultTest { res.setIncludeSeparator(true); res.setIncludeTitle(true); res.setOutput("Output"); - res.setPrintDirection(PrintDirection.LANDSCAPE); + res.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE); OnapCommandResultAttribute att = new OnapCommandResultAttribute(); att.setName("param"); att.setDescription("description"); - att.setType(ParameterType.STRING); + att.setType(OnapCommandParameterType.STRING); att.setValues(new ArrayList(Arrays.asList(new String[] { "value" }))); List list = new ArrayList(); list.add(att); res.setRecords(list); res.setScope(OnapCommandResultAttributeScope.LONG); - res.setType(ResultType.TABLE); + res.setType(OnapCommandResultType.TABLE); res.getRecordsMap(); String expRes = "+--------+\n|param |\n+--------+\n|value |\n+--------+\n"; String result = res.print(); @@ -88,19 +88,19 @@ public class OnapCommandResultTest { res.setIncludeSeparator(true); res.setIncludeTitle(true); res.setOutput("Output"); - res.setPrintDirection(PrintDirection.LANDSCAPE); + res.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE); OnapCommandResultAttribute att = new OnapCommandResultAttribute(); att.setName("param"); att.setDescription("description"); - att.setType(ParameterType.JSON); + att.setType(OnapCommandParameterType.JSON); att.setValues( new ArrayList(Arrays.asList(new String[] { "{\"id\": \"0001\",\"value\": \"result\"}" }))); List list = new ArrayList(); list.add(att); res.setRecords(list); res.setScope(OnapCommandResultAttributeScope.LONG); - res.setType(ResultType.JSON); + res.setType(OnapCommandResultType.JSON); // Will be handled after the json print is implemented String result = res.print(); @@ -118,25 +118,25 @@ public class OnapCommandResultTest { res.setIncludeSeparator(true); res.setIncludeTitle(true); res.setOutput("Output"); - res.setPrintDirection(PrintDirection.LANDSCAPE); + res.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE); OnapCommandResultAttribute att = new OnapCommandResultAttribute(); att.setName("param"); att.setDescription("description"); - att.setType(ParameterType.STRING); + att.setType(OnapCommandParameterType.STRING); att.setValues(new ArrayList(Arrays.asList(new String[] { "value" }))); List list = new ArrayList(); list.add(att); OnapCommandResultAttribute a1 = new OnapCommandResultAttribute(); a1.setName("param1"); a1.setDescription("description1"); - a1.setType(ParameterType.STRING); + a1.setType(OnapCommandParameterType.STRING); a1.setValues(new ArrayList(Arrays.asList(new String[] { "value1" }))); list.add(a1); res.setRecords(list); res.setScope(OnapCommandResultAttributeScope.LONG); - res.setType(ResultType.CSV); + res.setType(OnapCommandResultType.CSV); String expRes = "param,param1\r\n"; String result = res.print(); @@ -152,25 +152,25 @@ public class OnapCommandResultTest { res.setIncludeSeparator(true); res.setIncludeTitle(true); res.setOutput("Output"); - res.setPrintDirection(PrintDirection.PORTRAIT); + res.setPrintDirection(OnapCommandPrintDirection.PORTRAIT); OnapCommandResultAttribute att = new OnapCommandResultAttribute(); att.setName("param"); att.setDescription("description"); - att.setType(ParameterType.STRING); + att.setType(OnapCommandParameterType.STRING); att.setValues(new ArrayList(Arrays.asList(new String[] { "value" }))); List list = new ArrayList(); list.add(att); OnapCommandResultAttribute a1 = new OnapCommandResultAttribute(); a1.setName("param1"); a1.setDescription("description1"); - a1.setType(ParameterType.STRING); + a1.setType(OnapCommandParameterType.STRING); a1.setValues(new ArrayList(Arrays.asList(new String[] { "value1" }))); list.add(a1); res.setRecords(list); res.setScope(OnapCommandResultAttributeScope.LONG); - res.setType(ResultType.CSV); + res.setType(OnapCommandResultType.CSV); String expRes = "property,value\r\nparam,value\r\n"; String result = res.print(); assertEquals(expRes, result); @@ -183,19 +183,19 @@ public class OnapCommandResultTest { res.setIncludeSeparator(true); res.setIncludeTitle(true); res.setOutput("Output"); - res.setPrintDirection(PrintDirection.PORTRAIT); + res.setPrintDirection(OnapCommandPrintDirection.PORTRAIT); OnapCommandResultAttribute att = new OnapCommandResultAttribute(); att.setName("param"); att.setDescription("description"); - att.setType(ParameterType.STRING); + att.setType(OnapCommandParameterType.STRING); att.setValues(new ArrayList(Arrays.asList(new String[] { "value" }))); List list = new ArrayList(); list.add(att); res.setRecords(list); res.setScope(OnapCommandResultAttributeScope.LONG); - res.setType(ResultType.TABLE); + res.setType(OnapCommandResultType.TABLE); String expRes = "+----------+--------+\n|property |value |\n+----------+--------+" + "\n|param |value |\n+----------+--------+\n"; diff --git a/framework/src/test/java/org/onap/cli/fw/output/PrintDirectionTest.java b/framework/src/test/java/org/onap/cli/fw/output/PrintDirectionTest.java index d1ad7950..ae8dd2e1 100644 --- a/framework/src/test/java/org/onap/cli/fw/output/PrintDirectionTest.java +++ b/framework/src/test/java/org/onap/cli/fw/output/PrintDirectionTest.java @@ -27,14 +27,14 @@ public class PrintDirectionTest { public void printDirectionGetTest() { try { - assertTrue(PrintDirection.LANDSCAPE.equals(PrintDirection.get("landscape")) - && PrintDirection.PORTRAIT.equals(PrintDirection.get("portrait"))); + assertTrue(OnapCommandPrintDirection.LANDSCAPE.equals(OnapCommandPrintDirection.get("landscape")) + && OnapCommandPrintDirection.PORTRAIT.equals(OnapCommandPrintDirection.get("portrait"))); } catch (OnapCommandInvalidPrintDirection e) { fail("Shouldn't have thrown this exception : " + e.getMessage()); } try { - PrintDirection.get("name"); + OnapCommandPrintDirection.get("name"); } catch (OnapCommandInvalidPrintDirection e) { assertTrue("0x8003::Print direction name is invalid".equals(e.getMessage())); } diff --git a/framework/src/test/java/org/onap/cli/fw/output/ResultTypeTest.java b/framework/src/test/java/org/onap/cli/fw/output/ResultTypeTest.java index 3c4c5665..a6590b3d 100644 --- a/framework/src/test/java/org/onap/cli/fw/output/ResultTypeTest.java +++ b/framework/src/test/java/org/onap/cli/fw/output/ResultTypeTest.java @@ -24,19 +24,19 @@ import org.junit.Test; public class ResultTypeTest { @Test public void resultTypeGetTest() { - assertTrue(ResultType.TABLE.equals(ResultType.get("table")) && ResultType.CSV.equals(ResultType.get("csv")) - && ResultType.JSON.equals(ResultType.get("json")) && ResultType.YAML.equals(ResultType.get("yaml")) - && ResultType.TEXT.equals(ResultType.get("text"))); + assertTrue(OnapCommandResultType.TABLE.equals(OnapCommandResultType.get("table")) && OnapCommandResultType.CSV.equals(OnapCommandResultType.get("csv")) + && OnapCommandResultType.JSON.equals(OnapCommandResultType.get("json")) && OnapCommandResultType.YAML.equals(OnapCommandResultType.get("yaml")) + && OnapCommandResultType.TEXT.equals(OnapCommandResultType.get("text"))); } @Test public void isTabularFormTest() { - assertTrue(ResultType.isTabularForm("table")); + assertTrue(OnapCommandResultType.isTabularForm("table")); } @Test public void isTabularFormNotTest() { - assertFalse(ResultType.isTabularForm("text")); + assertFalse(OnapCommandResultType.isTabularForm("text")); } } diff --git a/framework/src/test/java/org/onap/cli/fw/output/print/OnapCommandPrintTest.java b/framework/src/test/java/org/onap/cli/fw/output/print/OnapCommandPrintTest.java index 84c868b3..812e58e2 100644 --- a/framework/src/test/java/org/onap/cli/fw/output/print/OnapCommandPrintTest.java +++ b/framework/src/test/java/org/onap/cli/fw/output/print/OnapCommandPrintTest.java @@ -25,7 +25,7 @@ import java.util.List; import org.junit.Ignore; import org.junit.Test; import org.onap.cli.fw.error.OnapCommandOutputPrintingFailed; -import org.onap.cli.fw.output.PrintDirection; +import org.onap.cli.fw.output.OnapCommandPrintDirection; public class OnapCommandPrintTest { @@ -33,7 +33,7 @@ public class OnapCommandPrintTest { @Ignore public void printCsvTest() throws OnapCommandOutputPrintingFailed { OnapCommandPrint pr = new OnapCommandPrint(); - pr.setDirection(PrintDirection.LANDSCAPE); + pr.setDirection(OnapCommandPrintDirection.LANDSCAPE); pr.setPrintTitle(true); pr.addColumn("name1", new ArrayList(Arrays.asList(new String[] { "value1" }))); String exp = "name1\r\n"; @@ -45,7 +45,7 @@ public class OnapCommandPrintTest { public void printTableTest() throws OnapCommandOutputPrintingFailed { OnapCommandPrint pr = new OnapCommandPrint(); List getColumnsData = new ArrayList(); - pr.setDirection(PrintDirection.LANDSCAPE); + pr.setDirection(OnapCommandPrintDirection.LANDSCAPE); pr.setPrintTitle(true); pr.addColumn("name2", new ArrayList(Arrays.asList(new String[] { "value2" }))); String exp = "+--------+\n|name2 |\n+--------+\n|value2 |\n+--------+\n"; @@ -58,7 +58,7 @@ public class OnapCommandPrintTest { public void printTableNullColumnHeaderTest() throws OnapCommandOutputPrintingFailed { OnapCommandPrint pr = new OnapCommandPrint(); List getColumnsData = new ArrayList(); - pr.setDirection(PrintDirection.LANDSCAPE); + pr.setDirection(OnapCommandPrintDirection.LANDSCAPE); pr.setPrintTitle(true); pr.addColumn("name2", new ArrayList(Arrays.asList(new String[] { "value2" }))); String exp = "+--------+\n|name2 |\n+--------+\n|value2 |\n+--------+\n"; @@ -71,7 +71,7 @@ public class OnapCommandPrintTest { public void printTableEmptyColumnValuesTest() throws OnapCommandOutputPrintingFailed { OnapCommandPrint pr = new OnapCommandPrint(); List getColumnsData = new ArrayList(); - pr.setDirection(PrintDirection.LANDSCAPE); + pr.setDirection(OnapCommandPrintDirection.LANDSCAPE); pr.setPrintTitle(true); pr.addColumn("name2", new ArrayList(Arrays.asList(new String[] { "" }))); String exp = "+--------+\n|name2 |\n+--------+\n| |\n+--------+\n"; 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 new file mode 100644 index 00000000..539ec245 --- /dev/null +++ b/framework/src/test/java/org/onap/cli/fw/registrar/OnapCommandRegistrarTest.java @@ -0,0 +1,150 @@ +/* + * 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.registrar; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.net.URL; + +import org.junit.Before; +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.error.OnapCommandNotFound; +import org.onap.cli.fw.schema.OnapCommandSchema; + +public class OnapCommandRegistrarTest { + + OnapCommandRegistrar registerar; + + @Before + public void setup() throws OnapCommandException { + registerar = OnapCommandRegistrar.getRegistrar(); + createDir(); + } + + private void createDir() { + URL url = OnapCommandRegistrarTest.class.getClassLoader().getResource("open-cli-schema"); + if (url != null) { + String path = url.getPath(); + path = path.replaceFirst("open-cli-schema", "data"); + File file = new File(path); + if (!file.exists()) { + file.mkdir(); + } else { + File f1 = new File(path + "/cli-schema.json"); + f1.delete(); + } + } + } + + @Test + public void oclipCommandNotFoundTest() throws OnapCommandException { + try { + registerar = OnapCommandRegistrar.getRegistrar(); + registerar.get("Test1"); + fail("This should have thrown an exception"); + } catch (OnapCommandNotFound e) { + //pass // NOSONAR + } catch (Exception e) { + fail("This should have thrown an OnapCommandNotFound exception"); + } + } + + @Test + public void helpTest() throws OnapCommandException { + String help = registerar.getHelp(); + assertNotNull(help); + } + + @Test + public void versionTest() throws OnapCommandHelpFailed { + String version = registerar.getVersion(); + assertNotNull(version); + } + + @Test + public void listTest() { + registerar.listCommands(); + } + + @Test + public void testProfile() throws OnapCommandException { + try { + OnapCommandRegistrar.getRegistrar().setProfile("test"); + OnapCommandRegistrar.getRegistrar().addParamCache("a", "b"); + OnapCommandRegistrar.getRegistrar().getParamCache(); + OnapCommandRegistrar.getRegistrar().removeParamCache("a"); + + OnapCommandRegistrar.getRegistrar().setInteractiveMode(false); + assertTrue(!OnapCommandRegistrar.getRegistrar().isInteractiveMode()); + + OnapCommandRegistrar.getRegistrar().setEnabledProductVersion("open-cli"); + assertEquals("open-cli", OnapCommandRegistrar.getRegistrar().getEnabledProductVersion()); + OnapCommandRegistrar.getRegistrar().getAvailableProductVersions(); + assertTrue(OnapCommandRegistrar.getRegistrar().listCommandsForEnabledProductVersion().contains("sample-test")); + + assertTrue(OnapCommandRegistrar.getRegistrar().listCommandInfo().size() > 2); + } catch (Exception e) { + fail("failed to test the profile"); + } + } + + + @Test + public void test() throws OnapCommandException { + OnapCommandRegistrar registrar = OnapCommandRegistrar.getRegistrar(); + OnapCommand cmd = registrar.get("sample-test"); + cmd.printVersion(); + registrar.listCommands(); + } +} + +@OnapCommandSchema(schema = "sample-test-schema.yaml") +class OnapCommandTest extends OnapCommand { + + public OnapCommandTest() { + + } + + public static final String CMD_NAME = "test"; + + protected void run() throws OnapCommandException { + + } + +} + +@OnapCommandSchema(schema = "test-schema.yaml") +class OnapCommandTest1 extends OnapCommand { + + public OnapCommandTest1() { + + } + + public static final String CMD_NAME = "test1"; + + protected void run() throws OnapCommandException { + + } + +} diff --git a/framework/src/test/java/org/onap/cli/fw/schema/ValidateSchemaTest.java b/framework/src/test/java/org/onap/cli/fw/schema/ValidateSchemaTest.java index a900fe6d..8153b6db 100644 --- a/framework/src/test/java/org/onap/cli/fw/schema/ValidateSchemaTest.java +++ b/framework/src/test/java/org/onap/cli/fw/schema/ValidateSchemaTest.java @@ -21,11 +21,9 @@ import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.cmd.OnapHttpCommand; +import org.onap.cli.fw.cmd.OnapCommand; import org.onap.cli.fw.error.OnapCommandException; import org.onap.cli.fw.error.OnapCommandInvalidSchema; -import org.onap.cli.fw.utils.OnapCommandSchemaLoaderUtils; public class ValidateSchemaTest { @@ -36,7 +34,7 @@ public class ValidateSchemaTest { @Override protected void run() throws OnapCommandException {} }; - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "fdsfds.yaml", true, true); + OnapCommandSchemaLoader.loadSchema(cmd, "fdsfds.yaml", true, true); } @Test(expected = OnapCommandInvalidSchema.class) @@ -45,7 +43,7 @@ public class ValidateSchemaTest { @Override protected void run() throws OnapCommandException {} }; - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "fdsfds", true, true); + OnapCommandSchemaLoader.loadSchema(cmd, "fdsfds", true, true); } @Test(expected = OnapCommandInvalidSchema.class) @@ -54,7 +52,7 @@ public class ValidateSchemaTest { @Override protected void run() throws OnapCommandException {} }; - OnapCommandSchemaLoaderUtils.loadSchema(cmd, + OnapCommandSchemaLoader.loadSchema(cmd, ValidateSchemaTest.class.getClassLoader().getResource("open-cli.properties").getFile(), true, true); } @@ -65,7 +63,7 @@ public class ValidateSchemaTest { @Override protected void run() throws OnapCommandException {} }; - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "schema-invalid-file-null.yaml", true, true); + OnapCommandSchemaLoader.loadSchema(cmd, "schema-invalid-file-null.yaml", true, true); } @Test @@ -74,7 +72,7 @@ public class ValidateSchemaTest { @Override protected void run() throws OnapCommandException {} }; - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "schema-validate-pass.yaml", true, true); + OnapCommandSchemaLoader.loadSchema(cmd, "schema-validate-pass.yaml", true, true); } @@ -84,49 +82,32 @@ public class ValidateSchemaTest { @Override protected void run() throws OnapCommandException {} }; - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "schema-invalid-file.yaml", true, true); + OnapCommandSchemaLoader.loadSchema(cmd, "schema-invalid-file.yaml", true, true); } @Test public void validateTest() throws OnapCommandException { - OnapCommand cmd1 = new OnapCommand() { - @Override - protected void run() throws OnapCommandException {} - }; - List errorList1 = OnapCommandSchemaLoaderUtils.loadSchema(cmd1, "schema-validate-http.yaml", true, true); - assertTrue(errorList1.size() > 0); - OnapCommand cmd2 = new OnapCommand() { @Override protected void run() throws OnapCommandException {} }; - List errorList2 = OnapCommandSchemaLoaderUtils.loadSchema(cmd2, "schema-validate-basic.yaml", true, true); + List errorList2 = OnapCommandSchemaLoader.loadSchema(cmd2, "schema-validate-basic.yaml", true, true); assertTrue(errorList2.size() > 0); OnapCommand cmd3 = new OnapCommand() { @Override protected void run() throws OnapCommandException {} }; - List errorList3 = OnapCommandSchemaLoaderUtils.loadSchema(cmd2, "schema-validate-invalidschematype.yaml", true, true); + List errorList3 = OnapCommandSchemaLoader.loadSchema(cmd2, "schema-validate-invalidschematype.yaml", true, true); assertTrue(errorList3.size() > 0); - OnapCommand cmd4 = new OnapCommand() { - @Override - protected void run() throws OnapCommandException {} - }; - List errorList4 = OnapCommandSchemaLoaderUtils.loadSchema(cmd2, "schema-validate-invalid.yaml", true, true); - - OnapHttpCommand oclipHttpCommand = new OnapHttpCommand(); - errorList4.addAll(OnapCommandSchemaLoaderUtils.loadHttpSchema(oclipHttpCommand, - "schema-validate-invalid.yaml", true, true)); - assertTrue(errorList4.size() > 0); OnapCommand cmd5 = new OnapCommand() { @Override protected void run() throws OnapCommandException {} }; - List errorList5 = OnapCommandSchemaLoaderUtils.loadSchema(cmd5, "schema-validate-pass.yaml", true, true); + List errorList5 = OnapCommandSchemaLoader.loadSchema(cmd5, "schema-validate-pass.yaml", true, true); assertTrue(errorList5.size() == 0); } 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 8cac03bf..317920f8 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 @@ -23,9 +23,7 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; -import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -35,29 +33,20 @@ import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; import org.junit.runners.MethodSorters; -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.OnapCommandSchema; -import org.onap.cli.fw.cmd.OnapHttpCommand; +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.error.OnapCommandHttpHeaderNotFound; -import org.onap.cli.fw.error.OnapCommandHttpInvalidResponseBody; -import org.onap.cli.fw.error.OnapCommandInvalidParameterType; -import org.onap.cli.fw.error.OnapCommandInvalidPrintDirection; -import org.onap.cli.fw.error.OnapCommandInvalidResultAttributeScope; import org.onap.cli.fw.error.OnapCommandInvalidSchema; import org.onap.cli.fw.error.OnapCommandInvalidSchemaVersion; import org.onap.cli.fw.error.OnapCommandParameterNameConflict; -import org.onap.cli.fw.error.OnapCommandParameterNotFound; import org.onap.cli.fw.error.OnapCommandParameterOptionConflict; import org.onap.cli.fw.error.OnapCommandSchemaNotFound; -import org.onap.cli.fw.http.HttpInput; -import org.onap.cli.fw.http.HttpResult; import org.onap.cli.fw.info.OnapCommandInfo; import org.onap.cli.fw.input.OnapCommandParameter; -import org.onap.cli.fw.input.ParameterType; import org.onap.cli.fw.output.OnapCommandResult; -import org.springframework.core.io.Resource; +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; @@ -65,21 +54,9 @@ import mockit.MockUp; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class OnapCommandUtilsTest { - - @Test(expected = OnapCommandInvalidSchema.class) - public void oclipCommandUtilsInputStreamNullTest() throws OnapCommandException { - OnapCommandSchemaLoaderUtils.validateSchemaVersion("sample-test1-schema-http1.yaml", "1.0"); - } - - @Test - public void oclipCommandUtilsInputStreamNotNullTest() throws OnapCommandException { - Map map = OnapCommandSchemaLoaderUtils.validateSchemaVersion("sample-test1-schema-http.yaml", "1.0"); - assertTrue(map != null); - } - @Test public void externalSchemaTest() { - SchemaInfo schema = new SchemaInfo(); + OnapCommandSchemaInfo schema = new OnapCommandSchemaInfo(); schema.setCmdName("cmdName"); schema.setSchemaName("schemaName"); schema.setVersion("version"); @@ -91,7 +68,7 @@ public class OnapCommandUtilsTest { @Test public void schemaFileNotFoundTest() throws OnapCommandException { - Map map = OnapCommandSchemaLoaderUtils.validateSchemaVersion("sample-test-schema.yaml", "1.0"); + Map map = OnapCommandSchemaLoader.validateSchemaVersion("sample-test-schema.yaml", "1.0"); assertTrue(map.size() > 0); } @@ -100,7 +77,7 @@ public class OnapCommandUtilsTest { public void invalidSchemaFileTest() throws OnapCommandException { Map map = null; try { - map = OnapCommandSchemaLoaderUtils.validateSchemaVersion("sample-test-schema1.yaml", "1.0"); + map = OnapCommandSchemaLoader.validateSchemaVersion("sample-test-schema1.yaml", "1.0"); } catch (OnapCommandInvalidSchemaVersion e) { fail("Test should not have thrown this exception : " + e.getMessage()); } catch (OnapCommandInvalidSchema e) { @@ -114,7 +91,7 @@ public class OnapCommandUtilsTest { public void validateWrongSchemaVersionTest() throws OnapCommandException { Map map = null; try { - map = OnapCommandSchemaLoaderUtils.validateSchemaVersion("sample-test-invalid-schema.yaml", "1.0"); + map = OnapCommandSchemaLoader.validateSchemaVersion("sample-test-invalid-schema.yaml", "1.0"); } catch (OnapCommandInvalidSchemaVersion e) { fail("Test should not have thrown this exception : " + e.getMessage()); } catch (OnapCommandInvalidSchema e) { @@ -128,7 +105,7 @@ public class OnapCommandUtilsTest { public void validateSchemaVersionTest() throws OnapCommandException { Map map = null; try { - map = OnapCommandSchemaLoaderUtils.validateSchemaVersion("sample-test-schema.yaml", "1.1"); + map = OnapCommandSchemaLoader.validateSchemaVersion("sample-test-schema.yaml", "1.1"); } catch (OnapCommandInvalidSchemaVersion e) { assertEquals("0xb003::Command schema open_cli_schema_version 1.0 is invalid or missing", e.getMessage()); } catch (OnapCommandInvalidSchema e) { @@ -141,32 +118,32 @@ public class OnapCommandUtilsTest { @Test public void loadOnapCommandSchemaWithOutDefaultTest() throws OnapCommandException { OnapCommand cmd = new OnapCommandSample(); - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "sample-test-schema.yaml", false, false); + OnapCommandSchemaLoader.loadSchema(cmd, "sample-test-schema.yaml", false, false); assertTrue("sample-test".equals(cmd.getName()) && cmd.getParameters().size() == 9); } @Test(expected = OnapCommandParameterNameConflict.class) public void loadOnapCommandSchemaWithDuplicateNameTest() throws OnapCommandException { OnapCommand cmd = new OnapCommandSample(); - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "sample-test-invalid-schema-duplicate-name.yaml", false, false); + OnapCommandSchemaLoader.loadSchema(cmd, "sample-test-invalid-schema-duplicate-name.yaml", false, false); } @Test(expected = OnapCommandParameterOptionConflict.class) public void loadOnapCommandSchemaWithDuplicateShortOptionTest() throws OnapCommandException { OnapCommand cmd = new OnapCommandSample(); - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "sample-test-invalid-schema-duplicate-shortoption.yaml", false, false); + OnapCommandSchemaLoader.loadSchema(cmd, "sample-test-invalid-schema-duplicate-shortoption.yaml", false, false); } @Test(expected = OnapCommandParameterOptionConflict.class) public void loadOnapCommandSchemaWithDuplicateLongOptionTest() throws OnapCommandException { OnapCommand cmd = new OnapCommandSample(); - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "sample-test-invalid-schema-duplicate-longoption.yaml", false, false); + OnapCommandSchemaLoader.loadSchema(cmd, "sample-test-invalid-schema-duplicate-longoption.yaml", false, false); } @Test public void loadOnapCommandSchemaWithDefaultTest() throws OnapCommandException { OnapCommand cmd = new OnapCommandSample(); - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "sample-test-schema.yaml", true, false); + OnapCommandSchemaLoader.loadSchema(cmd, "sample-test-schema.yaml", true, false); assertTrue("sample-test".equals(cmd.getName()) && cmd.getParameters().size() > 9); for (OnapCommandParameter com : cmd.getParameters()) { @@ -177,49 +154,11 @@ public class OnapCommandUtilsTest { assertTrue(map.size() == 15); } - @Test - public void loadOnapCommandSchemaAuthRequiredTest() throws OnapCommandException { - OnapCommand cmd = new OnapCommandSample(); - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "sample-test-schema-auth-required.yaml", true, false); - assertTrue("sample-test".equals(cmd.getName())); - - Map map = OnapCommandUtils.getInputMap(cmd.getParameters()); - assertTrue(map.size() == 7); - } - - @Test - public void loadHttpBasedSchemaExceptionTest() throws OnapCommandException { - OnapHttpCommand cmd = new OnapHttpCommandSample(); - cmd.setName("sample-test-http"); - try { - OnapCommandSchemaLoaderUtils.loadHttpSchema(cmd, "sample-test-schema.yaml", true, false); - } catch (OnapCommandParameterNameConflict | OnapCommandParameterOptionConflict - | OnapCommandInvalidParameterType | OnapCommandInvalidPrintDirection - | OnapCommandInvalidResultAttributeScope | OnapCommandSchemaNotFound | OnapCommandInvalidSchema - | OnapCommandInvalidSchemaVersion e) { - assertTrue(e.getMessage().contains("0xb001::Command schema sample-test-schema.yaml is invalid")); - } - } - - @Test - public void loadHttpBasedSchemaTest() throws OnapCommandException { - OnapHttpCommand cmd = new OnapHttpCommandSample(); - cmd.setName("sample-create-http"); - try { - OnapCommandSchemaLoaderUtils.loadHttpSchema(cmd, "sample-test-schema-http.yaml", true, true); - assertTrue(cmd.getSuccessStatusCodes().size() == 2); - } catch (OnapCommandParameterNameConflict | OnapCommandParameterOptionConflict - | OnapCommandInvalidParameterType | OnapCommandInvalidPrintDirection - | OnapCommandInvalidResultAttributeScope | OnapCommandSchemaNotFound | OnapCommandInvalidSchema - | OnapCommandInvalidSchemaVersion e) { - fail("Test should not have thrown this exception : " + e.getMessage()); - } - } @Test public void helpCommandTest() throws IOException, OnapCommandException { OnapCommand cmd = new OnapCommandSample(); - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "sample-test-schema.yaml", true, false); + OnapCommandSchemaLoader.loadSchema(cmd, "sample-test-schema.yaml", true, false); String actualResult = OnapCommandHelperUtils.help(cmd); @@ -231,7 +170,7 @@ public class OnapCommandUtilsTest { @Test public void findOnapCommandsTest() { List> cmds = OnapCommandDiscoveryUtils.discoverCommandPlugins(); - assertTrue(cmds.size() == 7); + assertTrue(cmds.size() == 3); } @Test @@ -264,105 +203,12 @@ public class OnapCommandUtilsTest { } - @Test - public void formMethodNameFromAttributeTest() { - - String str = ""; - String name = OnapCommandUtils.formMethodNameFromAttributeName(str, "test"); - - assertEquals("", name); - - str = null; - name = OnapCommandUtils.formMethodNameFromAttributeName(str, "test"); - - assertEquals(null, name); - - str = "test-get"; - name = OnapCommandUtils.formMethodNameFromAttributeName(str, ""); - assertEquals("TestGet", name); - - } - - @Test - public void populateParametersTest() throws OnapCommandException { - - HttpInput input = new HttpInput(); - input.setBody("body"); - input.setMethod("method"); - Map mapHead = new HashMap<>(); - mapHead.put("key2", "${value2}"); - input.setReqHeaders(mapHead); - Map query = new HashMap<>(); - query.put("key3", "{${value3}}"); - input.setReqQueries(query); - input.setUri("uri"); - - Map params = new HashMap<>(); - OnapCommandParameter param = new OnapCommandParameter(); - param.setDefaultValue("defaultValue2"); - param.setParameterType(ParameterType.STRING); - params.put("value2", param); - OnapCommandParameter param1 = new OnapCommandParameter(); - param1.setDefaultValue("{\"defaultValue3\"}"); - param1.setParameterType(ParameterType.JSON); - params.put("value3", param1); - - HttpInput input1 = OnapCommandUtils.populateParameters(params, input); - String expected = "\nURL: uri\nMethod: method\nRequest Queries: {key3={\"defaultValue3\"}}\n" - + "Request Body: body\nRequest Headers: {key2=defaultValue2}\nRequest Cookies: {}\nbinaryData=false"; - assertEquals(expected, input1.toString()); - - input.setBody("${body}"); - - HttpInput input2 = null; - try { - input2 = OnapCommandUtils.populateParameters(params, input); - } catch (OnapCommandParameterNotFound e) { - assertEquals("0x7005::Command input parameter body is not valid", e.getMessage()); - } - - } - - @Test(expected = OnapCommandHttpHeaderNotFound.class) - public void populateOutputsTest() throws OnapCommandException { - HttpResult output = new HttpResult(); - output.setBody( - "{\"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\"}"); - Map mapHead = new HashMap<>(); - mapHead.put("head1", "value1"); - output.setRespHeaders(mapHead); - output.setStatus(0); - - Map params = new HashMap<>(); - params.put("head", "$h{head1}"); - params.put("body", "$b{$.serviceName}"); - params.put("key", "value"); - - Map> input1 = OnapCommandUtils.populateOutputs(params, output); - assertEquals("{head=[value1], body=[test], key=[value]}", input1.toString()); - - params.put("body", "$b{{$.serviceName}"); - try { - input1 = OnapCommandUtils.populateOutputs(params, output); - } catch (OnapCommandHttpInvalidResponseBody e) { - assertEquals( - "0x3004::Http response body does not have json entry {$.serviceName, Missing property in path $['{$']", - e.getMessage()); - } - output.setBody("{}"); - input1 = OnapCommandUtils.populateOutputs(params, output); - params.put("head", "$h{head2}"); - output.setBody("{\"test\"}"); - input1 = OnapCommandUtils.populateOutputs(params, output); - } - - @Test(expected = OnapCommandHelpFailed.class) public void zendExceptionHelpTest1() throws OnapCommandException { mockPrintMethodException(); OnapCommand cmd = new OnapCommandSample(); - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "sample-test-schema.yaml", true, false); + OnapCommandSchemaLoader.loadSchema(cmd, "sample-test-schema.yaml", true, false); OnapCommandHelperUtils.help(cmd); @@ -372,7 +218,7 @@ public class OnapCommandUtilsTest { @Test public void test() throws OnapCommandException { OnapCommandSampleInfo cmd = new OnapCommandSampleInfo(); - OnapCommandSchemaLoaderUtils.loadSchema(cmd, "sample-test-info.yaml", true, false); + OnapCommandSchemaLoader.loadSchema(cmd, "sample-test-info.yaml", true, false); OnapCommandInfo info = cmd.getInfo(); assert info != null; } @@ -391,30 +237,6 @@ public class OnapCommandUtilsTest { } } - @OnapCommandSchema(schema = "sample-test-schema-http.yaml") - class OnapHttpCommandSample extends OnapHttpCommand { - - @Override - protected void run() throws OnapCommandException { - } - } - - private void mockExternalResources() { - new MockUp() { - boolean isMock = true; - - @Mock - public Resource[] getExternalResources(Invocation inv, String pattern) throws IOException { - if (isMock) { - isMock = false; - throw new IOException(); - } else { - return inv.proceed(pattern); - } - } - }; - } - private void mockPrintMethodException() { new MockUp() { boolean isMock = true; diff --git a/framework/src/test/java/org/onap/cli/fw/utils/OpenCommandRegistrarTest.java b/framework/src/test/java/org/onap/cli/fw/utils/OpenCommandRegistrarTest.java deleted file mode 100644 index 648746ca..00000000 --- a/framework/src/test/java/org/onap/cli/fw/utils/OpenCommandRegistrarTest.java +++ /dev/null @@ -1,41 +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.fw.utils; - -import org.junit.Before; -import org.junit.Test; -import org.onap.cli.fw.OnapCommand; -import org.onap.cli.fw.OnapCommandRegistrar; -import org.onap.cli.fw.error.OnapCommandException; - - -public class OpenCommandRegistrarTest { - - @Before - public void setUp() throws Exception { - - } - - @Test - public void test() throws OnapCommandException { - OnapCommandRegistrar registrar = OnapCommandRegistrar.getRegistrar(); - OnapCommand cmd = registrar.get("sample-test"); - cmd.printVersion(); - registrar.listCommands(); - } - -} diff --git a/framework/src/test/resources/META-INF/services/org.onap.cli.fw.OnapCommand b/framework/src/test/resources/META-INF/services/org.onap.cli.fw.OnapCommand deleted file mode 100644 index a01b9d53..00000000 --- a/framework/src/test/resources/META-INF/services/org.onap.cli.fw.OnapCommand +++ /dev/null @@ -1 +0,0 @@ -org.onap.cli.cmd.sample.OnapCommandSample \ No newline at end of file diff --git a/framework/src/test/resources/META-INF/services/org.onap.cli.fw.cmd.OnapCommand b/framework/src/test/resources/META-INF/services/org.onap.cli.fw.cmd.OnapCommand new file mode 100644 index 00000000..a01b9d53 --- /dev/null +++ b/framework/src/test/resources/META-INF/services/org.onap.cli.fw.cmd.OnapCommand @@ -0,0 +1 @@ +org.onap.cli.cmd.sample.OnapCommandSample \ No newline at end of file diff --git a/framework/src/test/resources/open-cli-schema/sample-test1-schema-http.yaml b/framework/src/test/resources/open-cli-schema/sample-test1-schema-http.yaml deleted file mode 100644 index f162231f..00000000 --- a/framework/src/test/resources/open-cli-schema/sample-test1-schema-http.yaml +++ /dev/null @@ -1,95 +0,0 @@ -open_cli_schema_version: 1.0 -name: sample-test1 -description: Oclip sample command to test the command features - -info: - product: open-cli - service: test - type: cmd - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com - -parameters: - - name: bool-param - type: bool - description: Oclip boolean param, by default its always false. - short_option: b - long_option: bool - is_optional: true - default_value: false - - name: secure-param - type: string - description: Oclip secure param such as password - short_option: x - long_option: secure - is_secured: true - is_optional: false - default_Value: pass123# - - name: string-param - type: string - description: Oclip string param - long_option: string-param - short_option: c - is_optional: false - default_Value: test - - name: yaml-param - type: json - description: Oclip yaml file location param - long_option: yaml-param - short_option: y - is_optional: false - - name: json-param - type: json - description: Oclip json file location param - long_option: json-param - short_option: j - is_optional: false - - name: long-param - type: digit - description: Oclip long param - short_option: l - long_option: long-opt - is_optional: false - default_value: 10 - - name: url-param - type: url - description: Oclip url param - short_option: r - long_option: url - is_optional: false - default_value: http://localhost:8082/file.txt - - name: env-param - type: string - description: Oclip env param. - short_option: z - long_option: env - is_optional: false - default_value: ${ENV_VAR} - - name: positional-args - type: string - description: Oclip positional args, if no short option and no long option given for it - is_optional: false - default_value: http://localhost:8082/file.txt -http: - request: - uri: /vims - 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: - success_codes: - - 201 - - 200 - result_map: - id: $b{$.vimId} - name: $b{$.name} - vendor: $b{$.vendor} - type: $b{$.type} - version: $b{$.version} - url: $b{$.url} - description: $b{$.description} - username: $b{$.userName} - password: $b{$.password} - domain: $b{$.domain} - tenant: $b{$.tenant} - create-time: $b{$.createTime} - sample_response: - body:'{"id":"string","name":"string","vendor":"string","version":"string","description":"string","type":"string","createTime":"string","url":"string","userName":"string","password":"string","domain":"string","tenant":"string"}' \ No newline at end of file diff --git a/framework/src/test/resources/open-cli-schema/testauth-login.yaml b/framework/src/test/resources/open-cli-schema/testauth-login.yaml deleted file mode 100644 index 3e9211ef..00000000 --- a/framework/src/test/resources/open-cli-schema/testauth-login.yaml +++ /dev/null @@ -1,28 +0,0 @@ -open_cli_schema_version: 1.0 - -name: testauth-login - -description: basic login auth command - -info: - product: open-cli - service: test - type: auth - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com - -parameters: - - name: string-param - type: string - description: Oclip string param - long_option: string-param - short_option: c - is_optional: false - default_Value: test - -# followings are dummy simulator for http command -http: - request: - uri: / - method: GET - success_codes: - - 200 diff --git a/framework/src/test/resources/open-cli-schema/testauth-logout.yaml b/framework/src/test/resources/open-cli-schema/testauth-logout.yaml deleted file mode 100644 index dfe33638..00000000 --- a/framework/src/test/resources/open-cli-schema/testauth-logout.yaml +++ /dev/null @@ -1,19 +0,0 @@ -open_cli_schema_version: 1.0 - -name: testauth-logout - -description: basic logout auth command - -info: - product: open-cli - service: test - type: auth - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com - -# followings are dummy simulator for http command -http: - request: - uri: / - method: GET - success_codes: - - 200 \ No newline at end of file diff --git a/framework/src/test/resources/open-cli.properties b/framework/src/test/resources/open-cli.properties deleted file mode 100644 index 23ba7800..00000000 --- a/framework/src/test/resources/open-cli.properties +++ /dev/null @@ -1,39 +0,0 @@ -cli.ignore_auth=false -cli.http.api_key_use_cookies=true -cli.discover_always=true -cli.product_name=open-cli -cli.version=1.0 - -#schema validation -cli.schema.top_level_params_list=open_cli_schema_version,name,description,parameters,results,http,info -cli.schema.top_level_mandatory_list=open_cli_schema_version - -cli.schema.info_params_list=product,service,type,author,ignore -cli.schema.info_params_mandatory_list=product,service - -cli.schema.input_params_list=name,description,type,short_option,long_option, is_optional,default_value,is_secured,is_include -cli.schema.input_params_mandatory_list=name,description,type - -cli.schema.result_params_list=name,description,scope,type,is_secured, default_value -cli.schema.result_params_mandatory_list=name, description, type, scope - -#http -cli.schema.http_sections=request,service,success_codes,result_map,sample_response -cli.schema.http_mandatory_sections=request, success_codes - -cli.schema.http_request_params=uri,method,body,headers,queries,multipart_entity_name -cli.schema.http_request_mandatory_params=uri,method - -cli.schema.service_params_list=name,version,auth,mode -cli.schema.service_params_mandatory_list=auth,mode - -cli.schema.http_methods=post,get,delete,put,head - -cli.schema.boolean_values=true,false -cli.schema.auth_values=none,basic -cli.schema.mode_values=direct,catalog -cli.command.type=cmd,auth,catalog - -# mrkanag Move this to db, once exteranl command registration is supported in place of discovery -cli.schema.type.supported=http - diff --git a/framework/src/test/resources/sample-test-schema-auth-required.yaml b/framework/src/test/resources/sample-test-schema-auth-required.yaml deleted file mode 100644 index bb919d9a..00000000 --- a/framework/src/test/resources/sample-test-schema-auth-required.yaml +++ /dev/null @@ -1,16 +0,0 @@ -open_cli_schema_version: 1.0 -name: sample-test -description: Oclip sample command to test the command features -info: - product: open-cli - service: test - type: cmd - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com -parameters: - - name: bool-param - type: bool - description: Oclip boolean param, by default its always false. - short_option: b - long_option: bool - is_optional: true - default_value: false \ No newline at end of file diff --git a/framework/src/test/resources/sample-test-schema-http.yaml b/framework/src/test/resources/sample-test-schema-http.yaml deleted file mode 100644 index 4ae6e9e0..00000000 --- a/framework/src/test/resources/sample-test-schema-http.yaml +++ /dev/null @@ -1,92 +0,0 @@ -open_cli_schema_version: 1.0 -name: sample-create-http -description: Register microservice into Onap -info: - product: open-cli - service: test - type: cmd - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com -parameters: - - name: service-name - description: Oclip service name - type: string - short_option: x - long_option: service-name - is_optional: false - - name: service-version - description: Oclip service version - type: string - short_option: y - long_option: service-version - is_optional: false - - name: service-url - description: Oclip service base url - type: url - short_option: r - long_option: service-url - is_optional: false - - name: status - description: Oclip service status - type: digit - short_option: z - long_option: service-status - is_optional: true - default_value: 1 - - name: node-ip - description: Oclip service running node IP - type: string - - name: node-port - description: Oclip service running node port - type: string - - name: create-or-update - description: Oclip service create or update - type: bool - default_value: true -results: - direction: portrait - attributes: - - name: name - description: Oclip service name - scope: short - type: string - - name: version - description: Oclip service version - scope: short - type: string - - name: url - description: Oclip service base url - scope: short - type: url - - name: status - description: Oclip service status - scope: short - type: digit - - name: nodes - description: Oclip service running nodes - scope: long - type: string - - name: location - description: Oclip service location - scope: long - type: url -http: - request: - uri: /services - method: POST - body: '{"serviceName":"${service-name}","version":"${service-version}","url":"${service-url}","protocol":"REST","visualRange":"1","lb_policy":"hash","nodes":[{"ip":"${node-ip}","port":"${node-port}","ttl":0}]}' - headers: - queries: - createOrUpdate: ${create-or-update} - success_codes: - - 201 - - 200 - result_map: - name: $b{$.serviceName} - version: $b{$.version} - url: $b{$.url} - status: $b{$.status} - nodes: $b{$.nodes[*].ip}:$b{$.nodes[*].port} - location: $h{Location} - - 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"} \ No newline at end of file diff --git a/framework/src/test/resources/sample-test-schema-no-auth-no-catalog.yaml b/framework/src/test/resources/sample-test-schema-no-auth-no-catalog.yaml deleted file mode 100644 index 2629a2f9..00000000 --- a/framework/src/test/resources/sample-test-schema-no-auth-no-catalog.yaml +++ /dev/null @@ -1,26 +0,0 @@ -open_cli_schema_version: 1.0 - -name: sample-cmd-no-auth-no-catalog - -description: sample - -info: - product: open-cli - service: test - type: cmd - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com - -http: - - service: - name: sample - version: v1 - auth: none - mode: direct - request: - uri: /test - method: GET - success_codes: - - 200 - result_map: - name: ${name} diff --git a/framework/src/test/resources/sample-test-schema-no-auth-yes-catalog.yaml b/framework/src/test/resources/sample-test-schema-no-auth-yes-catalog.yaml deleted file mode 100644 index 15b5bf0c..00000000 --- a/framework/src/test/resources/sample-test-schema-no-auth-yes-catalog.yaml +++ /dev/null @@ -1,28 +0,0 @@ -open_cli_schema_version: 1.0 - -name: sample-cmd-no-auth-no-catalog - -description: sample - - -info: - product: open-cli - service: test - type: cmd - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com - -http: - - service: - name: sample - version: v1 - auth: none - mode: catalog - - request: - uri: /test - method: GET - success_codes: - - 200 - result_map: - name: ${name} diff --git a/framework/src/test/resources/sample-test-schema-swagger.yaml b/framework/src/test/resources/sample-test-schema-swagger.yaml deleted file mode 100644 index 4108d4e6..00000000 --- a/framework/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/framework/src/test/resources/sample-test-schema-yes-auth-no-catalog.yaml b/framework/src/test/resources/sample-test-schema-yes-auth-no-catalog.yaml deleted file mode 100644 index bb0ae46b..00000000 --- a/framework/src/test/resources/sample-test-schema-yes-auth-no-catalog.yaml +++ /dev/null @@ -1,26 +0,0 @@ -open_cli_schema_version: 1.0 - -name: sample-cmd-yes-auth-no-catalog - -description: sample - -info: - product: open-cli - service: test - type: cmd - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com - -http: - - service: - name: sample - version: v1 - auth: basic - mode: direct - request: - uri: /test - method: GET - success_codes: - - 200 - result_map: - name: ${name} diff --git a/framework/src/test/resources/sample-test-schema-yes-auth-with-additional-params-no-catalog.yaml b/framework/src/test/resources/sample-test-schema-yes-auth-with-additional-params-no-catalog.yaml deleted file mode 100644 index a5a39f92..00000000 --- a/framework/src/test/resources/sample-test-schema-yes-auth-with-additional-params-no-catalog.yaml +++ /dev/null @@ -1,28 +0,0 @@ -open_cli_schema_version: 1.0 - -name: sample-cmd-yes-auth-no-catalog-extra-params - -description: sample - - -info: - product: open-cli - service: test - type: cmd - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com - -http: - - service: - name: sample - version: v1 - auth: testauth - mode: catalog - - request: - uri: /test - method: GET - success_codes: - - 200 - result_map: - name: ${name} diff --git a/framework/src/test/resources/sample-test-schema-yes-auth-yes-catalog.yaml b/framework/src/test/resources/sample-test-schema-yes-auth-yes-catalog.yaml deleted file mode 100644 index 4efd4c51..00000000 --- a/framework/src/test/resources/sample-test-schema-yes-auth-yes-catalog.yaml +++ /dev/null @@ -1,28 +0,0 @@ -open_cli_schema_version: 1.0 - -name: sample-cmd-no-auth-no-catalog - -description: sample - - -info: - product: open-cli - service: test - type: cmd - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com - -http: - - service: - name: sample - version: v1 - auth: basic - mode: catalog - - request: - uri: /test - method: GET - success_codes: - - 200 - result_map: - name: ${name} diff --git a/framework/src/test/resources/schema-validate-http.yaml b/framework/src/test/resources/schema-validate-http.yaml deleted file mode 100644 index 7bdafc56..00000000 --- a/framework/src/test/resources/schema-validate-http.yaml +++ /dev/null @@ -1,98 +0,0 @@ -open_cli_schema_version: 1.0 -description: Register microservice into Onap -name: schema-validate -info: - product: open-cli - service: test - type: cmd - author: Kanagaraj Manickam kanagaraj.manickam@huawei.com - -parameters: - - name: service-name1 - description: Oclip service name - type: string - short_option: x - long_option: service-name - is_optional: false - - name: service-version - description: Oclip service version - type: string - short_option: x - long_option: service-version - is_optional: false - - name: service-url - description: Oclip service base url - type: url1 - short_option: u - long_option: service-url - is_optional: false1 - - name: status - description: Oclip service status - type: digit - short_option: z - long_option: service-version - is_optional: true - default_value: 1 - - name: node-ip - description: Oclip service running node IP - type: string - - name: node-port - description: Oclip service running node port - type: string - - name: create-or-update - description: Oclip service create or update - type: cfbcv - default_value: true -results: - direction: portrait - attributes: - - name: name - description: Oclip service name - scope: short - type: string - - name: version - description: Oclip service version - scope: short - type: string - - name: status - description: Oclip service base url - scope: short - type: url - - name: status - description: Oclip service status - scope: short1 - type: digit - - name: nodes - description: Oclip service running nodes - scope: long - type: string - - name: location - description: Oclip service location - scope: long - type: url -http: - service: - name: msb - version: v1 - type: direct - auth: none - request: - uri: /services - method: POST1 - body: '{"serviceName":"${service}","serviceName":"${service-name}","version":"${service-version}","url":"${service-url}","protocol":"REST","visualRange":"1","lb_policy":"hash","nodes":[{"ip":"${node-ip}","port":"${node-port}","ttl":0}]}' - headers: - queries: - createOrUpdate: ${create-or-update1} - success_codes: - - 201 - - 300 - result_map: - name: $b{$.serviceName} - version: $b{$.version} - url: $b{$.url} - status1: $b{$.status} - nodes: $b{$.nodes[*].ip}:$b{$.nodes[*].port} - location: $h{Location} - 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"} - -- cgit 1.2.3-korg