Merging in bug fixes 43/6343/9
authorPatrick Brady <pb071s@att.com>
Fri, 28 Jul 2017 18:29:23 +0000 (11:29 -0700)
committerPatrick Brady <pb071s@att.com>
Wed, 2 Aug 2017 15:43:44 +0000 (15:43 +0000)
Change-Id: I85da90b9ba0d03149f42035a820c76ef0285e413
Signed-off-by: Patrick Brady <pb071s@att.com>
Issue: APPC-100

88 files changed:
appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/pom.xml
appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/openecomp/appc/adapter/chef/impl/ChefAdapterImpl.java
appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/CommonHttpClient.java
appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/main/java/org/openecomp/appc/adapter/messaging/dmaap/http/HttpDmaapProducerImpl.java
appc-adapters/appc-dmaap-adapter/appc-dmaap-adapter-bundle/src/test/resources/DCAEResponse.txt
appc-adapters/appc-dmaap-adapter/appc-message-adapter-factory/src/main/java/org/openecomp/appc/adapter/factory/DmaapMessageAdapterFactoryImpl.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/impl/ProviderAdapterImpl.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/openecomp/appc/adapter/iaas/provider/operation/impl/base/ProviderServerOperation.java
appc-adapters/appc-netconf-adapter/appc-netconf-adapter-bundle/pom.xml
appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/pom.xml
appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/adapter/restHealthcheck/impl/TestRestHealthcheckAdapterImpl.java [new file with mode: 0644]
appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-features/src/main/resources/features.xml
appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-installer/pom.xml
appc-asdc-listener/appc-asdc-listener-bundle/pom.xml
appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/ArtifactProcessor.java [new file with mode: 0644]
appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/ArtifactStorageService.java [new file with mode: 0644]
appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java [new file with mode: 0644]
appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java [new file with mode: 0644]
appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java [new file with mode: 0644]
appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java [new file with mode: 0644]
appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java [new file with mode: 0644]
appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/ArtifactType.java [new file with mode: 0644]
appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Resource.java [new file with mode: 0644]
appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCArtifact.java [new file with mode: 0644]
appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/AsdcCallback.java
appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/AsdcConfig.java
appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/DownloadAndStoreOp.java [deleted file]
appc-asdc-listener/appc-asdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/TestAsdcListener.java [new file with mode: 0644]
appc-asdc-listener/appc-asdc-listener-bundle/src/test/resources/csar/service-ServiceAppc-csar.csar [new file with mode: 0644]
appc-asdc-listener/appc-yang-generator/pom.xml
appc-asdc-listener/appc-yang-generator/src/main/java/org/openecomp/appc/yang/impl/YANGGeneratorImpl.java
appc-common/pom.xml
appc-common/src/main/java/org/openecomp/appc/CmdLine.java [new file with mode: 0644]
appc-common/src/main/java/org/openecomp/appc/i18n/Msg.java
appc-common/src/main/resources/org/openecomp/appc/i18n/MessageResources.properties
appc-common/src/main/resources/org/openecomp/appc/org.ops4j.pax.logging.cfg [moved from appc-provider/appc-provider-bundle/src/main/resources/org/openecomp/appc/org.ops4j.pax.logging.cfg with 98% similarity]
appc-common/src/test/resources/org/openecomp/appc/i18n/TestResources_de.properties
appc-dg-util/appc-dg-util-bundle/pom.xml
appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/AAIPluginImpl.java
appc-dg/appc-dg-shared/appc-dg-aai/src/main/java/org/openecomp/appc/dg/aai/impl/Constants.java
appc-dg/appc-dg-shared/appc-dg-common/pom.xml
appc-dg/appc-dg-shared/appc-dg-dependency-model/pom.xml
appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/dependencymanager/helper/DependencyModelParser.java
appc-dg/appc-dg-shared/appc-dg-dependency-model/src/main/java/org/openecomp/appc/dg/objects/VnfcDependencyModel.java
appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/Constants.java
appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/impl/MDSALStoreImpl.java
appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge [new file with mode: 0644]
appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperationRequestFormatter.java
appc-dg/appc-dg-shared/appc-dg-netconf/pom.xml
appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java [new file with mode: 0644]
appc-dg/appc-dg-shared/pom.xml
appc-dispatcher/appc-command-executor/appc-command-executor-api/src/main/java/org/openecomp/appc/executor/objects/LCMCommandStatus.java
appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandExecutorImpl.java
appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/CommandTaskFactory.java
appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/ExpiredMessageHandler.java
appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/java/org/openecomp/appc/executor/impl/LCMCommandTask.java
appc-dispatcher/appc-command-executor/appc-command-executor-core/src/main/resources/OSGI-INF/blueprint/blueprint.xml
appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/TestCommandExecutionTask.java
appc-dispatcher/appc-command-executor/appc-command-executor-core/src/test/java/org/openecomp/appc/executor/TestCommandExecutor.java
appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ActionLevel.java [new file with mode: 0644]
appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/RequestContext.java
appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/pom.xml
appc-dispatcher/appc-dispatcher-common/state-machine-lib/src/test/java/org/openecomp/appc/statemachine/TestStateMachine.java
appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/Constants.java
appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/LicenseDataAccessService.java
appc-dispatcher/appc-license-manager/appc-license-manager-api/src/main/java/org/openecomp/appc/licmgr/LicenseManager.java
appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/openecomp/appc/licmgr/impl/LicenseDataAccessServiceImpl.java
appc-dispatcher/appc-license-manager/appc-license-manager-core/src/main/java/org/openecomp/appc/licmgr/impl/LicenseManagerImpl.java
appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseManagerMock.java
appc-dispatcher/appc-license-manager/appc-license-manager-core/src/test/java/org/openecomp/appc/licmgr/LicenseServiceMock.java
appc-dispatcher/appc-lifecycle-management/appc-lifecycle-management-core/pom.xml
appc-dispatcher/appc-lifecycle-management/appc-lifecycle-management-core/src/main/java/org/openecomp/appc/lifecyclemanager/helper/MetadataReader.java
appc-dispatcher/appc-lifecycle-management/appc-lifecycle-management-core/src/main/java/org/openecomp/appc/lifecyclemanager/impl/LifecycleManagerImpl.java
appc-dispatcher/appc-lifecycle-management/appc-lifecycle-management-core/src/test/java/org/openecomp/appc/TestLifecycleManager.java
appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestHandlerImpl.java [new file with mode: 0644]
appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestValidatorImpl.java [new file with mode: 0644]
appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestHandlerImpl.java
appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestValidatorImpl.java
appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestHandlerImpl.java [new file with mode: 0644]
appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestValidatorImpl.java [new file with mode: 0644]
appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/resources/OSGI-INF/blueprint/blueprint.xml
appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/openecomp/appc/requesthandler/TestRequestHandler.java
appc-event-listener/appc-event-listener-bundle/src/main/java/org/openecomp/appc/listener/AppcEventListenerActivator.java
appc-event-listener/appc-event-listener-bundle/src/test/resources/IncomingMessage.txt [new file with mode: 0644]
appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/messageadapter/MessageAdapter.java
appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/AppcProviderLcm.java
appc-provider/appc-provider-bundle/src/main/java/org/openecomp/appc/provider/lcm/util/RequestInputBuilder.java
pom.xml

index 0fddd2b..0cb1c1d 100644 (file)
        <name>chef Adapter - bundle</name>
 
        <dependencies>
+       <dependency>
+                       <groupId>org.json</groupId>
+                       <artifactId>json</artifactId>
+                       <version>20160810</version>
+               </dependency>
                <dependency>
                        <groupId>org.json</groupId>
                        <artifactId>json</artifactId>
@@ -35,8 +40,6 @@
                        <version>4.4.4</version>
                </dependency>
 
-               <!--<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> 
-                       <version>4.5.1</version> </dependency> -->
                <dependency>
                        <groupId>org.bouncycastle</groupId>
                        <artifactId>bcpkix-jdk15on</artifactId>
                        <groupId>org.openecomp.appc</groupId>
                        <artifactId>appc-common</artifactId>
                        <version>${project.version}</version>
-                       <!-- <classifier>jar-with-dependencies</classifier> -->
-                       <scope>test</scope>
-               </dependency>
-               <dependency>
-                       <groupId>org.openecomp.appc</groupId>
-                       <artifactId>appc-common</artifactId>
-                       <version>${project.version}</version>
-
                </dependency>
                <dependency>
                        <groupId>javax</groupId>
                        <artifactId>jackson-jaxrs</artifactId>
                        <version>1.9.12</version>
                </dependency>
+
+               <dependency>
+                       <groupId>org.apache.httpcomponents</groupId>
+                       <artifactId>httpclient</artifactId>
+                       <version>4.5.1</version>
+               </dependency>
+
                <dependency>
                        <groupId>junit</groupId>
                        <artifactId>junit</artifactId>
                                                <Embed-Transitive>true</Embed-Transitive>
                                        </instructions>
 
-                                       <manifestLocation>${project.basedir}/src/main/resources/META-INF</manifestLocation>
+       <manifestLocation>${project.basedir}/src/main/resources/META-INF</manifestLocation> 
                                </configuration>
                        </plugin>
                </plugins>
index 9dc50e5..5326b66 100644 (file)
@@ -106,7 +106,7 @@ import org.json.JSONObject;
 public class ChefAdapterImpl implements ChefAdapter {
 
        // chef server Initialize variable
-       public String username = "";
+       public String clientName = "";
        public String clientPrivatekey = "";
        public String chefserver = "";
        public String serverAddress = "";
@@ -207,7 +207,7 @@ public class ChefAdapterImpl implements ChefAdapter {
                String message = null;
                if (privateKeyCheck()) {
                        // update the details of an environment on the Chef server.
-                       ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
+                       ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations);
                        ApiMethod am = cac.put("/environments/"+envName).body(env);
                        am.execute();
                        code = am.getReturnCode();
@@ -247,7 +247,7 @@ public class ChefAdapterImpl implements ChefAdapter {
                int code=200;
                String message = null;
                if (privateKeyCheck()) {
-                       ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
+                       ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations);
 
                        for(int i = 0; i < nodes.size(); i++){
                                String nodeName=nodes.get(i);
@@ -306,7 +306,7 @@ public class ChefAdapterImpl implements ChefAdapter {
 
                rc.isAlive();
                SvcLogicContext svcLogic = rc.getSvcLogicContext();
-               ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
+               ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations);
                ApiMethod am = cac.post(chefAction).body(pushRequest);
                
                am.execute();
@@ -342,7 +342,7 @@ public class ChefAdapterImpl implements ChefAdapter {
                        int code;
                        String message = null;
                        if (privateKeyCheck()) {
-                               ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
+                               ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations);
                                ApiMethod am = cac.get(chefAction);
                                am.execute();
                                code = am.getReturnCode();
@@ -393,16 +393,21 @@ public class ChefAdapterImpl implements ChefAdapter {
        }
 
 
+       
+       /**
+        * build node object
+        */
+
        @SuppressWarnings("nls")
        @Override
        public void nodeObejctBuilder(Map<String, String> params, SvcLogicContext ctx) {
                logger.info("nodeObejctBuilder");
-               String name = params.get("nodeobject.name");
-               String normal = params.get("nodeobject.normal");
-               String overrides = params.get("nodeobject.overrides");
-               String defaults = params.get("nodeobject.defaults");
-               String run_list = params.get("nodeobject.run_list");
-               String chef_environment = params.get("nodeobject.chef_environment");
+               String name = params.get("org.openecomp.appc.instance.nodeobject.name");
+               String normal = params.get("org.openecomp.appc.instance.nodeobject.normal");
+               String overrides = params.get("org.openecomp.appc.instance.nodeobject.overrides");
+               String defaults = params.get("org.openecomp.appc.instance.nodeobject.defaults");
+               String run_list = params.get("org.openecomp.appc.instance.nodeobject.run_list");
+               String chef_environment = params.get("org.openecomp.appc.instance.nodeobject.chef_environment");
                String nodeObject = "{\"json_class\":\"Chef::Node\",\"default\":{" + defaults
                                + "},\"chef_type\":\"node\",\"run_list\":[" + run_list + "],\"override\":{" + overrides
                                + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\""
@@ -412,17 +417,20 @@ public class ChefAdapterImpl implements ChefAdapter {
                RequestContext rc = new RequestContext(ctx);
                rc.isAlive();
                SvcLogicContext svcLogic = rc.getSvcLogicContext();
-               svcLogic.setAttribute("chef.nodeObject", nodeObject);
+               svcLogic.setAttribute("org.openecomp.appc.chef.nodeObject", nodeObject);
 
        }
 
+       /**
+        * Nicolas send get request to chef server
+        */
 
        public void chefInfo(Map<String, String> params) {
-               username = params.get("username");
-               serverAddress = params.get("serverAddress");
-               organizations = params.get("organizations");
+               clientName = params.get("org.openecomp.appc.instance.username");
+               serverAddress = params.get("org.openecomp.appc.instance.serverAddress");
+               organizations = params.get("org.openecomp.appc.instance.organizations");
                chefserver = "https://" + serverAddress + "/organizations/" + organizations;
-               clientPrivatekey = "/opt/app/bvc/chef/" + serverAddress + "/" + organizations + "/" + username + ".pem";
+               clientPrivatekey = "/opt/app/bvc/chef/" + serverAddress + "/" + organizations + "/" + clientName + ".pem";
        }
 
        public Boolean privateKeyCheck() {
@@ -438,9 +446,9 @@ public class ChefAdapterImpl implements ChefAdapter {
        @Override
        public void retrieveData(Map<String, String> params, SvcLogicContext ctx) {
                String contextData = "someValue";
-               String allConfigData = params.get("allConfig");
-               String key = params.get("key");
-               String dgContext = params.get("dgContext");
+               String allConfigData = params.get("org.openecomp.appc.instance.allConfig");
+               String key = params.get("org.openecomp.appc.instance.key");
+               String dgContext = params.get("org.openecomp.appc.instance.dgContext");
                JSONObject josnConfig = new JSONObject(allConfigData);
                try {
                        contextData = josnConfig.getString(key);
@@ -462,28 +470,33 @@ public class ChefAdapterImpl implements ChefAdapter {
        @Override
        public void combineStrings(Map<String, String> params, SvcLogicContext ctx) {
 
-               String String1 = params.get("String1");
-               String String2 = params.get("String2");
-               String dgContext = params.get("dgContext");
+               String String1 = params.get("org.openecomp.appc.instance.String1");
+               String String2 = params.get("org.openecomp.appc.instance.String2");
+               String dgContext = params.get("org.openecomp.appc.instance.dgContext");
                String contextData = String1 + String2;
                RequestContext rc = new RequestContext(ctx);
                rc.isAlive();
                SvcLogicContext svcLogic = rc.getSvcLogicContext();
                svcLogic.setAttribute(dgContext, contextData);
        }
+       
+       
+       /**
+        * Send GET request to chef server
+        */
 
        @SuppressWarnings("nls")
        @Override
        public void chefGet(Map<String, String> params, SvcLogicContext ctx) {
                logger.info("chef get method");
                chefInfo(params);
-               String chefAction = params.get("chefAction");
+               String chefAction = params.get("org.openecomp.appc.instance.chefAction");
                RequestContext rc = new RequestContext(ctx);
                rc.isAlive();
                int code;
                String message = null;
                if (privateKeyCheck()) {
-                       ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
+                       ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations);
                        ApiMethod am = cac.get(chefAction);
                        am.execute();
                        code = am.getReturnCode();
@@ -505,14 +518,14 @@ public class ChefAdapterImpl implements ChefAdapter {
        @Override
        public void chefPut(Map<String, String> params, SvcLogicContext ctx) {
                chefInfo(params);
-               String chefAction = params.get("chefAction");
-               String CHEF_NODE_STR = params.get("chefRequestBody");
+               String chefAction = params.get("org.openecomp.appc.instance.chefAction");
+               String CHEF_NODE_STR = params.get("org.openecomp.appc.instance.chefRequestBody");
                RequestContext rc = new RequestContext(ctx);
                rc.isAlive();
                int code;
                String message = null;
                if (privateKeyCheck()) {
-                       ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
+                       ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations);
 
                        ApiMethod am = cac.put(chefAction).body(CHEF_NODE_STR);
                        am.execute();
@@ -525,10 +538,11 @@ public class ChefAdapterImpl implements ChefAdapter {
                }
                logger.info(code + "   " + message);
                chefServerResult(rc, Integer.toString(code), message);
-       }
 
+       }
+       
        /**
-        *   send Post request to chef server
+        * Nicolas send Post request to chef server
         */
 
        @SuppressWarnings("nls")
@@ -536,15 +550,25 @@ public class ChefAdapterImpl implements ChefAdapter {
        public void chefPost(Map<String, String> params, SvcLogicContext ctx) {
                chefInfo(params);
                logger.info("chef Post method");
-               logger.info(username + " " + clientPrivatekey + " " + chefserver + " " + organizations);
-               String CHEF_NODE_STR = params.get("chefRequestBody");
-               String chefAction = params.get("chefAction");
+               logger.info(clientName + " " + clientPrivatekey + " " + chefserver + " " + organizations);
+               String CHEF_NODE_STR = params.get("org.openecomp.appc.instance.chefRequestBody");
+               String chefAction = params.get("org.openecomp.appc.instance.chefAction");
+
+               // attributes="\"reconfig-test\":{\"secret\":\"newpass2\"}";
+               // String CHEF_NODE_STR =
+               // "{\"json_class\":\"Chef::Node\",\"default\":{},\"chef_type\":\"node\",\"run_list\":[\""+runList+"\"],\"override\":{},\"automatic\":{},\"normal\":{"+attributes+"},\"name\":\"testnode\",\"chef_environment\":\"_default\"}";
+               // String CHEF_NODE_STR = "{\"json_class\":\"Chef::Node\"}";
+               // logger.info(vm_url);
                RequestContext rc = new RequestContext(ctx);
                rc.isAlive();
                int code;
                String message = null;
+               // should load pem from somewhere else
                if (privateKeyCheck()) {
-                       ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
+                       ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations);
+
+                       // need pass path into it
+                       // "/nodes/testnode"
                        ApiMethod am = cac.post(chefAction).body(CHEF_NODE_STR);
                        am.execute();
                        code = am.getReturnCode();
@@ -558,19 +582,22 @@ public class ChefAdapterImpl implements ChefAdapter {
                chefServerResult(rc, Integer.toString(code), message);
        }
 
+       /**
+        * Nicolas send delete request to chef server
+        */
 
        @SuppressWarnings("nls")
        @Override
        public void chefDelete(Map<String, String> params, SvcLogicContext ctx) {
                logger.info("chef delete method");
                chefInfo(params);
-               String chefAction = params.get("chefAction");
+               String chefAction = params.get("org.openecomp.appc.instance.chefAction");
                RequestContext rc = new RequestContext(ctx);
                rc.isAlive();
                int code;
                String message = null;
                if (privateKeyCheck()) {
-                       ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
+                       ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations);
                        ApiMethod am = cac.delete(chefAction);
                        am.execute();
                        code = am.getReturnCode();
@@ -583,6 +610,10 @@ public class ChefAdapterImpl implements ChefAdapter {
                logger.info(code + "   " + message);
                chefServerResult(rc, Integer.toString(code), message);
        }
+       
+       
+
+
 
 
        @SuppressWarnings("nls")
@@ -608,13 +639,16 @@ public class ChefAdapterImpl implements ChefAdapter {
                }
        }
 
+
+
+
        @SuppressWarnings("nls")
        @Override
        public void checkPushJob(Map<String, String> params, SvcLogicContext ctx) {
                chefInfo(params);
-               String jobID = params.get("jobid");
-               int retryTimes = Integer.parseInt(params.get("retryTimes"));
-               int retryInterval = Integer.parseInt(params.get("retryInterval"));
+               String jobID = params.get("org.openecomp.appc.instance.jobid");
+               int retryTimes = Integer.parseInt(params.get("org.openecomp.appc.instance.retryTimes"));
+               int retryInterval = Integer.parseInt(params.get("org.openecomp.appc.instance.retryInterval"));
                String chefAction = "/pushy/jobs/" + jobID;
 
                RequestContext rc = new RequestContext(ctx);
@@ -628,7 +662,7 @@ public class ChefAdapterImpl implements ChefAdapter {
                        } catch (InterruptedException ex) {
                                Thread.currentThread().interrupt();
                        }
-                       ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
+                       ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations);
                        ApiMethod am = cac.get(chefAction);
                        am.execute();
                        int code = am.getReturnCode();
@@ -642,15 +676,15 @@ public class ChefAdapterImpl implements ChefAdapter {
 
                }
                if (status.equals("complete")) {
-                       svcLogic.setAttribute("chefServerResult.code", "200");
-                       svcLogic.setAttribute("chefServerResult.message", message);
+                       svcLogic.setAttribute("org.openecomp.appc.chefServerResult.code", "200");
+                       svcLogic.setAttribute("org.openecomp.appc.chefServerResult.message", message);
                } else {
                        if (status.equals("running")) {
-                               svcLogic.setAttribute("chefServerResult.code", "202");
-                               svcLogic.setAttribute("chefServerResult.message", "chef client runtime out");
+                               svcLogic.setAttribute("org.openecomp.appc.chefServerResult.code", "202");
+                               svcLogic.setAttribute("org.openecomp.appc.chefServerResult.message", "chef client runtime out");
                        } else {
-                               svcLogic.setAttribute("chefServerResult.code", "500");
-                               svcLogic.setAttribute("chefServerResult.message", message);
+                               svcLogic.setAttribute("org.openecomp.appc.chefServerResult.code", "500");
+                               svcLogic.setAttribute("org.openecomp.appc.chefServerResult.message", message);
                        }
                }
        }
@@ -660,12 +694,12 @@ public class ChefAdapterImpl implements ChefAdapter {
        @Override
        public void pushJob(Map<String, String> params, SvcLogicContext ctx) {
                chefInfo(params);
-               String pushRequest = params.get("pushRequest");
+               String pushRequest = params.get("org.openecomp.appc.instance.pushRequest");
                String chefAction = "/pushy/jobs";
                RequestContext rc = new RequestContext(ctx);
                rc.isAlive();
                SvcLogicContext svcLogic = rc.getSvcLogicContext();
-               ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
+               ChefApiClient cac = new ChefApiClient(clientName, clientPrivatekey, chefserver, organizations);
                ApiMethod am = cac.post(chefAction).body(pushRequest);
                ;
                am.execute();
@@ -675,13 +709,12 @@ public class ChefAdapterImpl implements ChefAdapter {
                        int startIndex = message.indexOf("jobs") + 6;
                        int endIndex = message.length() - 2;
                        String jobID = message.substring(startIndex, endIndex);
-                       svcLogic.setAttribute("jobID", jobID);
+                       svcLogic.setAttribute("org.openecomp.appc.jobID", jobID);
                        logger.info(jobID);
                }
                chefServerResult(rc, Integer.toString(code), message);
        }
 
-
        @SuppressWarnings("static-method")
        private void doFailure(RequestContext rc, int code, String message) {
                SvcLogicContext svcLogic = rc.getSvcLogicContext();
index a2e1579..ed2f13f 100644 (file)
@@ -50,19 +50,23 @@ public class CommonHttpClient {
     }
 
     public HttpGet getReq(URI uri, int timeoutMs) throws Exception {
-       HttpGet out = (uri == null) ? new HttpGet() : new HttpGet(uri);
-        if (AUTH_STR != null) {
-               out.setHeader("Authorization", String.format("Basic %s", AUTH_STR));
-        }       
+        if (AUTH_STR == null) {
+            throw new Exception("All DMaaP requests require authentication and none was provided.");
+        }
+
+        HttpGet out = (uri == null) ? new HttpGet() : new HttpGet(uri);
+        out.setHeader("Authorization", String.format("Basic %s", AUTH_STR));
         out.setConfig(getConfig(timeoutMs));
         return out;
     }
 
     public HttpPost postReq(String url) throws Exception {
-       HttpPost out = (url == null) ? new HttpPost() : new HttpPost(url);
-        if (AUTH_STR != null) {
-               out.setHeader("Authorization", String.format("Basic %s", AUTH_STR));
+        if (AUTH_STR == null) {
+            throw new Exception("All DMaaP requests require authentication and none was provided.");
         }
+
+        HttpPost out = (url == null) ? new HttpPost() : new HttpPost(url);
+        out.setHeader("Authorization", String.format("Basic %s", AUTH_STR));
         out.setConfig(getConfig(0));
         return out;
     }
index 1073e15..aeb248c 100644 (file)
@@ -119,7 +119,7 @@ public class HttpDmaapProducerImpl extends CommonHttpClient implements Producer
     }
 
     /**
-     * Format the body for the application/cambria content type with no partitioning.
+     * Format the body for the application/cambria content type with no partitioning. See
      *
      * @param msg
      *            The message body to format
index 0d7ea2a..884a852 100644 (file)
@@ -15,4 +15,6 @@
 "nOID": ".1.3.6.1.4.1.193.183.4.2.0.4",
 "AgentAddress": "192.168.1.2",
 "vmOID": ".1.3.6.1.4.1.193.183.4.1.2.1",
+"AICTenantID": "0123456789abcdef0123456789",
+"AICVServerSelfLink": "http://somewhere"
 }
\ No newline at end of file
index ed27db9..d555f39 100644 (file)
@@ -30,21 +30,29 @@ import java.util.Set;
 import org.openecomp.appc.adapter.message.Consumer;
 import org.openecomp.appc.adapter.message.MessageAdapterFactory;
 import org.openecomp.appc.adapter.message.Producer;
+
 import org.openecomp.appc.adapter.messaging.dmaap.http.HttpDmaapConsumerImpl;
 import org.openecomp.appc.adapter.messaging.dmaap.http.HttpDmaapProducerImpl;
 
+import org.openecomp.appc.adapter.messaging.dmaap.impl.DmaapConsumerImpl;
+import org.openecomp.appc.adapter.messaging.dmaap.impl.DmaapProducerImpl;
+
 public class DmaapMessageAdapterFactoryImpl implements MessageAdapterFactory {
 
+       //Set to true if the HttpDmaap... should be used instead of the regular Dmaap...
+       private static final boolean HTTP = true;
+       
        public Producer createProducer(Collection<String> pools, String writeTopic, String apiKey, String apiSecret) {
-        return new HttpDmaapProducerImpl(pools, writeTopic);
+               return  HTTP ? new HttpDmaapProducerImpl(pools, writeTopic) : new DmaapProducerImpl(pools, writeTopic,apiKey, apiSecret);
        }
-       
+
        public Producer createProducer(Collection<String> pools, Set<String> writeTopics, String apiKey, String apiSecret) {
-               return new HttpDmaapProducerImpl(pools, writeTopics);
+               return HTTP ? new HttpDmaapProducerImpl(pools, writeTopics) : new DmaapProducerImpl(pools, writeTopics, apiKey, apiSecret);
        }
 
        public Consumer createConsumer(Collection<String> pool, String readTopic, 
-                                                     String clientName, String clientId, String filter_json, String apiKey, String apiSecret) {
-               return new HttpDmaapConsumerImpl(pool, readTopic, clientName, clientId, apiKey, apiSecret, filter_json);
+                       String clientName, String clientId, String filter_json, String apiKey, String apiSecret) {
+               return HTTP ? new HttpDmaapConsumerImpl(pool, readTopic, clientName, clientId, apiKey, apiSecret, filter_json) : 
+                       new DmaapConsumerImpl(pool, readTopic, clientName, clientId, apiKey, apiSecret, filter_json);
        }
 }
index de0569d..1888861 100644 (file)
@@ -52,6 +52,9 @@ import java.util.Properties;
 /**
  * This class implements the {@link ProviderAdapter} interface. This interface defines the behaviors that our service
  * provides.
+ *
+ * @since Aug 12, 2015
+ * @version $Id$
  */
 @SuppressWarnings("javadoc")
 public class ProviderAdapterImpl implements ProviderAdapter {
@@ -278,8 +281,8 @@ public class ProviderAdapterImpl implements ProviderAdapter {
          * provider1.name=ILAB
          * provider1.identity=http://provider1:5000/v2.0
          * provider1.tenant1.name=CDP-ONAP-APPC
-         * provider1.tenant1.userid=cdpdev
-         * provider1.tenant1.password=cdpdev@123
+         * provider1.tenant1.userid=testUser
+         * provider1.tenant1.password=testPassword
          * provider1.tenant2.name=TEST-TENANT
          * provider1.tenant2.userid=testUser
          * provider1.tenant2.password=testPassword
index f037e58..b7ad626 100644 (file)
@@ -535,19 +535,33 @@ public abstract class ProviderServerOperation extends ProviderOperation{
                        throws ZoneException, RequestFailedException {
 
                logger.info("Performing the Hypervisor status checks..");
-               String status = null, state = null, msg = null;
-
-               status = server.getHypervisor().getStatus().toString();
-               state = server.getHypervisor().getState().toString();
                
-               if (!status.equals(Hypervisor.Status.ENABLED.toString()) || !state.equals(Hypervisor.State.UP.toString())) {
-                       msg = EELFResourceManager.format(Msg.HYPERVISOR_DOWN_ERROR, server.getHypervisor().getHostName(), server.getName());
-                       logger.error(msg.toString());
+               String msg = null;
+               if(server.getHypervisor() != null && server.getHypervisor().getStatus() != null && server.getHypervisor().getState() != null)
+               {
+                       String status = null, state = null;
+               
+                       status = server.getHypervisor().getStatus().toString();
+                       state = server.getHypervisor().getState().toString();
+               
+                       if (!status.equals(Hypervisor.Status.ENABLED.toString()) || !state.equals(Hypervisor.State.UP.toString())) 
+                       {
+                               msg = EELFResourceManager.format(Msg.HYPERVISOR_DOWN_ERROR, server.getHypervisor().getHostName(), server.getName());
+                               logger.error(msg.toString());
                
-                       //doFailure(rc, HttpStatus.PRECONDITION_FAILED_412, msg);
-                       throw new RequestFailedException("Hypervisor status DOWN or NOT ENABLED", msg.toString(), HttpStatus.PRECONDITION_FAILED_412,
+                               //doFailure(rc, HttpStatus.PRECONDITION_FAILED_412, msg);
+                               throw new RequestFailedException("Hypervisor status DOWN or NOT ENABLED", msg.toString(), HttpStatus.PRECONDITION_FAILED_412,
                                        server);
 
+                       }
+               }
+               else
+               {
+                       msg = EELFResourceManager.format(Msg.HYPERVISOR_STATUS_UKNOWN, server.getName());
+                       logger.error(msg.toString());
+       
+                       throw new RequestFailedException("Unable to determine Hypervisor status", msg.toString(), HttpStatus.PRECONDITION_FAILED_412,
+                               server);
                }
                
                logger.info("Passed the Hypervisor status checks..");
index 19f9ebb..b09e559 100644 (file)
             <artifactId>appc-common</artifactId>
             <version>${project.version}</version>
         </dependency>
-<!--         <dependency> -->
-<!--             <groupId>org.openecomp.appc</groupId> -->
-<!--             <artifactId>appc-dmaap-adapter-bundle</artifactId> -->
-<!--             <version>${project.version}</version> -->
-<!--         </dependency> -->
 
         <dependency>
             <groupId>javax</groupId>
             <scope>compile</scope>
         </dependency>
 
-        <dependency>
-            <groupId>equinoxSDK381</groupId>
-            <artifactId>org.eclipse.osgi</artifactId>
-        </dependency>
-
         <dependency>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-api</artifactId>
index 094ca9a..b8fdf9a 100644 (file)
                        <groupId>org.openecomp.appc</groupId>
                        <artifactId>appc-common</artifactId>
                        <version>${project.version}</version>
-                       <classifier>jar-with-dependencies</classifier>
                        <scope>compile</scope>
                </dependency>
-               <dependency>
-                       <groupId>org.openecomp.appc</groupId>
-                       <artifactId>appc-common</artifactId>
-                       <version>${project.version}</version>
-                       <scope>test</scope>
-               </dependency>
 
                <dependency>
                        <groupId>javax</groupId>
                        <groupId>org.glassfish.jersey.core</groupId>
                        <artifactId>jersey-common</artifactId>
                        <version>2.9.1</version>
+            <scope>test</scope>
                </dependency>
 
                <dependency>
                        <version>1.9.12</version>
                </dependency>
 
-               <dependency>
-                       <groupId>org.apache.httpcomponents</groupId>
-                       <artifactId>httpclient</artifactId>
-                       <version>4.5.1</version>
-               </dependency>
-
                <dependency>
                        <groupId>junit</groupId>
                        <artifactId>junit</artifactId>
                <dependency>
                        <groupId>org.openecomp.sdnc.core</groupId>
                        <artifactId>sli-common</artifactId>
-                       <scope>compile</scope>
+                       <scope>provided</scope>
                        <!-- Added exclusion to prevent missing dependency issue on dblib -->
                        <exclusions>
                                <exclusion>
                <dependency>
                        <groupId>org.openecomp.sdnc.core</groupId>
                        <artifactId>sli-provider</artifactId>
-                       <scope>compile</scope>
+                       <scope>provided</scope>
                        <!-- Added exclusion to prevent missing dependency issue on dblib -->
                        <exclusions>
                                <exclusion>
                                                <Bundle-SymbolicName>appc-rest-healthcheck-adapter</Bundle-SymbolicName>
                                                <Bundle-Activator>org.openecomp.appc.adapter.restHealthcheck.RestHealthcheckActivator</Bundle-Activator>
                                                <Export-Package>org.openecomp.appc.adapter.restHealthcheck</Export-Package>
-                                               <Import-Package>
-                                                       org.openecomp.sdnctl.sli.*,org.osgi.framework.*,org.slf4j.*,com.vmware.*,org.apache.xerces.*,javax.net.*,javax.net.ssl.*,org.xml.sax.*,javax.xml.bind.*,javax.naming.*,javax.security.auth.*
+                                               <Import-Package>org.openecomp.sdnc.sli.*,org.osgi.framework.*,org.slf4j.*,com.vmware.*,org.apache.xerces.*,javax.net.*,javax.net.ssl.*,org.xml.sax.*,javax.xml.bind.*,javax.naming.*,javax.security.auth.*
                                                </Import-Package>
                                                <Embed-Dependency>
                                                        *;scope=compile|runtime;artifactId=!sli-common|!appc-common|org.eclipse.osgi|slf4j-api|jcl-over-slf4j|xml-apis
diff --git a/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/adapter/restHealthcheck/impl/TestRestHealthcheckAdapterImpl.java b/appc-adapters/appc-rest-healthcheck-adapter/appc-rest-healthcheck-adapter-bundle/src/test/java/org/openecomp/appc/adapter/restHealthcheck/impl/TestRestHealthcheckAdapterImpl.java
new file mode 100644 (file)
index 0000000..de18956
--- /dev/null
@@ -0,0 +1,119 @@
+/*-
+ * ============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.adapter.restHealthcheck.impl;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.slf4j.MDC;
+
+import org.openecomp.appc.Constants;
+import org.openecomp.appc.adapter.restHealthcheck.*;
+import org.openecomp.appc.configuration.ConfigurationFactory;
+import org.openecomp.appc.exceptions.APPCException;
+import org.openecomp.appc.exceptions.UnknownProviderException;
+import com.att.cdp.exceptions.ZoneException;
+import com.att.cdp.zones.ComputeService;
+import com.att.cdp.zones.Context;
+import com.att.cdp.zones.ContextFactory;
+import com.att.cdp.zones.model.Server;
+import com.att.cdp.zones.model.Server.Status;
+import org.openecomp.sdnc.sli.SvcLogicContext;
+
+
+
+public class TestRestHealthcheckAdapterImpl {
+
+    @SuppressWarnings("nls")
+    private static final String PROVIDER_NAME = "ILAB";
+
+    @SuppressWarnings("nls")
+    private static final String PROVIDER_TYPE = "OpenStackProvider";
+
+    private static String IDENTITY_URL;
+
+    private static String PRINCIPAL;
+
+    private static String CREDENTIAL;
+
+    private static String TENANT_NAME;
+
+    private static String TENANT_ID;
+
+    private static String USER_ID;
+
+    private static String REGION_NAME;
+
+    private static String SERVER_URL;
+
+    private static Class<?> providerAdapterImplClass;
+    private static Class<?> configurationFactoryClass;
+    private static Field providerCacheField;
+    private static Field configField;
+
+    private RestHealthcheckAdapterImpl adapter;
+
+
+    @SuppressWarnings("nls")
+    @BeforeClass
+    public static void once() throws NoSuchFieldException, SecurityException, NoSuchMethodException {
+
+    }
+
+    @Before
+    public void setup() throws IllegalArgumentException, IllegalAccessException {
+
+        adapter = new RestHealthcheckAdapterImpl();
+    }
+
+    @Test
+    public void testCheckHealth() throws IOException, IllegalStateException, IllegalArgumentException,
+        ZoneException, APPCException {
+
+            Map<String, String> params = new HashMap<>();
+            params.put("VNF.URI", "http://restHalthCheck.test");
+            params.put("VNF.endpoint", "health");
+            SvcLogicContext svcContext = new SvcLogicContext();
+            adapter.checkHealth(params, svcContext);
+            String statusCode=svcContext.getAttribute("healthcheck.result.code");
+            assertEquals("200",statusCode);
+    }
+
+
+
+}
index 1758e95..0342b23 100644 (file)
@@ -28,7 +28,7 @@
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.2.0 http://karaf.apache.org/xmlns/features/v1.2.0">     
     
-    <repository>mvn:org.opendaylight.mdsal/features-mdsal/${features-mdsal.version}/xml/features</repository>
+    <repository>mvn:org.opendaylight.mdsal/features-mdsal/${odl.mdsal.features.version}/xml/features</repository>
 
     <feature name='appc-rest-healthcheck-adapter' description="appc-rest-healthcheck-adapter" version='${project.version}'>
         <!-- Most applications will have a dependency on the ODL MD-SAL Broker -->
index 4dc4a4d..2490cd8 100644 (file)
@@ -7,7 +7,7 @@
         <version>1.1.0-SNAPSHOT</version>
     </parent>
     <artifactId>appc-rest-healthcheck-adapter-installer</artifactId>
-    <name>Chef Adapter - Karaf Installer</name>
+    <name>Rest Health Check Adapter - Karaf Installer</name>
     <packaging>pom</packaging>
     <properties>
         <application.name>appc-rest-healthcheck-adapter</application.name>
index 607ab77..35b9b31 100644 (file)
                        <artifactId>json</artifactId>
                        <scope>compile</scope>
                </dependency>
+               <dependency>
+                       <groupId>org.mockito</groupId>
+                       <artifactId>mockito-all</artifactId>
+                       <scope>test</scope>
+               </dependency>
+
+               <dependency>
+                       <groupId>org.mockito</groupId>
+                       <artifactId>mockito-core</artifactId>
+                       <scope>test</scope>
+               </dependency>
+               <dependency>
+            <groupId>org.powermock</groupId>
+            <artifactId>powermock-module-junit4</artifactId>
+            <version>1.6.2</version>
+            <scope>test</scope>
+        </dependency>
+               <dependency>
+                       <groupId>org.powermock</groupId>
+                       <artifactId>powermock-api-mockito</artifactId>
+                       <scope>test</scope>
+               </dependency>
 
                <dependency>
-                       <groupId>org.openecomp.sdc</groupId>
+                       <groupId>org.openecomp.sdc.sdc-distribution-client</groupId>
                        <artifactId>sdc-distribution-client</artifactId>
-                       <version>1.0.0</version>
+                       <version>${sdc-client.version}</version>
                </dependency>
 
                <dependency>
                        <version>${project.version}</version>
                </dependency>
 
+               <dependency>
+                       <groupId>org.openecomp.appc</groupId>
+                       <artifactId>appc-message-adapter-factory</artifactId>
+                       <version>${project.version}</version>
+               </dependency>
+
                <dependency>
                        <groupId>org.yaml</groupId>
                        <artifactId>snakeyaml</artifactId>
                        <groupId>org.openecomp.appc</groupId>
                        <artifactId>appc-license-manager-api</artifactId>
                        <!-- <version>${project.version}</version> -->
-                       <version>1.1.0-SNAPSHOT</version>
+                       <version>${project.version}</version>
                </dependency>
 
                <dependency>
                        <artifactId>gson</artifactId>
                </dependency>
 
-               <dependency>
-                       <groupId>org.openecomp.sdc</groupId>
-                       <artifactId>openecomp-tosca-lib</artifactId>
-                       <version>${toscalib.version}</version>
-               </dependency>
+        <dependency>
+            <groupId>org.openecomp.sdc.common</groupId>
+            <artifactId>openecomp-tosca-datatype</artifactId>
+            <version>${toscalib.version}</version>
+        </dependency>
 
                <dependency>
                        <groupId>org.apache.velocity</groupId>
                        <artifactId>ietf-yang-types</artifactId>
                        <version>${odl.ietf-yang-types.version}</version>
                </dependency>
-       </dependencies>
+               <dependency>
+                       <groupId>com.fasterxml.jackson.dataformat</groupId>
+                       <artifactId>jackson-dataformat-yaml</artifactId>
+                       <version>${jackson.yml.version}</version>
+               </dependency>
+               <dependency>
+                       <groupId>org.mockito</groupId>
+                       <artifactId>mockito-core</artifactId>
+               </dependency>
+    </dependencies>
 
 
        <build>
diff --git a/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/ArtifactProcessor.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/ArtifactProcessor.java
new file mode 100644 (file)
index 0000000..c0f5220
--- /dev/null
@@ -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-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/ArtifactStorageService.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/helper/ArtifactStorageService.java
new file mode 100644 (file)
index 0000000..6bae969
--- /dev/null
@@ -0,0 +1,180 @@
+/*-
+ * ============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.openecomp.appc.exceptions.APPCException;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+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.licmgr.Constants.ASDC_ARTIFACTS;
+import static org.openecomp.appc.licmgr.Constants.ASDC_ARTIFACTS_FIELDS.*;
+
+/**
+ * Provides methods for storing sdc artifacts into app-c database
+ */
+public class ArtifactStorageService {
+
+    private DbLibService dbLibService;
+
+    private static final String COMMA = " , ";
+    private static final String QUERY_PLACEHOLDER = " = ? ";
+
+    private static final String SCHEMA =  "sdnctl";
+
+    private static final String SELECT_QUERY = "SELECT * FROM " + ASDC_ARTIFACTS +
+                                                " WHERE " + RESOURCE_NAME + QUERY_PLACEHOLDER +
+                                                " AND " + RESOURCE_VERSION + QUERY_PLACEHOLDER +
+                                                " AND " + ARTIFACT_TYPE + QUERY_PLACEHOLDER;
+
+    private static final String INSERT_QUERY = "INSERT INTO " + ASDC_ARTIFACTS +
+            " ( " + SERVICE_UUID + COMMA +
+                    DISTRIBUTION_ID + COMMA +
+                    SERVICE_NAME + COMMA +
+                    SERVICE_DESCRIPTION + COMMA +
+                    RESOURCE_UUID + COMMA +
+                    RESOURCE_INSTANCE_NAME + COMMA +
+                    RESOURCE_NAME + COMMA +
+                    RESOURCE_VERSION + COMMA +
+                    RESOURCE_TYPE + COMMA +
+                    ARTIFACT_UUID + COMMA +
+                    ARTIFACT_TYPE + COMMA +
+                    ARTIFACT_VERSION + COMMA +
+                    ARTIFACT_DESCRIPTION + COMMA +
+                    CREATION_DATE + COMMA +
+                    ARTIFACT_NAME  +COMMA +
+                    ARTIFACT_CONTENT + " ) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+
+
+    private final EELFLogger logger = EELFManager.getInstance().getLogger(ArtifactStorageService.class);
+
+    /**
+     * Stores Artifact received from SDC into APP-C database
+     * @param artifact
+     * @throws APPCException
+     */
+    public void storeASDCArtifact(SDCArtifact artifact) throws APPCException {
+        if(logger.isDebugEnabled()){
+            logger.debug("Entering storeASDCArtifact with : " + artifact.toString());
+        }
+        try {
+            initializeDBLibService();
+            ArrayList<String> 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 storeASDCArtifact");
+        }
+    }
+
+    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<String> prepareArguments(SDCArtifact artifact) {
+        ArrayList<String> arguments = new ArrayList<>();
+        arguments.add(artifact.getServiceUUID());
+        arguments.add(artifact.getDistributionId());
+        arguments.add(artifact.getServiceName());
+        arguments.add(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;
+    }
+
+    /**
+     * reads the SDC artifact from APP-C database
+     * @param resourceName
+     * @param resourceVersion
+     * @param artifactType
+     * @return
+     * @throws APPCException
+     */
+    public SDCArtifact retrieveSDCArtifact(String resourceName, String resourceVersion, String artifactType) throws APPCException {
+        SDCArtifact artifact = null;
+        try {
+            initializeDBLibService();
+            ArrayList<String> 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(ARTIFACT_UUID.toString()));
+                artifact.setArtifactName(rowSet.getString(ARTIFACT_NAME.toString()));
+                artifact.setArtifactType(rowSet.getString(ARTIFACT_TYPE.toString()));
+                artifact.setArtifactVersion(rowSet.getString(ARTIFACT_VERSION.toString()));
+                artifact.setArtifactDescription(rowSet.getString(ARTIFACT_DESCRIPTION.toString()));
+                artifact.setArtifactContent(rowSet.getString(ARTIFACT_CONTENT.toString()));
+
+                artifact.setResourceUUID(rowSet.getString(RESOURCE_UUID.toString()));
+                artifact.setResourceName(rowSet.getString(RESOURCE_NAME.toString()));
+                artifact.setResourceType(rowSet.getString(RESOURCE_TYPE.toString()));
+                artifact.setResourceVersion(rowSet.getString(RESOURCE_VERSION.toString()));
+                artifact.setResourceInstanceName(rowSet.getString(RESOURCE_INSTANCE_NAME.toString()));
+
+                artifact.setServiceUUID(rowSet.getString(SERVICE_UUID.toString()));
+                artifact.setServiceName(rowSet.getString(SERVICE_NAME.toString()));
+                artifact.setServiceDescription(rowSet.getString(SERVICE_DESCRIPTION.toString()));
+
+                artifact.setCreationDate(rowSet.getString(CREATION_DATE.toString()));
+                artifact.setDistributionId(rowSet.getString(DISTRIBUTION_ID.toString()));
+            }
+
+        } catch (SQLException e) {
+            logger.error("Error query artifact for " + RESOURCE_NAME + " = " + resourceName +
+                    RESOURCE_VERSION + " = " + resourceVersion +
+                    ARTIFACT_TYPE + " = " + artifactType, e);
+            throw new APPCException(e);
+        }
+        return artifact;
+    }
+}
diff --git a/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/AbstractArtifactProcessor.java
new file mode 100644 (file)
index 0000000..12fd260
--- /dev/null
@@ -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("ASDC 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-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ArtifactProcessorFactory.java
new file mode 100644 (file)
index 0000000..aa9d0e0
--- /dev/null
@@ -0,0 +1,89 @@
+/*-
+ * ============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.appc.sdc.listener.AsdcListener;
+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-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ConfigArtifactProcessor.java
new file mode 100644 (file)
index 0000000..3667b6b
--- /dev/null
@@ -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.toAsdcStoreDocumentInput(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-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/LicenseArtifactProcessor.java
new file mode 100644 (file)
index 0000000..9cbc562
--- /dev/null
@@ -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 ASDC 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.storeASDCArtifact(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-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/impl/ToscaCsarArtifactProcessor.java
new file mode 100644 (file)
index 0000000..5379d46
--- /dev/null
@@ -0,0 +1,210 @@
+/*-
+ * ============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.object.Resource;
+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 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);
+
+    public ToscaCsarArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource,
+                               IArtifactInfo artifact, URI storeUri){
+        super(client,eventSender,notification,resource,artifact,storeUri);
+    }
+
+    @Override
+    public void processArtifact(IDistributionClientDownloadResult download) throws APPCException {
+        logger.debug("processing artifact " + super.artifact.getArtifactType());
+        byte[] byteArray = download.getArtifactPayload();
+        String serviceFileName = "";
+        String serviceTemplateContent = "";
+        List<Resource> resources = null;
+        Map<String,String> 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<Resource> readResources(String serviceTemplateContent) throws IOException {
+        List<Resource> 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<Map.Entry<String, JsonNode>> itr = nodeTemplates.fields();
+        while(itr.hasNext()){
+            Map.Entry<String, JsonNode> 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 {
+            SDCArtifact existingArtifact = artifactStorageService.retrieveSDCArtifact(vnfType, version,artifact.getArtifactType());
+
+            if (existingArtifact ==null) { // new resource
+                logger.debug("Artifact not found for vnfType = " + vnfType + " , version = " +  version + " , artifactType = " + artifact.getArtifactType());
+                artifactStorageService.storeASDCArtifact(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() );
+            throw new APPCException(e.getMessage(),e);
+        }
+    }
+
+
+}
diff --git a/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/ArtifactType.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/ArtifactType.java
new file mode 100644 (file)
index 0000000..1ff6238
--- /dev/null
@@ -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-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Resource.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/Resource.java
new file mode 100644 (file)
index 0000000..42716dc
--- /dev/null
@@ -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-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCArtifact.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/artifacts/object/SDCArtifact.java
new file mode 100644 (file)
index 0000000..6cba5b2
--- /dev/null
@@ -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;
+    }
+}
index 6b36e2e..3451496 100644 (file)
@@ -27,12 +27,15 @@ 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;
@@ -86,13 +89,34 @@ public class AsdcCallback implements INotificationCallback {
         }
 
         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.toAsdcStoreDocumentInput(data, resource, artifact, "abc"));
                     if (executor.getQueue().size() >= threadCount) {
                         // log warning about job backlog
                     }
-                    executor.submit(new DownloadAndStoreOp(client, eventSender, data, resource, artifact, storeUri));
+                    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 {
index 7a176a9..448a7f3 100644 (file)
@@ -41,7 +41,7 @@ public class AsdcConfig implements IConfiguration {
        private String keystorePass;
        private int pollingInterval; // Time between listening sessions
        private int pollingTimeout; // Time to listen for (dmaap timeout url param)/1000
-       private List<String> types = new ArrayList<>(1);
+       private List<String> types = new ArrayList<>();
        private String user;
        private String pass;
 
@@ -94,6 +94,10 @@ public class AsdcConfig implements IConfiguration {
                        // Download type
                        types.add("APPC_CONFIG");
                        types.add("VF_LICENSE");
+                       types.add("TOSCA_CSAR");
+                       /*
+                       This types seems redundant, as it looks from the code that they are not being used anywhere
+                        */
 
                        storeOp = new URI(props.getProperty("appc.asdc.provider.url"));
                }
diff --git a/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/DownloadAndStoreOp.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/main/java/org/openecomp/appc/sdc/listener/DownloadAndStoreOp.java
deleted file mode 100644 (file)
index 8fcf1fb..0000000
+++ /dev/null
@@ -1,229 +0,0 @@
-/*-
- * ============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.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.exceptions.APPCException;
-import org.openecomp.appc.licmgr.Constants;
-import org.openecomp.appc.licmgr.LicenseManager;
-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 com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceReference;
-
-import static org.openecomp.appc.licmgr.Constants.ASDC_ARTIFACTS_FIELDS.*;
-
-import java.io.UnsupportedEncodingException;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-
-@SuppressWarnings("JavaDoc")
-public class DownloadAndStoreOp implements Runnable {
-
-    public static final String PAYLOAD_CHARSET = "UTF-8";
-
-    private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm:ss";
-
-    private final EELFLogger logger = EELFManager.getInstance().getLogger(DownloadAndStoreOp.class);
-
-    private IDistributionClient client;
-    private EventSender eventSender;
-
-    private INotificationData notification;
-    private IResourceInstance resource;
-    private IArtifactInfo artifact;
-
-    private URI storeUri;
-
-    public DownloadAndStoreOp(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource,
-                              IArtifactInfo artifact, URI storeUri) {
-        this.client = client;
-        this.eventSender = eventSender;
-        this.notification = notification;
-        this.resource = resource;
-        this.artifact = artifact;
-        this.storeUri = storeUri;
-    }
-
-    @Override
-    public void run() {
-        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));
-
-        String data = null;
-        try {
-            if (download.getArtifactPayload() != null) {
-                data = new String(download.getArtifactPayload(), PAYLOAD_CHARSET);
-            }
-        } catch (UnsupportedEncodingException e) {
-            e.printStackTrace();
-        }
-
-        boolean providerSuccess = false;
-        String providerReason = "Unknown Error";
-        // Send data to provider
-        if (data != null && artifact != null) {
-            switch(artifact.getArtifactType()) {
-                case "APPC_CONFIG":
-                    String postData = Util.toAsdcStoreDocumentInput(notification, resource, artifact, data);
-                    try {
-                        ProviderResponse result = ProviderOperations.post(storeUri.toURL(), postData, null);
-                        if (result.getStatus() == 200) {
-                            providerSuccess = Util.parseResponse(result.getBody());
-                            providerReason = "Success";
-                        }
-                    } catch (MalformedURLException | APPCException e) {
-                        providerReason = e.getMessage();
-                        e.printStackTrace();
-                    }
-                    break;
-
-                case "VF_LICENSE":
-                    BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
-                    ServiceReference srefLicenseService = bctx.getServiceReference(LicenseManager.class);
-                    LicenseManager licenseService = (LicenseManager) bctx.getService(srefLicenseService);
-
-                    Map<String, String> artifactPayload = prepareArtifactPayloadParamsMap(data);
-
-                    String vnfType = artifactPayload.get(RESOURCE_NAME.name());
-                    String version = artifactPayload.get(RESOURCE_VERSION.name());
-                    String packageArtifactID = artifactPayload.get(ARTIFACT_UUID.name());
-
-                    try {
-                        if (null == vnfType || null == version || null == packageArtifactID || vnfType.isEmpty() || version.isEmpty() || packageArtifactID.isEmpty()) {
-                            throw new APPCException(String.format("Missing information in ASDC request. Details: resource_type='%s', resource_version='%s', artifactID='%s'", vnfType, version, packageArtifactID));
-                        }
-
-                        Map<String, String> existingArtifactPayload = licenseService.retrieveLicenseModelData(vnfType, version);
-
-                        if (existingArtifactPayload.isEmpty()) { // new resource
-                            licenseService.storeArtifactPayload(artifactPayload);
-                        } else { // duplicate
-                            logger.warn(String.format("Artifact of type '%s' already deployed for resource_type='%s' and resource_version='%s'", Constants.VF_LICENSE, vnfType, version));
-                        }
-
-                        providerSuccess = true;
-
-                    } catch (Exception e) {
-                        providerSuccess = false;
-                        providerReason = e.getMessage();
-                    }
-                    break;
-
-                default:
-                    throw new UnsupportedOperationException("Artifact type " + artifact.getArtifactType() + " is not supported");
-            }
-
-        }
-
-        // Notify of provider's response
-        if (providerSuccess) {
-            client.sendDeploymentStatus(
-                            Util.buildDistributionStatusMessage(client, notification, artifact, DistributionStatusEnum.DEPLOY_OK));
-        } else {
-            client.sendDeploymentStatus(Util.buildDistributionStatusMessage(client, notification, artifact,
-                            DistributionStatusEnum.DEPLOY_ERROR), providerReason);
-            sendDCAEEvent(notification.getDistributionID(), notification.getServiceName(), notification.getServiceVersion(), providerReason);
-        }
-
-    }
-
-    /**
-     * Prepares Artifact Payload params map
-     * @param data
-     * @return Map<String,String>
-     */
-    private Map<String, String> prepareArtifactPayloadParamsMap(String data) {
-        Map<String, String> paramsMap = new HashMap<>();
-
-        paramsMap.put(SERVICE_UUID.name(), this.notification.getServiceUUID());
-        paramsMap.put(DISTRIBUTION_ID.name(), this.notification.getDistributionID());
-        paramsMap.put(SERVICE_NAME.name(), this.notification.getServiceName());
-        paramsMap.put(SERVICE_DESCRIPTION.name(), this.notification.getServiceDescription());
-        paramsMap.put(RESOURCE_UUID.name(), this.resource.getResourceUUID());
-        paramsMap.put(RESOURCE_INSTANCE_NAME.name(), this.resource.getResourceInstanceName());
-        paramsMap.put(RESOURCE_NAME.name(), this.resource.getResourceName());
-        paramsMap.put(RESOURCE_VERSION.name(), this.resource.getResourceVersion());
-        paramsMap.put(RESOURCE_TYPE.name(), this.resource.getResourceType());
-        paramsMap.put(ARTIFACT_UUID.name(), this.artifact.getArtifactUUID());
-        paramsMap.put(ARTIFACT_TYPE.name(), this.artifact.getArtifactType());
-        paramsMap.put(ARTIFACT_VERSION.name(), this.artifact.getArtifactVersion());
-        paramsMap.put(ARTIFACT_DESCRIPTION.name(), this.artifact.getArtifactDescription());
-        paramsMap.put(CREATION_DATE.name(), getCurrentDateTime());
-        paramsMap.put(ARTIFACT_NAME.name(), this.artifact.getArtifactName());
-        paramsMap.put(ARTIFACT_CONTENT.name(), data);
-
-        return paramsMap;
-    }
-
-
-    private 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("ASDC distribution of service '%s', version '%s' is failed with reason: '%s'",
-                        serviceName, serviceVersion, errorMessage);
-
-        EventMessage eventMessage = new EventMessage(
-                        new EventHeader((new java.util.Date()).toString(), serviceVersion, distributionID),
-                        new EventStatus(401, errorDescription));
-
-        eventSender.sendEvent(MessageDestination.DCAE, eventMessage);
-    }
-
-}
diff --git a/appc-asdc-listener/appc-asdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/TestAsdcListener.java b/appc-asdc-listener/appc-asdc-listener-bundle/src/test/java/org/openecomp/appc/sdc/listener/TestAsdcListener.java
new file mode 100644 (file)
index 0000000..e6f913a
--- /dev/null
@@ -0,0 +1,194 @@
+/*-
+ * ============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.Test;
+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 TestAsdcListener {
+
+    IDistributionClient client;
+    private EventSender eventSender;
+    private INotificationCallback asdcCallback;
+    private ArtifactStorageService storageService;
+    private ToscaCsarArtifactProcessor artifactProcessor;
+
+
+    @Before
+    public void setup() throws Exception {
+        client =  PowerMockito.mock(IDistributionClient.class);
+        eventSender = PowerMockito.mock(EventSender.class);
+        asdcCallback = new AsdcCallback(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(asdcCallback,"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<Object>() {
+            @Override
+            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
+                System.out.print(invocationOnMock.getArguments()[0].toString());
+                return null;
+            }
+        }).when(storageService).storeASDCArtifact((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 testASDCListener() throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
+
+
+        INotificationData notificationData = getNotificationData();
+        asdcCallback.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<IArtifactInfo> serviceArtifacts = getServiceArtifacts();
+
+        invokeMethod(notificationData, "setServiceArtifacts", serviceArtifacts);
+        return notificationData;
+    }
+
+    private List<IResourceInstance> getResources() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
+        List<IResourceInstance> resources = new ArrayList<>();
+        IResourceInstance resource = (IResourceInstance)getObject("org.openecomp.sdc.impl.JsonContainerResourceInstance");
+
+        List<IArtifactInfo> 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<IArtifactInfo> getServiceArtifacts() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
+        List<IArtifactInfo> 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-asdc-listener/appc-asdc-listener-bundle/src/test/resources/csar/service-ServiceAppc-csar.csar b/appc-asdc-listener/appc-asdc-listener-bundle/src/test/resources/csar/service-ServiceAppc-csar.csar
new file mode 100644 (file)
index 0000000..a30ca2f
Binary files /dev/null and b/appc-asdc-listener/appc-asdc-listener-bundle/src/test/resources/csar/service-ServiceAppc-csar.csar differ
index 6834bd8..4735241 100644 (file)
             <artifactId>openecomp-tosca-lib</artifactId>
             <version>${toscalib.version}</version>
         </dependency>
+        <dependency>
+            <groupId>org.openecomp.sdc.common</groupId>
+            <artifactId>openecomp-tosca-datatype</artifactId>
+            <version>${toscalib.version}</version>
+        </dependency>
     </dependencies>
-
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-shade-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>shade</goal>
+                        </goals>
+                    </execution>
+                </executions>
+                <configuration>
+                    <finalName>${artifactId}-${version}</finalName>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <version>3.6.1</version>
+                <configuration>
+                    <source>1.8</source>
+                    <target>1.8</target>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
 
 </project>
\ No newline at end of file
index bc52732..2465639 100644 (file)
@@ -42,7 +42,7 @@ 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.ToscaExtensionYamlUtil;
+import org.openecomp.sdc.tosca.services.YamlUtil;
 
 import java.io.*;
 import java.util.HashMap;
@@ -127,7 +127,7 @@ public class YANGGeneratorImpl implements YANGGenerator {
 
        private Map<String,Object> parseTosca(String tosca) throws YANGGenerationException {
                Log.info("Entered into parseTosca.");
-               ServiceTemplate serviceTemplate = new ToscaExtensionYamlUtil().yamlToObject(tosca, ServiceTemplate.class);
+               ServiceTemplate serviceTemplate = new YamlUtil().yamlToObject(tosca, ServiceTemplate.class);
                Map<String, NodeType> nodeTypeMap = serviceTemplate.getNode_types();
                String kind = nodeTypeMap.keySet().toArray(new String[0])[0];
                NodeType nodeType = nodeTypeMap.get(kind);
index 90cec79..9565cb8 100644 (file)
       <plugin>
         <groupId>com.att.eelf</groupId>
         <artifactId>eelf-maven-plugin</artifactId>
-        <version>${eelf.maven.plugin.version}</version>
         <executions>
           <execution>
             <id>validation</id>
diff --git a/appc-common/src/main/java/org/openecomp/appc/CmdLine.java b/appc-common/src/main/java/org/openecomp/appc/CmdLine.java
new file mode 100644 (file)
index 0000000..699edc7
--- /dev/null
@@ -0,0 +1,60 @@
+/*-
+ * ============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.openecomp.appc.encryption.EncryptionTool;
+
+public class CmdLine {
+
+        public static void main(String[] args) {
+        if(args.length <= 1 || args.length >= 3){
+            printUsage();
+        }else{
+            String command = args[0];
+            
+            switch(command){
+                case "encrypt":
+                    if(args[1]!= null){
+                        String clearText = args[1];
+                        String encrypted = EncryptionTool.getInstance().encrypt(clearText);
+                        System.out.println(encrypted);                        
+                    }else{
+                        printUsage();
+                    }
+                    break;
+                default:
+                    printUsage();
+                    break;
+                
+            }
+          }
+            
+        }
+        
+        private static void printUsage(){
+            System.out.println("Usage: java -jar <this jar> ...");
+            System.out.println("\tencrypt <your text> \t\t(Encrypts your text)");
+        }
+}
index c6e87c6..7306b4c 100644 (file)
@@ -702,6 +702,12 @@ public enum Msg implements EELFResolvableErrorEnum {
      *
      */
     HYPERVISOR_DOWN_ERROR,
+    
+    /**
+     * Unable to determine Hypervisor status for Server {0}. failed.
+     *
+     */
+    HYPERVISOR_STATUS_UKNOWN,
 
     /**
      * Hypervisor Network check for Server {0} failed. Not reachable by APPC
index 08020f8..28971c7 100644 (file)
@@ -879,6 +879,11 @@ HYPERVISOR_DOWN_ERROR=APPC0141E|\
   the requested operation on it.
   .
 
+HYPERVISOR_STATUS_UKNOWN=APPC0158E|\
+  Unable to determine the status of the Hypervisor for the Server {0} |\
+  Please ensure the userid has privileges enabled to query for the Hypervisor status. |\
+  If you wish to proceed with the requested operation, either obtain the privileges from the Cloud provider, or skip the Hypervisor check and retry the request.
+  .
 
 HYPERVISOR_NETWORK_ERROR=APPC0142E|\
   Hypervisor {0} for the Server {1} is NOT Reachable by APPC for initiating the requested operation|\
     log4j.appender.audit.layout.ConversionPattern=%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%t|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%-5.5p|%X{Severity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{ClientIPAddress}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%m%n
 
     #Loggers
+
     #Routing of all messages from root logger
-    log4j.logger.com.att=TRACE, debug, error
+    log4j.logger.org.openecomp=TRACE, debug, error
     #Store to the same log file messages from upper level appender or not
-    log4j.additivity.com.att=false
+    log4j.additivity.org.openecomp=false
 
     #EELFManager loggers
     #EELF parent logger
index c71d690..805b3df 100644 (file)
@@ -24,6 +24,7 @@
 
 #
 # Message bundle for German (language de, no specific country) 
+# 
 #
-MESSAGE_TEST=Eine Nachricht f�r Unit-Tests den Ressource-Manager, arg0 = {0}, arg1 = {1}, arg2 = {2}
-TEST_001=Dies ist eine Testnachricht ohne Eins�tze bearbeitet werden!
+MESSAGE_TEST=Eine Nachricht f\u00FCr Unit-Tests den Ressource-Manager, arg0 = {0}, arg1 = {1}, arg2 = {2}
+TEST_001=Dies ist eine Testnachricht ohne Eins\u00FCtze bearbeitet werden!
index 425bc99..2d0c95b 100644 (file)
                <dependency>
                        <groupId>org.openecomp.appc</groupId>
                        <artifactId>appc-netconf-adapter-bundle</artifactId>
-                       <!--<version>${project.version}</version> -->
                        <version>1.1.0-SNAPSHOT</version>
                </dependency>
 
index 308261c..93ad6a5 100644 (file)
@@ -147,7 +147,7 @@ public class AAIPluginImpl implements AAIPlugin {
             vnfQueryResult = readVnf(vnfId);
 
             vnfType = vnfQueryResult.getAdditionProperties().get("vnf-type");
-            vnfVersion = vnfQueryResult.getAdditionProperties().get("persona-model-version");
+            vnfVersion = vnfQueryResult.getAdditionProperties().get(Constants.AAI_VNF_MODEL_VERSION_ID);
 
             for(Relationship vnfRelationship:vnfQueryResult.getRelationshipList()){
                 if("vserver".equalsIgnoreCase(vnfRelationship.getRelatedTo())){
@@ -258,7 +258,7 @@ public class AAIPluginImpl implements AAIPlugin {
 
         String[] additionalProperties = new String[]{"vnf-type","vnf-name",
                 "in-maint","prov-status","heat-stack-id",
-                "is-closed-loop-disabled","orchestration-status","resource-version","persona-model-version"};
+                "is-closed-loop-disabled","orchestration-status","resource-version",Constants.AAI_VNF_MODEL_VERSION_ID};
 
         AAIQueryResult result = readRelationDataAndProperties(prefix, vnfContext,additionalProperties);
 
index 0a9fe21..1ccd6c4 100644 (file)
@@ -93,6 +93,11 @@ public class Constants {
     public static final String IS_ACQUIRE_ENTITLEMENT_REQUIRE ="is.acquire-entitlement.require";
     public static final String IS_RELEASE_ENTITLEMENT_REQUIRE ="is.release-entitlement.require";
 
+    /**
+     * AAI property names
+     */
+    public static final String AAI_VNF_MODEL_VERSION_ID ="model-version-id";
+
     public enum ASDC_ARTIFACTS_FIELDS {
         SERVICE_UUID,
         DISTRIBUTION_ID,
index ae59b07..1d92f13 100644 (file)
                        <artifactId>appc-dg-mdsal-store</artifactId>
                        <version>${project.version}</version>
                </dependency>
-       </dependencies>
+        <dependency>
+            <groupId>com.fasterxml.jackson.dataformat</groupId>
+            <artifactId>jackson-dataformat-yaml</artifactId>
+            <version>${jackson-yaml-version}</version>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-annotations</artifactId>
+            <version>${jackson-yaml-version}</version>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-databind</artifactId>
+            <version>${jackson-yaml-version}</version>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-core</artifactId>
+            <version>${jackson-yaml-version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.yaml</groupId>
+            <artifactId>snakeyaml</artifactId>
+            <version>${snakeyaml.version}</version>
+        </dependency>  </dependencies>
 
        <build>
                <plugins>
                                                <Private-Package>org.openecomp.appc.dg.common.impl.*</Private-Package>
                                                <Import-Package>org.openecomp.appc.adapter.message.*,org.openecomp.appc.adapter.factory.*,org.openecomp.appc.adapter.messaging.*,
                                                        *;resolution:=optional</Import-Package>
-                                               <Embed-Dependency>appc-dg-mdsal-store,appc-dg-domain-model-lib,appc-dg-dependency-model,jackson-dataformat-yaml,jackson-databind;scope=compile|runtime;inline=false;artifactId=!org.eclipse.osgi</Embed-Dependency>
+                                               <Embed-Dependency>appc-dg-mdsal-store,appc-dg-domain-model-lib,appc-dg-dependency-model,jackson-dataformat-yaml,jackson-databind,jackson-core;scope=compile|runtime;inline=false;artifactId=!org.eclipse.osgi</Embed-Dependency>
 
                                                <!--Embed-Dependency>eelf-core,logback-core,logback-classic;scope=compile|runtime;inline=false</Embed-Dependency-->
                                                <Embed-Transitive>true</Embed-Transitive>
index 20dbc6b..52a3d5f 100644 (file)
   </properties>
 
   <dependencies>
-    <dependency>
-      <groupId>junit</groupId>
-      <artifactId>junit</artifactId>
-      <scope>test</scope>
-    </dependency>
     <dependency>
       <groupId>org.openecomp.appc</groupId>
       <artifactId>appc-common</artifactId>
     <dependency>
       <groupId>com.fasterxml.jackson.dataformat</groupId>
       <artifactId>jackson-dataformat-yaml</artifactId>
-      <version>2.3.2</version>
+      <version>${jackson-yaml-version}</version>
+    </dependency>
+    <dependency>
+      <groupId>com.fasterxml.jackson.core</groupId>
+      <artifactId>jackson-annotations</artifactId>
+      <version>${jackson-yaml-version}</version>
     </dependency>
     <dependency>
       <groupId>com.fasterxml.jackson.core</groupId>
       <artifactId>jackson-databind</artifactId>
+      <version>${jackson-yaml-version}</version>
+    </dependency>
+    <dependency>
+      <groupId>com.fasterxml.jackson.core</groupId>
+      <artifactId>jackson-core</artifactId>
+      <version>${jackson-yaml-version}</version>
     </dependency>
+    <dependency>
+      <groupId>org.yaml</groupId>
+      <artifactId>snakeyaml</artifactId>
+      <version>${snakeyaml.version}</version>
+    </dependency>    
     <dependency>
       <groupId>commons-io</groupId>
       <artifactId>commons-io</artifactId>
index 222e3a0..c068412 100644 (file)
@@ -68,7 +68,6 @@ public class DependencyModelParser {
         String prefix = "org.openecomp.resource.vfc."+vnfType+".abstract.nodes.";
         try {
             ObjectNode root = (ObjectNode) mapper.readTree(vnfModel);
-            logger.debug("VNF Model after parsing: " + root);
 
             if(root.get(TOPOLOGY_TEMPLATE) == null || root.get(TOPOLOGY_TEMPLATE).get("node_templates") == null) {
                 throw new InvalidDependencyModel("Dependency model is missing 'topology_template' or  'node_templates' elements");
@@ -79,7 +78,8 @@ public class DependencyModelParser {
             Iterator<Map.Entry<String, JsonNode>> itretor  = nodeTemplateNode.fields();
             for (JsonNode yamlNode : nodeTemplateNode) {
                 logger.debug("Processing node: " + yamlNode);
-                String vnfcType = itretor.next().getKey();
+                String fullvnfcType = itretor.next().getValue().get("type").textValue();
+                String vnfcType= getQualifiedVnfcType(fullvnfcType);
                 String type = yamlNode.get("type").textValue();
                 type = type.substring(0,type.lastIndexOf(".")+1);
                 if(type.concat(vnfcType).toLowerCase().startsWith(prefix.concat(vnfcType).toLowerCase())) {
@@ -95,7 +95,7 @@ public class DependencyModelParser {
                     }else {
                         mandatory = yamlNode.get(PROPERTIES).findValue(MANDATORY).booleanValue();
                     }
-                    String[] parentList = getDependencyArray(yamlNode);
+                    String[] parentList = getDependencyArray(yamlNode,nodeTemplateNode);
                     Node<Vnfc> vnfcNode = getNode(dependencies, vnfcType);
                     if (vnfcNode != null) {
                         logger.debug("Dependency node already exists for vnfc Type: " + vnfcType);
@@ -126,6 +126,10 @@ public class DependencyModelParser {
         return new VnfcDependencyModel(dependencies);
     }
 
+    private String getQualifiedVnfcType(String fullvnfcType) {
+        return fullvnfcType.substring(fullvnfcType.lastIndexOf(".")+1,fullvnfcType.length());
+    }
+
     private void addDependencies(Set<Node<Vnfc>> nodes, Node node, String[] parentList) {
         for (String type : parentList) {
             String parentType = getVnfcType(type);
@@ -143,15 +147,18 @@ public class DependencyModelParser {
         }
     }
 
-    private String[] getDependencyArray(JsonNode node) {
+    private String[] getDependencyArray(JsonNode node, JsonNode nodeTemplateNode) {
         JsonNode requirementsNode = node.get("requirements");
         List<String> dependencyList  = new ArrayList();
         if(requirementsNode!=null) {
             for (JsonNode internalNode : requirementsNode) {
-                if (nodeNullCheck(internalNode) &&"tosca.capabilities.Node".equalsIgnoreCase(internalNode.get("capability").asText())
-                        && "tosca.relationships.DependsOn".equalsIgnoreCase(internalNode.get("relationship").asText())) {
-                    if(internalNode.get("node") != null) {
-                        dependencyList.add(internalNode.get("node").asText());
+                //TODO : In this release we are supporting both relationship = tosca.capabilities.Node  and relationship =tosca.relationships.DependsOn we need to remove one of them in next release post confirming with SDC team
+                if (nodeNullCheck(internalNode) &&"tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("capability").asText())
+                        && ("tosca.relationships.DependsOn".equalsIgnoreCase(internalNode.findValue("relationship").asText()) || "tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("relationship").asText()))) {
+                    if(internalNode.findValue("node") != null) {
+                        String nodeName = internalNode.findValue("node").asText();
+                        String fullVnfcName = nodeTemplateNode.get(nodeName).get("type").asText();
+                        dependencyList.add(getQualifiedVnfcType(fullVnfcName));
                     }else{
                         throw new InvalidDependencyModel("Error parsing dependency model. " + "Dependent Node not found for "+ node.get("type"));
                     }
@@ -164,7 +171,7 @@ public class DependencyModelParser {
     }
 
     private boolean nodeNullCheck(JsonNode internalNode) {
-        return internalNode.get("dependency") != null && internalNode.get("capability") != null && internalNode.get("relationship") != null;
+        return internalNode.get("dependency") != null && internalNode.findValue("capability") != null && internalNode.findValue("relationship") != null;
     }
 
     private Node<Vnfc> getNode(Set<Node<Vnfc>> nodes, String vnfcType) {
index 0eb11bf..f8b0d03 100644 (file)
@@ -46,6 +46,6 @@ public class VnfcDependencyModel {
         for(Node node:dependencies){
             stringBuilder.append(node.toString()).append(", ");
         }
-        return super.toString();
+        return stringBuilder.toString();
     }
 }
index a367bdc..711ec1d 100644 (file)
@@ -80,6 +80,21 @@ public class Constants {
      */
 
     public static final String CONFIG_URL = "https://localhost:8443/restconf/config";
+    public static final String CONFIG_URL_DEFAULT = "https://localhost:8443/restconf/config";
+
+    public static final String CONFIG_URL_PROPERTY = "appc.LCM.provider.url";
+
+    public static final String CONFIG_PATH = "/restconf/config";
+
+    /**
+     * Restconf authentication user property name
+     */
+    public static final String CONFIG_USER_PROPERTY = "appc.LCM.provider.user";
+
+    /**
+     * Restconf authentication password property name
+     */
+    public static final String CONFIG_PASS_PROPERTY = "appc.LCM.provider.pass";
 
     /**
      * Content for blueprint.xml used while creation of OSGI bundle.
index 091c770..b90d9c0 100644 (file)
@@ -24,6 +24,8 @@
 
 package org.openecomp.appc.mdsal.impl;
 
+import org.openecomp.appc.configuration.Configuration;
+import org.openecomp.appc.configuration.ConfigurationFactory;
 import org.openecomp.appc.exceptions.APPCException;
 import org.openecomp.appc.mdsal.MDSALStore;
 import org.openecomp.appc.mdsal.exception.MDSALStoreException;
@@ -38,6 +40,7 @@ import org.osgi.framework.FrameworkUtil;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.util.Date;
+import java.util.Properties;
 import java.util.jar.Attributes;
 import java.util.jar.JarEntry;
 import java.util.jar.JarOutputStream;
@@ -50,9 +53,20 @@ public class MDSALStoreImpl implements MDSALStore{
 
     private static final EELFLogger logger = EELFManager.getInstance().getLogger(MDSALStoreImpl.class);
 
+    private static final Configuration configuration = ConfigurationFactory.getConfiguration();
+
     MDSALStoreImpl(){
-        ConfigOperation.setUrl(Constants.CONFIG_URL);
-        ConfigOperation.setAuthentication(null,null);
+        String configUrl = null;
+        String user =null;
+        String password = null;
+        Properties properties = configuration.getProperties();
+        if (properties != null) {
+            configUrl= properties.getProperty(  Constants.CONFIG_URL_PROPERTY , Constants.CONFIG_URL_DEFAULT);
+            user  = properties.getProperty(Constants.CONFIG_USER_PROPERTY);
+            password = properties.getProperty(Constants.CONFIG_PASS_PROPERTY);
+        }
+        ConfigOperation.setUrl(configUrl);
+        ConfigOperation.setAuthentication(user,password);
     }
 
 
diff --git a/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge b/appc-dg/appc-dg-shared/appc-dg-mdsal-store/src/main/java/org/openecomp/appc/mdsal/operation/ConfigOperation.java~ccmerge
new file mode 100644 (file)
index 0000000..c1695d4
--- /dev/null
@@ -0,0 +1,295 @@
+/*-
+ * ============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.mdsal.operation;
+
+import org.openecomp.appc.exceptions.APPCException;
+import org.openecomp.appc.mdsal.impl.Constants;
+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 org.apache.commons.codec.binary.Base64;
+import org.apache.http.HttpHeaders;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpVersion;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpPut;
+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 javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.Socket;
+import java.net.URL;
+import java.security.*;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import org.apache.commons.io.IOUtils;
+
+/**
+ * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation.
+*/
+public class ConfigOperation {
+    private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class);
+
+    private static URL url;
+    private static String basicAuth;
+
+    ConfigOperation(){}
+
+    private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter();
+
+    private static ObjectMapper mapper = new ObjectMapper();
+
+    /**
+     * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input
+     * @param configJson - configuration JSON as String. This value will be stored in  MD-SAL store
+     * @param module - Module name that contains yang Schema
+     * @param containerName - yang container name which will be used as base container.
+     * @param subModules - Sub modules list if any. Order of sub module is top to bottom.
+     * @throws APPCException
+     */
+    public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException {
+        if (configJson == null) {
+            throw new APPCException("Provided message was null");
+        }
+        LOG.debug("Config JSON: " + configJson +"\n"
+                +"module" + module +"\n"
+                +"containerName" + containerName +"\n"
+                +"subModules length : " + subModules.length );
+
+        int httpCode;
+        String respBody ;
+        try {
+            String path = requestFormatter.buildPath(url, module, containerName, subModules);
+            LOG.debug("Configuration Path : " + path);
+            URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
+            HttpResponse response = doPut(serviceUrl , configJson);
+            httpCode = response.getStatusLine().getStatusCode();
+            respBody = IOUtils.toString(response.getEntity().getContent());
+        } catch (IOException e) {
+            LOG.error("Error while storing configuration json "+e.getMessage(), e);
+            throw new APPCException(e);
+        }
+
+        if (httpCode < 200 || httpCode >= 300 ) {
+            try {
+                LOG.debug("Config operation Error response code: " + httpCode);
+                ArrayList<String> errorMessage = new ArrayList<>();
+                JsonNode responseJson = toJsonNodeFromJsonString(respBody);
+                if(responseJson!=null && responseJson.get("errors")!=null) {
+                    JsonNode errors = responseJson.get("errors").get("error");
+                for (Iterator<JsonNode> i = errors.elements();i.hasNext();){
+                    JsonNode error = i.next();
+                    errorMessage.add(error.get("error-message").textValue());
+                }
+                }
+                throw new APPCException("Failed to load config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + errorMessage.toString());
+            } catch (Exception e) {
+                LOG.error("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(), e);
+                throw new APPCException("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(),e);
+            }
+        }else{
+            LOG.debug("Config operation successful. Response code: " + httpCode);
+        }
+    }
+
+    /**
+     * This is Generic method that can be used to perform REST Put operation
+     * @param url - Destination URL for put
+     * @param body - payload for put action which will be sent as request body.
+     * @return - HttpResponse object which is returned from put REST call.
+     * @throws APPCException
+     */
+    public static HttpResponse doPut (URL url, String body) throws APPCException {
+        HttpPut put;
+        try {
+            put = new HttpPut(url.toExternalForm());
+            put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON);
+            put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON);
+
+            if (basicAuth != null) {
+                put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
+            }
+
+            StringEntity entity = new StringEntity(body);
+            entity.setContentType(Constants.OPERATION_APPLICATION_JSON);
+            put.setEntity(new StringEntity(body));
+        } catch (UnsupportedEncodingException e) {
+            throw new APPCException(e);
+        }
+
+        HttpClient client = getHttpClient();
+
+        try {
+            return client.execute(put);
+        } catch (IOException e) {
+            throw new APPCException(e);
+        }
+
+    }
+
+    /**
+     * Updates the static var URL and returns the value;
+     *
+     * @return The new value of URL
+     */
+    public static String getUrl() {
+        return url.toExternalForm();
+    }
+
+    public static void setUrl(String newUrl) {
+        try {
+            url = new URL(newUrl);
+        } catch (MalformedURLException e) {
+            LOG.error("Malformed URL " +newUrl + e.getMessage(), 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;
+            basicAuth = new String(Base64.encodeBase64(authStr.getBytes()));
+        } else {
+            basicAuth = null;
+        }
+        return basicAuth;
+    }
+
+    @SuppressWarnings("deprecation")
+    private static HttpClient getHttpClient() throws APPCException {
+        HttpClient client;
+        if (url.getProtocol().equals(Constants.OPERATION_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(Constants.OPERATION_HTTPS, sf, 443));
+                registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443));
+                registry.register(new Scheme("http", sf, 8181));
+
+                ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
+                client = new DefaultHttpClient(ccm, params);
+            } catch (Exception e) {
+                LOG.error("Error creating HTTP Client. Creating default client." ,  e);
+                client = new DefaultHttpClient();
+            }
+        } else if ("http".equals(url.getProtocol())) {
+            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")
+    private static class MySSLSocketFactory extends SSLSocketFactory {
+        private SSLContext sslContext = SSLContext.getInstance("TLS");
+
+        private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
+                KeyStoreException, UnrecoverableKeyException {
+            super(truststore);
+
+            TrustManager tm = new X509TrustManager() {
+                @Override
+                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+                    LOG.debug("Inside checkClientTrusted");
+                }
+
+                @Override
+                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+                    LOG.debug("Inside checkServerTrusted");
+                }
+
+                @Override
+                public X509Certificate[] getAcceptedIssuers() {
+                    return new X509Certificate[1];
+                }
+            };
+
+            sslContext.init(null, new TrustManager[]{
+                    tm
+            }, null);
+        }
+
+        @Override
+        public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
+                throws IOException  {
+            return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
+        }
+
+        @Override
+        public Socket createSocket() throws IOException {
+            return sslContext.getSocketFactory().createSocket();
+        }
+    }
+
+    private static JsonNode toJsonNodeFromJsonString(String jsonStr) {
+        JsonNode jsonNode = null;
+        if(jsonStr != null) {
+            try {
+                jsonNode = mapper.readTree(jsonStr);
+            } catch (IOException e) {
+                LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e);
+            }
+        }
+        return jsonNode;
+    }
+
+}
index d5d6a0c..94e120f 100644 (file)
@@ -42,7 +42,7 @@ public class ConfigOperationRequestFormatter {
      */
     public String buildPath(URL url,String module, String containerName , String... subModules ) {
 
-        StringBuilder path = new StringBuilder( url.getPath()+ Constants.URL_BACKSLASH + module + ":"+containerName + Constants.URL_BACKSLASH);
+        StringBuilder path = new StringBuilder( Constants.CONFIG_PATH + Constants.URL_BACKSLASH + module + ":"+containerName + Constants.URL_BACKSLASH);
         if(subModules.length >0){
             for(String subModule : subModules){
                 path.append(subModule);
index 8ccb980..0aac262 100644 (file)
                <dependency>
                        <groupId>org.powermock</groupId>
                        <artifactId>powermock-api-mockito</artifactId>
-                       <version>1.6.2</version>
                        <scope>test</scope>
 
                </dependency>
                <dependency>
                        <groupId>org.powermock</groupId>
                        <artifactId>powermock-module-junit4</artifactId>
-                       <version>1.6.2</version>
                        <scope>test</scope>
                </dependency>
 
diff --git a/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java b/appc-dg/appc-dg-shared/appc-dg-netconf/src/test/java/org/openecomp/appc/dg/netconf/impl/NetconfClientPluginImplTest.java
new file mode 100644 (file)
index 0000000..66b3b15
--- /dev/null
@@ -0,0 +1,681 @@
+/*-
+ * ============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.dg.netconf.impl;
+
+import org.openecomp.appc.exceptions.APPCException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Matchers;
+import org.mockito.Mockito;
+import org.openecomp.appc.adapter.netconf.*;
+import org.openecomp.appc.adapter.netconf.util.Constants;
+import org.openecomp.appc.dg.netconf.impl.NetconfClientPluginImpl;
+import org.openecomp.sdnc.sli.SvcLogicContext;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.ServiceReference;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import java.lang.reflect.Field;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.powermock.api.mockito.PowerMockito.when;
+
+
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest({OperationalStateValidatorFactory.class, NetconfClientPluginImpl.class, FrameworkUtil.class, ObjectMapper.class})
+
+public class NetconfClientPluginImplTest {
+    private NetconfClientPluginImpl netconfClientPlugin;
+    private NetconfDataAccessService dao;
+    private NetconfClientFactory clientFactory;
+    private Map<String, String> params;
+
+    private final BundleContext bundleContext = Mockito.mock(BundleContext.class);
+    private final Bundle bundleService = Mockito.mock(Bundle.class);
+    private final ServiceReference sref1 = Mockito.mock(ServiceReference.class);
+    private final ServiceReference sref2 = Mockito.mock(ServiceReference.class);
+    private final ServiceReference sref3 = Mockito.mock(ServiceReference.class);
+    private static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message";
+
+
+    String host = "http://www.test.com";
+    String host1 = "http://www.test1.com";
+    String vnfType = "VNF";
+    int port = 8080;
+    String username = "test";
+    String password = "test";
+    String connectionDetails = "{\"host\":\"" + host + "\",\"port\":" + port + ",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"capabilities\":null,\"additionalProperties\":null}";
+    String fileContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
+            "<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
+            "\t<get-config>\n" +
+            "\t\t<source>\n" +
+            "\t\t\t<running/>\n" +
+            "\t\t </source>\n" +
+            "\t</get-config>\n" +
+            "</rpc>'";
+    String operationalState = "<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
+            "       <get>\n" +
+            "              <filter>\n" +
+            "                     <ManagedElement xmlns=\"urn:org:openecomp:appc:Test\">\n" +
+            "                           <VnfFunction xmlns=\"urn:org:openecomop:appc:Test\">\n" +
+            "                                  <ProcessorManagement>\n" +
+            "                                         <MatedPair>\n" +
+            "                                                <operationalState/>\n" +
+            "                                                <PayloadProcessor>\n" +
+            "                                                       <operationalState/>\n" +
+            "                                                </PayloadProcessor>\n" +
+            "                                         </MatedPair>\n" +
+            "                                         <SystemController>\n" +
+            "                                                <operationalState/>\n" +
+            "                                         </SystemController>\n" +
+            "                                  </ProcessorManagement>\n" +
+            "                           </VnfFunction>\n" +
+            "                     </ManagedElement>\n" +
+            "              </filter>\n" +
+            "       </get>\n" +
+            "</rpc>\n";
+
+
+    @Before
+    public void setUp() throws NoSuchFieldException, IllegalAccessException {
+        clientFactory = new NetconfClientFactoryMock();
+
+    }
+
+
+    @Test
+    public void testConfigure() throws Exception {
+
+        shortInit();
+        SvcLogicContext ctx = new SvcLogicContext();
+
+        params = new HashMap<>();
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails);
+        params.put(Constants.FILE_CONTENT_FIELD_NAME, fileContent);
+
+        netconfClientPlugin.configure(params, ctx);
+
+        NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH);
+
+        try {
+            Assert.assertEquals("wrong configuration", fileContent, client.getConf());
+            Assert.assertEquals("wrong host", host, client.getLastConnectionDetails().getHost());
+            Assert.assertEquals("wrong port", port, client.getLastConnectionDetails().getPort());
+            Assert.assertEquals("wrong username", username, client.getLastConnectionDetails().getUsername());
+            Assert.assertEquals("wrong password", password, client.getLastConnectionDetails().getPassword());
+            Assert.assertFalse(client.isConnection());
+        } catch (Exception e) {
+            Assert.fail("failed with because of " + e.getCause());
+        }
+
+
+    }
+
+
+    @Test
+    public void testConfigureNegativeIOException() throws Exception {
+        shortInit();
+        SvcLogicContext ctx = new SvcLogicContext();
+
+        params = new HashMap<>();
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails);
+        params.put(Constants.FILE_CONTENT_FIELD_NAME, fileContent);
+        NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH);
+
+
+        try {
+            netconfClientPlugin.configure(params, ctx);
+            Assert.assertTrue(false);
+        } catch (APPCException e) {
+            Assert.assertNull(client.getLastConnectionDetails());
+            Assert.assertNull(client.getConf());
+        }
+
+    }
+
+    @Test
+    public void testOperationStateValidation() throws Exception {
+        shortInit();
+        SvcLogicContext ctx = new SvcLogicContext();
+        DAOServiceMock daoServiceMock = (DAOServiceMock) dao;
+        daoServiceMock.setConfigFile(fileContent);
+
+        NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH);
+        client.setAnswer(operationalState);
+
+
+        params = new HashMap<>();
+        params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType);
+        params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1);
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails);
+        MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl();
+        validatorMock.setConfigurationFileName("VnfGetRunningConfig");
+
+        PowerMockito.mockStatic(OperationalStateValidatorFactory.class);
+        when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock);
+
+        netconfClientPlugin.operationStateValidation(params, ctx);
+
+        Assert.assertTrue("validation process failed", validatorMock.isValidated());
+        Assert.assertEquals(fileContent, client.getLastMessage());
+    }
+
+
+    @Test
+    public void testOperationStateValidationNegativeJsonProcessingNullIllegalStateException() throws Exception {
+        shortInit();
+        SvcLogicContext ctx = new SvcLogicContext();
+        DAOServiceMock daoServiceMock = (DAOServiceMock) dao;
+        daoServiceMock.setConfigFile(fileContent);
+
+        NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH);
+        client.setAnswer(operationalState);
+
+        params = new HashMap<>();
+        params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType);
+        params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1);
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails);
+        MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl();
+        validatorMock.setConfigurationFileName("VnfGetRunningConfig");
+
+        PowerMockito.mockStatic(OperationalStateValidatorFactory.class);
+        when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock);
+        substituteMapper(true);
+
+        try {
+            netconfClientPlugin.operationStateValidation(params, ctx);
+            substituteMapper(false);
+        } catch (APPCException e) {
+            substituteMapper(false);
+            Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE));
+            Assert.assertFalse(validatorMock.isValidated());
+            Assert.assertNull(client.getLastMessage());
+        }
+    }
+
+    @Test
+    public void testOperationStateValidationNegativeConnectionDetailsAreNullNullPointerException() throws Exception {
+        shortInit();
+        SvcLogicContext ctx = new SvcLogicContext();
+        DAOServiceMock daoServiceMock = (DAOServiceMock) dao;
+        daoServiceMock.setConfigFile(fileContent);
+
+        NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH);
+        client.setAnswer(operationalState);
+
+
+        params = new HashMap<>();
+        params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType);
+        params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1);
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, null);
+        MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl();
+        validatorMock.setConfigurationFileName("VnfGetRunningConfig");
+
+        PowerMockito.mockStatic(OperationalStateValidatorFactory.class);
+        when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock);
+        ObjectMapper mapper = PowerMockito.mock(ObjectMapper.class);
+        final NetconfConnectionDetails netconfConnectionDetails = null;
+        when(mapper.readValue(Matchers.anyString(), Matchers.any(Class.class))).thenReturn(netconfConnectionDetails);
+
+
+        try {
+            netconfClientPlugin.operationStateValidation(params, ctx);
+            Assert.assertTrue(false);
+        } catch (APPCException e) {
+            Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE));
+            Assert.assertFalse("validation process failed", validatorMock.isValidated());
+
+        }
+    }
+
+
+    @Test
+    public void testOperationStateValidationNegativeAppcException() throws Exception {
+        shortInit();
+        SvcLogicContext ctx = new SvcLogicContext();
+        DAOServiceMock daoServiceMock = (DAOServiceMock) dao;
+        daoServiceMock.setConfigFile(fileContent);
+
+        NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH);
+        client.setAnswer("wrong");
+
+
+        params = new HashMap<>();
+        params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType);
+        params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1);
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails);
+        MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl();
+        validatorMock.setConfigurationFileName("VnfGetRunningConfig");
+
+        PowerMockito.mockStatic(OperationalStateValidatorFactory.class);
+        when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock);
+
+
+        try {
+            netconfClientPlugin.operationStateValidation(params, ctx);
+            Assert.assertTrue(false);
+        } catch (APPCException e) {
+            Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE));
+            Assert.assertFalse("validation process failed", validatorMock.isValidated());
+
+        }
+    }
+
+
+    @Test
+    public void testOperationStateValidatioConnectionDetailsInParamsAreEmpty() throws Exception {
+        shortInit();
+        SvcLogicContext ctx = new SvcLogicContext();
+        DAOServiceMock daoServiceMock = (DAOServiceMock) dao;
+        daoServiceMock.setConfigFile(fileContent);
+
+        NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH);
+        client.setAnswer(operationalState);
+        ((DAOServiceMock) dao).setConnection(getConnectionDetails());
+
+
+        params = new HashMap<>();
+        params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType);
+        params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1);
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "");
+        MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl();
+        validatorMock.setConfigurationFileName("VnfGetRunningConfig");
+
+        PowerMockito.mockStatic(OperationalStateValidatorFactory.class);
+        when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock);
+
+        netconfClientPlugin.operationStateValidation(params, ctx);
+
+        Assert.assertTrue("validation process failed", validatorMock.isValidated());
+        Assert.assertEquals(fileContent, client.getLastMessage());
+    }
+
+    @Test
+    public void testOperationStateValidatioConnectionDetailsInParamsAreNull() throws Exception {
+        shortInit();
+        SvcLogicContext ctx = new SvcLogicContext();
+        DAOServiceMock daoServiceMock = (DAOServiceMock) dao;
+        daoServiceMock.setConfigFile(fileContent);
+
+        NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH);
+        client.setAnswer(operationalState);
+        ((DAOServiceMock) dao).setConnection(getConnectionDetails());
+
+
+        params = new HashMap<>();
+        params.put(Constants.VNF_TYPE_FIELD_NAME, vnfType);
+        params.put(Constants.VNF_HOST_IP_ADDRESS_FIELD_NAME, host1);
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, null);
+        MockOperationalStateValidatorImpl validatorMock = new MockOperationalStateValidatorImpl();
+        validatorMock.setConfigurationFileName("VnfGetRunningConfig");
+
+        PowerMockito.mockStatic(OperationalStateValidatorFactory.class);
+        when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock);
+
+        netconfClientPlugin.operationStateValidation(params, ctx);
+
+        Assert.assertTrue("validation process failed", validatorMock.isValidated());
+        Assert.assertEquals(fileContent, client.getLastMessage());
+    }
+
+
+    @Test
+    public void testBackupConfiguration() throws Exception {
+        shortInit();
+        SvcLogicContext ctx = new SvcLogicContext();
+        params = new HashMap<>();
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails);
+        NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH);
+        client.setConf(fileContent);
+        netconfClientPlugin.backupConfiguration(params, ctx);
+
+        DAOServiceMock mockdao = (DAOServiceMock) dao;
+        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
+        Date date = new Date();
+        String creationDateExpected = dateFormat.format(date);
+        String creationDateActual = mockdao.getBackupConf().get("creationDate").substring(0, 10);
+
+
+        Assert.assertEquals("wrong configuration in db", fileContent, mockdao.getBackupConf().get("logText"));
+        Assert.assertEquals(creationDateExpected, creationDateActual);
+
+
+    }
+
+
+    @Test
+    public void testBackupConfigurationNegativeDgErrorFieldName() throws Exception {
+        shortInit();
+        SvcLogicContext ctx = new SvcLogicContext();
+        params = new HashMap<>();
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails);
+        NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH);
+        client.setConf(fileContent);
+        try {
+            netconfClientPlugin.backupConfiguration(params, ctx);
+            Assert.assertTrue(false);
+        } catch (APPCException e) {
+            Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE));
+
+            DAOServiceMock mockdao = (DAOServiceMock) dao;
+            Assert.assertNull(mockdao.getBackupConf());
+        }
+
+    }
+
+    @Test
+    public void testGetConfig() throws Exception {
+        fullInit();
+        String entity = "123";
+
+        SvcLogicContext ctx = new SvcLogicContext();
+        ctx.setAttribute("entity", entity);
+
+        params = new HashMap<>();
+        params.put("conf-id", "current");
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails);
+        NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH);
+        client.setConf(fileContent);
+
+
+        netconfClientPlugin.getConfig(params, ctx);
+
+        Assert.assertEquals("Success", ctx.getAttribute("getConfig_Result"));
+        Assert.assertEquals(fileContent, ctx.getAttribute("fullConfig"));
+        Assert.assertNotNull(ctx.getAttribute(entity + ".Configuration"));
+        Assert.assertEquals(fileContent, ctx.getAttribute(entity + ".Configuration"));
+    }
+
+
+    @Test
+    public void testGetConfigNegativeConfigurationNull() throws Exception {
+        fullInit();
+        String entity = "123";
+
+        SvcLogicContext ctx = new SvcLogicContext();
+        ctx.setAttribute("entity", entity);
+
+        params = new HashMap<>();
+        params.put("conf-id", "current");
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails);
+
+
+        netconfClientPlugin.getConfig(params, ctx);
+
+        Assert.assertEquals("failure", ctx.getAttribute("getConfig_Result"));
+        Assert.assertNull(ctx.getAttribute("fullConfig"));
+        Assert.assertNull(ctx.getAttribute(entity + ".Configuration"));
+        Assert.assertNull(ctx.getAttribute(entity + ".Configuration"));
+    }
+
+
+    @Test
+    public void testGetConfigNegativeNotSupportedConfId() throws Exception {
+        fullInit();
+        String entity = "123";
+        SvcLogicContext ctx = new SvcLogicContext();
+        ctx.setAttribute("entity", entity);
+
+        params = new HashMap<>();
+        params.put("conf-id", "current1");
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, connectionDetails);
+
+
+        netconfClientPlugin.getConfig(params, ctx);
+
+        Assert.assertNull(ctx.getAttribute("getConfig_Result"));
+        Assert.assertNull(ctx.getAttribute("fullConfig"));
+        Assert.assertNull(ctx.getAttribute(entity + ".Configuration"));
+        Assert.assertNull(ctx.getAttribute(entity + ".Configuration"));
+    }
+
+    @Test
+    public void testGetConfigNegativeWronjJsonConnectionDetailsException() throws Exception {
+        fullInit();
+        String entity = "123";
+
+        SvcLogicContext ctx = new SvcLogicContext();
+        ctx.setAttribute("entity", entity);
+
+        params = new HashMap<>();
+        params.put("conf-id", "current");
+        params.put(Constants.CONNECTION_DETAILS_FIELD_NAME, "{" + connectionDetails);
+
+
+        try {
+            netconfClientPlugin.getConfig(params, ctx);
+            Assert.assertTrue(false);
+        } catch (APPCException e) {
+            Assert.assertEquals("failure", ctx.getAttribute("getConfig_Result"));
+            Assert.assertNull(ctx.getAttribute("fullConfig"));
+            Assert.assertNull(ctx.getAttribute(entity + ".Configuration"));
+            Assert.assertNull(ctx.getAttribute(entity + ".Configuration"));
+            Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE));
+        }
+
+
+    }
+
+    @Test
+    public void testGetRunningConfig() throws Exception {
+        fullInit();
+        SvcLogicContext ctx = new SvcLogicContext();
+        params = new HashMap<>();
+        params.put("host-ip-address", host);
+        params.put("user-name", username);
+        params.put("password", password);
+        params.put("port-number", String.valueOf(port));
+
+        NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH);
+        client.setConf(fileContent);
+
+        netconfClientPlugin.getRunningConfig(params, ctx);
+
+        Assert.assertEquals("Success", ctx.getAttribute("getRunningConfig_Result"));
+        Assert.assertEquals(fileContent, ctx.getAttribute("running-config"));
+        Assert.assertEquals("success", ctx.getStatus());
+    }
+
+    @Test
+    public void testGetRunningConfigWithoutPortNumberDgErrorFieldNameException() throws Exception {
+        fullInit();
+        SvcLogicContext ctx = new SvcLogicContext();
+        params = new HashMap<>();
+        params.put("host-ip-address", host);
+        params.put("user-name", username);
+        params.put("password", password);
+
+        NetconfClientJschMock client = (NetconfClientJschMock) clientFactory.GetNetconfClient(NetconfClientType.SSH);
+        client.setConf(fileContent);
+
+        try {
+            netconfClientPlugin.getRunningConfig(params, ctx);
+            Assert.assertTrue(false);
+        } catch (APPCException e) {
+            Assert.assertEquals("failure", ctx.getAttribute("getRunningConfig_Result"));
+            Assert.assertNull(ctx.getAttribute("running-config"));
+            Assert.assertNotNull(ctx.getAttribute(DG_OUTPUT_STATUS_MESSAGE));
+        }
+
+
+    }
+
+    @Test
+    public void testGetRunningConfigNegativeConfigurationNull() throws Exception {
+        fullInit();
+        SvcLogicContext ctx = new SvcLogicContext();
+        params = new HashMap<>();
+        params.put("host-ip-address", host);
+        params.put("user-name", username);
+        params.put("password", password);
+        params.put("port-number", String.valueOf(port));
+
+        netconfClientPlugin.getRunningConfig(params, ctx);
+
+        Assert.assertEquals("failure", ctx.getAttribute("getRunningConfig_Result"));
+        Assert.assertNull(ctx.getAttribute("running-config"));
+    }
+
+    @Test
+    public void testValidateMandatoryParamNegativeEmptyParamValue() throws Exception {
+        shortInit();
+        String paramName = "test";
+        String paramValue = "";
+
+        try {
+            netconfClientPlugin.validateMandatoryParam(paramName, paramValue);
+            Assert.assertTrue(false);
+        } catch (Exception e) {
+            Assert.assertTrue(true);
+        }
+    }
+
+    @Test
+    public void testRetrieveConnectionDetails() throws Exception {
+        shortInit();
+        DAOServiceMock daoServiceMock = (DAOServiceMock) dao;
+        daoServiceMock.setConfigFile(fileContent);
+        ConnectionDetails connectionDetails1 = getConnectionDetails();
+        daoServiceMock.setConnection(connectionDetails1);
+
+        NetconfConnectionDetails connectionDetailsActual = netconfClientPlugin.retrieveConnectionDetails(VnfType.VNF);
+
+
+        Assert.assertEquals("wrong host", connectionDetails1.getHost(), connectionDetailsActual.getHost());
+        Assert.assertEquals("wrong password", connectionDetails1.getPassword(), connectionDetailsActual.getPassword());
+        Assert.assertEquals("wrong port", connectionDetails1.getPort(), connectionDetailsActual.getPort());
+        Assert.assertEquals("wrong usename", connectionDetails1.getUsername(), connectionDetailsActual.getUsername());
+    }
+
+
+    @Test
+    public void testRetrieveConnectionDetailsNegativeMissingConfiguration() throws Exception {
+        shortInit();
+        DAOServiceMock daoServiceMock = (DAOServiceMock) dao;
+        daoServiceMock.setConfigFile(fileContent);
+        ConnectionDetails connectionDetails1 = getConnectionDetails();
+        daoServiceMock.setConnection(connectionDetails1);
+
+        NetconfConnectionDetails connectionDetailsActual = null;
+        try {
+            connectionDetailsActual = netconfClientPlugin.retrieveConnectionDetails(VnfType.MOCK);
+            Assert.assertTrue(false);
+        } catch (APPCException e) {
+            Assert.assertNull(connectionDetailsActual);
+        }
+
+
+    }
+
+    @Test
+    public void testRetrieveConfigurationFileContent() throws Exception {
+        shortInit();
+
+        DAOServiceMock daoServiceMock = (DAOServiceMock) dao;
+        daoServiceMock.setConfigFile(fileContent);
+
+        Assert.assertEquals("wrong config in a database", fileContent, netconfClientPlugin.retrieveConfigurationFileContent("VnfGetRunningConfig"));
+    }
+
+    private ConnectionDetails getConnectionDetails() {
+
+        ConnectionDetails connectionDetails = new ConnectionDetails();
+        connectionDetails.setPassword(password);
+        connectionDetails.setPort(port);
+        connectionDetails.setUsername(username);
+        connectionDetails.setHost(host);
+        return connectionDetails;
+    }
+
+
+    private void initDao() throws NoSuchFieldException, IllegalAccessException {
+        dao = new DAOServiceMock();
+        PowerMockito.mockStatic(FrameworkUtil.class);
+        when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService);
+        when(bundleService.getBundleContext()).thenReturn(bundleContext);
+        when(bundleContext.getServiceReference(NetconfDataAccessService.class)).thenReturn(sref1);
+        when(bundleContext.getService(sref1)).thenReturn(dao);
+
+
+    }
+
+    private void fullInit() throws NoSuchFieldException, IllegalAccessException {
+        initClientFactory();
+        initClientFactory2();
+        initDao();
+        netconfClientPlugin = new NetconfClientPluginImpl();
+        netconfClientPlugin.setDao(this.dao);
+    }
+
+    private void shortInit() throws NoSuchFieldException, IllegalAccessException {
+        initClientFactory();
+        initDao();
+        netconfClientPlugin = new NetconfClientPluginImpl();
+        netconfClientPlugin.setDao(this.dao);
+    }
+
+    private void initClientFactory() throws NoSuchFieldException, IllegalAccessException {
+
+        PowerMockito.mockStatic(FrameworkUtil.class);
+        when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService);
+        when(bundleService.getBundleContext()).thenReturn(bundleContext);
+        when(bundleContext.getServiceReference(NetconfClientFactory.class)).thenReturn(sref2);
+        when(bundleContext.getService(sref2)).thenReturn(clientFactory);
+
+    }
+
+    private void initClientFactory2() {
+        PowerMockito.mockStatic(FrameworkUtil.class);
+        when(FrameworkUtil.getBundle(Matchers.any(Class.class))).thenReturn(bundleService);
+        when(bundleService.getBundleContext()).thenReturn(bundleContext);
+        when(bundleContext.getServiceReference(Matchers.anyString())).thenReturn(sref3);
+        when(bundleContext.getService(sref3)).thenReturn(clientFactory);
+    }
+
+    private void substituteMapper(boolean command) throws NoSuchFieldException, IllegalAccessException {
+        ObjectMapper mapper = new ObjectMapperMock();
+        ObjectMapper mapper2 = new ObjectMapper();
+        Field field = NetconfClientPluginImpl.class.getDeclaredField("mapper");
+        field.setAccessible(true);
+        if (command) {
+            field.set(netconfClientPlugin, mapper);
+        } else {
+            field.set(netconfClientPlugin, mapper2);
+        }
+    }
+
+}
index 9082e0d..43396d0 100644 (file)
@@ -9,6 +9,11 @@
        <artifactId>appc-dg-shared</artifactId>
        <packaging>pom</packaging>
 
+    <properties>
+        <jackson-yaml-version>2.8.1</jackson-yaml-version>
+        <snakeyaml.version>1.15</snakeyaml.version>
+    </properties>
+
        <modules>
                <module>appc-dg-common</module>
                <module>appc-dg-dependency-model</module>
index cdff419..44588d0 100644 (file)
@@ -35,10 +35,10 @@ public enum LCMCommandStatus {
 
     ACCEPTED(100,"ACCEPTED - request accepted"),
 
-    //ERROR(2xx) â€“ request can’t be handled due to some technical error
+    //ERROR(2xx) - request can't be handled due to some technical error
     UNEXPECTED_ERROR(200,"UNEXPECTED ERROR - ${errorMsg}"),
 
-    //REJECT(3xx) â€“ request has been rejected due to some business reason (e.g. no such service-instance-id, command is not supported, etc)
+    //REJECT(3xx) - request has been rejected due to some business reason (e.g. no such service-instance-id, command is not supported, etc)
     REJECTED(300,"REJECTED - ${errorMsg}"),
     INVALID_INPUT_PARAMETER(301,"INVALID INPUT PARAMETER - ${errorMsg}"),// TODO 77777777 to support "${paramName} with invalid value ${paramValue}"
     MISSING_MANDATORY_PARAMETER(302,"MISSING MANDATORY PARAMETER - Parameter/s ${paramName} is/are missing" ),
@@ -57,7 +57,7 @@ public enum LCMCommandStatus {
     SUCCESS(400,"SUCCESS - request has been processed successfully"),
 
 
-    //        FAILURE(5xx) â€“ request processing results with failure. The FAILURE response is always transmitted asynchronously, via DMaaP.
+    //        FAILURE(5xx) - request processing results with failure. The FAILURE response is always transmitted asynchronously, via DMaaP.
     DG_FAILURE(401,"DG FAILURE - ${errorMsg}"),
     NO_TRANSITION_DEFINE_FAILURE(402,"NO TRANSITION DEFINE - No Transition Defined for ${actionName} action and ${currentState} state"),
     UPDATE_AAI_FAILURE(403,"UPDATE_AAI_FAILURE - failed to update AAI. ${errorMsg}"),
index 55499d7..5054d34 100644 (file)
@@ -34,6 +34,7 @@ import java.util.concurrent.TimeUnit;
 
 import org.apache.commons.lang.ObjectUtils;
 import org.openecomp.appc.domainmodel.lcm.RuntimeContext;
+import org.openecomp.appc.domainmodel.lcm.ActionLevel;
 import org.openecomp.appc.exceptions.APPCException;
 import org.openecomp.appc.executionqueue.ExecutionQueueService;
 import org.openecomp.appc.executionqueue.impl.ExecutionQueueServiceFactory;
@@ -96,22 +97,6 @@ public class CommandExecutorImpl implements CommandExecutor {
         }
         RuntimeContext commandRequest;
         commandRequest = commandExecutorInput;
-        /*
-        CommandRequest commandRequest;
-
-        switch(commandExecutorInput.getRequestContext().getAction()){
-            case Sync:
-            case Audit:
-            case ConfigBackup:
-            case ConfigBackupDelete:
-            case ConfigExport:
-                commandRequest = new LCMReadOnlyCommandRequest(commandExecutorInput);
-                break;
-            default:
-                commandRequest = new LCMCommandRequest(commandExecutorInput);
-                break;
-        }
-        */
         if (logger.isTraceEnabled()) {
             logger.trace("Exiting from getCommandRequest with (CommandRequest = "+ ObjectUtils.toString(commandRequest)+")");
         }
@@ -125,7 +110,7 @@ public class CommandExecutorImpl implements CommandExecutor {
         }
         try {
             String action = request.getRequestContext().getAction().name();
-            CommandTask commandTask = executionTaskFactory.getExecutionTask(action, request);
+            CommandTask commandTask = executionTaskFactory.getExecutionTask(request);
             long remainingTTL = getRemainingTTL(request);
             executionQueueService.putMessage(commandTask,remainingTTL, TimeUnit.MILLISECONDS);
         } catch (Exception e) {
@@ -144,5 +129,16 @@ public class CommandExecutorImpl implements CommandExecutor {
         return ChronoUnit.MILLIS.between(Instant.now(), requestTimestamp.plusSeconds(ttl));
     }
 
+    private CommandTask getMessageExecutor(RuntimeContext request){
+        if (logger.isTraceEnabled()) {
+            logger.trace("Entering to getMessageExecutor with command = "+ request);
+        }
+        CommandTask executionTask = executionTaskFactory.getExecutionTask(request);
+        if (logger.isTraceEnabled()) {
+            logger.trace("Exiting from getMessageExecutor");
+        }
+        return executionTask;
+    }
+
 
 }
index 571f51e..c5590f9 100644 (file)
@@ -25,6 +25,7 @@
 package org.openecomp.appc.executor.impl;
 
 
+import org.openecomp.appc.domainmodel.lcm.ActionLevel;
 import org.openecomp.appc.domainmodel.lcm.RuntimeContext;
 import org.openecomp.appc.domainmodel.lcm.VNFOperation;
 import org.openecomp.appc.lifecyclemanager.LifecycleManager;
@@ -35,7 +36,12 @@ import org.openecomp.appc.workflow.WorkFlowManager;
 
 
 public class CommandTaskFactory {
-    private RequestHandler requestHandler;
+
+//    private LCMCommandTask lcmCommandTask;
+//    private LCMReadonlyCommandTask LCMReadonlyCommandTask;
+
+    private RequestHandler vnfRequestHandler;
+    private RequestHandler vmRequestHandler;
     private WorkFlowManager workflowManager;
     private LifecycleManager lifecyclemanager;
 
@@ -44,8 +50,12 @@ public class CommandTaskFactory {
         this.workflowManager = workflowManager;
     }
 
-    public void setRequestHandler(RequestHandler requestHandler) {
-        this.requestHandler = requestHandler;
+    public void setVnfRequestHandler(RequestHandler vnfRequestHandler) {
+        this.vnfRequestHandler = vnfRequestHandler;
+    }
+
+    public void setVmRequestHandler(RequestHandler vmRequestHandler) {
+        this.vmRequestHandler = vmRequestHandler;
     }
 
     public void setLifecyclemanager(LifecycleManager lifecyclemanager) {
@@ -53,14 +63,30 @@ public class CommandTaskFactory {
     }
 
 
-    public synchronized CommandTask getExecutionTask(String action, RuntimeContext commandRequest){
-        if (VNFOperation.Sync.toString().equals(action) || VNFOperation.Audit.toString().equals(action) || VNFOperation.ConfigBackup.toString().equals(action) ||
-                VNFOperation.ConfigBackupDelete.toString().equals(action) || VNFOperation.ConfigExport.toString().equals(action)){
-            return new LCMReadonlyCommandTask(commandRequest, requestHandler,workflowManager);
+    public synchronized CommandTask getExecutionTask(RuntimeContext runtimeContext){
+        String action = runtimeContext.getRequestContext().getAction().name();
+        ActionLevel actionLevel = runtimeContext.getRequestContext().getActionLevel();
+        RequestHandler requestHandler = readRequestHandler(actionLevel);
+        if(ActionLevel.VM.equals(actionLevel)){
+            return new LCMReadonlyCommandTask(runtimeContext,requestHandler,workflowManager);
+        }
+        if (VNFOperation.Sync.toString().equals(action) ||
+                VNFOperation.Audit.toString().equals(action) ||
+                VNFOperation.ConfigBackup.toString().equals(action) ||
+                VNFOperation.ConfigBackupDelete.toString().equals(action) ||
+                VNFOperation.ConfigExport.toString().equals(action)){
+            return new LCMReadonlyCommandTask(runtimeContext,requestHandler,workflowManager);
         }else {
-            return new LCMCommandTask(commandRequest, requestHandler,workflowManager,
+            return new LCMCommandTask(runtimeContext,requestHandler,workflowManager,
                     lifecyclemanager);
         }
     }
 
+    private RequestHandler readRequestHandler(ActionLevel actionLevel) {
+        if (ActionLevel.VM.equals(actionLevel)) {
+            return vmRequestHandler;
+        }
+        return vnfRequestHandler;
+    }
+
 }
index 46a15f1..7aa4cd1 100644 (file)
 package org.openecomp.appc.executor.impl;
 
 import org.openecomp.appc.domainmodel.lcm.RuntimeContext;
+import org.openecomp.appc.domainmodel.lcm.ActionLevel;
 import org.openecomp.appc.executionqueue.MessageExpirationListener;
 import org.openecomp.appc.requesthandler.RequestHandler;
 
 
 public class ExpiredMessageHandler<M> implements MessageExpirationListener<M>{
-    private RequestHandler requestHandler;
+    private RequestHandler vnfRequestHandler;
+
+    private RequestHandler vmRequestHandler;
 
     public ExpiredMessageHandler(){
 
     }
 
-    public void setRequestHandler(RequestHandler requestHandler) {
-        this.requestHandler = requestHandler;
+    public void setVnfRequestHandler(RequestHandler vnfRequestHandler) {
+        this.vnfRequestHandler = vnfRequestHandler;
+    }
+
+    public void setVmRequestHandler(RequestHandler vmRequestHandler) {
+        this.vmRequestHandler = vmRequestHandler;
     }
 
     @Override
     public void onMessageExpiration(M message) {
         RuntimeContext commandRequest = (RuntimeContext)message;
+        RequestHandler requestHandler = readRequestHandler(commandRequest);
         requestHandler.onRequestTTLEnd(commandRequest, true);
     }
+
+    private RequestHandler readRequestHandler(RuntimeContext runtimeContext) {
+        if(ActionLevel.VM.equals(runtimeContext.getRequestContext().getActionLevel())){
+            return vmRequestHandler;
+        }
+        return vnfRequestHandler;
+    }
 }
index bba735a..aadfd3a 100644 (file)
@@ -55,10 +55,10 @@ import org.osgi.framework.FrameworkUtil;
 import org.osgi.framework.ServiceReference;
 import org.slf4j.MDC;
 
-import java.net.InetAddress;
 import com.att.eelf.configuration.EELFLogger;
 import com.att.eelf.configuration.EELFManager;
 
+import java.net.InetAddress;
 import static com.att.eelf.configuration.Configuration.*;
 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
index fd99cbe..f84e972 100644 (file)
     </bean>
 
     <bean id="CommandExecutionTaskFactory" class="org.openecomp.appc.executor.impl.CommandTaskFactory" scope="singleton" >
-        <property name="requestHandler" ref="RequestHandlerRef" />
+        <property name="vnfRequestHandler" ref="vnfRequestHandlerService" />
+        <property name="vmRequestHandler" ref="vmRequestHandlerService"/>
         <property name="workflowManager" ref="WorkFlowManagerRef" />
         <property name="lifecyclemanager" ref="LifecyclemanagerRef" />
     </bean>
 
     <bean id="expiredMessageHandlerBean" class="org.openecomp.appc.executor.impl.ExpiredMessageHandler"
           scope="singleton">
-        <property name="requestHandler" ref="RequestHandlerRef" />
+        <property name="vnfRequestHandler" ref="vnfRequestHandlerService" />
+        <property name="vmRequestHandler" ref="vmRequestHandlerService"/>
     </bean>
 
        <reference id="WorkFlowManagerRef" availability="mandatory" activation="eager" interface="org.openecomp.appc.workflow.WorkFlowManager" />
-       <reference id="RequestHandlerRef" availability="optional" activation="eager" interface="org.openecomp.appc.requesthandler.RequestHandler" />
+       <reference id="vnfRequestHandlerService" availability="optional" activation="eager" interface="org.openecomp.appc.requesthandler.RequestHandler" filter="(level=VNF)" />
+    <reference id="vmRequestHandlerService" availability="optional" activation="eager" interface="org.openecomp.appc.requesthandler.RequestHandler" filter="(level=VM)" />
     <reference id="LifecyclemanagerRef" availability="mandatory" activation="eager" interface="org.openecomp.appc.lifecyclemanager.LifecycleManager" />
 
     <service id="commandExecutorService" interface="org.openecomp.appc.executor.CommandExecutor" ref="commandExecutorBean"/>
index ee28fa8..460f0e7 100644 (file)
@@ -123,16 +123,23 @@ public class TestCommandExecutionTask {
                factory = new CommandTaskFactory();
                factory.setLifecyclemanager(lifecyclemanager);
                factory.setWorkflowManager(workflowManager);
-               factory.setRequestHandler(requestHandler);
+               factory.setVnfRequestHandler(requestHandler);
                Mockito.when(workflowManager.executeWorkflow((WorkflowRequest)anyObject())).thenReturn(getWorkflowResponse () );
        }
 
 
        @Test
        public void testFactory(){
-               CommandTask task = factory.getExecutionTask("Configure", null);
+               CommandTask task;
+               Instant timeStamp = Instant.now();
+               String requestId = "1";
+               RuntimeContext commandExecutorInputConfigure = pouplateCommandExecutorInput("FIREWALL", 30, "1.0",
+                               timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure,"15","") ;
+               task = factory.getExecutionTask(commandExecutorInputConfigure);
                assertEquals(LCMCommandTask.class,task.getClass() );
-               task = factory.getExecutionTask("Sync", null);
+               RuntimeContext commandExecutorInputSync = pouplateCommandExecutorInput("FIREWALL", 30, "1.0",
+                               timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync,"15","") ;
+               task = factory.getExecutionTask(commandExecutorInputSync);
                assertEquals(LCMReadonlyCommandTask.class,task.getClass() );
 
        }
@@ -215,6 +222,22 @@ public class TestCommandExecutionTask {
        }
 
 
+       private RuntimeContext getConfigCommandRequest(String vnfType , Integer ttl , Instant timeStamp, String requestId,
+                                                                                                                         Map<String,Object> flags, VNFOperation command , String vnfId, String vnfVersion ){
+
+               RuntimeContext commandExecutorInput = pouplateCommandExecutorInput(vnfType, ttl, vnfVersion, timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "", command, vnfId, "");
+
+               return commandExecutorInput;
+       }
+
+       private RuntimeContext getLCMCommandRequest(String vnfType , Integer ttl ,Instant timeStamp, String requestId,
+                                                                                                  Map<String,Object> flags, VNFOperation command , String vnfId, String vnfVersion ){
+
+               RuntimeContext commandExecutorInput = pouplateCommandExecutorInput(vnfType, ttl, vnfVersion, timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "", command, vnfId, "");
+
+               return commandExecutorInput;
+       }
+
        public WorkflowResponse getWorkflowResponse (){
                WorkflowResponse wfResponse = new WorkflowResponse();
                ResponseContext responseContext = createResponseContextWithSuObjects();
@@ -275,4 +298,3 @@ public class TestCommandExecutionTask {
        }
 
 }
-
index 30b7317..fa9257f 100644 (file)
@@ -24,7 +24,7 @@
 
 package org.openecomp.appc.executor;
 /**
- * 
+ *
  */
 
 
@@ -43,31 +43,41 @@ import org.openecomp.appc.domainmodel.lcm.VNFContext;
 import org.openecomp.appc.domainmodel.lcm.VNFOperation;
 import org.openecomp.appc.exceptions.APPCException;
 import org.openecomp.appc.executionqueue.ExecutionQueueService;
-import org.openecomp.appc.executor.impl.CommandExecutorImpl;
-import org.openecomp.appc.executor.impl.CommandTaskFactory;
-import org.openecomp.appc.executor.impl.LCMCommandTask;
-import org.openecomp.appc.executor.impl.LCMReadonlyCommandTask;
+import org.openecomp.appc.executor.impl.*;
 import org.openecomp.appc.lifecyclemanager.LifecycleManager;
 import org.openecomp.appc.requesthandler.RequestHandler;
 import org.openecomp.appc.workflow.WorkFlowManager;
+import org.powermock.api.mockito.PowerMockito;
+
+import java.util.Date;
+import java.util.concurrent.TimeUnit;
+
+import static junit.framework.Assert.assertTrue;
+import static org.powermock.api.support.membermodification.MemberMatcher.method;
 
 
 @SuppressWarnings("deprecation")
 public class TestCommandExecutor {
 
-               private static final String TTL_FLAG= "TTL";
-               private static final String API_VERSION= "2.0.0";
-               private static final String ORIGINATOR_ID= "1";
+       private static final String TTL_FLAG= "TTL";
+       private static final String API_VERSION= "2.0.0";
+       private static final String ORIGINATOR_ID= "1";
 
-       CommandExecutorImpl commandExecutor;
+       private CommandExecutorImpl commandExecutor;
 
-       CommandTaskFactory executionTaskFactory;
+       private CommandTaskFactory executionTaskFactory;
 
        private RequestHandler requestHandler;
        private WorkFlowManager workflowManager;
        private LifecycleManager lifecyclemanager;
 
        private ExecutionQueueService executionQueueService;
+       private Instant timeStamp = Instant.now();
+       private String requestId = "1";
+       private RuntimeContext commandExecutorInputConfigure = pouplateCommandExecutorInput("FIREWALL", 30000, "1.0",
+                       timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure,"15","") ;
+       private RuntimeContext commandExecutorInputSync = pouplateCommandExecutorInput("FIREWALL", 30, "1.0",
+                       timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync,"15","") ;
 
        @Before
        public void init()throws Exception {
@@ -82,16 +92,18 @@ public class TestCommandExecutor {
                commandExecutor.setExecutionTaskFactory(executionTaskFactory);
                commandExecutor.setExecutionQueueService(executionQueueService);
                LCMCommandTask lcmCommandTask = Mockito.mock(LCMCommandTask.class);
-               LCMReadonlyCommandTask LCMReadonlyCommandTask = Mockito.mock(LCMReadonlyCommandTask.class);
-               Mockito.doReturn(lcmCommandTask).when(executionTaskFactory).getExecutionTask("Configure", null);
-               Mockito.doReturn(LCMReadonlyCommandTask).when(executionTaskFactory).getExecutionTask("Sync", null);
+               LCMReadonlyCommandTask lCMReadonlyCommandTask = Mockito.mock(LCMReadonlyCommandTask.class);
+
+               Mockito.when(executionTaskFactory.getExecutionTask(commandExecutorInputConfigure)).thenReturn(lcmCommandTask);
+               Mockito.when(executionTaskFactory.getExecutionTask(commandExecutorInputSync)).thenReturn(lCMReadonlyCommandTask);
+
 //             Mockito.when(executionQueueService.putMessage((Runnable) Mockito.anyObject(),Mockito.anyLong(),(TimeUnit)Mockito.anyObject())).thenReturn(true);
 
        }
-               
+
 
        @Test
-       public void testPositiveFlow_LCM(){
+       public void testPositiveFlow_LCM() throws Exception {
                //Map <String,Object> flags = setTTLInFlags("30");
                String requestId = "1";
                RuntimeContext commandExecutorInput = pouplateCommandExecutorInput("FIREWALL", 30, "1.0", Instant.now(), API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure, "15", "") ;
@@ -153,4 +165,3 @@ public class TestCommandExecutor {
 
 
 }
-
diff --git a/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ActionLevel.java b/appc-dispatcher/appc-dispatcher-common/domain-model-lib/src/main/java/org/openecomp/appc/domainmodel/lcm/ActionLevel.java
new file mode 100644 (file)
index 0000000..67d0fab
--- /dev/null
@@ -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=========================================================
+ */
+
+package org.openecomp.appc.domainmodel.lcm;
+
+public enum ActionLevel {
+    VNF,VM,VNFC
+}
index e30c9d0..9a3dab1 100644 (file)
@@ -33,6 +33,7 @@ public class RequestContext {
     private CommonHeader commonHeader;
     private ActionIdentifiers actionIdentifiers;
     private VNFOperation action;
+    private ActionLevel actionLevel;
     private String payload;
     private Map<String, String> additionalContext;
 
@@ -83,12 +84,21 @@ public class RequestContext {
         this.additionalContext.put(key, value);
     }
 
+    public ActionLevel getActionLevel() {
+        return actionLevel;
+    }
+
+    public void setActionLevel(ActionLevel actionLevel) {
+        this.actionLevel = actionLevel;
+    }
+
     @Override
     public String toString() {
         return "RequestContext{" +
                 "commonHeader=" + commonHeader +
                 ", actionIdentifiers=" + actionIdentifiers +
                 ", action=" + action +
+                ", actionLevel = " + actionLevel +
                 ", payload='" + payload + '\'' +
                 ", additionalContext=" + additionalContext +
                 '}';
index 8da6519..3c1c483 100644 (file)
@@ -32,7 +32,6 @@
         <dependency>
             <groupId>com.att.eelf</groupId>
             <artifactId>eelf-core</artifactId>
-            <version>${eelf.version}</version>
         </dependency>
         <dependency>
             <groupId>junit</groupId>
index ec927c3..c2f79ec 100644 (file)
 package org.openecomp.appc.statemachine;
 
 
-import org.junit.Assert;
 import org.junit.Test;
-import org.openecomp.appc.statemachine.impl.StateMachineFactory;
-import org.openecomp.appc.statemachine.objects.*;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
+import org.openecomp.appc.statemachine.objects.InvalidInputException;
 
 
 public class TestStateMachine {
index c3b098f..dc255cd 100644 (file)
@@ -55,7 +55,7 @@ public class Constants {
     public static final String REQUEST_ID_FIELD_NAME = "REQUEST_ID";
     public static final String CREATION_DATE_FIELD_NAME = "CREATION_DATE";
     public static final String LOG_FIELD_NAME = "LOG";
-    public static final String ASDC_ARTIFACTS_TABLE_NAME = "ASDC_ARTIFACTS";
+    public static final String ASDC_ARTIFACTS = "ASDC_ARTIFACTS";
 
     // input fields names
     public static final String PAYLOAD = "payload";
index 1c3d55c..0f14b2e 100644 (file)
 
 package org.openecomp.appc.licmgr;
 
-import java.util.Map;
-
 import org.openecomp.appc.licmgr.exception.DataAccessException;
-import org.openecomp.sdnc.sli.resource.dblib.DbLibService;
+
+import java.util.Map;
 
 
 @SuppressWarnings("JavaDoc")
@@ -48,10 +47,4 @@ public interface LicenseDataAccessService {
      */
     Map<String,String> retrieveLicenseModelData(String vnfType, String vnfVersion, String... fields) throws DataAccessException;
 
-    /**
-     *
-     * @param parameters parameters to store in artifacts table
-     * @throws RuntimeException
-     */
-    void storeArtifactPayload(Map<String, String> parameters) throws RuntimeException;
 }
index ba874b2..144cfb6 100644 (file)
@@ -24,8 +24,6 @@
 
 package org.openecomp.appc.licmgr;
 
-import java.util.Map;
-
 import org.openecomp.appc.licmgr.exception.DataAccessException;
 import org.openecomp.appc.licmgr.objects.LicenseModel;
 
@@ -42,21 +40,5 @@ public interface LicenseManager {
      */
     LicenseModel retrieveLicenseModel(String vnfType, String vnfVersion) throws DataAccessException;
 
-    /**
-     *
-     * @param vnfType resource name
-     * @param vnfVersion resource version
-     * @return map contains requested fields as Strings
-     * @throws RuntimeException
-     */
-    Map<String,String> retrieveLicenseModelData(String vnfType, String vnfVersion, String... fields) throws
-                    DataAccessException;
-
-    /**
-     *
-     * @param parameters parameters to store in artifacts table
-     * @throws RuntimeException
-     */
-    void storeArtifactPayload(Map<String, String> parameters) throws RuntimeException;
 
 }
index ef252cc..8e999c4 100644 (file)
@@ -87,7 +87,7 @@ public class LicenseDataAccessServiceImpl implements LicenseDataAccessService {
                     result.put(field, data.getString(field));
                 }
             } else {
-                String msg = "Missing license model for VNF_TYPE: " + vnfType + " and VNF_VERSION: " + vnfVersion + " in table " + Constants.ASDC_ARTIFACTS_TABLE_NAME;
+                String msg = "Missing license model for VNF_TYPE: " + vnfType + " and VNF_VERSION: " + vnfVersion + " in table " + Constants.ASDC_ARTIFACTS;
                 logger.info(msg);
             }
         } catch (SQLException e) {
@@ -99,70 +99,10 @@ public class LicenseDataAccessServiceImpl implements LicenseDataAccessService {
     }
 
     private String buildQueryStatement() {
-        return "select * " + "from " + Constants.ASDC_ARTIFACTS_TABLE_NAME + " " +
+        return "select * " + "from " + Constants.ASDC_ARTIFACTS + " " +
             "where " + ASDC_ARTIFACTS_FIELDS.RESOURCE_NAME.name() + " = ?" +
              " AND " + ASDC_ARTIFACTS_FIELDS.RESOURCE_VERSION.name() + " = ?" +
              " AND " + ASDC_ARTIFACTS_FIELDS.ARTIFACT_TYPE.name() + " = ?";
     }
 
-    /**
-     * Implementation of storeArtifactPayload()
-     * @see LicenseDataAccessService
-     */
-    @Override
-    public void storeArtifactPayload(Map<String, String> parameters) throws RuntimeException {
-
-        if(parameters == null || parameters.isEmpty()) {
-            throw new RuntimeException("No parameters for insert are provided");
-        }
-
-        String insertStr = "INSERT INTO " + Constants.ASDC_ARTIFACTS_TABLE_NAME + "(";
-        String valuesStr = "VALUES(";
-        String insertStatementStr;
-
-        ArrayList<String> params = new ArrayList<>();
-        boolean firstTime = true;
-        for(Map.Entry<String, String> entry : parameters.entrySet()) {
-            if(!firstTime) {
-                insertStr += ",";
-                valuesStr += ",";
-            }
-            else {
-                firstTime = false;
-            }
-            insertStr += entry.getKey();
-            valuesStr += "?";
-
-            params.add(entry.getValue());
-        }
-
-        insertStr += ")";
-        valuesStr += ")";
-        insertStatementStr = insertStr + " " + valuesStr;
-
-        executeStoreArtifactPayload(insertStatementStr, params);
-    }
-
-    /**
-     * Exexutes insert statement for artifact payload
-     * @param insertStatementStr
-     * @param params
-     * @throws RuntimeException
-     */
-    private void executeStoreArtifactPayload(String insertStatementStr, ArrayList<String> params) throws RuntimeException {
-
-        try {
-            logger.info("used schema=" + this.schema);
-            logger.info("insert statement=" + insertStatementStr);
-
-            dbLibService.writeData(insertStatementStr, params, this.schema);
-
-            logger.info("finished to execute insert");
-
-        } catch (SQLException e) {
-            logger.error("Storing Artifact payload failed - " + insertStatementStr);
-            throw new RuntimeException("Storing Artifact payload failed - " + insertStatementStr);
-        }
-    }
-
 }
index 0d7da67..9f3db5a 100644 (file)
@@ -65,18 +65,6 @@ public class LicenseManagerImpl implements LicenseManager {
         return licenseModel;
     }
 
-    @Override
-    public Map<String, String> retrieveLicenseModelData(String vnfType, String vnfVersion, String... fields)  throws DataAccessException {
-
-        Map<String,String> resultMap = DAService.retrieveLicenseModelData(vnfType, vnfVersion, fields);
-        return resultMap;
-    }
-
-    @Override
-    public void storeArtifactPayload(Map<String, String> parameters) throws RuntimeException {
-
-        DAService.storeArtifactPayload(parameters);
-    }
 
     private static LicenseModel convert(String xml) {
 
index 2dad318..92adefe 100644 (file)
@@ -24,9 +24,6 @@
 
 package org.openecomp.appc.licmgr;
 
-import java.util.Map;
-
-import org.openecomp.appc.licmgr.LicenseManager;
 import org.openecomp.appc.licmgr.exception.DataAccessException;
 import org.openecomp.appc.licmgr.objects.LicenseModel;
 
@@ -44,15 +41,6 @@ public class LicenseManagerMock implements LicenseManager {
         }
     }
 
-    @Override public Map<String, String> retrieveLicenseModelData(String vnfType, String vnfVersion, String... fields)
-                    throws DataAccessException {
-        return null;
-    }
-
-    @Override public void storeArtifactPayload(Map<String, String> parameters) throws RuntimeException {
-
-    }
-
     public void storeLicenseModel(LicenseModel licenseModel){
         this.licenseModel = licenseModel;
 
index c930807..ec44e7c 100644 (file)
  */
 
 package org.openecomp.appc.licmgr;
-import java.util.HashMap;
-import java.util.Map;
 
-import org.openecomp.appc.licmgr.LicenseDataAccessService;
 import org.openecomp.appc.licmgr.exception.DataAccessException;
-import org.openecomp.sdnc.sli.resource.dblib.DbLibService;
+import java.util.HashMap;
+import java.util.Map;
 
 class LicenseServiceMock implements LicenseDataAccessService {
 
@@ -52,7 +50,4 @@ class LicenseServiceMock implements LicenseDataAccessService {
         return null;
     }
 
-    @Override
-    public void storeArtifactPayload(Map<String, String> parameters) throws DataAccessException {
-    }
 }
index 859e4a5..00bb686 100644 (file)
@@ -45,7 +45,6 @@
         <dependency>
             <groupId>com.att.eelf</groupId>
             <artifactId>eelf-core</artifactId>
-            <version>${eelf.version}</version>
         </dependency>
         <dependency>
             <groupId>org.openecomp.appc</groupId>
index 3ac4b60..cad3db7 100644 (file)
@@ -36,7 +36,7 @@ public class MetadataReader {
 
     private enum VNFStates {
         Not_Instantiated, Instantiated, Configuring, Configured, Testing, Tested, Rebuilding, Restarting, Starting, Error, Running, Unknown, Terminating, Stopping, Stopped,
-        Backing_Up, Snapshotting, Software_Uploading, Upgrading, Rollbacking, Licensing, Migrating, Evacuating , NOT_ORCHESTRATED("NOT ORCHESTRATED");
+        Backing_Up, Snapshotting, Software_Uploading, Upgrading, Rollbacking, Licensing, Migrating, Evacuating , NOT_ORCHESTRATED("NOT ORCHESTRATED"),Created;
 
         String stateName;
 
@@ -49,7 +49,7 @@ public class MetadataReader {
         }
 
         public String toString(){
-            return this.stateName;
+            return this.stateName.toLowerCase();
         }
     }
 
@@ -80,6 +80,7 @@ public class MetadataReader {
 
         State MIGRATING = new State(VNFStates.Migrating.toString());
         State EVACUATING = new State(VNFStates.Evacuating.toString());
+        State CREATED= new State(VNFStates.Created.toString());
 
         Event CONFIGURE = new Event(VNFOperation.Configure.toString());
         Event HEALTHCHECK = new Event(VNFOperation.HealthCheck.toString());
@@ -138,6 +139,7 @@ public class MetadataReader {
         builder = builder.addState(MIGRATING);
         builder = builder.addState(EVACUATING);
         builder = builder.addState(NOT_ORCHESTRATED);
+        builder = builder.addState(CREATED);
 
         builder = builder.addEvent(CONFIGURE);
         builder = builder.addEvent(TEST);
@@ -169,6 +171,27 @@ public class MetadataReader {
         builder = builder.addEvent(CONFIG_EXPORT);
 
         builder = builder.addTransition(NOT_ORCHESTRATED,CONFIGURE,CONFIGURING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,TEST,TESTING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,START,STARTING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,TERMINATE,TERMINATING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,RESTART,RESTARTING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,REBUILD,REBUILDING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,STOP,STOPPING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,CONFIG_MODIFY,CONFIGURING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,CONFIG_SCALEOUT,CONFIGURING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,CONFIG_RESTORE,CONFIGURING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,HEALTHCHECK,TESTING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,BACKUP,BACKING_UP);
+        builder = builder.addTransition(NOT_ORCHESTRATED,SNAPSHOT,SNAPSHOTTING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,SOFTWARE_UPLOAD,SOFTWARE_UPLOADING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,LIVE_UPGRADE,UPGRADING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,ROLLBACK,ROLLBACKING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,MIGRATE,MIGRATING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,EVACUATE,EVACUATING);
+        builder = builder.addTransition(NOT_ORCHESTRATED,LOCK,NOT_ORCHESTRATED);
+        builder = builder.addTransition(NOT_ORCHESTRATED,UNLOCK,NOT_ORCHESTRATED);
+        builder = builder.addTransition(NOT_ORCHESTRATED,CHECKLOCK,NOT_ORCHESTRATED);
+        builder = builder.addTransition(NOT_ORCHESTRATED,CONFIG_BACKUP,NOT_ORCHESTRATED);
 
         builder = builder.addTransition(INSTANTIATED,CONFIGURE,CONFIGURING);
         builder = builder.addTransition(INSTANTIATED,TEST,TESTING);
@@ -219,6 +242,29 @@ public class MetadataReader {
         builder = builder.addTransition(CONFIGURED,CONFIG_BACKUP_DELETE,CONFIGURED);
         builder = builder.addTransition(CONFIGURED,CONFIG_EXPORT,CONFIGURED);
 
+        builder = builder.addTransition(CREATED,CONFIGURE,CONFIGURING);
+        builder = builder.addTransition(CREATED,TEST,TESTING);
+        builder = builder.addTransition(CREATED,START,STARTING);
+        builder = builder.addTransition(CREATED,TERMINATE,TERMINATING);
+        builder = builder.addTransition(CREATED,RESTART,RESTARTING);
+        builder = builder.addTransition(CREATED,REBUILD,REBUILDING);
+        builder = builder.addTransition(CREATED,STOP,STOPPING);
+        builder = builder.addTransition(CREATED,CONFIG_MODIFY,CONFIGURING);
+        builder = builder.addTransition(CREATED,CONFIG_SCALEOUT,CONFIGURING);
+        builder = builder.addTransition(CREATED,CONFIG_RESTORE,CONFIGURING);
+        builder = builder.addTransition(CREATED,HEALTHCHECK,TESTING);
+        builder = builder.addTransition(CREATED,BACKUP,BACKING_UP);
+        builder = builder.addTransition(CREATED,SNAPSHOT,SNAPSHOTTING);
+        builder = builder.addTransition(CREATED,SOFTWARE_UPLOAD,SOFTWARE_UPLOADING);
+        builder = builder.addTransition(CREATED,LIVE_UPGRADE,UPGRADING);
+        builder = builder.addTransition(CREATED,ROLLBACK,ROLLBACKING);
+        builder = builder.addTransition(CREATED,MIGRATE,MIGRATING);
+        builder = builder.addTransition(CREATED,EVACUATE,EVACUATING);
+        builder = builder.addTransition(CREATED,LOCK,CREATED);
+        builder = builder.addTransition(CREATED,UNLOCK,CREATED);
+        builder = builder.addTransition(CREATED,CHECKLOCK,CREATED);
+        builder = builder.addTransition(CREATED,CONFIG_BACKUP,CREATED);
+
         builder = builder.addTransition(TESTED,CONFIGURE,CONFIGURING);
         builder = builder.addTransition(TESTED,TEST,TESTING);
         builder = builder.addTransition(TESTED,START,STARTING);
index a9690f9..8741b1b 100644 (file)
 
 package org.openecomp.appc.lifecyclemanager.impl;
 
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.att.eelf.i18n.EELFResourceManager;
 import org.openecomp.appc.i18n.Msg;
 import org.openecomp.appc.lifecyclemanager.LifecycleManager;
 import org.openecomp.appc.lifecyclemanager.helper.MetadataReader;
-import org.openecomp.appc.lifecyclemanager.objects.*;
-import org.openecomp.appc.statemachine.*;
+import org.openecomp.appc.lifecyclemanager.objects.LifecycleException;
+import org.openecomp.appc.lifecyclemanager.objects.NoTransitionDefinedException;
+import org.openecomp.appc.statemachine.StateMachine;
 import org.openecomp.appc.statemachine.impl.StateMachineFactory;
 import org.openecomp.appc.statemachine.objects.*;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.att.eelf.i18n.EELFResourceManager;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
 
 
 public class LifecycleManagerImpl implements LifecycleManager{
@@ -60,7 +61,7 @@ public class LifecycleManagerImpl implements LifecycleManager{
                StateMachineResponse response;
                try {
                        machine = this.getStateMachine(vnfType);
-                       response = machine.handleEvent(new State(currentState),new Event(event));
+                       response = machine.handleEvent(new State(currentState.toLowerCase()),new Event(event));
                        if(Response.NO_TRANSITION_DEFINED.equals(response.getResponse())){
                                errorLogger.error(EELFResourceManager.format(Msg.VF_ILLEGAL_COMMAND, vnfType,event,currentState));
                                throw new NoTransitionDefinedException("No Transition Defined for currentState = " +  currentState + ", event = " + event,currentState,event);
index 41de2d8..7ba78c7 100644 (file)
@@ -40,13 +40,15 @@ import java.util.*;
 public class TestLifecycleManager {
 
     private static final State[] VALID_LOCK_STATES = new State[] {
-            new State("Instantiated"),
-            new State("Configured"),
-            new State("Tested"),
-            new State("Running"),
-            new State("Error"),
-            new State("Unknown"),
-            new State("Stopped"),
+            new State("instantiated"),
+            new State("configured"),
+            new State("tested"),
+            new State("running"),
+            new State("error"),
+            new State("unknown"),
+            new State("created"),
+            new State("not orchestrated"),
+            new State("stopped"),
     };
 
     @Test
@@ -110,7 +112,7 @@ public class TestLifecycleManager {
     public void testNotOrchestratedState() throws LifecycleException, NoTransitionDefinedException {
         LifecycleManager lifecycleManager = new LifecycleManagerImpl();
         String nextState = lifecycleManager.getNextState(null,"NOT ORCHESTRATED",VNFOperation.Configure.toString());
-        Assert.assertEquals(nextState,"Configuring");
+        Assert.assertEquals(nextState,"configuring");
     }
 
     @Test(expected = NoTransitionDefinedException.class)
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestHandlerImpl.java
new file mode 100644 (file)
index 0000000..19451f1
--- /dev/null
@@ -0,0 +1,627 @@
+/*-
+ * ============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.requesthandler.impl;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.att.eelf.i18n.EELFResourceManager;
+import org.apache.commons.lang.ObjectUtils;
+import org.openecomp.appc.common.constant.Constants;
+import org.openecomp.appc.configuration.Configuration;
+import org.openecomp.appc.configuration.ConfigurationFactory;
+import org.openecomp.appc.domainmodel.lcm.*;
+import org.openecomp.appc.exceptions.APPCException;
+import org.openecomp.appc.executor.CommandExecutor;
+import org.openecomp.appc.executor.UnstableVNFException;
+import org.openecomp.appc.executor.objects.LCMCommandStatus;
+import org.openecomp.appc.executor.objects.Params;
+import org.openecomp.appc.executor.objects.UniqueRequestIdentifier;
+import org.openecomp.appc.i18n.Msg;
+import org.openecomp.appc.lifecyclemanager.objects.LifecycleException;
+import org.openecomp.appc.lifecyclemanager.objects.NoTransitionDefinedException;
+import org.openecomp.appc.logging.LoggingConstants;
+import org.openecomp.appc.logging.LoggingUtils;
+import org.openecomp.appc.messageadapter.MessageAdapter;
+import org.openecomp.appc.messageadapter.impl.MessageAdapterImpl;
+import org.openecomp.appc.metricservice.MetricRegistry;
+import org.openecomp.appc.metricservice.MetricService;
+import org.openecomp.appc.metricservice.metric.DispatchingFuntionMetric;
+import org.openecomp.appc.metricservice.metric.Metric;
+import org.openecomp.appc.metricservice.metric.MetricType;
+import org.openecomp.appc.metricservice.policy.PublishingPolicy;
+import org.openecomp.appc.metricservice.publisher.LogPublisher;
+import org.openecomp.appc.requesthandler.RequestHandler;
+import org.openecomp.appc.requesthandler.exceptions.*;
+import org.openecomp.appc.requesthandler.helper.RequestRegistry;
+import org.openecomp.appc.requesthandler.helper.RequestValidator;
+import org.openecomp.appc.requesthandler.objects.RequestHandlerInput;
+import org.openecomp.appc.requesthandler.objects.RequestHandlerOutput;
+import org.openecomp.appc.transactionrecorder.TransactionRecorder;
+import org.openecomp.appc.transactionrecorder.objects.TransactionRecord;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.ServiceReference;
+import org.slf4j.MDC;
+
+import java.net.InetAddress;
+import java.time.Instant;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Properties;
+
+import static com.att.eelf.configuration.Configuration.*;
+
+/**
+ * This class provides application logic for the Request/Response Handler Component.
+ *
+ */
+public abstract class AbstractRequestHandlerImpl implements RequestHandler {
+
+    private RequestValidator requestValidator;
+
+
+
+    private RequestRegistry requestRegistry;
+
+    private CommandExecutor commandExecutor;
+
+    private TransactionRecorder transactionRecorder;
+
+    private MessageAdapter messageAdapter;
+
+    private static MetricRegistry metricRegistry;
+
+    private boolean isMetricEnabled = false;
+
+    protected static final Configuration configuration = ConfigurationFactory.getConfiguration();
+
+    private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractRequestHandlerImpl.class);
+
+    public AbstractRequestHandlerImpl() {
+        requestRegistry = new RequestRegistry();
+        messageAdapter = new MessageAdapterImpl();
+        messageAdapter.init();
+        Properties properties = configuration.getProperties();
+        if (properties != null && properties.getProperty("metric.enabled") != null) {
+            isMetricEnabled = Boolean.valueOf(properties.getProperty("metric.enabled"));
+        }
+        if (isMetricEnabled) {
+            initMetric();
+        }
+    }
+
+    public void setTransactionRecorder(TransactionRecorder transactionRecorder) {
+        this.transactionRecorder = transactionRecorder;
+    }
+
+    public void setRequestValidator(RequestValidator requestValidator) {
+        this.requestValidator = requestValidator;
+    }
+
+    public void setMessageAdapter(MessageAdapter messageAdapter) {
+        this.messageAdapter = messageAdapter;
+    }
+
+
+
+    public void setRequestRegistry(RequestRegistry requestRegistry) {
+        this.requestRegistry = requestRegistry;
+    }
+
+    public void setCommandExecutor(CommandExecutor commandExecutor) {
+        this.commandExecutor = commandExecutor;
+    }
+
+
+    /**
+     * It receives requests from the north-bound REST API (Communication) Layer and
+     * performs following validations.
+     * 1. VNF exists in A&AI for the given targetID (VnfID)
+     * 2. For the current VNF  Orchestration Status, the command can be executed
+     * 3. For the given VNF type and Operation, there exists work-flow definition in the APPC database
+     * If any of the validation fails, it returns appropriate response
+     *
+     * @param input RequestHandlerInput object which contains request header and  other request parameters like command , target Id , payload etc.
+     * @return response for request as enum with Return code and message.
+     */
+    @Override
+    public RequestHandlerOutput handleRequest(RequestHandlerInput input) {
+        if (logger.isTraceEnabled())
+            logger.trace("Entering to handleRequest with RequestHandlerInput = " + ObjectUtils.toString(input) + ")");
+        Params params ;
+        String vnfId, vnfType = null, errorMessage = null;
+        Instant startTime = Instant.now();
+        RequestHandlerOutput output = null;
+        setInitialLogProperties(input.getRequestContext());
+
+        RuntimeContext runtimeContext = new RuntimeContext();
+        runtimeContext.setRequestContext(input.getRequestContext());
+        runtimeContext.setTimeStart(startTime);
+        runtimeContext.setRpcName(input.getRpcName());
+
+        final ResponseContext responseContext = new ResponseContext();
+        responseContext.setStatus(new Status(0,""));
+        responseContext.setAdditionalContext(new HashMap<>(4));
+        responseContext.setCommonHeader(input.getRequestContext().getCommonHeader());
+        runtimeContext.setResponseContext(responseContext);
+        runtimeContext.getResponseContext().setStatus(new Status(0,""));
+
+        vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
+
+        try {
+
+            requestValidator.validateRequest(runtimeContext);
+
+            handleRequest(runtimeContext);
+
+            final int statusCode = runtimeContext.getResponseContext().getStatus().getCode();
+            if (statusCode % 100 == 2 || statusCode % 100 == 3) {
+                createTransactionRecord(runtimeContext);
+            }
+            output = new RequestHandlerOutput();
+            output.setResponseContext(runtimeContext.getResponseContext());
+
+        } catch (VNFNotFoundException e) {
+            errorMessage = e.getMessage();
+            String logMessage = EELFResourceManager.format(Msg.APPC_NO_RESOURCE_FOUND, vnfId);
+            storeErrorMessageToLog(runtimeContext, LoggingConstants.TargetNames.AAI, "", logMessage);
+            params = new Params().addParam("vnfId", vnfId);
+            output = buildRequestHandlerOutput(LCMCommandStatus.VNF_NOT_FOUND, params);
+        } catch (NoTransitionDefinedException e) {
+            errorMessage = e.getMessage();
+            String logMessage = EELFResourceManager.format(Msg.VF_UNDEFINED_STATE, input.getRequestContext().getCommonHeader().getOriginatorId(), input.getRequestContext().getAction().name());
+            params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState);
+            output = buildRequestHandlerOutput(LCMCommandStatus.NO_TRANSITION_DEFINE, params);
+            storeErrorMessageToLog(runtimeContext,
+                    LoggingConstants.TargetNames.APPC,
+                    LoggingConstants.TargetNames.STATE_MACHINE,
+                    logMessage);
+        } catch (LifecycleException e) {
+            errorMessage = e.getMessage();
+            params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState);
+            output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_VNF_STATE, params);
+        } catch (UnstableVNFException e) {
+            errorMessage = e.getMessage();
+            params = new Params().addParam("vnfId", vnfId);
+            output = buildRequestHandlerOutput(LCMCommandStatus.UNSTABLE_VNF, params);
+        } catch (WorkflowNotFoundException e) {
+            errorMessage = e.getMessage();
+            String vnfTypeVersion = e.vnfTypeVersion;
+            params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("vnfTypeVersion", vnfTypeVersion);
+            output = buildRequestHandlerOutput(LCMCommandStatus.WORKFLOW_NOT_FOUND, params);
+        } catch (DGWorkflowNotFoundException e) {
+            errorMessage = e.getMessage();
+            String logMessage = EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfType, input.getRequestContext().getAction().name());
+            storeErrorMessageToLog(runtimeContext,
+                    LoggingConstants.TargetNames.APPC,
+                    LoggingConstants.TargetNames.WORKFLOW_MANAGER,
+                    logMessage);
+            params = new Params().addParam("actionName", input.getRequestContext().getAction().name())
+                    .addParam("dgModule", e.workflowModule).addParam("dgName", e.workflowName).addParam("dgVersion", e.workflowVersion);
+            output = buildRequestHandlerOutput(LCMCommandStatus.DG_WORKFLOW_NOT_FOUND, params);
+        } catch (RequestExpiredException e) {
+            errorMessage = e.getMessage();
+            params = new Params().addParam("actionName", input.getRequestContext().getAction().name());
+            output = buildRequestHandlerOutput(LCMCommandStatus.EXPIRED_REQUEST, params);
+        } catch (InvalidInputException e) {
+            errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
+            params = new Params().addParam("errorMsg", errorMessage);
+            output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_INPUT_PARAMETER, params);
+        } catch (DuplicateRequestException e) {
+            errorMessage = e.getMessage();
+            output = buildRequestHandlerOutput(LCMCommandStatus.DUPLICATE_REQUEST, null);
+        } catch (MissingVNFDataInAAIException e) {
+            params = new Params().addParam("attributeName",e.getMissingAttributeName())
+                    .addParam("vnfId",vnfId);
+            output = buildRequestHandlerOutput(LCMCommandStatus.MISSING_VNF_DATA_IN_AAI,params);
+            errorMessage = output.getResponseContext().getStatus().getMessage();
+        } catch (LCMOperationsDisabledException e) {
+            errorMessage = e.getMessage();
+            params = new Params().addParam("errorMsg", errorMessage);
+            output = buildRequestHandlerOutput(LCMCommandStatus.REJECTED, params);
+        } catch (Exception e) {
+            storeErrorMessageToLog(runtimeContext, "", "", "Exception = " + e.getMessage());
+            errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
+            params = new Params().addParam("errorMsg", errorMessage);
+            output = buildRequestHandlerOutput(LCMCommandStatus.UNEXPECTED_ERROR, params);
+        } finally {
+            try {
+                if (logger.isDebugEnabled() && errorMessage != null)
+                    logger.debug("error occurred in handleRequest " + errorMessage);
+                logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.ACCEPTED.getResponseCode():  " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode()));
+                logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.SUCCESS.getResponseCode():  " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode()));
+
+                runtimeContext.setResponseContext(output.getResponseContext());
+                if ((null == output) || !(output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode())) {
+                    if (isMetricEnabled) {
+                        if((output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode())) {
+                            ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest();
+                        }else {
+                            ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementRejectedRequest();
+                        }
+                    }
+                    removeRequestFromRegistry(input.getRequestContext().getCommonHeader());
+                }
+            } finally {
+                storeAuditLogRecord(runtimeContext);
+                storeMetricLogRecord(runtimeContext);
+                clearRequestLogProperties();
+            }
+        }
+        if (logger.isTraceEnabled()) {
+            logger.trace("Exiting from handleRequest with (RequestHandlerOutput = " + ObjectUtils.toString(output.getResponseContext()) + ")");
+        }
+        return output;
+    }
+
+    protected void storeErrorMessageToLog(RuntimeContext runtimeContext, String targetEntity, String targetServiceName, String additionalMessage) {
+        LoggingUtils.logErrorMessage(runtimeContext.getResponseContext().getStatus() != null ?
+                        String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()) : "",
+                runtimeContext.getResponseContext().getStatus() != null ?
+                        String.valueOf(runtimeContext.getResponseContext().getStatus().getMessage()) : "",
+                targetEntity,
+                targetServiceName,
+                additionalMessage,
+                this.getClass().getCanonicalName());
+    }
+
+    private void createTransactionRecord(RuntimeContext runtimeContext) {
+        TransactionRecord transactionRecord = new TransactionRecord();
+        transactionRecord.setTimeStamp(runtimeContext.getResponseContext().getCommonHeader().getTimeStamp());
+        transactionRecord.setRequestID(runtimeContext.getResponseContext().getCommonHeader().getRequestId());
+        transactionRecord.setStartTime(runtimeContext.getTimeStart());
+        transactionRecord.setEndTime(Instant.now());
+        transactionRecord.setTargetID(runtimeContext.getVnfContext().getId());
+        transactionRecord.setTargetType(runtimeContext.getVnfContext().getType());
+        transactionRecord.setOperation(runtimeContext.getRequestContext().getAction().name());
+        transactionRecord.setResultCode(String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()));
+        transactionRecord.setDescription(runtimeContext.getResponseContext().getStatus().getMessage());
+        transactionRecorder.store(transactionRecord);
+    }
+
+    protected abstract void handleRequest(RuntimeContext runtimeContext) ;
+
+    protected void callWfOperation(RuntimeContext runtimeContext) {
+        int remainingTTL = calculateRemainingTTL(runtimeContext.getRequestContext().getCommonHeader());
+        if (remainingTTL > 0) {
+            if (logger.isDebugEnabled()) {
+                logger.debug("Calling command Executor with remaining TTL value: " + remainingTTL);
+            }
+
+            RuntimeContext clonedContext = cloneContext(runtimeContext);
+
+            try {
+                commandExecutor.executeCommand(clonedContext);
+                if(logger.isTraceEnabled()) {
+                    logger.trace("Command was added to queue successfully for vnfID = " + ObjectUtils.toString(runtimeContext.getRequestContext().getActionIdentifiers().getVnfId()));
+                }
+                fillStatus(runtimeContext, LCMCommandStatus.ACCEPTED, null);
+                if (isMetricEnabled) {
+                    ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest();
+                }
+            } catch (APPCException e) {
+                String errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
+                Params params = new Params().addParam("errorMsg", errorMessage);
+                fillStatus(runtimeContext, LCMCommandStatus.UNEXPECTED_ERROR, params);
+            }
+
+        } else {
+            fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST, null);
+            storeErrorMessageToLog(runtimeContext,
+                    LoggingConstants.TargetNames.APPC,
+                    LoggingConstants.TargetNames.REQUEST_HANDLER,
+                    EELFResourceManager.format(Msg.APPC_EXPIRED_REQUEST,
+                            runtimeContext.getRequestContext().getCommonHeader().getOriginatorId(),
+                            runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(),
+                            String.valueOf(runtimeContext.getRequestContext().getCommonHeader().getFlags().getTtl())));
+        }
+    }
+
+    protected void fillStatus(RuntimeContext runtimeContext, LCMCommandStatus lcmCommandStatus, Params params) {
+        runtimeContext.getResponseContext().setStatus(new Status(lcmCommandStatus.getResponseCode(),lcmCommandStatus.getFormattedMessage(params)));
+    }
+
+    /*
+     * Workaround to clone context in order to prevent sharing of ResponseContext by two threads (one to set Accepted
+     * status code and other - depending on DG status). Other properties should not be a problem
+     */
+    private RuntimeContext cloneContext(RuntimeContext runtimeContext) {
+        RuntimeContext other = new RuntimeContext();
+        other.setRequestContext(runtimeContext.getRequestContext());
+        other.setResponseContext(new ResponseContext());
+        other.getResponseContext().setStatus(new Status(0,""));
+        other.getResponseContext().setCommonHeader(runtimeContext.getRequestContext().getCommonHeader());
+        other.setVnfContext(runtimeContext.getVnfContext());
+        other.setRpcName(runtimeContext.getRpcName());
+        other.setTimeStart(runtimeContext.getTimeStart());
+        other.setIsLockAcquired(runtimeContext.isLockAcquired());
+        return other;
+    }
+
+
+    private void clearRequestLogProperties() {
+        try {
+            MDC.remove(MDC_KEY_REQUEST_ID);
+            MDC.remove(MDC_SERVICE_INSTANCE_ID);
+            MDC.remove(MDC_SERVICE_NAME);
+            MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME);
+            MDC.remove(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY);
+        } catch (Exception e) {
+            //do nothing
+        }
+    }
+
+    private void removeRequestFromRegistry(CommonHeader commonHeader) {
+        if (logger.isTraceEnabled())
+            logger.trace("Entering to removeRequestFromRegistry with RequestHeader = " + ObjectUtils.toString(commonHeader));
+        requestRegistry.removeRequest(
+                new UniqueRequestIdentifier(commonHeader.getOriginatorId(),
+                        commonHeader.getRequestId(),
+                        commonHeader.getSubRequestId()));
+    }
+
+
+    private void setInitialLogProperties(RequestContext requestContext) {
+
+        try {
+            MDC.put(MDC_KEY_REQUEST_ID, requestContext.getCommonHeader().getRequestId());
+            if (requestContext.getActionIdentifiers().getServiceInstanceId() != null) {
+                MDC.put(MDC_SERVICE_INSTANCE_ID, requestContext.getActionIdentifiers().getServiceInstanceId());
+            }
+            MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, requestContext.getCommonHeader().getOriginatorId());
+            MDC.put(MDC_INSTANCE_UUID, ""); // value should be created in the future
+            try {
+                MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); //Don't change it to a .getHostName() again please. It's wrong!
+                MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
+                MDC.put(LoggingConstants.MDCKeys.SERVER_NAME, InetAddress.getLocalHost().getHostName());
+                MDC.put(MDC_SERVICE_NAME, requestContext.getAction().name());
+                MDC.put(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY, requestContext.getActionIdentifiers().getVnfId());
+
+            } catch (Exception e) {
+                logger.debug(e.getMessage());
+            }
+        } catch (RuntimeException e) {
+            //ignore
+        }
+    }
+
+
+    private int calculateRemainingTTL(CommonHeader commonHeader) {
+        if (logger.isTraceEnabled()) {
+            logger.trace("Entering to calculateRemainingTTL with RequestHeader = " + ObjectUtils.toString(commonHeader));
+        }
+        long usedTimeInMillis = (System.currentTimeMillis() - commonHeader.getTimeStamp().getEpochSecond());
+        logger.debug("usedTimeInMillis = " + usedTimeInMillis);
+        int usedTimeInSeconds = Math.round(usedTimeInMillis / 1000);
+        logger.debug("usedTimeInSeconds = " + usedTimeInSeconds);
+        Integer inputTTL = this.getInputTTL(commonHeader);
+        logger.debug("inputTTL = " + inputTTL);
+        Integer remainingTTL = inputTTL - usedTimeInSeconds;
+        logger.debug("Remaining TTL = " + remainingTTL);
+        if (logger.isTraceEnabled())
+            logger.trace("Exiting from calculateRemainingTTL with (remainingTTL = " + ObjectUtils.toString(remainingTTL) + ")");
+        return remainingTTL;
+    }
+
+    private Integer getInputTTL(CommonHeader header) {
+        if (logger.isTraceEnabled())
+            logger.trace("Entering in getInputTTL with RequestHeader = " + ObjectUtils.toString(header));
+        if (!isValidTTL(String.valueOf(header.getFlags().getTtl()))) {
+            String defaultTTLStr = configuration.getProperty("org.openecomp.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL));
+            Integer defaultTTL = Integer.parseInt(defaultTTLStr);
+            if (logger.isTraceEnabled())
+                logger.trace("Exiting from getInputTTL with (defaultTTL = " + ObjectUtils.toString(defaultTTL) + ")");
+            return defaultTTL;
+        }
+        if (logger.isTraceEnabled())
+            logger.trace("Exiting from getInputTTL with (inputTTL = " + ObjectUtils.toString(header.getFlags().getTtl()) + ")");
+
+        return header.getFlags().getTtl();
+    }
+
+    private boolean isValidTTL(String ttl) {
+        if (ttl == null || ttl.length() == 0) {
+            if (logger.isTraceEnabled())
+                logger.trace("Exiting from getInputTTL with (result = false)");
+            return false;
+        }
+        try {
+            Integer i = Integer.parseInt(ttl);
+            return (i > 0);
+        } catch (NumberFormatException e) {
+            if (logger.isTraceEnabled())
+                logger.trace("Exiting from getInputTTL with (result = false)");
+            return false;
+        }
+    }
+
+    private Boolean isLoggingEnabled() {
+        String defaultFlagStr = configuration.getProperty("org.openecomp.appc.localTransactionRecorder.enable", String.valueOf(Constants.DEFAULT_LOGGING_FLAG));
+        return Boolean.parseBoolean(defaultFlagStr);
+    }
+
+    private static RequestHandlerOutput buildRequestHandlerOutput(LCMCommandStatus response, Params params) {
+        RequestHandlerOutput output = new RequestHandlerOutput();
+        ResponseContext responseContext = new ResponseContext();
+        org.openecomp.appc.domainmodel.lcm.Status status = new org.openecomp.appc.domainmodel.lcm.Status(response.getResponseCode(),response.getFormattedMessage(params));
+        responseContext.setStatus(status);
+        output.setResponseContext(responseContext);
+        return output;
+    }
+
+    /**
+     * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI.
+     *
+     * @param vnfId String of VNF ID
+     * @param readOnlyActivity boolean indicator
+     * @param  requestIdentifierString - string contains id uniquely represents the request
+     * @param forceFlag boolean indicator
+     * @throws UnstableVNFException when failed
+     */
+    @Override
+    public abstract void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException ;
+
+    /**
+     * This method perform following operations required after execution of workflow.
+     * It posts asynchronous response to message bus (DMaaP).
+     * Unlock VNF Id
+     * Removes request from request registry.
+     * Generate audit logs.
+     * Adds transaction record to database id if transaction logging is enabled.
+     *
+     * @param isAAIUpdated boolean flag which indicate AAI upodate status after request completion.
+     */
+    @Override
+    public void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated) {
+        if (logger.isTraceEnabled()) {
+            logger.trace("Entering to onRequestExecutionEnd with runtimeContext = " + ObjectUtils.toString(runtimeContext));
+        }
+
+        postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext());
+        requestRegistry.removeRequest(
+                new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(),
+                        runtimeContext.getResponseContext().getCommonHeader().getRequestId(),
+                        runtimeContext.getResponseContext().getCommonHeader().getSubRequestId()));
+
+        storeAuditLogRecord(runtimeContext);
+        if (isLoggingEnabled()) {
+            createTransactionRecord(runtimeContext);
+        }
+    }
+
+    private void storeAuditLogRecord(RuntimeContext runtimeContext) {
+        LoggingUtils.logAuditMessage(runtimeContext.getTimeStart(),
+                Instant.now(),
+                String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
+                runtimeContext.getResponseContext().getStatus().getMessage(),
+                this.getClass().getCanonicalName());
+    }
+
+    private void storeMetricLogRecord(RuntimeContext runtimeContext) {
+        LoggingUtils.logMetricsMessage(runtimeContext.getTimeStart(),
+                Instant.now(),
+                LoggingConstants.TargetNames.APPC,
+                runtimeContext.getRequestContext().getAction().name(),
+                runtimeContext.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode() ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR,
+                String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
+                runtimeContext.getResponseContext().getStatus().getMessage(),
+                this.getClass().getCanonicalName());
+    }
+
+
+
+
+    private void postMessageToDMaaP(VNFOperation operation, String rpcName, ResponseContext responseContext) {
+        if (logger.isTraceEnabled()) {
+            logger.trace("Entering to postMessageToDMaaP with AsyncResponse = " + ObjectUtils.toString(responseContext));
+        }
+        boolean callbackResponse = messageAdapter.post(operation, rpcName, responseContext);
+        if (!callbackResponse) {
+            logger.error("DMaaP posting status: " + callbackResponse, "dmaapMessage: " + responseContext);
+        }
+        if (logger.isTraceEnabled())
+            logger.trace("Exiting from postMessageToDMaaP with (callbackResponse = " + ObjectUtils.toString(callbackResponse) + ")");
+    }
+
+    /**
+     * This method perform following operations required if TTL ends when request still waiting in execution queue .
+     * It posts asynchronous response to message bus (DMaaP).
+     * Unlock VNF Id
+     * Removes request from request registry.
+     *
+     * @param runtimeContext AsyncResponse object which contains VNF Id        , timestamp , apiVersion, responseId, executionSuccess, payload, isExpired, action, startTime, vnfType, originatorId, subResponseId;
+     * @param updateAAI      boolean flag which indicate AAI upodate status after request completion.
+     */
+    @Override
+    public void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI) {
+        if (logger.isTraceEnabled()) {
+            logger.trace("Entering to onRequestTTLEnd with " +
+                    "AsyncResponse = " + ObjectUtils.toString(runtimeContext) +
+                    ", updateAAI = " + ObjectUtils.toString(updateAAI));
+        }
+        logger.error(LCMCommandStatus.EXPIRED_REQUEST_FAILURE.getResponseMessage());
+        fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST_FAILURE, null);
+        postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext());
+
+        requestRegistry.removeRequest(
+                new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(),
+                        runtimeContext.getResponseContext().getCommonHeader().getRequestId(),
+                        runtimeContext.getResponseContext().getCommonHeader().getSubRequestId()));
+    }
+
+    private void initMetric() {
+        if (logger.isDebugEnabled())
+            logger.debug("Metric getting initialized");
+        MetricService metricService = getMetricservice();
+        metricRegistry = metricService.createRegistry("APPC");
+        DispatchingFuntionMetric dispatchingFuntionMetric = metricRegistry.metricBuilderFactory().
+                dispatchingFunctionCounterBuilder().
+                withName("DISPATCH_FUNCTION").withType(MetricType.COUNTER).
+                withAcceptRequestValue(0)
+                .withRejectRequestValue(0)
+                .build();
+        if (metricRegistry.register(dispatchingFuntionMetric)) {
+            Metric[] metrics = new Metric[]{dispatchingFuntionMetric};
+            LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics);
+            LogPublisher[] logPublishers = new LogPublisher[1];
+            logPublishers[0] = logPublisher;
+            PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory().
+                    scheduledPolicyBuilder().withPublishers(logPublishers).
+                    withMetrics(metrics).
+                    build();
+            if (logger.isDebugEnabled())
+                logger.debug("Policy getting initialized");
+            manuallyScheduledPublishingPolicy.init();
+            if (logger.isDebugEnabled())
+                logger.debug("Metric initialized");
+        }
+    }
+
+
+    private MetricService getMetricservice() {
+        BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext();
+        ServiceReference sref = bctx.getServiceReference(MetricService.class.getName());
+        if (sref != null) {
+            logger.info("Metric Service from bundlecontext");
+            return (MetricService) bctx.getService(sref);
+        } else {
+            logger.info("Metric Service error from bundlecontext");
+            logger.warn("Cannot find service reference for org.openecomp.appc.metricservice.MetricService");
+            return null;
+        }
+    }
+
+    /**
+     * This method returns the count of in progress requests
+     * * @return in progress requests count
+     */
+    @Override
+    public int getInprogressRequestCount() {
+        if (logger.isTraceEnabled()) {
+            logger.trace("Entering to getInprogressRequestCount");
+        }
+        return requestRegistry.getRegisteredRequestCount();
+    }
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/AbstractRequestValidatorImpl.java
new file mode 100644 (file)
index 0000000..df9c93c
--- /dev/null
@@ -0,0 +1,328 @@
+/*-
+ * ============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.requesthandler.impl;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.att.eelf.i18n.EELFResourceManager;
+import org.apache.commons.lang.ObjectUtils;
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.appc.common.constant.Constants;
+import org.openecomp.appc.configuration.Configuration;
+import org.openecomp.appc.configuration.ConfigurationFactory;
+import org.openecomp.appc.domainmodel.lcm.CommonHeader;
+import org.openecomp.appc.domainmodel.lcm.RequestContext;
+import org.openecomp.appc.domainmodel.lcm.RuntimeContext;
+import org.openecomp.appc.domainmodel.lcm.VNFContext;
+import org.openecomp.appc.executor.UnstableVNFException;
+import org.openecomp.appc.executor.objects.UniqueRequestIdentifier;
+import org.openecomp.appc.i18n.Msg;
+import org.openecomp.appc.lifecyclemanager.LifecycleManager;
+import org.openecomp.appc.lifecyclemanager.objects.LifecycleException;
+import org.openecomp.appc.lifecyclemanager.objects.NoTransitionDefinedException;
+import org.openecomp.appc.logging.LoggingConstants;
+import org.openecomp.appc.logging.LoggingUtils;
+import org.openecomp.appc.requesthandler.LCMStateManager;
+import org.openecomp.appc.requesthandler.exceptions.*;
+import org.openecomp.appc.requesthandler.helper.RequestRegistry;
+import org.openecomp.appc.requesthandler.helper.RequestValidator;
+import org.openecomp.appc.workflow.WorkFlowManager;
+import org.openecomp.appc.workflow.objects.WorkflowExistsOutput;
+import org.openecomp.appc.workflow.objects.WorkflowRequest;
+import org.openecomp.sdnc.sli.SvcLogicContext;
+import org.openecomp.sdnc.sli.SvcLogicException;
+import org.openecomp.sdnc.sli.SvcLogicResource;
+import org.openecomp.sdnc.sli.aai.AAIService;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.ServiceReference;
+
+import java.time.Instant;
+import java.util.Calendar;
+import java.util.Date;
+
+public abstract class AbstractRequestValidatorImpl implements RequestValidator {
+
+    protected final EELFLogger logger = EELFManager.getInstance().getLogger(RequestValidatorImpl.class);
+    private final Configuration configuration = ConfigurationFactory.getConfiguration();
+    protected LifecycleManager lifecyclemanager;
+    protected LCMStateManager lcmStateManager;
+    private AAIService aaiService;
+    private WorkFlowManager workflowManager;
+    private RequestRegistry requestRegistry = new RequestRegistry();
+
+    protected static Calendar DateToCalendar(Date date) {
+        Calendar cal = Calendar.getInstance();
+        cal.setTime(date);
+        return cal;
+    }
+
+    public void setWorkflowManager(WorkFlowManager workflowManager) {
+        this.workflowManager = workflowManager;
+    }
+
+    public void setLcmStateManager(LCMStateManager lcmStateManager) {
+        this.lcmStateManager = lcmStateManager;
+    }
+
+    public void setRequestRegistry(RequestRegistry requestRegistry) {
+        this.requestRegistry = requestRegistry;
+    }
+
+    public abstract void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException;
+
+    private boolean isValidTTL(String ttl) {
+        if (logger.isTraceEnabled()){
+            logger.trace("Entering to isValidTTL where ttl = "+ ObjectUtils.toString(ttl));
+        }
+        if (ttl == null || ttl.length() == 0) {
+            if (logger.isTraceEnabled()) {
+                logger.trace("Exiting from isValidTT with (result = "+ ObjectUtils.toString(false)+")");
+            }
+            return false;
+        }
+        try {
+            Integer i = Integer.parseInt(ttl);
+            if (logger.isTraceEnabled()) {
+                logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(i > 0)+")");
+            }
+            return (i > 0);
+        } catch (NumberFormatException e) {
+            if (logger.isTraceEnabled()) {
+                logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(false)+")");
+            }
+            return false;
+        }
+    }
+
+    protected void getAAIservice() {
+        BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
+        // Get AAIadapter reference
+        ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
+        if (sref != null) {
+            logger.info("AAIService from bundlecontext");
+            aaiService = (AAIService) bctx.getService(sref);
+
+        } else {
+            logger.info("AAIService error from bundlecontext");
+            logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService");
+
+        }
+    }
+
+    protected VNFContext queryAAI(String vnfId) throws VNFNotFoundException, MissingVNFDataInAAIException {
+        SvcLogicContext ctx = new SvcLogicContext();
+        ctx = getVnfdata(vnfId, "vnf", ctx);
+
+        VNFContext vnfContext = new VNFContext();
+        populateVnfContext(vnfContext, ctx);
+
+        return vnfContext;
+    }
+
+    protected void queryWFM(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {
+
+        checkWorkflowExists(vnfContext, requestContext);
+    }
+
+    private void checkWorkflowExists(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {
+
+        WorkflowExistsOutput workflowExistsOutput = workflowManager.workflowExists(getWorkflowQueryParams(vnfContext, requestContext));
+        if (!workflowExistsOutput.isMappingExist()) {
+            if (logger.isDebugEnabled()) {
+                logger.debug("WorkflowManager : Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name());
+            }
+
+            LoggingUtils.logErrorMessage(
+                    LoggingConstants.TargetNames.WORKFLOW_MANAGER,
+                    EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
+                    this.getClass().getCanonicalName());
+
+
+            throw new WorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),vnfContext.getType(),requestContext.getAction().name());
+        }
+        if (!workflowExistsOutput.isDgExist()) {
+            if (logger.isDebugEnabled()) {
+                logger.debug("WorkflowManager : DG Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()+" "+workflowExistsOutput);
+            }
+
+
+            LoggingUtils.logErrorMessage(
+                    LoggingConstants.TargetNames.WORKFLOW_MANAGER,
+                    EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
+                    this.getClass().getCanonicalName());
+
+
+            throw new DGWorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),
+                    workflowExistsOutput.getWorkflowModule(),workflowExistsOutput.getWorkflowName(),workflowExistsOutput.getWorkflowVersion());
+        }
+    }
+
+    private void populateVnfContext(VNFContext vnfContext, SvcLogicContext ctx) throws MissingVNFDataInAAIException {
+        String vnfType = ctx.getAttribute("vnf.vnf-type");
+        String orchestrationStatus = ctx.getAttribute("vnf.orchestration-status");
+        if(StringUtils.isEmpty(vnfType)){
+            throw new MissingVNFDataInAAIException("vnf-type");
+        }
+        else if(StringUtils.isEmpty(orchestrationStatus)){
+            throw new MissingVNFDataInAAIException("orchestration-status");
+        }
+        vnfContext.setType(vnfType);
+        vnfContext.setStatus(orchestrationStatus);
+        vnfContext.setId(ctx.getAttribute("vnf.vnf-id"));
+    }
+
+    private WorkflowRequest getWorkflowQueryParams(VNFContext vnfContext, RequestContext requestContext) {
+
+        WorkflowRequest workflowRequest = new WorkflowRequest();
+        workflowRequest.setVnfContext(vnfContext);
+        workflowRequest.setRequestContext(requestContext);
+        if (logger.isTraceEnabled()) {
+            logger.trace("Exiting from etWorkflowQueryParams with (WorkflowRequest = "+ ObjectUtils.toString(workflowRequest)+")");
+        }
+        return workflowRequest;
+    }
+
+    protected void checkForDuplicateRequest(CommonHeader header) throws DuplicateRequestException {
+        if (logger.isTraceEnabled()) {
+            logger.trace("Entering to checkForDuplicateRequest with RequestHeader = "+ ObjectUtils.toString(header));
+        }
+
+        UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(header.getOriginatorId(), header.getRequestId(), header.getSubRequestId());
+        boolean requestAccepted = requestRegistry.registerRequest(requestIdentifier);
+        if (!requestAccepted) {
+            if (logger.isDebugEnabled()) {
+                logger.debug("Duplicate Request with " + requestIdentifier);
+            }
+            throw new DuplicateRequestException("Duplicate Request with " + requestIdentifier);
+        }
+    }
+
+    protected Integer readTTL(CommonHeader header) {
+        if (logger.isTraceEnabled()) {
+            logger.trace("Entering to readTTL with RequestHandlerInput = "+ ObjectUtils.toString(header));
+        }
+        if (header.getFlags()== null || !isValidTTL(String.valueOf(header.getFlags().getTtl()))) {
+            String defaultTTLStr = configuration.getProperty("org.openecomp.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL));
+            return Integer.parseInt(defaultTTLStr);
+        }
+        if (logger.isTraceEnabled()) {
+            logger.trace("Exiting from readTTL with (TTL = "+  ObjectUtils.toString(header.getFlags().getTtl())+")");
+        }
+        return header.getFlags().getTtl();
+    }
+
+    private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) throws VNFNotFoundException {
+        if (logger.isTraceEnabled()) {
+            logger.trace("Entering to getVnfdata with vnfid = "+ ObjectUtils.toString(vnf_id) + ", prefix = "+ ObjectUtils.toString(prefix)+ ", SvcLogicContext"+ ObjectUtils.toString(ctx));
+        }
+
+        String key = "vnf-id = '" + vnf_id + "'";
+        logger.debug("inside getVnfdata=== " + key);
+        try {
+            Instant beginTimestamp = Instant.now();
+            SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key, prefix, null, ctx);
+            Instant endTimestamp = Instant.now();
+            String status = SvcLogicResource.QueryStatus.SUCCESS.equals(response) ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR;
+            LoggingUtils.logMetricsMessage(
+                    beginTimestamp,
+                    endTimestamp,
+                    LoggingConstants.TargetNames.AAI,
+                    LoggingConstants.TargetServiceNames.AAIServiceNames.QUERY,
+                    status,
+                    "",
+                    response.name(),
+                    this.getClass().getCanonicalName());
+            if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
+                throw new VNFNotFoundException("VNF not found for vnf_id = " + vnf_id);
+            } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
+                throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id);
+            }
+            logger.info("AAIResponse: " + response.toString());
+        } catch (SvcLogicException e) {
+
+            LoggingUtils.logErrorMessage(
+                    LoggingConstants.TargetServiceNames.AAIServiceNames.GET_VNF_DATA,
+                    "Error in getVnfdata" + e,
+                    this.getClass().getCanonicalName());
+
+            throw new RuntimeException(e);
+        }
+        if (logger.isTraceEnabled()) {
+            logger.trace("Exiting from getVnfdata with (SvcLogicContext = "+ ObjectUtils.toString(ctx)+")");
+        }
+        return ctx;
+    }
+
+    protected void validateInput(RequestContext requestContext)
+            throws RequestExpiredException, InvalidInputException, DuplicateRequestException {
+        if (logger.isTraceEnabled()){
+            logger.trace("Entering to validateInput with RequestHandlerInput = "+ ObjectUtils.toString(requestContext));
+        }
+        if (requestContext.getActionIdentifiers().getVnfId() == null || requestContext.getAction() == null
+                || requestContext.getActionIdentifiers().getVnfId().length() == 0 || requestContext.getAction().name().length() == 0 ||
+                null == requestContext.getCommonHeader().getApiVer()) {
+            if (logger.isDebugEnabled()) {
+                logger.debug("vnfID = " + requestContext.getActionIdentifiers().getVnfId() + ", action = " + requestContext.getAction().name());
+            }
+
+            LoggingUtils.logErrorMessage(
+                    LoggingConstants.TargetNames.REQUEST_VALIDATOR,
+                    EELFResourceManager.format(Msg.APPC_INVALID_INPUT),
+                    this.getClass().getCanonicalName());
+
+            throw new InvalidInputException("vnfID or command is null");
+        }
+        CommonHeader commonHeader = requestContext.getCommonHeader();
+
+        checkForDuplicateRequest(commonHeader);
+
+        Calendar inputTimeStamp = DateToCalendar(Date.from(commonHeader.getTimeStamp()));
+        Calendar currentTime = Calendar.getInstance();
+
+        // If input timestamp is of future, we reject the request
+        if (inputTimeStamp.getTime().getTime() > currentTime.getTime().getTime()) {
+            if (logger.isDebugEnabled()) {
+                logger.debug("Input Timestamp is of future = " + inputTimeStamp.getTime());
+            }
+            throw new InvalidInputException("Input Timestamp is of future = " + inputTimeStamp.getTime());
+        }
+        Integer ttl = readTTL(commonHeader);
+        logger.debug("TTL value set to (seconds) : " + ttl);
+        inputTimeStamp.add(Calendar.SECOND, ttl);
+        if (currentTime.getTime().getTime() >= inputTimeStamp.getTime().getTime()) {
+
+            LoggingUtils.logErrorMessage(
+                    LoggingConstants.TargetNames.REQUEST_VALIDATOR,
+                    "TTL Expired: Current time - " + currentTime.getTime().getTime() + " Request time: " + inputTimeStamp.getTime().getTime() + " with TTL value: " + ttl,
+                    this.getClass().getCanonicalName());
+
+            throw new RequestExpiredException("TTL Expired");
+        }
+        if (logger.isDebugEnabled()) {
+            logger.debug("Validation of the request is successful");
+        }
+    }
+}
index 0356d2e..65761e1 100644 (file)
 
 package org.openecomp.appc.requesthandler.impl;
 
-import org.apache.commons.lang.ObjectUtils;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.att.eelf.i18n.EELFResourceManager;
 import org.openecomp.appc.common.constant.Constants;
-import org.openecomp.appc.configuration.Configuration;
-import org.openecomp.appc.configuration.ConfigurationFactory;
-import org.openecomp.appc.domainmodel.lcm.*;
-import org.openecomp.appc.exceptions.APPCException;
-import org.openecomp.appc.executor.CommandExecutor;
+import org.openecomp.appc.domainmodel.lcm.RuntimeContext;
+import org.openecomp.appc.domainmodel.lcm.Status;
+import org.openecomp.appc.domainmodel.lcm.VNFOperation;
 import org.openecomp.appc.executor.UnstableVNFException;
 import org.openecomp.appc.executor.objects.LCMCommandStatus;
 import org.openecomp.appc.executor.objects.Params;
 import org.openecomp.appc.executor.objects.UniqueRequestIdentifier;
 import org.openecomp.appc.i18n.Msg;
-import org.openecomp.appc.lifecyclemanager.objects.LifecycleException;
-import org.openecomp.appc.lifecyclemanager.objects.NoTransitionDefinedException;
 import org.openecomp.appc.lockmanager.api.LockException;
 import org.openecomp.appc.lockmanager.api.LockManager;
 import org.openecomp.appc.logging.LoggingConstants;
-import org.openecomp.appc.logging.LoggingUtils;
-import org.openecomp.appc.messageadapter.MessageAdapter;
-import org.openecomp.appc.messageadapter.impl.MessageAdapterImpl;
-import org.openecomp.appc.metricservice.MetricRegistry;
-import org.openecomp.appc.metricservice.MetricService;
-import org.openecomp.appc.metricservice.metric.DispatchingFuntionMetric;
-import org.openecomp.appc.metricservice.metric.Metric;
-import org.openecomp.appc.metricservice.metric.MetricType;
-import org.openecomp.appc.metricservice.policy.PublishingPolicy;
-import org.openecomp.appc.metricservice.publisher.LogPublisher;
-import org.openecomp.appc.requesthandler.RequestHandler;
-import org.openecomp.appc.requesthandler.exceptions.*;
-import org.openecomp.appc.requesthandler.helper.RequestRegistry;
-import org.openecomp.appc.requesthandler.helper.RequestValidator;
-import org.openecomp.appc.requesthandler.objects.RequestHandlerInput;
-import org.openecomp.appc.requesthandler.objects.RequestHandlerOutput;
-import org.openecomp.appc.transactionrecorder.TransactionRecorder;
-import org.openecomp.appc.transactionrecorder.objects.TransactionRecord;
 import org.openecomp.appc.workingstatemanager.WorkingStateManager;
 import org.openecomp.appc.workingstatemanager.objects.VNFWorkingState;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.att.eelf.i18n.EELFResourceManager;
-import org.openecomp.sdnc.sli.SvcLogicContext;
-import org.openecomp.sdnc.sli.SvcLogicException;
-import org.openecomp.sdnc.sli.SvcLogicResource.QueryStatus;
-import org.openecomp.sdnc.sli.aai.AAIService;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.MDC;
-
-import static com.att.eelf.configuration.Configuration.*;
-
-import java.net.InetAddress;
-import java.time.Instant;
-import java.time.temporal.ChronoUnit;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
 
 /**
  * This class provides application logic for the Request/Response Handler Component.
  *
  */
-public class RequestHandlerImpl implements RequestHandler {
+public class RequestHandlerImpl extends AbstractRequestHandlerImpl {
 
     /**
      * APP-C VNF lock idle timeout in milliseconds. Applied only when locking VNF using northbound API "lock"
      */
     private static final String PROP_IDLE_TIMEOUT = "org.openecomp.appc.lock.idleTimeout";
 
-    private CommandExecutor commandExecutor;
-
-    private TransactionRecorder transactionRecorder;
-    private MessageAdapter messageAdapter;
-    private RequestValidator requestValidator;
-    private static MetricRegistry metricRegistry;
-    private boolean isMetricEnabled = false;
-    private RequestRegistry requestRegistry;
     private LockManager lockManager;
-    private WorkingStateManager workingStateManager;
-    private AAIService aaiService;
-
-    private static final EELFLogger logger = EELFManager.getInstance().getLogger(RequestHandlerImpl.class);
 
-    public void setAaiService(AAIService aaiService) {
-        this.aaiService = aaiService;
-    }
-
-    public void setTransactionRecorder(TransactionRecorder transactionRecorder) {
-        this.transactionRecorder = transactionRecorder;
-    }
+    private WorkingStateManager workingStateManager;
 
     public void setLockManager(LockManager lockManager) {
         this.lockManager = lockManager;
     }
 
-    public void setRequestValidator(RequestValidator requestValidator) {
-        this.requestValidator = requestValidator;
-    }
-
-    public void setMessageAdapter(MessageAdapter messageAdapter) {
-        this.messageAdapter = messageAdapter;
-    }
-
-    private static final Configuration configuration = ConfigurationFactory.getConfiguration();
-
     public void setWorkingStateManager(WorkingStateManager workingStateManager) {
         this.workingStateManager = workingStateManager;
     }
 
-    public RequestHandlerImpl() {
-        requestRegistry = new RequestRegistry();
-        messageAdapter = new MessageAdapterImpl();
-        messageAdapter.init();
-        Properties properties = configuration.getProperties();
-        if (properties != null && properties.getProperty("metric.enabled") != null) {
-            isMetricEnabled = Boolean.valueOf(properties.getProperty("metric.enabled"));
-        }
-        if (isMetricEnabled) {
-            initMetric();
-        }
-    }
-
-    public void setCommandExecutor(CommandExecutor commandExecutor) {
-        this.commandExecutor = commandExecutor;
-    }
-
-
-    /**
-     * It receives requests from the north-bound REST API (Communication) Layer and
-     * performs following validations.
-     * 1. VNF exists in A&AI for the given targetID (VnfID)
-     * 2. For the current VNF  Orchestration Status, the command can be executed
-     * 3. For the given VNF type and Operation, there exists work-flow definition in the APPC database
-     * If any of the validation fails, it returns appropriate response
-     *
-     * @param input RequestHandlerInput object which contains request header and  other request parameters like command , target Id , payload etc.
-     * @return response for request as enum with Return code and message.
-     */
-    @Override
-    public RequestHandlerOutput handleRequest(RequestHandlerInput input) {
-        if (logger.isTraceEnabled())
-            logger.trace("Entering to handleRequest with RequestHandlerInput = " + ObjectUtils.toString(input) + ")");
-        Params params = null;
-        String vnfId = null, vnfType = null, errorMessage = null;
-        Instant startTime = Instant.now();
-        RequestHandlerOutput output = null;
-        setInitialLogProperties(input.getRequestContext());
-
-        RuntimeContext runtimeContext = new RuntimeContext();
-        runtimeContext.setRequestContext(input.getRequestContext());
-        runtimeContext.setTimeStart(startTime);
-        runtimeContext.setRpcName(input.getRpcName());
-
-        final ResponseContext responseContext = new ResponseContext();
-        responseContext.setStatus(new Status(0, null));
-        responseContext.setAdditionalContext(new HashMap<String, String>(4));
-        responseContext.setCommonHeader(input.getRequestContext().getCommonHeader());
-        runtimeContext.setResponseContext(responseContext);
-        runtimeContext.getResponseContext().setStatus(new Status(0, null));
-
-        vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
-
-        try {
-
-            requestValidator.validateRequest(runtimeContext);
-
-            handleRequest(runtimeContext);
-
-            final int statusCode = runtimeContext.getResponseContext().getStatus().getCode();
-            if (statusCode % 100 == 2 || statusCode % 100 == 3) {
-                createTransactionRecord(runtimeContext);
-            }
-            output = new RequestHandlerOutput();
-            output.setResponseContext(runtimeContext.getResponseContext());
-
-        } catch (VNFNotFoundException e) {
-            errorMessage = e.getMessage();
-            String logMessage = EELFResourceManager.format(Msg.APPC_NO_RESOURCE_FOUND, vnfId);
-            storeErrorMessageToLog(runtimeContext, LoggingConstants.TargetNames.AAI, "", logMessage);
-            params = new Params().addParam("vnfId", vnfId);
-            output = buildRequestHandlerOutput(LCMCommandStatus.VNF_NOT_FOUND, params);
-        } catch (NoTransitionDefinedException e) {
-            errorMessage = e.getMessage();
-            String logMessage = EELFResourceManager.format(Msg.VF_UNDEFINED_STATE, input.getRequestContext().getCommonHeader().getOriginatorId(), input.getRequestContext().getAction().name());
-            params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState);
-            output = buildRequestHandlerOutput(LCMCommandStatus.NO_TRANSITION_DEFINE, params);
-            storeErrorMessageToLog(runtimeContext,
-                    LoggingConstants.TargetNames.APPC,
-                    LoggingConstants.TargetNames.STATE_MACHINE,
-                    logMessage);
-        } catch (LifecycleException e) {
-            errorMessage = e.getMessage();
-            params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState);
-            output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_VNF_STATE, params);
-        } catch (UnstableVNFException e) {
-            errorMessage = e.getMessage();
-            params = new Params().addParam("vnfId", vnfId);
-            output = buildRequestHandlerOutput(LCMCommandStatus.UNSTABLE_VNF, params);
-        } catch (WorkflowNotFoundException e) {
-            errorMessage = e.getMessage();
-            String vnfTypeVersion = e.vnfTypeVersion;
-            params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("vnfTypeVersion", vnfTypeVersion);
-            output = buildRequestHandlerOutput(LCMCommandStatus.WORKFLOW_NOT_FOUND, params);
-        } catch (DGWorkflowNotFoundException e) {
-            errorMessage = e.getMessage();
-            String logMessage = EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfType, input.getRequestContext().getAction().name());
-            storeErrorMessageToLog(runtimeContext,
-                    LoggingConstants.TargetNames.APPC,
-                    LoggingConstants.TargetNames.WORKFLOW_MANAGER,
-                    logMessage);
-            params = new Params().addParam("actionName", input.getRequestContext().getAction().name())
-                    .addParam("dgModule", e.workflowModule).addParam("dgName", e.workflowName).addParam("dgVersion", e.workflowVersion);
-            output = buildRequestHandlerOutput(LCMCommandStatus.DG_WORKFLOW_NOT_FOUND, params);
-        } catch (RequestExpiredException e) {
-            errorMessage = e.getMessage();
-            params = new Params().addParam("actionName", input.getRequestContext().getAction().name());
-            output = buildRequestHandlerOutput(LCMCommandStatus.EXPIRED_REQUEST, params);
-        } catch (InvalidInputException e) {
-            errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
-            params = new Params().addParam("errorMsg", errorMessage);
-            output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_INPUT_PARAMETER, params);
-        } catch (DuplicateRequestException e) {
-            errorMessage = e.getMessage();
-            output = buildRequestHandlerOutput(LCMCommandStatus.DUPLICATE_REQUEST, null);
-        } catch (MissingVNFDataInAAIException e) {
-            params = new Params().addParam("attributeName",e.getMissingAttributeName())
-                    .addParam("vnfId",vnfId);
-            output = buildRequestHandlerOutput(LCMCommandStatus.MISSING_VNF_DATA_IN_AAI,params);
-            errorMessage = output.getResponseContext().getStatus().getMessage();
-        } catch (LCMOperationsDisabledException e) {
-            errorMessage = e.getMessage();
-            params = new Params().addParam("errorMsg", errorMessage);
-            output = buildRequestHandlerOutput(LCMCommandStatus.REJECTED, params);
-        } catch (Exception e) {
-            storeErrorMessageToLog(runtimeContext, "", "", "Exception = " + e.getMessage());
-            errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
-            params = new Params().addParam("errorMsg", errorMessage);
-            output = buildRequestHandlerOutput(LCMCommandStatus.UNEXPECTED_ERROR, params);
-        } finally {
-            try {
-                if (logger.isDebugEnabled() && errorMessage != null)
-                    logger.debug("error occurred in handleRequest " + errorMessage);
-                logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.ACCEPTED.getResponseCode():  " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode()));
-                logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.SUCCESS.getResponseCode():  " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode()));
-
-                runtimeContext.setResponseContext(output.getResponseContext());
-                if ((null == output) || !(output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode())) {
-                    if (isMetricEnabled) {
-                        if((output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode())) {
-                            ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest();
-                        }else {
-                            ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementRejectedRequest();
-                        }
-                    }
-                    removeRequestFromRegistry(input.getRequestContext().getCommonHeader());
-                }
-            } finally {
-                storeAuditLogRecord(runtimeContext);
-                storeMetricLogRecord(runtimeContext);
-                clearRequestLogProperties();
-            }
-        }
-        if (logger.isTraceEnabled()) {
-            logger.trace("Exiting from handleRequest with (RequestHandlerOutput = " + ObjectUtils.toString(output.getResponseContext()) + ")");
-        }
-        return output;
-    }
-
-    private void storeErrorMessageToLog(RuntimeContext runtimeContext, String targetEntity, String targetServiceName, String additionalMessage) {
-        LoggingUtils.logErrorMessage(runtimeContext.getResponseContext().getStatus() != null ?
-                        String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()) : "",
-                runtimeContext.getResponseContext().getStatus() != null ?
-                        String.valueOf(runtimeContext.getResponseContext().getStatus().getMessage()) : "",
-                targetEntity,
-                targetServiceName,
-                additionalMessage,
-                this.getClass().getCanonicalName());
-    }
-
-    private void createTransactionRecord(RuntimeContext runtimeContext) {
-        TransactionRecord transactionRecord = new TransactionRecord();
-        transactionRecord.setTimeStamp(runtimeContext.getResponseContext().getCommonHeader().getTimeStamp());
-        transactionRecord.setRequestID(runtimeContext.getResponseContext().getCommonHeader().getRequestId());
-        transactionRecord.setStartTime(runtimeContext.getTimeStart());
-        transactionRecord.setEndTime(Instant.now());
-        transactionRecord.setTargetID(runtimeContext.getVnfContext().getId());
-        transactionRecord.setTargetType(runtimeContext.getVnfContext().getType());
-        transactionRecord.setOperation(runtimeContext.getRequestContext().getAction().name());
-        transactionRecord.setResultCode(String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()));
-        transactionRecord.setDescription(runtimeContext.getResponseContext().getStatus().getMessage());
-        transactionRecorder.store(transactionRecord);
-    }
+    private static final EELFLogger logger = EELFManager.getInstance().getLogger(RequestHandlerImpl.class);
 
-    private void handleRequest(RuntimeContext runtimeContext) {
+    protected void handleRequest(RuntimeContext runtimeContext) {
 
         switch (runtimeContext.getRequestContext().getAction()) {
             case Lock:
                 try {
                     lockWithTimeout(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId());
-                    fillStatus(runtimeContext,LCMCommandStatus.SUCCESS, null);
+                    fillStatus(runtimeContext, LCMCommandStatus.SUCCESS, null);
                 } catch (LockException e) {
                     Params params = new Params().addParam("errorMsg", e.getMessage());
                     fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params);
@@ -333,7 +82,6 @@ public class RequestHandlerImpl implements RequestHandler {
                             LoggingConstants.TargetNames.LOCK_MANAGER,
                             EELFResourceManager.format(Msg.VF_SERVER_BUSY, runtimeContext.getVnfContext().getId()));
                 }
-
                 break;
 
             case Unlock:
@@ -367,94 +115,23 @@ public class RequestHandlerImpl implements RequestHandler {
                         if (statusCode % 100 == 2 || statusCode % 100 == 3) {
                             try {
                                 releaseVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId());
-                                //TODO add logger call
                             } catch (LockException e) {
-                                //ignore
+                                logger.error("Error releasing the lock",e);
                             }
                         }
                     }
                 }
         }
-
-    }
-
-    private void callWfOperation(RuntimeContext runtimeContext) {
-        int remainingTTL = calculateRemainingTTL(runtimeContext.getRequestContext().getCommonHeader());
-        if (remainingTTL > 0) {
-            if (logger.isDebugEnabled()) {
-                logger.debug("Calling command Executor with remaining TTL value: " + remainingTTL);
-            }
-
-            RuntimeContext commandExecutorInput = cloneContext(runtimeContext);
-
-            try {
-                commandExecutor.executeCommand(commandExecutorInput);
-                if(logger.isTraceEnabled()) {
-                    logger.trace("Command was added to queue successfully for vnfID = " + ObjectUtils.toString(runtimeContext.getRequestContext().getActionIdentifiers().getVnfId()));
-                }
-                fillStatus(runtimeContext, LCMCommandStatus.ACCEPTED, null);
-                if (isMetricEnabled) {
-                    ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest();
-                }
-            } catch (APPCException e) {
-                String errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
-                Params params = new Params().addParam("errorMsg", errorMessage);
-                fillStatus(runtimeContext, LCMCommandStatus.UNEXPECTED_ERROR, params);
-            }
-
-        } else {
-            fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST, null);
-            storeErrorMessageToLog(runtimeContext,
-                    LoggingConstants.TargetNames.APPC,
-                    LoggingConstants.TargetNames.REQUEST_HANDLER,
-                    EELFResourceManager.format(Msg.APPC_EXPIRED_REQUEST,
-                            runtimeContext.getRequestContext().getCommonHeader().getOriginatorId(),
-                            runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(),
-                            String.valueOf(runtimeContext.getRequestContext().getCommonHeader().getFlags().getTtl())));
-        }
-    }
-
-    private void fillStatus(RuntimeContext runtimeContext, LCMCommandStatus lcmCommandStatus, Params params) {
-        runtimeContext.getResponseContext().setStatus(lcmCommandStatus.toStatus(params));
     }
 
-    /*
-     * Workaround to clone context in order to prevent sharing of ResponseContext by two threads (one to set Accepted
-     * status code and other - depending on DG status). Other properties should not be a problem
-     */
-    private RuntimeContext cloneContext(RuntimeContext runtimeContext) {
-        RuntimeContext other = new RuntimeContext();
-        other.setRequestContext(runtimeContext.getRequestContext());
-        other.setResponseContext(new ResponseContext());
-        other.getResponseContext().setStatus(new Status(0, null));
-        other.getResponseContext().setCommonHeader(runtimeContext.getRequestContext().getCommonHeader());
-        other.setVnfContext(runtimeContext.getVnfContext());
-        other.setRpcName(runtimeContext.getRpcName());
-        other.setTimeStart(runtimeContext.getTimeStart());
-        other.setIsLockAcquired(runtimeContext.isLockAcquired());
-        return other;
-    }
-
-
-    private void clearRequestLogProperties() {
-        try {
-            MDC.remove(MDC_KEY_REQUEST_ID);
-            MDC.remove(MDC_SERVICE_INSTANCE_ID);
-            MDC.remove(MDC_SERVICE_NAME);
-            MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME);
-            MDC.remove(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY);
-        } catch (Exception e) {
-
-        }
+    private void releaseVNFLock(String vnfId, String transactionId) throws LockException {
+        lockManager.releaseLock(vnfId, transactionId);
+        logger.info("Lock released for vnfID = " + vnfId);
     }
 
-    private void removeRequestFromRegistry(CommonHeader commonHeader) {
-        if (logger.isTraceEnabled())
-            logger.trace("Entering to removeRequestFromRegistry with RequestHeader = " + ObjectUtils.toString(commonHeader));
-        requestRegistry.removeRequest(
-                new UniqueRequestIdentifier(commonHeader.getOriginatorId(),
-                        commonHeader.getRequestId(),
-                        commonHeader.getSubRequestId()));
+    protected void lockWithTimeout(String vnfId, String requestId) throws LockException {
+        long timeout = configuration.getLongProperty(PROP_IDLE_TIMEOUT, Constants.DEFAULT_IDLE_TIMEOUT);
+        acquireVNFLock(vnfId, requestId, timeout);
     }
 
     private boolean acquireVNFLock(String vnfID, String requestId, long timeout) throws LockException {
@@ -469,127 +146,14 @@ public class RequestHandlerImpl implements RequestHandler {
         return lockAcquired;
     }
 
-    private void lockWithTimeout(String vnfId, String requestId) throws LockException {
-        long timeout = configuration.getLongProperty(PROP_IDLE_TIMEOUT, Constants.DEFAULT_IDLE_TIMEOUT);
-        acquireVNFLock(vnfId, requestId, timeout);
-    }
-
-    private void resetLock(String vnfId, String requestId, boolean lockAcquired, boolean resetLockTimeout) {
-        if (lockAcquired) {
-            try {
-                releaseVNFLock(vnfId, requestId);
-            } catch (LockException e) {
-                logger.error("Unlock VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e);
-
-
-            }
-        } else if (resetLockTimeout) {
-            try {
-                // reset timeout to previous value
-                lockWithTimeout(vnfId, requestId);
-            } catch (LockException e) {
-                logger.error("Reset lock idle timeout for VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e);
-            }
-        }
-    }
-
-    private void releaseVNFLock(String vnfId, String transactionId) throws LockException {
-        lockManager.releaseLock(vnfId, transactionId);
-        logger.info("Lock released for vnfID = " + vnfId);
-    }
-
-    private void setInitialLogProperties(RequestContext requestContext) {
-
-        try {
-            MDC.put(MDC_KEY_REQUEST_ID, requestContext.getCommonHeader().getRequestId());
-            if (requestContext.getActionIdentifiers().getServiceInstanceId() != null) {
-                MDC.put(MDC_SERVICE_INSTANCE_ID, requestContext.getActionIdentifiers().getServiceInstanceId());
-            }
-            MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, requestContext.getCommonHeader().getOriginatorId());
-            MDC.put(MDC_INSTANCE_UUID, ""); // value should be created in the future
-            try {
-                MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); //Don't change it to a .getHostName() again please. It's wrong!
-                MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
-                MDC.put(LoggingConstants.MDCKeys.SERVER_NAME, InetAddress.getLocalHost().getHostName());
-                MDC.put(MDC_SERVICE_NAME, requestContext.getAction().name());
-                MDC.put(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY, requestContext.getActionIdentifiers().getVnfId());
-
-            } catch (Exception e) {
-                logger.debug(e.getMessage());
-            }
-        } catch (RuntimeException e) {
-            //ignore
-        }
-    }
-
-
-    private int calculateRemainingTTL(CommonHeader commonHeader) {
-        if (logger.isTraceEnabled()) {
-            logger.trace("Entering to calculateRemainingTTL with RequestHeader = " + ObjectUtils.toString(commonHeader));
-        }
-        long usedTimeInMillis = ChronoUnit.MILLIS.between(commonHeader.getTimeStamp(), Instant.now());
-        logger.debug("usedTimeInMillis = " + usedTimeInMillis);
-        int usedTimeInSeconds = Math.round(usedTimeInMillis / 1000);
-        logger.debug("usedTimeInSeconds = " + usedTimeInSeconds);
-        Integer inputTTL = this.getInputTTL(commonHeader);
-        logger.debug("inputTTL = " + inputTTL);
-        Integer remainingTTL = inputTTL - usedTimeInSeconds;
-        logger.debug("Remaining TTL = " + remainingTTL);
-        if (logger.isTraceEnabled())
-            logger.trace("Exiting from calculateRemainingTTL with (remainingTTL = " + ObjectUtils.toString(remainingTTL) + ")");
-        return remainingTTL;
-    }
-
-    private Integer getInputTTL(CommonHeader header) {
-        if (logger.isTraceEnabled())
-            logger.trace("Entering in getInputTTL with RequestHeader = " + ObjectUtils.toString(header));
-        if (!isValidTTL(String.valueOf(header.getFlags().getTtl()))) {
-            String defaultTTLStr = configuration.getProperty("org.openecomp.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL));
-            Integer defaultTTL = Integer.parseInt(defaultTTLStr);
-            if (logger.isTraceEnabled())
-                logger.trace("Exiting from getInputTTL with (defaultTTL = " + ObjectUtils.toString(defaultTTL) + ")");
-            return defaultTTL;
-        }
-        if (logger.isTraceEnabled())
-            logger.trace("Exiting from getInputTTL with (inputTTL = " + ObjectUtils.toString(header.getFlags().getTtl()) + ")");
-
-        return header.getFlags().getTtl();
-    }
-
-    private boolean isValidTTL(String ttl) {
-        if (ttl == null || ttl.length() == 0) {
-            if (logger.isTraceEnabled())
-                logger.trace("Exiting from getInputTTL with (result = false)");
-            return false;
-        }
-        try {
-            Integer i = Integer.parseInt(ttl);
-            return (i > 0);
-        } catch (NumberFormatException e) {
-            if (logger.isTraceEnabled())
-                logger.trace("Exiting from getInputTTL with (result = false)");
-            return false;
-        }
-    }
-
-    private Boolean isLoggingEnabled() {
-        String defaultFlagStr = configuration.getProperty("org.openecomp.appc.localTransactionRecorder.enable", String.valueOf(Constants.DEFAULT_LOGGING_FLAG));
-        Boolean defaultFlag = Boolean.parseBoolean(defaultFlagStr);
-        return defaultFlag;
-    }
-
-    private static RequestHandlerOutput buildRequestHandlerOutput(LCMCommandStatus response, Params params) {
-        RequestHandlerOutput output = new RequestHandlerOutput();
-        ResponseContext responseContext = new ResponseContext();
-        responseContext.setStatus(response.toStatus(params));
-        output.setResponseContext(responseContext);
-        return output;
-    }
-
     /**
      * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI.
      *
-     * @return true in case AAI updates are successful. false for any error or exception.
+     * @param vnfId String of VNF ID
+     * @param readOnlyActivity boolean indicator
+     * @param  requestIdentifierString - string contains id uniquely represents the request
+     * @param forceFlag boolean indicator
+     * @throws UnstableVNFException when failed
      */
     @Override
     public void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException {
@@ -614,31 +178,22 @@ public class RequestHandlerImpl implements RequestHandler {
             logger.trace("Exiting from onRequestExecutionStart ");
     }
 
-    /**
-     * This method perform following operations required after execution of workflow.
-     * It posts asynchronous response to message bus (DMaaP).
-     * Unlock VNF Id
-     * Removes request from request registry.
-     * Generate audit logs.
-     * Adds transaction record to database id if transaction logging is enabled.
-     *
-     * @param isAAIUpdated boolean flag which indicate AAI upodate status after request completion.
-     */
-    @Override
-    public void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated) {
-        if (logger.isTraceEnabled()) {
-            logger.trace("Entering to onRequestExecutionEnd with runtimeContext = " + ObjectUtils.toString(runtimeContext));
+    private boolean isReadOnlyAction(VNFOperation action) {
+        if (VNFOperation.Sync.toString().equals(action) ||
+                VNFOperation.Audit.toString().equals(action) ||
+                VNFOperation.ConfigBackup.toString().equals(action) ||
+                VNFOperation.ConfigBackupDelete.toString().equals(action) ||
+                VNFOperation.ConfigExport.toString().equals(action)){
+            return true;
         }
+        return false;
+    }
 
-        postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext());
-        requestRegistry.removeRequest(
-                new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(),
-                        runtimeContext.getResponseContext().getCommonHeader().getRequestId(),
-                        runtimeContext.getResponseContext().getCommonHeader().getSubRequestId()));
-        resetLock(runtimeContext.getVnfContext().getId(), runtimeContext.getResponseContext().getCommonHeader().getRequestId(), runtimeContext.isLockAcquired(), true);
-        Status status = runtimeContext.getResponseContext().getStatus();
-
+    @Override
+    public void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated) {
+        super.onRequestExecutionEnd(runtimeContext,isAAIUpdated);
         VNFWorkingState workingState;
+        Status status = runtimeContext.getResponseContext().getStatus();
         if (status.getCode() == LCMCommandStatus.SUCCESS.getResponseCode() || isReadOnlyAction(runtimeContext.getRequestContext().getAction())) {
             workingState = VNFWorkingState.STABLE;
         } else {
@@ -651,190 +206,30 @@ public class RequestHandlerImpl implements RequestHandler {
 
         String requestIdentifierString = requestIdentifier.toIdentifierString();
         workingStateManager.setWorkingState(runtimeContext.getVnfContext().getId(), workingState, requestIdentifierString, false);
-
-
-        storeAuditLogRecord(runtimeContext);
-
-        if (isLoggingEnabled()) {
-            createTransactionRecord(runtimeContext);
-        }
-    }
-
-    private void storeAuditLogRecord(RuntimeContext runtimeContext) {
-        LoggingUtils.logAuditMessage(runtimeContext.getTimeStart(),
-                Instant.now(),
-                String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
-                runtimeContext.getResponseContext().getStatus().getMessage(),
-                this.getClass().getCanonicalName());
-    }
-
-    private void storeMetricLogRecord(RuntimeContext runtimeContext) {
-        LoggingUtils.logMetricsMessage(runtimeContext.getTimeStart(),
-                Instant.now(),
-                LoggingConstants.TargetNames.APPC,
-                runtimeContext.getRequestContext().getAction().name(),
-                runtimeContext.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode() ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR,
-                String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
-                runtimeContext.getResponseContext().getStatus().getMessage(),
-                this.getClass().getCanonicalName());
-    }
-
-    private boolean isReadOnlyAction(VNFOperation action) {
-        return VNFOperation.Sync == action
-                || VNFOperation.Audit == action;
-    }
-
-
-    //returns null if asyncResponse was not modified otherwise reutrns the updated asyncResponse
-    private void postMessageToDMaaP(VNFOperation operation, String rpcName, ResponseContext responseContext/*, boolean isTTLEnd, boolean aaiUpdateSuccess*/) {
-        if (logger.isTraceEnabled()) {
-            logger.trace("Entering to postMessageToDMaaP with AsyncResponse = " + ObjectUtils.toString(responseContext));
-        }
-        boolean callbackResponse = messageAdapter.post(operation, rpcName, responseContext);
-        if (!callbackResponse) {
-            logger.error("DMaaP posting status: " + callbackResponse, "dmaapMessage: " + responseContext);
-        }
-        if (logger.isTraceEnabled())
-            logger.trace("Exiting from postMessageToDMaaP with (callbackResponse = " + ObjectUtils.toString(callbackResponse) + ")");
-    }
-
-    /**
-     * This method perform following operations required if TTL ends when request still waiting in execution queue .
-     * It posts asynchronous response to message bus (DMaaP).
-     * Unlock VNF Id
-     * Removes request from request registry.
-     *
-     * @param runtimeContext AsyncResponse object which contains VNF Id        , timestamp , apiVersion, responseId, executionSuccess, payload, isExpired, action, startTime, vnfType, originatorId, subResponseId;
-     * @param updateAAI      boolean flag which indicate AAI upodate status after request completion.
-     */
-    @Override
-    public void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI) {
-        if (logger.isTraceEnabled()) {
-            logger.trace("Entering to onRequestTTLEnd with " +
-                    "AsyncResponse = " + ObjectUtils.toString(runtimeContext) +
-                    ", updateAAI = " + ObjectUtils.toString(updateAAI));
-        }
-        logger.error(LCMCommandStatus.EXPIRED_REQUEST_FAILURE.getResponseMessage());
-        fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST_FAILURE, null);
-        postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext());
+        logger.debug("Reset lock for vnfId " + runtimeContext.getVnfContext().getId());
         resetLock(runtimeContext.getVnfContext().getId(), runtimeContext.getResponseContext().getCommonHeader().getRequestId(), runtimeContext.isLockAcquired(), true);
-        requestRegistry.removeRequest(
-                new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(),
-                        runtimeContext.getResponseContext().getCommonHeader().getRequestId(),
-                        runtimeContext.getResponseContext().getCommonHeader().getSubRequestId()));
-    }
-
-    private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) throws VNFNotFoundException {
-        String key = "vnf-id = '" + vnf_id + "'";
-        if (logger.isTraceEnabled()) {
-            logger.trace("Entering to getVnfdata with " +
-                    "vnfId = " + vnf_id +
-                    ", prefix = " + prefix +
-                    ", SvcLogicContex = " + ObjectUtils.toString(ctx));
-        }
-        try {
-            QueryStatus response = aaiService.query("generic-vnf", false, null, key, prefix, null, ctx);
-            if (QueryStatus.NOT_FOUND.equals(response)) {
-                throw new VNFNotFoundException("VNF not found for vnf_id = " + vnf_id);
-            } else if (QueryStatus.FAILURE.equals(response)) {
-                throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id);
-            }
-            logger.info("AAIResponse: " + response.toString());
-        } catch (SvcLogicException e) {
-            logger.error("Error in getVnfdata " + e);
-            throw new RuntimeException(e);
-        }
-        if (logger.isTraceEnabled()) {
-            logger.trace("Exiting from getVnfdata with (SvcLogicContext = " + ObjectUtils.toString(ctx) + ")");
-        }
-        return ctx;
     }
 
-    private boolean postVnfdata(String vnf_id, String status, String prefix, SvcLogicContext ctx) throws VNFNotFoundException {
-        if (logger.isTraceEnabled()) {
-            logger.trace("Entering to postVnfdata with " +
-                    "vnfId = " + vnf_id +
-                    ", status = " + status +
-                    ", prefix = " + prefix +
-                    ", SvcLogicContext = " + ObjectUtils.toString(ctx));
-        }
-        String key = "vnf-id = '" + vnf_id + "'";
-        Map<String, String> data = new HashMap<>();
-        data.put("orchestration-status", status);
-        try {
-            QueryStatus response = aaiService.update("generic-vnf", key, data, prefix, ctx);
-            if (QueryStatus.NOT_FOUND.equals(response)) {
-                throw new VNFNotFoundException("VNF not found for vnf_id = " + vnf_id);
+    private void resetLock(String vnfId, String requestId, boolean lockAcquired, boolean resetLockTimeout) {
+        if (lockAcquired) {
+            try {
+                releaseVNFLock(vnfId, requestId);
+            } catch (LockException e) {
+                logger.error("Unlock VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e);
             }
-            logger.info("AAIResponse: " + response.toString());
-            if (response.toString().equals("SUCCESS")) {
-                if (logger.isTraceEnabled()) {
-                    logger.trace("Exiting from postVnfdata with (Result = " + ObjectUtils.toString(true) + ")");
-                }
-                return true;
+        } else if (resetLockTimeout) {
+            try {
+                // reset timeout to previous value
+                lockWithTimeout(vnfId, requestId);
+            } catch (LockException e) {
+                logger.error("Reset lock idle timeout for VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e);
             }
-
-        } catch (SvcLogicException e) {
-            logger.error("Error in postVnfdata " + e);
-            throw new RuntimeException(e);
-        }
-        if (logger.isTraceEnabled()) {
-            logger.trace("Exiting from postVnfdata with (Result = " + ObjectUtils.toString(false) + ")");
-        }
-        return false;
-    }
-
-    private void initMetric() {
-        if (logger.isDebugEnabled())
-            logger.debug("Metric getting initialized");
-        MetricService metricService = getMetricservice();
-        metricRegistry = metricService.createRegistry("APPC");
-        DispatchingFuntionMetric dispatchingFuntionMetric = metricRegistry.metricBuilderFactory().
-                dispatchingFunctionCounterBuilder().
-                withName("DISPATCH_FUNCTION").withType(MetricType.COUNTER).
-                withAcceptRequestValue(0)
-                .withRejectRequestValue(0)
-                .build();
-        if (metricRegistry.register(dispatchingFuntionMetric)) {
-            Metric[] metrics = new Metric[]{dispatchingFuntionMetric};
-            LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics);
-            LogPublisher[] logPublishers = new LogPublisher[1];
-            logPublishers[0] = logPublisher;
-            PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory().
-                    scheduledPolicyBuilder().withPublishers(logPublishers).
-                    withMetrics(metrics).
-                    build();
-            if (logger.isDebugEnabled())
-                logger.debug("Policy getting initialized");
-            manuallyScheduledPublishingPolicy.init();
-            if (logger.isDebugEnabled())
-                logger.debug("Metric initialized");
-        }
-    }
-
-
-    private MetricService getMetricservice() {
-        BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext();
-        ServiceReference sref = bctx.getServiceReference(MetricService.class.getName());
-        if (sref != null) {
-            logger.info("Metric Service from bundlecontext");
-            return (MetricService) bctx.getService(sref);
-        } else {
-            logger.info("Metric Service error from bundlecontext");
-            logger.warn("Cannot find service reference for org.openecomp.appc.metricservice.MetricService");
-            return null;
         }
     }
 
-    /**
-     * This method returns the count of in progress requests
-     * * @return in progress requests count
-     */
     @Override
-    public int getInprogressRequestCount() {
-        if (logger.isTraceEnabled()) {
-            logger.trace("Entering to getInprogressRequestCount");
-        }
-        return requestRegistry.getRegisteredRequestCount();
+    public void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI) {
+        super.onRequestTTLEnd(runtimeContext,updateAAI);
+        resetLock(runtimeContext.getVnfContext().getId(), runtimeContext.getResponseContext().getCommonHeader().getRequestId(), runtimeContext.isLockAcquired(), true);
     }
 }
index 55aff07..8e0947e 100644 (file)
 
 package org.openecomp.appc.requesthandler.impl;
 
-import java.time.Instant;
-
+import com.att.eelf.i18n.EELFResourceManager;
 import org.apache.commons.lang.ObjectUtils;
-import org.apache.commons.lang.StringUtils;
-import org.openecomp.appc.common.constant.Constants;
-import org.openecomp.appc.configuration.Configuration;
-import org.openecomp.appc.configuration.ConfigurationFactory;
-import org.openecomp.appc.domainmodel.lcm.CommonHeader;
-import org.openecomp.appc.domainmodel.lcm.RequestContext;
 import org.openecomp.appc.domainmodel.lcm.RuntimeContext;
 import org.openecomp.appc.domainmodel.lcm.VNFContext;
 import org.openecomp.appc.domainmodel.lcm.VNFOperation;
 import org.openecomp.appc.executor.UnstableVNFException;
-import org.openecomp.appc.executor.objects.UniqueRequestIdentifier;
 import org.openecomp.appc.i18n.Msg;
 import org.openecomp.appc.lifecyclemanager.LifecycleManager;
 import org.openecomp.appc.lifecyclemanager.objects.LifecycleException;
@@ -46,56 +38,18 @@ import org.openecomp.appc.logging.LoggingConstants;
 import org.openecomp.appc.logging.LoggingUtils;
 import org.openecomp.appc.requesthandler.LCMStateManager;
 import org.openecomp.appc.requesthandler.exceptions.*;
-import org.openecomp.appc.requesthandler.exceptions.DGWorkflowNotFoundException;
-import org.openecomp.appc.requesthandler.exceptions.DuplicateRequestException;
-import org.openecomp.appc.requesthandler.exceptions.InvalidInputException;
-import org.openecomp.appc.requesthandler.exceptions.RequestExpiredException;
-import org.openecomp.appc.requesthandler.exceptions.VNFNotFoundException;
-import org.openecomp.appc.requesthandler.exceptions.WorkflowNotFoundException;
-import org.openecomp.appc.requesthandler.helper.RequestRegistry;
-import org.openecomp.appc.requesthandler.helper.RequestValidator;
-import org.openecomp.appc.workflow.WorkFlowManager;
-import org.openecomp.appc.workflow.objects.WorkflowExistsOutput;
-import org.openecomp.appc.workflow.objects.WorkflowRequest;
 import org.openecomp.appc.workingstatemanager.WorkingStateManager;
-import org.openecomp.sdnc.sli.SvcLogicContext;
-import org.openecomp.sdnc.sli.SvcLogicException;
-import org.openecomp.sdnc.sli.SvcLogicResource;
-import org.openecomp.sdnc.sli.aai.AAIService;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceReference;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.att.eelf.i18n.EELFResourceManager;
 
 
-public class RequestValidatorImpl implements RequestValidator {
-
-    private AAIService aaiService;
-
-    private LifecycleManager lifecyclemanager;
-
-    private WorkFlowManager workflowManager;
+public class RequestValidatorImpl extends AbstractRequestValidatorImpl {
 
     private WorkingStateManager workingStateManager;
     private LCMStateManager lcmStateManager;
 
-    private final RequestRegistry requestRegistry = new RequestRegistry();
-
-    private final Configuration configuration = ConfigurationFactory.getConfiguration();
-    private final EELFLogger logger = EELFManager.getInstance().getLogger(RequestValidatorImpl.class);
-    private final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
-
     public void setLifecyclemanager(LifecycleManager lifecyclemanager) {
         this.lifecyclemanager = lifecyclemanager;
     }
 
-    public void setWorkflowManager(WorkFlowManager workflowManager) {
-        this.workflowManager = workflowManager;
-    }
-
     public void setWorkingStateManager(WorkingStateManager workingStateManager) {
         this.workingStateManager = workingStateManager;
     }
@@ -108,7 +62,10 @@ public class RequestValidatorImpl implements RequestValidator {
     }
 
     @Override
-    public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException {
+    public void validateRequest(RuntimeContext runtimeContext)
+            throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException,
+            DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException,
+            DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException {
         if (logger.isTraceEnabled()){
             logger.trace("Entering to validateRequest with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext));
         }
@@ -135,105 +92,6 @@ public class RequestValidatorImpl implements RequestValidator {
         }
     }
 
-    private boolean isValidTTL(String ttl) {
-        if (logger.isTraceEnabled()){
-            logger.trace("Entering to isValidTTL where ttl = "+ ObjectUtils.toString(ttl));
-        }
-        if (ttl == null || ttl.length() == 0) {
-            if (logger.isTraceEnabled()) {
-                logger.trace("Exiting from isValidTT with (result = "+ ObjectUtils.toString(false)+")");
-            }
-            return false;
-        }
-        try {
-            Integer i = Integer.parseInt(ttl);
-            if (logger.isTraceEnabled()) {
-                logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(i > 0)+")");
-            }
-            return (i > 0);
-        } catch (NumberFormatException e) {
-            if (logger.isTraceEnabled()) {
-                logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(false)+")");
-            }
-            return false;
-        }
-    }
-
-    private void validateInput(RequestContext requestContext) throws RequestExpiredException, InvalidInputException, DuplicateRequestException {
-        if (logger.isTraceEnabled()){
-            logger.trace("Entering to validateInput with RequestHandlerInput = "+ ObjectUtils.toString(requestContext));
-        }
-        if (requestContext.getActionIdentifiers().getVnfId() == null || requestContext.getAction() == null
-                || requestContext.getActionIdentifiers().getVnfId().length() == 0 || requestContext.getAction().name().length() == 0 ||
-                null == requestContext.getCommonHeader().getApiVer()) {
-            if (logger.isDebugEnabled()) {
-                logger.debug("vnfID = " + requestContext.getActionIdentifiers().getVnfId() + ", action = " + requestContext.getAction().name());
-            }
-
-            LoggingUtils.logErrorMessage(
-                    LoggingConstants.TargetNames.REQUEST_VALIDATOR,
-                    EELFResourceManager.format(Msg.APPC_INVALID_INPUT),
-                    this.getClass().getCanonicalName());
-
-            throw new InvalidInputException("vnfID or command is null");
-        }
-        CommonHeader commonHeader = requestContext.getCommonHeader();
-
-        checkForDuplicateRequest(commonHeader);
-
-        Instant inputTimeStamp = commonHeader.getTimeStamp();
-        Instant currentTime = Instant.now();
-
-        // If input timestamp is of future, we reject the request
-        if (inputTimeStamp.isAfter(currentTime)) {
-            if (logger.isDebugEnabled()) {
-                logger.debug("Input Timestamp is of future = " + inputTimeStamp);
-            }
-            throw new InvalidInputException("Input Timestamp is of future = " + inputTimeStamp);
-        }
-        int ttl = readTTL(commonHeader);
-        logger.debug("TTL value set to (seconds) : " + ttl);
-        Instant expirationTime = inputTimeStamp.plusSeconds(ttl);
-        if (currentTime.isAfter(expirationTime)) {
-
-            LoggingUtils.logErrorMessage(
-                    LoggingConstants.TargetNames.REQUEST_VALIDATOR,
-                    "TTL Expired: Current time - " + currentTime + " Request time: " + expirationTime + " with TTL value: " + ttl,
-                    this.getClass().getCanonicalName());
-
-            throw new RequestExpiredException("TTL Expired");
-        }
-        if (logger.isDebugEnabled()) {
-            logger.debug("Validation of the request is successful");
-        }
-    }
-
-
-    // TODO: Get reference once via Blueprint and get rid of this method
-    private void getAAIservice() {
-        BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
-        // Get AAIadapter reference
-        ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
-        if (sref != null) {
-            logger.info("AAIService from bundlecontext");
-            aaiService = (AAIService) bctx.getService(sref);
-
-        } else {
-            logger.info("AAIService error from bundlecontext");
-            logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService");
-
-        }
-    }
-
-    private VNFContext queryAAI(String vnfId) throws VNFNotFoundException, MissingVNFDataInAAIException {
-        SvcLogicContext ctx = new SvcLogicContext();
-        ctx = getVnfdata(vnfId, "vnf", ctx);
-
-        VNFContext vnfContext = new VNFContext();
-        populateVnfContext(vnfContext, ctx);
-
-        return vnfContext;
-    }
 
     private String queryLCM(String orchestrationStatus, VNFOperation action) throws LifecycleException, NoTransitionDefinedException {
         if (logger.isTraceEnabled()) {
@@ -248,164 +106,27 @@ public class RequestValidatorImpl implements RequestValidator {
         return nextState;
     }
 
-    private void queryWFM(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {
-
-        checkWorkflowExists(vnfContext, requestContext);
-    }
-
-    private void checkWorkflowExists(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {
-
-        WorkflowExistsOutput workflowExistsOutput = workflowManager.workflowExists(getWorkflowQueryParams(vnfContext, requestContext));
-        if (!workflowExistsOutput.isMappingExist()) {
-            if (logger.isDebugEnabled()) {
-                logger.debug("WorkflowManager : Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name());
-            }
-
-            LoggingUtils.logErrorMessage(
-                    LoggingConstants.TargetNames.WORKFLOW_MANAGER,
-                    EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
-                    this.getClass().getCanonicalName());
-
-
-            throw new WorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),vnfContext.getType(),requestContext.getAction().name());
-        }
-        if (!workflowExistsOutput.isDgExist()) {
-            if (logger.isDebugEnabled()) {
-                logger.debug("WorkflowManager : DG Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()+" "+workflowExistsOutput);
-            }
-
-
-            LoggingUtils.logErrorMessage(
-                    LoggingConstants.TargetNames.WORKFLOW_MANAGER,
-                    EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
-                    this.getClass().getCanonicalName());
-
-
-            throw new DGWorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),
-                    workflowExistsOutput.getWorkflowModule(),workflowExistsOutput.getWorkflowName(),workflowExistsOutput.getWorkflowVersion());
-        }
-    }
-
-    private void populateVnfContext(VNFContext vnfContext, SvcLogicContext ctx) throws MissingVNFDataInAAIException {
-        String vnfType = ctx.getAttribute("vnf.vnf-type");
-        String orchestrationStatus = ctx.getAttribute("vnf.orchestration-status");
-        if(StringUtils.isEmpty(vnfType)){
-            throw new MissingVNFDataInAAIException("vnf-type");
-        }
-        else if(StringUtils.isEmpty(orchestrationStatus)){
-            throw new MissingVNFDataInAAIException("orchestration-status");
-        }
-        vnfContext.setType(vnfType);
-        vnfContext.setStatus(orchestrationStatus);
-        vnfContext.setId(ctx.getAttribute("vnf.vnf-id"));
-        // TODO: Uncomment once A&AI supports VNF version
-        //vnfContext.setVersion(ctx.getAttribute("vnf.vnf-version"));
-        }
-
-    private WorkflowRequest getWorkflowQueryParams(VNFContext vnfContext, RequestContext requestContext) {
-
-        WorkflowRequest workflowRequest = new WorkflowRequest();
-        workflowRequest.setVnfContext(vnfContext);
-        workflowRequest.setRequestContext(requestContext);
-        if (logger.isTraceEnabled()) {
-            logger.trace("Exiting from etWorkflowQueryParams with (WorkflowRequest = "+ ObjectUtils.toString(workflowRequest)+")");
-        }
-        return workflowRequest;
-    }
-
-
-    private void checkForDuplicateRequest(CommonHeader header) throws DuplicateRequestException {
-        if (logger.isTraceEnabled()) {
-            logger.trace("Entering to checkForDuplicateRequest with RequestHeader = "+ ObjectUtils.toString(header));
-        }
-
-        UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(header.getOriginatorId(), header.getRequestId(), header.getSubRequestId());
-        boolean requestAccepted = requestRegistry.registerRequest(requestIdentifier);
-        if (!requestAccepted) {
-            if (logger.isDebugEnabled()) {
-                logger.debug("Duplicate Request with " + requestIdentifier);
-            }
-            throw new DuplicateRequestException("Duplicate Request with " + requestIdentifier);
-        }
-    }
 
     private void checkVNFWorkingState(RuntimeContext runtimeContext) throws UnstableVNFException {
 
         if (logger.isTraceEnabled()) {
             logger.trace("Entering to checkVNFWorkingState with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext.getRequestContext()));
         }
-        boolean forceFlag = runtimeContext.getRequestContext().getCommonHeader().getFlags() != null ? runtimeContext.getRequestContext().getCommonHeader().getFlags().isForce() : false;
+        boolean forceFlag = runtimeContext.getRequestContext().getCommonHeader().getFlags() != null && runtimeContext.getRequestContext().getCommonHeader().getFlags().isForce();
         String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
 
-            if (logger.isDebugEnabled()) {
-                logger.debug("forceFlag = " + forceFlag);
-            }
+        if (logger.isDebugEnabled()) {
+            logger.debug("forceFlag = " + forceFlag);
+        }
         boolean isVNFStable = workingStateManager.isVNFStable(vnfId);
-            if (!isVNFStable && !forceFlag) {
-                if (logger.isDebugEnabled()) {
+        if (!isVNFStable && !forceFlag) {
+            if (logger.isDebugEnabled()) {
                 logger.debug("VNF is not stable for VNF ID = " + vnfId);
-                }
-            throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId);
             }
-
+            throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId);
         }
 
-
-    private int readTTL(CommonHeader header) {
-        if (logger.isTraceEnabled()) {
-            logger.trace("Entering to readTTL with RequestHandlerInput = "+ ObjectUtils.toString(header));
-        }
-        if (header.getFlags()== null || !isValidTTL(String.valueOf(header.getFlags().getTtl()))) {
-            String defaultTTLStr = configuration.getProperty("org.openecomp.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL));
-            return Integer.parseInt(defaultTTLStr);
-        }
-        if (logger.isTraceEnabled()) {
-            logger.trace("Exiting from readTTL with (TTL = "+  ObjectUtils.toString(header.getFlags().getTtl())+")");
-        }
-        return header.getFlags().getTtl();
     }
 
 
-    private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) throws VNFNotFoundException {
-        if (logger.isTraceEnabled()) {
-            logger.trace("Entering to getVnfdata with vnfid = "+ ObjectUtils.toString(vnf_id) + ", prefix = "+ ObjectUtils.toString(prefix)+ ", SvcLogicContext"+ ObjectUtils.toString(ctx));
-        }
-
-        String key = "vnf-id = '" + vnf_id + "'";
-        logger.debug("inside getVnfdata=== " + key);
-        try {
-            Instant beginTimestamp = Instant.now();
-            SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key, prefix, null, ctx);
-            Instant endTimestamp = Instant.now();
-            String status = SvcLogicResource.QueryStatus.SUCCESS.equals(response) ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR;
-            LoggingUtils.logMetricsMessage(
-                    beginTimestamp,
-                    endTimestamp,
-                    LoggingConstants.TargetNames.AAI,
-                    LoggingConstants.TargetServiceNames.AAIServiceNames.QUERY,
-                    status,
-                    "",
-                    response.name(),
-                    this.getClass().getCanonicalName());
-            if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
-                throw new VNFNotFoundException("VNF not found for vnf_id = " + vnf_id);
-            } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
-                throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id);
-            }
-            logger.info("AAIResponse: " + response.toString());
-        } catch (SvcLogicException e) {
-
-            LoggingUtils.logErrorMessage(
-                    LoggingConstants.TargetServiceNames.AAIServiceNames.GET_VNF_DATA,
-                    "Error in getVnfdata" + e,
-                    this.getClass().getCanonicalName());
-
-            throw new RuntimeException(e);
-        }
-        if (logger.isTraceEnabled()) {
-            logger.trace("Exiting from getVnfdata with (SvcLogicContext = "+ ObjectUtils.toString(ctx)+")");
-        }
-        return ctx;
-    }
-
 }
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestHandlerImpl.java
new file mode 100644 (file)
index 0000000..e5dad86
--- /dev/null
@@ -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.requesthandler.impl;
+
+import org.openecomp.appc.domainmodel.lcm.RuntimeContext;
+import org.openecomp.appc.executor.UnstableVNFException;
+
+public class VMRequestHandlerImpl extends AbstractRequestHandlerImpl{
+
+    protected void handleRequest(RuntimeContext runtimeContext) {
+        runtimeContext.setIsLockAcquired(false);
+        callWfOperation(runtimeContext);
+    }
+
+    @Override
+    public void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException {
+
+    }
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/VMRequestValidatorImpl.java
new file mode 100644 (file)
index 0000000..4bfac80
--- /dev/null
@@ -0,0 +1,83 @@
+/*-
+ * ============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.requesthandler.impl;
+
+import com.att.eelf.i18n.EELFResourceManager;
+import org.openecomp.appc.domainmodel.lcm.RuntimeContext;
+import org.openecomp.appc.domainmodel.lcm.VNFContext;
+import org.openecomp.appc.domainmodel.lcm.VNFOperation;
+import org.openecomp.appc.i18n.Msg;
+import org.openecomp.appc.logging.LoggingConstants;
+import org.openecomp.appc.logging.LoggingUtils;
+import org.openecomp.appc.requesthandler.exceptions.*;
+
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+public class VMRequestValidatorImpl extends AbstractRequestValidatorImpl {
+
+    @Override
+    public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, InvalidInputException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException, DuplicateRequestException {
+        if(!lcmStateManager.isLCMOperationEnabled()) {
+            LoggingUtils.logErrorMessage(
+                    LoggingConstants.TargetNames.REQUEST_VALIDATOR,
+                    EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED),
+                    this.getClass().getCanonicalName());
+            throw new LCMOperationsDisabledException("APPC LCM operations have been administratively disabled");
+        }
+
+        getAAIservice();
+        super.validateInput(runtimeContext.getRequestContext());
+        String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
+
+        VNFContext vnfContext = queryAAI(vnfId);
+        runtimeContext.setVnfContext(vnfContext);
+
+        VNFOperation operation = runtimeContext.getRequestContext().getAction();
+        if(supportedVMLevelAction().contains(operation)) {
+            queryWFM(vnfContext, runtimeContext.getRequestContext());
+        }
+        else{
+            throw new LCMOperationsDisabledException("Action "+ operation.name() + " is not supported on VM level");
+        }
+    }
+
+    public Set<VNFOperation> supportedVMLevelAction(){
+        Set<VNFOperation> vnfOperations = new HashSet<>();
+        vnfOperations.add(VNFOperation.Start);
+        vnfOperations.add(VNFOperation.Stop);
+        vnfOperations.add(VNFOperation.Restart);
+        vnfOperations.add(VNFOperation.Rebuild);
+        vnfOperations.add(VNFOperation.Terminate);
+        vnfOperations.add(VNFOperation.Migrate);
+        vnfOperations.add(VNFOperation.Evacuate);
+        vnfOperations.add(VNFOperation.Snapshot);
+        return vnfOperations;
+    }
+
+
+}
index 44cef76..8870292 100644 (file)
 <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">
-    <bean id="requestHandlerBean" class="org.openecomp.appc.requesthandler.impl.RequestHandlerImpl" scope="singleton" >
+    <bean id="vnfRequestHandlerBean" class="org.openecomp.appc.requesthandler.impl.RequestHandlerImpl" scope="singleton" >
        <property name="commandExecutor" ref="commandExecutorRef" />
-        <property name="requestValidator" ref="requestValidatorBean" />
+        <property name="requestValidator" ref="vnfRequestValidatorBean" />
         <property name="lockManager" ref="lockManagerRef" />
         <property name="workingStateManager" ref="workingStateManagerBean"/>
         <property name="transactionRecorder" ref="transactionRecorderRef" />
-        <property name="aaiService" ref="aaiServiceRef" />
     </bean>
 
-    <bean id="requestValidatorBean" class="org.openecomp.appc.requesthandler.impl.RequestValidatorImpl" scope="singleton" >
+    <bean id="vmRequestHandlerBean" class="org.openecomp.appc.requesthandler.impl.VMRequestHandlerImpl" scope="singleton" >
+        <property name="commandExecutor" ref="commandExecutorRef" />
+        <property name="requestValidator" ref="vmRequestValidatorBean" />
+        <property name="transactionRecorder" ref="transactionRecorderRef" />
+    </bean>
+
+    <bean id="vnfRequestValidatorBean" class="org.openecomp.appc.requesthandler.impl.RequestValidatorImpl" scope="singleton" >
         <property name="lifecyclemanager" ref="lifecyclemanagerRef" />
         <property name="workflowManager" ref="workflowManagerRef" />
         <property name="workingStateManager" ref="workingStateManagerBean" />
         <property name="lcmStateManager" ref="lcmStateManagerBean" />
     </bean>
 
+    <bean id="vmRequestValidatorBean" class="org.openecomp.appc.requesthandler.impl.VMRequestValidatorImpl" scope="singleton">
+        <property name="workflowManager" ref="workflowManagerRef" />
+        <property name="lcmStateManager" ref="lcmStateManagerBean" />
+    </bean>
+
     <bean id="lcmStateManagerBean" class="org.openecomp.appc.requesthandler.impl.LCMStateManagerImpl" scope="singleton" />
 
-    <service id="requestHandlerService" interface="org.openecomp.appc.requesthandler.RequestHandler" ref="requestHandlerBean"/>
+    <service id="vmRequestHandlerService" interface="org.openecomp.appc.requesthandler.RequestHandler" ref="vmRequestHandlerBean">
+        <service-properties>
+            <entry key="level">
+                <value type="java.lang.String">VM</value>
+            </entry>
+        </service-properties>
+    </service>
+    <service id="vnfRequestHandlerService" interface="org.openecomp.appc.requesthandler.RequestHandler" ref="vnfRequestHandlerBean">
+        <service-properties>
+            <entry key="level">
+                <value type="java.lang.String">VNF</value>
+            </entry>
+        </service-properties>
+    </service>
     <service id="lcmStateManagerService" interface="org.openecomp.appc.requesthandler.LCMStateManager" ref="lcmStateManagerBean"/>
     <reference id="lifecyclemanagerRef" availability="mandatory" activation="eager" interface="org.openecomp.appc.lifecyclemanager.LifecycleManager" />
     <reference id="workflowManagerRef" availability="mandatory" activation="eager" interface="org.openecomp.appc.workflow.WorkFlowManager" />
index a6c8c9d..fe09190 100644 (file)
@@ -37,6 +37,7 @@ import java.util.UUID;
 
 import org.junit.Assert;
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Matchers;
@@ -101,6 +102,7 @@ import org.powermock.modules.junit4.PowerMockRunner;
 import com.att.eelf.configuration.EELFLogger;
 import com.att.eelf.configuration.EELFManager;
 
+@Ignore
 @RunWith(PowerMockRunner.class)
 @PrepareForTest( {WorkingStateManager.class,FrameworkUtil.class, TransactionRecorder.class, RequestHandlerImpl.class,RequestValidatorImpl.class, TransactionRecorder.class, MessageAdapterImpl.class})
 public class TestRequestHandler {
index 4e61d14..86abd60 100644 (file)
@@ -126,7 +126,22 @@ public class AppcEventListenerActivator implements BundleActivator {
         demoProps.setListenerClass(org.openecomp.appc.listener.demo.impl.ListenerImpl.class);
         listeners.add(demoProps);
 
-        // ===========================================================================                                                                         
+       // ===========================================================================
+
+        ListenerProperties clLCMProps = new ListenerProperties("appc.LCM", props);
+        clLCMProps.setListenerClass(org.openecomp.appc.listener.LCM.impl.ListenerImpl.class);
+        listeners.add(clLCMProps);
+
+        //Configure the OAM properties
+        clLCMProps = new ListenerProperties("appc.OAM", props);
+        clLCMProps.setListenerClass(org.openecomp.appc.listener.LCM.impl.ListenerImpl.class);
+        listeners.add(clLCMProps);
+
+/*
+        ListenerProperties clLCMProps1607 = new ListenerProperties("appc.LCM1607", props);
+        clLCMProps1607.setListenerClass(org.openecomp.appc.listener.LCM1607.impl.ListenerImpl.class);
+        listeners.add(clLCMProps1607);
+*/
 
         adapter = new ControllerImpl(listeners);
         if (ctx != null && registration == null) {
diff --git a/appc-event-listener/appc-event-listener-bundle/src/test/resources/IncomingMessage.txt b/appc-event-listener/appc-event-listener-bundle/src/test/resources/IncomingMessage.txt
new file mode 100644 (file)
index 0000000..51b9a9c
--- /dev/null
@@ -0,0 +1,24 @@
+{
+"eventID": "SomeEventID-TBD",
+
+"APPCVDCName": "Delete this field not needed by App-C",
+"requestTime": "0000-00-00 00:00:00.000000",
+"policyVersion": "1",
+"VMName": "123",
+"from": "test",
+"msgOid": ".1.3.6.1.4.1.193.183.4.1.3.5.1.4",
+"AICVMID": "abc12345-1234-5678-890a-abcdefg12345",
+"trapID": "1410360",
+"requestClient": "test",
+"message": "Abnormal condition detected",
+"time": "123567890",
+"policyName": "RESTART",
+"trapIDOID": ".1.3.6.1.4.1.193.183.4.1.3.5.1.3",
+"request": "Restart",
+"OPS_CL_timer": "15",
+"nOID": ".1.3.6.1.4.1.193.183.4.2.0.4",
+"AgentAddress": "192.168.1.2",
+"vmOID": ".1.3.6.1.4.1.193.183.4.1.2.1",
+"AICTenantID": "abcde12345fghijk6789lmnopq123rst",
+"AICVServerSelfLink": "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345"
+}
\ No newline at end of file
index 8c818b2..21f0966 100644 (file)
 
 package org.openecomp.appc.oam.messageadapter;
 
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import org.apache.commons.lang.ObjectUtils;
 import org.openecomp.appc.adapter.message.MessageAdapterFactory;
 import org.openecomp.appc.adapter.message.Producer;
 import org.openecomp.appc.configuration.Configuration;
@@ -33,11 +37,6 @@ import org.osgi.framework.BundleContext;
 import org.osgi.framework.FrameworkUtil;
 import org.osgi.framework.ServiceReference;
 
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import org.apache.commons.lang.ObjectUtils;
-
 import java.util.HashSet;
 import java.util.Properties;
 
@@ -66,7 +65,7 @@ public class MessageAdapter {
         updateProperties(properties);
         Producer localProducer = null;
         
-        BundleContext ctx = FrameworkUtil.getBundle(EventHandlerImpl.class).getBundleContext();
+        BundleContext ctx = FrameworkUtil.getBundle(MessageAdapter.class).getBundleContext();
         if (ctx != null) {
                ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName());
                if (svcRef != null) {
index de77c8e..90097ae 100644 (file)
@@ -25,6 +25,7 @@
 package org.openecomp.appc.provider;
 
 import java.text.ParseException;
+import java.util.Collection;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
@@ -42,6 +43,7 @@ import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.openecomp.appc.Constants;
 import org.openecomp.appc.configuration.Configuration;
 import org.openecomp.appc.configuration.ConfigurationFactory;
+import org.openecomp.appc.domainmodel.lcm.ActionLevel;
 import org.openecomp.appc.domainmodel.lcm.ResponseContext;
 import org.openecomp.appc.domainmodel.lcm.RuntimeContext;
 import org.openecomp.appc.executor.objects.LCMCommandStatus;
@@ -59,6 +61,7 @@ import com.att.eelf.configuration.EELFManager;
 import com.att.eelf.i18n.EELFResourceManager;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.InvalidSyntaxException;
 import org.osgi.framework.ServiceReference;
 
 import com.google.common.util.concurrent.Futures;
@@ -179,7 +182,7 @@ public class AppcProviderLcm implements AutoCloseable, AppcProviderLcmService {
     /**
      * Restarts a specific VNF
      *
-     * @see org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160108.AppcProviderLcmService#restart(RestartInput)
+     * @see org.opendaylight.yang.gen.v1.org.openecomp.appc.lcm.rev160108.AppcProviderLcmService#restart(RestartInput)
      */
     @Override
     public Future<RpcResult<RestartOutput>> restart(RestartInput input) {
@@ -402,7 +405,7 @@ public class AppcProviderLcm implements AutoCloseable, AppcProviderLcmService {
 
     private RequestHandlerOutput executeRequest(RequestHandlerInput request){
 
-        RequestHandler handler = getRequestHandler();
+        RequestHandler handler = getRequestHandler(request.getRequestContext().getActionLevel());
         RequestHandlerOutput requestHandlerOutput;
         try {
             requestHandlerOutput = handler.handleRequest(request);
@@ -432,16 +435,21 @@ public class AppcProviderLcm implements AutoCloseable, AppcProviderLcmService {
         return requestHandlerOutput;
     }
 
-    private RequestHandler getRequestHandler(){
+    private RequestHandler getRequestHandler(ActionLevel actionLevel){
         RequestHandler handler ;
         final BundleContext context = FrameworkUtil.getBundle(RequestHandler.class).getBundleContext();
-        final ServiceReference reference = context.getServiceReference(RequestHandler.class.getName());
-
-        if (reference != null) {
-            handler = (RequestHandler) context.getService(reference);
-        } else {
-            logger.error("Cannot find service reference for " + RequestHandler.class.getName());
-            throw new RuntimeException();
+        String filter = "(level=" + actionLevel.name() + ")";
+        try {
+            Collection<ServiceReference<RequestHandler>> serviceReferences = context.getServiceReferences(RequestHandler.class, filter);
+            if (serviceReferences.size() != 1) {
+                logger.error("Cannot find service reference for " + RequestHandler.class.getName());
+                throw new RuntimeException();
+            }
+            ServiceReference<RequestHandler> serviceReference = serviceReferences.iterator().next();
+            handler = context.getService(serviceReference);
+        } catch (InvalidSyntaxException e) {
+            logger.error("Cannot find service reference for " + RequestHandler.class.getName() + ": Invalid Syntax " + filter, e);
+            throw new RuntimeException(e);
         }
         return  handler ;
     }
index 0c4fc73..495fa82 100644 (file)
@@ -28,11 +28,13 @@ import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.TimeZone;
 
+import org.apache.commons.lang.StringUtils;
 import org.opendaylight.yang.gen.v1.org.openecomp.appc.lcm.rev160108.Payload;
 import org.opendaylight.yang.gen.v1.org.openecomp.appc.lcm.rev160108.action.identifiers.ActionIdentifiers;
 import org.opendaylight.yang.gen.v1.org.openecomp.appc.lcm.rev160108.common.header.CommonHeader;
 import org.opendaylight.yang.gen.v1.org.openecomp.appc.lcm.rev160108.common.header.common.header.Flags;
 import org.openecomp.appc.domainmodel.lcm.Flags.Mode;
+import org.openecomp.appc.domainmodel.lcm.ActionLevel;
 import org.openecomp.appc.domainmodel.lcm.RequestContext;
 import org.openecomp.appc.domainmodel.lcm.VNFOperation;
 import org.openecomp.appc.requesthandler.objects.RequestHandlerInput;
@@ -139,11 +141,21 @@ public class RequestInputBuilder {
             actionIds.setvServerId(actionIdentifiers.getVserverId());
             actionIds.setVnfId(actionIdentifiers.getVnfId());
             this.requestContext.setActionIdentifiers(actionIds);
+
+            ActionLevel actionLevel = readActionLevel(actionIds);
+            this.requestContext.setActionLevel(actionLevel);
             return this;
         }else{
             throw new ParseException("Missing action identifier" , 0);
         }
     }
 
+    private ActionLevel readActionLevel(org.openecomp.appc.domainmodel.lcm.ActionIdentifiers actionIds) {
+        if(!StringUtils.isEmpty(actionIds.getVserverId())){
+            return ActionLevel.VM;
+        }
+        return ActionLevel.VNF;
+    }
+
 
 }
diff --git a/pom.xml b/pom.xml
index faa9ebb..6bb19d7 100644 (file)
--- a/pom.xml
+++ b/pom.xml
@@ -67,7 +67,9 @@
         <antlr.version>4.5.1</antlr.version>
         <mysql.connector.version>5.1.39</mysql.connector.version>
         <logback.version>1.1.1</logback.version>
-        <toscalib.version>1.0.0-SNAPSHOT</toscalib.version>
+        <toscalib.version>1.1.0-SNAPSHOT</toscalib.version>
+        <sdc-client.version>1.1.13-SNAPSHOT</sdc-client.version>
+               <jackson.yml.version>2.3.2</jackson.yml.version>
 
         <!-- SONAR -->
         <sonar.language>java</sonar.language>