diff options
Diffstat (limited to 'openecomp-be/lib/openecomp-core-lib')
68 files changed, 5276 insertions, 0 deletions
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 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-core-lib</artifactId> + <version>1.0.0-SNAPSHOT</version> + </parent> + + <artifactId>openecomp-config-lib</artifactId> + + <dependencies> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.3.1</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.yaml</groupId> + <artifactId>snakeyaml</artifactId> + <version>1.14</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-nosqldb-core</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.testng</groupId> + <artifactId>testng</artifactId> + <version>6.9.10</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-vendor-software-product-api</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> + </dependencies> + + +</project>
\ 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<ApplicationConfigEntity> 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<ApplicationConfig> { + + 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<ApplicationConfigEntity> { + + 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<ApplicationConfigDao> { + + 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<ApplicationConfigEntity> + implements ApplicationConfigDao { + + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static final Mapper<ApplicationConfigEntity> mapper = + noSqlDb.getMappingManager().mapper(ApplicationConfigEntity.class); + private static final ApplicationConfigAccessor accessor = + noSqlDb.getMappingManager().createAccessor(ApplicationConfigAccessor.class); + + @Override + protected Mapper<ApplicationConfigEntity> getMapper() { + return mapper; + } + + @Override + protected Object[] getKeys(ApplicationConfigEntity entity) { + return new Object[]{entity.getNamespace(), entity.getKey(), entity.getValue()}; + } + + @Override + public Collection<ApplicationConfigEntity> 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<ApplicationConfigEntity> 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<ApplicationConfigEntity> 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 @@ +<!-- +<?xml version="1.0" encoding="UTF-8"?> +<configuration> + + + <appender name="DEBUG_ROLLING" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>DOX-BE.log + </file> + + <!– No need to deny audit messages - they are INFO only, will be denied + anyway –> + <!– Transaction messages filter - deny Transaction messages, there are + some DEBUG level messages among them –> + + + <!– accept DEBUG and TRACE level –> + + <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> + <fileNamePattern>/DOX-BE.log.%i + </fileNamePattern> + <minIndex>1</minIndex> + <maxIndex>10</maxIndex> + </rollingPolicy> + + <triggeringPolicy + class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>20MB</maxFileSize> + </triggeringPolicy> + <encoder> + <pattern>%level [%d{yyyy-MM-dd'T'HH:mm:ss}] - Method=%M, Desc=<%msg>%n</pattern> + </encoder> + </appender> + + + <root level="info"> + <appender-ref ref="DEBUG_ROLLING" /> + </root> +</configuration>--> +<configuration scan="true" scanPeriod="3 seconds"> + + <property name="logDir" value="logs"/> + <property name="componentName" value="ASDC"/> + <property name="ECOMP-subcomponent-name" value="ASDC-BE"/> + + <property name="defaultPattern" + value="%msg%n"/> + + <!--<property name="MetricsLogPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%X{CategoryLogLevel}|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{ClientIP}|%logger%n" /> + <property name="AuditLogPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%X{CategoryLogLevel}|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{ClientIP}%n" /> + <property name="ErrorLogPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS, GMT}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDescription}|%msg%n"/> + <property name="DebugLogPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS, GMT}|%X{RequestId}||%logger|%msg%n"/>--> + + <!-- new pattern --> + <property name="default-log-pattern" + value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{BeginTimestamp}|%X{EndTimestamp}|%X{uuid}|%X{serviceInstanceID}|%thread|%X{ServerName}|%X{ServiceName}|${ECOMP-subcomponent-name}|%X{userId}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDescription}|%level|%X{alarmSeverity}|%X{localAddr}|%X{ElapsedTime}|%X{beFqdn}|%X{remoteAddr}|%logger{35}|%X{timer}|ActivityType=<%M>, Desc=<%msg>%n"/> + + <property name="logDirectory" value="${logDir}/${componentName}"/> + + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <pattern>${defaultPattern}</pattern> + </encoder> + </appender> + + <appender name="DISPATCHER" class="ch.qos.logback.classic.sift.SiftingAppender"> + <discriminator class="org.openecomp.core.logging.logback.EventTypeDiscriminator"/> + <sift> + <appender name="${eventType}" class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/${eventType}.log</file> + <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> + <fileNamePattern>${logDirectory}/${eventType}.%i.log.zip</fileNamePattern> + <minIndex>1</minIndex> + <maxIndex>9</maxIndex> + </rollingPolicy> + <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>5MB</maxFileSize> + </triggeringPolicy> + <encoder> + <pattern>${default-log-pattern}</pattern> + </encoder> + </appender> + </sift> + </appender> + + <root level="DEBUG"> + <appender-ref ref="DISPATCHER"/> + </root> + +</configuration>
\ 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 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-lib</artifactId> + <version>1.0.0-SNAPSHOT</version> + <relativePath>../../..</relativePath> + </parent> + + <name>openecomp-facade-api</name> + <artifactId>openecomp-facade-api</artifactId> + <groupId>org.openecomp.core</groupId> + + + <dependencies> + + <dependency> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-utilities-lib</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-common-lib</artifactId> + <version>${project.version}</version> + </dependency> + </dependencies> + +</project>
\ 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 <i>thread-safe</i>. + * In a general case, the hierarchy of + * factory objects for an Java interface <tt>IUknown</tt> may look as follows: + * <pre> + * AbstractFactory<IUnknown> + * ^ + * | + * Application code ----> ConcreteFactory + * ^ + * | + * +---------+---------+ + * | | + * BaselineFactoryImpl CustomFactoryImpl + * </pre> + * Where the classes responsibility is: <ul> <li>Abstract factory - common logic to retrieve the + * implementation class name from a central repository.</li> <li>Concrete factory - abstract class + * that only exposes to application layer the type specific API such as: <ul> <li><tt>public static + * ConcreteFactory getInstance()</tt></li> </ul> <li>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: <ul> <li><tt>public IUnknown createInterface()</tt></li> + * </ul> </ul> The normal concrete factory class may look like: + * <pre> + * 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); + * } + * } + * </pre> + * + * @param <I> Java interface type created by the factory. + */ +public abstract class AbstractFactory<I> extends AbstractFactoryBase { + + + /** + * Returns the interface implementor instance. + * <b>Note</b>: 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<String, String> registry = new ConcurrentHashMap<String, String>(); + + /** + * Cached factory instances. + */ + private static Map<String, AbstractFactoryBase> factoryMap = + new ConcurrentHashMap<String, AbstractFactoryBase>(); + + /** + * Registers implementor for an abstract factory. The method accepts Java classes rather + * then class names to ensure type safety at compilation time. + * + * @param <I> Java interface type instantiated by abstract factory + * @param <F> 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 <I, F extends AbstractFactoryBase> void registerFactory(Class<F> factory, + Class<? extends F> 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 <F> the type parameter + * @param factory the factory + */ + public static <F extends AbstractFactoryBase> void unregisterFactory(Class<F> 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 <I> Java interface type instantiated by abstract factory + * @param <F> 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 <I, F extends AbstractFactoryBase> F getInstance(Class<F> 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 <F> the type parameter + * @param factoryType the factory type + * @return the boolean + */ + public static <F extends AbstractFactoryBase> boolean isFactoryRegistered(Class<F> 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<AbstractFactoryBase> 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 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <artifactId>openecomp-sdc-lib</artifactId> + <groupId>org.openecomp.sdc</groupId> + <version>1.0.0-SNAPSHOT</version> + <relativePath>../../..</relativePath> + </parent> + + <artifactId>openecomp-facade-core</artifactId> + <name>openecomp-facade-core</name> + <groupId>org.openecomp.core</groupId> + + <dependencies> + <dependency> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-utilities-lib</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-common-lib</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-facade-api</artifactId> + <version>${project.version}</version> + </dependency> + </dependencies> + + + +</project>
\ 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<I, C> 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<String, String> getFactoriesMap() { + synchronized (this) { + if (!initialized) { + init(); + initialized = true; + } + } + return factoryMap; + } + + private void init() { + List<InputStream> 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<String, String> 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<I> extends AbstractFactory<I> { + + 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<String, String> factoryMap = FactoryConfig.getFactoriesMap(); + + try { + for (Map.Entry<String, String> 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 <T> Class<T> unsecureCast(Class<?> cls) { + return (Class<T>) 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<String, String> 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 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <artifactId>openecomp-core-lib</artifactId> + <groupId>org.openecomp.core</groupId> + <version>1.0.0-SNAPSHOT</version> + </parent> + + <packaging>pom</packaging> + <artifactId>openecomp-facade-lib</artifactId> + <name>openecomp-facade-lib</name> + + <modules> + <module>openecomp-facade-api</module> + <module>openecomp-facade-core</module> + </modules> + + <dependencies> + <dependency> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-facade-api</artifactId> + <version>${project.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-facade-core</artifactId> + <version>${project.version}</version> + <scope>runtime</scope> + </dependency> + </dependencies> +</project>
\ 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 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <artifactId>openecomp-sdc-lib</artifactId> + <groupId>org.openecomp.sdc</groupId> + <version>1.0.0-SNAPSHOT</version> + <relativePath>../../..</relativePath> + </parent> + + <name>openecomp-nosqldb-api</name> + <artifactId>openecomp-nosqldb-api</artifactId> + <groupId>org.openecomp.core</groupId> + + <dependencies> + <dependency> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-facade-api</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>com.datastax.cassandra</groupId> + <artifactId>cassandra-driver-core</artifactId> + <version>${datasatx.version}</version> + </dependency> + <dependency> + <groupId>com.datastax.cassandra</groupId> + <artifactId>cassandra-driver-mapping</artifactId> + <version>${datasatx.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-facade-core</artifactId> + <version>${project.version}</version> + </dependency> + </dependencies> + + +</project>
\ 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<T> { + + Collection<T> 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<UniqueValueEntity> { + +} 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<UniqueValueDao> { + 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<NoSqlDb> { + + 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<String> 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<String> 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<String> 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<String> 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 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <artifactId>openecomp-sdc-lib</artifactId> + <groupId>org.openecomp.sdc</groupId> + <version>1.0.0-SNAPSHOT</version> + <relativePath>../../..</relativePath> + </parent> + + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-nosqldb-core</artifactId> + <name>openecomp-nosqldb-core</name> + + + <dependencies> + <dependency> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-nosqldb-api</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.yaml</groupId> + <artifactId>snakeyaml</artifactId> + <version>1.14</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.3.1</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-all</artifactId> + <scope>test</scope> + <version>1.10.19</version> + </dependency> + <dependency> + <groupId>org.testng</groupId> + <artifactId>testng</artifactId> + <scope>test</scope> + <version>6.8.5</version> + <exclusions> + <exclusion> + <artifactId>snakeyaml</artifactId> + <groupId>org.yaml</groupId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + <version>RELEASE</version> + </dependency> + </dependencies> +</project>
\ 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<T> implements BaseDao<T> { + protected abstract Mapper<T> 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<UniqueValueEntity> + implements UniqueValueDao { + + private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static Mapper<UniqueValueEntity> mapper = + noSqlDb.getMappingManager().mapper(UniqueValueEntity.class); + private static UniqueValueAccessor accessor = + noSqlDb.getMappingManager().createAccessor(UniqueValueAccessor.class); + + + @Override + protected Mapper<UniqueValueEntity> getMapper() { + return mapper; + } + + @Override + protected Object[] getKeys(UniqueValueEntity entity) { + return new Object[]{entity.getType(), entity.getValue()}; + } + + @Override + public Collection<UniqueValueEntity> list(UniqueValueEntity entity) { + return accessor.listAll().all(); + } + + @Accessor + interface UniqueValueAccessor { + + @Query("select * from unique_value") + Result<UniqueValueEntity> 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<SSLOptions> getSslOptions() { + Optional<String> truststorePath = Optional.of(CassandraUtils.getTruststore()); + Optional<String> 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<String, String> 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<String, Object> 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<String, LinkedHashMap<String, Object>> 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<Row> 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<String, LinkedHashMap<String, Object>> configurationMap = yamlutil.yamlToMap(yamlAsIS); + LinkedHashMap<String, Object> 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<String, InnerP> inner; + + public Map<String, InnerP> getInner() { + return inner; + } + + public void setInner(Map<String, InnerP> 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<String, Parameter> 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<String, Parameter> getParameters() { + return parameters; + } + + public void setParameters(Map<String, Parameter> 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 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <artifactId>openecomp-sdc-lib</artifactId> + <groupId>org.openecomp.sdc</groupId> + <version>1.0.0-SNAPSHOT</version> + <relativePath>../..</relativePath> + </parent> + + <artifactId>openecomp-nosqldb-lib</artifactId> + <groupId>org.openecomp.core</groupId> + <name>openecomp-nosqldb-lib</name> + <packaging>pom</packaging> + + <modules> + <module>openecomp-nosqldb-api</module> + <module>openecomp-nosqldb-core</module> + </modules> + + <dependencies> + <dependency> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-nosqldb-api</artifactId> + <version>${project.version}</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-nosqldb-core</artifactId> + <version>${project.version}</version> + <scope>runtime</scope> + </dependency> + </dependencies> +</project>
\ 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 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <artifactId>openecomp-core-lib</artifactId> + <groupId>org.openecomp.core</groupId> + <version>1.0.0-SNAPSHOT</version> + </parent> + + <artifactId>openecomp-utilities-lib</artifactId> + <name>openecomp-utilities-lib</name> + + + <dependencies> + <dependency> + <groupId>org.yaml</groupId> + <artifactId>snakeyaml</artifactId> + <version>1.14</version> + </dependency> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-lang3</artifactId> + <version>3.4</version> + </dependency> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-collections4</artifactId> + <version>4.1</version> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.3.1</version> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + <version>1.7.10</version> + + </dependency> + <!--<dependency> + <groupId>org.yaml</groupId> + <artifactId>snakeyaml</artifactId> + <version>1.17</version> + </dependency>--> + <dependency> + <groupId>commons-codec</groupId> + <artifactId>commons-codec</artifactId> + <version>${commons.codec.version}</version> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + <version>RELEASE</version> + </dependency> + <dependency> + <groupId>org.codehaus.jackson</groupId> + <artifactId>jackson-mapper-asl</artifactId> + <version>${org.codehaus.jackson.version}</version> + </dependency> + <dependency> + <groupId>org.everit.json</groupId> + <artifactId>org.everit.json.schema</artifactId> + <version>${org.everit.json.schema.version}</version> + </dependency> + <dependency> + <groupId>org.testng</groupId> + <artifactId>testng</artifactId> + <scope>test</scope> + <version>6.8.5</version> + <exclusions> + <exclusion> + <artifactId>snakeyaml</artifactId> + <groupId>org.yaml</groupId> + </exclusion> + </exclusions> + </dependency> + </dependencies> + +</project>
\ 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 <tt>Object</tt> is empty. + * + * @param obj Object to be checked. + * @return <tt>true</tt> - if the Object is null, <tt>false</tt> otherwise. + */ + public static boolean isEmpty(Object obj) { + return obj == null; + } + + /** + * Checks whether the given <tt>Object</tt> is empty. + * + * @param byteArray Object to be checked. + * @return <tt>true</tt> - if the Object is null, <tt>false</tt> otherwise. + */ + public static boolean isEmpty(byte[] byteArray) { + return (byteArray == null || byteArray.length == 0); + } + + /** + * Checks whether the given <tt>String</tt> is empty. + * + * @param str String object to be checked. + * @return <tt>true</tt> - if the String is null or empty, <tt>false</tt> - 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 <tt>true</tt> - if the array is null or empty, <tt>false</tt> - 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 <tt>true</tt> - if the collection is null or empty, <tt>false</tt> - 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 <tt>true</tt> - if the map is null or empty, <tt>false</tt> - 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 <T> 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> T[] toArray(Collection<? extends T> col, Class<T> 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 <T> the type parameter + * @param left Elements of this array will be copied to positions from 0 to + * <tt>left.length - 1</tt> in the target array. + * @param right Elements of this array will be copied to positions from + * <tt>left.length</tt> to <tt>left.length + right.length</tt> + * @return A newly allocate Java array that accommodates elements of source (left/right) + arraysor one of source arrays if another is empty, <tt>null</tt> - otherwise. + */ + @SuppressWarnings("unchecked") + public static <T> 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 + * <tt>Class</tt> object. The method logic is similar to Java method + * <tt>Class.cast(Object)</tt> 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 <B> the type parameter + * @param <D> 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 <B, D> D cast(B b0, Class<D> 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 <T> the type parameter + * @param classname the classname + * @param cls the cls + * @return the t + */ + @SuppressWarnings("unchecked") + public static <T> T newInstance(String classname, Class<T> 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<? extends T> impl = (Class<? extends T>) temp; + + return newInstance(impl); + } catch (ClassNotFoundException e0) { + throw new IllegalArgumentException(e0); + } + } + + /** + * New instance t. + * + * @param <T> the type parameter + * @param cls the cls + * @return the t + */ + public static <T> T newInstance(Class<T> 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<String> elementCollection) { + List<String> 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<String> 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 <T> 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 <T> Set<T> 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<String, byte[]> 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<String> getFileList() { + return files.keySet(); + } + + public void putAll(Map<String, byte[]> 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<InputStream> getFileInputStreams(String fileName) { + Enumeration<URL> urlFiles; + List<InputStream> 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<URL> 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<String, Object> 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 <T> the type parameter + * @param json the json + * @param classOfT the class of t + * @return the t + */ + public static <T> T json2Object(String json, Class<T> 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 <T> the type parameter + * @param is the is + * @param classOfT the class of t + * @return the t + */ + public static <T> T json2Object(InputStream is, Class<T> 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<String> validate(String json, String jsonSchema) { + List<ValidationException> 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<Object> 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<ValidationException> 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 <T> the type parameter + * @param yamlContent the yaml content + * @param typClass the typ class + * @return the t + */ + public <T> T yamlToObject(String yamlContent, Class<T> 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 <T> the type parameter + * @param yamlContent the yaml content + * @param typClass the typ class + * @return the t + */ + public <T> T yamlToObject(InputStream yamlContent, Class<T> 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 <T> the type parameter + * @param typClass the typ class + * @return the constructor + */ + public <T> Constructor getConstructor(Class<T> 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<String, LinkedHashMap<String, Object>> yamlToMap(InputStream yamlContent) { + Yaml yaml = new Yaml(); + Map<String, LinkedHashMap<String, Object>> yamlData = + (Map<String, LinkedHashMap<String, Object>>) yaml.load(yamlContent); + return yamlData; + } + + /** + * Object to yaml string. + * + * @param <T> the type parameter + * @param obj the obj + * @return the string + */ + public <T> 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<Property> 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<Property> createPropertySet(Class<? extends Object> type, BeanAccess beanAccess) + throws IntrospectionException { + return new LinkedHashSet<Property>(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<Object, Object> 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<Object, Object> createDefaultMap() { + final Map<Object, Object> delegate = super.createDefaultMap(); + return new AbstractMap<Object, Object>() { + @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<Entry<Object, Object>> 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<String> 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<String> 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 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <artifactId>openecomp-sdc-lib</artifactId> + <groupId>org.openecomp.sdc</groupId> + <version>1.0.0-SNAPSHOT</version> + </parent> + + <groupId>org.openecomp.core</groupId> + <artifactId>openecomp-core-lib</artifactId> + <name>openecomp-core-lib</name> + + <packaging>pom</packaging> + + <modules> + <module>/openecomp-facade-lib</module> + <module>/openecomp-nosqldb-lib</module> + <module>/openecomp-utilities-lib</module> + <module>/openecomp-config-lib</module> + </modules> +</project>
\ No newline at end of file |