From f5f13c4f6b6fe3b4d98e349dfd7db59339803436 Mon Sep 17 00:00:00 2001 From: Michael Lando Date: Sun, 19 Feb 2017 12:35:04 +0200 Subject: push addional code Change-Id: Ia427bb3460cda3a896f8faced2de69eaf3807b74 Signed-off-by: Michael Lando --- .../openecomp-config-lib/pom.xml | 48 ++ .../applicationconfig/ApplicationConfig.java | 35 ++ .../ApplicationConfigFactory.java | 31 ++ .../dao/ApplicationConfigDao.java | 33 ++ .../dao/ApplicationConfigDaoFactory.java | 32 ++ .../impl/ApplicationConfigDaoCassandraImpl.java | 115 +++++ .../dao/impl/ApplicationConfigDaoFactoryImpl.java | 33 ++ .../dao/type/ApplicationConfigEntity.java | 79 +++ .../impl/ApplicationConfigFactoryImpl.java | 34 ++ .../impl/ApplicationConfigImpl.java | 74 +++ .../applicationconfig/type/ConfigurationData.java | 48 ++ .../src/main/resources/factoryConfiguration.json | 4 + .../src/main/resources/logback.xml | 90 ++++ .../dao/ApplicationConfigImplDaoTest.java | 88 ++++ .../test/resources/questionnaire/testTemplate.txt | 12 + .../openecomp-facade-api/pom.xml | 31 ++ .../core/factory/api/AbstractFactory.java | 81 +++ .../core/factory/impl/AbstractFactoryBase.java | 212 ++++++++ .../openecomp-facade-core/pom.xml | 36 ++ .../core/factory/AbstractContextFactory.java | 27 + .../core/factory/FactoriesConfigImpl.java | 61 +++ .../org/openecomp/core/factory/FactoryConfig.java | 46 ++ .../core/factory/api/AbstractComponentFactory.java | 105 ++++ .../core/factory/api/FactoriesConfiguration.java | 29 ++ .../openecomp-facade-lib/pom.xml | 34 ++ .../openecomp-nosqldb-api/pom.xml | 40 ++ .../main/java/org/openecomp/core/dao/BaseDao.java | 36 ++ .../org/openecomp/core/dao/UniqueValueDao.java | 28 ++ .../openecomp/core/dao/UniqueValueDaoFactory.java | 30 ++ .../core/dao/types/UniqueValueEntity.java | 58 +++ .../org/openecomp/core/nosqldb/api/NoSqlDb.java | 37 ++ .../core/nosqldb/factory/NoSqlDbFactory.java | 34 ++ .../org/openecomp/core/util/UniqueValueUtil.java | 127 +++++ .../src/main/resources/cassandraStatements.json | 6 + .../src/main/resources/factoryConfiguration.json | 4 + .../openecomp-nosqldb-core/pom.xml | 60 +++ .../openecomp/core/dao/impl/CassandraBaseDao.java | 50 ++ .../core/dao/impl/UniqueValueCassandraDaoImpl.java | 65 +++ .../core/dao/impl/UniqueValueDaoFactoryImpl.java | 33 ++ .../cassandra/CassandraNoSqlDbFactoryImpl.java | 43 ++ .../impl/cassandra/CassandraNoSqlDbImpl.java | 104 ++++ .../impl/cassandra/CassandraSessionFactory.java | 124 +++++ .../core/nosqldb/util/CassandraUtils.java | 92 ++++ .../core/nosqldb/util/ConfigurationManager.java | 234 +++++++++ .../src/main/resources/configuration.yaml | 253 ++++++++++ .../org/openecomp/core/nosqldb/NoSqlDbTest.java | 48 ++ .../core/utilities/Yaml/YamlUtilTest.java | 47 ++ .../core/utilities/json/JsonUtilTest.java | 13 + .../src/test/java/testobjects/yaml/InnerP.java | 25 + .../src/test/java/testobjects/yaml/Parameter.java | 68 +++ .../src/test/java/testobjects/yaml/YamlFile.java | 37 ++ .../openecomp-nosqldb-lib/pom.xml | 36 ++ .../openecomp-utilities-lib/pom.xml | 82 +++ .../openecomp/core/utilities/CommonMethods.java | 555 +++++++++++++++++++++ .../core/utilities/file/FileContentHandler.java | 88 ++++ .../openecomp/core/utilities/file/FileUtils.java | 286 +++++++++++ .../utilities/json/JsonSchemaDataGenerator.java | 185 +++++++ .../openecomp/core/utilities/json/JsonUtil.java | 187 +++++++ .../openecomp/core/utilities/yaml/YamlUtil.java | 289 +++++++++++ .../json/JsonSchemaDataGeneratorTest.java | 50 ++ .../core/utilities/json/JsonUtilTest.java | 40 ++ .../src/test/resources/jsonUtil/json/a.json | 12 + .../test/resources/jsonUtil/json/a_invalid.json | 13 + .../resources/jsonUtil/json_schema/aSchema.json | 60 +++ .../resources/jsonUtil/json_schema/nicSchema.json | 118 +++++ .../json_schema/schemaWithInvalidDefault.json | 67 +++ .../json_schema/schemaWithRefsAndDefaults.json | 71 +++ openecomp-be/lib/openecomp-core-lib/pom.xml | 23 + 68 files changed, 5276 insertions(+) create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/pom.xml create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfig.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfigFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDao.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDaoFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoCassandraImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/type/ApplicationConfigEntity.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/type/ConfigurationData.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/resources/factoryConfiguration.json create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/resources/logback.xml create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/java/org/openecomp/sdc/applicationconfig/dao/ApplicationConfigImplDaoTest.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/resources/questionnaire/testTemplate.txt create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/pom.xml create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/api/AbstractFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/pom.xml create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/AbstractContextFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoriesConfigImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoryConfig.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/AbstractComponentFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/FactoriesConfiguration.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/pom.xml create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/pom.xml create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/BaseDao.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDao.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDaoFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/types/UniqueValueEntity.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/api/NoSqlDb.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/factory/NoSqlDbFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/util/UniqueValueUtil.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/resources/cassandraStatements.json create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/resources/factoryConfiguration.json create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/pom.xml create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/CassandraBaseDao.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueCassandraDaoImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueDaoFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbFactoryImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbImpl.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraSessionFactory.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/CassandraUtils.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/ConfigurationManager.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/resources/configuration.yaml create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/NoSqlDbTest.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/utilities/Yaml/YamlUtilTest.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/utilities/json/JsonUtilTest.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/testobjects/yaml/InnerP.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/testobjects/yaml/Parameter.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/testobjects/yaml/YamlFile.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/pom.xml create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/pom.xml create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/yaml/YamlUtil.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonSchemaDataGeneratorTest.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonUtilTest.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json/a.json create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json/a_invalid.json create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/aSchema.json create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/nicSchema.json create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/schemaWithInvalidDefault.json create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/schemaWithRefsAndDefaults.json create mode 100644 openecomp-be/lib/openecomp-core-lib/pom.xml (limited to 'openecomp-be/lib/openecomp-core-lib') diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/pom.xml new file mode 100644 index 0000000000..a10e9cbd04 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + + + org.openecomp.core + openecomp-core-lib + 1.0.0-SNAPSHOT + + + openecomp-config-lib + + + + com.google.code.gson + gson + 2.3.1 + test + + + org.yaml + snakeyaml + 1.14 + test + + + org.openecomp.core + openecomp-nosqldb-core + ${project.version} + + + org.testng + testng + 6.9.10 + test + + + org.openecomp.sdc + openecomp-sdc-vendor-software-product-api + ${project.version} + test + + + + + \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfig.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfig.java new file mode 100644 index 0000000000..a68c6b614a --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfig.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.applicationconfig; + +import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; +import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; + +import java.util.Collection; + +public interface ApplicationConfig { + + ConfigurationData getConfigurationData(String namespace, String key); + + void insertValue(String namespace, String key, String value); + + Collection getListOfConfigurationByNamespace(String namespace); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfigFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfigFactory.java new file mode 100644 index 0000000000..e022294dfd --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfigFactory.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.applicationconfig; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +public abstract class ApplicationConfigFactory extends AbstractComponentFactory { + + public static ApplicationConfigFactory getInstance() { + return AbstractFactory.getInstance(ApplicationConfigFactory.class); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDao.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDao.java new file mode 100644 index 0000000000..a4c582744a --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDao.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.applicationconfig.dao; + +import org.openecomp.core.dao.BaseDao; +import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; +import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; + + +public interface ApplicationConfigDao extends BaseDao { + + long getValueTimestamp(String namespace, String key); + + ConfigurationData getConfigurationData(String namespace, String key); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDaoFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDaoFactory.java new file mode 100644 index 0000000000..f60e4a9010 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDaoFactory.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.applicationconfig.dao; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +public abstract class ApplicationConfigDaoFactory + extends AbstractComponentFactory { + + public static ApplicationConfigDaoFactory getInstance() { + return AbstractFactory.getInstance(ApplicationConfigDaoFactory.class); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoCassandraImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoCassandraImpl.java new file mode 100644 index 0000000000..7fb0e2f5ae --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoCassandraImpl.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.applicationconfig.dao.impl; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.mapping.Mapper; +import com.datastax.driver.mapping.Result; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.core.dao.impl.CassandraBaseDao; +import org.openecomp.core.nosqldb.api.NoSqlDb; +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; +import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDao; +import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; +import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; + +import java.util.Collection; +import java.util.Objects; + +public class ApplicationConfigDaoCassandraImpl extends CassandraBaseDao + implements ApplicationConfigDao { + + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static final Mapper mapper = + noSqlDb.getMappingManager().mapper(ApplicationConfigEntity.class); + private static final ApplicationConfigAccessor accessor = + noSqlDb.getMappingManager().createAccessor(ApplicationConfigAccessor.class); + + @Override + protected Mapper getMapper() { + return mapper; + } + + @Override + protected Object[] getKeys(ApplicationConfigEntity entity) { + return new Object[]{entity.getNamespace(), entity.getKey(), entity.getValue()}; + } + + @Override + public Collection list(ApplicationConfigEntity entity) { + return accessor.list(entity.getNamespace()).all(); + } + + @Override + public void create(ApplicationConfigEntity entity) { + accessor.updateApplicationConfigData(entity.getNamespace(), entity.getKey(), entity.getValue()); + } + + @Override + public void update(ApplicationConfigEntity entity) { + accessor.updateApplicationConfigData(entity.getNamespace(), entity.getKey(), entity.getValue()); + } + + @Override + public ApplicationConfigEntity get(ApplicationConfigEntity entity) { + return accessor.get(entity.getNamespace(), entity.getKey()); + } + + @Override + public long getValueTimestamp(String namespace, String key) { + ResultSet resultSet = accessor.getValueAndTimestampOfConfigurationValue(namespace, key); + + return resultSet.one().getLong("writetime(value)"); + } + + @Override + public ConfigurationData getConfigurationData(String namespace, String key) { + //String value = accessor.getValue(namespace, key).one().getString("value"); + ResultSet resultSet = accessor.getValueAndTimestampOfConfigurationValue(namespace, key); + Row one = resultSet.one(); + + if (Objects.nonNull(one)) { + return new ConfigurationData(one.getString("value"), one.getLong("writetime(value)")); + } + + return null; + } + + + @Accessor + interface ApplicationConfigAccessor { + + @Query("select namespace, key, value from application_config where namespace=?") + Result list(String namespace); + + @Query("insert into application_config (namespace, key, value) values (?,?,?)") + ResultSet updateApplicationConfigData(String namespace, String key, String value); + + @Query("select namespace, key, value from application_config where namespace=? and key=?") + ApplicationConfigEntity get(String namespace, String key); + + @Query("select value, writetime(value) from application_config where namespace=? and key=?") + ResultSet getValueAndTimestampOfConfigurationValue(String namespace, String key); + + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoFactoryImpl.java new file mode 100644 index 0000000000..cea49ea8d1 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoFactoryImpl.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.applicationconfig.dao.impl; + +import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDao; +import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDaoFactory; + +public class ApplicationConfigDaoFactoryImpl extends ApplicationConfigDaoFactory { + private static final ApplicationConfigDao INSTANCE = new ApplicationConfigDaoCassandraImpl(); + + @Override + public ApplicationConfigDao createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/type/ApplicationConfigEntity.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/type/ApplicationConfigEntity.java new file mode 100644 index 0000000000..c73ce36744 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/type/ApplicationConfigEntity.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.applicationconfig.dao.type; + + +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; + +@Table(keyspace = "dox", name = "application_config") +public class ApplicationConfigEntity { + + @PartitionKey + private String namespace; + @ClusteringColumn + private String key; + private String value; + + /** + * Instantiates a new Application config entity. + * + * @param namespace the namespace + * @param key the key + * @param value the value + */ + public ApplicationConfigEntity(String namespace, String key, String value) { + this.namespace = namespace; + this.key = key; + this.value = value; + } + + + public ApplicationConfigEntity() { + } + + + public String getNamespace() { + return namespace; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigFactoryImpl.java new file mode 100644 index 0000000000..cca07fc227 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigFactoryImpl.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.applicationconfig.impl; + +import org.openecomp.core.utilities.applicationconfig.ApplicationConfig; +import org.openecomp.core.utilities.applicationconfig.ApplicationConfigFactory; + +public class ApplicationConfigFactoryImpl extends ApplicationConfigFactory { + + private static final ApplicationConfig INSTANCE = new ApplicationConfigImpl(); + + @Override + public ApplicationConfig createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigImpl.java new file mode 100644 index 0000000000..ff9c9aea87 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigImpl.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.applicationconfig.impl; + +import org.openecomp.core.utilities.applicationconfig.ApplicationConfig; +import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDao; +import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDaoFactory; +import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; +import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; + +import java.util.Collection; +import java.util.Objects; + +/** + * The type Application config. + */ +public class ApplicationConfigImpl implements ApplicationConfig { + private static final ApplicationConfigDao applicationConfigDao = + ApplicationConfigDaoFactory.getInstance().createInterface(); + + private static final String CONFIGURATION_SEARCH_ERROR = "CONFIGURATION_NOT_FOUND"; + private static final String CONFIGURATION_SEARCH_ERROR_MSG = + "Configuration for namespace %s and key %s was not found"; + + @Override + public ConfigurationData getConfigurationData(String namespace, String key) { + ConfigurationData configurationData = applicationConfigDao.getConfigurationData(namespace, key); + + if (Objects.isNull(configurationData)) { + throw new CoreException(new ErrorCode.ErrorCodeBuilder() + .withCategory(ErrorCategory.APPLICATION) + .withId(CONFIGURATION_SEARCH_ERROR) + .withMessage(String.format(CONFIGURATION_SEARCH_ERROR_MSG, namespace, key)) + .build()); + } + + return configurationData; + } + + @Override + public void insertValue(String namespace, String key, String value) { + ApplicationConfigEntity applicationConfigEntity = + new ApplicationConfigEntity(namespace, key, value); + applicationConfigDao.create(applicationConfigEntity); + } + + @Override + public Collection getListOfConfigurationByNamespace(String namespace) { + ApplicationConfigEntity applicationConfigEntity = + new ApplicationConfigEntity(namespace, null, null); + return applicationConfigDao.list(applicationConfigEntity); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/type/ConfigurationData.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/type/ConfigurationData.java new file mode 100644 index 0000000000..53d3797e53 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/type/ConfigurationData.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.applicationconfig.type; + +public class ConfigurationData { + + private String value; + private long timeStamp; + + public ConfigurationData(String value, long timeStamp) { + this.value = value; + this.timeStamp = timeStamp; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public long getTimeStamp() { + return timeStamp; + } + + public void setTimeStamp(long timeStamp) { + this.timeStamp = timeStamp; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..19d2cafe8f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/resources/factoryConfiguration.json @@ -0,0 +1,4 @@ +{ + "org.openecomp.core.utilities.applicationconfig.ApplicationConfigFactory":"org.openecomp.core.utilities.applicationconfig.impl.ApplicationConfigFactoryImpl", + "org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDaoFactory":"org.openecomp.core.utilities.applicationconfig.dao.impl.ApplicationConfigDaoFactoryImpl" +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/resources/logback.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/resources/logback.xml new file mode 100644 index 0000000000..e256e0b10a --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/resources/logback.xml @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + ${defaultPattern} + + + + + + + + ${logDirectory}/${eventType}.log + + ${logDirectory}/${eventType}.%i.log.zip + 1 + 9 + + + 5MB + + + ${default-log-pattern} + + + + + + + + + + \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/java/org/openecomp/sdc/applicationconfig/dao/ApplicationConfigImplDaoTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/java/org/openecomp/sdc/applicationconfig/dao/ApplicationConfigImplDaoTest.java new file mode 100644 index 0000000000..40cde1ecb2 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/java/org/openecomp/sdc/applicationconfig/dao/ApplicationConfigImplDaoTest.java @@ -0,0 +1,88 @@ +package org.openecomp.sdc.applicationconfig.dao; + +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityType; +import org.openecomp.core.utilities.applicationconfig.ApplicationConfig; +import org.openecomp.core.utilities.applicationconfig.ApplicationConfigFactory; +import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDao; +import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDaoFactory; +import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; +import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; +import org.openecomp.core.utilities.file.FileUtils; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + + +public class ApplicationConfigImplDaoTest { + + private static final String SCHEMA_GENERATOR_INITIALIZATION_ERROR = + "SCHEMA_GENERATOR_INITIALIZATION_ERROR"; + private static final String SCHEMA_GENERATOR_INITIALIZATION_ERROR_MSG = + "Error occurred while loading questionnaire schema templates"; + private static ApplicationConfigDao applicationConfigDao = + ApplicationConfigDaoFactory.getInstance().createInterface(); + private static ApplicationConfig applicationConfig = + ApplicationConfigFactory.getInstance().createInterface(); + +// @BeforeClass + public static void init() { + try { + + ApplicationConfigEntity applicationConfigEntity1 = + new ApplicationConfigEntity("test - namespace", "vsp", "vspTemplate"); + ApplicationConfigEntity applicationConfigEntity2 = + new ApplicationConfigEntity("test - namespace", "nic", "nicTemplate"); + ApplicationConfigEntity applicationConfigEntity3 = + new ApplicationConfigEntity("test - namespace", "component", "componentTemplate"); + + applicationConfigDao.create(applicationConfigEntity1); + applicationConfigDao.create(applicationConfigEntity2); + applicationConfigDao.create(applicationConfigEntity3); + + } catch (Exception e) { + throw new CoreException(new ErrorCode.ErrorCodeBuilder(). + withCategory(ErrorCategory.APPLICATION). + withId(SCHEMA_GENERATOR_INITIALIZATION_ERROR). + withMessage(SCHEMA_GENERATOR_INITIALIZATION_ERROR_MSG). + build()); + } + } + + private static String loadFileToString(String path) { + return new String(FileUtils.toByteArray(FileUtils.loadFileToInputStream(path))); + } + +// @Test + public void testApplicationConfigTimestampValue() { + ConfigurationData configurationData = applicationConfig + .getConfigurationData("test - namespace", CompositionEntityType.vsp.name()); + + Assert.assertNotNull(configurationData); + Assert.assertNotEquals(configurationData.getTimeStamp(), 0); + + } + +// @Test(dependsOnMethods = "testApplicationConfigTimestampValue") + public void testNotExistingApplicationConfigTimestampValue() { + try { + applicationConfig.getConfigurationData("test - namespace", "aaa"); + } catch (CoreException ce) { + Assert.assertEquals(ce.getMessage(), + "Configuration for namespace test - namespace and key aaa was not found"); + } + + } + +// @Test(dependsOnMethods = "testApplicationConfigTimestampValue") + public void testInsertApplicationConfiguration() { + String testTemplate = loadFileToString("questionnaire/testTemplate.txt"); + applicationConfig.insertValue("test_namespace", "test_key", testTemplate); + + Assert.assertEquals(testTemplate, + applicationConfig.getConfigurationData("test_namespace", "test_key").getValue()); + } + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/resources/questionnaire/testTemplate.txt b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/resources/questionnaire/testTemplate.txt new file mode 100644 index 0000000000..0bb19c5984 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/resources/questionnaire/testTemplate.txt @@ -0,0 +1,12 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "properties": { + "general": { + "type": "object", + "properties": { + "testObject":{ + "type": "string" + } + } +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/pom.xml new file mode 100644 index 0000000000..ccb3db833e --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/pom.xml @@ -0,0 +1,31 @@ + + 4.0.0 + + + org.openecomp.sdc + openecomp-sdc-lib + 1.0.0-SNAPSHOT + ../../.. + + + openecomp-facade-api + openecomp-facade-api + org.openecomp.core + + + + + + org.openecomp.core + openecomp-utilities-lib + ${project.version} + + + org.openecomp.core + openecomp-common-lib + ${project.version} + + + + \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/api/AbstractFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/api/AbstractFactory.java new file mode 100644 index 0000000000..53b8f00fc0 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/api/AbstractFactory.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.factory.api; + +import org.openecomp.core.factory.impl.AbstractFactoryBase; + +/** + * This class provides generic implementation of an abstract factory. Components exposed as Java + * interfaces should have their own concrete factories derived from the given class. This assures + * code alignment and consistency across all Service Management components. + * The class actually + * uses singleton pattern to instantiate and reuse just one instance of a factory. Therefore, each + * factory implementation has to be thread-safe. + * In a general case, the hierarchy of + * factory objects for an Java interface IUknown may look as follows: + *
+ *                     AbstractFactory<IUnknown>
+ *                                ^
+ *                                |
+ *   Application code ----> ConcreteFactory
+ *                                ^
+ *                                |
+ *                      +---------+---------+
+ *                      |                   |
+ *             BaselineFactoryImpl   CustomFactoryImpl
+ * 
+ * Where the classes responsibility is:
  • Abstract factory - common logic to retrieve the + * implementation class name from a central repository.
  • Concrete factory - abstract class + * that only exposes to application layer the type specific API such as:
    • public static + * ConcreteFactory getInstance()
  • Baseline factory - out of the box + * implementation of concrete factory (that can be replaced by a custom one depending on customer + * needs) which actually implements method:
    • public IUnknown createInterface()
    • + *
The normal concrete factory class may look like: + *
+ * public abstract class ConcreteFactory extends AbstractFactory<IUnknown> {
+ *   static {
+ *     registerFactory(ConcreteFactory.class, BaselineFactoryImpl.class);
+ *   }
+ * public static ConcreteFactory getInstance() {
+ * return AbstractFactory.<IUnknown, ConcreteFactory.class>getInstance(ConcreteFactory.class);
+ *   }
+ * }
+ * 
+ * + * @param Java interface type created by the factory. + */ +public abstract class AbstractFactory extends AbstractFactoryBase { + + + /** + * Returns the interface implementor instance. + * Note: It's up to the concrete factory to decide on the actual + * implementation of the returned interface. Therefore, the call can get the + * same instance per each call in case of singleton implementation or new + * instance otherwise. However, the API consumer may not assume anything + * regarding the underlying logic and has always go through the factory to + * obtain the reference. + * + * @return Implementor of the exposed Java interface. + */ + public abstract I createInterface(); + +} // End of class diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java new file mode 100644 index 0000000000..e19d9e972f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java @@ -0,0 +1,212 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.factory.impl; + +import static org.openecomp.core.utilities.CommonMethods.isEmpty; +import static org.openecomp.core.utilities.CommonMethods.newInstance; + +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; + + +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The type Abstract factory base. + */ +public abstract class AbstractFactoryBase { + + /** + * Temporary registry of default implementations. The map keeps class names rather then class + * types to allow unloading of those classes from memory by garbage collector if + * factory is not actually used. + */ + private static Map registry = new ConcurrentHashMap(); + + /** + * Cached factory instances. + */ + private static Map factoryMap = + new ConcurrentHashMap(); + + /** + * Registers implementor for an abstract factory. The method accepts Java classes rather + * then class names to ensure type safety at compilation time. + * + * @param Java interface type instantiated by abstract factory + * @param Type specific abstract factory for concrete Java interface + * @param factory Java class of a type specific abstract factory + * @param impl Java class of type specific factory implementor + */ + public static void registerFactory(Class factory, + Class impl) { + if (factory == null) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withId("E0001").withMessage("Mandatory input factory.") + .withCategory(ErrorCategory.SYSTEM).build()); + } + + if (impl == null) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withId("E0001").withMessage("Mandatory input impl.") + .withCategory(ErrorCategory.SYSTEM).build()); + } + if (factoryMap != null && factoryMap.containsKey(factory.getName())) { + factoryMap.remove(factory.getName()); + } + registry.put(factory.getName(), impl.getName()); + } // registerFactory + + /** + * Register factory. + * + * @param factoryName the factory name + * @param implName the impl name + */ + // TODO: Remove + protected static void registerFactory(String factoryName, String implName) { + registry.put(factoryName, implName); + } // registerFactory + + /** + * Unregister factory. + * + * @param the type parameter + * @param factory the factory + */ + public static void unregisterFactory(Class factory) { + if (factory == null) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withId("E0001").withMessage("Mandatory input factory.") + .withCategory(ErrorCategory.SYSTEM).build()); + } + if (factoryMap != null) { + factoryMap.remove(factory.getName()); + } + } + + /** + * Instantiates the configured implementation of an abstract factory. + * + * @param Java interface type instantiated by abstract factory + * @param Type specific abstract factory for concrete Java interface + * @param factoryType Java class of type specific abstract factory + * @return Instance of implementation class + */ + @SuppressWarnings("unchecked") + public static F getInstance(Class factoryType) { + if (factoryType == null) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withId("E0001") + .withMessage("Mandatory input factory type.").withCategory(ErrorCategory.SYSTEM) + .build()); + + } + // Pick up factory instance from cache + F factory = (F) factoryMap.get(factoryType.getName()); + // Check for the first time access + if (factory == null) { + // Synchronize factory instantiation + synchronized (factoryType) { + // Re-check the factory instance + factory = (F) factoryMap.get(factoryType.getName()); + if (factory == null) { + // Get the implementation class name + String implName = registry.get(factoryType.getName()); + + if (isEmpty(implName)) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withId("E0001") + .withMessage("Mandatory input factory implementation.") + .withCategory(ErrorCategory.SYSTEM).build()); + } + + factory = newInstance(implName, factoryType); + + factory.init(); + + // Cache the instantiated singleton + factoryMap.put(factoryType.getName(), factory); + } + } + } + + return factory; + + } // getInstance + + + /** + * Is factory registered boolean. + * + * @param the type parameter + * @param factoryType the factory type + * @return the boolean + */ + public static boolean isFactoryRegistered(Class factoryType) { + boolean isFactoryRegistered = false; + if (factoryType == null) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withId("E0001") + .withMessage("Mandatory input factory type.").withCategory(ErrorCategory.SYSTEM) + .build()); + } + // Pick up factory instance from cache + F factory = (F) factoryMap.get(factoryType.getName()); + // Check for the first time access + if (factory != null) { + isFactoryRegistered = true; + } else { + // Get the implementation class name + String implName = registry.get(factoryType.getName()); + if (!isEmpty(implName)) { + isFactoryRegistered = true; + } + } + return isFactoryRegistered; + } + + /** + * Stop all. + */ + public static void stopAll() { + Collection factorylist = factoryMap.values(); + for (AbstractFactoryBase factory : factorylist) { + factory.stop(); + } + } + + /** + * Init. + */ + protected void init() { + } + + /** + * Stop. + */ + protected void stop() { + } + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/pom.xml new file mode 100644 index 0000000000..0c5d36abcc --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + + + openecomp-sdc-lib + org.openecomp.sdc + 1.0.0-SNAPSHOT + ../../.. + + + openecomp-facade-core + openecomp-facade-core + org.openecomp.core + + + + org.openecomp.core + openecomp-utilities-lib + ${project.version} + + + org.openecomp.core + openecomp-common-lib + ${project.version} + + + org.openecomp.core + openecomp-facade-api + ${project.version} + + + + + + \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/AbstractContextFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/AbstractContextFactory.java new file mode 100644 index 0000000000..f4e1a85fee --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/AbstractContextFactory.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.factory; + +import org.openecomp.core.factory.impl.AbstractFactoryBase; + +public abstract class AbstractContextFactory extends AbstractFactoryBase { + public abstract I createInterface(C contextType); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoriesConfigImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoriesConfigImpl.java new file mode 100644 index 0000000000..173f9b15b1 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoriesConfigImpl.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.factory; + + +import org.openecomp.core.factory.api.FactoriesConfiguration; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.core.utilities.json.JsonUtil; + +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public final class FactoriesConfigImpl implements FactoriesConfiguration { + + + private static final String FACTORY_CONFIG_FILE_NAME = "factoryConfiguration.json"; + private static Map factoryMap = new HashMap(); + private static boolean initialized = false; + + @SuppressWarnings("unchecked") + @Override + public Map getFactoriesMap() { + synchronized (this) { + if (!initialized) { + init(); + initialized = true; + } + } + return factoryMap; + } + + private void init() { + List factoryConfigIsList = FileUtils.getFileInputStreams(FACTORY_CONFIG_FILE_NAME); + for (InputStream factoryConfigIs : factoryConfigIsList) { + factoryMap.putAll(JsonUtil.json2Object(factoryConfigIs, Map.class)); + } + } + + +} + diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoryConfig.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoryConfig.java new file mode 100644 index 0000000000..d664cbee38 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoryConfig.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.factory; + +import org.openecomp.core.factory.api.FactoriesConfiguration; +import org.openecomp.core.utilities.CommonMethods; + +import java.util.Map; + +public final class FactoryConfig { + + private static final FactoriesConfiguration INSTANCE; + + static { + + try { + INSTANCE = CommonMethods.newInstance( + "org.openecomp.core.factory.FactoriesConfigImpl", FactoriesConfiguration.class); + } catch (Exception exception) { + exception.printStackTrace(); + throw exception; + } + } + + public static Map getFactoriesMap() { + return INSTANCE.getFactoriesMap(); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/AbstractComponentFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/AbstractComponentFactory.java new file mode 100644 index 0000000000..9cd7749f55 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/AbstractComponentFactory.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.factory.api; + +import org.openecomp.core.factory.FactoryConfig; +import org.openecomp.core.factory.impl.AbstractFactoryBase; +import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; + +import java.util.Map; + +public abstract class AbstractComponentFactory extends AbstractFactory { + + static { + Registry registry = new RegistryImpl(); + InitializationHelper.registerFactoryMapping(registry); + } + + interface Registry { + void register(String factory, String impl); + } + + private static class RegistryImpl implements Registry { + @Override + public void register(String factory, String impl) { + AbstractFactoryBase.registerFactory(factory, impl); + } + } + + static class InitializationHelper { + + + private static boolean isRegistered = false; + + private InitializationHelper() { + } + + static synchronized boolean registerFactoryMapping(Registry registry) { + + boolean done = !isRegistered; + + if (!isRegistered) { + registerFactoryMappingImpl(registry); + isRegistered = true; + } + + return done; + } + + private static void registerFactoryMappingImpl(Registry registry) { + Map factoryMap = FactoryConfig.getFactoriesMap(); + + try { + for (Map.Entry entry : factoryMap.entrySet()) { + String abstractClassName = entry.getKey(); + String concreteTypeName = entry.getValue(); + + if (CommonMethods.isEmpty(concreteTypeName)) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withId("E0003") + .withMessage("Missing configuration value:" + concreteTypeName + ".") + .withCategory(ErrorCategory.SYSTEM).build()); + + } + + registry.register(abstractClassName, concreteTypeName); + } + } catch (RuntimeException exception) { + throw exception; + } catch (Exception exception) { + throw new RuntimeException(exception); + } + } + + @SuppressWarnings("unchecked") + private static Class unsecureCast(Class cls) { + return (Class) cls; + } + + private static String nameOf(Class clazz) { + return (clazz != null) ? clazz.getName() : "null"; + } + } + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/FactoriesConfiguration.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/FactoriesConfiguration.java new file mode 100644 index 0000000000..8086181204 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/FactoriesConfiguration.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.factory.api; + +import java.util.Map; + + +public interface FactoriesConfiguration { + + Map getFactoriesMap(); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/pom.xml new file mode 100644 index 0000000000..29e9cce688 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/pom.xml @@ -0,0 +1,34 @@ + + 4.0.0 + + + openecomp-core-lib + org.openecomp.core + 1.0.0-SNAPSHOT + + + pom + openecomp-facade-lib + openecomp-facade-lib + + + openecomp-facade-api + openecomp-facade-core + + + + + org.openecomp.core + openecomp-facade-api + ${project.version} + compile + + + org.openecomp.core + openecomp-facade-core + ${project.version} + runtime + + + \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/pom.xml new file mode 100644 index 0000000000..174f2a36d9 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/pom.xml @@ -0,0 +1,40 @@ + + 4.0.0 + + + openecomp-sdc-lib + org.openecomp.sdc + 1.0.0-SNAPSHOT + ../../.. + + + openecomp-nosqldb-api + openecomp-nosqldb-api + org.openecomp.core + + + + org.openecomp.core + openecomp-facade-api + ${project.version} + + + com.datastax.cassandra + cassandra-driver-core + ${datasatx.version} + + + com.datastax.cassandra + cassandra-driver-mapping + ${datasatx.version} + + + org.openecomp.core + openecomp-facade-core + ${project.version} + + + + + \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/BaseDao.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/BaseDao.java new file mode 100644 index 0000000000..c7623f8181 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/BaseDao.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.dao; + +import java.util.Collection; + +public interface BaseDao { + + Collection list(T entity); + + void create(T entity); + + void update(T entity); + + T get(T entity); + + void delete(T entity); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDao.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDao.java new file mode 100644 index 0000000000..1fa4bb23fe --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDao.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.dao; + + +import org.openecomp.core.dao.types.UniqueValueEntity; + +public interface UniqueValueDao extends BaseDao { + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDaoFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDaoFactory.java new file mode 100644 index 0000000000..9f57e4fadd --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDaoFactory.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.dao; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +public abstract class UniqueValueDaoFactory extends AbstractComponentFactory { + public static UniqueValueDaoFactory getInstance() { + return AbstractFactory.getInstance(UniqueValueDaoFactory.class); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/types/UniqueValueEntity.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/types/UniqueValueEntity.java new file mode 100644 index 0000000000..1147644253 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/types/UniqueValueEntity.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.dao.types; + +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; + +@Table(keyspace = "dox", name = "unique_value") +public class UniqueValueEntity { + + @PartitionKey + private String type; + + @PartitionKey(value = 1) + private String value; + + public UniqueValueEntity() { + } + + public UniqueValueEntity(String type, String value) { + this.type = type; + this.value = value; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/api/NoSqlDb.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/api/NoSqlDb.java new file mode 100644 index 0000000000..6b13ee71e4 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/api/NoSqlDb.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.nosqldb.api; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.mapping.MappingManager; + +public interface NoSqlDb { + + //TODO: remove cassandra types from here!! (like done in SDC...). + + void insert(String tableName, String[] colNames, Object[] values); + + ResultSet execute(String statement); + + ResultSet execute(String statementName, Object... values); + + MappingManager getMappingManager(); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/factory/NoSqlDbFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/factory/NoSqlDbFactory.java new file mode 100644 index 0000000000..ede264f288 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/factory/NoSqlDbFactory.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.nosqldb.factory; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; +import org.openecomp.core.nosqldb.api.NoSqlDb; + + +public abstract class NoSqlDbFactory extends AbstractComponentFactory { + + public static NoSqlDbFactory getInstance() { + + return AbstractFactory.getInstance(NoSqlDbFactory.class); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/util/UniqueValueUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/util/UniqueValueUtil.java new file mode 100644 index 0000000000..a82c97c51c --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/util/UniqueValueUtil.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.util; + +import org.openecomp.core.dao.UniqueValueDao; +import org.openecomp.core.dao.UniqueValueDaoFactory; +import org.openecomp.core.dao.types.UniqueValueEntity; +import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; + +import java.util.Optional; + +/** + * The type Unique value util. + */ +public class UniqueValueUtil { + /** + * The constant UNIQUE_VALUE_VIOLATION. + */ + public static final String UNIQUE_VALUE_VIOLATION = "UNIQUE_VALUE_VIOLATION"; + private static final String UNIQUE_VALUE_VIOLATION_MSG = "%s with the value '%s' already exists."; + + private static final UniqueValueDao uniqueValueDao = + UniqueValueDaoFactory.getInstance().createInterface(); + + /** + * Create unique value. + * + * @param type the type + * @param uniqueCombination the unique combination + */ + public static void createUniqueValue(String type, String... uniqueCombination) { + Optional value = formatValue(uniqueCombination); + if (!value.isPresent()) { + return; + } + validateUniqueValue(type, value.get(), uniqueCombination); + uniqueValueDao.create(new UniqueValueEntity(type, value.get())); + } + + /** + * Delete unique value. + * + * @param type the type + * @param uniqueCombination the unique combination + */ + public static void deleteUniqueValue(String type, String... uniqueCombination) { + Optional value = formatValue(uniqueCombination); + if (!value.isPresent()) { + return; + } + uniqueValueDao.delete(new UniqueValueEntity(type, value.get())); + } + + /** + * Update unique value. + * + * @param type the type + * @param oldValue the old value + * @param newValue the new value + * @param uniqueContext the unique context + */ + public static void updateUniqueValue(String type, String oldValue, String newValue, + String... uniqueContext) { + if ((newValue != null && oldValue != null + && !newValue.toLowerCase().equals(oldValue.toLowerCase())) + || newValue == null || oldValue == null) { + createUniqueValue(type, CommonMethods.concat(uniqueContext, new String[]{newValue})); + deleteUniqueValue(type, CommonMethods.concat(uniqueContext, new String[]{oldValue})); + } + } + + /** + * Validate unique value. + * + * @param type the type + * @param uniqueCombination the unique combination + */ + public static void validateUniqueValue(String type, String... uniqueCombination) { + Optional value = formatValue(uniqueCombination); + if (!value.isPresent()) { + return; + } + validateUniqueValue(type, value.get(), uniqueCombination); + } + + private static void validateUniqueValue(String type, String value, String... uniqueCombination) { + if (uniqueValueDao.get(new UniqueValueEntity(type, value)) != null) { + throw new CoreException(new ErrorCode.ErrorCodeBuilder() + .withCategory(ErrorCategory.APPLICATION) + .withId(UNIQUE_VALUE_VIOLATION) + .withMessage(String.format(UNIQUE_VALUE_VIOLATION_MSG, type, + uniqueCombination[uniqueCombination.length - 1])).build()); + } + } + + private static Optional formatValue(String[] uniqueCombination) { + if (uniqueCombination == null || uniqueCombination.length == 0 + || uniqueCombination[uniqueCombination.length - 1] == null) { + return Optional.empty(); + } + + uniqueCombination[uniqueCombination.length - 1] = + uniqueCombination[uniqueCombination.length - 1].toLowerCase(); + return Optional.of(CommonMethods.arrayToSeparatedString(uniqueCombination, '_')); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/resources/cassandraStatements.json b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/resources/cassandraStatements.json new file mode 100644 index 0000000000..e83b9f0126 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/resources/cassandraStatements.json @@ -0,0 +1,6 @@ +{ + "test.select.all": "SELECT * FROM test", + "test.drop": "DROP TABLE IF EXISTS test", + "test.create": "CREATE TABLE test (name text PRIMARY KEY,value text)", + "test.insert": "INSERT INTO test (name,value) VALUES ( ?,?)" +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..0d5440508f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/resources/factoryConfiguration.json @@ -0,0 +1,4 @@ +{ + "org.openecomp.core.dao.UniqueValueDaoFactory": "org.openecomp.core.dao.impl.UniqueValueDaoFactoryImpl", + "org.openecomp.core.nosqldb.factory.NoSqlDbFactory": "org.openecomp.core.nosqldb.impl.cassandra.CassandraNoSqlDbFactoryImpl" +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/pom.xml new file mode 100644 index 0000000000..d799edb961 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/pom.xml @@ -0,0 +1,60 @@ + + 4.0.0 + + + openecomp-sdc-lib + org.openecomp.sdc + 1.0.0-SNAPSHOT + ../../.. + + + org.openecomp.core + openecomp-nosqldb-core + openecomp-nosqldb-core + + + + + org.openecomp.core + openecomp-nosqldb-api + ${project.version} + + + org.yaml + snakeyaml + 1.14 + test + + + com.google.code.gson + gson + 2.3.1 + test + + + org.mockito + mockito-all + test + 1.10.19 + + + org.testng + testng + test + 6.8.5 + + + snakeyaml + org.yaml + + + + + junit + junit + test + RELEASE + + + \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/CassandraBaseDao.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/CassandraBaseDao.java new file mode 100644 index 0000000000..1b3dbc4c6f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/CassandraBaseDao.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.dao.impl; + +import com.datastax.driver.mapping.Mapper; +import org.openecomp.core.dao.BaseDao; + +public abstract class CassandraBaseDao implements BaseDao { + protected abstract Mapper getMapper(); + + protected abstract Object[] getKeys(T entity); + + @Override + public void create(T entity) { + getMapper().save(entity); + } + + @Override + public void update(T entity) { + getMapper().save(entity); + } + + @Override + public T get(T entity) { + return getMapper().get(getKeys(entity)); + } + + @Override + public void delete(T entity) { + getMapper().delete(entity); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueCassandraDaoImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueCassandraDaoImpl.java new file mode 100644 index 0000000000..31dd602400 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueCassandraDaoImpl.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.dao.impl; + +import com.datastax.driver.mapping.Mapper; +import com.datastax.driver.mapping.Result; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.core.dao.UniqueValueDao; +import org.openecomp.core.dao.types.UniqueValueEntity; +import org.openecomp.core.nosqldb.api.NoSqlDb; +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; + +import java.util.Collection; + +public class UniqueValueCassandraDaoImpl extends CassandraBaseDao + implements UniqueValueDao { + + private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static Mapper mapper = + noSqlDb.getMappingManager().mapper(UniqueValueEntity.class); + private static UniqueValueAccessor accessor = + noSqlDb.getMappingManager().createAccessor(UniqueValueAccessor.class); + + + @Override + protected Mapper getMapper() { + return mapper; + } + + @Override + protected Object[] getKeys(UniqueValueEntity entity) { + return new Object[]{entity.getType(), entity.getValue()}; + } + + @Override + public Collection list(UniqueValueEntity entity) { + return accessor.listAll().all(); + } + + @Accessor + interface UniqueValueAccessor { + + @Query("select * from unique_value") + Result listAll(); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueDaoFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueDaoFactoryImpl.java new file mode 100644 index 0000000000..b717fcbee1 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueDaoFactoryImpl.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.dao.impl; + +import org.openecomp.core.dao.UniqueValueDao; +import org.openecomp.core.dao.UniqueValueDaoFactory; + +public class UniqueValueDaoFactoryImpl extends UniqueValueDaoFactory { + private static UniqueValueDao INSTANCE = new UniqueValueCassandraDaoImpl(); + + @Override + public UniqueValueDao createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbFactoryImpl.java new file mode 100644 index 0000000000..2922925171 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbFactoryImpl.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.nosqldb.impl.cassandra; + +import com.datastax.driver.core.Session; +import org.openecomp.core.nosqldb.api.NoSqlDb; +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; + +public class CassandraNoSqlDbFactoryImpl extends NoSqlDbFactory { + + @Override + public NoSqlDb createInterface() { + + + return new CassandraNoSqlDbImpl(ReferenceHolder.CASSANDRA); + } + + protected void stop() { + ReferenceHolder.CASSANDRA.close(); + } + + private static class ReferenceHolder { + private static final Session CASSANDRA = CassandraSessionFactory.getSession(); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbImpl.java new file mode 100644 index 0000000000..bcac5f8d79 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbImpl.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.nosqldb.impl.cassandra; + +import com.datastax.driver.core.BoundStatement; +import com.datastax.driver.core.PreparedStatement; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Session; +import com.datastax.driver.mapping.MappingManager; +import org.openecomp.core.nosqldb.api.NoSqlDb; +import org.openecomp.core.nosqldb.util.CassandraUtils; +import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; + +class CassandraNoSqlDbImpl implements NoSqlDb { + + private final Session session; + private final String keySpace; + private final MappingManager mappingManager; + + + public CassandraNoSqlDbImpl(Session session) { + this.session = session; + this.keySpace = this.session.getLoggedKeyspace(); + this.mappingManager = new MappingManager(this.session); + + } + + @Override + public void insert(String tableName, String[] colNames, Object[] values) { + if (colNames.length != values.length) { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage( + "number of colmuns[" + colNames.length + "] is not equal to the number of values[" + + values.length + "].").withId("E0005").withCategory(ErrorCategory.APPLICATION) + .build()); + } + + StringBuilder sb = new StringBuilder(); + sb.append("insert into ") + .append(tableName) + .append(" (") + .append(CommonMethods.arrayToCommaSeparatedString(colNames)) + .append(") values (") + .append(CommonMethods.duplicateStringWithDelimiter("?", ',', values.length)) + .append(")"); + System.out.println(sb.toString()); + PreparedStatement prepared = session.prepare(sb.toString()); + + BoundStatement bound; + bound = prepared.bind(values); + session.execute(bound); + + } + + @Override + public ResultSet execute(String statement) { + return session.execute(statement); + } + + @Override + public ResultSet execute(String statementName, Object... values) { + + String statement = CassandraUtils.getStatement(statementName); + if (statement == null) { + statement = statementName; + } + if (values != null) { + PreparedStatement prepared = session.prepare(statement); + + BoundStatement bound; + bound = prepared.bind(values); + return session.execute(bound); + } else { + return session.execute(statement); + } + + } + + @Override + public MappingManager getMappingManager() { + return mappingManager; + } + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraSessionFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraSessionFactory.java new file mode 100644 index 0000000000..1b98f095b5 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraSessionFactory.java @@ -0,0 +1,124 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.nosqldb.impl.cassandra; + +import com.google.common.base.Optional; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.SSLOptions; +import com.datastax.driver.core.Session; + +import org.openecomp.core.nosqldb.util.CassandraUtils; + +import java.io.FileInputStream; +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +public class CassandraSessionFactory { + public static Session getSession() { + return ReferenceHolder.CASSANDRA; + } + + /** + * New cassandra session session. + * + * @return the session + */ + public static Session newCassandraSession() { + Cluster.Builder builder = Cluster.builder(); + String[] addresses = CassandraUtils.getAddresses(); + for (String address : addresses) { + builder.addContactPoint(address); + } + Boolean isSsl = CassandraUtils.isSsl(); + if (isSsl) { + builder.withSSL(getSslOptions().get()); + } + int port = CassandraUtils.getCassandraPort(); + if (port > 0) { + builder.withPort(port); + } + //Check if user/pass + Boolean isAuthenticate = CassandraUtils.isAuthenticate(); + if (isAuthenticate) { + builder.withCredentials(CassandraUtils.getUser(), CassandraUtils.getPassword()); + } + + Cluster cluster = builder.build(); + String keyStore = CassandraUtils.getKeySpace(); + return cluster.connect(keyStore); + } + + private static Optional getSslOptions() { + Optional truststorePath = Optional.of(CassandraUtils.getTruststore()); + Optional truststorePassword = Optional.of(CassandraUtils.getTruststorePassword()); + + if (truststorePath.isPresent() && truststorePassword.isPresent()) { + SSLContext context; + try { + context = getSslContext(truststorePath.get(), truststorePassword.get()); + } catch (UnrecoverableKeyException | KeyManagementException + | NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e0) { + throw new RuntimeException(e0); + } + String[] css = new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"}; + return Optional.of(new SSLOptions(context, css)); + } + return Optional.absent(); + } + + private static SSLContext getSslContext(String truststorePath, String truststorePassword) + throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, + UnrecoverableKeyException, KeyManagementException { + FileInputStream tsf = null; + SSLContext ctx = null; + try { + tsf = new FileInputStream(truststorePath); + ctx = SSLContext.getInstance("SSL"); + + KeyStore ts = KeyStore.getInstance("JKS"); + ts.load(tsf, truststorePassword.toCharArray()); + TrustManagerFactory tmf = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(ts); + + ctx.init(null, tmf.getTrustManagers(), new SecureRandom()); + } catch (Exception e0) { + e0.printStackTrace(); + } finally { + tsf.close(); + + } + return ctx; + } + + private static class ReferenceHolder { + private static final Session CASSANDRA = newCassandraSession(); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/CassandraUtils.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/CassandraUtils.java new file mode 100644 index 0000000000..2a88d0e521 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/CassandraUtils.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.nosqldb.util; + +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.core.utilities.json.JsonUtil; + +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +public class CassandraUtils { + + + private static final String CASSANDRA_STATEMENT_DEFINITION_FILE = "cassandraStatements.json"; + private static Map statementMap = new HashMap<>(); + + public static String[] getAddresses() { + return ConfigurationManager.getInstance().getAddresses(); + + } + + public static String getKeySpace() { + return ConfigurationManager.getInstance().getKeySpace(); + } + + /** + * Gets statement. + * + * @param statementName the statement name + * @return the statement + */ + public static String getStatement(String statementName) { + if (statementMap.size() == 0) { + InputStream statementJson = FileUtils.getFileInputStream(CASSANDRA_STATEMENT_DEFINITION_FILE); + statementMap = JsonUtil.json2Object(statementJson, Map.class); + } + return statementMap.get(statementName); + } + + public static String getUser() { + + return ConfigurationManager.getInstance().getUsername(); + } + + public static String getPassword() { + return ConfigurationManager.getInstance().getPassword(); + + } + + public static String getTruststore() { + return ConfigurationManager.getInstance().getTruststorePath(); + + } + + public static String getTruststorePassword() { + return ConfigurationManager.getInstance().getTruststorePassword(); + + } + + public static int getCassandraPort() { + return ConfigurationManager.getInstance().getSslPort(); + + } + + public static boolean isSsl() { + return ConfigurationManager.getInstance().isSsl(); + + } + + public static boolean isAuthenticate() { + return ConfigurationManager.getInstance().isAuthenticate(); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/ConfigurationManager.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/ConfigurationManager.java new file mode 100644 index 0000000000..a1c0b528fb --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/ConfigurationManager.java @@ -0,0 +1,234 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.nosqldb.util; + +import org.openecomp.core.utilities.yaml.YamlUtil; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The type Configuration manager. + */ +public class ConfigurationManager { + + private static final String CONFIGURATION_YAML_FILE = "configuration.yaml"; + private static final String cassandraKey = "cassandraConfig"; + private static final String DEFAULT_KEYSPACE_NAME = "dox"; + private static final String CASSANDRA_ADDRESSES = "cassandra.addresses"; + private static final String CASSANDRA_DOX_KEY_STORE = "cassandra.dox.keystore"; + private static final String CASSANDRA_AUTHENTICATE = "cassandra.authenticate"; + private static final String CASSANDRA_USER = "cassandra.user"; + private static final String CASSANDRA_PASSWORD = "cassandra.password"; + private static final String CASSANDRA_PORT = "cassandra.port"; + private static final String CASSANDRA_SSL = "cassandra.ssl"; + private static final String CASSANDRA_TRUSTSTORE = "cassandra.Truststore"; + private static final String CASSANDRA_TRUSTSTORE_PASSWORD = "cassandra.TruststorePassword"; + private static final String cassandraHostsKey = "cassandraHosts"; + private static final String cassandraPortKey = "port"; + private static final String cassandraUsernameKey = "username"; + private static final String cassandraPasswordKey = "password"; + private static final String cassandraAuthenticateKey = "authenticate"; + private static final String cassandraSSLKey = "ssl"; + private static final String cassandraTruststorePathKey = "truststorePath"; + private static final String cassandraTruststorePasswordKey = "truststorePassword"; + private static ConfigurationManager instance = null; + private final LinkedHashMap cassandraConfiguration; + + + private ConfigurationManager() { + YamlUtil yamlUtil = new YamlUtil(); + String configurationYamlFile = System.getProperty(CONFIGURATION_YAML_FILE); + InputStream yamlAsString; + if (configurationYamlFile != null) { + yamlAsString = getConfigFileIs(configurationYamlFile); + } else { + //Load from resources + yamlAsString = yamlUtil.loadYamlFileIs("/" + CONFIGURATION_YAML_FILE); + } + Map> configurationMap = yamlUtil.yamlToMap(yamlAsString); + cassandraConfiguration = configurationMap.get(cassandraKey); + + } + + /** + * Gets instance. + * + * @return the instance + */ + public static ConfigurationManager getInstance() { + if (instance == null) { + instance = new ConfigurationManager(); + } + return instance; + } + + /** + * Get addresses string [ ]. + * + * @return the string [ ] + */ + public String[] getAddresses() { + + String addresses = System.getProperty(CASSANDRA_ADDRESSES); + if (addresses != null) { + return addresses.split(","); + } + List locAddresses = (ArrayList) cassandraConfiguration.get(cassandraHostsKey); + String[] addressesArray; + addressesArray = (String[]) locAddresses.toArray(new String[locAddresses.size()]); + return addressesArray; + + } + + /** + * Gets key space. + * + * @return the key space + */ + public String getKeySpace() { + String keySpace = System.getProperty(CASSANDRA_DOX_KEY_STORE); + if (keySpace == null) { + //keySpace = cassandraConfiguration.get(cassandraKeySpaceKey); + //if (keySpace == null) + keySpace = DEFAULT_KEYSPACE_NAME; + } + return keySpace; + } + + /** + * Gets username. + * + * @return the username + */ + public String getUsername() { + String username = System.getProperty(CASSANDRA_USER); + if (username == null) { + username = (String) cassandraConfiguration.get(cassandraUsernameKey); + } + return username; + } + + /** + * Gets password. + * + * @return the password + */ + public String getPassword() { + String password = System.getProperty(CASSANDRA_PASSWORD); + if (password == null) { + password = (String) cassandraConfiguration.get(cassandraPasswordKey); + } + return password; + } + + /** + * Gets truststore path. + * + * @return the truststore path + */ + public String getTruststorePath() { + String truststorePath = System.getProperty(CASSANDRA_TRUSTSTORE); + if (truststorePath == null) { + truststorePath = (String) cassandraConfiguration.get(cassandraTruststorePathKey); + } + return truststorePath; + } + + /** + * Gets truststore password. + * + * @return the truststore password + */ + public String getTruststorePassword() { + String truststorePassword = System.getProperty(CASSANDRA_TRUSTSTORE_PASSWORD); + if (truststorePassword == null) { + truststorePassword = (String) cassandraConfiguration.get(cassandraTruststorePasswordKey); + } + return truststorePassword; + } + + /** + * Gets ssl port. + * + * @return the ssl port + */ + public int getSslPort() { + int port; + String sslPort = System.getProperty(CASSANDRA_PORT); + if (sslPort == null) { + sslPort = (String) cassandraConfiguration.get(cassandraPortKey); + if (sslPort == null) { + sslPort = "0"; + } + } + port = Integer.valueOf(sslPort); + return port; + } + + + /** + * Is ssl boolean. + * + * @return the boolean + */ + public boolean isSsl() { + return getBooleanResult(CASSANDRA_SSL, cassandraSSLKey); + } + + /** + * Is authenticate boolean. + * + * @return the boolean + */ + public boolean isAuthenticate() { + return getBooleanResult(CASSANDRA_AUTHENTICATE, cassandraAuthenticateKey); + } + + private Boolean getBooleanResult(String property, String key) { + Boolean res; + String value; + if (System.getProperty(property) == null) { + value = String.valueOf(cassandraConfiguration.get(key)); + } else { + value = System.getProperty(property); + } + + res = Boolean.valueOf(value); + + return res; + } + + private InputStream getConfigFileIs(String file) { + InputStream is = null; + try { + is = new FileInputStream(file); + } catch (FileNotFoundException e0) { + e0.printStackTrace(); + } + return is; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/resources/configuration.yaml b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/resources/configuration.yaml new file mode 100644 index 0000000000..0988f50237 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/resources/configuration.yaml @@ -0,0 +1,253 @@ +identificationHeaderFields: + - HTTP_IV_USER + - HTTP_CSP_FIRSTNAME + - HTTP_CSP_LASTNAME + - HTTP_IV_REMOTE_ADDRESS + - HTTP_CSP_WSTYPE + + + +# catalog backend hostname +beFqdn: sdccatalog.att.com + +# catalog backend http port +beHttpPort: 8080 + +# catalog backend http context +beContext: /sdc/rest/config/get + +# catalog backend protocol +beProtocol: http + +# catalog backend ssl port +beSslPort: 8443 + +version: 1.0 +released: 2012-11-30 + +titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties +titanInMemoryGraph: false +titanLockTimeout: 30 +titanReconnectIntervalInSeconds: 3 +titanHealthCheckReadTimeout: 1 +esReconnectIntervalInSeconds: 3 +uebHealthCheckReconnectIntervalInSeconds: 15 +uebHealthCheckReadTimeout: 4 + +# Protocols +protocols: + - http + - https + +# Users +users: + tom: passwd + bob: passwd + +neo4j: + host: neo4jhost + port: 7474 + user: neo4j + password: "12345" + +cassandraConfig: + cassandraHosts: ['127.0.0.1'] + reconnectTimeout : 30000 + authenticate: false + username: sdc_user + password: Aa1234%^! + ssl: false + truststorePath : /path/path + truststorePassword : Aa123456 + keySpaces: + - { name: dox, replicationStrategy: SimpleStrategy, replicationInfo: ['1']} + - { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']} + +#Application-specific settings of ES +elasticSearch: + # Mapping of index prefix to time-based frame. For example, if below is configured: + # + # - indexPrefix: auditingevents + # creationPeriod: minute + # + # then ES object of type which is mapped to "auditingevents-*" template, and created on 2015-12-23 13:24:54, will enter "auditingevents-2015-12-23-13-24" index. + # Another object created on 2015-12-23 13:25:54, will enter "auditingevents-2015-12-23-13-25" index. + # If creationPeriod: month, both of the above will enter "auditingevents-2015-12" index. + # + # PLEASE NOTE: the timestamps are created in UTC/GMT timezone! This is needed so that timestamps will be correctly presented in Kibana. + # + # Legal values for creationPeriod - year, month, day, hour, minute, none (meaning no time-based behaviour). + # + # If no creationPeriod is configured for indexPrefix, default behavour is creationPeriod: month. + + indicesTimeFrequency: + - indexPrefix: auditingevents + creationPeriod: month + - indexPrefix: monitoring_events + creationPeriod: month + +artifactTypes: + - CHEF + - PUPPET + - SHELL + - YANG + - YANG_XML + - HEAT + - BPEL + - DG_XML + - MURANO_PKG + - OTHER + +licenseTypes: + - User + - Installation + - CPU + +#Deployment artifacts placeHolder +deploymentResourceArtifacts: + heat: + displayName: "HEAT Template" + type: HEAT + +deploymentResourceInstanceArtifacts: + heatEnv: + displayName: "HEAT ENV" + type: HEAT_ENV + description: "Auto-generated HEAT Environment deployment artifact" + fileExtension: "env" + +#Informational artifacts placeHolder +excludeResourceCategory: + - Generic +informationalResourceArtifacts: + features: + displayName: Features + type: OTHER + capacity: + displayName: Capacity + type: OTHER + vendorTestResult: + displayName: Vendor Test Result + type: OTHER + testScripts: + displayName: Test Scripts + type: OTHER + cloudQuestionnaire: + displayName: Cloud Questionnaire (completed) + type: OTHER + HEATTemplateFromVendor: + displayName: HEAT Template from Vendor + type: HEAT + +excludeServiceCategory: + +informationalServiceArtifacts: + messageFlows: + displayName: Message Flows + type: OTHER + instantiationFlows: + displayName: Management Flows + type: OTHER + serviceArtifactPlan: + displayName: Service Artifact Plan + type: OTHER + summaryOfImpactsToECOMPElements: + displayName: Summary of impacts to ECOMP elements,OSSs, BSSs + type: OTHER + controlLoopFunctions: + displayName: Control Loop Functions + type: OTHER + dimensioningInfo: + displayName: Dimensioning Info + type: OTHER + affinityRules: + displayName: Affinity Rules + type: OTHER + operationalPolicies: + displayName: Operational Policies + type: OTHER + serviceSpecificPolicies: + displayName: Service-specific Policies + type: OTHER + engineeringRules: + displayName: Engineering Rules (ERD) + type: OTHER + distributionInstructions: + displayName: Distribution Instructions + type: OTHER + certificationTestResults: + displayName: TD Certification Test Results + type: OTHER + deploymentVotingRecord: + displayName: Deployment Voting Record + type: OTHER + serviceQuestionnaire: + displayName: Service Questionnaire + type: OTHER + +serviceApiArtifacts: + configuration: + displayName: Configuration + type: OTHER + instantiation: + displayName: Instantiation + type: OTHER + monitoring: + displayName: Monitoring + type: OTHER + reporting: + displayName: Reporting + type: OTHER + logging: + displayName: Logging + type: OTHER + testing: + displayName: Testing + type: OTHER + + +additionalInformationMaxNumberOfKeys: 50 + +systemMonitoring: + enabled: false + isProxy: false + probeIntervalInSeconds: 15 + +defaultHeatArtifactTimeoutMinutes: 60 + +serviceDeploymentArtifacts: + +resourceDeploymentArtifacts: + HEAT: + acceptedTypes: + - yaml + - yml + +resourceInformationalDeployedArtifacts: + YANG_XML: + acceptedTypes: + - xml + + +unLoggedUrls: + - /sdc2/rest/healthCheck + +cleanComponentsConfiguration: + cleanIntervalInMinutes: 1440 + componentsToClean: + - Resource + +artifactsIndex: resources + +heatEnvArtifactHeader: + " # _______________________________________________________________________________________________________________________________________\n + #| AT&T Proprietary (Restricted) |\n + #| Only for use by authorized individuals or any above-designated team(s) |\n + #| within the AT&T companies and not for general distribution |\n + #|_______________________________________________________________________________________________________________________________________|\n" +heatEnvArtifactFooter: + " # _______________________________________________________________________________________________________________________________________\n + #| AT&T Proprietary (Restricted) |\n + #| Only for use by authorized individuals or any above-designated team(s) |\n + #| within the AT&T companies and not for general distribution |\n + #|_______________________________________________________________________________________________________________________________________|\n" diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/NoSqlDbTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/NoSqlDbTest.java new file mode 100644 index 0000000000..e53c482b86 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/NoSqlDbTest.java @@ -0,0 +1,48 @@ +package org.openecomp.core.nosqldb; + +import org.openecomp.core.nosqldb.api.NoSqlDb; + +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.List; + +public class NoSqlDbTest { + + private static NoSqlDb noSqlDb; + + +// @Test + public void testNoSqlDbFactoryFactoryInit(){ + this.noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + Assert.assertNotNull(this.noSqlDb); + Assert.assertEquals(this.noSqlDb.getClass().getName(),"org.openecomp.core.nosqldb.impl.cassandra.CassandraNoSqlDbImpl"); + } + +// @Test(dependsOnMethods = {"testNoSqlDbFactoryFactoryInit"}) + public void testCreateTable(){ + this.noSqlDb.execute("test.drop",null); + this.noSqlDb.execute("test.create",null); + } + +// @Test(dependsOnMethods = {"testCreateTable"}) + public void testInsertTable(){ + this.noSqlDb.insert("test",new String[]{"name","value"},new String[]{"TestName","testValue"}); + this.noSqlDb.execute("test.insert",new String[]{"TestName2","testValue2"}); + } + +// @Test(dependsOnMethod`s = {"testInsertTable"}) + public void gettestSelectTable(){ + ResultSet result = this.noSqlDb.execute("test.select.all",null); + List rows = result.all(); + Assert.assertEquals(rows.size(),2); + for (Row row:rows){ + System.out.format("%s %s\n", row.getString("name"), row.getString("value")); + } + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/utilities/Yaml/YamlUtilTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/utilities/Yaml/YamlUtilTest.java new file mode 100644 index 0000000000..baf9bfb350 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/utilities/Yaml/YamlUtilTest.java @@ -0,0 +1,47 @@ +package org.openecomp.core.utilities.Yaml; + +import org.openecomp.core.utilities.yaml.YamlUtil; +import org.junit.Before; +import org.junit.Test; +import testobjects.yaml.YamlFile; + + +public class YamlUtilTest { + + String yamlContent; + + @Before + public void setup() { + initYamlFileContent(); + } + + void initYamlFileContent() { + yamlContent = "heat_template_version: ss\n" + + "description: ab\n" + + "parameters:\n" + + " jsa_net_name: \n" + + " description: network name of jsa log network\n" + + " hidden: true\n" + + " inner:\n" + + " inner1:\n" + + " name: shiri\n" + + " inner2:\n" + + " name: avi"; + } + + @Test + public void shouldConvertSimpleYamlToObject() { + new YamlUtil().yamlToObject(yamlContent, YamlFile.class); + } + + + /*public void loadCassandraParameters(){ + YamlUtil yamlutil = new YamlUtil(); + String cassandraKey = "cassandraConfig"; + String configurationFile = "/configuration.yaml"; + InputStream yamlAsIS = yamlutil.loadYamlFileIs(configurationFile); + Map> configurationMap = yamlutil.yamlToMap(yamlAsIS); + LinkedHashMap cassandraConfiguration = configurationMap.get(cassandraKey); + System.out.println(cassandraConfiguration.entrySet()); + }*/ +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/utilities/json/JsonUtilTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/utilities/json/JsonUtilTest.java new file mode 100644 index 0000000000..5cf8988c06 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/utilities/json/JsonUtilTest.java @@ -0,0 +1,13 @@ +package org.openecomp.core.utilities.json; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class JsonUtilTest { + @Test + public void abc() { + System.out.println("as"); + } + +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/testobjects/yaml/InnerP.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/testobjects/yaml/InnerP.java new file mode 100644 index 0000000000..eda4143e3e --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/testobjects/yaml/InnerP.java @@ -0,0 +1,25 @@ +package testobjects.yaml; + +public class InnerP { + String name; + String label; + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/testobjects/yaml/Parameter.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/testobjects/yaml/Parameter.java new file mode 100644 index 0000000000..febcef9c40 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/testobjects/yaml/Parameter.java @@ -0,0 +1,68 @@ +package testobjects.yaml; + +import java.util.Map; + +public class Parameter { + String name; + String label; + String description; + String paramDefault; + boolean hidden; + Map inner; + + public Map getInner() { + return inner; + } + + public void setInner(Map inner) { + this.inner = inner; + } + + public String getParamDefault() { + return paramDefault; + } + + public void setParamDefault(String paramDefault) { + this.paramDefault = paramDefault; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDefault() { + return paramDefault; + } + + public void setDefault(String paramDefault) { + this.paramDefault = paramDefault; + } + + public boolean isHidden() { + return hidden; + } + + public void setHidden(boolean hidden) { + this.hidden = hidden; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/testobjects/yaml/YamlFile.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/testobjects/yaml/YamlFile.java new file mode 100644 index 0000000000..1c4989da37 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/testobjects/yaml/YamlFile.java @@ -0,0 +1,37 @@ +package testobjects.yaml; + +import java.util.Map; + +public class YamlFile { + String heat_template_version; + String description; + Map parameters; + + + public YamlFile() { + } + + public String getHeat_template_version() { + return heat_template_version; + } + + public void setHeat_template_version(String heat_template_version) { + this.heat_template_version = heat_template_version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Map getParameters() { + return parameters; + } + + public void setParameters(Map parameters) { + this.parameters = parameters; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/pom.xml new file mode 100644 index 0000000000..cb1d810547 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + + + openecomp-sdc-lib + org.openecomp.sdc + 1.0.0-SNAPSHOT + ../.. + + + openecomp-nosqldb-lib + org.openecomp.core + openecomp-nosqldb-lib + pom + + + openecomp-nosqldb-api + openecomp-nosqldb-core + + + + + org.openecomp.core + openecomp-nosqldb-api + ${project.version} + compile + + + org.openecomp.core + openecomp-nosqldb-core + ${project.version} + runtime + + + \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/pom.xml new file mode 100644 index 0000000000..a7a53a32f0 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/pom.xml @@ -0,0 +1,82 @@ + + 4.0.0 + + + openecomp-core-lib + org.openecomp.core + 1.0.0-SNAPSHOT + + + openecomp-utilities-lib + openecomp-utilities-lib + + + + + org.yaml + snakeyaml + 1.14 + + + org.apache.commons + commons-lang3 + 3.4 + + + org.apache.commons + commons-collections4 + 4.1 + + + com.google.code.gson + gson + 2.3.1 + + + org.slf4j + slf4j-api + 1.7.10 + + + + + commons-codec + commons-codec + ${commons.codec.version} + + + junit + junit + test + RELEASE + + + org.codehaus.jackson + jackson-mapper-asl + ${org.codehaus.jackson.version} + + + org.everit.json + org.everit.json.schema + ${org.everit.json.schema.version} + + + org.testng + testng + test + 6.8.5 + + + snakeyaml + org.yaml + + + + + + \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java new file mode 100644 index 0000000000..343636bd15 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java @@ -0,0 +1,555 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities; + +import org.apache.commons.codec.binary.Base64; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.PrintWriter; +import java.io.Serializable; +import java.io.StringWriter; +import java.lang.reflect.Array; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +/** + * This class provides auxiliary static methods. + */ +public class CommonMethods { + //private static final Logger logger = LoggerFactory.getLogger(CommonMethods.class); + + private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); + + private static final char[] CHARS = new char[]{ + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + }; + + /** + * Private default constructor to prevent instantiation of the class objects. + */ + private CommonMethods() { + } + + /** + * Serializes an object instance into byte array. + * + * @param object An instance to be serialized. + * @return Java array of bytes. + * @see #deserializeObject(byte[]) #deserializeObject(byte[]) + */ + public static byte[] serializeObject(Serializable object) { + ByteArrayOutputStream byteArray = new ByteArrayOutputStream(2048); + try { + ObjectOutputStream ds = new ObjectOutputStream(byteArray); + ds.writeObject(object); + ds.close(); + } catch (IOException e0) { + throw new RuntimeException(e0); + } + + return byteArray.toByteArray(); + } // serializeObject + + /** + * Deserializes an object instance. + * + * @param bytes Java array of bytes. + * @return Deserialized instance of an object. + * @see #serializeObject(Serializable) #serializeObject(Serializable) + */ + public static Serializable deserializeObject(byte[] bytes) { + Serializable obj = null; + try { + ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(bytes)); + obj = (Serializable) stream.readObject(); + stream.close(); + } catch (IOException | ClassNotFoundException e0) { + throw new RuntimeException(e0); + } + + return obj; + } // deserializeObject + + /** + * Encodes binary byte stream to ASCII format. + * + * @param binary An Java array of bytes in binary format. + * @return An Java array of bytes encoded in ASCII format. + * @see #decode(byte[]) #decode(byte[]) + */ + public static byte[] encode(byte[] binary) { + return Base64.encodeBase64(binary); + } + + /** + * Decodes ASCII byte stream into binary format. + * + * @param ascii An Java array of bytes in ASCII format. + * @return An Java array of bytes encoded in binary format. + * @see #encode(byte[]) #encode(byte[]) + */ + public static byte[] decode(byte[] ascii) { + return Base64.decodeBase64(ascii); + } + + /** + * Checks whether the given Object is empty. + * + * @param obj Object to be checked. + * @return true - if the Object is null, false otherwise. + */ + public static boolean isEmpty(Object obj) { + return obj == null; + } + + /** + * Checks whether the given Object is empty. + * + * @param byteArray Object to be checked. + * @return true - if the Object is null, false otherwise. + */ + public static boolean isEmpty(byte[] byteArray) { + return (byteArray == null || byteArray.length == 0); + } + + /** + * Checks whether the given String is empty. + * + * @param str String object to be checked. + * @return true - if the String is null or empty, false - otherwise. + */ + public static boolean isEmpty(String str) { + return str == null || str.length() == 0; + } + + /** + * Checks whether the given Java array is empty. + * + * @param array Java array to be checked. + * @return true - if the array is null or empty, false - otherwise. + */ + public static boolean isEmpty(Object[] array) { + return array == null || array.length == 0; + } + + /** + * Checks whether the given collection is empty. + * + * @param collection A collection to be checked. + * @return true - if the collection is null or empty, false - otherwise. + */ + public static boolean isEmpty(Collection collection) { + return collection == null || collection.isEmpty(); + } + + /** + * Checks whether the given map is empty. + * + * @param map A map to be checked. + * @return true - if the map is null or empty, false - otherwise. + */ + public static boolean isEmpty(Map map) { + return map == null || map.isEmpty(); + } + + /** + * Converts the array with Long elements to the array with long (primitive type). + * + * @param array input array with Long elements. + * @return array with the same elements converted to the long type (primitive). + */ + public static long[] toPrimitive(Long[] array) { + if (array == null) { + return null; + } + + long[] result = new long[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = array[i] != null ? array[i] : 0L; + } + return result; + } + + /** + * Converts a collection to Java array. + * + * @param Java type of the collection element. + * @param col Collection to be converted to array + * @param type Java type of collection/array element + * @return An Java array of collection elements, or empty array if collection is null or empty. + */ + @SuppressWarnings("unchecked") + public static T[] toArray(Collection col, Class type) { + int length = isEmpty(col) ? 0 : col.size(); + T[] array = (T[]) Array.newInstance(type, length); + return col != null ? col.toArray(array) : array; + } + + /** + * Gets an universally unique identifier (UUID). + * + * @return String representation of generated UUID. + */ + public static String nextUuId() { + UUID uuid = UUID.randomUUID(); + + StringBuilder buff = new StringBuilder(32); + long2string(uuid.getMostSignificantBits(), buff); + long2string(uuid.getLeastSignificantBits(), buff); + + return buff.toString(); + } + + private static void long2string(long lng, StringBuilder buff) { + for (int i = 0; i < 16; i++) { + long nextByte = lng & 0xF000000000000000L; + lng <<= 4; + boolean isNegative = nextByte < 0; + nextByte = rightShift(nextByte, 60); + + if (isNegative) { + nextByte |= 0x08; + } + + buff.append(CHARS[(int) nextByte]); + } + } + + private static long rightShift(long lng, int num) { + return lng >>> num; + } + + /** + * Concatenates two Java arrays. The method allocates a new array and copies + * all elements to it or returns one of input arrays if another one is + * empty. + * + * @param the type parameter + * @param left Elements of this array will be copied to positions from 0 to + * left.length - 1 in the target array. + * @param right Elements of this array will be copied to positions from + * left.length to left.length + right.length + * @return A newly allocate Java array that accommodates elements of source (left/right) + arraysor one of source arrays if another is empty, null - otherwise. + */ + @SuppressWarnings("unchecked") + public static T[] concat(T[] left, T[] right) { + T[] res = null; + + if (isEmpty(left)) { + res = right; + } else if (isEmpty(right)) { + res = left; + } else { + res = (T[]) Array.newInstance(left[0].getClass(), left.length + right.length); + System.arraycopy(left, 0, res, 0, left.length); + System.arraycopy(right, 0, res, left.length, right.length); + } + + return res; + } // concat + + /** + * Casts an object to the class or interface represented by the specified + * Class object. The method logic is similar to Java method + * Class.cast(Object) with the only difference that unlike Java's + * version the type name of the current object instance is specified in the + * error message if casting fails to simplify error tracking. + * + * @param the type parameter + * @param the type parameter + * @param b0 An object instance to be casted to the specified Java type. + * @param cls Target Java type. + * @return Object instance safely casted to the requested Java type. + * @throws ClassCastException In case which is the given object is not instance of the + * specified Java type. + */ + @SuppressWarnings("unchecked") + public static D cast(B b0, Class cls) { + D d0 = null; + if (b0 != null) { + if (!cls.isInstance(b0)) { + throw new ClassCastException(String + .format("Failed to cast from '%s' to '%s'", b0.getClass().getName(), cls.getName())); + } else { + d0 = (D) b0; + } + } + + return d0; + } // cast + + /** + * New instance object. + * + * @param classname the classname + * @return the object + */ + public static Object newInstance(String classname) { + return newInstance(classname, Object.class); + } + + /** + * New instance t. + * + * @param the type parameter + * @param classname the classname + * @param cls the cls + * @return the t + */ + @SuppressWarnings("unchecked") + public static T newInstance(String classname, Class cls) { + + if (isEmpty(classname)) { + throw new IllegalArgumentException(); + } + + if (cls == null) { + throw new IllegalArgumentException(); + } + + try { + Class temp = Class.forName(classname); + + if (!cls.isAssignableFrom(temp)) { + throw new ClassCastException( + String.format("Failed to cast from '%s' to '%s'", classname, cls.getName())); + } + + Class impl = (Class) temp; + + return newInstance(impl); + } catch (ClassNotFoundException e0) { + throw new IllegalArgumentException(e0); + } + } + + /** + * New instance t. + * + * @param the type parameter + * @param cls the cls + * @return the t + */ + public static T newInstance(Class cls) { + try { + return cls.newInstance(); + } catch (InstantiationException e0) { + throw new RuntimeException(e0); + } catch (IllegalAccessException e0) { + throw new RuntimeException(e0); + } + } + + /** + * Gets resources path. + * + * @param resourceName the resource name + * @return the resources path + */ + public static String getResourcesPath(String resourceName) { + URL resourceUrl = CommonMethods.class.getClassLoader().getResource(resourceName); + String resourcePath = resourceUrl.getPath(); + String dirPath = resourcePath.substring(0, resourcePath.lastIndexOf("/") + 1); + + return dirPath; + } + + /** + * Gets stack trace. + * + * @param t0 the t 0 + * @return the stack trace + */ + public static String getStackTrace(Throwable t0) { + if (null == t0) { + return ""; + } + StringWriter sw = new StringWriter(); + t0.printStackTrace(new PrintWriter(sw)); + return sw.toString(); + } + + /** + * Print stack trace string. + * + * @return the string + */ + public static String printStackTrace() { + + StringWriter sw = new StringWriter(); + StackTraceElement[] trace = Thread.currentThread().getStackTrace(); + for (StackTraceElement traceElement : trace) { + sw.write("\t " + traceElement); + sw.write(System.lineSeparator()); + } + String str = sw.toString(); + try { + sw.close(); + } catch (IOException e0) { + System.err.println(e0); + } + return str; + + } + + /** + * Is equal object boolean. + * + * @param obj1 the obj 1 + * @param obj2 the obj 2 + * @return the boolean + */ + public static boolean isEqualObject(Object obj1, Object obj2) { + boolean isEqualValue = false; + if (obj1 == null && obj2 == null) { + isEqualValue = true; + } + + if (!isEqualValue && obj1 != null && obj2 != null && obj1.equals(obj2)) { + isEqualValue = true; + } + return isEqualValue; + } + + /** + * Converts array of strings to comma-separated string. + * + * @param arr array of strings + * @return the string + */ + public static String arrayToCommaSeparatedString(String[] arr) { + return arrayToSeparatedString(arr, ','); + } + + /** + * Collection to comma separated string string. + * + * @param elementCollection the element collection + * @return the string + */ + public static String collectionToCommaSeparatedString(Collection elementCollection) { + List list = new ArrayList<>(); + elementCollection.stream().forEach(element -> list.add(element)); + return listToSeparatedString(list, ','); + } + + /** + * Converts array of strings to string separated with specified character. + * + * @param arr array of strings + * @param separator the separator + * @return the string + */ + public static String arrayToSeparatedString(String[] arr, char separator) { + return listToSeparatedString(Arrays.asList(arr), separator); + } + + /** + * Converts array of strings to string separated with specified character. + * + * @param list array of strings + * @param separator the separator + * @return the string + */ + public static String listToSeparatedString(List list, char separator) { + String res = null; + if (null != list) { + StringBuilder sb = new StringBuilder(); + int sz = list.size(); + for (int i = 0; i < sz; i++) { + if (i > 0) { + sb.append(separator); + } + sb.append(list.get(i)); + } + res = sb.toString(); + } + return res; + } + + /** + * Duplicate string with delimiter string. + * + * @param arg the arg + * @param separator the separator + * @param numberOfDuplications the number of duplications + * @return the string + */ + public static String duplicateStringWithDelimiter(String arg, char separator, + int numberOfDuplications) { + String res = null; + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < numberOfDuplications; i++) { + if (i > 0) { + sb.append(separator); + } + sb.append(arg); + } + res = sb.toString(); + return res; + } + + /** + * Bytes to hex string. + * + * @param bytes the bytes + * @return the string + */ + public static String bytesToHex(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for (int j = 0; j < bytes.length; j++) { + int v0 = bytes[j] & 0xFF; + int x0 = j << 1; + hexChars[x0] = hexArray[v0 >>> 4]; + hexChars[x0 + 1] = hexArray[v0 & 0x0F]; + } + return new String(hexChars); + } + + /** + * To single element set set. + * + * @param the class of the objects in the set + * @param element the single element to be contained in the returned Set + * @return an immutable set containing only the specified object.The returned set is serializable. + */ + public static Set toSingleElementSet(T element) { + return Collections.singleton(element); + + } + + +} + diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java new file mode 100644 index 0000000000..67a79875d4 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.file; + +import org.apache.commons.collections4.MapUtils; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class FileContentHandler { + private Map files = new HashMap<>(); + + /** + * Gets file content. + * + * @param fileName the file name + * @return the file content + */ + public InputStream getFileContent(String fileName) { + + byte[] content = files.get(fileName); + if (content == null || content.length == 0) { + return null; + } + + ByteArrayInputStream is = new ByteArrayInputStream(content); + return is; + } + + public void addFile(String fileName, byte[] contect) { + files.put(fileName, contect); + } + + public void addFile(String fileName, InputStream is) { + + files.put(fileName, FileUtils.toByteArray(is)); + } + + public void setFiles(FileContentHandler extFiles) { + extFiles.getFileList().stream() + .forEach(fileName -> this.addFile(fileName, extFiles.getFileContent(fileName))); + } + + public Set getFileList() { + return files.keySet(); + } + + public void putAll(Map files) { + this.files = files; + } + + public void addAll(FileContentHandler other) { + this.files.putAll(other.files); + } + + public boolean isEmpty() { + return MapUtils.isEmpty(this.files); + } + + public void remove(String fileName) { + files.remove(fileName); + } + + public boolean containsFile(String fileName) { + return files.containsKey(fileName); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java new file mode 100644 index 0000000000..72fa9ac7b8 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java @@ -0,0 +1,286 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.file; + +import org.openecomp.core.utilities.json.JsonUtil; +import org.openecomp.core.utilities.yaml.YamlUtil; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +/** + * The type File utils. + */ +public class FileUtils { + + /** + * Gets file input stream. + * + * @param fileName the file name + * @return the file input stream + */ + public static InputStream getFileInputStream(String fileName) { + URL urlFile = FileUtils.class.getClassLoader().getResource(fileName); + InputStream is; + try { + assert urlFile != null; + is = urlFile.openStream(); + } catch (IOException exception) { + throw new RuntimeException(exception); + } + return is; + } + + /** + * Gets file input streams. + * + * @param fileName the file name + * @return the file input streams + */ + public static List getFileInputStreams(String fileName) { + Enumeration urlFiles; + List streams = new ArrayList<>(); + InputStream is; + URL url; + try { + urlFiles = FileUtils.class.getClassLoader().getResources(fileName); + while (urlFiles.hasMoreElements()) { + url = urlFiles.nextElement(); + is = url.openStream(); + streams.add(is); + } + + + } catch (IOException exception) { + throw new RuntimeException(exception); + } + return streams; + } + + /** + * Convert to bytes byte [ ]. + * + * @param object the object + * @param extension the extension + * @return the byte [ ] + */ + public static byte[] convertToBytes(Object object, FileExtension extension) { + if (object != null) { + if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) { + return new YamlUtil().objectToYaml(object).getBytes(); + } else { + return JsonUtil.object2Json(object).getBytes(); + } + } else { + return new byte[]{}; + } + } + + /** + * Convert to input stream input stream. + * + * @param object the object + * @param extension the extension + * @return the input stream + */ + public static InputStream convertToInputStream(Object object, FileExtension extension) { + if (object != null) { + + byte[] content; + + if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) { + content = new YamlUtil().objectToYaml(object).getBytes(); + } else { + content = JsonUtil.object2Json(object).getBytes(); + + } + return new ByteArrayInputStream(content); + } else { + return null; + } + } + + /** + * Load file to input stream input stream. + * + * @param fileName the file name + * @return the input stream + */ + public static InputStream loadFileToInputStream(String fileName) { + URL urlFile = FileUtils.class.getClassLoader().getResource(fileName); + try { + Enumeration en = FileUtils.class.getClassLoader().getResources(fileName); + while (en.hasMoreElements()) { + urlFile = en.nextElement(); + } + } catch (IOException | NullPointerException exception) { + throw new RuntimeException(exception); + } + try { + if (urlFile != null) { + return urlFile.openStream(); + } else { + throw new RuntimeException(); + } + } catch (IOException | NullPointerException exception) { + throw new RuntimeException(exception); + } + + } + + /** + * To byte array byte [ ]. + * + * @param input the input + * @return the byte [ ] + */ + public static byte[] toByteArray(InputStream input) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try { + copy(input, output); + } catch (IOException exception) { + throw new RuntimeException( + "error will convertion input stream to byte array:" + exception.getMessage()); + } + return output.toByteArray(); + } + + /** + * Copy int. + * + * @param input the input + * @param output the output + * @return the int + * @throws IOException the io exception + */ + public static int copy(InputStream input, OutputStream output) throws IOException { + long count = copyLarge(input, output); + return count > 2147483647L ? -1 : (int) count; + } + + private static long copyLarge(InputStream input, OutputStream output) throws IOException { + return copyLarge(input, output, new byte[4096]); + } + + private static long copyLarge(InputStream input, OutputStream output, byte[] buffer) + throws IOException { + long count = 0L; + + int n1; + if (input == null) { + return count; + } + for (; -1 != (n1 = input.read(buffer)); count += (long) n1) { + output.write(buffer, 0, n1); + } + + return count; + + + } + + /** + * Gets file without extention. + * + * @param fileName the file name + * @return the file without extention + */ + public static String getFileWithoutExtention(String fileName) { + if (!fileName.contains(".")) { + return fileName; + } + return fileName.substring(0, fileName.lastIndexOf(".")); + } + + /** + * Gets file content map from zip. + * + * @param zipData the zip data + * @return the file content map from zip + * @throws IOException the io exception + */ + public static FileContentHandler getFileContentMapFromZip(byte[] zipData) throws IOException { + ZipEntry zipEntry; + FileContentHandler mapFileContent = new FileContentHandler(); + try { + ZipInputStream inputZipStream; + + byte[] fileByteContent; + String currentEntryName; + inputZipStream = new ZipInputStream(new ByteArrayInputStream(zipData)); + + while ((zipEntry = inputZipStream.getNextEntry()) != null) { + currentEntryName = zipEntry.getName(); + fileByteContent = FileUtils.toByteArray(inputZipStream); + mapFileContent.addFile(currentEntryName, fileByteContent); + } + + } catch (RuntimeException exception) { + throw new IOException(exception); + } + return mapFileContent; + } + + /** + * The enum File extension. + */ + public enum FileExtension { + + /** + * Json file extension. + */ + JSON("json"), + /** + * Yaml file extension. + */ + YAML("yaml"), + /** + * Yml file extension. + */ + YML("yml"); + + private String displayName; + + FileExtension(String displayName) { + this.displayName = displayName; + } + + /** + * Gets display name. + * + * @return the display name + */ + public String getDisplayName() { + return displayName; + } + } + + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java new file mode 100644 index 0000000000..8968eeb323 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java @@ -0,0 +1,185 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.json; + +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; + +/** + * The type Json schema data generator. + */ +public class JsonSchemaDataGenerator { + + private static final String ROOT = "root"; + private static final Logger logger = LoggerFactory.getLogger(JsonSchemaDataGenerator.class); + /** + * The Include defaults. + */ + boolean includeDefaults = true; + private JSONObject root; + private Map referencesData; + + /** + * Instantiates a new Json schema data generator. + * + * @param jsonSchema the json schema + */ + public JsonSchemaDataGenerator(String jsonSchema) { + if (jsonSchema == null) { + throw new IllegalArgumentException("Input string jsonSchema can not be null"); + } + root = new JSONObject(jsonSchema); + } + + /** + * Sets include defaults. + * + * @param includeDefaults the include defaults + */ + public void setIncludeDefaults(boolean includeDefaults) { + this.includeDefaults = includeDefaults; + } + + /** + * Generates json data that conform to the schema according to turned on flags. + * + * @return json that conform to the schema. + */ + public String generateData() { + referencesData = new HashMap<>(); + JSONObject data = new JSONObject(); + + generateData(ROOT, root, + data); // "root" is dummy name to represent the top level object (which, as apposed to + // inner objects, doesn't have a name in the schema) + return data.has(ROOT) ? data.get(ROOT).toString() : data.toString(); + } + + private void generateData(String propertyName, JSONObject property, JSONObject propertyData) { + if (property.has(JsonSchemaKeyword.TYPE)) { + String propertyType = property.getString(JsonSchemaKeyword.TYPE); + if (JsonSchemaKeyword.OBJECT.equals(propertyType)) { + generateObjectData(propertyName, property, propertyData); + } else { + generatePrimitiveData(propertyType, propertyName, property, propertyData); + } + } else if (property.has(JsonSchemaKeyword.REF)) { + generateReferenceData(propertyName, property.getString(JsonSchemaKeyword.REF), propertyData); + } + } + + private void generateObjectData(String propertyName, JSONObject property, + JSONObject propertyData) { + JSONObject subProperties = property.getJSONObject(JsonSchemaKeyword.PROPERTIES); + + JSONObject subPropertiesData = new JSONObject(); + for (String subPropertyName : subProperties.keySet()) { + generateData(subPropertyName, subProperties.getJSONObject(subPropertyName), + subPropertiesData); + } + + if (subPropertiesData.length() > 0) { + propertyData.put(propertyName, subPropertiesData); + } + } + + private void generateReferenceData(String propertyName, String referencePath, + JSONObject propertyData) { + if (referencesData.containsKey(referencePath)) { + Object referenceData = referencesData.get(referencePath); + if (referenceData != null) { + propertyData.put(propertyName, referenceData); + } + } else { + generateData(propertyName, resolveReference(referencePath), propertyData); + referencesData.put(referencePath, propertyData.opt(propertyName)); + } + } + + private JSONObject resolveReference(String referencePath) { + String[] keys = referencePath.replaceFirst("#/", "").split("/"); + + JSONObject reference = root; + for (String key : keys) { + reference = reference.getJSONObject(key); + } + return reference; + } + + private void generatePrimitiveData(String propertyType, String propertyName, JSONObject property, + JSONObject propertyData) { + if (includeDefaults) { + populateWithDefaultValue(propertyType, propertyName, property, propertyData); + } + } + + private void populateWithDefaultValue(String propertyType, String propertyName, + JSONObject property, JSONObject propertyData) { + if (!property.has(JsonSchemaKeyword.DEFAULT)) { + return; + } + try { + switch (propertyType) { + case JsonSchemaKeyword.ARRAY: + propertyData.put(propertyName, property.getJSONArray(JsonSchemaKeyword.DEFAULT)); + break; + case JsonSchemaKeyword.BOOLEAN: + propertyData.put(propertyName, property.getBoolean(JsonSchemaKeyword.DEFAULT)); + break; + case JsonSchemaKeyword.INTEGER: + propertyData.put(propertyName, property.getInt(JsonSchemaKeyword.DEFAULT)); + break; + case JsonSchemaKeyword.NUMBER: + propertyData.put(propertyName, property.getDouble(JsonSchemaKeyword.DEFAULT)); + break; + case JsonSchemaKeyword.STRING: + propertyData.put(propertyName, property.getString(JsonSchemaKeyword.DEFAULT)); + break; + default: + break; + } + } catch (JSONException e0) { + Object defaultValue = property.get(JsonSchemaKeyword.DEFAULT); + logger.error(String.format( + "Invalid schema: '%s' property type is '%s' but it has a default value which is not: %s.", + propertyName, propertyType, defaultValue), e0); + throw e0; + } + } + + private static class JsonSchemaKeyword { + private static final String DEFAULT = "default"; + private static final String TYPE = "type"; + private static final String PROPERTIES = "properties"; + private static final String ARRAY = "array"; + private static final String BOOLEAN = "boolean"; + private static final String INTEGER = "integer"; + private static final String NUMBER = "number"; + private static final String STRING = "string"; + private static final String OBJECT = "object"; + private static final String REF = "$ref"; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java new file mode 100644 index 0000000000..6ae3677a8d --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java @@ -0,0 +1,187 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.json; + + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonIOException; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; + +import org.apache.commons.collections.CollectionUtils; +import org.everit.json.schema.EnumSchema; +import org.everit.json.schema.Schema; +import org.everit.json.schema.ValidationException; +import org.everit.json.schema.loader.SchemaLoader; +import org.json.JSONObject; +import org.openecomp.core.utilities.CommonMethods; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * The type Json util. + */ +public class JsonUtil { + + /** + * Object 2 json string. + * + * @param obj the obj + * @return the string + */ + //TODO: refactor all other ugly code to use this + public static String object2Json(Object obj) { + return sbObject2Json(obj).toString(); + + } + + /** + * Sb object 2 json string buffer. + * + * @param obj the obj + * @return the string buffer + */ + public static StringBuffer sbObject2Json(Object obj) { + return new StringBuffer((new GsonBuilder()).setPrettyPrinting().create().toJson(obj)); + } + + /** + * Json 2 object t. + * + * @param the type parameter + * @param json the json + * @param classOfT the class of t + * @return the t + */ + public static T json2Object(String json, Class classOfT) { + T type; + try { + try (Reader br = new StringReader(json)) { + type = new Gson().fromJson(br, classOfT); + } catch (IOException e0) { + throw e0; + } + } catch (JsonIOException | JsonSyntaxException | IOException e0) { + throw new RuntimeException(e0); + } + return type; + } + + /** + * Json 2 object t. + * + * @param the type parameter + * @param is the is + * @param classOfT the class of t + * @return the t + */ + public static T json2Object(InputStream is, Class classOfT) { + T type; + try { + try (Reader br = new BufferedReader(new InputStreamReader(is))) { + type = new Gson().fromJson(br, classOfT); + } + } catch (JsonIOException | JsonSyntaxException | IOException e0) { + throw new RuntimeException(e0); + } finally { + if (is != null) { + try { + is.close(); + } catch (IOException ignore) { + //do nothing + } + } + } + return type; + } + + + /** + * Is valid json boolean. + * + * @param json the json + * @return the boolean + */ + //todo check https://github.com/stleary/JSON-java as replacement for this code + public static boolean isValidJson(String json) { + try { + return new JsonParser().parse(json).isJsonObject(); + } catch (JsonSyntaxException jse) { + return false; + } + } + + /** + * Validate list. + * + * @param json the json + * @param jsonSchema the json schema + * @return the list + */ + public static List validate(String json, String jsonSchema) { + List validationErrors = validateUsingEverit(json, jsonSchema); + return validationErrors == null ? null + : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage) + .collect(Collectors.toList()); + } + + private static String mapValidationExceptionToMessage(ValidationException e0) { + if (e0.getViolatedSchema() instanceof EnumSchema) { + return mapEnumViolationToMessage(e0); + } + return e0.getMessage(); + } + + private static String mapEnumViolationToMessage(ValidationException e1) { + Set possibleValues = ((EnumSchema) e1.getViolatedSchema()).getPossibleValues(); + return e1.getMessage().replaceFirst("enum value", possibleValues.size() == 1 + ? String.format("value. %s is the only possible value for this field", + possibleValues.iterator().next()) + : String.format("value. Possible values: %s", CommonMethods + .collectionToCommaSeparatedString( + possibleValues.stream().map(Object::toString).collect(Collectors.toList())))); + } + + private static List validateUsingEverit(String json, String jsonSchema) { + if (json == null || jsonSchema == null) { + throw new IllegalArgumentException("Input strings json and jsonSchema can not be null"); + } + + Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema)); + try { + schemaObj.validate(new JSONObject(json)); + } catch (ValidationException ve) { + return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve) + : ve.getCausingExceptions(); + } + return null; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/yaml/YamlUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/yaml/YamlUtil.java new file mode 100644 index 0000000000..56261f08de --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/yaml/YamlUtil.java @@ -0,0 +1,289 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.yaml; + +import org.openecomp.core.utilities.CommonMethods; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.introspector.BeanAccess; +import org.yaml.snakeyaml.introspector.Property; +import org.yaml.snakeyaml.introspector.PropertyUtils; +import org.yaml.snakeyaml.nodes.MappingNode; +import org.yaml.snakeyaml.nodes.NodeTuple; +import org.yaml.snakeyaml.nodes.Tag; +import org.yaml.snakeyaml.parser.ParserException; +import org.yaml.snakeyaml.representer.Representer; + +import java.beans.IntrospectionException; +import java.io.IOException; +import java.io.InputStream; +import java.util.AbstractMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +/** + * The type Yaml util. + */ +public class YamlUtil { + + private static Logger logger = LoggerFactory.getLogger(YamlUtil.class); + + /** + * Yaml to object t. + * + * @param the type parameter + * @param yamlContent the yaml content + * @param typClass the typ class + * @return the t + */ + public T yamlToObject(String yamlContent, Class typClass) { + Constructor constructor = getConstructor(typClass); + constructor.setPropertyUtils(getPropertyUtils()); + TypeDescription yamlFileDescription = new TypeDescription(typClass); + constructor.addTypeDescription(yamlFileDescription); + Yaml yaml = new Yaml(constructor); + T yamlObj = (T) yaml.load(yamlContent); + yamlObj.toString(); + return yamlObj; + } + + /** + * Yaml to object t. + * + * @param the type parameter + * @param yamlContent the yaml content + * @param typClass the typ class + * @return the t + */ + public T yamlToObject(InputStream yamlContent, Class typClass) { + try { + Constructor constructor = getConstructor(typClass); + constructor.setPropertyUtils(getPropertyUtils()); + TypeDescription yamlFileDescription = new TypeDescription(typClass); + constructor.addTypeDescription(yamlFileDescription); + Yaml yaml = new Yaml(constructor); + T yamlObj = (T) yaml.load(yamlContent); + if (yamlObj != null) { + yamlObj.toString(); + return yamlObj; + } else { + throw new RuntimeException(); + } + } catch (Exception exception) { + logger.error("Error will trying to convert yaml to object:" + exception.getMessage()); + throw new RuntimeException(exception); + } finally { + try { + if (yamlContent != null) { + yamlContent.close(); + } + } catch (IOException ignore) { + //nothing to dd + } + } + } + + + /** + * Gets constructor. + * + * @param the type parameter + * @param typClass the typ class + * @return the constructor + */ + public Constructor getConstructor(Class typClass) { + return new StrictMapAppenderConstructor(typClass); + } + + /** + * Gets property utils. + * + * @return the property utils + */ + protected PropertyUtils getPropertyUtils() { + return new MyPropertyUtils(); + } + + /** + * Yaml to map map. + * + * @param yamlContent the yaml content + * @return the map + */ + public Map> yamlToMap(InputStream yamlContent) { + Yaml yaml = new Yaml(); + Map> yamlData = + (Map>) yaml.load(yamlContent); + return yamlData; + } + + /** + * Object to yaml string. + * + * @param the type parameter + * @param obj the obj + * @return the string + */ + public String objectToYaml(Object obj) { + DumperOptions options = new DumperOptions(); + options.setPrettyFlow(true); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Representer representer = new CustomRepresenter(); + representer.addClassTag(obj.getClass(), Tag.MAP); + representer.setPropertyUtils(new MyPropertyUtils()); + + Yaml yaml = new Yaml(representer, options); + return yaml.dump(obj); + } + + /** + * Load yaml file is input stream. + * + * @param yamlFullFileName the yaml full file name + * @return the input stream + */ + public InputStream loadYamlFileIs(String yamlFullFileName) { + return CommonMethods.class.getResourceAsStream(yamlFullFileName); + } + + /** + * Is yaml file content valid boolean. + * + * @param yamlFullFileName the yaml full file name + * @return the boolean + */ + public boolean isYamlFileContentValid(String yamlFullFileName) { + Yaml yaml = new Yaml(); + try { + Object loadResult = yaml.load(yamlFullFileName); + if (loadResult == null) { + return false; + } + return true; + } catch (Exception exception) { + return false; + } + } + + + private class CustomRepresenter extends Representer { + @Override + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, + Object propertyValue, Tag customTag) { + if (propertyValue == null) { + return null; + } else { + NodeTuple defaultNode = + super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); + + return property.getName().equals("_default") + ? new NodeTuple(representData("default"), defaultNode.getValueNode()) + : defaultNode; + } + } + + @Override + protected MappingNode representJavaBean(Set properties, Object javaBean) { + //remove the bean type from the output yaml (!! ...) + if (!classTags.containsKey(javaBean.getClass())) { + addClassTag(javaBean.getClass(), Tag.MAP); + } + + return super.representJavaBean(properties, javaBean); + } + } + + + /** + * The type My property utils. + */ + public class MyPropertyUtils extends PropertyUtils { + @Override + public Property getProperty(Class type, String name) throws IntrospectionException { + if (name.equals("default")) { + name = "_default"; + } + return super.getProperty(type, name); + } + + //Unsorted properties + @Override + protected Set createPropertySet(Class type, BeanAccess beanAccess) + throws IntrospectionException { + return new LinkedHashSet(getPropertiesMap(type, + BeanAccess.FIELD).values()); + } + + } + + /** + * The type Strict map appender constructor. + */ + protected class StrictMapAppenderConstructor extends Constructor { + + /** + * Instantiates a new Strict map appender constructor. + * + * @param theRoot the the root + */ + public StrictMapAppenderConstructor(Class theRoot) { + super(theRoot); + } + + @Override + protected Map constructMapping(MappingNode node) { + try { + return super.constructMapping(node); + } catch (IllegalStateException exception) { + throw new ParserException("while parsing MappingNode", node.getStartMark(), + exception.getMessage(), node.getEndMark()); + } + } + + @Override + protected Map createDefaultMap() { + final Map delegate = super.createDefaultMap(); + return new AbstractMap() { + @Override + public Object put(Object key, Object value) { + if (delegate.containsKey(key)) { + throw new IllegalStateException("duplicate key: " + key); + } + return delegate.put(key, value); + } + + @Override + public Set> entrySet() { + return delegate.entrySet(); + } + }; + } + } +} + + + diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonSchemaDataGeneratorTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonSchemaDataGeneratorTest.java new file mode 100644 index 0000000000..83c87737d2 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonSchemaDataGeneratorTest.java @@ -0,0 +1,50 @@ +package org.openecomp.core.utilities.json; + +import org.openecomp.core.utilities.file.FileUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class JsonSchemaDataGeneratorTest { + + public static final String SCHEMA_WITHOUT_DEFAULTS = new String( + FileUtils.toByteArray(FileUtils.getFileInputStream("jsonUtil/json_schema/aSchema.json"))); + public static final String SCHEMA_WITH_REFS_AND_DEFAULTS = new String(FileUtils.toByteArray( + FileUtils.getFileInputStream("jsonUtil/json_schema/schemaWithRefsAndDefaults.json"))); + public static final String SCHEMA_WITH_INVALID_DEFAULT = new String(FileUtils.toByteArray( + FileUtils.getFileInputStream("jsonUtil/json_schema/schemaWithInvalidDefault.json"))); + public static final String SCHEMA_NIC = new String( + FileUtils.toByteArray(FileUtils.getFileInputStream("jsonUtil/json_schema/nicSchema.json"))); + + @Test + public void testSchemaWithoutDefaults() { + testGenerate(SCHEMA_WITHOUT_DEFAULTS, new JSONObject()); + } + + @Test + public void testSchemaWithRefsAndDefaults() { + testGenerate(SCHEMA_WITH_REFS_AND_DEFAULTS, + new JSONObject( + "{\"cityOfBirth\":\"Tel Aviv\",\"address\":{\"city\":\"Tel Aviv\"},\"phoneNumber\":[{\"code\":1,\"location\":\"Home\"},{\"code\":2,\"location\":\"Office\"}]}")); + } + + @Test(expectedExceptions = JSONException.class) + public void testSchemaWithInvalidDefault() { + testGenerate(SCHEMA_WITH_INVALID_DEFAULT, null); + } + + @Test + public void testNicQuestionnaireSchema() { + testGenerate(SCHEMA_NIC, + new JSONObject("{\"ipConfiguration\":{\"ipv4Required\":true,\"ipv6Required\":false}}")); + } + + private void testGenerate(String schema, JSONObject expectedData) { + JsonSchemaDataGenerator jsonSchemaDataGenerator = new JsonSchemaDataGenerator(schema); + String data = jsonSchemaDataGenerator.generateData(); + System.out.println(data); + JSONObject dataJson = new JSONObject(data); + Assert.assertTrue(expectedData.similar(dataJson)); + } +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonUtilTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonUtilTest.java new file mode 100644 index 0000000000..e232f72f38 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonUtilTest.java @@ -0,0 +1,40 @@ +package org.openecomp.core.utilities.json; + + +import org.openecomp.core.utilities.file.FileUtils; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.List; + +public class JsonUtilTest { + + @Test + public void testValidJsonValidate() throws Exception { + String json = + new String(FileUtils.toByteArray(FileUtils.getFileInputStream("jsonUtil/json/a.json"))); + String jsonSchema = new String( + FileUtils.toByteArray(FileUtils.getFileInputStream("jsonUtil/json_schema/aSchema.json"))); + + List validationErrors = JsonUtil.validate(json, jsonSchema); + Assert.assertNull(validationErrors); + } + + @Test + public void testInValidJsonValidate() throws Exception { + String json = new String( + FileUtils.toByteArray(FileUtils.getFileInputStream("jsonUtil/json/a_invalid.json"))); + String jsonSchema = new String( + FileUtils.toByteArray(FileUtils.getFileInputStream("jsonUtil/json_schema/aSchema.json"))); + + List validationErrors = JsonUtil.validate(json, jsonSchema); + Assert.assertNotNull(validationErrors); + Assert.assertEquals(validationErrors.size(), 3); + Assert.assertEquals(validationErrors.get(0), + "#/cityOfBirth: Paris is not a valid value. Possible values: New York,Tel Aviv,London"); + Assert.assertEquals(validationErrors.get(1), + "#/address: {\"streetAddress\":\"21 2nd Street\",\"city\":\"Paris\"} is not a valid value. {\"streetAddress\":\"21 2nd Street\",\"city\":\"New York\"} is the only possible value for this field"); + Assert.assertEquals(validationErrors.get(2), + "#/phoneNumber/0/code: expected type: Number, found: String"); + } +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json/a.json b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json/a.json new file mode 100644 index 0000000000..a3320d5fc7 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json/a.json @@ -0,0 +1,12 @@ +{ + "address": { + "streetAddress": "21 2nd Street", + "city": "New York" + }, + "phoneNumber": [ + { + "location": "home", + "code": 44 + } + ] +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json/a_invalid.json b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json/a_invalid.json new file mode 100644 index 0000000000..8a02522ea9 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json/a_invalid.json @@ -0,0 +1,13 @@ +{ + "address": { + "streetAddress": "21 2nd Street", + "city": "Paris" + }, + "phoneNumber": [ + { + "location": "home", + "code": "test" + } + ], + "cityOfBirth": "Paris" +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/aSchema.json b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/aSchema.json new file mode 100644 index 0000000000..a77e38df87 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/aSchema.json @@ -0,0 +1,60 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "definitions": { + "city": { + "type": "string", + "enum": [ + "Tel Aviv", + "New York", + "London" + ] + } + }, + "properties": { + "address": { + "type": "object", + "properties": { + "streetAddress": { + "type": "string" + }, + "city": { + "$ref": "#/definitions/city" + } + }, + "enum": [ + { + "streetAddress": "21 2nd Street", + "city": "New York" + } + ], + "required": [ + "streetAddress", + "city" + ] + }, + "phoneNumber": { + "type": "array", + "items": { + "type": "object", + "properties": { + "location": { + "type": "string" + }, + "code": { + "type": "integer" + } + }, + "required": [ + "location", + "code" + ] + } + }, + "cityOfBirth" : { "$ref" : "#/definitions/city"} + }, + "required": [ + "address", + "phoneNumber" + ] +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/nicSchema.json b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/nicSchema.json new file mode 100644 index 0000000000..d96de6aa31 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/nicSchema.json @@ -0,0 +1,118 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "properties": { + "protocols": { + "type": "object", + "properties": { + "protocols": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "TCP", + "UDP", + "SCTP", + "IPsec" + ] + }, + "minItems": 1 + }, + "protocolWithHighestTrafficProfile": { + "$ref": "#/properties/protocols/properties/protocols/items" + } + }, + "additionalProperties": false + }, + "ipConfiguration": { + "type": "object", + "properties": { + "ipv4Required": { + "type": "boolean", + "default": true + }, + "ipv6Required": { + "type": "boolean", + "default": false + } + }, + "additionalProperties": false + }, + "network": { + "type": "object", + "properties": { + "networkDescription": { + "type": "string", + "pattern": "[A-Za-z]+", + "maxLength": 300 + } + }, + "additionalProperties": false + }, + "sizing": { + "type": "object", + "definitions": { + "peakAndAvg": { + "type": "object", + "properties": { + "peak": { + "type": "number" + }, + "avg": { + "type": "number" + } + }, + "additionalProperties": false + }, + "packetsAndBytes": { + "type": "object", + "properties": { + "packets": { + "$ref": "#/properties/sizing/definitions/peakAndAvg" + }, + "bytes": { + "$ref": "#/properties/sizing/definitions/peakAndAvg" + } + }, + "additionalProperties": false + } + }, + "properties": { + "describeQualityOfService": { + "type": "string" + }, + "inflowTrafficPerSecond": { + "$ref": "#/properties/sizing/definitions/packetsAndBytes" + }, + "outflowTrafficPerSecond": { + "$ref": "#/properties/sizing/definitions/packetsAndBytes" + }, + "flowLength": { + "$ref": "#/properties/sizing/definitions/packetsAndBytes" + }, + "acceptableJitter": { + "type": "object", + "properties": { + "mean": { + "type": "number" + }, + "max": { + "type": "number" + }, + "variable": { + "type": "number" + } + }, + "additionalProperties": false + }, + "acceptablePacketLoss": { + "type": "number", + "minimum": 0, + "maximum": 100 + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/schemaWithInvalidDefault.json b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/schemaWithInvalidDefault.json new file mode 100644 index 0000000000..100d17f48e --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/schemaWithInvalidDefault.json @@ -0,0 +1,67 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "definitions": { + "city": { + "type": "string", + "enum": [ + "Tel Aviv", + "New York", + "London" + ], + "default": "Tel Aviv" + } + }, + "type": "object", + "properties": { + "address": { + "type": "object", + "properties": { + "streetAddress": { + "type": "string", + "default" : 7 + }, + "city": { + "$ref": "#/definitions/city" + } + }, + "required": [ + "streetAddress", + "city" + ] + }, + "phoneNumber": { + "type": "array", + "items": { + "type": "object", + "properties": { + "location": { + "type": "string" + }, + "code": { + "type": "integer", + "default": 777 + } + }, + "required": [ + "location", + "code" + ] + }, + "default": [ + { + "location": "Home", + "code": 1 + }, + { + "location": "Office", + "code": 2 + } + ] + }, + "cityOfBirth" : { "$ref" : "#/definitions/city"} + }, + "required": [ + "address", + "phoneNumber" + ] +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/schemaWithRefsAndDefaults.json b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/schemaWithRefsAndDefaults.json new file mode 100644 index 0000000000..de027b9d56 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/schemaWithRefsAndDefaults.json @@ -0,0 +1,71 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "definitions": { + "city": { + "type": "string", + "enum": [ + "Tel Aviv", + "New York", + "London" + ], + "default": "Tel Aviv" + }, + "zipCode" : { + "type" : "integer" + } + }, + "type": "object", + "properties": { + "address": { + "type": "object", + "properties": { + "streetAddress": { + "type": "string" + }, + "city": { + "$ref": "#/definitions/city" + }, + "cityZipCode" : {"$ref" : "#/definitions/zipCode"} + }, + "required": [ + "streetAddress", + "city" + ] + }, + "phoneNumber": { + "type": "array", + "items": { + "type": "object", + "properties": { + "location": { + "type": "string" + }, + "locationZipCode" : {"$ref" : "#/definitions/zipCode"}, + "code": { + "type": "integer", + "default": 777 + } + }, + "required": [ + "location", + "code" + ] + }, + "default": [ + { + "location": "Home", + "code": 1 + }, + { + "location": "Office", + "code": 2 + } + ] + }, + "cityOfBirth" : { "$ref" : "#/definitions/city"} + }, + "required": [ + "address", + "phoneNumber" + ] +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/pom.xml b/openecomp-be/lib/openecomp-core-lib/pom.xml new file mode 100644 index 0000000000..312b085424 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/pom.xml @@ -0,0 +1,23 @@ + + 4.0.0 + + + openecomp-sdc-lib + org.openecomp.sdc + 1.0.0-SNAPSHOT + + + org.openecomp.core + openecomp-core-lib + openecomp-core-lib + + pom + + + /openecomp-facade-lib + /openecomp-nosqldb-lib + /openecomp-utilities-lib + /openecomp-config-lib + + \ No newline at end of file -- cgit 1.2.3-korg