aboutsummaryrefslogtreecommitdiffstats
path: root/framework/src/main/java
diff options
context:
space:
mode:
authorKanagaraj Manickam k00365106 <kanagaraj.manickam@huawei.com>2017-10-13 15:49:14 +0530
committerKanagaraj Manickam k00365106 <kanagaraj.manickam@huawei.com>2017-11-20 14:08:01 +0530
commitb7500cd5c7caef69f9d8689872eea01876c9fbba (patch)
tree4459532d3f0fd42e8c1275e4e58a920a3669475f /framework/src/main/java
parent89cf755a6e80c5ebd4bd989faad85aba60fc7b69 (diff)
Utils are splitted into multiple classes
Issue-Id: CLI-66 Change-Id: I334d9121fe19c25af00bd83a53260c43b7f5446e Signed-off-by: Kanagaraj Manickam k00365106 <kanagaraj.manickam@huawei.com>
Diffstat (limited to 'framework/src/main/java')
-rw-r--r--framework/src/main/java/org/onap/cli/fw/OnapCommand.java7
-rw-r--r--framework/src/main/java/org/onap/cli/fw/OnapCommandRegistrar.java12
-rw-r--r--framework/src/main/java/org/onap/cli/fw/cmd/OnapHttpCommand.java6
-rw-r--r--framework/src/main/java/org/onap/cli/fw/cmd/OnapSchemaRefreshCommand.java6
-rw-r--r--framework/src/main/java/org/onap/cli/fw/cmd/OnapSchemaValidateCommand.java6
-rw-r--r--framework/src/main/java/org/onap/cli/fw/error/OnapCommandInstantiationFailed.java38
-rw-r--r--framework/src/main/java/org/onap/cli/fw/input/cache/OnapCommandParameterCache.java6
-rw-r--r--framework/src/main/java/org/onap/cli/fw/utils/OnapCommandDiscoveryUtils.java302
-rw-r--r--framework/src/main/java/org/onap/cli/fw/utils/OnapCommandHelperUtils.java200
-rw-r--r--framework/src/main/java/org/onap/cli/fw/utils/OnapCommandProfileUtils.java72
-rw-r--r--framework/src/main/java/org/onap/cli/fw/utils/OnapCommandSchemaLoader.java686
-rw-r--r--framework/src/main/java/org/onap/cli/fw/utils/OnapCommandSchemaLoaderUtils.java708
-rw-r--r--framework/src/main/java/org/onap/cli/fw/utils/OnapCommandUtils.java499
13 files changed, 1344 insertions, 1204 deletions
diff --git a/framework/src/main/java/org/onap/cli/fw/OnapCommand.java b/framework/src/main/java/org/onap/cli/fw/OnapCommand.java
index 3dfb5c37..fe6adf25 100644
--- a/framework/src/main/java/org/onap/cli/fw/OnapCommand.java
+++ b/framework/src/main/java/org/onap/cli/fw/OnapCommand.java
@@ -39,7 +39,8 @@ 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.OnapCommandSchemaLoader;
+import org.onap.cli.fw.utils.OnapCommandHelperUtils;
+import org.onap.cli.fw.utils.OnapCommandSchemaLoaderUtils;
import org.onap.cli.fw.utils.OnapCommandUtils;
/**
@@ -157,7 +158,7 @@ public abstract class OnapCommand {
*/
public void initializeSchema(String schema) throws OnapCommandException {
this.setSchemaName(schema);
- OnapCommandSchemaLoader.loadSchema(this, schema, true, false);
+ OnapCommandSchemaLoaderUtils.loadSchema(this, schema, true, false);
this.initializeProfileSchema();
this.isInitialzied = true;
}
@@ -265,7 +266,7 @@ public abstract class OnapCommand {
* Failed to execute Help command.
*/
public String printHelp() throws OnapCommandHelpFailed {
- return OnapCommandUtils.help(this);
+ 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
index f42f68f9..b44279fb 100644
--- a/framework/src/main/java/org/onap/cli/fw/OnapCommandRegistrar.java
+++ b/framework/src/main/java/org/onap/cli/fw/OnapCommandRegistrar.java
@@ -42,6 +42,8 @@ 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;
@@ -178,7 +180,7 @@ public class OnapCommandRegistrar {
* exception
*/
public List<SchemaInfo> listCommandInfo() throws OnapCommandException {
- return OnapCommandUtils.discoverSchemas();
+ return OnapCommandDiscoveryUtils.discoverSchemas();
}
/**
@@ -208,7 +210,7 @@ public class OnapCommandRegistrar {
Constructor<?> constr = cls.getConstructor();
cmd = (OnapCommand) constr.newInstance();
- String schemaName = OnapCommandUtils.getSchemaInfo(cmdName, version).getSchemaName();
+ String schemaName = OnapCommandDiscoveryUtils.getSchemaInfo(cmdName, version).getSchemaName();
cmd.initializeSchema(schemaName);
} catch (OnapCommandException | NoSuchMethodException | SecurityException | InstantiationException
@@ -220,7 +222,7 @@ public class OnapCommandRegistrar {
}
private Map<String, Class<OnapCommand>> autoDiscoverCommandPlugins() throws OnapCommandException {
- List<Class<OnapCommand>> cmds = OnapCommandUtils.discoverCommandPlugins();
+ List<Class<OnapCommand>> cmds = OnapCommandDiscoveryUtils.discoverCommandPlugins();
Map<String, Class<OnapCommand>> map = new HashMap<>();
for (Class<OnapCommand> cmd : cmds) {
@@ -240,7 +242,7 @@ public class OnapCommandRegistrar {
}
private void autoDiscoverSchemas() throws OnapCommandException {
- List<SchemaInfo> schemas = OnapCommandUtils.discoverOrLoadSchemas();
+ List<SchemaInfo> schemas = OnapCommandDiscoveryUtils.discoverOrLoadSchemas();
Map<String, Class<OnapCommand>> plugins = this.autoDiscoverCommandPlugins();
@@ -266,7 +268,7 @@ public class OnapCommandRegistrar {
version = OnapCommandConfg.getVersion();
}
- String buildTime = OnapCommandUtils.findLastBuildTime();
+ String buildTime = OnapCommandHelperUtils.findLastBuildTime();
if (buildTime!= null && !buildTime.isEmpty()) {
buildTime = " [" + buildTime + "]";
} else {
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
index 01ce6247..11fc71f3 100644
--- a/framework/src/main/java/org/onap/cli/fw/cmd/OnapHttpCommand.java
+++ b/framework/src/main/java/org/onap/cli/fw/cmd/OnapHttpCommand.java
@@ -34,14 +34,14 @@ 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.OnapCommandSchemaLoader;
+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 Command.
+ * Oclip http Command.
*
*/
@OnapCommandSchema(type = Constants.HTTP_SCHEMA_PROFILE)
@@ -99,7 +99,7 @@ public class OnapHttpCommand extends OnapCommand {
@Override
protected void initializeProfileSchema() throws OnapCommandException {
- OnapCommandSchemaLoader.loadHttpSchema(this, this.getSchemaName(), true, false);
+ OnapCommandSchemaLoaderUtils.loadHttpSchema(this, this.getSchemaName(), true, false);
}
@Override
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 53d01a50..3319f03d 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
@@ -21,7 +21,7 @@ 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.utils.OnapCommandUtils;
+import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils;
import org.onap.cli.fw.utils.SchemaInfo;
/**
@@ -34,9 +34,9 @@ public class OnapSchemaRefreshCommand extends OnapCommand {
@Override
protected void run() throws OnapCommandException {
- List<SchemaInfo> schemas = OnapCommandUtils.discoverSchemas();
+ List<SchemaInfo> schemas = OnapCommandDiscoveryUtils.discoverSchemas();
// Will override the existing json file
- OnapCommandUtils.persistSchemaInfo(schemas);
+ OnapCommandDiscoveryUtils.persistSchemaInfo(schemas);
for (int i = 0; i < schemas.size(); i++) {
SchemaInfo schema = schemas.get(i);
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 c3088c53..15e3775a 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,7 +20,7 @@ import org.onap.cli.fw.OnapCommand;
import org.onap.cli.fw.OnapCommandSchema;
import org.onap.cli.fw.error.OnapCommandException;
import org.onap.cli.fw.input.OnapCommandParameter;
-import org.onap.cli.fw.utils.OnapCommandSchemaLoader;
+import org.onap.cli.fw.utils.OnapCommandSchemaLoaderUtils;
import java.util.ArrayList;
import java.util.List;
@@ -43,14 +43,14 @@ public class OnapSchemaValidateCommand extends OnapCommand {
location = location.substring(1);
}
- List<String> error = OnapCommandSchemaLoader.loadSchema(new OnapCommand() {
+ List<String> error = OnapCommandSchemaLoaderUtils.loadSchema(new OnapCommand() {
@Override
protected void run() throws OnapCommandException {
}
}, location, true, true);
- error.addAll(OnapCommandSchemaLoader.loadHttpSchema(new OnapHttpCommand(),
+ error.addAll(OnapCommandSchemaLoaderUtils.loadHttpSchema(new OnapHttpCommand(),
location, true, true));
List<String> slNumber = new ArrayList<>();
diff --git a/framework/src/main/java/org/onap/cli/fw/error/OnapCommandInstantiationFailed.java b/framework/src/main/java/org/onap/cli/fw/error/OnapCommandInstantiationFailed.java
new file mode 100644
index 00000000..ccc788d6
--- /dev/null
+++ b/framework/src/main/java/org/onap/cli/fw/error/OnapCommandInstantiationFailed.java
@@ -0,0 +1,38 @@
+/*
+ * 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 result initialization failed.
+ *
+ */
+public class OnapCommandInstantiationFailed extends OnapCommandException {
+
+ private static final long serialVersionUID = 8580121615330415456L;
+
+ private static final String ERROR_CODE = "0x6002";
+
+ private static final String ERROR_MSG = "Failed to instantiate the command plugin ";
+
+ public OnapCommandInstantiationFailed(String cmd) {
+ super(ERROR_CODE, ERROR_MSG + cmd);
+ }
+
+ public OnapCommandInstantiationFailed(String cmd, Exception e) {
+ super(ERROR_CODE, ERROR_MSG + cmd, e);
+ }
+}
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 32035737..0b70b5c1 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
@@ -24,7 +24,7 @@ import java.util.Map;
import org.onap.cli.fw.conf.Constants;
import org.onap.cli.fw.error.OnapCommandLoadProfileFailed;
import org.onap.cli.fw.error.OnapCommandPersistProfileFailed;
-import org.onap.cli.fw.utils.OnapCommandUtils;
+import org.onap.cli.fw.utils.OnapCommandProfileUtils;
public class OnapCommandParameterCache {
@@ -93,7 +93,7 @@ public class OnapCommandParameterCache {
}
try {
- OnapCommandUtils.persistProfile(params, this.profileName);
+ OnapCommandProfileUtils.persistProfile(params, this.profileName);
} catch (OnapCommandPersistProfileFailed e) {
throw new RuntimeException(e); // NOSONAR
}
@@ -102,7 +102,7 @@ public class OnapCommandParameterCache {
private void load() {
List<Param> params= new ArrayList<>();
try {
- params = OnapCommandUtils.loadParamFromCache(this.profileName);
+ params = OnapCommandProfileUtils.loadParamFromCache(this.profileName);
} catch (OnapCommandLoadProfileFailed e) {
throw new RuntimeException(e); // NOSONAR
}
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
new file mode 100644
index 00000000..69fd2ac4
--- /dev/null
+++ b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandDiscoveryUtils.java
@@ -0,0 +1,302 @@
+/*
+ * 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 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 java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.ServiceLoader;
+
+import org.onap.cli.fw.OnapCommand;
+import org.onap.cli.fw.conf.Constants;
+import org.onap.cli.fw.conf.OnapCommandConfg;
+import org.onap.cli.fw.error.OnapCommandDiscoveryFailed;
+import org.onap.cli.fw.error.OnapCommandException;
+import org.onap.cli.fw.error.OnapCommandInvalidSchema;
+import org.springframework.core.io.Resource;
+import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
+import org.springframework.core.io.support.ResourcePatternResolver;
+import org.yaml.snakeyaml.Yaml;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class OnapCommandDiscoveryUtils {
+
+ /**
+ * Fetch a particular schema details.
+ *
+ * @param cmd
+ * command name
+ * @return ExternalSchema obj
+ * @throws OnapCommandInvalidSchema
+ * exception
+ * @throws OnapCommandDiscoveryFailed
+ * exception
+ */
+ public static SchemaInfo getSchemaInfo(String cmd, String version) throws OnapCommandException {
+ List<SchemaInfo> list = OnapCommandDiscoveryUtils.discoverOrLoadSchemas();
+ SchemaInfo schemaInfo = null;
+ if (list != null) {
+ for (SchemaInfo schema : list) {
+ if (cmd.equals(schema.getCmdName()) && version.equals(schema.getProduct())) {
+ schemaInfo = schema;
+ break;
+ }
+ }
+ }
+ return schemaInfo;
+ }
+
+ /**
+ * Load the previous discovered json file.
+ *
+ * @return list
+ * @throws OnapCommandInvalidSchema
+ * exception
+ * @throws OnapCommandDiscoveryFailed
+ * exception
+ */
+ public static List<SchemaInfo> discoverOrLoadSchemas() throws OnapCommandException {
+ List<SchemaInfo> schemas = new ArrayList<>();
+ if (OnapCommandConfg.isDiscoverAlways() || !OnapCommandDiscoveryUtils.isAlreadyDiscovered()) {
+ schemas = OnapCommandDiscoveryUtils.discoverSchemas();
+ if (!schemas.isEmpty()) {
+ OnapCommandDiscoveryUtils.persistSchemaInfo(schemas);
+ }
+ } else {
+ try {
+ Resource resource = OnapCommandDiscoveryUtils.findResource(DISCOVERY_FILE,
+ DATA_PATH_JSON_PATTERN);
+ if (resource != null) {
+ File file = new File(resource.getURI().getPath());
+ ObjectMapper mapper = new ObjectMapper();
+ SchemaInfo[] list = mapper.readValue(file, SchemaInfo[].class);
+ schemas.addAll(Arrays.asList(list));
+ }
+ } catch (IOException e) {
+ throw new OnapCommandDiscoveryFailed(DATA_DIRECTORY,
+ DISCOVERY_FILE, e);
+ }
+ }
+
+ return schemas;
+ }
+
+ /**
+ * Check if json file discovered or not.
+ *
+ * @return boolean
+ * @throws OnapCommandDiscoveryFailed
+ * exception
+ */
+ public static boolean isAlreadyDiscovered() throws OnapCommandDiscoveryFailed {
+ Resource resource = null;
+ try {
+ resource = OnapCommandDiscoveryUtils.findResource(DISCOVERY_FILE,
+ DATA_PATH_JSON_PATTERN);
+ if (resource != null) {
+ return true;
+ }
+ } catch (IOException e) {
+ throw new OnapCommandDiscoveryFailed(DATA_DIRECTORY,
+ DISCOVERY_FILE, e);
+ }
+
+ return false;
+ }
+
+ /**
+ * Persist the external schema details.
+ *
+ * @param schemas
+ * list
+ * @throws OnapCommandDiscoveryFailed
+ * exception
+ */
+ public static void persistSchemaInfo(List<SchemaInfo> schemas) throws OnapCommandDiscoveryFailed {
+ if (schemas != 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 + DISCOVERY_FILE);
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.writerWithDefaultPrettyPrinter().writeValue(file, schemas);
+ }
+ } catch (IOException e1) {
+ throw new OnapCommandDiscoveryFailed(DATA_DIRECTORY,
+ DISCOVERY_FILE, e1);
+ }
+ }
+ }
+
+ /**
+ * Get schema map.
+ *
+ * @param resource
+ * resource obj
+ * @return map
+ * @throws OnapCommandInvalidSchema
+ * exception
+ */
+ public static Map<String, ?> loadSchema(Resource resource) throws OnapCommandInvalidSchema {
+ Map<String, ?> values = null;
+ try {
+ values = (Map<String, ?>) new Yaml().load(resource.getInputStream());
+ } catch (Exception e) {
+ throw new OnapCommandInvalidSchema(resource.getFilename(), e);
+ }
+ return values;
+ }
+
+ /**
+ * Returns a resource available under certain directory in class-path.
+ *
+ * @param pattern
+ * search pattern
+ * @return found resource
+ * @throws IOException
+ * exception
+ */
+ public static Resource findResource(String fileName, String pattern) throws IOException {
+ Resource[] resources = OnapCommandDiscoveryUtils.findResources(pattern);
+ if (resources != null && resources.length > 0) {
+ for (Resource res : resources) {
+ if (res.getFilename().equals(fileName)) {
+ return res;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Returns all resources available under certain directory in class-path.
+ *
+ * @param pattern
+ * search pattern
+ * @return resources found resources
+ * @throws IOException
+ * exception
+ */
+ public static Resource[] findResources(String pattern) throws IOException {
+ ClassLoader cl = OnapCommandUtils.class.getClassLoader();
+ ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
+ return resolver.getResources("classpath*:" + pattern);
+ }
+
+ static String identitySchemaProfileType(Map<String, ?> schemaYamlMap) {
+
+ for (String schemeType : OnapCommandConfg.getSchemaAttrInfo(Constants.SCHEMA_TYPES_SUPPORTED)) {
+ if (schemaYamlMap.get(schemeType) != null) {
+ return schemeType;
+ }
+ }
+
+ return Constants.BASIC_SCHEMA_PROFILE;
+ }
+
+ /**
+ * Find external schema files.
+ *
+ * @return list ExternalSchema
+ * @throws OnapCommandDiscoveryFailed
+ * exception
+ * @throws OnapCommandInvalidSchema
+ * exception
+ */
+ public static List<SchemaInfo> discoverSchemas() throws OnapCommandException {
+ List<SchemaInfo> extSchemas = new ArrayList<>();
+ try {
+ Resource[] res = findResources(SCHEMA_PATH_PATERN);
+ if (res != null && res.length > 0) {
+ Map<String, ?> resourceMap;
+
+ for (Resource resource : res) {
+ try {
+ resourceMap = loadSchema(resource);
+ } catch (OnapCommandException e) {
+ OnapCommandUtils.LOG.error("Invalid schema " + resource.getURI().toString(), e);
+ continue;
+ }
+
+ if (resourceMap != null && resourceMap.size() > 0) {
+ SchemaInfo schema = new SchemaInfo();
+
+ 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)) {
+ OnapCommandUtils.LOG.info("Unsupported Schema version found " + schema.getSchemaURI());
+ continue;
+ }
+
+ schema.setSchemaName(resource.getFilename());
+ schema.setCmdName((String) resourceMap.get(NAME));
+
+ Map<String, ?> infoMap = (Map<String, ?>) resourceMap.get(Constants.INFO);
+ if (infoMap != null && infoMap.get(Constants.INFO_TYPE) != null) {
+ schema.setType(infoMap.get(Constants.INFO_TYPE).toString());
+ }
+
+ if (infoMap != null && infoMap.get(Constants.INFO_PRODUCT) != null) {
+ schema.setProduct(infoMap.get(Constants.INFO_PRODUCT).toString());
+ }
+
+ schema.setSchemaProfile(identitySchemaProfileType(resourceMap));
+
+ extSchemas.add(schema);
+ }
+ }
+ }
+ } catch (IOException e) {
+ throw new OnapCommandDiscoveryFailed(SCHEMA_DIRECTORY, e);
+ }
+
+ return extSchemas;
+ }
+
+ /**
+ * Discover the Oclip commands.
+ *
+ * @return list
+ */
+ public static List<Class<OnapCommand>> discoverCommandPlugins() {
+ ServiceLoader<OnapCommand> loader = ServiceLoader.load(OnapCommand.class);
+ List<Class<OnapCommand>> clss = new ArrayList<>();
+ for (OnapCommand implClass : loader) {
+ clss.add((Class<OnapCommand>) implClass.getClass());
+ }
+
+ return clss;
+ }
+
+}
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
new file mode 100644
index 00000000..c4a93370
--- /dev/null
+++ b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandHelperUtils.java
@@ -0,0 +1,200 @@
+/*
+ * 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.DESCRIPTION;
+import static org.onap.cli.fw.conf.Constants.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.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.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;
+
+public class OnapCommandHelperUtils {
+
+ /**
+ * Returns the build time from manifest.mf
+ */
+ public static String findLastBuildTime() {
+ String impBuildDate = "";
+ try
+ {
+ String path = OnapCommandUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
+ JarFile jar = new JarFile(path);
+ Manifest manifest = jar.getManifest();
+ jar.close();
+
+ Attributes attributes = manifest.getMainAttributes();
+
+ impBuildDate = attributes.getValue("Build-Time");
+ }
+ catch (IOException e)
+ {
+ //Ignore it as it will never occur
+ }
+
+ return impBuildDate;
+ }
+
+ /**
+ * Returns Help.
+ *
+ * @param cmd
+ * OnapCommand
+ * @return help string
+ * @throws OnapCommandHelpFailed
+ * help failed exception
+ */
+ public static String help(OnapCommand cmd) throws OnapCommandHelpFailed {
+
+ String help = "usage: oclip " + cmd.getName();
+
+ // Add description
+ help += "\n\n" + cmd.getDescription();
+
+ // Add service
+ help += "\n\nService: " + cmd.getInfo().getService();
+
+ // Add whole command
+ String commandOptions = "";
+
+ // Add parameters
+ OnapCommandResult paramTable = new OnapCommandResult();
+ paramTable.setPrintDirection(PrintDirection.LANDSCAPE);
+ paramTable.setType(ResultType.TABLE);
+ paramTable.setIncludeTitle(false);
+ paramTable.setIncludeSeparator(false);
+
+ OnapCommandResultAttribute attrName = new OnapCommandResultAttribute();
+ attrName.setName(NAME);
+ attrName.setDescription(NAME);
+ attrName.setScope(OnapCommandResultAttributeScope.SHORT);
+ paramTable.getRecords().add(attrName);
+
+ OnapCommandResultAttribute attrDescription = new OnapCommandResultAttribute();
+ attrDescription.setName(DESCRIPTION);
+ attrDescription.setDescription(DESCRIPTION);
+ attrDescription.setScope(OnapCommandResultAttributeScope.SHORT);
+ paramTable.getRecords().add(attrDescription);
+
+ int newLineOptions = 0;
+ for (OnapCommandParameter param : cmd.getParameters()) {
+ if (!param.isInclude()) {
+ continue;
+ }
+
+ // First column Option or positional args
+ String optFirstCol;
+ if (newLineOptions == 3) {
+ newLineOptions = 0;
+ commandOptions += "\n";
+ }
+
+ if (param.getShortOption() != null || param.getLongOption() != null) {
+ optFirstCol = OnapCommandParameter.printShortOption(param.getShortOption()) + " | "
+ + OnapCommandParameter.printLongOption(param.getLongOption());
+ commandOptions += " [" + optFirstCol + "]";
+ } else {
+ optFirstCol = param.getName();
+ commandOptions += " <" + optFirstCol + ">";
+ }
+
+ newLineOptions++;
+
+ attrName.getValues().add(" " + optFirstCol);
+
+ // Second column description
+ String optSecondCol = param.getDescription().trim();
+ if (!optSecondCol.endsWith(".")) {
+ optSecondCol += ".";
+ }
+ optSecondCol += " It is of type " + param.getParameterType().name() + ".";
+
+ if (param.getParameterType().equals(ParameterType.JSON)
+ || param.getParameterType().equals(ParameterType.YAML)) {
+ optSecondCol += " It's recommended to input the complete path of the file, which is having the value for it.";
+ }
+ if (param.isOptional()) {
+ optSecondCol += " It is optional.";
+ }
+
+ String defaultMsg = " By default, it is ";
+ if (param.isRawDefaultValueAnEnv()) {
+ optSecondCol += defaultMsg + "read from environment variable " + param.getEnvVarNameFromrRawDefaultValue()
+ + ".";
+ } else if (param.getDefaultValue() != null && !((String)param.getDefaultValue()).isEmpty()) {
+ optSecondCol += defaultMsg + param.getDefaultValue() + ".";
+ }
+
+ if (param.isSecured()) {
+ optSecondCol += " Secured.";
+ }
+ // (mrkanag) Add help msg for reading default value from env
+ attrDescription.getValues().add(optSecondCol);
+ }
+
+ try {
+ help += "\n\nOptions::\n\n" + commandOptions + "\n\nwhere::\n\n" + paramTable.print();
+ } catch (OnapCommandException e) {
+ throw new OnapCommandHelpFailed(e);
+ }
+
+ // Add results
+ OnapCommandResult resultTable = new OnapCommandResult();
+ resultTable.setPrintDirection(PrintDirection.PORTRAIT);
+ resultTable.setType(ResultType.TABLE);
+ resultTable.setIncludeTitle(false);
+ resultTable.setIncludeSeparator(false);
+
+ for (OnapCommandResultAttribute attr : cmd.getResult().getRecords()) {
+ OnapCommandResultAttribute attrHelp = new OnapCommandResultAttribute();
+ attrHelp.setName(" " + attr.getName());
+ attrHelp.setDescription(attr.getDescription());
+ String msg = attr.getDescription() + " and is of type " + attr.getType().name() + ".";
+ if (attr.isSecured()) {
+ msg += " It is secured.";
+ }
+ attrHelp.getValues().add(msg);
+ attrHelp.setType(attr.getType());
+ resultTable.getRecords().add(attrHelp);
+ }
+
+ if (cmd.getResult().getRecords().size() > 0) {
+ try {
+ help += "\n\nResults::\n\n" + resultTable.print();
+ } catch (OnapCommandException e) {
+ throw new OnapCommandHelpFailed(e);
+ }
+ }
+
+ // Error
+ help += "\n\nError::\n\n On error, it prints <HTTP STATUS CODE>::<ERROR CODE>::<ERROR MESSAGE>\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
new file mode 100644
index 00000000..b1fff95d
--- /dev/null
+++ b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandProfileUtils.java
@@ -0,0 +1,72 @@
+/*
+ * 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<Param> loadParamFromCache(String profileName) throws OnapCommandLoadProfileFailed {
+ List<Param> 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<Param> 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/OnapCommandSchemaLoader.java b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandSchemaLoader.java
deleted file mode 100644
index 439ec227..00000000
--- a/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandSchemaLoader.java
+++ /dev/null
@@ -1,686 +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.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_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_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.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.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 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<String, ?> validateSchemaVersion(String schemaName, String version) throws OnapCommandException {
- InputStream inputStream = OnapCommandUtils.class.getClassLoader().getResourceAsStream(schemaName);
-
- try {
- Resource resource = OnapCommandUtils.findResource(schemaName, SCHEMA_PATH_PATERN);
-
- if (resource != null) {
- inputStream = resource.getInputStream();
- }
-
- } catch (IOException e) {
- throw new OnapCommandSchemaNotFound(schemaName, e);
- }
- if (inputStream == null) {
- inputStream = OnapCommandUtils.loadSchemaFromFile(schemaName);
- }
-
- Map<String, ?> values = null;
- try {
- values = (Map<String, ?>) new Yaml().load(inputStream);
- } catch (Exception e) {
- throw new OnapCommandInvalidSchema(schemaName, e);
- }
- 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<String> loadSchema(OnapCommand cmd, String schemaName, boolean includeDefault,
- boolean validateSchema) throws OnapCommandException {
- try {
- List<String> errors = new ArrayList<>();
- if (includeDefault) {
- Map<String, ?> defaultParameterMap = includeDefault ?
- validateSchemaVersion(DEFAULT_PARAMETER_FILE_NAME, cmd.getSchemaVersion()) : new HashMap<>();
- errors.addAll(OnapCommandSchemaLoader.parseSchema(cmd, defaultParameterMap, validateSchema));
- }
-
- Map<String, List<Map<String, String>>> commandYamlMap =
- (Map<String, List<Map<String, String>>>)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<String> loadHttpSchema(OnapHttpCommand cmd, String schemaName, boolean includeDefault,
- boolean validateSchema) throws OnapCommandException {
- try {
- List<String> errors = new ArrayList<>();
- if (includeDefault) {
- Map<String, ?> defaultParameterMap = includeDefault ?
- validateSchemaVersion(DEFAULT_PARAMETER_HTTP_FILE_NAME, cmd.getSchemaVersion()) : new HashMap<>();
- errors.addAll(OnapCommandSchemaLoader.parseSchema(cmd, defaultParameterMap, validateSchema));
- }
-
- Map<String, List<Map<String, String>>> commandYamlMap =
- (Map<String, List<Map<String, String>>>)validateSchemaVersion(schemaName, cmd.getSchemaVersion());
-
- errors.addAll(OnapCommandSchemaLoader.parseHttpSchema(cmd, commandYamlMap, validateSchema));
-
- return errors;
-
- } catch (OnapCommandException e) {
- throw e;
- } catch (Exception e) {
- throw new OnapCommandInvalidSchema(schemaName, e);
- }
- }
-
- static List<String> parseSchema(OnapCommand cmd,
- final Map<String, ?> values,
- boolean validate) throws OnapCommandException {
-
- List<String> exceptionList = new ArrayList<>();
- List<String> shortOptions = new ArrayList<>();
- List<String> longOptions = new ArrayList<>();
-
- if (validate) {
- OnapCommandUtils.validateTags(exceptionList, (Map<String, Object>) values, OnapCommandConfg.getSchemaAttrInfo(TOP_LEVEL_PARAMS_LIST),
- OnapCommandConfg.getSchemaAttrInfo(TOP_LEVEL_MANDATORY_LIST), "root level");
- }
-
-
- List<String> 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<String, String> infoMap = (Map<String, String>) values.get(key);
-
- if (infoMap != null) {
- if (validate) {
- OnapCommandUtils.validateTags(exceptionList, (Map<String, Object>) values.get(key),
- OnapCommandConfg.getSchemaAttrInfo(INFO_PARAMS_LIST),
- OnapCommandConfg.getSchemaAttrInfo(INFO_PARAMS_MANDATORY_LIST), INFO);
-
- HashMap<String, String> 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<String, String> 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;
- }
- }
-
- cmd.setInfo(info);
- }
- break;
-
- case PARAMETERS:
-
- List<Map<String, String>> parameters = (List) values.get(key);
-
- if (parameters != null) {
- Set<String> 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<String> existingParamNames = cmd.getParametersMap().keySet();
-
- for (Map<String, String> 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<String, String> 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(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(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 ("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 ("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 ("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<String, ?> valueMap = (Map<String, ?>) values.get(key);
- if (valueMap != null) {
- OnapCommandResult result = new OnapCommandResult();
- for (Map.Entry<String, ?> 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<Map<String, String>> attrs = (ArrayList) valueMap.get(key3);
-
- for (Map<String, String> 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<String> resultParamNames = new HashSet<>();
-
- for (Map.Entry<String, String> 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 ("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<String> parseHttpSchema(OnapHttpCommand cmd,
- final Map<String, ?> values,
- boolean validate) throws OnapCommandException {
- ArrayList<String> errorList = new ArrayList<>();
- try {
- Map<String, ?> valMap = (Map<String, ?>) 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<String, ?> entry1 : valMap.entrySet()) {
- String key1 = entry1.getKey();
-
- switch (key1) {
- case REQUEST:
- Map<String, ?> map = (Map<String, ?>) valMap.get(key1);
-
- for (Map.Entry<String, ?> 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<String, String> head = (Map<String, String>) map.get(key2);
- cmd.getInput().setReqHeaders(head);
- break;
- case QUERIES:
- Map<String, String> query = (Map<String, String>) 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<String, String> serviceMap = (Map<String, String>) valMap.get(key1);
-
- if (serviceMap != null) {
- if (validate) {
- OnapCommandUtils.validateTags(errorList, (Map<String, Object>) valMap.get(key1),
- OnapCommandConfg.getSchemaAttrInfo(SERVICE_PARAMS_LIST),
- OnapCommandConfg.getSchemaAttrInfo(SERVICE_PARAMS_MANDATORY_LIST), SERVICE);
-
- HashMap<String, String> 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<String, String> 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;
-
- 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<Object>) valMap.get(key1));
- }
- cmd.setSuccessStatusCodes((ArrayList) valMap.get(key1));
- break;
-
- case RESULT_MAP:
- if (validate) {
- OnapCommandUtils.validateHttpResultMap(errorList, values);
- }
- cmd.setResultMap((Map<String, String>) valMap.get(key1));
- break;
-
- case SAMPLE_RESPONSE:
- // (mrkanag) implement sample response handling
- break;
- }
- }
- }
- }catch (OnapCommandException e) {
- OnapCommandUtils.throwOrCollect(e, errorList, validate);
- }
- return errorList;
- }
-
-}
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
new file mode 100644
index 00000000..a33b98ac
--- /dev/null
+++ b/framework/src/main/java/org/onap/cli/fw/utils/OnapCommandSchemaLoaderUtils.java
@@ -0,0 +1,708 @@
+/*
+ * 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.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_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.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<String, ?> 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<String, ?> values = null;
+ try {
+ values = (Map<String, ?>) new Yaml().load(inputStream);
+ } catch (Exception e) {
+ throw new OnapCommandInvalidSchema(schemaName, e);
+ }
+ 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<String> loadSchema(OnapCommand cmd, String schemaName, boolean includeDefault,
+ boolean validateSchema) throws OnapCommandException {
+ try {
+ List<String> errors = new ArrayList<>();
+ if (includeDefault) {
+ Map<String, ?> defaultParameterMap = includeDefault ?
+ validateSchemaVersion(DEFAULT_PARAMETER_FILE_NAME, cmd.getSchemaVersion()) : new HashMap<>();
+ errors.addAll(OnapCommandSchemaLoaderUtils.parseSchema(cmd, defaultParameterMap, validateSchema));
+ }
+
+ Map<String, List<Map<String, String>>> commandYamlMap =
+ (Map<String, List<Map<String, String>>>)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<String> loadHttpSchema(OnapHttpCommand cmd, String schemaName, boolean includeDefault,
+ boolean validateSchema) throws OnapCommandException {
+ try {
+ List<String> errors = new ArrayList<>();
+ if (includeDefault) {
+ Map<String, ?> defaultParameterMap = includeDefault ?
+ validateSchemaVersion(DEFAULT_PARAMETER_HTTP_FILE_NAME, cmd.getSchemaVersion()) : new HashMap<>();
+ errors.addAll(OnapCommandSchemaLoaderUtils.parseSchema(cmd, defaultParameterMap, validateSchema));
+ }
+
+ Map<String, List<Map<String, String>>> commandYamlMap =
+ (Map<String, List<Map<String, String>>>)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<String> parseSchema(OnapCommand cmd,
+ final Map<String, ?> values,
+ boolean validate) throws OnapCommandException {
+
+ List<String> exceptionList = new ArrayList<>();
+ List<String> shortOptions = new ArrayList<>();
+ List<String> longOptions = new ArrayList<>();
+
+ if (validate) {
+ OnapCommandUtils.validateTags(exceptionList, (Map<String, Object>) values, OnapCommandConfg.getSchemaAttrInfo(TOP_LEVEL_PARAMS_LIST),
+ OnapCommandConfg.getSchemaAttrInfo(TOP_LEVEL_MANDATORY_LIST), "root level");
+ }
+
+
+ List<String> 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<String, String> infoMap = (Map<String, String>) values.get(key);
+
+ if (infoMap != null) {
+ if (validate) {
+ OnapCommandUtils.validateTags(exceptionList, (Map<String, Object>) values.get(key),
+ OnapCommandConfg.getSchemaAttrInfo(INFO_PARAMS_LIST),
+ OnapCommandConfg.getSchemaAttrInfo(INFO_PARAMS_MANDATORY_LIST), INFO);
+
+ HashMap<String, String> 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<String, String> 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;
+ }
+ }
+
+ cmd.setInfo(info);
+ }
+ break;
+
+ case PARAMETERS:
+
+ List<Map<String, String>> parameters = (List) values.get(key);
+
+ if (parameters != null) {
+ Set<String> 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<String> existingParamNames = cmd.getParametersMap().keySet();
+
+ for (Map<String, String> 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<String, String> 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(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(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 ("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 ("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 ("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<String, ?> valueMap = (Map<String, ?>) values.get(key);
+ if (valueMap != null) {
+ OnapCommandResult result = new OnapCommandResult();
+ for (Map.Entry<String, ?> 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<Map<String, String>> attrs = (ArrayList) valueMap.get(key3);
+
+ for (Map<String, String> 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<String> resultParamNames = new HashSet<>();
+
+ for (Map.Entry<String, String> 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 ("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<String> parseHttpSchema(OnapHttpCommand cmd,
+ final Map<String, ?> values,
+ boolean validate) throws OnapCommandException {
+ ArrayList<String> errorList = new ArrayList<>();
+ try {
+ Map<String, ?> valMap = (Map<String, ?>) 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<String, ?> entry1 : valMap.entrySet()) {
+ String key1 = entry1.getKey();
+
+ switch (key1) {
+ case REQUEST:
+ Map<String, ?> map = (Map<String, ?>) valMap.get(key1);
+
+ for (Map.Entry<String, ?> 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<String, String> head = (Map<String, String>) map.get(key2);
+ cmd.getInput().setReqHeaders(head);
+ break;
+ case QUERIES:
+ Map<String, String> query = (Map<String, String>) 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<String, String> serviceMap = (Map<String, String>) valMap.get(key1);
+
+ if (serviceMap != null) {
+ if (validate) {
+ OnapCommandUtils.validateTags(errorList, (Map<String, Object>) valMap.get(key1),
+ OnapCommandConfg.getSchemaAttrInfo(SERVICE_PARAMS_LIST),
+ OnapCommandConfg.getSchemaAttrInfo(SERVICE_PARAMS_MANDATORY_LIST), SERVICE);
+
+ HashMap<String, String> 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<String, String> 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;
+
+ 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<Object>) valMap.get(key1));
+ }
+ cmd.setSuccessStatusCodes((ArrayList) valMap.get(key1));
+ break;
+
+ case RESULT_MAP:
+ if (validate) {
+ OnapCommandUtils.validateHttpResultMap(errorList, values);
+ }
+ cmd.setResultMap((Map<String, String>) valMap.get(key1));
+ break;
+
+ case SAMPLE_RESPONSE:
+ // (mrkanag) implement sample response handling
+ break;
+ }
+ }
+ }
+ }catch (OnapCommandException e) {
+ OnapCommandUtils.throwOrCollect(e, errorList, validate);
+ }
+ return errorList;
+ }
+
+ 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);
+ }
+ }
+
+}
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 9a6f6366..0c5a75fb 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
@@ -19,10 +19,6 @@ 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.DATA_DIRECTORY;
-import static org.onap.cli.fw.conf.Constants.DATA_PATH_JSON_PATTERN;
-import static org.onap.cli.fw.conf.Constants.DESCRIPTION;
-import static org.onap.cli.fw.conf.Constants.DISCOVERY_FILE;
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;
@@ -33,72 +29,43 @@ 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.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.SCHEMA_DIRECTORY;
-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.URI;
-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.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.ServiceLoader;
import java.util.Set;
import java.util.UUID;
-import java.util.jar.Attributes;
-import java.util.jar.JarFile;
-import java.util.jar.Manifest;
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.error.OnapCommandDiscoveryFailed;
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.OnapCommandHttpInvalidResultMap;
import org.onap.cli.fw.error.OnapCommandInvalidParameterValue;
-import org.onap.cli.fw.error.OnapCommandInvalidSchema;
-import org.onap.cli.fw.error.OnapCommandLoadProfileFailed;
import org.onap.cli.fw.error.OnapCommandParameterNotFound;
-import org.onap.cli.fw.error.OnapCommandPersistProfileFailed;
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.cache.Param;
-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.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.core.io.Resource;
-import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
-import org.springframework.core.io.support.ResourcePatternResolver;
-import org.yaml.snakeyaml.Yaml;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
@@ -112,7 +79,7 @@ import net.minidev.json.JSONObject;
*/
public class OnapCommandUtils {
- private static Logger LOG = LoggerFactory.getLogger(OnapCommandUtils.class);
+ static Logger LOG = LoggerFactory.getLogger(OnapCommandUtils.class);
/**
* Private constructor.
*/
@@ -120,23 +87,6 @@ public class OnapCommandUtils {
}
- 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);
- }
- }
-
static void throwOrCollect(OnapCommandException ex, List<String> list, boolean shouldCollectException)
throws OnapCommandException {
if (shouldCollectException) {
@@ -362,142 +312,6 @@ public class OnapCommandUtils {
/**
- * Returns Help.
- *
- * @param cmd
- * OnapCommand
- * @return help string
- * @throws OnapCommandHelpFailed
- * help failed exception
- */
- public static String help(OnapCommand cmd) throws OnapCommandHelpFailed {
-
- String help = "usage: oclip " + cmd.getName();
-
- // Add description
- help += "\n\n" + cmd.getDescription();
-
- // Add service
- help += "\n\nService: " + cmd.getInfo().getService();
-
- // Add whole command
- String commandOptions = "";
-
- // Add parameters
- OnapCommandResult paramTable = new OnapCommandResult();
- paramTable.setPrintDirection(PrintDirection.LANDSCAPE);
- paramTable.setType(ResultType.TABLE);
- paramTable.setIncludeTitle(false);
- paramTable.setIncludeSeparator(false);
-
- OnapCommandResultAttribute attrName = new OnapCommandResultAttribute();
- attrName.setName(NAME);
- attrName.setDescription(NAME);
- attrName.setScope(OnapCommandResultAttributeScope.SHORT);
- paramTable.getRecords().add(attrName);
-
- OnapCommandResultAttribute attrDescription = new OnapCommandResultAttribute();
- attrDescription.setName(DESCRIPTION);
- attrDescription.setDescription(DESCRIPTION);
- attrDescription.setScope(OnapCommandResultAttributeScope.SHORT);
- paramTable.getRecords().add(attrDescription);
-
- int newLineOptions = 0;
- for (OnapCommandParameter param : cmd.getParameters()) {
- if (!param.isInclude()) {
- continue;
- }
-
- // First column Option or positional args
- String optFirstCol;
- if (newLineOptions == 3) {
- newLineOptions = 0;
- commandOptions += "\n";
- }
-
- if (param.getShortOption() != null || param.getLongOption() != null) {
- optFirstCol = OnapCommandParameter.printShortOption(param.getShortOption()) + " | "
- + OnapCommandParameter.printLongOption(param.getLongOption());
- commandOptions += " [" + optFirstCol + "]";
- } else {
- optFirstCol = param.getName();
- commandOptions += " <" + optFirstCol + ">";
- }
-
- newLineOptions++;
-
- attrName.getValues().add(" " + optFirstCol);
-
- // Second column description
- String optSecondCol = param.getDescription().trim();
- if (!optSecondCol.endsWith(".")) {
- optSecondCol += ".";
- }
- optSecondCol += " It is of type " + param.getParameterType().name() + ".";
-
- if (param.getParameterType().equals(ParameterType.JSON)
- || param.getParameterType().equals(ParameterType.YAML)) {
- optSecondCol += " It's recommended to input the complete path of the file, which is having the value for it.";
- }
- if (param.isOptional()) {
- optSecondCol += " It is optional.";
- }
-
- String defaultMsg = " By default, it is ";
- if (param.isRawDefaultValueAnEnv()) {
- optSecondCol += defaultMsg + "read from environment variable " + param.getEnvVarNameFromrRawDefaultValue()
- + ".";
- } else if (param.getDefaultValue() != null && !((String)param.getDefaultValue()).isEmpty()) {
- optSecondCol += defaultMsg + param.getDefaultValue() + ".";
- }
-
- if (param.isSecured()) {
- optSecondCol += " Secured.";
- }
- // (mrkanag) Add help msg for reading default value from env
- attrDescription.getValues().add(optSecondCol);
- }
-
- try {
- help += "\n\nOptions::\n\n" + commandOptions + "\n\nwhere::\n\n" + paramTable.print();
- } catch (OnapCommandException e) {
- throw new OnapCommandHelpFailed(e);
- }
-
- // Add results
- OnapCommandResult resultTable = new OnapCommandResult();
- resultTable.setPrintDirection(PrintDirection.PORTRAIT);
- resultTable.setType(ResultType.TABLE);
- resultTable.setIncludeTitle(false);
- resultTable.setIncludeSeparator(false);
-
- for (OnapCommandResultAttribute attr : cmd.getResult().getRecords()) {
- OnapCommandResultAttribute attrHelp = new OnapCommandResultAttribute();
- attrHelp.setName(" " + attr.getName());
- attrHelp.setDescription(attr.getDescription());
- String msg = attr.getDescription() + " and is of type " + attr.getType().name() + ".";
- if (attr.isSecured()) {
- msg += " It is secured.";
- }
- attrHelp.getValues().add(msg);
- attrHelp.setType(attr.getType());
- resultTable.getRecords().add(attrHelp);
- }
-
- if (cmd.getResult().getRecords().size() > 0) {
- try {
- help += "\n\nResults::\n\n" + resultTable.print();
- } catch (OnapCommandException e) {
- throw new OnapCommandHelpFailed(e);
- }
- }
-
- // Error
- help += "\n\nError::\n\n On error, it prints <HTTP STATUS CODE>::<ERROR CODE>::<ERROR MESSAGE>\n";
- return help;
- }
-
- /**
* Create Dict from list of Parameters.
*
* @param inputs
@@ -513,21 +327,6 @@ public class OnapCommandUtils {
}
/**
- * Discover the Oclip commands.
- *
- * @return list
- */
- public static List<Class<OnapCommand>> discoverCommandPlugins() {
- ServiceLoader<OnapCommand> loader = ServiceLoader.load(OnapCommand.class);
- List<Class<OnapCommand>> clss = new ArrayList<>();
- for (OnapCommand implClass : loader) {
- clss.add((Class<OnapCommand>) implClass.getClass());
- }
-
- return clss;
- }
-
- /**
* sort the set.
*
* @param col
@@ -902,278 +701,6 @@ public class OnapCommandUtils {
}
/**
- * Find external schema files.
- *
- * @return list ExternalSchema
- * @throws OnapCommandDiscoveryFailed
- * exception
- * @throws OnapCommandInvalidSchema
- * exception
- */
- public static List<SchemaInfo> discoverSchemas() throws OnapCommandException {
- List<SchemaInfo> extSchemas = new ArrayList<>();
- try {
- Resource[] res = findResources(SCHEMA_PATH_PATERN);
- if (res != null && res.length > 0) {
- Map<String, ?> resourceMap;
-
- for (Resource resource : res) {
- try {
- resourceMap = loadSchema(resource);
- } catch (OnapCommandException e) {
- LOG.error("Invalid schema " + resource.getURI().toString(), e);
- continue;
- }
-
- if (resourceMap != null && resourceMap.size() > 0) {
- SchemaInfo schema = new SchemaInfo();
-
- 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)) {
- LOG.info("Unsupported Schema version found " + schema.getSchemaURI());
- continue;
- }
-
- schema.setSchemaName(resource.getFilename());
- schema.setCmdName((String) resourceMap.get(NAME));
-
- Map<String, ?> infoMap = (Map<String, ?>) resourceMap.get(Constants.INFO);
- if (infoMap != null && infoMap.get(Constants.INFO_TYPE) != null) {
- schema.setType(infoMap.get(Constants.INFO_TYPE).toString());
- }
-
- if (infoMap != null && infoMap.get(Constants.INFO_PRODUCT) != null) {
- schema.setProduct(infoMap.get(Constants.INFO_PRODUCT).toString());
- }
-
- schema.setSchemaProfile(identitySchemaProfileType(resourceMap));
-
- extSchemas.add(schema);
- }
- }
- }
- } catch (IOException e) {
- throw new OnapCommandDiscoveryFailed(SCHEMA_DIRECTORY, e);
- }
-
- return extSchemas;
- }
-
- private static String identitySchemaProfileType(Map<String, ?> schemaYamlMap) {
-
- for (String schemeType : OnapCommandConfg.getSchemaAttrInfo(Constants.SCHEMA_TYPES_SUPPORTED)) {
- if (schemaYamlMap.get(schemeType) != null) {
- return schemeType;
- }
- }
-
- return Constants.BASIC_SCHEMA_PROFILE;
- }
-
- /**
- * Returns all resources available under certain directory in class-path.
- *
- * @param pattern
- * search pattern
- * @return resources found resources
- * @throws IOException
- * exception
- */
- public static Resource[] findResources(String pattern) throws IOException {
- ClassLoader cl = OnapCommandUtils.class.getClassLoader();
- ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
- return resolver.getResources("classpath*:" + pattern);
- }
-
- /**
- * Returns a resource available under certain directory in class-path.
- *
- * @param pattern
- * search pattern
- * @return found resource
- * @throws IOException
- * exception
- */
- public static Resource findResource(String fileName, String pattern) throws IOException {
- Resource[] resources = findResources(pattern);
- if (resources != null && resources.length > 0) {
- for (Resource res : resources) {
- if (res.getFilename().equals(fileName)) {
- return res;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Get schema map.
- *
- * @param resource
- * resource obj
- * @return map
- * @throws OnapCommandInvalidSchema
- * exception
- */
- public static Map<String, ?> loadSchema(Resource resource) throws OnapCommandInvalidSchema {
- Map<String, ?> values = null;
- try {
- values = (Map<String, ?>) new Yaml().load(resource.getInputStream());
- } catch (Exception e) {
- throw new OnapCommandInvalidSchema(resource.getFilename(), e);
- }
- return values;
- }
-
- /**
- * Persist the external schema details.
- *
- * @param schemas
- * list
- * @throws OnapCommandDiscoveryFailed
- * exception
- */
- public static void persistSchemaInfo(List<SchemaInfo> schemas) throws OnapCommandDiscoveryFailed {
- if (schemas != null) {
- try {
- Resource[] resources = findResources(DATA_DIRECTORY);
- if (resources != null && resources.length == 1) {
- String path = resources[0].getURI().getPath();
- File file = new File(path + File.separator + DISCOVERY_FILE);
- ObjectMapper mapper = new ObjectMapper();
- mapper.writerWithDefaultPrettyPrinter().writeValue(file, schemas);
- }
- } catch (IOException e1) {
- throw new OnapCommandDiscoveryFailed(DATA_DIRECTORY,
- DISCOVERY_FILE, e1);
- }
- }
- }
-
- public static void persistProfile(List<Param> params, String profileName) throws OnapCommandPersistProfileFailed {
- if (params != null) {
- try {
- Resource[] resources = 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);
- }
- }
- }
-
- /**
- * Check if json file discovered or not.
- *
- * @return boolean
- * @throws OnapCommandDiscoveryFailed
- * exception
- */
- public static boolean isAlreadyDiscovered() throws OnapCommandDiscoveryFailed {
- Resource resource = null;
- try {
- resource = findResource(DISCOVERY_FILE,
- DATA_PATH_JSON_PATTERN);
- if (resource != null) {
- return true;
- }
- } catch (IOException e) {
- throw new OnapCommandDiscoveryFailed(DATA_DIRECTORY,
- DISCOVERY_FILE, e);
- }
-
- return false;
- }
-
- /**
- * Load the previous discovered json file.
- *
- * @return list
- * @throws OnapCommandInvalidSchema
- * exception
- * @throws OnapCommandDiscoveryFailed
- * exception
- */
- public static List<SchemaInfo> discoverOrLoadSchemas() throws OnapCommandException {
- List<SchemaInfo> schemas = new ArrayList<>();
- if (OnapCommandConfg.isDiscoverAlways() || !isAlreadyDiscovered()) {
- schemas = discoverSchemas();
- if (!schemas.isEmpty()) {
- persistSchemaInfo(schemas);
- }
- } else {
- try {
- Resource resource = findResource(DISCOVERY_FILE,
- DATA_PATH_JSON_PATTERN);
- if (resource != null) {
- File file = new File(resource.getURI().getPath());
- ObjectMapper mapper = new ObjectMapper();
- SchemaInfo[] list = mapper.readValue(file, SchemaInfo[].class);
- schemas.addAll(Arrays.asList(list));
- }
- } catch (IOException e) {
- throw new OnapCommandDiscoveryFailed(DATA_DIRECTORY,
- DISCOVERY_FILE, e);
- }
- }
-
- return schemas;
- }
-
- public static List<Param> loadParamFromCache(String profileName) throws OnapCommandLoadProfileFailed {
- List<Param> params = new ArrayList<>();
-
- try {
- Resource resource = 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;
- }
-
- /**
- * Fetch a particular schema details.
- *
- * @param cmd
- * command name
- * @return ExternalSchema obj
- * @throws OnapCommandInvalidSchema
- * exception
- * @throws OnapCommandDiscoveryFailed
- * exception
- */
- public static SchemaInfo getSchemaInfo(String cmd, String version) throws OnapCommandException {
- List<SchemaInfo> list = discoverOrLoadSchemas();
- SchemaInfo schemaInfo = null;
- if (list != null) {
- for (SchemaInfo schema : list) {
- if (cmd.equals(schema.getCmdName()) && version.equals(schema.getProduct())) {
- schemaInfo = schema;
- break;
- }
- }
- }
- return schemaInfo;
- }
-
- /**
* Copy the parameters across the commands, mainly used for catalog, login and logout commands
*
* @throws OnapCommandInvalidParameterValue
@@ -1193,29 +720,5 @@ public class OnapCommandUtils {
}
}
}
-
- /**
- * Returns the build time from manifest.mf
- */
- public static String findLastBuildTime() {
- String impBuildDate = "";
- try
- {
- String path = OnapCommandUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
- JarFile jar = new JarFile(path);
- Manifest manifest = jar.getManifest();
- jar.close();
-
- Attributes attributes = manifest.getMainAttributes();
-
- impBuildDate = attributes.getValue("Build-Time");
- }
- catch (IOException e)
- {
- //Ignore it as it will never occur
- }
-
- return impBuildDate;
- }
}