From 3df3182a7badeef662f743bfc8d67cea805b1ef4 Mon Sep 17 00:00:00 2001 From: mojahidi Date: Tue, 29 Aug 2017 18:20:26 +0530 Subject: Update ASDC References to SDC 1/2 This patch changes ASDC to SDC in APPC code, bundle names and other pertinent places. This change sanitizes SDC for Open Source. It is the first in a two part change, the first updates code mentions and artifacts. The second will update database references. Change-Id: Iffd73480cc325172b5d8969fe839728f1c88ef78 Issue-ID:APPC-179 Signed-off-by: mojahidi --- appc-sdc-listener/.gitignore | 21 ++ .../appc-sdc-listener-bundle/.gitignore | 2 + .../org.eclipse.wst.common.project.facet.core.xml | 4 + .../appc-sdc-listener-bundle/etc/asdc-client.jks | Bin 0 -> 1177 bytes .../etc/asdcclientstore.jks | Bin 0 -> 907 bytes .../appc-sdc-listener-bundle/log4j.properties | 17 + appc-sdc-listener/appc-sdc-listener-bundle/pom.xml | 267 +++++++++++++++ .../appc/sdc/artifacts/ArtifactProcessor.java | 41 +++ .../artifacts/helper/ArtifactStorageService.java | 329 ++++++++++++++++++ .../appc/sdc/artifacts/helper/Constants.java | 72 ++++ .../artifacts/helper/DependencyModelGenerator.java | 97 ++++++ .../artifacts/impl/AbstractArtifactProcessor.java | 196 +++++++++++ .../artifacts/impl/ArtifactProcessorFactory.java | 88 +++++ .../artifacts/impl/ConfigArtifactProcessor.java | 76 +++++ .../artifacts/impl/LicenseArtifactProcessor.java | 92 +++++ .../artifacts/impl/ToscaCsarArtifactProcessor.java | 241 +++++++++++++ .../appc/sdc/artifacts/object/ArtifactType.java | 46 +++ .../appc/sdc/artifacts/object/Resource.java | 87 +++++ .../appc/sdc/artifacts/object/SDCArtifact.java | 215 ++++++++++++ .../appc/sdc/artifacts/object/SDCReference.java | 94 ++++++ .../openecomp/appc/sdc/artifacts/object/Vnfc.java | 78 +++++ .../appc/sdc/listener/ProviderOperations.java | 211 ++++++++++++ .../appc/sdc/listener/ProviderResponse.java | 45 +++ .../openecomp/appc/sdc/listener/SdcCallback.java | 147 ++++++++ .../org/openecomp/appc/sdc/listener/SdcConfig.java | 197 +++++++++++ .../openecomp/appc/sdc/listener/SdcListener.java | 219 ++++++++++++ .../java/org/openecomp/appc/sdc/listener/Util.java | 126 +++++++ .../org/openecomp/tlv/sdc/security/Passwords.java | 170 ++++++++++ .../resources/OSGI-INF/blueprint/blueprint.xml | 43 +++ .../main/resources/ci/conf/attsdc-packages.yaml | 10 + .../src/main/resources/ci/conf/attsdc.yaml | 35 ++ .../src/main/resources/ci/conf/log4j.properties | 58 ++++ .../src/main/resources/ci/conf/titan.properties | 29 ++ .../src/main/resources/ci/scripts/startTest.sh | 112 +++++++ .../org/openecomp/appc/default.properties | 40 +++ .../appc/sdc/listener/SdcCallbackTest.java | 192 +++++++++++ .../appc/sdc/listener/SdcListenerTest.java | 158 +++++++++ .../org/openecomp/appc/sdc/listener/TestRun.java | 41 +++ .../resources/csar/service-ServiceAppc-csar.csar | Bin 0 -> 9782 bytes .../org/openecomp/appc/default.properties | 36 ++ .../appc-sdc-listener-features/.gitignore | 3 + .../appc-sdc-listener-features/pom.xml | 112 +++++++ .../src/main/resources/features.xml | 41 +++ .../appc-sdc-listener-installer/.gitignore | 2 + .../appc-sdc-listener-installer/pom.xml | 156 +++++++++ .../src/assembly/assemble_installer_zip.xml | 62 ++++ .../src/assembly/assemble_mvnrepo_zip.xml | 50 +++ .../src/main/resources/scripts/install-feature.sh | 63 ++++ appc-sdc-listener/appc-yang-generator/pom.xml | 97 ++++++ .../org/openecomp/appc/yang/YANGGenerator.java | 49 +++ .../yang/exception/YANGGenerationException.java | 51 +++ .../appc/yang/impl/YANGGeneratorFactory.java | 52 +++ .../appc/yang/impl/YANGGeneratorImpl.java | 176 ++++++++++ .../java/org/openecomp/appc/yang/objects/Leaf.java | 72 ++++ .../org/openecomp/appc/yang/type/YangTypes.java | 108 ++++++ .../src/main/resources/templates/YangTemplate.vm | 47 +++ .../java/org/openecomp/appc/TestYANGGenerator.java | 197 +++++++++++ .../src/test/resources/tosca/toscaFile.yml | 319 ++++++++++++++++++ .../resources/tosca/toscaFileWithSyntaxError.yml | 319 ++++++++++++++++++ .../tosca/toscaFileWithUnsupportedTypes.yml | 373 +++++++++++++++++++++ .../src/test/resources/yang/expectedYang.yang | 345 +++++++++++++++++++ appc-sdc-listener/pom.xml | 129 +++++++ 62 files changed, 6755 insertions(+) create mode 100644 appc-sdc-listener/.gitignore create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/.gitignore create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/.settings/org.eclipse.wst.common.project.facet.core.xml create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/etc/asdc-client.jks create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/etc/asdcclientstore.jks create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/log4j.properties create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/pom.xml create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/ArtifactProcessor.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/ArtifactStorageService.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/Constants.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/DependencyModelGenerator.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/ArtifactType.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Resource.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCArtifact.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCReference.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Vnfc.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderOperations.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderResponse.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcCallback.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcConfig.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcListener.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/Util.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/tlv/sdc/security/Passwords.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/OSGI-INF/blueprint/blueprint.xml create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/attsdc-packages.yaml create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/attsdc.yaml create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/log4j.properties create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/titan.properties create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/scripts/startTest.sh create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/org/openecomp/appc/default.properties create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcCallbackTest.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcListenerTest.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/TestRun.java create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/csar/service-ServiceAppc-csar.csar create mode 100644 appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/org/openecomp/appc/default.properties create mode 100644 appc-sdc-listener/appc-sdc-listener-features/.gitignore create mode 100644 appc-sdc-listener/appc-sdc-listener-features/pom.xml create mode 100644 appc-sdc-listener/appc-sdc-listener-features/src/main/resources/features.xml create mode 100644 appc-sdc-listener/appc-sdc-listener-installer/.gitignore create mode 100644 appc-sdc-listener/appc-sdc-listener-installer/pom.xml create mode 100644 appc-sdc-listener/appc-sdc-listener-installer/src/assembly/assemble_installer_zip.xml create mode 100644 appc-sdc-listener/appc-sdc-listener-installer/src/assembly/assemble_mvnrepo_zip.xml create mode 100644 appc-sdc-listener/appc-sdc-listener-installer/src/main/resources/scripts/install-feature.sh create mode 100644 appc-sdc-listener/appc-yang-generator/pom.xml create mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/YANGGenerator.java create mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/exception/YANGGenerationException.java create mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorFactory.java create mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorImpl.java create mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/objects/Leaf.java create mode 100644 appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/type/YangTypes.java create mode 100644 appc-sdc-listener/appc-yang-generator/src/main/resources/templates/YangTemplate.vm create mode 100644 appc-sdc-listener/appc-yang-generator/src/test/java/org/openecomp/appc/TestYANGGenerator.java create mode 100644 appc-sdc-listener/appc-yang-generator/src/test/resources/tosca/toscaFile.yml create mode 100644 appc-sdc-listener/appc-yang-generator/src/test/resources/tosca/toscaFileWithSyntaxError.yml create mode 100644 appc-sdc-listener/appc-yang-generator/src/test/resources/tosca/toscaFileWithUnsupportedTypes.yml create mode 100644 appc-sdc-listener/appc-yang-generator/src/test/resources/yang/expectedYang.yang create mode 100644 appc-sdc-listener/pom.xml (limited to 'appc-sdc-listener') diff --git a/appc-sdc-listener/.gitignore b/appc-sdc-listener/.gitignore new file mode 100644 index 000000000..c82c130d9 --- /dev/null +++ b/appc-sdc-listener/.gitignore @@ -0,0 +1,21 @@ +# Target dirs in all projects +**/target/* + +# Generated models and features +/model/bin/* +/features/bin/* + +# MANIFEST.MF is updated on every clean install +MANIFEST.MF + +# Karaf Assembly + + +*.prefs +.classpath +.project +/.settings/ + +logs/ +debug-logs/ +/target/ diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/.gitignore b/appc-sdc-listener/appc-sdc-listener-bundle/.gitignore new file mode 100644 index 000000000..09e3bc9b2 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/.gitignore @@ -0,0 +1,2 @@ +/bin/ +/target/ diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/.settings/org.eclipse.wst.common.project.facet.core.xml b/appc-sdc-listener/appc-sdc-listener-bundle/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 000000000..f4ef8aa0a --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,4 @@ + + + + diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/etc/asdc-client.jks b/appc-sdc-listener/appc-sdc-listener-bundle/etc/asdc-client.jks new file mode 100644 index 000000000..eb0a0d35a Binary files /dev/null and b/appc-sdc-listener/appc-sdc-listener-bundle/etc/asdc-client.jks differ diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/etc/asdcclientstore.jks b/appc-sdc-listener/appc-sdc-listener-bundle/etc/asdcclientstore.jks new file mode 100644 index 000000000..5dc006db0 Binary files /dev/null and b/appc-sdc-listener/appc-sdc-listener-bundle/etc/asdcclientstore.jks differ diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/log4j.properties b/appc-sdc-listener/appc-sdc-listener-bundle/log4j.properties new file mode 100644 index 000000000..abdf8675a --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/log4j.properties @@ -0,0 +1,17 @@ +log4j.rootCategory=DEBUG, CONSOLE, LOGFILE + +log4j.logger.com.att=TRACE, CONSOLE, LOGFILE + +# CONSOLE is set to be a ConsoleAppender using a PatternLayout. +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss.SSS Z} %c{1} - %m%n + +# LOGFILE is set to be a File appender using a PatternLayout. +log4j.appender.LOGFILE=org.apache.log4j.RollingFileAppender +log4j.appender.LOGFILE.File=logs/wordnik.log +log4j.appender.LOGFILE.Append=true +log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout +log4j.appender.LOGFILE.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss.SSS Z} %c{1} - %m%n +log4j.appender.LOGFILE.MaxFileSize=10MB +log4j.appender.LOGFILE.MaxBackupIndex=10 diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/pom.xml b/appc-sdc-listener/appc-sdc-listener-bundle/pom.xml new file mode 100644 index 000000000..22040cb55 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/pom.xml @@ -0,0 +1,267 @@ + + + 4.0.0 + + + + appc-sdc-listener + org.openecomp.appc + 1.1.0-SNAPSHOT + + + + 2.8.1 + 1.15 + + + appc-sdc-listener-bundle + bundle + + + + + equinoxSDK381 + org.eclipse.osgi + + + + org.json + json + compile + + + org.mockito + mockito-all + test + + + + org.mockito + mockito-core + test + + + org.powermock + powermock-module-junit4 + 1.6.2 + test + + + org.powermock + powermock-api-mockito + test + + + + org.openecomp.sdc.sdc-distribution-client + sdc-distribution-client + ${sdc-client.version} + + + + org.openecomp.appc + appc-message-adapter-api + ${project.version} + + + + org.openecomp.appc + appc-message-adapter-factory + ${project.version} + + + + org.yaml + snakeyaml + ${snakeyaml.version} + + + + org.openecomp.appc + appc-common + ${project.version} + + + + + junit + junit + compile + + + + com.att.eelf + eelf-core + + + ch.qos.logback + logback-core + + + ch.qos.logback + logback-classic + + + org.functionaljava + functionaljava + 4.2 + + + org.apache.httpcomponents + httpcore + 4.4.1 + + + org.apache.httpcomponents + httpclient + 4.4.1 + + + + org.openecomp.appc + appc-license-manager-api + + ${project.version} + + + + com.google.code.gson + gson + + + + org.apache.velocity + velocity + 1.7 + + + + org.opendaylight.yangtools + yang-parser-impl + ${odl.yangtools.version} + + + + org.opendaylight.mdsal.model + ietf-inet-types + ${odl.ietf-inet-types.version} + + + org.opendaylight.mdsal.model + ietf-yang-types + ${odl.ietf-yang-types.version} + + + + org.openecomp.appc + appc-dg-dependency-model + ${project.version} + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + ${jackson-yaml-version} + + + org.openecomp.appc + appc-dg-domain-model-lib + ${project.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-yaml-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-yaml-version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson-yaml-version} + + + org.yaml + snakeyaml + ${snakeyaml.version} + + + + org.mockito + mockito-core + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + 1.7 + 1.7 + + + + + org.apache.felix + maven-bundle-plugin + true + + + org.openecomp.appc.sdc.listener + + org.openecomp.appc.sdc.listener + + org.openecomp.appc.licmgr, + org.openecomp.appc.adapter.messaging.*, + com.att.eelf.*, + *;resolution:=optional + + + sdc-distribution-client,snakeyaml, + saClientLibrary,cambriaClient,saToolkit, + functionaljava,httpcore,httpclient,gson,appc-dg-dependency-model,appc-dg-domain-model-lib, + jackson-core,jackson-databind,jackson-annotations,jackson-dataformat-yaml; + scope=compile|runtime;inline=false + + true + + + + + + diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/ArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/ArtifactProcessor.java new file mode 100644 index 000000000..c0f52206f --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/ArtifactProcessor.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts; + +import org.openecomp.appc.exceptions.APPCException; +import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; + +/** + * This interface provides api processArtifact which cab have multiple implementation + * for type of artifact app-c receives from sdc + */ +public interface ArtifactProcessor extends Runnable { + /** + * Processes the artifact received from sdc + * @param result an instance of IDistributionClientDownloadResult + * @throws APPCException + */ + void processArtifact(IDistributionClientDownloadResult result) throws APPCException; +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/ArtifactStorageService.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/ArtifactStorageService.java new file mode 100644 index 000000000..7f461c043 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/ArtifactStorageService.java @@ -0,0 +1,329 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts.helper; + +import org.apache.commons.lang.StringUtils; +import org.openecomp.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.openecomp.appc.sdc.artifacts.object.SDCReference; +import org.openecomp.sdnc.sli.resource.dblib.DbLibService; +import org.openecomp.appc.sdc.artifacts.object.SDCArtifact; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import javax.sql.rowset.CachedRowSet; +import java.sql.SQLException; +import java.util.ArrayList; + +import static org.openecomp.appc.sdc.artifacts.helper.Constants.COMMA; +import static org.openecomp.appc.sdc.artifacts.helper.Constants.AND; + +/** + * Provides methods for storing sdc artifacts into app-c database + */ +public class ArtifactStorageService { + + private DbLibService dbLibService; + + private static final String SCHEMA = "sdnctl"; + + private static final String SELECT_QUERY = Constants.SELECT_FROM + Constants.SDC_ARTIFACTS + + Constants.WHERE + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME + Constants.QUERY_PLACEHOLDER + + AND + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION + Constants.QUERY_PLACEHOLDER + + AND + Constants.ARTIFACT_TYPE + Constants.QUERY_PLACEHOLDER; + + private static final String SELECT_QUERY_SDC_REFERENCE = Constants.SELECT_FROM + Constants.SDC_REFERENCE + + Constants.WHERE + Constants.SDC_REFERENCE_FIELDS.VNF_TYPE + Constants.QUERY_PLACEHOLDER + + AND + Constants.SDC_REFERENCE_FIELDS.FILE_CATEGORY + Constants.QUERY_PLACEHOLDER ; + + private static final String INSERT_QUERY = Constants.INSERT + Constants.SDC_ARTIFACTS + + " ( " + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_UUID + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.DISTRIBUTION_ID + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_DESCRIPTION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_UUID + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_INSTANCE_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_TYPE + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_UUID + COMMA + + Constants.ARTIFACT_TYPE + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_VERSION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_DESCRIPTION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.CREATION_DATE + COMMA + + Constants.ARTIFACT_NAME +COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_CONTENT + " ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + private static final String INSERT_QUERY_WITH_INT_VER = Constants.INSERT + Constants.SDC_ARTIFACTS + + " ( " + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_UUID + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.DISTRIBUTION_ID + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.SERVICE_DESCRIPTION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_UUID + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_INSTANCE_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_TYPE + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_UUID + COMMA + + Constants.ARTIFACT_TYPE + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_VERSION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_DESCRIPTION + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.CREATION_DATE + COMMA + + Constants.ARTIFACT_NAME + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_CONTENT + COMMA + + Constants.SDC_ARTIFACTS_FIELDS.INTERNAL_VERSION + " ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + private static final String SDC_REF_INSERT_QUERY = Constants.INSERT + Constants.SDC_REFERENCE + + "( "+ Constants.SDC_REFERENCE_FIELDS.VNF_TYPE + COMMA + + Constants.SDC_REFERENCE_FIELDS.VNFC_TYPE+ COMMA + + Constants.SDC_REFERENCE_FIELDS.FILE_CATEGORY +COMMA + + Constants.SDC_REFERENCE_FIELDS.ACTION +COMMA + + Constants.ARTIFACT_TYPE + COMMA + + Constants.ARTIFACT_NAME + " ) values (?,?,?,?,?,?)"; + + private static final String SELECT_MAX_INT_VERSION = "SELECT coalesce(max(" + Constants.SDC_ARTIFACTS_FIELDS.INTERNAL_VERSION + ")+1,1) as " + Constants.SDC_ARTIFACTS_FIELDS.INTERNAL_VERSION + + " FROM " + Constants.SDC_ARTIFACTS + Constants.WHERE + Constants.ARTIFACT_NAME + Constants.QUERY_PLACEHOLDER; + + + private final EELFLogger logger = EELFManager.getInstance().getLogger(ArtifactStorageService.class); + + /** + * Stores Artifact received from SDC into APP-C database + * @param artifact - SDC Artifact object + * @throws APPCException + */ + public void storeSDCArtifact(SDCArtifact artifact) throws APPCException { + if(logger.isDebugEnabled()){ + logger.debug("Entering storeSDCArtifact with : " + artifact.toString()); + } + try { + initializeDBLibService(); + ArrayList arguments = prepareArguments(artifact); + dbLibService.writeData(INSERT_QUERY,arguments,SCHEMA); + } catch (SQLException e) { + logger.error("Error storing artifact in database : " +artifact.toString(),e); + throw new APPCException(e.getMessage(),e); + } + if(logger.isDebugEnabled()){ + logger.debug("Exiting storeSDCArtifact"); + } + } + + /** + * Stores Artifact received from SDC and its Reference into APP-C database if it does not exist + * @param artifact - SDC Artifact object + * @param reference - SDC reference object + * @throws APPCException + */ + public void storeSDCArtifactWithReference(SDCArtifact artifact , SDCReference reference) throws APPCException { + if(logger.isDebugEnabled()){ + logger.debug("Entering storeSDCArtifactWithReference with : " + artifact.toString()); + } + try { + initializeDBLibService(); + SDCArtifact existingArtifact = retrieveSDCArtifact(artifact.getResourceName(), artifact.getResourceVersion(),artifact.getArtifactType()); + if (existingArtifact ==null) { // new resource + logger.debug(String.format("Artifact not found for vnfType = %s, version = %s and artifactType = %s. Inserting data." , + artifact.getResourceName(),artifact.getResourceVersion() ,artifact.getArtifactType())); + ArrayList arguments = prepareArguments(artifact); + Integer version = getNextInternalVersion(artifact.getArtifactName()); + arguments.add(version.toString()); + dbLibService.writeData(INSERT_QUERY_WITH_INT_VER,arguments,SCHEMA); + } else { // duplicate + logger.debug(String.format("Artifact of type '%s' already deployed for resource_type='%s' and resource_version='%s'", + artifact.getArtifactType() , artifact.getResourceName() , artifact.getResourceVersion())); + } + + SDCReference existingReference = retrieveSDCReference(reference.getVnfType(),reference.getFileCategory()); + if(existingReference == null){ + logger.debug("Inserting SDC Reference data: " +reference.toString()); + ArrayList arguments = prepareReferenceArguments(reference); + dbLibService.writeData(SDC_REF_INSERT_QUERY,arguments,SCHEMA); + }else{ + logger.debug("Artifact reference already exists for: " +reference.toString()); + } + } catch (SQLException e) { + logger.error("Error storing artifact to database: " + artifact.toString(),e); + throw new APPCException(e.getMessage(),e); + } + if(logger.isDebugEnabled()){ + logger.debug("Exiting storeSDCArtifactWithReference"); + } + } + + private Integer getNextInternalVersion(String artifactName) throws APPCException { + if (logger.isDebugEnabled()) { + logger.debug("Entering getNextInternalVersion with artifactName:" + artifactName); + } + Integer version = 1; + try { + initializeDBLibService(); + ArrayList arguments = new ArrayList<>(); + arguments.add(artifactName); + CachedRowSet rowSet = dbLibService.getData(SELECT_MAX_INT_VERSION, arguments, SCHEMA); + if (rowSet.first()) { + version = rowSet.getInt(Constants.SDC_ARTIFACTS_FIELDS.INTERNAL_VERSION .toString()); + } + }catch (SQLException e) { + logger.error("Error getting internal version for artifact name " + artifactName , e); + throw new APPCException(e); + } + if (logger.isDebugEnabled()) { + logger.debug("Exiting getNextInternalVersion with retrieved version:" + version.toString()); + } + return version; + } + + private void initializeDBLibService() { + if(dbLibService == null){ + BundleContext context = FrameworkUtil.getBundle(DbLibService.class).getBundleContext(); + ServiceReference serviceReference = context.getServiceReference(DbLibService.class.getName()); + dbLibService = (DbLibService)context.getService(serviceReference); + } + } + + private ArrayList prepareReferenceArguments(SDCReference reference) { + ArrayList arguments = new ArrayList<>(); + arguments.add(reference.getVnfType()); + arguments.add(reference.getVnfcType()); + arguments.add(reference.getFileCategory()); + arguments.add(reference.getAction()); + arguments.add(reference.getArtifactType()); + arguments.add(reference.getArtifactName()); + return arguments; + } + + private ArrayList prepareArguments(SDCArtifact artifact) { + ArrayList arguments = new ArrayList<>(); + arguments.add(artifact.getServiceUUID()); + arguments.add(artifact.getDistributionId()); + arguments.add(artifact.getServiceName()); + arguments.add(truncateServiceDescription(artifact.getServiceDescription())); + arguments.add(artifact.getResourceUUID()); + arguments.add(artifact.getResourceInstanceName()); + arguments.add(artifact.getResourceName()); + arguments.add(artifact.getResourceVersion()); + arguments.add(artifact.getResourceType()); + arguments.add(artifact.getArtifactUUID()); + arguments.add(artifact.getArtifactType()); + arguments.add(artifact.getArtifactVersion()); + arguments.add(artifact.getArtifactDescription()); + arguments.add(artifact.getCreationDate()); + arguments.add(artifact.getArtifactName()); + arguments.add(artifact.getArtifactContent()); + return arguments; + } + + private String truncateServiceDescription(String serviceDescription){ + if (!StringUtils.isBlank(serviceDescription) && serviceDescription.length()>255){ + logger.info("Truncating the SERVICE_DESCRIPTION to 255 characters"); + serviceDescription=serviceDescription.substring(0,255); + } + return serviceDescription; + } + + /** + * Reads the SDC artifact from APP-C database + * @param resourceName - resource Name from SDC Artifact + * @param resourceVersion - resource version from SDC Artifact + * @param artifactType artifact type from SDC Artifact + * @return - SDC_ARTIFACT record if data exists + * @throws APPCException + */ + public SDCArtifact retrieveSDCArtifact(String resourceName, String resourceVersion, String artifactType) throws APPCException { + SDCArtifact artifact = null; + try { + initializeDBLibService(); + ArrayList arguments = new ArrayList<>(); + arguments.add(resourceName); + arguments.add(resourceVersion); + arguments.add(artifactType); + CachedRowSet rowSet = dbLibService.getData(SELECT_QUERY, arguments, SCHEMA); + if (rowSet.first()) { + artifact = new SDCArtifact(); + artifact.setArtifactUUID(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_UUID.toString())); + artifact.setArtifactName(rowSet.getString(Constants.ARTIFACT_NAME)); + artifact.setArtifactType(rowSet.getString(Constants.ARTIFACT_TYPE)); + artifact.setArtifactVersion(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_VERSION.toString())); + artifact.setArtifactDescription(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_DESCRIPTION.toString())); + artifact.setArtifactContent(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.ARTIFACT_CONTENT.toString())); + + artifact.setResourceUUID(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_UUID.toString())); + artifact.setResourceName(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME.toString())); + artifact.setResourceType(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_TYPE.toString())); + artifact.setResourceVersion(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION.toString())); + artifact.setResourceInstanceName(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_INSTANCE_NAME.toString())); + + artifact.setServiceUUID(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.SERVICE_UUID.toString())); + artifact.setServiceName(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.SERVICE_NAME.toString())); + artifact.setServiceDescription(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.SERVICE_DESCRIPTION.toString())); + + artifact.setCreationDate(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.CREATION_DATE.toString())); + artifact.setDistributionId(rowSet.getString(Constants.SDC_ARTIFACTS_FIELDS.DISTRIBUTION_ID.toString())); + } + + } catch (SQLException e) { + logger.error("Error query artifact for " + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_NAME + " = " + resourceName + + Constants.SDC_ARTIFACTS_FIELDS.RESOURCE_VERSION + " = " + resourceVersion + + Constants.ARTIFACT_TYPE + " = " + artifactType, e); + throw new APPCException(e); + } + return artifact; + } + + /** + * Reads the SDC reference from APP-C database + * @param vnfType - vnf Type from SDC reference + * @param fileCategory - file category from SDC reference + * @return - SDC_ARTIFACT record if data exists + * @throws APPCException + */ + public SDCReference retrieveSDCReference(String vnfType, String fileCategory) throws APPCException { + SDCReference reference = null; + try { + initializeDBLibService(); + ArrayList arguments = new ArrayList<>(); + arguments.add(vnfType); + arguments.add(fileCategory); + CachedRowSet rowSet = dbLibService.getData(SELECT_QUERY_SDC_REFERENCE, arguments, SCHEMA); + if (rowSet.first()) { + reference = new SDCReference(); + reference.setVnfType(rowSet.getString(Constants.SDC_REFERENCE_FIELDS.VNF_TYPE.toString())); + reference.setVnfcType(rowSet.getString(Constants.SDC_REFERENCE_FIELDS.VNFC_TYPE.toString())); + reference.setFileCategory(rowSet.getString(Constants.SDC_REFERENCE_FIELDS.FILE_CATEGORY.toString())); + reference.setAction(rowSet.getString(Constants.SDC_REFERENCE_FIELDS.ACTION.toString())); + reference.setArtifactType(rowSet.getString(Constants.ARTIFACT_TYPE)); + reference.setArtifactName(rowSet.getString(Constants.ARTIFACT_NAME)); + } + } catch (SQLException e) { + logger.error("Error querying SDC_REFERENCE for " + Constants.SDC_REFERENCE_FIELDS.VNF_TYPE + " = " + vnfType + + Constants.SDC_REFERENCE_FIELDS.FILE_CATEGORY + " = " + fileCategory , e); + throw new APPCException(e); + } + return reference; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/Constants.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/Constants.java new file mode 100644 index 000000000..4970a739e --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/Constants.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts.helper; + +/** + * Constants required in SDC listener module + */ +public class Constants { + static final String SDC_ARTIFACTS = "ASDC_ARTIFACTS"; + static final String SDC_REFERENCE = "ASDC_REFERENCE"; + + static final String AND = " AND "; + + static final String ARTIFACT_TYPE = "ARTIFACT_TYPE"; + static final String ARTIFACT_NAME = "ARTIFACT_NAME"; + + static final String VF_LICENSE = "VF_LICENSE"; + + public enum SDC_ARTIFACTS_FIELDS { + SERVICE_UUID, + DISTRIBUTION_ID, + SERVICE_NAME, + SERVICE_DESCRIPTION, + RESOURCE_UUID, + RESOURCE_INSTANCE_NAME, + RESOURCE_NAME, + RESOURCE_VERSION, + RESOURCE_TYPE, + ARTIFACT_UUID, + ARTIFACT_VERSION, + ARTIFACT_DESCRIPTION, + INTERNAL_VERSION, + CREATION_DATE, + ARTIFACT_CONTENT + } + + public enum SDC_REFERENCE_FIELDS{ + SDC_REFERENCE_ID, + VNF_TYPE, + VNFC_TYPE, + FILE_CATEGORY, + ACTION + } + + static final String COMMA = " , "; + static final String QUERY_PLACEHOLDER = " = ? "; + static final String SELECT_FROM = "SELECT * FROM " ; + static final String WHERE = " WHERE "; + static final String INSERT = "INSERT INTO "; +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/DependencyModelGenerator.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/DependencyModelGenerator.java new file mode 100644 index 000000000..0f8065a30 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/DependencyModelGenerator.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts.helper; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import org.openecomp.appc.dg.dependencymanager.helper.DependencyModelParser; +import org.openecomp.appc.dg.objects.Node; +import org.openecomp.appc.dg.objects.VnfcDependencyModel; +import org.openecomp.appc.domainmodel.Vnfc; +import org.openecomp.appc.exceptions.APPCException; + +import java.util.ArrayList; +import java.util.List; + +/** + * Provides method for genrating Dependency JSON from Tosca model + */ +public class DependencyModelGenerator { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(DependencyModelGenerator.class); + + /** + * + * @param tosca - tosca string from SDC + * @param vnfType - Vnf Type from tosca + * @return - Dependency JSON in String format + * @throws APPCException is thrown if error occurs + */ + public String getDependencyModel(String tosca, String vnfType) throws APPCException { + logger.debug(String.format("Generating dependency model for vnfType : %s , TOSCA: %s ", vnfType ,tosca)); + String dependencyJson; + DependencyModelParser dependencyModelParser = new DependencyModelParser(); + VnfcDependencyModel vnfcDependencyModel = dependencyModelParser.generateDependencyModel(tosca, vnfType); + + if (vnfcDependencyModel != null && !vnfcDependencyModel.getDependencies().isEmpty()) { + logger.debug(String.format("Dependency Model generated : %s ", vnfcDependencyModel.toString())); + List vnfcs = new ArrayList<>(); + + for (Node node : vnfcDependencyModel.getDependencies()) { + org.openecomp.appc.sdc.artifacts.object.Vnfc vnfc = new org.openecomp.appc.sdc.artifacts.object.Vnfc(); + vnfc.setVnfcType(node.getChild().getVnfcType()); + vnfc.setMandatory(node.getChild().isMandatory()); + vnfc.setResilienceType(node.getChild().getResilienceType()); + if (node.getParents() != null && !node.getParents().isEmpty()) { + List parents = new ArrayList<>(); + for (Vnfc parentNode : node.getParents()) { + parents.add(parentNode.getVnfcType()); + } + vnfc.setParents(parents); + } + vnfcs.add(vnfc); + } + ObjectMapper objectMapper = new ObjectMapper(); + + ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure + (MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true).writer().withRootName("vnfcs"); + try { + dependencyJson = writer.writeValueAsString(vnfcs); + } catch (JsonProcessingException e) { + logger.error("Error converting dependency model to JSON"); + throw new APPCException("Error converting dependency model to JSON",e); + } + } else { + logger.error("Error generating dependency model from tosca. Empty dependency model"); + throw new APPCException("Error generating dependency model from tosca. Empty dependency model"); + } + return dependencyJson; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java new file mode 100644 index 000000000..06bda8b2d --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java @@ -0,0 +1,196 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts.impl; + +import org.openecomp.appc.adapter.message.EventSender; +import org.openecomp.appc.adapter.message.MessageDestination; +import org.openecomp.appc.adapter.message.event.EventHeader; +import org.openecomp.appc.adapter.message.event.EventMessage; +import org.openecomp.appc.adapter.message.event.EventStatus; +import org.openecomp.appc.sdc.listener.Util; +import org.openecomp.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.openecomp.appc.sdc.artifacts.ArtifactProcessor; +import org.openecomp.appc.sdc.artifacts.helper.ArtifactStorageService; +import org.openecomp.appc.sdc.artifacts.object.SDCArtifact; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; +import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; +import org.openecomp.sdc.utils.DistributionActionResultEnum; +import org.openecomp.sdc.utils.DistributionStatusEnum; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * Provides abstrace implementation for SDC artifact processor + */ +public abstract class AbstractArtifactProcessor implements ArtifactProcessor { + + public static final String PAYLOAD_CHARSET = "UTF-8"; + private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm:ss"; + + protected IDistributionClient client; + protected EventSender eventSender; + + protected INotificationData notification; + protected IResourceInstance resource; + protected IArtifactInfo artifact; + protected URI storeUri; + + private final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractArtifactProcessor.class); + + protected ArtifactStorageService artifactStorageService; + + private AbstractArtifactProcessor(){ + artifactStorageService = new ArtifactStorageService(); + } + + AbstractArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource, + IArtifactInfo artifact, URI storeUri){ + + this(); + this.client = client; + this.eventSender = eventSender; + this.notification = notification; + this.resource = resource; + this.artifact = artifact; + this.storeUri = storeUri; + } + + @Override + public void run(){ + + try{ + logger.info(String.format("Attempting to download artifact %s", artifact)); + // Download artifact + IDistributionClientDownloadResult download = client.download(artifact); + + logger.info(String.format("Download of artifact %s completed with status %s", artifact.getArtifactUUID(), download)); + + // Notify of download status + if (download.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) { + client.sendDownloadStatus(Util.buildDistributionStatusMessage(client, notification, artifact, + DistributionStatusEnum.DOWNLOAD_ERROR), download.getDistributionMessageResult()); + sendDCAEEvent(notification.getDistributionID(), notification.getServiceName(), notification.getServiceVersion(), "Download is failed."); + return; + } + + client.sendDownloadStatus(Util.buildDistributionStatusMessage(client, notification, artifact, DistributionStatusEnum.DOWNLOAD_OK)); + + processArtifact(download); + + client.sendDeploymentStatus( + Util.buildDistributionStatusMessage(client, notification, this.artifact, DistributionStatusEnum.DEPLOY_OK)); + } + catch (Exception e){ + logger.error("Error processing artifact " + this.artifact.toString() ,e); + + client.sendDeploymentStatus(Util.buildDistributionStatusMessage(client, notification, artifact, + DistributionStatusEnum.DEPLOY_ERROR), e.getMessage()); + sendDCAEEvent(notification.getDistributionID(), notification.getServiceName(), notification.getServiceVersion(), e.getMessage()); + } + } + + + @Override + public void processArtifact(IDistributionClientDownloadResult download) throws APPCException { + String data = null; + if(logger.isDebugEnabled()){ + logger.debug("Entry processArtifact in AbstractArtifactProcessor"); + } + try { + if (download.getArtifactPayload() != null) { + data = new String(download.getArtifactPayload(), PAYLOAD_CHARSET); + } + } catch (UnsupportedEncodingException e) { + logger.error("Error reading artifact with " + PAYLOAD_CHARSET + " encoding" + new String(download.getArtifactPayload()) ,e); + throw new APPCException(e); + } + + SDCArtifact sdcArtifact = getArtifactObject(data); + logger.debug("Constructed SDCArtifact = " + sdcArtifact); + processArtifact(sdcArtifact); + + if(logger.isDebugEnabled()){ + logger.debug("Exit processArtifact in AbstractArtifactProcessor"); + } + } + + protected abstract void processArtifact(SDCArtifact artifact) throws APPCException; + + protected SDCArtifact getArtifactObject(String data){ + + SDCArtifact sdcArtifact = new SDCArtifact(); + + sdcArtifact.setArtifactUUID(this.artifact.getArtifactUUID()); + sdcArtifact.setArtifactName(this.artifact.getArtifactName()); + sdcArtifact.setArtifactType(this.artifact.getArtifactType()); + sdcArtifact.setArtifactVersion(this.artifact.getArtifactVersion()); + sdcArtifact.setArtifactDescription(this.artifact.getArtifactDescription()); + sdcArtifact.setArtifactContent(data); + sdcArtifact.setCreationDate(getCurrentDateTime()); + + sdcArtifact.setDistributionId(this.notification.getDistributionID()); + sdcArtifact.setServiceUUID(this.notification.getServiceUUID()); + sdcArtifact.setServiceName(this.notification.getServiceName()); + sdcArtifact.setServiceDescription(this.notification.getServiceDescription()); + + sdcArtifact.setResourceName(this.resource.getResourceName()); + sdcArtifact.setResourceType(this.resource.getResourceType()); + sdcArtifact.setResourceVersion(this.resource.getResourceVersion()); + sdcArtifact.setResourceUUID(this.resource.getResourceUUID()); + sdcArtifact.setResourceInstanceName(this.resource.getResourceInstanceName()); + + return sdcArtifact; + } + + protected String getCurrentDateTime() { + DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); + Date date = new Date(); + return dateFormat.format(date); + } + + private void sendDCAEEvent(String distributionID, String serviceName, String serviceVersion, String errorMessage) { + if (null == eventSender){ + return; + } + String errorDescription = String.format("SDC distribution of service '%s', version '%s' is failed with reason: '%s'", + serviceName, serviceVersion, errorMessage); + + EventMessage eventMessage = new EventMessage( + new EventHeader((new Date()).toString(), serviceVersion, distributionID), + new EventStatus(401, errorDescription)); + + eventSender.sendEvent(MessageDestination.DCAE, eventMessage); + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java new file mode 100644 index 000000000..3ad88b4b9 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.openecomp.appc.adapter.message.EventSender; +import org.openecomp.appc.sdc.artifacts.ArtifactProcessor; +import org.openecomp.appc.sdc.artifacts.object.ArtifactType; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; + +import java.net.URI; + +/** + * Factory class for creating instance of Artifact Processor + */ +public class ArtifactProcessorFactory { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ArtifactProcessorFactory.class); + + private ArtifactProcessorFactory (){ + + } + + /** + * Provides and instance of Artifact Processor + * @param client an instance of IDistributionClient + * @param eventSender an instance of EventSender + * @param notification an instance of INotificationData + * @param resource an instance of IResourceInstance + * @param artifact an instance of IArtifactInfo + * @param storeUri + * @return + */ + public static ArtifactProcessor getArtifactProcessor(IDistributionClient client, EventSender eventSender, + INotificationData notification, IResourceInstance resource, + IArtifactInfo artifact, URI storeUri) { + + logger.debug("Creating artifact processor for artifact type = " + artifact.getArtifactType()); + ArtifactType artifactType = ArtifactType.getArtifactType(artifact.getArtifactType()); + if(artifactType == null){ + return null; + } + ArtifactProcessor artifactProcessor = null; + switch (artifactType){ + case APPC_CONFIG : + artifactProcessor = new ConfigArtifactProcessor(client, eventSender, notification, resource, + artifact, storeUri); + break; + case VF_LICENSE: + artifactProcessor = new LicenseArtifactProcessor(client,eventSender,notification,resource, + artifact,storeUri); + break; + case TOSCA_CSAR: + artifactProcessor = new ToscaCsarArtifactProcessor(client,eventSender,notification,resource, + artifact,storeUri); + default: + break; + } + return artifactProcessor; + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java new file mode 100644 index 000000000..3baca3574 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts.impl; + +import org.openecomp.appc.adapter.message.EventSender; +import org.openecomp.appc.sdc.listener.ProviderOperations; +import org.openecomp.appc.sdc.listener.ProviderResponse; +import org.openecomp.appc.sdc.listener.Util; +import org.openecomp.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.openecomp.appc.sdc.artifacts.object.SDCArtifact; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; + +import java.net.MalformedURLException; +import java.net.URI; + +/** + * Artifact processor for config artifact type + */ +public class ConfigArtifactProcessor extends AbstractArtifactProcessor { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(ConfigArtifactProcessor.class); + + /** + * returns an instance of ConfigArtifactProcessor + * @param client an instance of IDistributionClient + * @param eventSender an instance of EventSender + * @param notification an instance of INotificationData + * @param resource an instance of IResourceInstance + * @param artifact an instance of IArtifactInfo + * @param storeUri an instance of URI + */ + public ConfigArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource, IArtifactInfo artifact, URI storeUri) { + super(client,eventSender,notification,resource,artifact,storeUri); + } + + @Override + public void processArtifact(SDCArtifact artifact) throws APPCException { + String postData = Util.toSdcStoreDocumentInput(notification, resource, super.artifact, artifact.getArtifactContent()); + try { + ProviderResponse result = ProviderOperations.post(storeUri.toURL(), postData, null); + if (result.getStatus() == 200) { + Util.parseResponse(result.getBody()); + } + } catch (MalformedURLException | APPCException e) { + logger.error("Error processing artifact : " + this.artifact.toString(),e); + throw new APPCException(e.getMessage(),e); + } + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java new file mode 100644 index 000000000..21b32dc8e --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts.impl; + +import org.openecomp.appc.adapter.message.EventSender; +import org.openecomp.appc.exceptions.APPCException; +import org.openecomp.appc.licmgr.Constants; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.commons.lang.StringUtils; +import org.openecomp.appc.sdc.artifacts.object.SDCArtifact; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; + +import java.net.URI; + +/** + * Artifact processor for VNF license artifact type + */ +public class LicenseArtifactProcessor extends AbstractArtifactProcessor { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(LicenseArtifactProcessor.class); + + /** + * returns an instance of ConfigArtifactProcessor + * @param client an instance of IDistributionClient + * @param eventSender an instance of EventSender + * @param notification an instance of INotificationData + * @param resource an instance of IResourceInstance + * @param artifact an instance of IArtifactInfo + * @param storeUri an instance of URI + */ + public LicenseArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource, IArtifactInfo artifact, URI storeUri) { + super(client,eventSender,notification,resource,artifact,storeUri); + } + + @Override + public void processArtifact(SDCArtifact artifact) throws APPCException { + + String vnfType = artifact.getResourceName(); + String version = artifact.getResourceVersion(); + String packageArtifactID = artifact.getArtifactUUID(); + + if (StringUtils.isEmpty(vnfType) || + StringUtils.isEmpty(version) || + StringUtils.isEmpty(packageArtifactID)) { + String errStr = String.format("Missing information in SDC request. Details: resource_type='%s', resource_version='%s', artifactID='%s'", vnfType, version, packageArtifactID); + logger.error(errStr); + throw new APPCException(errStr); + } + + try { + SDCArtifact existingArtifact = artifactStorageService.retrieveSDCArtifact(vnfType, version,artifact.getArtifactType()); + + if (existingArtifact ==null) { // new resource + logger.debug("Artifact not found from database for vnfType = " + vnfType + " , version = " + version + " , artifactType = " + artifact.getArtifactType()); + artifactStorageService.storeSDCArtifact(artifact); + } else { // duplicate + logger.debug("Artifact retrieved from database = " + existingArtifact); + logger.warn(String.format("Artifact of type '%s' already deployed for resource_type='%s' and resource_version='%s'", Constants.VF_LICENSE, vnfType, version)); + } + + } catch (Exception e) { + logger.error("Error processing artifact : " + artifact.toString(),e); + throw new APPCException(e.getMessage(),e); + } + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java new file mode 100644 index 000000000..ff3ee5509 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java @@ -0,0 +1,241 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import org.apache.commons.lang.StringUtils; +import org.openecomp.appc.adapter.message.EventSender; +import org.openecomp.appc.exceptions.APPCException; +import org.openecomp.appc.licmgr.Constants; +import org.openecomp.appc.sdc.artifacts.helper.DependencyModelGenerator; +import org.openecomp.appc.sdc.artifacts.object.Resource; +import org.openecomp.appc.sdc.artifacts.object.SDCArtifact; +import org.openecomp.appc.sdc.artifacts.object.SDCReference; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; +import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; + +import javax.json.Json; +import java.io.*; +import java.net.URI; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +public class ToscaCsarArtifactProcessor extends AbstractArtifactProcessor{ + + private final EELFLogger logger = EELFManager.getInstance().getLogger(ToscaCsarArtifactProcessor.class); + + private DependencyModelGenerator dependencyModelGenerator; + + public ToscaCsarArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource, + IArtifactInfo artifact, URI storeUri){ + super(client,eventSender,notification,resource,artifact,storeUri); + dependencyModelGenerator = new DependencyModelGenerator(); + } + + @Override + public void processArtifact(IDistributionClientDownloadResult download) throws APPCException { + logger.debug("processing artifact " + super.artifact.getArtifactType()); + byte[] byteArray = download.getArtifactPayload(); + String serviceFileName = ""; + String serviceTemplateContent = ""; + List resources = null; + Map csarFiles = new HashMap<>(); + try (ZipInputStream inputStream = new ZipInputStream(new ByteArrayInputStream(byteArray))) { + ZipEntry entry = inputStream.getNextEntry(); + logger.debug("First Entry = " +entry); + while(entry!= null){ + String filename = entry.getName(); + logger.debug("Next Entry = "+ filename); + + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + String str = null; + StringBuilder sb = new StringBuilder(); + while((str = bufferedReader.readLine()) != null){ + sb.append(new String(str)).append(System.getProperty("line.separator")); + } + csarFiles.put(filename,sb.toString()); + entry = inputStream.getNextEntry(); + } + + } catch (IOException e) { + logger.error("Error Reading TOSCA.meta from CSAR",e); + throw new APPCException(e); + } + serviceFileName = readServiceFileName(csarFiles.get("TOSCA-Metadata/TOSCA.meta")); + logger.debug("Service File Name = " + serviceFileName); + serviceTemplateContent = csarFiles.get(serviceFileName); + + try { + resources = readResources (serviceTemplateContent); + } catch (Exception e) { + logger.error("Error reading resources from " + ", serviceFileName = " + serviceFileName + + ", TOSCA Metadata = " + csarFiles.get("TOSCA-Metadata/TOSCA.meta"),e); + throw new APPCException(e); + } + + for(Resource resource:resources){ + String resourceTemplate = csarFiles.get("Definitions/resource-" + resource.getFileNameTag() + "-template.yml"); + SDCArtifact artifact = this.getArtifactObject(resource,resourceTemplate); + processArtifact(artifact); + } + } + + private String readServiceFileName(String toscaMetadata) { + toscaMetadata = toscaMetadata.substring(toscaMetadata.indexOf("Entry-Definitions"), toscaMetadata.indexOf(System.getProperty("line.separator"),toscaMetadata.indexOf("Entry-Definitions"))); + toscaMetadata =toscaMetadata.split(":")[1].trim(); + return toscaMetadata; + } + + protected SDCArtifact getArtifactObject(Resource resource, String data){ + + SDCArtifact sdcArtifact = new SDCArtifact(); + + sdcArtifact.setArtifactUUID(this.artifact.getArtifactUUID()); + sdcArtifact.setArtifactName(this.artifact.getArtifactName()); + sdcArtifact.setArtifactType(this.artifact.getArtifactType()); + sdcArtifact.setArtifactVersion(this.artifact.getArtifactVersion()); + sdcArtifact.setArtifactDescription(this.artifact.getArtifactDescription()); + sdcArtifact.setArtifactContent(data); + sdcArtifact.setCreationDate(super.getCurrentDateTime()); + + sdcArtifact.setDistributionId(this.notification.getDistributionID()); + sdcArtifact.setServiceUUID(this.notification.getServiceUUID()); + sdcArtifact.setServiceName(this.notification.getServiceName()); + sdcArtifact.setServiceDescription(this.notification.getServiceDescription()); + + sdcArtifact.setResourceName(resource.getName()); + sdcArtifact.setResourceType(resource.getType()); + sdcArtifact.setResourceVersion(resource.getVersion()); + sdcArtifact.setResourceUUID(resource.getUuid()); + sdcArtifact.setResourceInstanceName(resource.getInstanceName()); + + return sdcArtifact; + } + + private List readResources(String serviceTemplateContent) throws IOException { + List resources = new LinkedList<>(); + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + JsonNode root = mapper.readTree(serviceTemplateContent); + JsonNode topologyTemplate = root.get("topology_template"); + JsonNode nodeTemplates = topologyTemplate.get("node_templates"); + Iterator> itr = nodeTemplates.fields(); + while(itr.hasNext()){ + Map.Entry entry = itr.next(); + String instanceName = entry.getKey(); + JsonNode nodeTemplate = entry.getValue(); + + String fileNameTag = nodeTemplate.get("type").asText(); + logger.debug("Resource type in Service Template = " + fileNameTag); + fileNameTag = fileNameTag.substring(fileNameTag.lastIndexOf(".")+1,fileNameTag.length()); + String version = nodeTemplate.get("metadata").get("version").asText(); + String uuid = nodeTemplate.get("metadata").get("UUID").asText(); + String name = nodeTemplate.get("metadata").get("name").asText(); + String type = nodeTemplate.get("metadata").get("type").asText(); + + if(!"VF".equalsIgnoreCase(type)){ + continue; + } + + Resource resource = new Resource(); + resource.setFileNameTag(fileNameTag); + resource.setVersion(version); + resource.setUuid(uuid); + resource.setInstanceName(instanceName); + resource.setName(name); + resource.setType(type); + + resources.add(resource); + } + return resources; + } + + + @Override + protected void processArtifact(SDCArtifact artifact) throws APPCException { + String vnfType = artifact.getResourceName(); + String version = artifact.getResourceVersion(); + String packageArtifactID = artifact.getArtifactUUID(); + + if (StringUtils.isEmpty(vnfType) || + StringUtils.isEmpty(version) || + StringUtils.isEmpty(packageArtifactID)) { + String errStr = String.format("Missing information in SDC request. Details: resource_type='%s', resource_version='%s', artifactID='%s'", vnfType, version, packageArtifactID); + logger.error(errStr); + throw new APPCException(errStr); + } + try { + SDCReference reference = new SDCReference(); + reference.setVnfType(vnfType); + reference.setFileCategory("tosca_model"); + reference.setArtifactName(artifact.getArtifactName()); + logger.debug("Storing TOSCA to SDC Artifact"); + artifactStorageService.storeSDCArtifactWithReference(artifact,reference); + + SDCArtifact dependencyArtifact = getDependencyArtifact(artifact); + SDCReference dependencyReference = new SDCReference(); + dependencyReference.setVnfType(vnfType); + dependencyReference.setFileCategory("tosca_dependency_model"); + dependencyReference.setArtifactName(dependencyArtifact.getArtifactName()); + logger.debug("Storing Dependency to SDC Artifact"); + artifactStorageService.storeSDCArtifactWithReference(dependencyArtifact,dependencyReference); + } catch (Exception e) { + logger.error("Error processing artifact : " + artifact.toString() ); + throw new APPCException(e.getMessage(),e); + } + } + + private SDCArtifact getDependencyArtifact(SDCArtifact toscaArtifact) throws APPCException { + SDCArtifact artifact = new SDCArtifact(); + artifact.setArtifactName("dependency_"+toscaArtifact.getArtifactName()); + String dependencyModel = dependencyModelGenerator.getDependencyModel(toscaArtifact.getArtifactContent(),toscaArtifact.getResourceName()); + artifact.setArtifactContent(dependencyModel); + artifact.setArtifactType("DEPENDENCY_MODEL"); + + artifact.setArtifactUUID(toscaArtifact.getArtifactUUID()); + artifact.setArtifactVersion(toscaArtifact.getArtifactVersion()); + artifact.setArtifactDescription(toscaArtifact.getArtifactDescription()); + artifact.setCreationDate(super.getCurrentDateTime()); + artifact.setDistributionId(toscaArtifact.getDistributionId()); + artifact.setServiceUUID(toscaArtifact.getServiceUUID()); + artifact.setServiceName(toscaArtifact.getServiceName()); + artifact.setServiceDescription(toscaArtifact.getServiceDescription()); + artifact.setResourceName(toscaArtifact.getResourceName()); + artifact.setResourceType(toscaArtifact.getResourceType()); + artifact.setResourceVersion(toscaArtifact.getResourceVersion()); + artifact.setResourceUUID(toscaArtifact.getResourceUUID()); + artifact.setResourceInstanceName(toscaArtifact.getResourceInstanceName()); + return artifact; + } + + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/ArtifactType.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/ArtifactType.java new file mode 100644 index 000000000..1ff62385d --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/ArtifactType.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts.object; + +/** + * Enummration listing SDC artifact types + */ +public enum ArtifactType { + APPC_CONFIG,VF_LICENSE,TOSCA_CSAR; + + /** + * returns ArtifactType for the input string type + * @param artifactTypeStr + * @return + */ + public static ArtifactType getArtifactType(String artifactTypeStr){ + for(ArtifactType artifactType: ArtifactType.values()){ + if(artifactType.name().equals(artifactTypeStr)){ + return artifactType; + } + } + return null; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Resource.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Resource.java new file mode 100644 index 000000000..42716dc47 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Resource.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts.object; + +public class Resource { + private String name; + private String type; + private String version; + private String uuid; + private String instanceName; + private String fileNameTag; + + public Resource(){ + + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getInstanceName() { + return instanceName; + } + + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + + public String getFileNameTag() { + return fileNameTag; + } + + public void setFileNameTag(String fileNameTag) { + this.fileNameTag = fileNameTag; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCArtifact.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCArtifact.java new file mode 100644 index 000000000..6cba5b2a2 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCArtifact.java @@ -0,0 +1,215 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts.object; + +/** + * POJO containing metadata about SDC artifact + */ +public class SDCArtifact { + + private String artifactUUID; + + private String artifactName; + + private String artifactType; + + private String artifactVersion; + + private String artifactContent; + + private String artifactDescription; + + private String creationDate; + + private String distributionId; + + + + private String resourceUUID; + + private String resourceName; + + private String resourceType; + + private String resourceVersion; + + private String resourceInstanceName; + + + private String serviceUUID; + + private String serviceName; + + private String serviceDescription; + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getArtifactContent() { + return artifactContent; + } + + public void setArtifactContent(String artifactContent) { + this.artifactContent = artifactContent; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getCreationDate() { + return creationDate; + } + + public void setCreationDate(String creationDate) { + this.creationDate = creationDate; + } + + public String getDistributionId() { + return distributionId; + } + + public void setDistributionId(String distributionId) { + this.distributionId = distributionId; + } + + public String getResourceInstanceName() { + return resourceInstanceName; + } + + public void setResourceInstanceName(String resourceInstanceName) { + this.resourceInstanceName = resourceInstanceName; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public String getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(String resourceUUID) { + this.resourceUUID = resourceUUID; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public String getServiceDescription() { + return serviceDescription; + } + + public void setServiceDescription(String serviceDescription) { + this.serviceDescription = serviceDescription; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getServiceUUID() { + return serviceUUID; + } + + public void setServiceUUID(String serviceUUID) { + this.serviceUUID = serviceUUID; + } + + + @Override + public String toString() { + return "artifactUUID = " + artifactUUID + + " , artifactName = " + artifactName + + " , artifactType = " + artifactType + + " , artifactVersion = " + artifactVersion + + " , artifactContent = " + artifactContent + + " , artifactDescription = " + artifactDescription + + " , creationDate = " + creationDate + + " , distributionId = " +distributionId + + " , resourceUUID = " + resourceUUID + + " , resourceName = " + resourceName + + " , resourceType = " + resourceType + + " , resourceVersion = " + resourceVersion + + " , resourceInstanceName = " + resourceInstanceName + + " , serviceUUID = " + serviceUUID + + " , serviceName = " + serviceName + + " , serviceDescription = " + serviceDescription; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCReference.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCReference.java new file mode 100644 index 000000000..b9d630026 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCReference.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts.object; + +public class SDCReference { + + private String vnfType; + private String vnfcType; + private String fileCategory; + private String action; + private String artifactType; + private String artifactName; + + public String getVnfType() { + return vnfType; + } + + public void setVnfType(String vnfType) { + this.vnfType = vnfType; + } + + public String getVnfcType() { + return vnfcType; + } + + public void setVnfcType(String vnfcType) { + this.vnfcType = vnfcType; + } + + public String getFileCategory() { + return fileCategory; + } + + public void setFileCategory(String fileCategory) { + this.fileCategory = fileCategory; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + @Override + public String toString() { + return "vnfType = " + vnfType+ + ", vnfType = " + vnfType+ + ", fileCategory = " + fileCategory+ + ", action = " + action+ + ", artifactType = " + artifactType+ + ", artifactName = " + artifactName+ + ", vnfType = " + vnfType; + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Vnfc.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Vnfc.java new file mode 100644 index 000000000..47d5f4516 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Vnfc.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.artifacts.object; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import java.util.List; + +@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonPropertyOrder({"vnfc-type","mandatory","resilience","parents"}) +public class Vnfc { + + @JsonProperty("vnfc-type") + private String vnfcType; + @JsonProperty("mandatory") + private boolean mandatory; + @JsonProperty("resilience") + private String resilienceType; + @JsonProperty("parents") + private List parents; + + public String getVnfcType() { + return vnfcType; + } + + public void setVnfcType(String vnfcType) { + this.vnfcType = vnfcType; + } + public boolean isMandatory() { + return mandatory; + } + + public void setMandatory(boolean mandatory) { + this.mandatory = mandatory; + } + + public String getResilienceType() { + return resilienceType; + } + + public void setResilienceType(String resilienceType) { + this.resilienceType = resilienceType; + } + + public List getParents() { + return parents; + } + + public void setParents(List parents) { + this.parents = parents; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderOperations.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderOperations.java new file mode 100644 index 000000000..c644930e4 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderOperations.java @@ -0,0 +1,211 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.listener; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.Socket; +import java.net.URL; +import java.net.UnknownHostException; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Map; +import java.util.Map.Entry; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.HTTP; +import org.openecomp.appc.exceptions.APPCException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ProviderOperations { + + private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class); + + private static String basic_auth; + + public static ProviderResponse post(URL url, String json, Map adtl_headers) throws APPCException { + if (json == null) { + throw new APPCException("Provided message was null"); + } + + HttpPost post = null; + try { + post = new HttpPost(url.toExternalForm()); + post.setHeader("Content-Type", "application/json"); + post.setHeader("Accept", "application/json"); + + // Set Auth + if (basic_auth != null) { + post.setHeader("Authorization", "Basic " + basic_auth); + } + + if (adtl_headers != null) { + for (Entry header : adtl_headers.entrySet()) { + post.setHeader(header.getKey(), header.getValue()); + } + } + + StringEntity entity = new StringEntity(json); + entity.setContentType("application/json"); + post.setEntity(new StringEntity(json)); + } catch (UnsupportedEncodingException e) { + throw new APPCException(e); + } + + HttpClient client = getHttpClient(url); + + int httpCode = 0; + String respBody = null; + try { + HttpResponse response = client.execute(post); + httpCode = response.getStatusLine().getStatusCode(); + respBody = IOUtils.toString(response.getEntity().getContent()); + return new ProviderResponse(httpCode, respBody); + } catch (IOException e) { + throw new APPCException(e); + } + } + + /** + * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth + * to null + * + * @param user + * The user with optional domain name (for AAF) + * @param password + * The password for the user + * @return The new value of the basic auth string that will be used in the request headers + */ + public static String setAuthentication(String user, String password) { + if (user != null && password != null) { + String authStr = user + ":" + password; + basic_auth = new String(Base64.encodeBase64(authStr.getBytes())); + } else { + basic_auth = null; + } + return basic_auth; + } + + @SuppressWarnings("deprecation") + private static HttpClient getHttpClient(URL url) throws APPCException { + HttpClient client; + if (url.getProtocol().equals("https")) { + try { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); + sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); + + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + registry.register(new Scheme("https", sf, 443)); + registry.register(new Scheme("https", sf, 8443)); + registry.register(new Scheme("http", sf, 8181)); + + ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); + client = new DefaultHttpClient(ccm, params); + } catch (Exception e) { + client = new DefaultHttpClient(); + } + } else if (url.getProtocol().equals("http")) { + client = new DefaultHttpClient(); + } else { + throw new APPCException( + "The provider.topology.url property is invalid. The url did not start with http[s]"); + } + return client; + } + + @SuppressWarnings("deprecation") + public static class MySSLSocketFactory extends SSLSocketFactory { + private SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); + + public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, + KeyStoreException, UnrecoverableKeyException { + super(truststore); + + TrustManager tm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + + sslContext.init(null, new TrustManager[] { + tm + }, null); + } + + @Override + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) + throws IOException, UnknownHostException { + return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); + } + + @Override + public Socket createSocket() throws IOException { + return sslContext.getSocketFactory().createSocket(); + } + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderResponse.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderResponse.java new file mode 100644 index 000000000..cc21cea0c --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/ProviderResponse.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.listener; + +public class ProviderResponse { + + private int status; + private String body; + + public ProviderResponse(int status, String body) { + this.status = status; + this.body = body; + } + + public String getBody() { + return body; + } + + public int getStatus() { + return status; + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcCallback.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcCallback.java new file mode 100644 index 000000000..d721e13a0 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcCallback.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.listener; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.openecomp.appc.adapter.message.EventSender; +import org.openecomp.appc.sdc.artifacts.ArtifactProcessor; +import org.openecomp.appc.sdc.artifacts.impl.ArtifactProcessorFactory; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.consumer.INotificationCallback; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.openecomp.sdc.utils.DistributionStatusEnum; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +import java.net.URI; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +public class SdcCallback implements INotificationCallback { + + private final EELFLogger logger = EELFManager.getInstance().getLogger(SdcCallback.class); + + private URI storeUri; + private IDistributionClient client; + + private EventSender eventSender = null; + + private ThreadPoolExecutor executor; + private int threadCount = 10; + + private AtomicBoolean isRunning = new AtomicBoolean(false); + + + public SdcCallback(URI storeUri, IDistributionClient client) { + this.storeUri = storeUri; + this.client = client; + + // Create the thread pool + executor = new ThreadPoolExecutor(threadCount, threadCount, 1, TimeUnit.SECONDS, + new ArrayBlockingQueue(threadCount * 2)); + + // Custom Named thread factory + BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("Appc-Listener-%d").build(); + executor.setThreadFactory(threadFactory); + + isRunning.set(true); + } + + @Override + public void activateCallback(INotificationData data) { + if (null == eventSender) { + try { + BundleContext bctx = FrameworkUtil.getBundle(EventSender.class).getBundleContext(); + ServiceReference sref = bctx.getServiceReference(EventSender.class); + eventSender = (EventSender) bctx.getService(sref); + } catch (Throwable t) { + logger.error("SdcCallback failed on initializing EventSender", t); + } + } + + if (isRunning.get()) { + + for(IArtifactInfo artifact:data.getServiceArtifacts()){ + ArtifactProcessor artifactProcessor = ArtifactProcessorFactory.getArtifactProcessor(client, eventSender, data, null, artifact, storeUri); + if(artifactProcessor!=null){ + executor.submit(artifactProcessor); + } + } + + for (IResourceInstance resource : data.getResources()) { + for (IArtifactInfo artifact : resource.getArtifacts()) { + logger.info(Util.toSdcStoreDocumentInput(data, resource, artifact, "abc")); + if (executor.getQueue().size() >= threadCount) { + // log warning about job backlog + } + ArtifactProcessor artifactProcessor = ArtifactProcessorFactory.getArtifactProcessor(client, eventSender, data, resource, artifact, storeUri); + if(artifactProcessor != null){ + executor.submit(artifactProcessor); + } + else{ + /* Before refactoring of the DownloadAndStoreOp class, the approach was to download all the + artifacts, send the download status, and then perform the processing of artifact if it is + required. Now that we are downloading the artifacts only when its processing is required, + we are sending the download status as positive just to have the same behaviour as before + refactoring. + */ + client.sendDownloadStatus(Util.buildDistributionStatusMessage(client, data, artifact, DistributionStatusEnum.DOWNLOAD_OK)); + logger.error("Artifact type not supported : " + artifact.getArtifactType()); + } + } + } + } else { + // TODO - return a failed result so sdc knows we are shut down + } + } + + public void stop() { + stop(10); + } + + public void stop(int waitSec) { + isRunning.set(false); + logger.info(String.format("Stopping the SDC listener and waiting up to %ds for %d pending jobs", waitSec, + executor.getQueue().size())); + boolean cleanShutdown = false; + executor.shutdown(); + try { + cleanShutdown = executor.awaitTermination(waitSec, TimeUnit.SECONDS); + executor.shutdownNow(); // In case of timeout + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info(String.format("Attempting to shutdown cleanly: %s", cleanShutdown ? "SUCCESS" : "FAILURE")); + logger.info("Shutdown complete."); + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcConfig.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcConfig.java new file mode 100644 index 000000000..9c14d6756 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcConfig.java @@ -0,0 +1,197 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.listener; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.openecomp.sdc.api.consumer.IConfiguration; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +public class SdcConfig implements IConfiguration { + + private String host; + private String consumer; + private String consumerId; + private String env; + private String keystorePath; + private String keystorePass; + /** Polling internal is time between listening sessions */ + private int pollingInterval; + /** Polling timeout is the time to listen for (dmaap timeout url param)/1000 */ + private int pollingTimeout; + private List types = new ArrayList<>(); + private String user; + private String pass; + + private URI storeOp; + + private Properties props; + + private final EELFLogger logger = EELFManager.getInstance().getLogger(SdcConfig.class); + + SdcConfig(Properties props) throws Exception { + this.props = props; + init(); + } + + private void init() throws Exception { + if (props == null) { + logger.error("SdcConfig init is skipped due to properties is null"); + return; + } + + // Keystore for ca cert + keystorePath = props.getProperty("appc.sdc.keystore.path"); + keystorePass = props.getProperty("appc.sdc.keystore.pass"); + + // ASDC host + host = props.getProperty("appc.sdc.host"); + env = props.getProperty("appc.sdc.env"); + user = props.getProperty("appc.sdc.user"); + pass = props.getProperty("appc.sdc.pass"); + + // DMaaP properties + consumer = props.getProperty("appc.sdc.consumer"); + consumerId = props.getProperty("appc.sdc.consumer.id"); + + pollingInterval = Integer.valueOf(props.getProperty("interval", "60")); + + // Client uses cambriaClient-0.2.4 which throws non relevant (wrong) + // exceptions with times > 30s + pollingTimeout = Integer.valueOf(props.getProperty("timeout", "25")); + + // Anything less than 60 and we risk 429 Too Many Requests + if (pollingInterval < 60) { + pollingInterval = 60; + } + + if (pollingInterval > pollingTimeout) { + logger.warn(String.format( + "Message acknowledgement may be delayed by %ds in the ADSC listener. [Listening Time: %s, Poll Period: %s]", + pollingInterval - pollingTimeout, pollingTimeout, pollingInterval)); + } + + logParams(); + + // Download type + /* + This types seems redundant, as it looks from the code that they are not being used anywhere + */ + types.add("APPC_CONFIG"); + types.add("VF_LICENSE"); + types.add("TOSCA_CSAR"); + + storeOp = new URI(props.getProperty("appc.sdc.provider.url")); + } + + @Override + public boolean activateServerTLSAuth() { + return false; + } + + public boolean isFilterInEmptyResources() { + return false; + } + + @Override + public String getAsdcAddress() { + return host; + } + + @Override + public String getConsumerGroup() { + return consumer; + } + + @Override + public String getConsumerID() { + return consumerId; + } + + @Override + public String getEnvironmentName() { + return env; + } + + @Override + public String getKeyStorePassword() { + return keystorePass; + } + + @Override + public String getKeyStorePath() { + return keystorePath; + } + + @Override + public String getPassword() { + return pass; + } + + @Override + public int getPollingInterval() { + return pollingInterval; + } + + @Override + public int getPollingTimeout() { + return pollingTimeout; + } + + @Override + public List getRelevantArtifactTypes() { + return types; + } + + @Override + public String getUser() { + return user; + } + + URI getStoreOpURI() { + return storeOp; + } + + /** + * Logs the relevant parameters + */ + private void logParams() { + Map params = new HashMap<>(); + params.put("SDC Host", getAsdcAddress()); + params.put("SDC Environment", getEnvironmentName()); + params.put("Consumer Name", getConsumerGroup()); + params.put("Consumer ID", getConsumerID()); + params.put("Poll Active Wait", String.valueOf(getPollingInterval())); + params.put("Poll Timeout", String.valueOf(getPollingTimeout())); + + logger.info(String.format("SDC Params: %s", params)); + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcListener.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcListener.java new file mode 100644 index 000000000..dccc95841 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/SdcListener.java @@ -0,0 +1,219 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.listener; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.openecomp.appc.configuration.Configuration; +import org.openecomp.appc.configuration.ConfigurationFactory; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.results.IDistributionClientResult; +import org.openecomp.sdc.impl.DistributionClientFactory; +import org.openecomp.sdc.utils.DistributionActionResultEnum; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * SDC listener handles bundle start and stop through start and stop method.

+ * Register connection with SDC server based on properties file configuration when start, + * and disconnect with SDC server when stop. + */ +public class SdcListener { + private final EELFLogger logger = EELFManager.getInstance().getLogger(SdcListener.class); + + /** + * The bundle context + */ + private IDistributionClient client; + private SdcCallback callback; + private SdcConfig config; + private CountDownLatch latch; + + private Thread startThread = null; + + @SuppressWarnings("unused") + public void start() throws Exception { + // Add timestamp to the log to differentiate the jmeter run testing calls. + final long timeStamp = System.currentTimeMillis(); + logger.info(String.format("[%d] Starting SDC Listener", timeStamp)); + + Configuration configuration = ConfigurationFactory.getConfiguration(); + Properties props = configuration.getProperties(); + config = new SdcConfig(props); + logger.debug(String.format("[%d] created SDC config", timeStamp)); + + client = DistributionClientFactory.createDistributionClient(); + logger.debug(String.format("[%d] created SDC client", timeStamp)); + + callback = new SdcCallback(config.getStoreOpURI(), client); + logger.debug(String.format("[%d] created SDC callback", timeStamp)); + + latch = new CountDownLatch(1); + + startThread = new Thread(new StartRunnable(timeStamp)); + startThread.setName(String.format("[%d] sdcListener start", timeStamp)); + logger.debug(String.format("[%d] created SDC initialization thread", timeStamp)); + startThread.start(); + } + + @SuppressWarnings("unused") + public void stop() throws InterruptedException { + // Add timestamp to the log to differentiate the jmeter run testing calls. + final long timeStamp = System.currentTimeMillis(); + logger.info(String.format("[%d] Stopping SDC Listener", timeStamp)); + + stopStartThread(timeStamp); + + if (latch != null) { + logger.debug(String.format("[%d] waiting SDC latch count to 0 for 10 seconds", timeStamp)); + latch.await(10, TimeUnit.SECONDS); + latch = null; + } + + if (callback != null) { + logger.debug(String.format("[%d] stopping SDC callback", timeStamp)); + callback.stop(); + callback = null; + } + if (client != null) { + logger.debug(String.format("[%d] stopping SDC client", timeStamp)); + client.stop(); + client = null; + + } + logger.info(String.format("[%d] SDC Listener stopped successfully", timeStamp)); + } + + void stopStartThread(long timeStamp) throws InterruptedException { + if (startThread == null) { + return; + } + + if (startThread.getState() == Thread.State.TERMINATED) { + logger.debug(String.format("[%d] SDC thread(%s) is already terminated.", + timeStamp, startThread.getName())); + } else { + logger.debug(String.format("[%d] SDC thread(%s) is to be interrupted with state(%s)", + timeStamp, startThread.getName(), startThread.getState().toString())); + + startThread.interrupt(); + + logger.debug(String.format("[%d] SDC thread(%s) has been interrupted(%s) with state(%s)", + timeStamp, startThread.getName(), startThread.isInterrupted(), + startThread.getState().toString())); + } + startThread = null; + } + + /** + * Runnable implementation for actual initialization during SDC listener start + */ + class StartRunnable implements Runnable { + private final long timeStamp; + + StartRunnable(long theTimeStamp) { + timeStamp = theTimeStamp; + } + + /** + * This run method calls SDC client for init and start which are synchronized calls along with stop. + * To interrupt this thread at stop time, we added thread interrupted checking in each step + * for earlier interruption. + */ + @Override + public void run() { + if (!initialRegistration()) { + logger.warn(String.format("[%d] SDC thread initial registration failed.", timeStamp)); + } + + if (isThreadInterrupted("after initial registration")) { + return; + } + + IDistributionClientResult result = client.init(config, callback); + + if (isThreadInterrupted("after client init")) { + return; + } + + if (result.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) { + client.start(); + } else { + logger.error(String.format("[%d] Could not register SDC client. %s - %s", + timeStamp, result.getDistributionActionResult(), result.getDistributionMessageResult())); + } + + latch.countDown(); + } + + private boolean initialRegistration() { + try { + final String jsonTemplate = + "{\"consumerName\": \"%s\",\"consumerSalt\": \"%s\",\"consumerPassword\":\"%s\"}"; + String saltedPassStr = org.openecomp.tlv.sdc.security.Passwords.hashPassword(config.getPassword()); + if (saltedPassStr == null || !saltedPassStr.contains(":")) { + return false; + } + + String[] saltedPass = saltedPassStr.split(":"); + String json = String.format(jsonTemplate, config.getUser(), saltedPass[0], saltedPass[1]); + + Map headers = new HashMap<>(); + // TODO - Replace the header below to sdc's requirements. What should the new value be + headers.put("USER_ID", "test"); + + // TODO - How to format the url. Always same endpoint or ports? + String host = config.getAsdcAddress(); + URL url = new URL(String.format("http%s://%s/sdc2/rest/v1/consumers", + host.contains("443") ? "s" : "", host)); + + logger.info(String.format("Attempting to register user %s on %s with salted pass of %s", + config.getUser(), url, saltedPass[1])); + + ProviderOperations providerOperations = new ProviderOperations(); + ProviderResponse result = providerOperations.post(url, json, headers); + return result.getStatus() == 200; + } catch (Exception e) { + logger.error( + "Error performing initial registration with SDC server. User may not be able to connect", + e); + return false; + } + } + + private boolean isThreadInterrupted(String details) { + if (Thread.currentThread().isInterrupted()) { + logger.info(String.format("[%d] SDC thread interrupted %s.", timeStamp, details)); + return true; + } + return false; + } + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/Util.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/Util.java new file mode 100644 index 000000000..2dbb66e30 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/Util.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.listener; +import org.openecomp.sdc.utils.DistributionStatusEnum; + +import org.json.JSONException; +import org.json.JSONObject; +import org.openecomp.appc.exceptions.APPCException; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.consumer.IDistributionStatusMessage; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; +import org.openecomp.sdc.utils.DistributionStatusEnum; + +public class Util { + + // TODO - Use the yang builder instead + public static String toSdcStoreDocumentInput(INotificationData notification, IResourceInstance resource, + IArtifactInfo artifact, String data) { + JSONObject json = new JSONObject(); + + JSONObject requestInfo = new JSONObject(); + requestInfo.put("request-id", notification.getServiceUUID()); + requestInfo.put("request-action", "StoreSdcDocumentRequest"); + requestInfo.put("source", "SDC"); + + JSONObject docParams = new JSONObject(); + docParams.put("service-uuid", notification.getServiceUUID()); + docParams.put("distribution-id", notification.getDistributionID()); + docParams.put("service-name", notification.getServiceName()); + docParams.put("service-description", notification.getServiceDescription()); + docParams.put("service-artifacts", "[]"); + docParams.put("resource-uuid", resource.getResourceUUID()); + docParams.put("resource-instance-name", resource.getResourceInstanceName()); + docParams.put("resource-name", resource.getResourceName()); + docParams.put("resource-version", resource.getResourceVersion()); + docParams.put("resource-type", resource.getResourceType()); + docParams.put("artifact-uuid", artifact.getArtifactUUID()); + docParams.put("artifact-name", artifact.getArtifactName()); + docParams.put("artifact-type", artifact.getArtifactType()); + docParams.put("artifact-version", artifact.getArtifactVersion()); + docParams.put("artifact-description", artifact.getArtifactDescription()); + docParams.put("artifact-contents", data); + + json.put("request-information", requestInfo); + json.put("document-parameters", docParams); + + return String.format("{\"input\": %s}", json.toString()); + } + + public static boolean parseResponse(String input) throws APPCException { + JSONObject result, output, response; + try { + result = new JSONObject(input); + output = result.getJSONObject("output"); + response = output.getJSONObject("config-document-response"); + String id = response.getString("request-id"); + String status = response.getString("status"); + if (status.equals(DistributionStatusEnum.DEPLOY_OK.toString())) { + return true; + } else { + String error = response.optString("error-reason"); + String msg = error.isEmpty() ? "No Reason Provided" : error; + throw new APPCException(msg); + } + } catch (JSONException jse) { + throw new APPCException("Did not get valid json from provider.", jse); + } + } + + public static IDistributionStatusMessage buildDistributionStatusMessage(final IDistributionClient client, + final INotificationData data, final IArtifactInfo relevantArtifact, final DistributionStatusEnum status) { + IDistributionStatusMessage statusMessage = new IDistributionStatusMessage() { + + @Override + public long getTimestamp() { + long currentTimeMillis = System.currentTimeMillis(); + return currentTimeMillis; + } + + @Override + public DistributionStatusEnum getStatus() { + return status; + } + + @Override + public String getDistributionID() { + return data.getDistributionID(); + } + + @Override + public String getConsumerID() { + return client.getConfiguration().getConsumerID(); + } + + @Override + public String getArtifactURL() { + return relevantArtifact.getArtifactURL(); + } + }; + return statusMessage; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/tlv/sdc/security/Passwords.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/tlv/sdc/security/Passwords.java new file mode 100644 index 000000000..30b275a51 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/java/org/openecomp/tlv/sdc/security/Passwords.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.tlv.sdc.security; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Random; + +/** + * A copy from the org.openecomp.sdc:security-utils artifact that works with java 7. + */ +public class Passwords { + + private static final Random RANDOM = new SecureRandom(); + private static final int SALT = 0; + private static final int HASH = 1; + private static final String HASH_ALGORITHM = "SHA-256"; + + /** + * static utility class + */ + private Passwords() { + } + + /** + * the method calculates a hash with a generated salt for the given password + * + * @param password + * @return a "salt:hash" value + */ + public static String hashPassword(String password) { + byte[] salt = getNextSalt(); + byte byteData[] = hash(salt, password.getBytes()); + if (byteData != null) { + return toHex(salt) + ":" + toHex(byteData); + } + return null; + + } + + /** + * the method checks if the given password matches the calculated hash + * + * @param password + * @param expectedHash + * @return + */ + public static boolean isExpectedPassword(String password, String expectedHash) { + String[] params = expectedHash.split(":"); + return isExpectedPassword(password, params[SALT], params[HASH]); + } + + /** + * the method checks if the given password matches the calculated hash + * + * @param password + * @param salt + * @param hash + * the hash generated using the salt + * @return true if the password matched the hash + */ + public static boolean isExpectedPassword(String password, String salt, String hash) { + byte[] saltBytes = fromHex(salt); + byte[] hashBytes = fromHex(hash); + + byte byteData[] = hash(saltBytes, password.getBytes()); + if (byteData != null) { + return Arrays.equals(byteData, hashBytes); + } + return false; + } + + public static void main(String[] args) { + if (args.length > 1 || args.length > 0) { + System.out.println("[" + hashPassword(args[0]) + "]"); + } else { + System.out.println("no passward passed."); + } + + } + + /** + * Returns a random salt to be used to hash a password. + * + * @return a 16 bytes random salt + */ + private static byte[] getNextSalt() { + byte[] salt = new byte[16]; + RANDOM.nextBytes(salt); + return salt; + } + + /** + * hase's the salt and value using the chosen algorithm + * + * @param salt + * @param password + * @return an array of bytes resulting from the hash + */ + private static byte[] hash(byte[] salt, byte[] password) { + MessageDigest md; + byte[] byteData = null; + try { + md = MessageDigest.getInstance(HASH_ALGORITHM); + md.update(salt); + md.update(password); + byteData = md.digest(); + } catch (NoSuchAlgorithmException e) { + System.out.println("in vlide algorithem name"); + } + return byteData; + } + + /** + * Converts a string of hexadecimal characters into a byte array. + * + * @param hex + * the hex string + * @return the hex string decoded into a byte array + */ + private static byte[] fromHex(String hex) { + byte[] binary = new byte[hex.length() / 2]; + for (int i = 0; i < binary.length; i++) { + binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); + } + return binary; + } + + /** + * Converts a byte array into a hexadecimal string. + * + * @param array + * the byte array to convert + * @return a length*2 character string encoding the byte array + */ + private static String toHex(byte[] array) { + BigInteger bi = new BigInteger(1, array); + String hex = bi.toString(16); + int paddingLength = (array.length * 2) - hex.length(); + if (paddingLength > 0) + return String.format("%0" + paddingLength + "d", 0) + hex; + else + return hex; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 000000000..3f0eacc88 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/attsdc-packages.yaml b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/attsdc-packages.yaml new file mode 100644 index 000000000..8385dc988 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/attsdc-packages.yaml @@ -0,0 +1,10 @@ +packages: + - org.openecomp.tlv.sdc.ci.tests.execute.general + - org.openecomp.tlv.sdc.ci.tests.execute.user + - org.openecomp.tlv.sdc.ci.tests.execute.property + - org.openecomp.tlv.sdc.ci.tests.execute.lifecycle + - org.openecomp.tlv.sdc.ci.tests.execute.resource + - org.openecomp.tlv.sdc.ci.tests.execute.service + - org.openecomp.tlv.sdc.ci.tests.execute.artifacts + - org.openecomp.tlv.sdc.ci.tests.execute.imports + - org.openecomp.tlv.sdc.ci.tests.execute.category \ No newline at end of file diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/attsdc.yaml b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/attsdc.yaml new file mode 100644 index 000000000..7e612fe9b --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/attsdc.yaml @@ -0,0 +1,35 @@ +outputFolder: target +reportName: index.html +catalogBeHost: localhost +catalogFeHost: localhost +esHost: localhost +disributionClientHost: localhost +catalogFePort: 8181 +catalogBePort: 8080 +disributionClientPort: 8181 +esPort: 9200 +neoHost: localhost +neoPort: 7474 +neoDBusername: neo4j +neoDBpassword: 123456 + +resourceConfigDir: src/test/resources/CI/tests +componentsConfigDir: src/test/resources/CI/components +importResourceConfigDir: src/test/resources/CI/importResource +importResourceTestsConfigDir: src/test/resources/CI/importResourceTests +errorConfigurationFile: ../catalog-be/src/main/resources/config/error-configuration.yaml + +titanPropertiesFile: src/main/resources/ci/conf/titan.properties + +stopOnClassFailure: false + +#List of non-abstract resources to keep during titan cleanup between tests +#Only 1.0 version will be kept +resourcesNotToDelete: + - tosca.nodes.Compute + - tosca.nodes.Database + - tosca.nodes.ObjectStorage + - tosca.nodes.BlockStorage + - tosca.nodes.LoadBalancer + - org.openecomp.d2.resource.cp.Port + - org.openecomp.d2.resource.vl.Network \ No newline at end of file diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/log4j.properties b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/log4j.properties new file mode 100644 index 000000000..cc8c97a6a --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/log4j.properties @@ -0,0 +1,58 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# Define the root logger with appender file +log4j.rootLogger = DEBUG, FILE, stdout + +# Define the file appender +log4j.appender.FILE=org.apache.log4j.RollingFileAppender +log4j.appender.FILE.File=${targetlog}logs/ci-log.out + +# Define the layout for file appender +log4j.appender.FILE.layout=org.apache.log4j.PatternLayout +log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p [%10c] : %m%n + +# Set the maximum file size before rollover +log4j.appender.FILE.maxFileSize=5MB + +# Set the the backup index +log4j.appender.FILE.maxBackupIndex=10 + + +############################################################# + +# Direct log messages to stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +#log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %10c:%L - %m%n + +log4j.logger.org.apache.cassandra.service.StorageProxy=DEBUG +log4j.logger.com.thinkaurelius.titan.diskstorage.cassandra.CassandraTransaction=INFO, FILE, stdout + +log4j.logger.org.openecomp.tlv.sdc.ci.tests.utils=TRACE, FILE, stdout +log4j.additivity.org.openecomp.tlv.sdc.ci.tests.utils=false + + diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/titan.properties b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/titan.properties new file mode 100644 index 000000000..e4bcb4bea --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/conf/titan.properties @@ -0,0 +1,29 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +storage.backend=cassandra +storage.hostname=locahost +storage.port=9160 + +cache.db-cache = false diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/scripts/startTest.sh b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/scripts/startTest.sh new file mode 100644 index 000000000..28e81ca2b --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/ci/scripts/startTest.sh @@ -0,0 +1,112 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +#!/bin/bash + +function usage { + echo "Usage: $0 " +} + +function exitOnError() { + if [ $1 -ne 0 ] + then + echo "Failed running task $2" + exit 2 + fi +} + +if [ $# -lt 1 ] +then + usage + exit 2 +fi + +CURRENT_DIR=`pwd` +BASEDIR=$(dirname $0) + +if [ ${BASEDIR:0:1} = "/" ] +then + FULL_PATH=$BASEDIR +else + FULL_PATH=$CURRENT_DIR/$BASEDIR +fi + +LOGS_PROP_FILE=file:${FULL_PATH}/conf/log4j.properties +############################################# +TARGET_DIR=${FULL_PATH}/target +CONF_FILE=${FULL_PATH}/conf/attsdc.yaml +DEBUG=true +#MainClass=org.openecomp.tlv.sdc.ci.tests.run.StartTest +MainClass=org.openecomp.test.ClientTest + +JAR_FILE=$1 + +#TARGET_DIR=`echo ${TARGET_DIR} | sed 's/\//\//g'` +#echo $TARGET_DIR + +TESTS_DIR=/opt/app/sdc/ci/resources/tests +COMPONENTS_DIR=/opt/app/sdc/ci/resources/components + +#sed -i 's#\(outputFolder:\).*#\1 '${TARGET_DIR}'#g' $CONF_FILE +#sed -i 's#\(resourceConfigDir:\).*#\1 '${TESTS_DIR}'#g' $CONF_FILE +#sed -i 's#\(componentsConfigDir:\).*#\1 '${COMPONENTS_DIR}'#g' $CONF_FILE +TARGET_LOG_DIR="${TARGET_DIR}/" + +mkdir -p ${TARGET_DIR} +if [ -d ${TARGET_DIR} ] +then + rm -rf ${TARGET_DIR}/* + exitOnError $? "Failed_to_delete_target_dir" +fi + +debug_port=8800 +#JAVA_OPTION="-javaagent:/var/tmp/jacoco/lib/jacocoagent.jar=destfile=jacoco-it.exec" +JAVA_OPTION="" +case "$2" in + -debug) echo "Debug mode, Listen on port $debug_port"; JAVA_OPTION="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=${debug_port}" ;; + "") echo "Standard mode";; + *) echo "USAGE: startTest.sh [-debug]";; +esac + +cmd="java $JAVA_OPTION -DdisplayException=true -Dtargetlog=${TARGET_LOG_DIR} -Dconfig.resource=${CONF_FILE} -Ddebug=${DEBUG} -Dlog4j.configuration=${LOGS_PROP_FILE} -cp $JAR_FILE ${MainClass}" + +#echo $cmd +#console=`$cmd` + +if [ $DEBUG == "true" ] +then + $cmd +else + $cmd >> /dev/null +fi +status=`echo $?` + + + +echo "##################################################" +echo "################# status is ${status} #################" +echo "##################################################" + +exit $status + diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/org/openecomp/appc/default.properties b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/org/openecomp/appc/default.properties new file mode 100644 index 000000000..20cbbbcb0 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/main/resources/org/openecomp/appc/default.properties @@ -0,0 +1,40 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +org.openecomp.appc.bootstrap.file=appc.properties +org.openecomp.appc.bootstrap.path=/opt/openecomp/appc/data/properties,${user.home},. + +# These SDC properties were provided by the SDC Op-So team +appc.sdc.keystore.path=etc/sdc-client.jks +appc.sdc.keystore.pass=Aa123456 + +appc.sdc.host=192.168.1.2:8443 +appc.sdc.env=TEST +appc.sdc.user=appc +appc.sdc.pass=appc + +appc.sdc.consumer=TEST +appc.sdc.consumer.id=TEST +appc.sdc.provider.url=http://localhost:8181/restconf/operations/SdcMessage:configuration-document-request + diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcCallbackTest.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcCallbackTest.java new file mode 100644 index 000000000..9e2a86051 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcCallbackTest.java @@ -0,0 +1,192 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.listener; + +import org.junit.Before; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.appc.adapter.message.EventSender; +import org.openecomp.appc.sdc.artifacts.helper.ArtifactStorageService; +import org.openecomp.appc.sdc.artifacts.impl.ArtifactProcessorFactory; +import org.openecomp.appc.sdc.artifacts.impl.ToscaCsarArtifactProcessor; +import org.openecomp.appc.sdc.artifacts.object.SDCArtifact; +import org.openecomp.sdc.api.IDistributionClient; +import org.openecomp.sdc.api.consumer.IDistributionStatusMessage; +import org.openecomp.sdc.api.consumer.INotificationCallback; +import org.openecomp.sdc.api.notification.IArtifactInfo; +import org.openecomp.sdc.api.notification.INotificationData; +import org.openecomp.sdc.api.notification.IResourceInstance; +import org.openecomp.sdc.api.results.IDistributionClientDownloadResult; +import org.openecomp.sdc.impl.DistributionClientDownloadResultImpl; +import org.openecomp.sdc.utils.DistributionActionResultEnum; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.List; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({IDistributionClient.class, + EventSender.class, + ArtifactStorageService.class, + ToscaCsarArtifactProcessor.class, + ArtifactProcessorFactory.class}) +public class SdcCallbackTest { + + IDistributionClient client; + private EventSender eventSender; + private INotificationCallback sdcCallback; + private ArtifactStorageService storageService; + private ToscaCsarArtifactProcessor artifactProcessor; + + + @Before + public void setup() throws Exception { + client = PowerMockito.mock(IDistributionClient.class); + eventSender = PowerMockito.mock(EventSender.class); + sdcCallback = new SdcCallback(null,client); + + artifactProcessor = Mockito.spy(new ToscaCsarArtifactProcessor(client,eventSender,getNotificationData(),getResources().get(0) + ,getServiceArtifacts().get(0),null)); + storageService = PowerMockito.mock(ArtifactStorageService.class); + Whitebox.setInternalState(artifactProcessor,"artifactStorageService", storageService); + + PowerMockito.doCallRealMethod().when(artifactProcessor).processArtifact((IDistributionClientDownloadResult) Matchers.anyObject()); + PowerMockito.doCallRealMethod().when(artifactProcessor).run(); + + + PowerMockito.mockStatic(ArtifactProcessorFactory.class); + PowerMockito.when(ArtifactProcessorFactory.getArtifactProcessor((IDistributionClient)Matchers.anyObject(), (EventSender)Matchers.anyObject(), + (INotificationData)Matchers.anyObject(), (IResourceInstance)Matchers.anyObject(), + (IArtifactInfo)Matchers.anyObject(), (URI)Matchers.anyObject())).thenReturn(artifactProcessor); + + Whitebox.setInternalState(sdcCallback,"eventSender", eventSender); + PowerMockito.doReturn(readDownloadResult()).when(client).download((IArtifactInfo) Matchers.anyObject()); + PowerMockito.doReturn(null).when(client).sendDownloadStatus((IDistributionStatusMessage) Matchers.anyObject()); + + PowerMockito.doReturn(null).when(storageService).retrieveSDCArtifact(Matchers.anyString(),Matchers.anyString(),Matchers.anyString()); + + PowerMockito.doAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocationOnMock) throws Throwable { + System.out.print(invocationOnMock.getArguments()[0].toString()); + return null; + } + }).when(storageService).storeSDCArtifact((SDCArtifact)Matchers.anyObject()); + } + + private IDistributionClientDownloadResult readDownloadResult() throws IOException, URISyntaxException { + DistributionClientDownloadResultImpl downloadResult = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS,"Download success"); + File file = new File(this.getClass().getResource("/csar/service-ServiceAppc-csar.csar").toURI()); + + byte[] bFile = new byte[(int) file.length()]; + FileInputStream fileInputStream = new FileInputStream(file); + fileInputStream.read(bFile); + fileInputStream.close(); + + downloadResult.setArtifactPayload(bFile); + return downloadResult; + } + + +// @Test + public void testSDCListener() throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { + + + INotificationData notificationData = getNotificationData(); + sdcCallback.activateCallback(notificationData); + +// pause(); + } + +// private void pause(){ +// try { +// Thread.sleep(50000000); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } +// } + + private INotificationData getNotificationData() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { + + INotificationData notificationData = (INotificationData)getObject("org.openecomp.sdc.impl.NotificationDataImpl"); + + List serviceArtifacts = getServiceArtifacts(); + + invokeMethod(notificationData, "setServiceArtifacts", serviceArtifacts); + return notificationData; + } + + private List getResources() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException { + List resources = new ArrayList<>(); + IResourceInstance resource = (IResourceInstance)getObject("org.openecomp.sdc.impl.JsonContainerResourceInstance"); + + List serviceArtifacts = getServiceArtifacts(); + invokeMethod(resource,"setArtifacts",serviceArtifacts); + invokeMethod(resource,"setResourceName","Vnf"); + invokeMethod(resource,"setResourceVersion","1.0"); + + resources.add(resource); + return resources; + } + + private void invokeMethod(Object object, String methodName,Object... arguments) throws IllegalAccessException, InvocationTargetException { + Method[] methods = object.getClass().getDeclaredMethods(); + for(Method method:methods){ + if(methodName.equalsIgnoreCase(method.getName())){ + method.setAccessible(true); + method.invoke(object,arguments); + } + } + } + + private Object getObject(String fqcn) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { + Constructor constructor = Class.forName(fqcn).getDeclaredConstructors()[0]; + constructor.setAccessible(true); + return constructor.newInstance(); + } + + private List getServiceArtifacts() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException { + List serviceArtifacts = new ArrayList<>(); + IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.openecomp.sdc.impl.ArtifactInfoImpl"); + invokeMethod(artifactInfo,"setArtifactType","TOSCA_CSAR"); + invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl"); + serviceArtifacts.add(artifactInfo); + return serviceArtifacts; + } +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcListenerTest.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcListenerTest.java new file mode 100644 index 000000000..17e286bc5 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/SdcListenerTest.java @@ -0,0 +1,158 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ +package org.openecomp.appc.sdc.listener; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.openecomp.sdc.api.IDistributionClient; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(Thread.class) +public class SdcListenerTest { + private SdcListener sdcListener; + private EELFLogger mockLogger = mock(EELFLogger.class); + + @Before + public void setUp() throws Exception { + sdcListener = new SdcListener(); + + // to avoid operation on logger fail, mock up the logger + Whitebox.setInternalState(sdcListener, "logger", mockLogger); + } + + @Test + public void testStart() throws Exception { + sdcListener.start(); + Assert.assertTrue("Should created startThread", + Whitebox.getInternalState(sdcListener, "startThread") != null); + } + + @Test + public void testStop() throws Exception { + // test interrupt thread and other null case + MockThread mockThread = spy(new MockThread()); + mockThread.setNewState(Thread.State.TIMED_WAITING); + Whitebox.setInternalState(sdcListener, "startThread", mockThread); + + sdcListener.stop(); + Mockito.verify(mockThread, times(1)).interrupt(); + Assert.assertTrue("Should reset startThread", + Whitebox.getInternalState(sdcListener, "startThread") == null); + + // test other non-null case and thread null case + IDistributionClient mockClient = mock(IDistributionClient.class); + Whitebox.setInternalState(sdcListener, "client", mockClient); + SdcCallback mockCallback = mock(SdcCallback.class); + Whitebox.setInternalState(sdcListener, "callback", mockCallback); + CountDownLatch mockLatch = mock(CountDownLatch.class); + Whitebox.setInternalState(sdcListener, "latch", mockLatch); + + sdcListener.stop(); + + Mockito.verify(mockLatch, times(1)).await(10, TimeUnit.SECONDS); + Mockito.verify(mockCallback, times(1)).stop(); + Mockito.verify(mockClient, times(1)).stop(); + Assert.assertTrue("Should reset latch", + Whitebox.getInternalState(sdcListener, "latch") == null); + Assert.assertTrue("Should reset callback", + Whitebox.getInternalState(sdcListener, "callback") == null); + Assert.assertTrue("Should reset client", + Whitebox.getInternalState(sdcListener, "client") == null); + } + + @Test + public void testStopStartThread() throws Exception { + // null case + sdcListener.stopStartThread(123); + Mockito.verify(mockLogger, times(0)).debug(String.valueOf(any())); + + MockThread mockThread = spy(new MockThread()); + + // thread terminated case + Whitebox.setInternalState(sdcListener, "startThread", mockThread); + mockThread.setNewState(Thread.State.TERMINATED); + sdcListener.stopStartThread(123); + Mockito.verify(mockThread, times(0)).interrupt(); + Mockito.verify(mockLogger, times(1)).debug(String.valueOf(any())); + Assert.assertTrue("Should reset startThread", + Whitebox.getInternalState(sdcListener, "startThread") == null); + + // thread not termianted case + int timesCallThread = 0; + int timesCallLogger = 1; + for(Thread.State state : Thread.State.values()) { + if (state == Thread.State.TERMINATED) { + continue; + } + Whitebox.setInternalState(sdcListener, "startThread", mockThread); + mockThread.setNewState(state); + sdcListener.stopStartThread(123); + Mockito.verify(mockThread, times(++ timesCallThread)).interrupt(); + Mockito.verify(mockLogger, times(timesCallLogger += 2)).debug(String.valueOf(any())); + Assert.assertTrue("Should reset startThread", + Whitebox.getInternalState(sdcListener, "startThread") == null); + } + } + + /* + * I have used the following PowerMockito (due to Thread.getName() is a final method) + * try to mock up the thread behavior. But the mock Thread.getName() always returns null + * which works in intelliJ Junit test, but not Jenkins build: + * Thread mockThread = PowerMockito.mock(Thread.class); + * PowerMockito.doReturn(Thread.State.TERMINATED).when(mockThread).getState(); + * PowerMockito.doReturn("testing").when(mockThread).getName(); + * Hence, here goes the MockThread class to override Thread to my expected behavior. + */ + class MockThread extends Thread { + private State state; + + private MockThread() { + super.setName("testing"); + } + + void setNewState(State newState) { + state = newState; + } + + @Override + public State getState() { + return state; + } + } +} \ No newline at end of file diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/TestRun.java b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/TestRun.java new file mode 100644 index 000000000..84337e471 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/TestRun.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.sdc.listener; + +import org.junit.Test; + +public class TestRun { + + @Test + public void testRunning() throws Exception { + /* + AppcSdcListenerActivator a = new AppcSdcListenerActivator(); + a.start(null); + Thread.sleep(10000); + a.stop(null); + */ + } + +} diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/csar/service-ServiceAppc-csar.csar b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/csar/service-ServiceAppc-csar.csar new file mode 100644 index 000000000..a30ca2f6f Binary files /dev/null and b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/csar/service-ServiceAppc-csar.csar differ diff --git a/appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/org/openecomp/appc/default.properties b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/org/openecomp/appc/default.properties new file mode 100644 index 000000000..522e0ed72 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-bundle/src/test/resources/org/openecomp/appc/default.properties @@ -0,0 +1,36 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +# These ASDC properties were provided by the ASDC Op-So team +appc.sdc.keystore.path=etc/sdc-client.jks +appc.sdc.keystore.pass=Aa123456 + +appc.sdc.host=192.168.1.2:8443 +appc.sdc.env=TEST +appc.sdc.user=appc +appc.sdc.pass=appc + +appc.sdc.consumer=TEST +appc.sdc.consumer.id=TEST +appc.sdc.provider.url=http://localhost:8181/restconf/operations/SdcMessage:configuration-document-request diff --git a/appc-sdc-listener/appc-sdc-listener-features/.gitignore b/appc-sdc-listener/appc-sdc-listener-features/.gitignore new file mode 100644 index 000000000..2992ae832 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-features/.gitignore @@ -0,0 +1,3 @@ +/target/ +/bin/ +/.settings/ diff --git a/appc-sdc-listener/appc-sdc-listener-features/pom.xml b/appc-sdc-listener/appc-sdc-listener-features/pom.xml new file mode 100644 index 000000000..ff93b23bf --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-features/pom.xml @@ -0,0 +1,112 @@ + + + + 4.0.0 + + appc-sdc-listener + org.openecomp.appc + 1.1.0-SNAPSHOT + + appc-sdc-listener-features + Event Listener - Features + + jar + + + + org.openecomp.appc + appc-sdc-listener-bundle + ${project.version} + + + + commons-lang + commons-lang + compile + + + + org.opendaylight.mdsal + features-mdsal + features + xml + runtime + + + + org.opendaylight.yangtools + features-yangtools + features + xml + runtime + + + + + + + true + src/main/resources + + + + + org.apache.maven.plugins + maven-resources-plugin + + + filter + + resources + + generate-resources + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + attach-artifacts + + attach-artifact + + package + + + + ${project.build.directory}/classes/${features.file} + xml + features + + + + + + + + + diff --git a/appc-sdc-listener/appc-sdc-listener-features/src/main/resources/features.xml b/appc-sdc-listener/appc-sdc-listener-features/src/main/resources/features.xml new file mode 100644 index 000000000..409d31d53 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-features/src/main/resources/features.xml @@ -0,0 +1,41 @@ + + + + + + + + mvn:org.opendaylight.mdsal/features-mdsal/${odl.mdsal.features.version}/xml/features + + + + odl-mdsal-broker + mvn:org.openecomp.appc/appc-common/${project.version} + mvn:org.openecomp.appc/appc-sdc-listener-bundle/${project.version} + + + diff --git a/appc-sdc-listener/appc-sdc-listener-installer/.gitignore b/appc-sdc-listener/appc-sdc-listener-installer/.gitignore new file mode 100644 index 000000000..731eb433c --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-installer/.gitignore @@ -0,0 +1,2 @@ +/target/ +/.settings/ diff --git a/appc-sdc-listener/appc-sdc-listener-installer/pom.xml b/appc-sdc-listener/appc-sdc-listener-installer/pom.xml new file mode 100644 index 000000000..cc15ae14e --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-installer/pom.xml @@ -0,0 +1,156 @@ + + + + 4.0.0 + + appc-sdc-listener + org.openecomp.appc + 1.1.0-SNAPSHOT + + appc-sdc-listener-installer + SDC Listener - Karaf Installer + pom + + + appc-sdc-listener + appc-sdc-listener + mvn:org.openecomp.appc/appc-sdc-listener-features/${project.version}/xml/features + false + + + + + + org.openecomp.appc + appc-sdc-listener-features + ${project.version} + features + xml + + + * + * + + + + + + org.openecomp.appc + appc-sdc-listener-bundle + ${project.version} + + + + + + + maven-assembly-plugin + + + maven-repo-zip + + single + + package + + false + false + stage/${application.name}-${project.version} + + src/assembly/assemble_mvnrepo_zip.xml + + + + + installer-zip + + single + + package + + false + true + ${application.name}-${project.version} + + src/assembly/assemble_installer_zip.xml + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + + copy-dependencies + + prepare-package + + false + ${project.build.directory}/assembly/system + false + true + true + true + false + false + org.opendaylight + provided + + + + + + maven-resources-plugin + + + copy-version + + copy-resources + + + validate + + ${basedir}/target/stage + + + src/main/resources/scripts + + install-feature.sh + + true + + + + + + + + + + diff --git a/appc-sdc-listener/appc-sdc-listener-installer/src/assembly/assemble_installer_zip.xml b/appc-sdc-listener/appc-sdc-listener-installer/src/assembly/assemble_installer_zip.xml new file mode 100644 index 000000000..322fa76eb --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-installer/src/assembly/assemble_installer_zip.xml @@ -0,0 +1,62 @@ + + + + + + adapter + + zip + + + + false + + + + target/stage/ + ${application.name} + 755 + + *.sh + + + + target/stage/ + ${application.name} + 644 + + *.sh + + + + + + + diff --git a/appc-sdc-listener/appc-sdc-listener-installer/src/assembly/assemble_mvnrepo_zip.xml b/appc-sdc-listener/appc-sdc-listener-installer/src/assembly/assemble_mvnrepo_zip.xml new file mode 100644 index 000000000..615ee37d0 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-installer/src/assembly/assemble_mvnrepo_zip.xml @@ -0,0 +1,50 @@ + + + + + + adapter + + zip + + + + false + + + + target/assembly/ + . + + + + + + diff --git a/appc-sdc-listener/appc-sdc-listener-installer/src/main/resources/scripts/install-feature.sh b/appc-sdc-listener/appc-sdc-listener-installer/src/main/resources/scripts/install-feature.sh new file mode 100644 index 000000000..13d41ca56 --- /dev/null +++ b/appc-sdc-listener/appc-sdc-listener-installer/src/main/resources/scripts/install-feature.sh @@ -0,0 +1,63 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +#!/bin/bash + +ODL_HOME=${ODL_HOME:-/opt/opendaylight/current} +ODL_KARAF_CLIENT=${ODL_KARAF_CLIENT:-${ODL_HOME}/bin/client} +ODL_KARAF_CLIENT_OPTS=${ODL_KARAF_CLIENT_OPTS:-"-u karaf"} +INSTALLERDIR=$(dirname $0) + +REPOZIP=${INSTALLERDIR}/${features.boot}-${project.version}.zip + +if [ -f ${REPOZIP} ] +then + unzip -n -d ${ODL_HOME} ${REPOZIP} +else + echo "ERROR : repo zip ($REPOZIP) not found" + exit 1 +fi + +COUNT=0 +while [ $COUNT -lt 10 ]; do + ${ODL_KARAF_CLIENT} ${ODL_KARAF_CLIENT_OPTS} feature:repo-add ${features.repositories} 2> /tmp/installErr + cat /tmp/installErr + if grep -q 'Failed to get the session' /tmp/installErr; then + sleep 10 + else + let COUNT=10 + fi + let COUNT=COUNT+1 +done +COUNT=0 +while [ $COUNT -lt 10 ]; do + ${ODL_KARAF_CLIENT} ${ODL_KARAF_CLIENT_OPTS} feature:install ${features.boot} 2> /tmp/installErr + cat /tmp/installErr + if grep -q 'Failed to get the session' /tmp/installErr; then + sleep 10 + else + let COUNT=10 + fi + let COUNT=COUNT+1 +done diff --git a/appc-sdc-listener/appc-yang-generator/pom.xml b/appc-sdc-listener/appc-yang-generator/pom.xml new file mode 100644 index 000000000..abe531e35 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/pom.xml @@ -0,0 +1,97 @@ + + + + 4.0.0 + + appc-sdc-listener + org.openecomp.appc + 1.1.0-SNAPSHOT + + + appc-yang-generator + jar + + + UTF-8 + + + + + com.att.eelf + eelf-core + + + org.apache.velocity + velocity + 1.7 + + + org.opendaylight.yangtools + yang-parser-impl + ${odl.yangtools.version} + + + junit + junit + test + + + org.openecomp.sdc.common + openecomp-tosca-datatype + ${toscalib.version} + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + + + ${artifactId}-${version} + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + 1.8 + 1.8 + + + + + + \ No newline at end of file diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/YANGGenerator.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/YANGGenerator.java new file mode 100644 index 000000000..562c4abf2 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/YANGGenerator.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.yang; + +import org.openecomp.appc.yang.exception.YANGGenerationException; + +import java.io.OutputStream; + +/** + * The Interface YANGGenerator - provides method to generate YANG file from TOSCA. + */ +public interface YANGGenerator { + + /** + * Generate YANG from TOSCA. + * if any exceptional Type is coming in the input tosca as a part of configuration parameter property, YANGGenerationException will be thrown. + * This API is not supporting below mentioned built-in Types: + * bits, decimal64, enumeration, identityref, leafref, union + * + * @param uniqueID - Set as module name in the yang, mandatory, cannot be null or empty + * @param tosca - TOSCA String from which the YANG is to be generated, mandatory, cannot be null or empty + * @param stream - The outputStream to which the generated yang is written, mandatory, cannot be null + * @throws YANGGenerationException - Thrown when any error occurred during method execution, the origin can be found from ex.getCause() or ex.getMessage() + */ + + void generateYANG(String uniqueID, String tosca, OutputStream stream) throws YANGGenerationException; +} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/exception/YANGGenerationException.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/exception/YANGGenerationException.java new file mode 100644 index 000000000..a37d6f685 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/exception/YANGGenerationException.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.yang.exception; + +/** + * The Class YANGGenerationException. + */ +public class YANGGenerationException extends Exception { + + + /** + * Instantiates a new YANG generation exception. + * + * @param message - the appropriate message + * @param cause -the appropriate cause + */ + public YANGGenerationException(String message,Throwable cause){ + super(message,cause); + } + + + /** + * Instantiates new YANG generation exception + * @param message + */ + public YANGGenerationException(String message){ + super(message); + } +} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorFactory.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorFactory.java new file mode 100644 index 000000000..25d9b211a --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorFactory.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.yang.impl; + +import org.openecomp.appc.yang.YANGGenerator; + +/** + * A factory for creating YANGGenerator objects. + */ +public class YANGGeneratorFactory { + + private YANGGeneratorFactory(){} + + private static class InstanceHolder + { + private static YANGGeneratorImpl instance = new YANGGeneratorImpl(); + private InstanceHolder(){} + } + + /** + * Gets the YANG generator. + * + * @return the YANG generator + */ + public static YANGGenerator getYANGGenerator() + { + return InstanceHolder.instance; + } + +} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorImpl.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorImpl.java new file mode 100644 index 000000000..246563932 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorImpl.java @@ -0,0 +1,176 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.yang.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.commons.lang.StringUtils; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.exception.ParseErrorException; +import org.apache.velocity.exception.ResourceNotFoundException; +import org.apache.velocity.runtime.RuntimeConstants; +import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; +import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl; +import org.openecomp.appc.yang.YANGGenerator; +import org.openecomp.appc.yang.exception.YANGGenerationException; +import org.openecomp.appc.yang.objects.Leaf; +import org.openecomp.appc.yang.type.YangTypes; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.YamlUtil; + +import java.io.*; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +@SuppressWarnings("CheckStyle") +public class YANGGeneratorImpl implements YANGGenerator { + + private static final EELFLogger Log = EELFManager.getInstance().getLogger(YANGGeneratorImpl.class); + private static final String MODULE_TYPE = "moduleType"; + private static final String LEAVES = "leaves"; + + + /* (non-Javadoc) + * @see org.openecomp.appc.yang.YANGGenerator#generateYANG(java.lang.String, java.lang.String, java.io.OutputStream) + */ + @Override + public void generateYANG(String uniqueID, String tosca, OutputStream stream) + throws YANGGenerationException { + Log.info("Entered into generateYANG."); + Log.debug("Received Tosca:\n" + tosca +"\n Received uniqueID: "+uniqueID); + + validateInput(uniqueID, tosca, stream); + Map parsedToscaMap = parseTosca(tosca); + String moduleType =parsedToscaMap.get(MODULE_TYPE).toString(); + List leaves = (List) parsedToscaMap.get(LEAVES); + VelocityEngine ve = new VelocityEngine(); + ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); + ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); + ve.init(); + Template template; + + try { + template = ve.getTemplate("templates/YangTemplate.vm"); + } catch ( ResourceNotFoundException | ParseErrorException ex) { + Log.error("Error while retrieving YANG Template", ex); + throw new YANGGenerationException("Error while retrieving YANG Template",ex); + } + + VelocityContext vc = new VelocityContext(); + + vc.put("moduleName", uniqueID); + vc.put(MODULE_TYPE, moduleType); + vc.put(LEAVES, leaves); + + StringWriter sw = new StringWriter(); + template.merge(vc,sw); + Log.debug("generated YANG \n "+sw.toString()); + try { + String yang = sw.toString(); + validateYang(yang); + stream.write(yang.getBytes()); + stream.flush(); + } catch (IOException e) { + Log.error("Error while writing to outputstream", e); + throw new YANGGenerationException("Error writing to outputstream",e); + } finally { + try { + stream.close(); + } catch (IOException e) { + Log.error("Error while closing outputstream", e); + } + } + Log.info("exiting generateYANG method."); + } + + private void validateYang(String yang) throws YANGGenerationException { + + try(InputStream inputYangStream = new ByteArrayInputStream(yang.getBytes())){ + YangStatementSourceImpl statementSource = new YangStatementSourceImpl(inputYangStream); + if(statementSource.getYangAST()==null){ + throw new YANGGenerationException("Syntax Error in Generated YANG = " + yang); + } + } + catch(IOException e){ + Log.error("Error validating yang file "+ yang,e); + throw new YANGGenerationException("Invalid YANG generated",e); + } + } + + private Map parseTosca(String tosca) throws YANGGenerationException { + Log.info("Entered into parseTosca."); + ServiceTemplate serviceTemplate = new YamlUtil().yamlToObject(tosca, ServiceTemplate.class); + Map nodeTypeMap = serviceTemplate.getNode_types(); + String kind = nodeTypeMap.keySet().toArray(new String[0])[0]; + NodeType nodeType = nodeTypeMap.get(kind); + Map returnMap= new HashMap<>(); + Map propertyDefinitionFromTOSCA = nodeType.getProperties(); + returnMap.put(MODULE_TYPE, kind); + List leaves = new LinkedList<>(); + + for(Map.Entry entry: propertyDefinitionFromTOSCA.entrySet()){ + Leaf leaf = new Leaf(); + leaf.setName(entry.getKey()); + PropertyDefinition pd = entry.getValue(); + Map typeMap=YangTypes.getYangTypeMap(); + if (typeMap.containsKey(pd.getType())) { + String paramType = typeMap.get(pd.getType()); + leaf.setType(paramType); + leaf.setDescription(!StringUtils.isEmpty(pd.getDescription()) ? pd.getDescription() : ""); + leaf.setMandatory((pd.getRequired() != null) ? Boolean.toString(pd.getRequired()) : Boolean.toString(false)); + leaf.setDefaultValue((pd.get_default() != null) ? pd.get_default().toString(): ""); + leaves.add(leaf); + } else { + YANGGenerationException yangGenerationException = new YANGGenerationException(pd.getType() + " Type is not supported ", null); + Log.error(pd.getType() + " Type is not supported ", yangGenerationException); + throw yangGenerationException; + } + } + returnMap.put(LEAVES, leaves); + Log.info("exiting parseTosca method with return MAP "+returnMap); + return returnMap; + } + + private void validateInput(String uniqueID, String tosca, OutputStream stream) throws YANGGenerationException { + Log.info("Entered into validateInput."); + if(StringUtils.isEmpty(uniqueID)) { + throw new YANGGenerationException("uniqueID is mandatory, cannot be null or empty.",null); + } + if(StringUtils.isEmpty(tosca)) { + throw new YANGGenerationException("tosca is mandatory, cannot be null or empty.",null); + } + if(stream == null){ + throw new YANGGenerationException("stream is mandatory, cannot be null.",null); + } + Log.info("exiting validateInput method."); + } + +} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/objects/Leaf.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/objects/Leaf.java new file mode 100644 index 000000000..013e31475 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/objects/Leaf.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.yang.objects; + +public class Leaf { + private String name; + private String type; + private String description; + private String mandatory; + private String defaultValue; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public String getMandatory() { + return mandatory; + } + public void setMandatory(String mandatory) { + this.mandatory = mandatory; + } + public String getDefaultValue() { + return defaultValue; + } + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + @Override + public String toString() { + return "Leaf [name=" + name + ", type=" + type + ", description=" + description + ", mandatory=" + mandatory + + ", defaultValue=" + defaultValue + "]"; + } + + + +} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/type/YangTypes.java b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/type/YangTypes.java new file mode 100644 index 000000000..ca18c4311 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/type/YangTypes.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.yang.type; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class YangTypes { + + private static final Map yangTypeMap; + private YangTypes(){} + static { + Map typeMap = new HashMap<>(); + + /* standard Types */ + /* typeMap.put("bits","bits"); + typeMap.put("leafref","leafref"); + typeMap.put("decimal64","decimal64"); + typeMap.put("enumeration","enumeration"); + typeMap.put("identityref","identityref"); + typeMap.put("union","union");*/ + typeMap.put("binary","binary"); + typeMap.put("boolean","boolean"); + typeMap.put("empty","empty"); + typeMap.put("instance-identifier","instance-identifier"); + typeMap.put("int8","int8"); + typeMap.put("int16","int16"); + typeMap.put("int32","int32"); + typeMap.put("int64","int64"); + typeMap.put("string","string"); + typeMap.put("uint8","uint8"); + typeMap.put("uint16","uint16"); + typeMap.put("uint32","uint32"); + typeMap.put("uint64","uint64"); + + + /* ietf-yang-types */ + + typeMap.put("counter32","yang:counter32"); + typeMap.put("zero-based-counter32","yang:zero-based-counter32"); + typeMap.put("counter64","yang:counter64"); + typeMap.put("zero-based-counter64","yang:zero-based-counter64"); + typeMap.put("gauge32","yang:gauge32"); + typeMap.put("gauge64","yang:gauge64"); + typeMap.put("object-identifier","yang:object-identifier"); + typeMap.put("object-identifier-128","yang:object-identifier-128"); + typeMap.put("yang-identifier","yang:yang-identifier"); + typeMap.put("date-and-time","yang:date-and-time"); + typeMap.put("timeticks","yang:timeticks"); + typeMap.put("timestamp","yang:timestamp"); + typeMap.put("phys-address","yang:phys-address"); + typeMap.put("mac-address","yang:mac-address"); + typeMap.put("xpath1.0","yang:xpath1.0"); + typeMap.put("hex-string","yang:hex-string"); + typeMap.put("uuid","yang:uuid"); + typeMap.put("dotted-quad","yang:dotted-quad"); + + /* ietf-inet-types */ + + typeMap.put("ip-version","inet:ip-version"); + typeMap.put("dscp","inet:dscp"); + typeMap.put("ipv6-flow-label","inet:ipv6-flow-label"); + typeMap.put("port-number","inet:port-number"); + typeMap.put("as-number","inet:as-number"); + typeMap.put("ip-address","inet:ip-address"); + typeMap.put("ipv4-address","inet:ipv4-address"); + typeMap.put("ipv6-address","inet:ipv6-address"); + typeMap.put("ip-address-no-zone","inet:ip-address-no-zone"); + typeMap.put("ipv4-address-no-zone","inet:ipv4-address-no-zone"); + typeMap.put("ipv6-address-no-zone","inet:ipv6-address-no-zone"); + typeMap.put("ip-prefix","inet:ip-prefix"); + typeMap.put("ipv4-prefix","inet:ipv4-prefix"); + typeMap.put("ipv6-prefix","inet:ipv6-prefix"); + typeMap.put("domain-name","inet:domain-name"); + typeMap.put("host","inet:host"); + typeMap.put("uri","inet:uri"); + + yangTypeMap = Collections.unmodifiableMap(typeMap); + } + + public static Map getYangTypeMap(){ + return yangTypeMap; + } + +} diff --git a/appc-sdc-listener/appc-yang-generator/src/main/resources/templates/YangTemplate.vm b/appc-sdc-listener/appc-yang-generator/src/main/resources/templates/YangTemplate.vm new file mode 100644 index 000000000..ab608c5e1 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/main/resources/templates/YangTemplate.vm @@ -0,0 +1,47 @@ +module $moduleName { + yang-version 1; + namespace "org:openecomp:appc:vnf:$moduleName"; + prefix appc-vnf; + organization "Copyright 2017 AT&T Intellectual Property."; + + description + "$moduleType description"; + + revision "2017-01-01" { + description + "$moduleName Configuration"; + } + + import ietf-inet-types { + prefix inet; + } + + import ietf-yang-types { + prefix yang; + } + + grouping vnf-config-grp { + container vnf-config { + #foreach( $data in $leaves ) + leaf $data.getName() { + type $data.getType(); + description "$data.getDescription()"; + mandatory $data.getMandatory(); + default "$data.getDefaultValue()"; + } + #end +} + } + + container vnf-config-repo { + list vnf-config-list { + key "vnf-identifier"; + leaf vnf-identifier { + type string; + } + uses vnf-config-grp; + } + + } + +} diff --git a/appc-sdc-listener/appc-yang-generator/src/test/java/org/openecomp/appc/TestYANGGenerator.java b/appc-sdc-listener/appc-yang-generator/src/test/java/org/openecomp/appc/TestYANGGenerator.java new file mode 100644 index 000000000..a4487ac52 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/test/java/org/openecomp/appc/TestYANGGenerator.java @@ -0,0 +1,197 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc; + +import org.junit.*; +import org.junit.rules.TemporaryFolder; +import org.openecomp.appc.yang.YANGGenerator; +import org.openecomp.appc.yang.exception.YANGGenerationException; +import org.openecomp.appc.yang.impl.YANGGeneratorFactory; + +import java.io.*; + +/** + * The Class TestYANGGenerator - Junit Test Class for all related test cases. + */ +@Ignore +public class TestYANGGenerator { + + private YANGGenerator yangGenerator = YANGGeneratorFactory.getYANGGenerator(); + private static String tosca; + private static String toscaWithSyntaxError; + private static String expectedYang; + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + /** + * Run before test method. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Before + public void runBeforeTestMethod() throws IOException { + tosca= getFileContent("tosca/toscaFile.yml"); + toscaWithSyntaxError = getFileContent("tosca/toscaFileWithSyntaxError.yml"); + expectedYang = getFileContent("yang/expectedYang.yang"); + } + + /** + * Test YANG generator for success. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws YANGGenerationException the YANG generation exception + */ + @Test + public void TestYANGGeneratorForSuccess() throws IOException, YANGGenerationException { + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + Assert.assertNotNull(tosca); + Assert.assertFalse("tosca file is emply or blank", tosca.equals("")); + yangGenerator.generateYANG("ATD456", tosca, out); + out.flush(); + out.close(); + String generatedYang = getFileContent(tempFile); + Assert.assertEquals(expectedYang,generatedYang); + } + + @Test(expected = YANGGenerationException.class) + public void testYangGenerationForSyntaxError() throws IOException, YANGGenerationException { + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + yangGenerator.generateYANG("ATD456",toscaWithSyntaxError,out); + } + + + /** + * Test for Yang Generator which generates YANG that is not matching with expected YANG. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws YANGGenerationException - the YANG generation exception + */ + @Test + public void unmatchedYangGenerationTest() throws IOException, YANGGenerationException { + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + yangGenerator.generateYANG("112476", tosca, out); + out.flush(); + out.close(); + String generatedYang = getFileContent(tempFile); + Assert.assertNotSame(expectedYang, generatedYang); + + } + + /** + * Yang generation test for empty tosca input. + * + * @throws YANGGenerationException the YANG generation exception + */ + @Test(expected = YANGGenerationException.class) + public void YangGenerationTestForEmptyUniqueIDInput() throws IOException, YANGGenerationException { +// OutputStream out = new FileOutputStream(classLoader.getResource("yang/generatedYang.yang").getFile()); + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + yangGenerator.generateYANG("", tosca, out); + } + + /** + * Yang generation test for empty tosca input. + * + * @throws YANGGenerationException the YANG generation exception + */ + @Test(expected = YANGGenerationException.class) + public void YangGenerationTestForUnSupportedType() throws IOException, YANGGenerationException { + tosca= getFileContent("tosca/toscaFileWithUnsupportedTypes.yml"); + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + yangGenerator.generateYANG("", tosca, out); + } + + /** + * Yang generation test for empty tosca input. + * + * @throws YANGGenerationException the YANG generation exception + */ + @Test(expected = YANGGenerationException.class) + public void YangGenerationTestForEmptyToscaInput() throws IOException, YANGGenerationException { + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + yangGenerator.generateYANG("1111", "", out); + } + + /** + * YANG generation test with invalid method arguments. + * + * @throws YANGGenerationException the YANG generation exception + */ + @Test(expected = YANGGenerationException.class) + public void YANGGenerationTestWithInvalidMethodArguments() throws YANGGenerationException { + yangGenerator.generateYANG("112476", "ToscaSAMPLE", null); + } + + @Test(expected = YANGGenerationException.class) + public void YANGGenerationTestWithIOException() throws IOException, YANGGenerationException { + File tempFile = temporaryFolder.newFile("generatedYang.yang"); + OutputStream out = new FileOutputStream(tempFile); + out.flush(); + out.close(); + yangGenerator.generateYANG("1111", tosca, out); + } + + + private String getFileContent(String fileName) throws IOException + { + ClassLoader classLoader = new TestYANGGenerator().getClass().getClassLoader(); + InputStream is = new FileInputStream(classLoader.getResource(fileName).getFile()); + BufferedReader buf = new BufferedReader(new InputStreamReader(is)); + String line = buf.readLine(); + StringBuilder sb = new StringBuilder(); + + while (line != null) { + sb.append(line).append("\n"); + line = buf.readLine(); + } + String fileString = sb.toString(); + is.close(); + return fileString; + } + + private String getFileContent(File file) throws IOException + { + InputStream is = new FileInputStream(file); + BufferedReader buf = new BufferedReader(new InputStreamReader(is)); + String line = buf.readLine(); + StringBuilder sb = new StringBuilder(); + + while (line != null) { + sb.append(line).append("\n"); + line = buf.readLine(); + } + String fileString = sb.toString(); + is.close(); + return fileString; + } + +} diff --git a/appc-sdc-listener/appc-yang-generator/src/test/resources/tosca/toscaFile.yml b/appc-sdc-listener/appc-yang-generator/src/test/resources/tosca/toscaFile.yml new file mode 100644 index 000000000..0356678d1 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/test/resources/tosca/toscaFile.yml @@ -0,0 +1,319 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +node_types: + Property Definition: + derived_from: org.openecomp.genericvnf + version: V1 + description: '' + properties: + param1: + type: domain-name + description: param1 desc + required: true + default: param1 def val + status: SUPPORTED + param2: + type: ipv4-address-no-zone + description: param2 desc + required: true + default: param2 def val + status: SUPPORTED + param3: + type: instance-identifier + description: param3 desc + required: true + default: param3 def val + status: SUPPORTED + param4: + type: uuid + description: param4 desc + required: true + default: param4 def val + status: SUPPORTED + param5: + type: empty + description: param5 desc + required: true + default: param5 def val + status: SUPPORTED + param6: + type: object-identifier-128 + description: param6 desc + required: true + default: param6 def val + status: SUPPORTED + param7: + type: dscp + description: param7 desc + required: true + default: param7 def val + status: SUPPORTED + param8: + type: int64 + description: param8 desc + required: true + default: param8 def val + status: SUPPORTED + param9: + type: zero-based-counter64 + description: param9 desc + required: true + default: param9 def val + status: SUPPORTED + param10: + type: int8 + description: param10 desc + required: true + default: param10 def val + status: SUPPORTED + param11: + type: host + description: param11 desc + required: true + default: param11 def val + status: SUPPORTED + param12: + type: uint32 + description: param12 desc + required: true + default: param12 def val + status: SUPPORTED + param13: + type: timeticks + description: param13 desc + required: true + default: param13 def val + status: SUPPORTED + param15: + type: mac-address + description: param15 desc + required: true + default: param15 def val + status: SUPPORTED + param16: + type: as-number + description: param16 desc + required: true + default: param16 def val + status: SUPPORTED + param17: + type: counter64 + description: param17 desc + required: true + default: param17 def val + status: SUPPORTED + param19: + type: xpath1.0 + description: param19 desc + required: true + default: param19 def val + status: SUPPORTED + param20: + type: ip-version + description: param20 desc + required: true + default: param20 def val + status: SUPPORTED + param21: + type: port-number + description: param21 desc + required: true + default: param21 def val + status: SUPPORTED + param22: + type: int16 + description: param22 desc + required: true + default: param22 def val + status: SUPPORTED + param23: + type: ipv6-address-no-zone + description: param23 desc + required: true + default: param23 def val + status: SUPPORTED + param24: + type: hex-string + description: param24 desc + required: true + default: param24 def val + status: SUPPORTED + param26: + type: uint64 + description: param26 desc + required: true + default: param26 def val + status: SUPPORTED + param27: + type: uint8 + description: param27 desc + required: true + default: param27 def val + status: SUPPORTED + param28: + type: ipv4-prefix + description: param28 desc + required: true + default: param28 def val + status: SUPPORTED + param29: + type: ipv6-prefix + description: param29 desc + required: true + default: param29 def val + status: SUPPORTED + param30: + type: gauge64 + description: param30 desc + required: true + default: param30 def val + status: SUPPORTED + param31: + type: counter32 + description: param31 desc + required: true + default: param31 def val + status: SUPPORTED + param32: + type: string + description: param32 desc + required: true + default: param32 def val + status: SUPPORTED + param33: + type: object-identifier + description: param33 desc + required: true + default: param33 def val + status: SUPPORTED + param34: + type: ip-address-no-zone + description: param34 desc + required: true + default: param34 def val + status: SUPPORTED + param36: + type: gauge32 + description: param36 desc + required: true + default: param36 def val + status: SUPPORTED + param37: + type: ipv4-address + description: param37 desc + required: true + default: param37 def val + status: SUPPORTED + param38: + type: ip-prefix + description: param38 desc + required: true + default: param38 def val + status: SUPPORTED + param39: + type: uint16 + description: param39 desc + required: true + default: param39 def val + status: SUPPORTED + param40: + type: timestamp + description: param40 desc + required: true + default: param40 def val + status: SUPPORTED + param42: + type: dotted-quad + description: param42 desc + required: true + default: param42 def val + status: SUPPORTED + param43: + type: uri + description: param43 desc + required: true + default: param43 def val + status: SUPPORTED + param44: + type: ipv6-address + description: param44 desc + required: true + default: param44 def val + status: SUPPORTED + param45: + type: ipv6-flow-label + description: param45 desc + required: true + default: param45 def val + status: SUPPORTED + param46: + type: zero-based-counter32 + description: param46 desc + required: true + default: param46 def val + status: SUPPORTED + param47: + type: ip-address + description: param47 desc + required: true + default: param47 def val + status: SUPPORTED + param48: + type: boolean + description: param48 desc + required: true + default: param48 def val + status: SUPPORTED + param50: + type: yang-identifier + description: param50 desc + required: true + default: param50 def val + status: SUPPORTED + param51: + type: int32 + description: param51 desc + required: true + default: param51 def val + status: SUPPORTED + param52: + type: date-and-time + description: param52 desc + required: true + default: param52 def val + status: SUPPORTED + param53: + type: phys-address + description: param53 desc + required: true + default: param53 def val + status: SUPPORTED +topology_template: + node_templates: + Property Definition_Template: + type: Property Definition + properties: + param 1: param1 source + param 2: param2 source diff --git a/appc-sdc-listener/appc-yang-generator/src/test/resources/tosca/toscaFileWithSyntaxError.yml b/appc-sdc-listener/appc-yang-generator/src/test/resources/tosca/toscaFileWithSyntaxError.yml new file mode 100644 index 000000000..8ef1729a9 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/test/resources/tosca/toscaFileWithSyntaxError.yml @@ -0,0 +1,319 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +node_types: + Property Definition: + derived_from: org.openecomp.genericvnf + version: V1 + description: '' + properties: + param 1: + type: domain-name + description: param1 desc + required: true + default: param1 def val + status: SUPPORTED + param2: + type: ipv4-address-no-zone + description: param2 desc + required: true + default: param2 def val + status: SUPPORTED + param3: + type: instance-identifier + description: param3 desc + required: true + default: param3 def val + status: SUPPORTED + param4: + type: uuid + description: param4 desc + required: true + default: param4 def val + status: SUPPORTED + param5: + type: empty + description: param5 desc + required: true + default: param5 def val + status: SUPPORTED + param6: + type: object-identifier-128 + description: param6 desc + required: true + default: param6 def val + status: SUPPORTED + param7: + type: dscp + description: param7 desc + required: true + default: param7 def val + status: SUPPORTED + param8: + type: int64 + description: param8 desc + required: true + default: param8 def val + status: SUPPORTED + param9: + type: zero-based-counter64 + description: param9 desc + required: true + default: param9 def val + status: SUPPORTED + param10: + type: int8 + description: param10 desc + required: true + default: param10 def val + status: SUPPORTED + param11: + type: host + description: param11 desc + required: true + default: param11 def val + status: SUPPORTED + param12: + type: uint32 + description: param12 desc + required: true + default: param12 def val + status: SUPPORTED + param13: + type: timeticks + description: param13 desc + required: true + default: param13 def val + status: SUPPORTED + param15: + type: mac-address + description: param15 desc + required: true + default: param15 def val + status: SUPPORTED + param16: + type: as-number + description: param16 desc + required: true + default: param16 def val + status: SUPPORTED + param17: + type: counter64 + description: param17 desc + required: true + default: param17 def val + status: SUPPORTED + param19: + type: xpath1.0 + description: param19 desc + required: true + default: param19 def val + status: SUPPORTED + param20: + type: ip-version + description: param20 desc + required: true + default: param20 def val + status: SUPPORTED + param21: + type: port-number + description: param21 desc + required: true + default: param21 def val + status: SUPPORTED + param22: + type: int16 + description: param22 desc + required: true + default: param22 def val + status: SUPPORTED + param23: + type: ipv6-address-no-zone + description: param23 desc + required: true + default: param23 def val + status: SUPPORTED + param24: + type: hex-string + description: param24 desc + required: true + default: param24 def val + status: SUPPORTED + param26: + type: uint64 + description: param26 desc + required: true + default: param26 def val + status: SUPPORTED + param27: + type: uint8 + description: param27 desc + required: true + default: param27 def val + status: SUPPORTED + param28: + type: ipv4-prefix + description: param28 desc + required: true + default: param28 def val + status: SUPPORTED + param29: + type: ipv6-prefix + description: param29 desc + required: true + default: param29 def val + status: SUPPORTED + param30: + type: gauge64 + description: param30 desc + required: true + default: param30 def val + status: SUPPORTED + param31: + type: counter32 + description: param31 desc + required: true + default: param31 def val + status: SUPPORTED + param32: + type: string + description: param32 desc + required: true + default: param32 def val + status: SUPPORTED + param33: + type: object-identifier + description: param33 desc + required: true + default: param33 def val + status: SUPPORTED + param34: + type: ip-address-no-zone + description: param34 desc + required: true + default: param34 def val + status: SUPPORTED + param36: + type: gauge32 + description: param36 desc + required: true + default: param36 def val + status: SUPPORTED + param37: + type: ipv4-address + description: param37 desc + required: true + default: param37 def val + status: SUPPORTED + param38: + type: ip-prefix + description: param38 desc + required: true + default: param38 def val + status: SUPPORTED + param39: + type: uint16 + description: param39 desc + required: true + default: param39 def val + status: SUPPORTED + param40: + type: timestamp + description: param40 desc + required: true + default: param40 def val + status: SUPPORTED + param42: + type: dotted-quad + description: param42 desc + required: true + default: param42 def val + status: SUPPORTED + param43: + type: uri + description: param43 desc + required: true + default: param43 def val + status: SUPPORTED + param44: + type: ipv6-address + description: param44 desc + required: true + default: param44 def val + status: SUPPORTED + param45: + type: ipv6-flow-label + description: param45 desc + required: true + default: param45 def val + status: SUPPORTED + param46: + type: zero-based-counter32 + description: param46 desc + required: true + default: param46 def val + status: SUPPORTED + param47: + type: ip-address + description: param47 desc + required: true + default: param47 def val + status: SUPPORTED + param48: + type: boolean + description: param48 desc + required: true + default: param48 def val + status: SUPPORTED + param50: + type: yang-identifier + description: param50 desc + required: true + default: param50 def val + status: SUPPORTED + param51: + type: int32 + description: param51 desc + required: true + default: param51 def val + status: SUPPORTED + param52: + type: date-and-time + description: param52 desc + required: true + default: param52 def val + status: SUPPORTED + param53: + type: phys-address + description: param53 desc + required: true + default: param53 def val + status: SUPPORTED +topology_template: + node_templates: + Property Definition_Template: + type: Property Definition + properties: + param 1: param1 source + param 2: param2 source diff --git a/appc-sdc-listener/appc-yang-generator/src/test/resources/tosca/toscaFileWithUnsupportedTypes.yml b/appc-sdc-listener/appc-yang-generator/src/test/resources/tosca/toscaFileWithUnsupportedTypes.yml new file mode 100644 index 000000000..e2102e134 --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/test/resources/tosca/toscaFileWithUnsupportedTypes.yml @@ -0,0 +1,373 @@ +### +# ============LICENSE_START======================================================= +# ONAP : APPC +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Copyright (C) 2017 Amdocs +# ============================================================================= +# 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. +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# ============LICENSE_END========================================================= +### + +node_types: + Property Definition: + derived_from: org.openecomp.genericvnf + version: V1 + description: '' + properties: + param1: + type: domain-name + description: param1 desc + required: true + default: param1 def val + status: SUPPORTED + param2: + type: ipv4-address-no-zone + description: param2 desc + required: true + default: param2 def val + status: SUPPORTED + param3: + type: instance-identifier + description: param3 desc + required: true + default: param3 def val + status: SUPPORTED + param4: + type: uuid + description: param4 desc + required: true + default: param4 def val + status: SUPPORTED + param5: + type: empty + description: param5 desc + required: true + default: param5 def val + status: SUPPORTED + param6: + type: object-identifier-128 + description: param6 desc + required: true + default: param6 def val + status: SUPPORTED + param7: + type: dscp + description: param7 desc + required: true + default: param7 def val + status: SUPPORTED + param8: + type: int64 + description: param8 desc + required: true + default: param8 def val + status: SUPPORTED + param9: + type: zero-based-counter64 + description: param9 desc + required: true + default: param9 def val + status: SUPPORTED + param10: + type: int8 + description: param10 desc + required: true + default: param10 def val + status: SUPPORTED + param11: + type: host + description: param11 desc + required: true + default: param11 def val + status: SUPPORTED + param12: + type: uint32 + description: param12 desc + required: true + default: param12 def val + status: SUPPORTED + param13: + type: timeticks + description: param13 desc + required: true + default: param13 def val + status: SUPPORTED + param14: + type: enumeration + description: param14 desc + required: true + default: param14 def val + status: SUPPORTED + param15: + type: mac-address + description: param15 desc + required: true + default: param15 def val + status: SUPPORTED + param16: + type: as-number + description: param16 desc + required: true + default: param16 def val + status: SUPPORTED + param17: + type: counter64 + description: param17 desc + required: true + default: param17 def val + status: SUPPORTED + param18: + type: bits + description: param18 desc + required: true + default: param18 def val + status: SUPPORTED + param19: + type: xpath1.0 + description: param19 desc + required: true + default: param19 def val + status: SUPPORTED + param20: + type: ip-version + description: param20 desc + required: true + default: param20 def val + status: SUPPORTED + param21: + type: port-number + description: param21 desc + required: true + default: param21 def val + status: SUPPORTED + param22: + type: int16 + description: param22 desc + required: true + default: param22 def val + status: SUPPORTED + param23: + type: ipv6-address-no-zone + description: param23 desc + required: true + default: param23 def val + status: SUPPORTED + param24: + type: hex-string + description: param24 desc + required: true + default: param24 def val + status: SUPPORTED + param25: + type: decimal64 + description: param25 desc + required: true + default: param25 def val + status: SUPPORTED + param26: + type: uint64 + description: param26 desc + required: true + default: param26 def val + status: SUPPORTED + param27: + type: uint8 + description: param27 desc + required: true + default: param27 def val + status: SUPPORTED + param28: + type: ipv4-prefix + description: param28 desc + required: true + default: param28 def val + status: SUPPORTED + param29: + type: ipv6-prefix + description: param29 desc + required: true + default: param29 def val + status: SUPPORTED + param30: + type: gauge64 + description: param30 desc + required: true + default: param30 def val + status: SUPPORTED + param31: + type: counter32 + description: param31 desc + required: true + default: param31 def val + status: SUPPORTED + param32: + type: string + description: param32 desc + required: true + default: param32 def val + status: SUPPORTED + param33: + type: object-identifier + description: param33 desc + required: true + default: param33 def val + status: SUPPORTED + param34: + type: ip-address-no-zone + description: param34 desc + required: true + default: param34 def val + status: SUPPORTED + param35: + type: identityref + description: param35 desc + required: true + default: param35 def val + status: SUPPORTED + param36: + type: gauge32 + description: param36 desc + required: true + default: param36 def val + status: SUPPORTED + param37: + type: ipv4-address + description: param37 desc + required: true + default: param37 def val + status: SUPPORTED + param38: + type: ip-prefix + description: param38 desc + required: true + default: param38 def val + status: SUPPORTED + param39: + type: uint16 + description: param39 desc + required: true + default: param39 def val + status: SUPPORTED + param40: + type: timestamp + description: param40 desc + required: true + default: param40 def val + status: SUPPORTED + param41: + type: union + description: param41 desc + required: true + default: param41 def val + status: SUPPORTED + param42: + type: dotted-quad + description: param42 desc + required: true + default: param42 def val + status: SUPPORTED + param43: + type: uri + description: param43 desc + required: true + default: param43 def val + status: SUPPORTED + param44: + type: ipv6-address + description: param44 desc + required: true + default: param44 def val + status: SUPPORTED + param45: + type: ipv6-flow-label + description: param45 desc + required: true + default: param45 def val + status: SUPPORTED + param46: + type: zero-based-counter32 + description: param46 desc + required: true + default: param46 def val + status: SUPPORTED + param47: + type: ip-address + description: param47 desc + required: true + default: param47 def val + status: SUPPORTED + param48: + type: boolean + description: param48 desc + required: true + default: param48 def val + status: SUPPORTED + param49: + type: leafref + description: param49 desc + required: true + default: param49 def val + status: SUPPORTED + param50: + type: yang-identifier + description: param50 desc + required: true + default: param50 def val + status: SUPPORTED + param51: + type: int32 + description: param51 desc + required: true + default: param51 def val + status: SUPPORTED + param52: + type: date-and-time + description: param52 desc + required: true + default: param52 def val + status: SUPPORTED + param53: + type: phys-address + description: param53 desc + required: true + default: param53 def val + status: SUPPORTED + param54: + type: phys-add + description: param54 desc + required: true + default: param54 def val + status: SUPPORTED + param55: + type: null + description: param55 desc + required: true + default: param55 def val + status: SUPPORTED + param56: + type: + description: param56 desc + required: true + default: param56 def val + status: SUPPORTED +topology_template: + node_templates: + Property Definition_Template: + type: Property Definition + properties: + param 1: param1 source + param 2: param2 source diff --git a/appc-sdc-listener/appc-yang-generator/src/test/resources/yang/expectedYang.yang b/appc-sdc-listener/appc-yang-generator/src/test/resources/yang/expectedYang.yang new file mode 100644 index 000000000..29c89182b --- /dev/null +++ b/appc-sdc-listener/appc-yang-generator/src/test/resources/yang/expectedYang.yang @@ -0,0 +1,345 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +module ATD456 { + yang-version 1; + namespace "org:openecomp:appc:vnf:ATD456"; + prefix appc-vnf; + organization "Copyright 2017 AT&T Intellectual Property."; + + description + "Property Definition description"; + + revision "2017-01-01" { + description + "ATD456 Configuration"; + } + + import ietf-inet-types { + prefix inet; + } + + import ietf-yang-types { + prefix yang; + } + + grouping vnf-config-grp { + container vnf-config { + leaf param1 { + type inet:domain-name; + description "param1 desc"; + mandatory true; + default "param1 def val"; + } + leaf param2 { + type inet:ipv4-address-no-zone; + description "param2 desc"; + mandatory true; + default "param2 def val"; + } + leaf param3 { + type instance-identifier; + description "param3 desc"; + mandatory true; + default "param3 def val"; + } + leaf param4 { + type yang:uuid; + description "param4 desc"; + mandatory true; + default "param4 def val"; + } + leaf param5 { + type empty; + description "param5 desc"; + mandatory true; + default "param5 def val"; + } + leaf param6 { + type yang:object-identifier-128; + description "param6 desc"; + mandatory true; + default "param6 def val"; + } + leaf param7 { + type inet:dscp; + description "param7 desc"; + mandatory true; + default "param7 def val"; + } + leaf param8 { + type int64; + description "param8 desc"; + mandatory true; + default "param8 def val"; + } + leaf param9 { + type yang:zero-based-counter64; + description "param9 desc"; + mandatory true; + default "param9 def val"; + } + leaf param10 { + type int8; + description "param10 desc"; + mandatory true; + default "param10 def val"; + } + leaf param11 { + type inet:host; + description "param11 desc"; + mandatory true; + default "param11 def val"; + } + leaf param12 { + type uint32; + description "param12 desc"; + mandatory true; + default "param12 def val"; + } + leaf param13 { + type yang:timeticks; + description "param13 desc"; + mandatory true; + default "param13 def val"; + } + leaf param15 { + type yang:mac-address; + description "param15 desc"; + mandatory true; + default "param15 def val"; + } + leaf param16 { + type inet:as-number; + description "param16 desc"; + mandatory true; + default "param16 def val"; + } + leaf param17 { + type yang:counter64; + description "param17 desc"; + mandatory true; + default "param17 def val"; + } + leaf param19 { + type yang:xpath1.0; + description "param19 desc"; + mandatory true; + default "param19 def val"; + } + leaf param20 { + type inet:ip-version; + description "param20 desc"; + mandatory true; + default "param20 def val"; + } + leaf param21 { + type inet:port-number; + description "param21 desc"; + mandatory true; + default "param21 def val"; + } + leaf param22 { + type int16; + description "param22 desc"; + mandatory true; + default "param22 def val"; + } + leaf param23 { + type inet:ipv6-address-no-zone; + description "param23 desc"; + mandatory true; + default "param23 def val"; + } + leaf param24 { + type yang:hex-string; + description "param24 desc"; + mandatory true; + default "param24 def val"; + } + leaf param26 { + type uint64; + description "param26 desc"; + mandatory true; + default "param26 def val"; + } + leaf param27 { + type uint8; + description "param27 desc"; + mandatory true; + default "param27 def val"; + } + leaf param28 { + type inet:ipv4-prefix; + description "param28 desc"; + mandatory true; + default "param28 def val"; + } + leaf param29 { + type inet:ipv6-prefix; + description "param29 desc"; + mandatory true; + default "param29 def val"; + } + leaf param30 { + type yang:gauge64; + description "param30 desc"; + mandatory true; + default "param30 def val"; + } + leaf param31 { + type yang:counter32; + description "param31 desc"; + mandatory true; + default "param31 def val"; + } + leaf param32 { + type string; + description "param32 desc"; + mandatory true; + default "param32 def val"; + } + leaf param33 { + type yang:object-identifier; + description "param33 desc"; + mandatory true; + default "param33 def val"; + } + leaf param34 { + type inet:ip-address-no-zone; + description "param34 desc"; + mandatory true; + default "param34 def val"; + } + leaf param36 { + type yang:gauge32; + description "param36 desc"; + mandatory true; + default "param36 def val"; + } + leaf param37 { + type inet:ipv4-address; + description "param37 desc"; + mandatory true; + default "param37 def val"; + } + leaf param38 { + type inet:ip-prefix; + description "param38 desc"; + mandatory true; + default "param38 def val"; + } + leaf param39 { + type uint16; + description "param39 desc"; + mandatory true; + default "param39 def val"; + } + leaf param40 { + type yang:timestamp; + description "param40 desc"; + mandatory true; + default "param40 def val"; + } + leaf param42 { + type yang:dotted-quad; + description "param42 desc"; + mandatory true; + default "param42 def val"; + } + leaf param43 { + type inet:uri; + description "param43 desc"; + mandatory true; + default "param43 def val"; + } + leaf param44 { + type inet:ipv6-address; + description "param44 desc"; + mandatory true; + default "param44 def val"; + } + leaf param45 { + type inet:ipv6-flow-label; + description "param45 desc"; + mandatory true; + default "param45 def val"; + } + leaf param46 { + type yang:zero-based-counter32; + description "param46 desc"; + mandatory true; + default "param46 def val"; + } + leaf param47 { + type inet:ip-address; + description "param47 desc"; + mandatory true; + default "param47 def val"; + } + leaf param48 { + type boolean; + description "param48 desc"; + mandatory true; + default "param48 def val"; + } + leaf param50 { + type yang:yang-identifier; + description "param50 desc"; + mandatory true; + default "param50 def val"; + } + leaf param51 { + type int32; + description "param51 desc"; + mandatory true; + default "param51 def val"; + } + leaf param52 { + type yang:date-and-time; + description "param52 desc"; + mandatory true; + default "param52 def val"; + } + leaf param53 { + type yang:phys-address; + description "param53 desc"; + mandatory true; + default "param53 def val"; + } + } + } + + container vnf-config-repo { + list vnf-config-list { + key "vnf-identifier"; + leaf vnf-identifier { + type string; + } + uses vnf-config-grp; + } + + } + +} diff --git a/appc-sdc-listener/pom.xml b/appc-sdc-listener/pom.xml new file mode 100644 index 000000000..6a515faf6 --- /dev/null +++ b/appc-sdc-listener/pom.xml @@ -0,0 +1,129 @@ + + + + 4.0.0 + + org.openecomp.appc + appc + 1.1.0-SNAPSHOT + + + appc-sdc-listener + SDC Event Listener + Listener to read and write events from DMaaP (Cambria) or DMaaP. + pom + + + + + maven-javadoc-plugin + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.antlr + antlr4 + ${antlr.version} + + + org.antlr + antlr4-runtime + 4.3 + + + + + + + javadoc-no-fork + test-javadoc-no-fork + + + + aggregate + + aggregate + test-aggregate + + + + + + org.apache.maven.plugins + maven-jxr-plugin + 2.3 + + + aggregate + + aggregate + test-aggregate + + + + + + + maven-surefire-plugin + + + + org.apache.maven.plugins + maven-changelog-plugin + 2.3 + + + dual-report + + range + 30 + + + changelog + file-activity + + + + + + + org.codehaus.mojo + taglist-maven-plugin + 2.4 + + + + + + appc-yang-generator + appc-sdc-listener-bundle + appc-sdc-listener-features + appc-sdc-listener-installer + + \ No newline at end of file -- cgit 1.2.3-korg