Merge "Support more Generic workflow for voLTE"
authorSeshu Kumar M <seshu.kumar.m@huawei.com>
Fri, 23 Feb 2018 04:37:04 +0000 (04:37 +0000)
committerGerrit Code Review <gerrit@onap.org>
Fri, 23 Feb 2018 04:37:04 +0000 (04:37 +0000)
129 files changed:
adapters/mso-adapter-utils/pom.xml
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfig.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudIdentity.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/authentication/AuthenticationMethodFactory.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/StackInfo.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoCommonUtils.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntry.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtils.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtilsWithUpdate.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoKeystoneUtils.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoNeutronUtils.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtils.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtilsFactory.java
adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/AdapterBeansTest.java
adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoHeatUtilsWithUpdateTest.java
adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/CloudConfigTest.java
adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/authentication/AuthenticationMethodFactoryTest.java [new file with mode: 0644]
adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/authentication/AuthenticationMethodTest.java
adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/beans/StackInfoTest.java [new file with mode: 0644]
adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntryTest.java [new file with mode: 0644]
adapters/mso-adapters-rest-interface/pom.xml
adapters/mso-catalog-db-adapter/pom.xml
adapters/mso-catalog-db-adapter/src/main/java/org/openecomp/mso/adapters/catalogdb/catalogrest/QueryVfModule.java
adapters/mso-network-adapter-async-client/pom.xml
adapters/mso-network-adapter/pom.xml
adapters/mso-network-adapter/src/main/java/org/openecomp/mso/adapters/network/MsoNetworkAdapterImpl.java
adapters/mso-requests-db-adapter/pom.xml
adapters/mso-sdnc-adapter/pom.xml
adapters/mso-sdnc-adapter/src/main/java/org/openecomp/mso/adapters/sdnc/impl/SDNCRestClient.java
adapters/mso-sdnc-adapter/src/main/java/org/openecomp/mso/adapters/sdnc/sdncrest/SDNCConnector.java
adapters/mso-sdnc-adapter/src/test/java/org/openecomp/mso/adapters/sdnc/SDNCAdapterRequestTest.java [new file with mode: 0644]
adapters/mso-tenant-adapter/pom.xml
adapters/mso-tenant-adapter/src/main/java/org/openecomp/mso/adapters/tenant/MsoTenantAdapterImpl.java
adapters/mso-vfc-adapter/pom.xml
adapters/mso-vnf-adapter-async-client/pom.xml
adapters/mso-vnf-adapter/pom.xml
adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/adapters/vnf/MsoVnfAdapterImpl.java
adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/vdu/utils/VduBlueprint.java [new file with mode: 0755]
adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/vdu/utils/VduInfo.java [new file with mode: 0755]
adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/vdu/utils/VduPlugin.java [new file with mode: 0755]
adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/vdu/utils/VduStatus.java [new file with mode: 0755]
adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/MsoVnfAdapterAsyncImplTest.java
adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/MsoVnfAdapterImplTest.java
adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/QueryTest.java
adapters/mso-workflow-message-adapter/pom.xml
adapters/pom.xml
aria/aria-rest-java-client/pom.xml
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/AriaClient.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/AriaClientFactory.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/AriaRestClient.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/Execution.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ExecutionDetails.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ExecutionImpl.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/Input.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/InputImpl.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/NodeTemplate.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/NodeTemplateImpl.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/Output.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/OutputImpl.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/Service.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ServiceImpl.java [new file with mode: 0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ServiceTemplate.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ServiceTemplateImpl.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ValidationResult.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ValidationResultImpl.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/Workflow.java [changed mode: 0755->0644]
aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/WorkflowImpl.java [changed mode: 0755->0644]
asdc-controller/pom.xml
asdc-controller/src/main/java/org/openecomp/mso/asdc/installer/VfModuleStructure.java
bpmn/MSOCockpit/pom.xml
bpmn/MSOCommonBPMN/pom.xml
bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/DecomposeService.groovy
bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericGetService.groovy
bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClient.java
bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClientImpl.java
bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerClient.java
bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/CompleteMsoProcessTest.groovy
bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericGetServiceTest.java
bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTest.java
bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/client/ResponseExceptionMapperImplTest.java [new file with mode: 0644]
bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/client/appc/ApplicationControllerSupportTest.java [new file with mode: 0644]
bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlByNameMultiCustomer.xml [new file with mode: 0644]
bpmn/MSOCoreBPMN/pom.xml
bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/RollbackData.java
bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/domain/JsonWrapper.java
bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/domain/ServiceDecomposition.java
bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/DecomposeJsonUtil.java
bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonDecomposingException.java [new file with mode: 0644]
bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/plugins/LoggingAndURNMappingPlugin.java
bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/RollbackDataTest.java [new file with mode: 0644]
bpmn/MSOInfrastructureBPMN/pom.xml
bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy
bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java
bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/serviceTask/SdncNetworkTopologyOperationTask.java
bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/serviceTask/SdncServiceTopologyOperationTask.java
bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/CreateGenericALaCarteServiceInstanceTest.java
bpmn/MSORESTClient/pom.xml
bpmn/pom.xml
common/pom.xml
common/src/main/java/org/openecomp/mso/logger/MsoLogger.java
common/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoPropertiesFactoryTest.java
mso-api-handlers/mso-api-handler-common/pom.xml
mso-api-handlers/mso-api-handler-common/src/main/java/org/openecomp/mso/apihandler/common/CamundaClient.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/openecomp/mso/apihandler/common/CamundaTaskClient.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/openecomp/mso/apihandler/common/ErrorNumbers.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/openecomp/mso/apihandler/common/LSInputImpl.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/openecomp/mso/apihandler/common/RequestClient.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/openecomp/mso/apihandler/common/RequestClientFactory.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/openecomp/mso/apihandler/common/ResponseHandler.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/openecomp/mso/apihandler/common/ValidationException.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/openecomp/mso/apihandler/common/XMLValidator.java
mso-api-handlers/mso-api-handler-infra/pom.xml
mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/OrchestrationRequests.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/VnfRequestHandler.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/VolumeRequestHandler.java
mso-api-handlers/mso-requests-db/pom.xml
mso-api-handlers/mso-requests-db/src/test/java/org/openecomp/mso/requestsdb/RequestsDatabaseTest.java [new file with mode: 0644]
mso-api-handlers/pom.xml
mso-catalog-db/pom.xml
mso-catalog-db/src/main/java/org/openecomp/mso/db/catalog/CatalogDatabase.java
mso-catalog-db/src/main/java/org/openecomp/mso/db/catalog/beans/VnfComponent.java
mso-catalog-db/src/main/java/org/openecomp/mso/db/catalog/beans/VnfResource.java
mso-catalog-db/src/test/java/org/openecomp/mso/db/catalog/test/HeatTemplateTest.java
packages/arquillian-unit-tests/pom.xml
packages/deliveries/pom.xml
packages/docker/pom.xml
packages/pom.xml
pom.xml
status-control/pom.xml

index dd1159f..cd0a688 100644 (file)
@@ -2,11 +2,11 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>adapters</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
-       <groupId>org.openecomp.so.adapters</groupId>
+       <groupId>org.onap.so.adapters</groupId>
        <artifactId>mso-adapter-utils</artifactId>
        <name>mso-adapter-utils</name>
        <description>Common MSO utilities, including Openstack client wrappers.</description>
 
        <dependencies>
                <dependency>
+<!--
+                       <groupId>org.onap.so.libs.openstack-java-sdk</groupId>
+-->
                        <groupId>org.openecomp.so.libs.openstack-java-sdk</groupId>
                        <artifactId>keystone-client</artifactId>
                        <version>${openstack.version}</version>
                </dependency>
                <dependency>
+<!--
+                       <groupId>org.onap.so.libs.openstack-java-sdk</groupId>
+-->
                        <groupId>org.openecomp.so.libs.openstack-java-sdk</groupId>
                        <artifactId>heat-client</artifactId>
                        <version>${openstack.version}</version>
                </dependency>
                <dependency>
+<!--
+                       <groupId>org.onap.so.libs.openstack-java-sdk</groupId>
+-->
                        <groupId>org.openecomp.so.libs.openstack-java-sdk</groupId>
                        <artifactId>quantum-client</artifactId>
                        <version>${openstack.version}</version>
                </dependency>
                <dependency>
+<!--
+                       <groupId>org.onap.so.libs.openstack-java-sdk.client-connectors</groupId>
+-->
                        <groupId>org.openecomp.so.libs.openstack-java-sdk.client-connectors</groupId>
                        <artifactId>http-connector</artifactId>
                        <version>${openstack.version}</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>common</artifactId>
                        <version>${project.version}</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>mso-catalog-db</artifactId>
                        <version>${project.version}</version>
                </dependency>
index ef37f9f..5d16a95 100644 (file)
@@ -46,7 +46,6 @@ import org.openecomp.mso.openstack.exceptions.MsoCloudIdentityNotFound;
  *
  * This class also contains methods to query cloud sites and/or identity
  * services by ID.
- *
  */
 
 @JsonRootName("cloud_config")
@@ -89,21 +88,20 @@ public class CloudConfig {
      * individual entries to try and find one with a CLLI that matches the ID
      * and an AIC version of 2.5.
      *
-     * @param id
-     *            the ID to match
-     * @return a CloudSite, or null of no match found
+     * @param id the ID to match
+     * @return an Optional of CloudSite object.
      */
-    public synchronized CloudSite getCloudSite(String id) {
-        if (id != null) {
-            if (cloudSites.containsKey(id)) {
-                return cloudSites.get(id);
-            }
-            // check for id == CLLI now as well
-            return getCloudSiteWithClli(id);
+    public synchronized Optional<CloudSite> getCloudSite(String id) {
+        if (id == null) {
+            return Optional.empty();
         }
-        return null;
+        if (cloudSites.containsKey(id)) {
+            return Optional.ofNullable(cloudSites.get(id));
+        }
+        return Optional.ofNullable(getCloudSiteWithClli(id));
     }
 
+
     private CloudSite getCloudSiteWithClli(String clli) {
         Optional <CloudSite> cloudSiteOptional = cloudSites.values().stream().filter(cs ->
                 cs.getClli() != null && clli.equals(cs.getClli()) && (CLOUD_SITE_VERSION.equals(cs.getAic_version())))
@@ -111,7 +109,6 @@ public class CloudConfig {
         return cloudSiteOptional.orElse(getDefaultCloudSite(clli));
     }
 
-    // TODO in future the result will be optional
     private CloudSite getDefaultCloudSite(String clli) {
         Optional<CloudSite> cloudSiteOpt = cloudSites.values().stream()
                 .filter(cs -> cs.getId().equalsIgnoreCase(DEFAULT_CLOUD_SITE_ID)).findAny();
index d0ba7e0..ba9a7d5 100644 (file)
 
 package org.openecomp.mso.cloud;
 
-import java.io.IOException;
-import java.net.URISyntaxException;
+import com.woorea.openstack.keystone.model.Authentication;
+import com.woorea.openstack.keystone.model.authentication.UsernamePassword;
 import java.security.GeneralSecurityException;
-
 import org.codehaus.jackson.annotate.JsonProperty;
 import org.codehaus.jackson.map.annotate.JsonDeserialize;
 import org.codehaus.jackson.map.annotate.JsonSerialize;
-import org.openecomp.mso.openstack.exceptions.MsoAdapterException;
-import org.openecomp.mso.openstack.exceptions.MsoException;
-import org.openecomp.mso.openstack.utils.MsoKeystoneUtils;
-import org.openecomp.mso.openstack.utils.MsoTenantUtils;
-import org.openecomp.mso.openstack.utils.MsoTenantUtilsFactory;
 import org.openecomp.mso.cloud.authentication.AuthenticationMethodFactory;
 import org.openecomp.mso.cloud.authentication.AuthenticationWrapper;
 import org.openecomp.mso.cloud.authentication.wrappers.RackspaceAPIKeyWrapper;
 import org.openecomp.mso.cloud.authentication.wrappers.UsernamePasswordWrapper;
 import org.openecomp.mso.logger.MessageEnum;
 import org.openecomp.mso.logger.MsoLogger;
-
-import com.woorea.openstack.keystone.model.authentication.UsernamePassword;
+import org.openecomp.mso.openstack.exceptions.MsoException;
+import org.openecomp.mso.openstack.utils.MsoKeystoneUtils;
+import org.openecomp.mso.openstack.utils.MsoTenantUtils;
+import org.openecomp.mso.openstack.utils.MsoTenantUtilsFactory;
 import org.openecomp.mso.utils.CryptoUtils;
-import com.woorea.openstack.keystone.model.Authentication;
 
 /**
  * JavaBean JSON class for a CloudIdentity. This bean represents a cloud identity
@@ -143,15 +138,11 @@ public class CloudIdentity {
                }
        }
     }
-    
-    public Authentication getAuthentication () throws MsoException {
+
+       public Authentication getAuthentication() {
        if (this.getIdentityAuthenticationType() != null) {
-                       try {
                        return AuthenticationMethodFactory.getAuthenticationFor(this);
-                       } catch (IllegalAccessException | InstantiationException | ClassNotFoundException | IOException | URISyntaxException e) {
-                               throw new MsoAdapterException("Could not retrieve authentication for " + this.identityAuthenticationType, e);
-                       }
-       } else { // Fallback
+       } else {
                return new UsernamePassword(this.getMsoId(), this.getMsoPass());
        }
     }
index 85cb296..c9be2c7 100644 (file)
 \r
 package org.openecomp.mso.cloud.authentication;\r
 \r
-import java.io.IOException;\r
-import java.net.URISyntaxException;\r
+import com.woorea.openstack.keystone.model.Authentication;\r
 import java.util.Map;\r
 import java.util.concurrent.ConcurrentHashMap;\r
-\r
 import org.openecomp.mso.cloud.CloudIdentity;\r
 \r
-import com.woorea.openstack.keystone.model.Authentication;\r
-\r
 /**\r
  * This factory manages all the wrappers associated to authentication types.\r
- *\r
  */\r
 public final class AuthenticationMethodFactory {\r
 \r
@@ -58,7 +53,7 @@ public final class AuthenticationMethodFactory {
                }\r
        }\r
        \r
-       public static final synchronized Authentication getAuthenticationFor(CloudIdentity cloudIdentity) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException, URISyntaxException {\r
+       public static final synchronized Authentication getAuthenticationFor(CloudIdentity cloudIdentity) {\r
                if (cloudIdentity == null) {\r
                        throw new IllegalArgumentException("Cloud identity cannot be null");\r
                }\r
index 83e1484..600985e 100644 (file)
@@ -7,9 +7,9 @@
  * 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.
 
 package org.openecomp.mso.openstack.beans;
 
-
-import java.util.Map;
-import java.util.HashMap;
-
 import com.woorea.openstack.heat.model.Stack;
+import java.util.HashMap;
+import java.util.Map;
 
 /*
  * This Java bean class relays Heat stack status information to ActiveVOS processes.
- * 
+ *
  * This bean is returned by all Heat-specific adapter operations (create, query, delete)
  */
-
 public class StackInfo {
-       // Set defaults for everything
        private String name = "";
        private String canonicalName = "";
-       private HeatStatus status = HeatStatus.UNKNOWN;
-       private String statusMessage = "";
-       private Map<String,Object> outputs = new HashMap<String,Object>();
-       private Map<String,Object> parameters = new HashMap<String,Object>();
-       
-       static Map<String,HeatStatus> HeatStatusMap;
-       static {
-               HeatStatusMap = new HashMap<String,HeatStatus>();
-               HeatStatusMap.put("CREATE_IN_PROGRESS", HeatStatus.BUILDING);
-               HeatStatusMap.put("CREATE_COMPLETE", HeatStatus.CREATED);
-               HeatStatusMap.put("CREATE_FAILED", HeatStatus.FAILED);
-               HeatStatusMap.put("DELETE_IN_PROGRESS", HeatStatus.DELETING);
-               HeatStatusMap.put("DELETE_COMPLETE", HeatStatus.NOTFOUND);
-               HeatStatusMap.put("DELETE_FAILED", HeatStatus.FAILED);
-               HeatStatusMap.put("UPDATE_IN_PROGRESS", HeatStatus.UPDATING);
-               HeatStatusMap.put("UPDATE_FAILED", HeatStatus.FAILED);
-               HeatStatusMap.put("UPDATE_COMPLETE", HeatStatus.UPDATED);
-       }
+       private HeatStatus status;
+       private Map<String, Object> outputs = new HashMap<>();
+       private Map<String,Object> parameters = new HashMap<>();
+       static private Map<String, HeatStatus> heatStatusMap;
 
-       public StackInfo () {
+       static {
+               heatStatusMap = new HashMap<>();
+               heatStatusMap.put("CREATE_IN_PROGRESS", HeatStatus.BUILDING);
+               heatStatusMap.put("CREATE_COMPLETE", HeatStatus.CREATED);
+               heatStatusMap.put("CREATE_FAILED", HeatStatus.FAILED);
+               heatStatusMap.put("DELETE_IN_PROGRESS", HeatStatus.DELETING);
+               heatStatusMap.put("DELETE_COMPLETE", HeatStatus.NOTFOUND);
+               heatStatusMap.put("DELETE_FAILED", HeatStatus.FAILED);
+               heatStatusMap.put("UPDATE_IN_PROGRESS", HeatStatus.UPDATING);
+               heatStatusMap.put("UPDATE_FAILED", HeatStatus.FAILED);
+               heatStatusMap.put("UPDATE_COMPLETE", HeatStatus.UPDATED);
        }
-       
-       public StackInfo (String name, HeatStatus status, String statusMessage, Map<String,Object> outputs) {
-               this.name = name;
-               this.canonicalName = name;      // Don't have an ID, so just use name
 
-               this.status = status;
-               if (statusMessage != null)  this.statusMessage = statusMessage;
-               if (outputs != null)  this.outputs = outputs;
-       }
-       
        public StackInfo (String name, HeatStatus status) {
                this.name = name;
                this.canonicalName = name;      // Don't have an ID, so just use name
                this.status = status;
        }
-       
+
        public StackInfo (Stack stack)
        {
                if (stack == null) {
                        this.status = HeatStatus.NOTFOUND;
                        return;
                }
-       
                this.name = stack.getStackName();
                this.canonicalName = stack.getStackName() + "/" + stack.getId();
 
                if (stack.getStackStatus() == null) {
                        this.status = HeatStatus.INIT;
-               } else if (HeatStatusMap.containsKey(stack.getStackStatus())) {
-                       this.status = HeatStatusMap.get(stack.getStackStatus());
+               } else if (heatStatusMap.containsKey(stack.getStackStatus())) {
+                       this.status = heatStatusMap.get(stack.getStackStatus());
                } else {
                        this.status = HeatStatus.UNKNOWN;
                }
-               
-               this.statusMessage = stack.getStackStatusReason();
-               
                if (stack.getOutputs() != null) {
-                       this.outputs = new HashMap<String,Object>();
-                       for (Stack.Output output : stack.getOutputs()) {
-                               this.outputs.put(output.getOutputKey(), output.getOutputValue());
-                       }
+                       this.outputs = new HashMap<>();
+                       stack.getOutputs().forEach(output -> outputs.put(output.getOutputKey(), output.getOutputValue()));
                }
-               
+
                this.parameters = stack.getParameters();
        }
-       
+
        public String getName() {
                return name;
        }
-       
+
        public void setName (String name) {
                this.name = name;
        }
-       
+
        public String getCanonicalName() {
                return canonicalName;
        }
-       
-       public void setCanonicalName (String name) {
-               this.canonicalName = name;
-       }
-       
+
        public HeatStatus getStatus() {
                return status;
        }
-       
-       public void setStatus (HeatStatus status) {
-               this.status = status;
-       }
-       
-       public String getStatusMessage() {
-               return statusMessage;
-       }
-       
-       public void setStatusMessage (String statusMessage) {
-               this.statusMessage = statusMessage;
-       }
-       
-       public Map<String,Object> getOutputs () {
+
+       public Map<String, Object> getOutputs() {
                return outputs;
        }
-       
-       public void setOutputs (Map<String,Object> outputs) {
-               this.outputs = outputs;
-       }
-       
+
        public Map<String,Object> getParameters () {
                return parameters;
        }
-       
-       public void setParameters (Map<String,Object> parameters) {
-               this.parameters = parameters;
-       }
-       
+
 }
 
index 269f6b0..7d6de31 100644 (file)
@@ -129,6 +129,7 @@ public class MsoCommonUtils {
                                        Thread.sleep (retryDelay * 1000L);
                                } catch (InterruptedException e1) {
                         logger.debug ("Thread interrupted while sleeping", e1);
+                                               Thread.currentThread().interrupt();
                                }
                        }
                        else
@@ -144,6 +145,7 @@ public class MsoCommonUtils {
                                        Thread.sleep (retryDelay * 1000L);
                                } catch (InterruptedException e1) {
                         logger.debug ("Thread interrupted while sleeping", e1);
+                                               Thread.currentThread().interrupt();
                                }
                        }
                        else
index 3aa77c2..69da437 100644 (file)
 
 package org.openecomp.mso.openstack.utils;
 
-
-
-import java.util.HashSet;
-import java.util.ArrayList;
 import java.util.Set;
-import org.openecomp.mso.db.catalog.beans.HeatTemplateParam;
 import org.openecomp.mso.logger.MsoLogger;
 
 public class MsoHeatEnvironmentEntry {
 
-    private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA);
-    
-       private Set<MsoHeatEnvironmentParameter> parameters = null;
-       private Set<MsoHeatEnvironmentResource> resources = null;
-       private StringBuilder rawEntry = null;
+       private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
+       private Set<MsoHeatEnvironmentParameter> parameters;
+       private String rawEntry;
        private boolean valid = true;
-       private String errorString = null;
-       private StringBuilder resourceRegistryEntryRaw = null;
-       
-       public MsoHeatEnvironmentEntry() {
-               super();
-       }
-       
-       public MsoHeatEnvironmentEntry(StringBuilder sb) {
-               this();
-               this.rawEntry = sb;
-               this.processRawEntry();
+       private String errorString;
+       private String resourceRegistryEntryRaw;
+
+       private MsoHeatEnvironmentEntry(String rawEntry) {
+               this.rawEntry = rawEntry;
        }
-       
-       private void processRawEntry() {
-               try {
-                       if (this.rawEntry == null || "".equals(this.rawEntry))
-                               return;
-                       byte[] b = this.rawEntry.toString().getBytes();
-                       MsoYamlEditorWithEnvt yaml = new MsoYamlEditorWithEnvt(b);
-                       this.parameters = yaml.getParameterListFromEnvt();
-                       //this.resources = yaml.getResourceListFromEnvt();
-                       StringBuilder sb = this.getResourceRegistryRawEntry();
-                       if (sb == null) {
-                               this.resourceRegistryEntryRaw = new StringBuilder("");
-                       } else {
-                               this.resourceRegistryEntryRaw = sb;
-                       }
-               } catch (Exception e) {
-                   LOGGER.debug("Exception:", e);
-                       this.valid = false;
-                       this.errorString = e.getMessage();
-                       //e.printStackTrace();
-               }
+
+       private MsoHeatEnvironmentEntry(Set<MsoHeatEnvironmentParameter> parameters, String rawEntry, boolean valid,
+                       String errorString, String resourceRegistryEntryRaw) {
+               this.parameters = parameters;
+               this.rawEntry = rawEntry;
+               this.valid = valid;
+               this.errorString = errorString;
+               this.resourceRegistryEntryRaw = resourceRegistryEntryRaw;
        }
-       
+
        public boolean isValid() {
                return this.valid;
        }
        public String getErrorString() {
                return this.errorString;
        }
-       
-       public Set<MsoHeatEnvironmentParameter> getParameters() {
-               return this.parameters;
-       }
-       public Set<MsoHeatEnvironmentResource> getResources() {
-               return this.resources;
-       }
-       public void setParameters(Set<MsoHeatEnvironmentParameter> paramSet) {
-               if (paramSet == null) {
-                       this.parameters = null;
-               } else {
-                       this.parameters = paramSet;
-               }
-       }
-       public void setResources(Set<MsoHeatEnvironmentResource> resourceSet) {
-               if (resourceSet == null) {
-                       this.resources = null;
-               } else {
-                       this.resources = resourceSet;
-               }
-       }
-       
-       public void addParameter(MsoHeatEnvironmentParameter hep) {
-               if (this.parameters == null) {
-                       this.parameters = new HashSet<>();
-               }
-               this.parameters.add(hep);
-       }
-       public void addResource(MsoHeatEnvironmentResource her) {
-               if (this.resources == null) {
-                       this.resources = new HashSet<>();
-               }
-               this.resources.add(her);
-       }
-       
-       public int getNumberOfParameters() {
-               return this.parameters.size();
-       }
-       public int getNumberOfResources() {
-               return this.resources.size();
-       }
-       
-       public boolean hasResources() {
-               if (this.resources != null && this.resources.size() > 0) {
-                       return true;
-               } 
-               return false;
-       }
-       public boolean hasParameters() {
-               if (this.parameters != null && this.parameters.size() > 0) {
-                       return true;
-               }
-               return false;
-       }
-       
+
        public boolean containsParameter(String paramName) {
-               boolean contains = false;
                if (this.parameters == null || this.parameters.size() < 1) {
                        return false;
                }
                if (this.parameters.contains(new MsoHeatEnvironmentParameter(paramName))) {
-                       contains = true;
-               }
-               return contains;
-       }
-       
-       public boolean containsParameter(String paramName, String paramAlias) {
-               if (this.containsParameter(paramName)) {
-                       return true;
-               }
-               if (this.containsParameter(paramAlias)) {
                        return true;
                }
                return false;
        }
-       
-       public StringBuilder toFullStringExcludeNonParams(Set<HeatTemplateParam> params) {
-               // Basically give back the envt - but exclude the params that aren't in the HeatTemplate 
-               
-               StringBuilder sb = new StringBuilder();
-               ArrayList<String> paramNameList = new ArrayList<String>(params.size());
-               for (HeatTemplateParam htp : params) {
-                       paramNameList.add(htp.getParamName());
-               }
-               
-               if (this.hasParameters()) {
-                       sb.append("parameters:\n");
-                       for (MsoHeatEnvironmentParameter hep : this.parameters) {
-                               String paramName = hep.getName();
-                               if (paramNameList.contains(paramName)) {
-                                       // This parameter *is* in the Heat Template - so include it:
-                                       sb.append("  " + hep.getName() + ": " + hep.getValue() + "\n");
-                                       // New - 1607 - if any of the params mapped badly - JUST RETURN THE ORIGINAL ENVT!
-                                       if (hep.getValue().startsWith("_BAD")) {
-                                               return this.rawEntry;
-                                       }
-                               } 
-                       }
-                       sb.append("\n");
-               }
-//             if (this.hasResources()) {
-//                     sb.append("resource_registry:\n");
-//                     for (MsoHeatEnvironmentResource her : this.resources) {
-//                             sb.append("   \"" + her.getName() + "\": " + her.getValue() + "\n");
-//                     }
-//             }
-               sb.append("\n");
-               sb.append(this.resourceRegistryEntryRaw);                               
-               return sb;
+
+       @Override
+       public String toString() {
+               final StringBuilder sb = new StringBuilder("MsoHeatEnvironmentEntry{");
+               sb.append("parameters=").append(parameters);
+               sb.append(", resourceRegistryEntryRaw='").append(resourceRegistryEntryRaw).append('\'');
+               sb.append('}');
+               return sb.toString();
+       }
+
+       public String getRawEntry() {
+               return rawEntry;
        }
        
-       public StringBuilder toFullString() {
-               StringBuilder sb = new StringBuilder();
-               
-               if (this.hasParameters()) {
-                       sb.append("parameters:\n");
-                       for (MsoHeatEnvironmentParameter hep : this.parameters) {
-                               sb.append("   " + hep.getName() + ":  " + hep.getValue() + "\n");
-                       }
-                       sb.append("\n");
+       private static String getResourceRegistryRawEntry(String rawEntry) {
+               int indexOf = rawEntry.indexOf("resource_registry:");
+               if (indexOf < 0) {
+                       return "";
                }
-//             if (this.hasResources()) {
-//                     sb.append("resource_registry:\n");
-//                     for (MsoHeatEnvironmentResource her : this.resources) {
-//                             sb.append("   \"" + her.getName() + "\": " + her.getValue() + "\n");
-//                     }
-//             }
-               sb.append("\n");
-               sb.append(this.resourceRegistryEntryRaw);                       
-               return sb;
+               return rawEntry.substring(indexOf);
        }
 
-       public StringBuilder getRawEntry() {
-               return this.rawEntry;
-       }
-       
-       private StringBuilder getResourceRegistryRawEntry() {
-               
-               if (this.rawEntry == null) {
-                       return null;
+       public static MsoHeatEnvironmentEntry create(String rawEntry) {
+               if (rawEntry == null || rawEntry.isEmpty()) {
+                       return new MsoHeatEnvironmentEntry(rawEntry);
                }
-               
-               StringBuilder sb = new StringBuilder();
-               int indexOf = this.rawEntry.indexOf("resource_registry:");
-               if (indexOf < 0) { // no resource_registry:
-                       return null;
+               try {
+                       Set<MsoHeatEnvironmentParameter> parameters = new MsoYamlEditorWithEnvt(rawEntry.getBytes())
+                                       .getParameterListFromEnvt();
+                       return new MsoHeatEnvironmentEntry(parameters, rawEntry, true, null,
+                                       getResourceRegistryRawEntry(rawEntry));
+               } catch (Exception e) {
+                       LOGGER.debug(String.format("An exception occurred during processing the following raw entry: %s", rawEntry),
+                                       e);
+                       return new MsoHeatEnvironmentEntry(null, rawEntry, false, e.getMessage(), null);
                }
-               sb.append(this.rawEntry.substring(indexOf));
-               return sb;
        }
-       
+
 }
index 08ea84d..20535e9 100644 (file)
@@ -258,7 +258,7 @@ public class MsoHeatUtils extends MsoCommonUtils {
      * @param cloudSiteId The cloud (may be a region) in which to create the stack.
      * @param tenantId The Openstack ID of the tenant in which to create the Stack
      * @param stackName The name of the stack to create
-     * @param stackTemplate The Heat template
+     * @param heatTemplate The Heat template
      * @param stackInputs A map of key/value inputs
      * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
      * @param environment An optional yaml-format string to specify environmental parameters
@@ -309,10 +309,8 @@ public class MsoHeatUtils extends MsoCommonUtils {
         }
 
         // Obtain the cloud site information where we will create the stack
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         LOGGER.debug("Found: " + cloudSite.toString());
         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
         // This could throw MsoTenantNotFound or MsoOpenstackException (both propagated)
@@ -632,10 +630,8 @@ public class MsoHeatUtils extends MsoCommonUtils {
         LOGGER.debug ("Query HEAT stack: " + stackName + " in tenant " + tenantId);
 
         // Obtain the cloud site information where we will create the stack
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         LOGGER.debug("Found: " + cloudSite.toString());
 
         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
@@ -648,7 +644,7 @@ public class MsoHeatUtils extends MsoCommonUtils {
         } catch (MsoTenantNotFound e) {
             // Tenant doesn't exist, so stack doesn't either
             LOGGER.debug ("Tenant with id " + tenantId + "not found.", e);
-            return new StackInfo (stackName, HeatStatus.NOTFOUND, null, null);
+            return new StackInfo (stackName, HeatStatus.NOTFOUND);
         } catch (MsoException me) {
             // Got an Openstack error. Propagate it
             LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Exception on Token request: " + me, "Openstack", "", MsoLogger.ErrorCode.AvailabilityError, "Connection Exception");
@@ -662,7 +658,7 @@ public class MsoHeatUtils extends MsoCommonUtils {
 
         if (heatStack == null) {
             // Stack does not exist. Return a StackInfo with status NOTFOUND
-            StackInfo stackInfo = new StackInfo (stackName, HeatStatus.NOTFOUND, null, null);
+            StackInfo stackInfo = new StackInfo (stackName, HeatStatus.NOTFOUND);
             return stackInfo;
         }
 
@@ -696,10 +692,8 @@ public class MsoHeatUtils extends MsoCommonUtils {
                                   String stackName,
                                   boolean pollForCompletion) throws MsoException {
         // Obtain the cloud site information where we will create the stack
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         LOGGER.debug("Found: " + cloudSite.toString());
 
         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
@@ -712,7 +706,7 @@ public class MsoHeatUtils extends MsoCommonUtils {
         } catch (MsoTenantNotFound e) {
             // Tenant doesn't exist, so stack doesn't either
             LOGGER.debug ("Tenant with id " + tenantId + "not found.", e);
-            return new StackInfo (stackName, HeatStatus.NOTFOUND, null, null);
+            return new StackInfo (stackName, HeatStatus.NOTFOUND);
         } catch (MsoException me) {
             // Got an Openstack error. Propagate it
             LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack", "Openstack Exception on Token request: " + me, "Openstack", "", MsoLogger.ErrorCode.AvailabilityError, "Connection Exception");
@@ -724,7 +718,7 @@ public class MsoHeatUtils extends MsoCommonUtils {
         Stack heatStack = queryHeatStack (heatClient, stackName);
         if (heatStack == null || "DELETE_COMPLETE".equals (heatStack.getStackStatus ())) {
             // Not found. Return a StackInfo with status NOTFOUND
-            return new StackInfo (stackName, HeatStatus.NOTFOUND, null, null);
+            return new StackInfo (stackName, HeatStatus.NOTFOUND);
         }
 
         // Delete the stack.
@@ -747,7 +741,7 @@ public class MsoHeatUtils extends MsoCommonUtils {
         } catch (OpenStackResponseException e) {
             if (e.getStatus () == 404) {
                 // Not found. We are OK with this. Return a StackInfo with status NOTFOUND
-                return new StackInfo (stackName, HeatStatus.NOTFOUND, null, null);
+                return new StackInfo (stackName, HeatStatus.NOTFOUND);
             } else {
                 // Convert the OpenStackResponseException to an MsoOpenstackException
                 throw heatExceptionToMsoException (e, DELETE_STACK);
@@ -813,7 +807,7 @@ public class MsoHeatUtils extends MsoCommonUtils {
             }
 
             // The stack is gone when this point is reached
-            return new StackInfo (stackName, HeatStatus.NOTFOUND, null, null);
+            return new StackInfo (stackName, HeatStatus.NOTFOUND);
         }
 
         // Return the current status (if not polling, the delete may still be in progress)
@@ -838,11 +832,8 @@ public class MsoHeatUtils extends MsoCommonUtils {
      */
     public List <StackInfo> queryAllStacks (String tenantId, String cloudSiteId) throws MsoException {
         // Obtain the cloud site information where we will create the stack
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
-
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
         Heat heatClient = getHeatClient (cloudSite, tenantId);
 
@@ -895,7 +886,7 @@ public class MsoHeatUtils extends MsoCommonUtils {
     public Map <String, Object> validateStackParams (Map <String, Object> inputParams,
                                                      HeatTemplate heatTemplate) throws IllegalArgumentException {
         // Check that required parameters have been supplied for this template type
-        String missingParams = null;
+        StringBuilder missingParams = null;
         List <String> paramList = new ArrayList <> ();
 
         // TODO: Enhance DB to support defaults for Heat Template parameters
@@ -903,9 +894,9 @@ public class MsoHeatUtils extends MsoCommonUtils {
         for (HeatTemplateParam parm : heatTemplate.getParameters ()) {
             if (parm.isRequired () && !inputParams.containsKey (parm.getParamName ())) {
                 if (missingParams == null) {
-                    missingParams = parm.getParamName ();
+                    missingParams = new StringBuilder(parm.getParamName());
                 } else {
-                    missingParams += "," + parm.getParamName ();
+                    missingParams.append("," + parm.getParamName());
                 }
             }
             paramList.add (parm.getParamName ());
@@ -950,8 +941,6 @@ public class MsoHeatUtils extends MsoCommonUtils {
      * tenantID + cloudId so that it can be reused without reauthenticating with
      * Openstack every time.
      *
-     * @param tenantName
-     * @param cloudId
      * @return an authenticated Heat object
      */
     public Heat getHeatClient (CloudSite cloudSite, String tenantId) throws MsoException {
@@ -1038,8 +1027,6 @@ public class MsoHeatUtils extends MsoCommonUtils {
      * the same Tenant Name is repeatedly used for creation/deletion.
      * <p>
      *
-     * @param tenantName
-     * @param cloudId
      */
     public static void expireHeatClient (String tenantId, String cloudId) {
         String cacheKey = cloudId + ":" + tenantId;
@@ -1561,7 +1548,7 @@ public class MsoHeatUtils extends MsoCommonUtils {
                                }
                        } else if ("boolean".equalsIgnoreCase(type)) {
                                String booleanString = inputs.get(key);
-                               Boolean aBool = new Boolean(booleanString);
+                               Boolean aBool = Boolean.valueOf(booleanString);
                                if (alias)
                                        newInputs.put(realName, aBool);
                                else
index dba52d4..2465b30 100644 (file)
@@ -21,7 +21,6 @@
 
 package org.openecomp.mso.openstack.utils;
 
-
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -160,7 +159,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
      * @param tenantId The Openstack ID of the tenant in which to create the Stack
      * @param cloudSiteId The cloud identifier (may be a region) in which to create the tenant.
      * @param stackName The name of the stack to update
-     * @param stackTemplate The Heat template
+     * @param heatTemplate The Heat template
      * @param stackInputs A map of key/value inputs
      * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
      * @param environment An optional yaml-format string to specify environmental parameters
@@ -194,10 +193,8 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
         }
 
         // Obtain the cloud site information where we will create the stack
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
         // This could throw MsoTenantNotFound or MsoOpenstackException (both propagated)
         Heat heatClient = getHeatClient (cloudSite, tenantId);
index ee89840..be36d67 100644 (file)
@@ -26,6 +26,7 @@ import java.util.Calendar;
 import java.util.HashMap;
 import java.util.Map;
 
+import java.util.Optional;
 import org.openecomp.mso.cloud.CloudIdentity;
 import org.openecomp.mso.cloud.CloudSite;
 import org.openecomp.mso.logger.MsoAlarmLogger;
@@ -58,7 +59,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
     // token will be used until it expires.
     //
     // The cache key is "cloudId"
-    private static Map <String, KeystoneCacheEntry> adminClientCache = new HashMap <String, KeystoneCacheEntry> ();
+    private static Map <String, KeystoneCacheEntry> adminClientCache = new HashMap<>();
 
        private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA);
        String msoPropID;
@@ -92,13 +93,12 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
                                 Map <String, String> metadata,
                                 boolean backout) throws MsoException {
         // Obtain the cloud site information where we will create the tenant
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
+        Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
+        if (!cloudSiteOpt.isPresent()) {
                LOGGER.error(MessageEnum.RA_CREATE_TENANT_ERR, "MSOCloudSite not found", "", "", MsoLogger.ErrorCode.DataError, "MSOCloudSite not found");
             throw new MsoCloudSiteNotFound (cloudSiteId);
         }
-        Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
-
+        Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSiteOpt.get());
         Tenant tenant = null;
         try {
             // Check if the tenant already exists
@@ -129,7 +129,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
         // Add MSO User to the tenant as a member and
         // apply tenant metadata if supported by the cloud site
         try {
-            CloudIdentity cloudIdentity = cloudSite.getIdentityService ();
+            CloudIdentity cloudIdentity = cloudSiteOpt.get().getIdentityService ();
 
             User msoUser = findUserByNameOrId (keystoneAdminClient, cloudIdentity.getMsoId ());
             Role memberRole = findRoleByNameOrId (keystoneAdminClient, cloudIdentity.getMemberRole ());
@@ -197,10 +197,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
      */
     public MsoTenant queryTenant (String tenantId, String cloudSiteId) throws MsoException {
         // Obtain the cloud site information where we will query the tenant
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
 
         Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
 
@@ -247,10 +245,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
      */
     public MsoTenant queryTenantByName (String tenantName, String cloudSiteId) throws MsoException {
         // Obtain the cloud site information where we will query the tenant
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
 
         try {
@@ -294,10 +290,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
      */
     public boolean deleteTenant (String tenantId, String cloudSiteId) throws MsoException {
         // Obtain the cloud site information where we will query the tenant
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
 
         try {
@@ -326,59 +320,6 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
         return true;
     }
 
-    /**
-     * Delete the specified Tenant (by Name) in the given cloud. This method returns true or
-     * false, depending on whether the tenant existed and was successfully deleted, or if
-     * the tenant already did not exist. Both cases are treated as success (no Exceptions).
-     * <p>
-     * Note for the AIC Cloud (DCP/LCP): all admin requests go to the centralized identity
-     * service in DCP. So deleting a tenant from one cloudSiteId will remove it from all
-     * sites managed by that identity service.
-     * <p>
-     *
-     * @param tenantName The name of the tenant to delete
-     * @param cloudSiteId The cloud identifier from which to delete the tenant.
-     * @return true if the tenant was deleted, false if the tenant did not exist.
-     * @throws MsoOpenstackException If the Openstack API call returns an exception.
-     */
-    public boolean deleteTenantByName (String tenantName, String cloudSiteId) throws MsoException {
-        // Obtain the cloud site information where we will query the tenant
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
-        Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
-
-        try {
-            // Need the Tenant ID to delete (can't directly delete by name)
-            Tenant tenant = findTenantByName (keystoneAdminClient, tenantName);
-            if (tenant == null) {
-                // OK if tenant already doesn't exist.
-               LOGGER.error(MessageEnum.RA_TENANT_NOT_FOUND, tenantName, cloudSiteId, "", "", MsoLogger.ErrorCode.DataError, "Tenant not found");
-                return false;
-            }
-
-            // Execute the Delete. It has no return value.
-            OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ());
-            executeAndRecordOpenstackRequest (request, msoProps);
-
-            LOGGER.debug ("Deleted Tenant " + tenant.getId () + " (" + tenant.getName () + ")");
-
-            // Clear any cached clients. Not really needed, ID will not be reused.
-            MsoHeatUtils.expireHeatClient (tenant.getId (), cloudSiteId);
-            MsoNeutronUtils.expireNeutronClient (tenant.getId (), cloudSiteId);
-        } catch (OpenStackBaseException e) {
-            // Note: It doesn't seem to matter if tenant doesn't exist, no exception is thrown.
-            // Convert Keystone OpenStackResponseException to MsoOpenstackException
-            throw keystoneErrorToMsoException (e, "DeleteTenant");
-        } catch (RuntimeException e) {
-            // Catch-all
-            throw runtimeExceptionToMsoException (e, "DeleteTenant");
-        }
-
-        return true;
-    }
-
     // -------------------------------------------------------------------
     // PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
 
@@ -462,29 +403,6 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
         return keystone;
     }
 
-    /*
-     * Find a tenant (or query its existance) by its Name or Id. Check first against the
-     * ID. If that fails, then try by name.
-     *
-     * @param adminClient an authenticated Keystone object
-     *
-     * @param tenantName the tenant name or ID to query
-     *
-     * @return a Tenant object or null if not found
-     */
-    public Tenant findTenantByNameOrId (Keystone adminClient, String tenantNameOrId) {
-        if (tenantNameOrId == null) {
-            return null;
-        }
-
-        Tenant tenant = findTenantById (adminClient, tenantNameOrId);
-        if (tenant == null) {
-            tenant = findTenantByName (adminClient, tenantNameOrId);
-        }
-
-        return tenant;
-    }
-
     /*
      * Find a tenant (or query its existance) by its Id.
      *
index ad3eae4..50a5946 100644 (file)
@@ -7,9 +7,9 @@
  * 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.
@@ -43,7 +43,6 @@ import org.openecomp.mso.openstack.exceptions.MsoIOException;
 import org.openecomp.mso.openstack.exceptions.MsoNetworkAlreadyExists;
 import org.openecomp.mso.openstack.exceptions.MsoNetworkNotFound;
 import org.openecomp.mso.openstack.exceptions.MsoOpenstackException;
-import org.openecomp.mso.openstack.exceptions.MsoTenantNotFound;
 import com.woorea.openstack.base.client.OpenStackBaseException;
 import com.woorea.openstack.base.client.OpenStackConnectException;
 import com.woorea.openstack.base.client.OpenStackRequest;
@@ -71,7 +70,7 @@ public class MsoNeutronUtils extends MsoCommonUtils
 
        private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA);
        private String msoPropID;
-       
+
        public enum NetworkType {
                BASIC, PROVIDER, MULTI_PROVIDER
        };
@@ -99,13 +98,11 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * @throws MsoCloudSiteNotFound Thrown if the cloudSite is invalid or unknown
         */
        public NetworkInfo createNetwork (String cloudSiteId, String tenantId, NetworkType type, String networkName, String provider, List<Integer> vlans)
-               throws MsoException, MsoNetworkAlreadyExists, MsoCloudSiteNotFound
+            throws MsoException
        {
                // Obtain the cloud site information where we will create the stack
-               CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId);
-               if (cloudSite == null) {
-                       throw new MsoCloudSiteNotFound(cloudSiteId);
-               }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
 
                Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
 
@@ -177,19 +174,15 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
         * @throws MsoCloudSiteNotFound
         */
-       public NetworkInfo queryNetwork (String networkNameOrId, String tenantId, String cloudSiteId)
-               throws MsoException, MsoCloudSiteNotFound
+    public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException
        {
                LOGGER.debug("In queryNetwork");
 
                // Obtain the cloud site information
-               CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId);
-               if (cloudSite == null) {
-                       throw new MsoCloudSiteNotFound(cloudSiteId);
-               }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
 
                Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
                // Check if the network exists and return its info
                try {
                        Network network = findNetworkByNameOrId (neutronClient, networkNameOrId);
@@ -215,24 +208,20 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * Delete the specified Network (by ID) in the given cloud.
         * If the network does not exist, success is returned.
         * <p>
-        * @param networkNameOrId The name or Openstack ID of the network to delete
-        * @param cloudId The cloud identifier (may be a region) from which to delete the network.
+        * @param networkId Openstack ID of the network to delete
+        * @param tenantId The Openstack tenant.
+        * @param cloudSiteId The cloud identifier (may be a region) from which to delete the network.
         * @return true if the network was deleted, false if the network did not exist
         * @throws MsoOpenstackException If the Openstack API call returns an exception, this local
         * exception will be thrown.
         * @throws MsoCloudSiteNotFound
         */
-       public boolean deleteNetwork (String networkId, String tenantId, String cloudSiteId)
-               throws MsoException, MsoCloudSiteNotFound
+    public boolean deleteNetwork(String networkId, String tenantId, String cloudSiteId) throws MsoException
        {
                // Obtain the cloud site information where we will create the stack
-               CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId);
-               if (cloudSite == null) {
-                       throw new MsoCloudSiteNotFound(cloudSiteId);
-               }
-
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
                Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
                try {
                        // Check that the network exists.
                        Network network = findNetworkById (neutronClient, networkId);
@@ -273,7 +262,7 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * to manage the virtual networking).
         *
         * @param cloudSiteId The cloud site ID (may be a region) in which to update the network.
-        * @param the Openstack ID of the tenant in which to update the network
+        * @param tenantId Openstack ID of the tenant in which to update the network
         * @param networkId The unique Openstack ID of the network to be updated
         * @param type The network type (Basic, Provider, Multi-Provider)
         * @param provider The provider network name.  This should not change.
@@ -284,15 +273,12 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * @throws MsoCloudSiteNotFound
         */
        public NetworkInfo updateNetwork (String cloudSiteId, String tenantId, String networkId, NetworkType type, String provider, List<Integer> vlans)
-               throws MsoException, MsoNetworkNotFound, MsoCloudSiteNotFound
+            throws MsoException
        {
                // Obtain the cloud site information where we will create the stack
-               CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId);
-               if (cloudSite == null) {
-                       throw new MsoCloudSiteNotFound(cloudSiteId);
-               }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
                Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
                // Check that the network exists
                Network network = findNetworkById (neutronClient, networkId);
 
@@ -359,8 +345,7 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * @param tenantId - Openstack tenant ID
         * @return an authenticated Quantum object
         */
-       private Quantum getNeutronClient (CloudSite cloudSite, String tenantId)
-               throws MsoTenantNotFound, MsoException
+    private Quantum getNeutronClient(CloudSite cloudSite, String tenantId) throws MsoException
        {
                String cloudId = cloudSite.getId();
 
@@ -440,9 +425,6 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * the KeystoneClient in case where a tenant is deleted.  In that case,
         * all cached credentials must be purged so that fresh authentication is
         * done on subsequent calls.
-        * <p>
-        * @param tenantName
-        * @param cloudId
         */
        public static void expireNeutronClient (String tenantId, String cloudId) {
                String cacheKey = cloudId + ":" + tenantId;
@@ -602,6 +584,6 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * This may be useful if cached credentials get out of sync.
         */
        public static void neutronCacheReset () {
-               neutronClientCache = new HashMap<String,NeutronCacheEntry>();
+               neutronClientCache = new HashMap<>();
        }
 }
index 4a19828..2cd4597 100644 (file)
 package org.openecomp.mso.openstack.utils;
 
 
-import java.io.Serializable;
-import java.util.Calendar;
-import java.util.HashMap;
 import java.util.Map;
-
 import org.openecomp.mso.cloud.CloudConfig;
 import org.openecomp.mso.cloud.CloudConfigFactory;
 import org.openecomp.mso.cloud.CloudIdentity;
-import org.openecomp.mso.logger.MsoAlarmLogger;
-import org.openecomp.mso.logger.MsoLogger;
 import org.openecomp.mso.logger.MessageEnum;
+import org.openecomp.mso.logger.MsoLogger;
 import org.openecomp.mso.openstack.beans.MsoTenant;
-import org.openecomp.mso.openstack.exceptions.MsoAdapterException;
 import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound;
 import org.openecomp.mso.openstack.exceptions.MsoException;
-import org.openecomp.mso.openstack.exceptions.MsoOpenstackException;
-import org.openecomp.mso.openstack.exceptions.MsoTenantAlreadyExists;
 import org.openecomp.mso.properties.MsoJavaProperties;
 import org.openecomp.mso.properties.MsoPropertiesException;
 import org.openecomp.mso.properties.MsoPropertiesFactory;
-import com.woorea.openstack.keystone.Keystone;
 
 public abstract class MsoTenantUtils extends MsoCommonUtils {
 
index a659fb6..e36d468 100644 (file)
@@ -26,6 +26,7 @@ import org.openecomp.mso.cloud.CloudIdentity;
 import org.openecomp.mso.cloud.CloudSite;
 
 import java.lang.reflect.InvocationTargetException;
+import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound;
 
 
 public class MsoTenantUtilsFactory {
@@ -39,12 +40,11 @@ public class MsoTenantUtilsFactory {
        }
 
        //based on Cloud IdentityServerType returns ORM or KEYSTONE Utils
-       public MsoTenantUtils getTenantUtils(String cloudSiteId) {
-
+       public MsoTenantUtils getTenantUtils(String cloudSiteId) throws MsoCloudSiteNotFound {
                // Obtain the cloud site information
                cloudConfig = cloudConfigFactory.getCloudConfig();
-               CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-
+               CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                               () -> new MsoCloudSiteNotFound(cloudSiteId));
                return getTenantUtilsByServerType(cloudSite.getIdentityService().getIdentityServerType().toString());
        }
 
index 6bd7815..2502118 100644 (file)
@@ -22,18 +22,15 @@ package org.openecomp.mso.adapter_utils.tests;
 \r
 import static org.junit.Assert.assertTrue;\r
 \r
-import com.woorea.openstack.heat.model.Stack;\r
 import java.util.ArrayList;\r
 import java.util.HashMap;\r
 import java.util.List;\r
 import java.util.Map;\r
 import org.junit.Test;\r
 import org.openecomp.mso.entity.MsoRequest;\r
-import org.openecomp.mso.openstack.beans.HeatStatus;\r
 import org.openecomp.mso.openstack.beans.MsoTenant;\r
 import org.openecomp.mso.openstack.beans.NetworkRollback;\r
 import org.openecomp.mso.openstack.beans.Pool;\r
-import org.openecomp.mso.openstack.beans.StackInfo;\r
 import org.openecomp.mso.openstack.beans.Subnet;\r
 import org.openecomp.mso.openstack.beans.VnfRollback;\r
 \r
@@ -98,26 +95,6 @@ public class AdapterBeansTest {
                p.toString();\r
        }\r
 \r
-       @Test\r
-       public final void stackInfoTest() {\r
-               StackInfo stackInfo = new StackInfo();\r
-               new StackInfo(new Stack());\r
-               new StackInfo("name", HeatStatus.CREATED, "statusmessage", new HashMap<>());\r
-               new StackInfo("name", HeatStatus.CREATED);\r
-               stackInfo.setCanonicalName("Canonicalname");\r
-               stackInfo.getCanonicalName();\r
-               stackInfo.setName("name");\r
-               stackInfo.getName();\r
-               stackInfo.setOutputs(new HashMap<>());\r
-               stackInfo.getOutputs();\r
-               stackInfo.setParameters(new HashMap<>());\r
-               stackInfo.getParameters();\r
-               stackInfo.setStatus(HeatStatus.CREATED);\r
-               stackInfo.getStatus();\r
-               stackInfo.setStatusMessage("statusMessage");\r
-               stackInfo.getStatusMessage();\r
-       }\r
-\r
        @Test\r
        public final void subnetTest() {\r
                Subnet subnet = new Subnet();\r
index 714bb66..62043e8 100644 (file)
@@ -26,6 +26,7 @@ import static org.mockito.Mockito.when;
 import java.util.HashMap;
 import java.util.Map;
 
+import java.util.Optional;
 import org.junit.Before;
 import org.junit.Ignore;
 import org.junit.Test;
@@ -68,8 +69,8 @@ public class MsoHeatUtilsWithUpdateTest {
         cloudIdentity.setKeystoneUrl ("toto");
         cloudIdentity.setMsoPass (CloudIdentity.encryptPassword ("mockId"));
         cloudSite.setIdentityService (cloudIdentity);
-        when (cloudConfig.getCloudSite ("cloud")).thenReturn (cloudSite);
-        when (cloudConfig.getCloudSite ("none")).thenReturn (null);
+        when(cloudConfig.getCloudSite("cloud")).thenReturn (Optional.of(cloudSite));
+        when(cloudConfig.getCloudSite("none")).thenReturn (Optional.empty());
     }
 
     @Test
index a73e435..1c2501e 100644 (file)
@@ -26,6 +26,7 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
+import java.util.Optional;
 import org.junit.Assert;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -112,29 +113,29 @@ public class CloudConfigTest {
     @Test
     public void cloudSiteIsGotById_when_IdFound() throws MsoCloudIdentityNotFound {
         CloudConfig con = createTestObject(cloudConfigJsonFilePath);
-        CloudSite cloudSite = con.getCloudSite("MT");
-        assertNotNull(cloudSite);
-        assertEquals("regionOne", cloudSite.getRegionId());
-        assertEquals("MT_KEYSTONE", cloudSite.getIdentityServiceId());
+        Optional<CloudSite> cloudSite = con.getCloudSite("MT");
+        assertTrue(cloudSite.isPresent());
+        assertEquals("regionOne", cloudSite.get().getRegionId());
+        assertEquals("MT_KEYSTONE", cloudSite.get().getIdentityServiceId());
     }
 
     @Test
     public void cloudSiteIsGotByClli_when_IdNotFound() throws MsoCloudIdentityNotFound {
         CloudConfig con = createTestObject(cloudConfigJsonFilePath);
-        CloudSite cloudSite = con.getCloudSite("CS_clli");
-        assertNotNull(cloudSite);
-        assertEquals("clliRegion", cloudSite.getRegionId());
-        assertEquals("CS_clli", cloudSite.getClli());
-        assertEquals("CS_service", cloudSite.getIdentityServiceId());
+        Optional<CloudSite> cloudSite = con.getCloudSite("CS_clli");
+        assertTrue(cloudSite.isPresent());
+        assertEquals("clliRegion", cloudSite.get().getRegionId());
+        assertEquals("CS_clli", cloudSite.get().getClli());
+        assertEquals("CS_service", cloudSite.get().getIdentityServiceId());
     }
 
     @Test
     public void cloudSiteIsGotByDefault_when_IdAndClliNotFound() throws MsoCloudIdentityNotFound {
         CloudConfig con = createTestObject(cloudDefaultConfigJsonFilePath);
-        CloudSite cloudSite = con.getCloudSite("not_existing_id");
-        assertNotNull(cloudSite);
-        assertEquals("not_existing_id", cloudSite.getId());
-        assertEquals("not_existing_id", cloudSite.getRegionId());
+        Optional<CloudSite> cloudSite = con.getCloudSite("not_existing_id");
+        assertTrue(cloudSite.isPresent());
+        assertEquals("not_existing_id", cloudSite.get().getId());
+        assertEquals("not_existing_id", cloudSite.get().getRegionId());
     }
 
     @Test
diff --git a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/authentication/AuthenticationMethodFactoryTest.java b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/authentication/AuthenticationMethodFactoryTest.java
new file mode 100644 (file)
index 0000000..2cfce27
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * ============LICENSE_START==========================================
+ * ===================================================================
+ * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END============================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ *
+ */
+
+package org.openecomp.mso.cloud.authentication;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.woorea.openstack.keystone.model.Authentication;
+import org.junit.Test;
+import org.openecomp.mso.cloud.CloudIdentity;
+import org.openecomp.mso.cloud.CloudIdentity.IdentityAuthenticationType;
+import org.openecomp.mso.cloud.authentication.wrappers.RackspaceAPIKeyWrapper;
+
+public class AuthenticationMethodFactoryTest {
+
+    private static final Class WRAPPER_CLASS = RackspaceAPIKeyWrapper.class;
+    private static final String AUTHENTICATION_TYPE = "authenticationTest";
+
+    @Test
+    public void register_NoExceptionThrown() throws IllegalAccessException, InstantiationException {
+        AuthenticationMethodFactory.register(AUTHENTICATION_TYPE, WRAPPER_CLASS);
+    }
+
+    @Test
+    public void register_throwExceptionWhenAuthTypeIsNull() throws InstantiationException, IllegalAccessException {
+        try {
+            AuthenticationMethodFactory.register(null, WRAPPER_CLASS);
+        } catch (IllegalArgumentException e) {
+            assertThat(e.getMessage()).isNotEmpty().contains("Authentication Type to register cannot be null "
+                    + "or an empty name string");
+        }
+    }
+
+    @Test
+    public void register_throwExceptionWhenAuthTypeIsEmpty() throws InstantiationException, IllegalAccessException {
+        try {
+            AuthenticationMethodFactory.register("", WRAPPER_CLASS);
+        } catch (IllegalArgumentException e) {
+            assertThat(e.getMessage()).isNotEmpty().contains("Authentication Type to register cannot be null "
+                    + "or an empty name string");
+        }
+    }
+
+    @Test
+    public void register_throwExceptionWhenWrapperIsNull() throws IllegalAccessException, InstantiationException {
+        try {
+            AuthenticationMethodFactory.register(AUTHENTICATION_TYPE, null);
+        } catch (IllegalArgumentException e) {
+            assertThat(e.getMessage()).isNotEmpty()
+                    .contains("Wrapper Class to register for Authentication cannot be null");
+        }
+    }
+
+    @Test
+    public void getAuthentication_NoExceptionThrown() {
+        CloudIdentity cloudIdentity = new CloudIdentity();
+        cloudIdentity.setIdentityAuthenticationType(IdentityAuthenticationType.RACKSPACE_APIKEY);
+        cloudIdentity.setMsoId("msoIdTest");
+        cloudIdentity.setMsoPass("123");
+        Authentication result = AuthenticationMethodFactory.getAuthenticationFor(cloudIdentity);
+        assertThat(result).isNotNull();
+    }
+
+    @Test
+    public void getAuthentication_ThrowExWhenCloudSiteIsNull() {
+        try {
+            AuthenticationMethodFactory.getAuthenticationFor(null);
+        } catch (IllegalArgumentException e) {
+            assertThat(e.getMessage()).isNotEmpty().contains("Cloud identity cannot be null");
+        }
+    }
+
+    @Test
+    public void getAuthentication_ThrowExWhenIdentityAuthenticationTypeIsNotSet() {
+        try {
+            AuthenticationMethodFactory.getAuthenticationFor(new CloudIdentity());
+        } catch (IllegalArgumentException e) {
+            assertThat(e.getMessage()).isNotEmpty()
+                    .contains("Cloud identity authentication type cannot be null or empty");
+        }
+    }
+
+}
index ccfede7..b6c1c73 100644 (file)
@@ -25,16 +25,11 @@ package org.openecomp.mso.cloud.authentication;
 \r
 import static org.junit.Assert.assertTrue;\r
 \r
-import java.io.IOException;\r
-import java.net.URISyntaxException;\r
-\r
+import com.woorea.openstack.keystone.model.Authentication;\r
+import com.woorea.openstack.keystone.model.authentication.UsernamePassword;\r
 import org.junit.Test;\r
 import org.openecomp.mso.cloud.CloudIdentity;\r
 import org.openecomp.mso.cloud.authentication.models.RackspaceAuthentication;\r
-import org.openecomp.mso.openstack.exceptions.MsoException;\r
-\r
-import com.woorea.openstack.keystone.model.Authentication;\r
-import com.woorea.openstack.keystone.model.authentication.UsernamePassword;\r
 \r
 /**\r
  * A few JUnit tests to evaluate the new factory that manages authentication\r
@@ -50,52 +45,15 @@ public class AuthenticationMethodTest {
        public AuthenticationMethodTest() {\r
                // TODO Auto-generated constructor stub\r
        }\r
-       \r
-       @Test\r
-       public void testCustomRackspaceAuth() {\r
-               CloudIdentity ci = new CloudIdentity();\r
-               ci.setIdentityAuthenticationType(CloudIdentity.IdentityAuthenticationType.RACKSPACE_APIKEY);\r
-               ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");\r
-               ci.setMsoId("test");\r
-               \r
-               try {\r
-                       Authentication auth = AuthenticationMethodFactory.getAuthenticationFor(ci);\r
-                       assertTrue(RackspaceAuthentication.class.equals(auth.getClass()));\r
-               } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | IOException\r
-                               | URISyntaxException e) {\r
-                       e.printStackTrace();\r
-               }\r
-       }\r
-       \r
-       @Test\r
-       public void testCoreUsernamePasswordAuth() {\r
-               CloudIdentity ci = new CloudIdentity();\r
-               ci.setIdentityAuthenticationType(CloudIdentity.IdentityAuthenticationType.USERNAME_PASSWORD);\r
-               ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");\r
-               ci.setMsoId("someuser");\r
-               \r
-               try {\r
-                       Authentication auth = AuthenticationMethodFactory.getAuthenticationFor(ci);\r
-                       assertTrue(UsernamePassword.class.equals(auth.getClass()));\r
-               } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | IOException\r
-                               | URISyntaxException e) {\r
-                       e.printStackTrace();\r
-               }\r
-       }\r
-       \r
+\r
        @Test\r
        public void testCustomRackspaceAuthFromCloudIdentity() {\r
                CloudIdentity ci = new CloudIdentity();\r
                ci.setIdentityAuthenticationType(CloudIdentity.IdentityAuthenticationType.RACKSPACE_APIKEY);\r
                ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");\r
                ci.setMsoId("test");\r
-               \r
-               try {\r
-                       Authentication auth = ci.getAuthentication();\r
-                       assertTrue(RackspaceAuthentication.class.equals(auth.getClass()));\r
-               } catch (MsoException e) {\r
-                       e.printStackTrace();\r
-               }\r
+               Authentication auth = ci.getAuthentication();\r
+               assertTrue(RackspaceAuthentication.class.equals(auth.getClass()));\r
        }\r
        \r
        @Test\r
@@ -104,12 +62,7 @@ public class AuthenticationMethodTest {
                ci.setIdentityAuthenticationType(CloudIdentity.IdentityAuthenticationType.USERNAME_PASSWORD);\r
                ci.setMsoPass("FD205490A48D48475607C36B9AD902BF");\r
                ci.setMsoId("someuser");\r
-               \r
-               try {\r
-                       Authentication auth = ci.getAuthentication();\r
-                       assertTrue(UsernamePassword.class.equals(auth.getClass()));\r
-               } catch (MsoException e) {\r
-                       e.printStackTrace();\r
-               }\r
+               Authentication auth = ci.getAuthentication();\r
+               assertTrue(UsernamePassword.class.equals(auth.getClass()));\r
        }\r
 }\r
diff --git a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/beans/StackInfoTest.java b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/beans/StackInfoTest.java
new file mode 100644 (file)
index 0000000..9c7911e
--- /dev/null
@@ -0,0 +1,98 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.mso.openstack.beans;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.woorea.openstack.heat.model.Stack;
+import java.io.IOException;
+import org.codehaus.jackson.JsonNode;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.junit.Test;
+
+public class StackInfoTest {
+
+    private static final String STACK_NAME = "stackNameTest";
+    private static final String STACK_STATUS = "CREATE_COMPLETE";
+    private static final String STACK_OUTPUT_KEY = "outputKeyTest";
+    private static final String STACK_OUTPUT_VALUE = "outputValueTest";
+    private static final String STACK_PARAM_KEY = "paramKeyTest";
+    private static final String STACK_PARAM_VALUE = "paramValueTest";
+
+    @Test
+    public void setStatusNotFoundWhenStackIsNull() {
+        StackInfo stackInfo = new StackInfo(null);
+        assertThat(stackInfo.getStatus()).isEqualTo(HeatStatus.NOTFOUND);
+        assertThat(stackInfo.getOutputs()).isEmpty();
+        assertThat(stackInfo.getParameters()).isEmpty();
+    }
+
+    @Test
+    public void createObjectWhenStackStatusIsNull() {
+        StackInfo stackInfo = new StackInfo(createStackWithStatus(null));
+        assertThat(stackInfo.getName()).isEqualTo(STACK_NAME);
+        assertThat(stackInfo.getOutputs()).isEmpty();
+        assertThat(stackInfo.getStatus()).isEqualTo(HeatStatus.INIT);
+        assertThat(stackInfo.getParameters()).hasSize(1).containsEntry(STACK_PARAM_KEY, STACK_PARAM_VALUE);
+    }
+
+    @Test
+    public void createObjectWhenStackStatusIsFound() {
+        StackInfo stackInfo = new StackInfo(createStackWithStatus(STACK_STATUS));
+        assertThat(stackInfo.getName()).isEqualTo(STACK_NAME);
+        assertThat(stackInfo.getOutputs()).isEmpty();
+        assertThat(stackInfo.getStatus()).isEqualTo(HeatStatus.CREATED);
+        assertThat(stackInfo.getParameters()).hasSize(1).containsEntry(STACK_PARAM_KEY, STACK_PARAM_VALUE);
+    }
+
+    @Test
+    public void createObjectWhenStackStatusIsUnknown() {
+        StackInfo stackInfo = new StackInfo(createStackWithStatus("unknownStatus"));
+        assertThat(stackInfo.getName()).isEqualTo(STACK_NAME);
+        assertThat(stackInfo.getOutputs()).isEmpty();
+        assertThat(stackInfo.getStatus()).isEqualTo(HeatStatus.UNKNOWN);
+        assertThat(stackInfo.getParameters()).hasSize(1).containsEntry(STACK_PARAM_KEY, STACK_PARAM_VALUE);
+    }
+
+    @Test
+    public void createStackWhenOutputsListIsNotNull() throws IOException {
+        StackInfo stackInfo = new StackInfo(createStackWithOutputs());
+        assertThat(stackInfo.getOutputs()).isNotEmpty().hasSize(1);
+        assertThat(stackInfo.getOutputs()).hasSize(1).containsEntry(STACK_OUTPUT_KEY, STACK_OUTPUT_VALUE);
+    }
+
+    private Stack createStackWithStatus(String stackStatus) {
+        Stack stack = new Stack();
+        stack.setStackName(STACK_NAME);
+        stack.setStackStatus(stackStatus);
+        stack.getParameters().put(STACK_PARAM_KEY, STACK_PARAM_VALUE);
+        return stack;
+    }
+
+    private Stack createStackWithOutputs() throws IOException {
+        String json = "{\"outputs\":[{\"output_key\" : \"" + STACK_OUTPUT_KEY + "\", \"output_value\" : \""
+                + STACK_OUTPUT_VALUE + "\" }]}";
+        JsonNode node = new ObjectMapper().readTree(json);
+        Stack stack = new ObjectMapper().readValue(node, Stack.class);
+        return stack;
+    }
+
+}
diff --git a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntryTest.java b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntryTest.java
new file mode 100644 (file)
index 0000000..60faa76
--- /dev/null
@@ -0,0 +1,79 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.mso.openstack.utils;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.Test;
+
+public class MsoHeatEnvironmentEntryTest {
+
+    private static final String PARAMETER_NAME = "keyTest";
+    private static final String VALUE_NAME = "valueTest";
+    private static final String NOT_EXISTING_PARAM = "notExistingParam";
+    private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY = "parameters: {"
+            + PARAMETER_NAME + ": " + VALUE_NAME + "}";
+    private static final String RAW_ENTRY_WITH_RESOURCE_REGISTRY = "resource_registry: resourceTest";
+    private static final String RAW_ENTRY_INVALID = "invalidRawEntry";
+    private static final String WHITESPACE = " ";
+
+    @Test
+    public void createObjectWithNullStringBuilder() {
+        MsoHeatEnvironmentEntry testedObject = MsoHeatEnvironmentEntry.create(null);
+        assertThat(testedObject.getRawEntry()).isNull();
+        assertThat(testedObject.containsParameter(PARAMETER_NAME)).isFalse();
+        assertThat(testedObject.isValid()).isTrue();
+    }
+
+    @Test
+    public void toFullString_ResourceRegistryNotPresentInRawEntry() {
+        MsoHeatEnvironmentEntry testedObject = MsoHeatEnvironmentEntry.create(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY);
+        assertThat(testedObject.getRawEntry()).isEqualTo(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY);
+        assertThat(testedObject.isValid()).isTrue();
+        assertThat(testedObject.containsParameter(PARAMETER_NAME)).isTrue();
+        assertThat(testedObject.toString()).contains(PARAMETER_NAME).contains(VALUE_NAME);
+    }
+
+    @Test
+    public void toFullString_ResourceRegistryPresentInRawEntry() {
+        MsoHeatEnvironmentEntry testedObject = MsoHeatEnvironmentEntry.create(RAW_ENTRY_WITH_RESOURCE_REGISTRY);
+        assertThat(testedObject.getRawEntry()).isEqualTo(RAW_ENTRY_WITH_RESOURCE_REGISTRY);
+        assertThat(testedObject.containsParameter(PARAMETER_NAME)).isFalse();
+        assertThat(testedObject.isValid()).isTrue();
+        assertThat(testedObject.toString()).contains(RAW_ENTRY_WITH_RESOURCE_REGISTRY);
+    }
+
+    @Test
+    public void toFullString_ExceptionOccurred() {
+        MsoHeatEnvironmentEntry testedObject = MsoHeatEnvironmentEntry.create(RAW_ENTRY_INVALID);
+        assertThat(testedObject.getRawEntry()).isEqualTo(RAW_ENTRY_INVALID);
+        assertThat(testedObject.isValid()).isFalse();
+        assertThat(testedObject.getErrorString()).isNotNull().isNotEmpty();
+    }
+
+    @Test
+    public void checkIfContainsTheParameter() {
+        MsoHeatEnvironmentEntry testedObject = MsoHeatEnvironmentEntry.create(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY);
+        assertThat(testedObject.containsParameter(PARAMETER_NAME)).isTrue();
+        assertThat(testedObject.containsParameter(NOT_EXISTING_PARAM)).isFalse();
+    }
+
+}
index f10500d..98cd183 100644 (file)
@@ -2,11 +2,11 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>adapters</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
-       <groupId>org.openecomp.so.adapters</groupId>
+       <groupId>org.onap.so.adapters</groupId>
        <artifactId>mso-adapters-rest-interface</artifactId>
        <packaging>jar</packaging>
        <name>mso-adapters-rest-interface</name>
@@ -44,7 +44,7 @@
                <version>3.0.19.Final</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so.adapters</groupId>
+                       <groupId>org.onap.so.adapters</groupId>
                        <artifactId>mso-adapter-utils</artifactId>
                        <version>${project.version}</version>
                </dependency>
index c9590ee..9bacb17 100644 (file)
@@ -2,12 +2,12 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>adapters</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
 
-       <groupId>org.openecomp.so.adapters</groupId>
+       <groupId>org.onap.so.adapters</groupId>
        <artifactId>mso-catalog-db-adapter</artifactId>
        <packaging>war</packaging>
 
@@ -65,7 +65,7 @@
 
        <dependencies>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>mso-catalog-db</artifactId>
                        <version>${project.version}</version>
                </dependency>
@@ -95,7 +95,7 @@
                        <version>3.0.16.Final</version>
                </dependency>
                <!--<dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>status-control</artifactId>
                        <version>${project.version}</version>
                </dependency>-->
index 309aa06..cb6ba1b 100644 (file)
@@ -104,10 +104,10 @@ public class QueryVfModule extends CatalogQuery {
                    put(valueMap, "MODEL_INVARIANT_ID",       vfNull ? null : o.getVfModule().getModelInvariantUuid());
                    put(valueMap, "MODEL_VERSION",            vfNull ? null : o.getVfModule().getVersion());
                    put(valueMap, "MODEL_CUSTOMIZATION_UUID", o.getModelCustomizationUuid());
-                   put(valueMap, "IS_BASE",                  vfNull ? false : new Boolean(o.getVfModule().isBase()? true: false));
-                   put(valueMap, "VF_MODULE_LABEL",          o.getLabel());
+                       put(valueMap, "IS_BASE", vfNull ? false : Boolean.valueOf(o.getVfModule().isBase() ? true : false));
+                       put(valueMap, "VF_MODULE_LABEL",          o.getLabel());
                    put(valueMap, "INITIAL_COUNT",            o.getInitialCount());
-                   put(valueMap, "HAS_VOLUME_GROUP",           new Boolean(hasVolumeGroup));
+                   put(valueMap, "HAS_VOLUME_GROUP", Boolean.valueOf(hasVolumeGroup));
 
             buf.append(sep+ this.setTemplate(template, valueMap));
             sep = ",\n";
index cc1ae6e..9920c72 100644 (file)
@@ -2,11 +2,11 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">\r
        <modelVersion>4.0.0</modelVersion>\r
        <parent>\r
-               <groupId>org.openecomp.so</groupId>\r
+               <groupId>org.onap.so</groupId>\r
                <artifactId>adapters</artifactId>\r
-               <version>1.2.0-SNAPSHOT</version>
+               <version>1.2.0-SNAPSHOT</version>\r
        </parent>\r
-       <groupId>org.openecomp.so.adapters</groupId>\r
+       <groupId>org.onap.so.adapters</groupId>\r
        <artifactId>mso-network-adapter-async-client</artifactId>\r
        <packaging>jar</packaging>\r
        <name>mso-network-adapter-async-client</name>\r
index 48b5b3e..48a19bd 100644 (file)
@@ -2,11 +2,11 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>adapters</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
-       <groupId>org.openecomp.so.adapters</groupId>
+       <groupId>org.onap.so.adapters</groupId>
        <artifactId>mso-network-adapter</artifactId>
        <packaging>war</packaging>
        <name>mso-network-adapter</name>
@@ -53,7 +53,7 @@
                                                <version>2.2.7</version>
                                        </dependency>
                                        <dependency>
-                                               <groupId>org.openecomp.so.adapters</groupId>
+                                               <groupId>org.onap.so.adapters</groupId>
                                                <artifactId>mso-adapter-utils</artifactId>
                                                <version>${project.version}</version>
                                        </dependency>
                        <scope>provided</scope>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so.adapters</groupId>
+                       <groupId>org.onap.so.adapters</groupId>
                        <artifactId>mso-adapter-utils</artifactId>
                        <version>${project.version}</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so.adapters</groupId>
+                       <groupId>org.onap.so.adapters</groupId>
                        <artifactId>mso-network-adapter-async-client</artifactId>
                        <version>${project.version}</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so.adapters</groupId>
+                       <groupId>org.onap.so.adapters</groupId>
                        <artifactId>mso-adapters-rest-interface</artifactId>
                        <version>${project.version}</version>
                </dependency>
                        <scope>provided</scope>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>status-control</artifactId>
                        <version>${project.version}</version>
                </dependency>
index 6879306..f050882 100644 (file)
@@ -26,6 +26,7 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
+import java.util.Optional;
 import javax.jws.WebService;
 import javax.xml.ws.Holder;
 
@@ -271,8 +272,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
         // So this is just catching that error in a bit more obvious way up front.
 
         cloudConfig = cloudConfigFactory.getCloudConfig ();
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null)
+        Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
+        if (!cloudSiteOpt.isPresent())
         {
                String error = "Configuration Error. Stack " + networkName + " in "
                                + cloudSiteId
@@ -299,7 +300,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                                                             physicalNetworkName,
                                                             vlans,
                                                             routeTargets,
-                                                            cloudSite);
+                                                            cloudSiteOpt.get());
             String mode = networkResource.getOrchestrationMode ();
             NetworkType neutronNetworkType = NetworkType.valueOf (networkResource.getNeutronNetworkType ());
 
@@ -787,8 +788,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
         networkRollback.setMsoRequest (msoRequest);
 
         cloudConfig = cloudConfigFactory.getCloudConfig ();
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
+        Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite (cloudSiteId);
+        if (!cloudSiteOpt.isPresent()) {
                   String error = "UpdateNetwork: Configuration Error. Stack " + networkName + " in "
                        + cloudSiteId
                        + "/"
@@ -814,7 +815,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                     physicalNetworkName,
                     vlans,
                     routeTargets,
-                    cloudSite);
+                    cloudSiteOpt.get());
             String mode = networkResource.getOrchestrationMode();
             NetworkType neutronNetworkType = NetworkType.valueOf(networkResource.getNeutronNetworkType());
 
@@ -1233,7 +1234,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                               Holder <NetworkStatus> status,
                               Holder <List <Integer>> vlans,
                               Holder <Map <String, String>> subnetIdMap) throws NetworkException {
-        queryNetwork (cloudSiteId,
+        queryNetworkInfo(cloudSiteId,
                       tenantId,
                       networkNameOrId,
                       msoRequest,
@@ -1242,7 +1243,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                       neutronNetworkId,
                       status,
                       vlans,
-                      null,
                       subnetIdMap);
     }
 
@@ -1257,7 +1257,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                                       Holder <NetworkStatus> status,
                                       Holder <List <String>> routeTargets,
                                       Holder <Map <String, String>> subnetIdMap) throws NetworkException {
-        queryNetwork (cloudSiteId,
+        queryNetworkInfo(cloudSiteId,
                       tenantId,
                       networkNameOrId,
                       msoRequest,
@@ -1266,18 +1266,17 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                       neutronNetworkId,
                       status,
                       null,
-                      routeTargets,
                       subnetIdMap);
     }
 
     /**
-     * This is the queryNetwork method. It returns the existence and status of
+     * This is the queryNetworkInfo method. It returns the existence and status of
      * the specified network, along with its Neutron UUID and list of VLANs.
      * This method attempts to find the network using both Heat and Neutron.
      * Heat stacks are first searched based on the provided network name/id.
      * If none is found, the Neutron is directly queried.
      */
-    private void queryNetwork (String cloudSiteId,
+    private void queryNetworkInfo(String cloudSiteId,
                               String tenantId,
                               String networkNameOrId,
                               MsoRequest msoRequest,
@@ -1286,7 +1285,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                               Holder <String> neutronNetworkId,
                               Holder <NetworkStatus> status,
                               Holder <List <Integer>> vlans,
-                              Holder <List <String>> routeTargets,
                               Holder <Map <String, String>> subnetIdMap) throws NetworkException {
         MsoLogger.setLogContext (msoRequest);
         MsoLogger.setServiceName ("QueryNetwork");
@@ -1309,9 +1307,9 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
             throw new NetworkException (error, MsoExceptionCategory.USERDATA);
         }
 
-        cloudConfig = cloudConfigFactory.getCloudConfig ();
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null)
+        cloudConfig = cloudConfigFactory.getCloudConfig();
+        Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
+        if (!cloudSiteOpt.isPresent())
         {
                String error = "Configuration Error. Stack " + networkNameOrId + " in "
                                + cloudSiteId
@@ -1414,7 +1412,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                 status.value = NetworkStatus.NOTFOUND;
                 neutronNetworkId.value = null;
                 if (vlans != null)
-                       vlans.value = new ArrayList <Integer> ();
+                       vlans.value = new ArrayList<>();
 
                 LOGGER.debug ("Network " + networkNameOrId + " not found");
             }
@@ -1987,16 +1985,16 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                String outputTempl = "  subnet_id_%subnetId%:\n" + "    description: Openstack subnet identifier\n"
                                + "    value: {get_resource: subnet_%subnetId%}\n";
 
-               String curR;
+               StringBuilder curR;
                String curO;
                StringBuilder resourcesBuf = new StringBuilder ();
                StringBuilder outputsBuf = new StringBuilder ();
                for (Subnet subnet : subnets) {
 
                        // build template for each subnet
-                       curR = resourceTempl;
+                       curR = new StringBuilder(resourceTempl);
                        if (subnet.getSubnetId () != null) {
-                               curR = curR.replace ("%subnetId%", subnet.getSubnetId ());
+                               curR = new StringBuilder(curR.toString().replace("%subnetId%", subnet.getSubnetId()));
                        } else {
                                String error = "Missing Required AAI SubnetId for subnet in HEAT Template";
                                LOGGER.error (MessageEnum.RA_MISSING_PARAM, error, "Openstack", "", MsoLogger.ErrorCode.DataError, "Missing Required AAI ID  for subnet in HEAT Template");
@@ -2004,13 +2002,13 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                        }
 
                        if (subnet.getSubnetName () != null) {
-                               curR = curR.replace ("%name%", subnet.getSubnetName ());
+                               curR = new StringBuilder(curR.toString().replace("%name%", subnet.getSubnetName()));
                        } else {
-                               curR = curR.replace ("%name%", subnet.getSubnetId ());
+                               curR = new StringBuilder(curR.toString().replace("%name%", subnet.getSubnetId()));
                        }
 
                        if (subnet.getCidr () != null) {
-                               curR = curR.replace ("%cidr%", subnet.getCidr ());
+                               curR = new StringBuilder(curR.toString().replace("%cidr%", subnet.getCidr()));
                        } else {
                                String error = "Missing Required cidr for subnet in HEAT Template";
                                LOGGER.error (MessageEnum.RA_MISSING_PARAM, error, "Openstack", "", MsoLogger.ErrorCode.DataError, "Missing Required cidr for subnet in HEAT Template");
@@ -2018,23 +2016,23 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                        }
 
                        if (subnet.getIpVersion () != null) {
-                               curR = curR + "      ip_version: " + subnet.getIpVersion () + "\n";
+                               curR.append("      ip_version: " + subnet.getIpVersion() + "\n");
                        }
                        if (subnet.getEnableDHCP () != null) {
-                               curR = curR + "      enable_dhcp: " +  Boolean.toString (subnet.getEnableDHCP ()) + "\n";
+                               curR.append("      enable_dhcp: ").append(Boolean.toString(subnet.getEnableDHCP())).append("\n");
                        }
                        if (subnet.getGatewayIp () != null && !subnet.getGatewayIp ().isEmpty() ) {
-                               curR = curR + "      gateway_ip: " + subnet.getGatewayIp () + "\n";
+                               curR.append("      gateway_ip: " + subnet.getGatewayIp() + "\n");
                        }
 
                        if (subnet.getAllocationPools() != null) {
-                               curR = curR + "      allocation_pools:\n";
+                               curR.append("      allocation_pools:\n");
                                for (Pool pool : subnet.getAllocationPools())
                                {
                                        if (!isNullOrEmpty(pool.getStart()) && !isNullOrEmpty(pool.getEnd()))
                                        {
-                                               curR = curR + "       - start: " + pool.getStart () + "\n";
-                                               curR = curR + "         end: " + pool.getEnd () + "\n";
+                                               curR.append("       - start: " + pool.getStart() + "\n");
+                                               curR.append("         end: " + pool.getEnd() + "\n");
                                        }
                                }
                        }
index ed8b2b3..8bec34e 100644 (file)
@@ -2,12 +2,12 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>adapters</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
 
-       <groupId>org.openecomp.so.adapters</groupId>
+       <groupId>org.onap.so.adapters</groupId>
        <artifactId>mso-requests-db-adapter</artifactId>
        <packaging>war</packaging>
 
@@ -15,7 +15,7 @@
        <dependencies>
 
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>mso-requests-db</artifactId>
                        <version>${project.version}</version>
                </dependency>
@@ -40,7 +40,7 @@
                        </exclusions>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>status-control</artifactId>
                        <version>${project.version}</version>
                </dependency>
@@ -85,7 +85,7 @@
                                                <version>2.2.7</version>
                                        </dependency>
                                        <dependency>
-                                               <groupId>org.openecomp.so.adapters</groupId>
+                                               <groupId>org.onap.so.adapters</groupId>
                                                <artifactId>mso-adapter-utils</artifactId>
                                                <version>${project.version}</version>
                                        </dependency>
index e7cb4d5..b0457e9 100644 (file)
@@ -2,11 +2,11 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>adapters</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
-       <groupId>org.openecomp.so.adapters</groupId>
+       <groupId>org.onap.so.adapters</groupId>
        <artifactId>mso-sdnc-adapter</artifactId>
        <packaging>war</packaging>
        <name>mso-sdnc-adapter</name>
@@ -67,7 +67,7 @@
        </build>
        <dependencies>
                <dependency>
-                       <groupId>org.openecomp.so.adapters</groupId>
+                       <groupId>org.onap.so.adapters</groupId>
                        <artifactId>mso-adapter-utils</artifactId>
                        <version>${project.version}</version>
 
                        <scope>provided</scope>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>status-control</artifactId>
                        <version>${project.version}</version>
                </dependency>
         <dependency>
-            <groupId>org.openecomp.so.adapters</groupId>
+            <groupId>org.onap.so.adapters</groupId>
             <artifactId>mso-adapters-rest-interface</artifactId>
             <version>${project.version}</version>
         </dependency>
index 97f30be..45d5944 100644 (file)
@@ -197,7 +197,7 @@ public class SDNCRestClient implements Runnable {
                        //default
                        sdncResp.setRespCode(HttpURLConnection.HTTP_INTERNAL_ERROR);
                        String respMsg = "Error processing request to SDNC. ";
-                       String sdncErrMsg = "";
+                       StringBuilder sdncErrMsg = new StringBuilder();
 
                        if (e instanceof java.net.SocketTimeoutException )
                        {
@@ -229,7 +229,7 @@ public class SDNCRestClient implements Runnable {
                                                                String eType = null;
                                                                try {
                                                                        eType = xpath.evaluate("error-type", error);
-                                                                       sdncErrMsg = ". SDNC Returned-[error-type:" + eType;
+                                                                       sdncErrMsg = new StringBuilder(". SDNC Returned-[error-type:" + eType);
                                                                } catch (Exception e3) {
                                                                    msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-type", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while evaluate xpath", e3);
                                                                }
@@ -237,7 +237,7 @@ public class SDNCRestClient implements Runnable {
                                                                String eTag = null;
                                                                try {
                                                                        eTag = xpath.evaluate( "error-tag", error);
-                                                                       sdncErrMsg = sdncErrMsg + ", error-tag:" + eTag;
+                                                                       sdncErrMsg.append(", error-tag:").append(eTag);
                                                                } catch (Exception e3) {
                                                                        msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-tag", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while evaluate xpath", e3);
                                                                }
@@ -245,7 +245,7 @@ public class SDNCRestClient implements Runnable {
                                                                String eMsg = null;
                                                                try {
                                                                        eMsg = xpath.evaluate("error-message", error);
-                                                                       sdncErrMsg = sdncErrMsg + ", error-message:" + eMsg + "]";
+                                                                       sdncErrMsg.append(", error-message:").append(eMsg).append("]");
                                                                } catch (Exception e3) {
                                                                        msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-message", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while evaluate xpath", e3);
                                                                }
index 262d23b..be0466a 100644 (file)
@@ -257,7 +257,7 @@ public abstract class SDNCConnector {
                //   </error>
                // </errors>
 
-               String output = null;
+               StringBuilder output = null;
 
                try {
                        XPathFactory xpathFactory = XPathFactory.newInstance();
@@ -306,9 +306,9 @@ public abstract class SDNCConnector {
 
                                if (!info.isEmpty()) {
                                        if (output == null) {
-                                               output = "[" + info + "]";
+                                               output = new StringBuilder("[" + info + "]");
                                        } else {
-                                               output += " [" + info + "]";
+                                               output.append(" [").append(info).append("]");
                                        }
                                }
                        }
@@ -317,6 +317,6 @@ public abstract class SDNCConnector {
                                MsoLogger.ErrorCode.DataError, "Exception while analyzing errors", e);
                }
 
-               return output;
+               return output.toString();
        }
 }
diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/openecomp/mso/adapters/sdnc/SDNCAdapterRequestTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/openecomp/mso/adapters/sdnc/SDNCAdapterRequestTest.java
new file mode 100644 (file)
index 0000000..fa96b79
--- /dev/null
@@ -0,0 +1,54 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+
+package org.openecomp.mso.adapters.sdnc;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.openecomp.mso.adapters.sdnc.SDNCAdapterRequest;
+import org.openecomp.mso.adapters.sdnc.RequestHeader;
+
+
+public class SDNCAdapterRequestTest {
+
+       static Object sd= new SDNCAdapterRequest();
+       static RequestHeader rh=new RequestHeader();
+       
+       @BeforeClass
+       public static final void RHeader()
+       {
+               rh.setCallbackUrl("callback");
+               rh.setMsoAction ("action");
+               rh.setRequestId ("reqid");
+               rh.setSvcAction ("svcAction");
+               rh.setSvcInstanceId ("svcId");
+               rh.setSvcOperation ("op");
+       }
+       @Test
+       public final void testtoString(){
+               ((SDNCAdapterRequest) sd).setRequestData("data");
+               ((SDNCAdapterRequest) sd).setRequestHeader(rh);
+        assert (((SDNCAdapterRequest) sd).getRequestData()!= null) ;
+               assert(((SDNCAdapterRequest) sd).getRequestData().equals("data"));
+               assert(((SDNCAdapterRequest) sd).getRequestHeader().equals(rh));                
+       }
+
+}
index 1479b28..916c3a7 100644 (file)
@@ -2,11 +2,11 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>adapters</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
-       <groupId>org.openecomp.so.adapters</groupId>
+       <groupId>org.onap.so.adapters</groupId>
        <artifactId>mso-tenant-adapter</artifactId>
        <packaging>war</packaging>
        <name>mso-tenant-adapter</name>
@@ -72,7 +72,7 @@
                                                <version>2.2.7</version>
                                        </dependency>
                                        <dependency>
-                                               <groupId>org.openecomp.so.adapters</groupId>
+                                               <groupId>org.onap.so.adapters</groupId>
                                                <artifactId>mso-adapter-utils</artifactId>
                                                <version>${project.version}</version>
                                        </dependency>
        </build>
        <dependencies>
                <dependency>
-                       <groupId>org.openecomp.so.adapters</groupId>
+                       <groupId>org.onap.so.adapters</groupId>
                        <artifactId>mso-adapter-utils</artifactId>
                        <version>${project.version}</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so.adapters</groupId>
+                       <groupId>org.onap.so.adapters</groupId>
                        <artifactId>mso-adapters-rest-interface</artifactId>
                        <version>${project.version}</version>
                </dependency>
                        <scope>provided</scope>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>status-control</artifactId>
                        <version>${project.version}</version>
                </dependency>
index 29f5630..58169f6 100644 (file)
@@ -28,6 +28,7 @@ import javax.jws.WebService;
 import javax.xml.ws.Holder;
 import javax.xml.ws.WebServiceContext;
 
+import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound;
 import org.openecomp.mso.properties.MsoPropertiesFactory;
 import org.openecomp.mso.adapters.tenant.exceptions.TenantAlreadyExists;
 import org.openecomp.mso.adapters.tenant.exceptions.TenantException;
@@ -84,7 +85,7 @@ public class MsoTenantAdapterImpl implements MsoTenantAdapter {
                               Boolean backout,
                               MsoRequest msoRequest,
                               Holder <String> tenantId,
-                              Holder <TenantRollback> rollback) throws TenantException, TenantAlreadyExists {
+                              Holder <TenantRollback> rollback) throws TenantException {
         MsoLogger.setLogContext (msoRequest);
         MsoLogger.setServiceName (CREATE_TENANT);
 
@@ -99,15 +100,16 @@ public class MsoTenantAdapterImpl implements MsoTenantAdapter {
         TenantRollback tenantRollback = new TenantRollback ();
         tenantRollback.setCloudId (cloudSiteId);
         tenantRollback.setMsoRequest (msoRequest);
-        
-        MsoTenantUtils tUtils = tFactory.getTenantUtils (cloudSiteId);
 
+        MsoTenantUtils tUtils;
         MsoTenant newTenant = null;
         String newTenantId;
         long queryTenantStartTime = System.currentTimeMillis ();
         try {
+            tUtils = tFactory.getTenantUtils (cloudSiteId);
             newTenant = tUtils.queryTenantByName (tenantName, cloudSiteId);
             logger.recordMetricEvent (queryTenantStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from Open Stack", OPENSTACK, QUERY_TENANT, null);
+
         } catch (MsoException me) {
             logger.recordMetricEvent (queryTenantStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with Open Stack", OPENSTACK, QUERY_TENANT, null);
             String error = "Create Tenant " + tenantName + ": " + me;
@@ -166,11 +168,11 @@ public class MsoTenantAdapterImpl implements MsoTenantAdapter {
         // Will capture execution time for metrics
         long startTime = System.currentTimeMillis ();
 
-        MsoTenantUtils tUtils = tFactory.getTenantUtils (cloudSiteId);
-        
+        MsoTenantUtils tUtils = null;
         MsoTenant qTenant = null;
         long subStartTime = System.currentTimeMillis ();
         try {
+            tUtils = tFactory.getTenantUtils (cloudSiteId);
             qTenant = tUtils.queryTenant (tenantNameOrId, cloudSiteId);
             logger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from Open Stack", OPENSTACK, QUERY_TENANT, null);
             if (qTenant == null) {
index abd8ce4..e851edf 100644 (file)
@@ -2,11 +2,11 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>adapters</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
-       <groupId>org.openecomp.so.adapters</groupId>
+       <groupId>org.onap.so.adapters</groupId>
        <artifactId>mso-vfc-adapter</artifactId>
        <packaging>war</packaging>
        <name>mso-vfc-adapter</name>
                        <version>2.0</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so.adapters</groupId>
+                       <groupId>org.onap.so.adapters</groupId>
                        <artifactId>mso-adapter-utils</artifactId>
                        <version>${project.version}</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so.adapters</groupId>
+                       <groupId>org.onap.so.adapters</groupId>
                        <artifactId>mso-adapters-rest-interface</artifactId>
                        <version>${project.version}</version>
                </dependency>
                        <scope>provided</scope>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>status-control</artifactId>
                        <version>${project.version}</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>mso-requests-db</artifactId>
                        <version>${project.version}</version>
                </dependency>
index 4a20257..e6217fc 100644 (file)
@@ -2,11 +2,11 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">\r
        <modelVersion>4.0.0</modelVersion>\r
        <parent>\r
-               <groupId>org.openecomp.so</groupId>\r
+               <groupId>org.onap.so</groupId>\r
                <artifactId>adapters</artifactId>\r
-               <version>1.2.0-SNAPSHOT</version>
+               <version>1.2.0-SNAPSHOT</version>\r
        </parent>\r
-       <groupId>org.openecomp.so.adapters</groupId>\r
+       <groupId>org.onap.so.adapters</groupId>\r
        <artifactId>mso-vnf-adapter-async-client</artifactId>\r
        <packaging>jar</packaging>\r
        <name>mso-vnf-adapter-async-client</name>\r
index 9116e57..9a290f4 100644 (file)
@@ -2,11 +2,11 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">\r
        <modelVersion>4.0.0</modelVersion>\r
        <parent>\r
-               <groupId>org.openecomp.so</groupId>\r
+               <groupId>org.onap.so</groupId>\r
                <artifactId>adapters</artifactId>\r
-               <version>1.2.0-SNAPSHOT</version>
+               <version>1.2.0-SNAPSHOT</version>\r
        </parent>\r
-       <groupId>org.openecomp.so.adapters</groupId>\r
+       <groupId>org.onap.so.adapters</groupId>\r
        <artifactId>mso-vnf-adapter</artifactId>\r
        <packaging>war</packaging>\r
        <name>mso-vnf-adapter</name>\r
@@ -56,7 +56,7 @@
                                </executions>\r
                                <dependencies>\r
                                        <dependency>\r
-                                               <groupId>org.openecomp.so.adapters</groupId>\r
+                                               <groupId>org.onap.so.adapters</groupId>\r
                                                <artifactId>mso-adapter-utils</artifactId>\r
                                                <version>${project.version}</version>\r
                                        </dependency>\r
        </build>\r
        <dependencies>\r
                <dependency>\r
-                       <groupId>org.openecomp.so.adapters</groupId>\r
+                       <groupId>org.onap.so.adapters</groupId>\r
                        <artifactId>mso-adapter-utils</artifactId>\r
                        <version>${project.version}</version>\r
                </dependency>\r
                <dependency>\r
-                       <groupId>org.openecomp.so.adapters</groupId>\r
+                       <groupId>org.onap.so.adapters</groupId>\r
                        <artifactId>mso-adapters-rest-interface</artifactId>\r
                        <version>${project.version}</version>\r
                </dependency>\r
                <dependency>\r
-                       <groupId>org.openecomp.so.adapters</groupId>\r
+                       <groupId>org.onap.so.adapters</groupId>\r
                        <artifactId>mso-vnf-adapter-async-client</artifactId>\r
                        <version>${project.version}</version>\r
                </dependency>\r
                        <scope>provided</scope>\r
                </dependency>\r
                <dependency>\r
-                       <groupId>org.openecomp.so</groupId>\r
+                       <groupId>org.onap.so</groupId>\r
                        <artifactId>status-control</artifactId>\r
                        <version>${project.version}</version>\r
                </dependency>\r
                        <scope>test</scope>\r
                </dependency>\r
                <!-- <dependency> -->\r
-               <!-- <groupId>org.openecomp.so</groupId> -->\r
+               <!-- <groupId>org.onap.so</groupId> -->\r
                <!-- <artifactId>mso-catalog-db</artifactId> -->\r
                <!-- <version>${project.version}</version> -->\r
                <!-- </dependency> -->\r
index fb86b8c..a292c76 100644 (file)
@@ -21,7 +21,7 @@
 
 package org.openecomp.mso.adapters.vnf;
 
-
+import java.util.Optional;
 import org.codehaus.jackson.JsonNode;
 import org.codehaus.jackson.JsonParseException;
 import org.codehaus.jackson.map.ObjectMapper;
@@ -953,15 +953,14 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
             }
             if (minVersionVnf != null && maxVersionVnf != null) {
                 MavenLikeVersioning aicV = new MavenLikeVersioning();
-                CloudSite cloudSite = null;
                 if (this.cloudConfig == null) {
                     this.cloudConfig = this.cloudConfigFactory.getCloudConfig();
                 }
                 // double check
                 if (this.cloudConfig != null) {
-                    cloudSite = this.cloudConfig.getCloudSite(cloudSiteId);
-                    if (cloudSite != null) {
-                        aicV.setVersion(cloudSite.getAic_version());
+                    Optional<CloudSite> cloudSiteOpt = this.cloudConfig.getCloudSite(cloudSiteId);
+                    if (cloudSiteOpt.isPresent()) {
+                        aicV.setVersion(cloudSiteOpt.get().getAic_version());
                         // Add code to handle unexpected values in here
                         boolean moreThanMin = true;
                         boolean equalToMin = true;
@@ -980,10 +979,10 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
                         if (!doNotTest) {
                             if ((moreThanMin || equalToMin) // aic >= min
                                     && (equalToMax || !(moreThanMax))) { //aic <= max
-                                LOGGER.debug("VNF Resource " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUuid() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version());
+                                LOGGER.debug("VNF Resource " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUuid() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version());
                             } else {
                                 // ERROR
-                                String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUuid() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version();
+                                String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUuid() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version();
                                 LOGGER.error(MessageEnum.RA_CONFIG_EXC, error, "OpenStack", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - setVersion");
                                 LOGGER.debug(error);
                                 throw new VnfException(error, MsoExceptionCategory.USERDATA);
@@ -1171,7 +1170,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
             }
 
             // Check that required parameters have been supplied
-            String missingParams = null;
+            StringBuilder missingParams = null;
             List <String> paramList = new ArrayList <> ();
 
             // New for 1510 - consult the PARAM_ALIAS field to see if we've been
@@ -1200,9 +1199,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
             if (heatEnvironmentString != null && heatEnvironmentString.contains ("parameters:")) {
                 //LOGGER.debug ("Have an Environment argument with a parameters: section - will bypass checking for valid params - but will still check for aliases");
                 LOGGER.debug("Enhanced environment checking enabled - 1604");
-                StringBuilder sb = new StringBuilder(heatEnvironmentString);
-                //LOGGER.debug("About to create MHEE with " + sb);
-                mhee = new MsoHeatEnvironmentEntry(sb);
+                mhee = MsoHeatEnvironmentEntry.create(heatEnvironmentString);
                 StringBuilder sb2 = new StringBuilder("\nHeat Template Parameters:\n");
                 for (HeatTemplateParam parm : heatTemplate.getParameters()) {
                     sb2.append("\t" + parm.getParamName() + ", required=" + parm.isRequired());
@@ -1211,7 +1208,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
                     sb2.append("Environment says it's not valid! " + mhee.getErrorString());
                 } else {
                     sb2.append("\nEnvironment:");
-                    sb2.append(mhee.toFullString());
+                    sb2.append(mhee);
                 }
                 LOGGER.debug(sb2.toString());
             } else {
@@ -1267,9 +1264,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
                     } else {
                         LOGGER.debug ("adding to missing parameters list: " + parm.getParamName ());
                         if (missingParams == null) {
-                            missingParams = parm.getParamName ();
+                            missingParams = new StringBuilder(parm.getParamName());
                         } else {
-                            missingParams += "," + parm.getParamName ();
+                            missingParams.append("," + parm.getParamName());
                         }
                     }
                 }
@@ -1279,7 +1276,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
                 if (checkRequiredParameters) {
                     // Problem - missing one or more required parameters
                     String error = "Create VFModule: Missing Required inputs: " + missingParams;
-                    LOGGER.error (MessageEnum.RA_MISSING_PARAM, missingParams, "OpenStack", "", MsoLogger.ErrorCode.DataError, "Create VFModule: Missing Required inputs");
+                    LOGGER.error (MessageEnum.RA_MISSING_PARAM, missingParams.toString(), "OpenStack", "", MsoLogger.ErrorCode.DataError, "Create VFModule: Missing Required inputs");
                     LOGGER.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.BadRequest, error);
                     throw new VnfException (error, MsoExceptionCategory.USERDATA);
                 } else {
@@ -1292,7 +1289,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
             // and it causes problems with json that has arrays
             String newEnvironmentString = null;
             if (mhee != null) {
-                newEnvironmentString = mhee.getRawEntry().toString();
+                newEnvironmentString = mhee.getRawEntry();
             }
 
             // "Fix" the template if it has CR/LF (getting this from Oracle)
@@ -1703,26 +1700,25 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
                 }
             if (minVersionVnf != null && maxVersionVnf != null) {
                 MavenLikeVersioning aicV = new MavenLikeVersioning();
-                CloudSite cloudSite = null;
                 //String aicVersion = "";
                 if (this.cloudConfig == null) {
                     this.cloudConfig = this.cloudConfigFactory.getCloudConfig();
             }
                 // double check
                 if (this.cloudConfig != null) {
-                    cloudSite = this.cloudConfig.getCloudSite(cloudSiteId);
-                    if (cloudSite != null) {
-                        aicV.setVersion(cloudSite.getAic_version());
+                    Optional<CloudSite> cloudSiteOpt = this.cloudConfig.getCloudSite(cloudSiteId);
+                    if (cloudSiteOpt.isPresent()) {
+                        aicV.setVersion(cloudSiteOpt.get().getAic_version());
                         if ((aicV.isMoreRecentThan(minVersionVnf) || aicV.isTheSameVersion(minVersionVnf)) // aic >= min
                                 && (aicV.isTheSameVersion(maxVersionVnf) || !(aicV.isMoreRecentThan(maxVersionVnf)))) { //aic <= max
-                            LOGGER.debug("VNF Resource " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version());
+                            LOGGER.debug("VNF Resource " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version());
                         } else {
                             // ERROR
-                            String error = "VNF Resource type: " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version();
+                            String error = "VNF Resource type: " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version();
                             LOGGER.error(MessageEnum.RA_CONFIG_EXC, error, "OpenStack", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - setVersion");
                             LOGGER.debug(error);
                             throw new VnfException(error, MsoExceptionCategory.USERDATA);
-                    }
+                        }
                     } // let this error out downstream to avoid introducing uncertainty at this stage
                 } else {
                     LOGGER.debug("cloudConfig is NULL - cannot check cloud site version");
@@ -1875,7 +1871,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
             }
 
             // Check that required parameters have been supplied
-            String missingParams = null;
+            StringBuilder missingParams = null;
             List <String> paramList = new ArrayList <> ();
 
             // New for 1510 - consult the PARAM_ALIAS field to see if we've been
@@ -1904,10 +1900,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
             MsoHeatEnvironmentEntry mhee = null;
             if (heatEnvironmentString != null && heatEnvironmentString.toLowerCase ().contains ("parameters:")) {
                 LOGGER.debug("Enhanced environment checking enabled - 1604");
-                haveEnvironmentParameters = true;
-                StringBuilder sb = new StringBuilder(heatEnvironmentString);
-                //LOGGER.debug("About to create MHEE with " + sb);
-                mhee = new MsoHeatEnvironmentEntry(sb);
+                mhee = MsoHeatEnvironmentEntry.create(heatEnvironmentString);
                 StringBuilder sb2 = new StringBuilder("\nHeat Template Parameters:\n");
                 for (HeatTemplateParam parm : heatTemplate.getParameters()) {
                     sb2.append("\t" + parm.getParamName() + ", required=" + parm.isRequired());
@@ -1916,7 +1909,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
                     sb2.append("Environment says it's not valid! " + mhee.getErrorString());
                 } else {
                     sb2.append("\nEnvironment:");
-                    sb2.append(mhee.toFullString());
+                    sb2.append(mhee);
                 }
                 LOGGER.debug(sb2.toString());
             } else {
@@ -2016,9 +2009,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
                     else {
                         LOGGER.debug ("adding to missing parameters list: " + parm.getParamName ());
                         if (missingParams == null) {
-                            missingParams = parm.getParamName ();
+                            missingParams = new StringBuilder(parm.getParamName());
                         } else {
-                            missingParams += "," + parm.getParamName ();
+                            missingParams.append("," + parm.getParamName());
                         }
                     }
                 }
@@ -2028,7 +2021,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
                 // Problem - missing one or more required parameters
                 if (checkRequiredParameters) {
                 String error = "Update VNF: Missing Required inputs: " + missingParams;
-                LOGGER.error (MessageEnum.RA_MISSING_PARAM, missingParams, "OpenStack", "", MsoLogger.ErrorCode.DataError, error);
+                LOGGER.error (MessageEnum.RA_MISSING_PARAM, missingParams.toString(), "OpenStack", "", MsoLogger.ErrorCode.DataError, error);
                     LOGGER.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.BadRequest, error);
                 throw new VnfException (error, MsoExceptionCategory.USERDATA);
                 } else {
@@ -2041,7 +2034,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
             // Just submit the envt entry as received from the database
             String newEnvironmentString = null;
             if (mhee != null) {
-                newEnvironmentString = mhee.getRawEntry().toString();
+                newEnvironmentString = mhee.getRawEntry();
             }
 
             // Remove any extraneous parameters (don't throw an error)
diff --git a/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/vdu/utils/VduBlueprint.java b/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/vdu/utils/VduBlueprint.java
new file mode 100755 (executable)
index 0000000..6e06eed
--- /dev/null
@@ -0,0 +1,90 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OPENECOMP - MSO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.mso.vdu.utils;
+
+import java.util.Map;
+
+/*
+ * This Java bean class describes the template model of a VDU as distributed
+ * by SDC to SO.  It is composed of one or more templates, one of which must be
+ * the main template, 
+ * 
+ * The structure of this class corresponds to the format in which the templates
+ * and associated artifacts are represented in the SO Catalog.
+ * 
+ * The map keys will be the "path" that is used to reference these artifacts within
+ * the other templates.  This may be relevant to how different VDU plugins package
+ * the files for delivery to the sub-orchestrator.
+ * 
+ * In the future, it is possible that pre-packaged blueprints (e.g. complete TOSCA CSARs)
+ * could be stored in the catalog (and added to this structure).
+ * 
+ * This bean is passed as an input to instantiateVdu and updateVdu.
+ */
+
+public class VduBlueprint {
+       String vduModelId;
+       String mainTemplateName;
+       Map<String,byte[]> templateFiles;
+       Map<String,byte[]> attachedFiles;
+
+       public String getVduModelId() {
+               return vduModelId;
+       }
+
+       public void setVduModelId(String vduModelId) {
+               this.vduModelId = vduModelId;
+       }
+
+       public String getMainTemplateName() {
+               return mainTemplateName;
+       }
+
+       public void setMainTemplateName(String mainTemplateName) {
+               this.mainTemplateName = mainTemplateName;
+       }
+
+       public Map<String, byte[]> getTemplateFiles() {
+               return templateFiles;
+       }
+
+       public void setTemplateFiles(Map<String, byte[]> templateFiles) {
+               this.templateFiles = templateFiles;
+       }
+
+       public Map<String, byte[]> getAttachedFiles() {
+               return attachedFiles;
+       }
+
+       public void setAttachedFiles(Map<String, byte[]> attachedFiles) {
+               this.attachedFiles = attachedFiles;
+       }
+
+       @Override
+    public String toString() {
+        return "VduInfo {" +
+                "id='" + vduModelId + '\'' +
+                "mainTemplateName='" + mainTemplateName + '\'' +
+                '}';
+    }
+
+}
+
diff --git a/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/vdu/utils/VduInfo.java b/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/vdu/utils/VduInfo.java
new file mode 100755 (executable)
index 0000000..53300c9
--- /dev/null
@@ -0,0 +1,130 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OPENECOMP - MSO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.mso.vdu.utils;
+
+import java.util.Map;
+import java.util.HashMap;
+
+/*
+ * This Java bean class relays VDU status information in a cloud-agnostic format.
+ * 
+ * This bean is returned by all implementors of the MsoVduUtils interface operations
+ * (instantiate, query, delete).
+ */
+
+public class VduInfo {
+       // Set defaults for everything
+       private String vduInstanceId = "";
+       private String vduInstanceName = "";
+       private VduStatus status = VduStatus.NOTFOUND;
+       private Map<String,Object> outputs = new HashMap<String,Object>();
+       private Map<String,Object> inputs = new HashMap<String,Object>();
+       private String lastAction;
+       private String actionStatus;
+       private String errorMessage;
+       
+       public VduInfo () {
+       }
+
+       // Add more constructors as appropriate
+       //
+       
+       public VduInfo (String id, Map<String,Object> outputs) {
+               this.vduInstanceId = id;
+               if (outputs != null)  this.outputs = outputs;
+       }
+       
+       public VduInfo (String id) {
+               this.vduInstanceId = id;
+       }
+       
+       public VduInfo (String id, VduStatus status) {
+               this.vduInstanceId = id;
+               this.status = status;
+       }
+       
+       public String getVnfInstanceId() {
+               return vduInstanceId;
+       }
+       
+       public void setVnfInstanceId (String id) {
+               this.vduInstanceId = id;
+       }
+       
+       public String getVnfInstanceName() {
+               return vduInstanceName;
+       }
+       
+       public void setVnfInstanceName (String name) {
+               this.vduInstanceName = name;
+       }
+       
+       public VduStatus getStatus() {
+               return status;
+       }
+       
+       public void setStatus (VduStatus status) {
+               this.status = status;
+       }
+       
+       public Map<String,Object> getOutputs () {
+               return outputs;
+       }
+       
+       public void setOutputs (Map<String,Object> outputs) {
+               this.outputs = outputs;
+       }
+       
+       public Map<String,Object> getInputs () {
+               return inputs;
+       }
+       
+       public void setInputs (Map<String,Object> inputs) {
+               this.inputs = inputs;
+       }
+
+       public String getLastAction() {
+               return lastAction;
+       }
+
+       public String getActionStatus() {
+               return actionStatus;
+       }
+
+       public String getErrorMessage() {
+               return errorMessage;
+       }
+
+       @Override
+    public String toString() {
+        return "VduInfo {" +
+                "id='" + vduInstanceId + '\'' +
+                "name='" + vduInstanceName + '\'' +
+                ", inputs='" + inputs + '\'' +
+                ", outputs='" + outputs + '\'' +
+                ", lastAction='" + lastAction + '\'' +
+                ", status='" + status + '\'' +
+                ", errorMessage='" + errorMessage + '\'' +
+                '}';
+    }
+
+}
+
diff --git a/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/vdu/utils/VduPlugin.java b/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/vdu/utils/VduPlugin.java
new file mode 100755 (executable)
index 0000000..3452a10
--- /dev/null
@@ -0,0 +1,248 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OPENECOMP - MSO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.mso.vdu.utils;
+
+/**
+ * This interface defines a common API for template-based cloud deployments.
+ * The methods here should be adaptable for Openstack (Heat), Cloudify (TOSCA),
+ * Aria (TOSCA), Multi-VIM (TBD), and others (e.g. Azure Resource Manager).
+ * 
+ * The deployed instances are referred to here as Virtual Deployment Units (VDUs).
+ * The package of templates that define a give VDU is referred to as its blueprint.
+ * 
+ * Template-based orchestrators all follow a similar template/blueprint model.
+ * - One main template that is the top level definition
+ * - Optional nested templates referenced/included by the main template
+ * - Optional files attached to the template package, typically containing
+ *   configuration files, install scripts, orchestration scripts, etc.
+ *   
+ * The main template also defines the required inputs for creating a new instance,
+ * and output values exposed by successfully deployed instances.  Inputs and outputs
+ * may include simple or complex (JSON) data types.
+ *   
+ * Each implementation of this interface is expected to understand the MSO CloudConfig
+ * to obtain the credentials for its sub-orchestrator and the targeted cloud.
+ * The sub-orchestrator may have different credentials from the cloud (e.g. an Aria 
+ * instance in front of an Openstack cloud) or they may be the same (e.g. Heat)
+ */
+import java.util.Map;
+
+import org.openecomp.mso.openstack.exceptions.MsoException;
+
+public interface VduPlugin {
+
+    /**
+     * The instantiateVdu interface deploys a new VDU instance from a blueprint package.
+     * The templates and files in the blueprint may be pre-installed where supported
+     * (e.g. in Cloudify or Aria), or may be passed in directly (e.g. for Heat).  These
+     * files are expressed as byte arrays, though only text files are expected from ASDC.
+     * 
+     * For some VIMs, this may be a single command (e.g. Heat -> create stack) or may
+     * require a series of API calls (e.g. Cloudify -> upload blueprint, create deployment,
+     * execute install workflow).  These details are hidden within the implementation.
+     * The instantiation should be fully completed before returning.  On failures, this
+     * method is expected to back out the attempt, leaving the cloud in its previous state.
+     * 
+     * It is expected that parameters have been validated and contain at minimum the
+     * required parameters for the given template with no extra parameters.
+     *
+     * The VDU name supplied by the caller will be globally unique, and identify the artifact
+     * in A&AI.  Inventory is managed by the higher levels invoking this function.
+     *
+     * @param cloudSiteId The target cloud for the VDU.  Maps to a CloudConfig entry.
+     * @param tenantId The cloud tenant in which to deploy the VDU.  The meaning may differ by
+     *                 cloud provider, but every cloud supports some sort of tenant partitioning.
+     * @param vduInstanceName A unique name for the VDU instance to create
+     * @param vduBlueprint Object containing the collection of templates and files that comprise
+     *                 the blueprint for this VDU.
+     * @param inputs A map of key/value inputs.  Values may be strings, numbers, or JSON objects.
+     * @param environmentFile A file containing default parameter name/value pairs.  This is
+     *                 primarily for Heat, though ASDC may create a similar file for other orchestrators.
+     * @param timeoutMinutes Timeout after which the instantiation attempt will be cancelled
+     * @param suppressBackout Flag to preserve the deployment on install Failure.  Should normally
+     *         be False except in troubleshooting/debug cases
+     * 
+     * @return A VduInfo object
+     * @throws MsoException Thrown if the sub-orchestrator API calls fail or if a timeout occurs.
+     * Various subclasses of MsoException may be thrown.
+     */
+    public VduInfo instantiateVdu (
+                               String cloudSiteId,
+                               String tenantId,
+                               String vduInstanceName,
+                               VduBlueprint vduBlueprint,
+                               Map <String, ? extends Object> inputs,
+                               String environmentFile,
+                               int timeoutMinutes,
+                               boolean suppressBackout)
+                       throws MsoException;
+
+    
+    /**
+     * Query a deployed VDU instance.  This call will return a VduInfo object, or null
+     * if the deployment does not exist.
+     * 
+     * Some VIM orchestrators identify deployment instances by string UUIDs, and others 
+     * by integers.  In the latter case, the ID will be passed in as a numeric string.
+     *
+     * The returned VduInfo object contains the input and output parameter maps,
+     * as well as other properties of the deployment (name, status, last action, etc.).
+     * 
+     * @param cloudSiteId The target cloud to query for the VDU.
+     * @param tenantId The cloud tenant in which to query
+     * @param vduInstanceId The ID of the deployment to query
+     * 
+     * @return A VduInfo object
+     * @throws MsoException Thrown if the VIM/sub-orchestrator API calls fail.
+     * Various subclasses of MsoException may be thrown.
+     */
+    public VduInfo queryVdu (
+                               String cloudSiteId,
+                               String tenantId,
+                               String vduInstanceId)
+                       throws MsoException;
+
+    
+    /**
+     * Delete a VDU instance by ID.  If the VIM sub-orchestrator supports pre-installation
+     * of blueprints, the blueprint itself may remain installed.  This is recommended, since
+     * other VDU instances may be using it.
+     * 
+     * Some VIM orchestrators identify deployment instances by string UUIDs, and others 
+     * by integers.  In the latter case, the ID will be passed in as a numeric string.
+     * 
+     * For some VIMs, deletion may be a single command (e.g. Heat -> delete stack) or a
+     * series of API calls (e.g. Cloudify -> execute uninstall workflow, delete deployment).
+     * These details are hidden within the implementation.  The deletion should be fully
+     * completed before returning.    
+     *  
+     * The successful return is a VduInfo object which contains the state of the object just prior
+     * to deletion, with a status of DELETED.  If the deployment was not found, the VduInfo object
+     * should be empty (with a status of NOTFOUND).  There is no rollback from a successful deletion.
+     * 
+     * A deletion failure will result in an undefined deployment state - the components may
+     * or may not have been all or partially uninstalled, so the resulting deployment must
+     * be considered invalid.
+     *
+     * @param cloudSiteId The target cloud from which to delete the VDU.
+     * @param tenantId The cloud tenant in which to delete the VDU.
+     * @param vduInstanceId The unique id of the deployment to delete.
+     * @param timeoutMinutes Timeout after which the delete action will be cancelled
+     * @param deleteBlueprint Flag to also delete the blueprint
+     * 
+     * @return A VduInfo object, representing the state of the instance just prior to deletion.
+     * 
+     * @throws MsoException Thrown if the API calls fail or if a timeout occurs.
+     * Various subclasses of MsoException may be thrown.
+     */
+    public VduInfo deleteVdu (
+                               String cloudSiteId,
+                               String tenantId,
+                               String vduInstanceId,
+                               int timeoutMinutes,
+                               boolean keepBlueprintLoaded)
+                       throws MsoException;
+
+    
+    /**
+     * The updateVdu interface attempts to update a VDU in-place, using either new inputs or
+     * a new model definition (i.e. updated templates/blueprints).  This depends on the
+     * capabilities of the targeted sub-orchestrator, as not all implementations are expected
+     * to support this ability.  It is primary included initially only for Heat.
+        *
+     * It is expected that parameters have been validated and contain at minimum the required
+     * parameters for the given template with no extra parameters.  The VDU instance name cannot
+     * be updated. 
+     * 
+        * The update should be fully completed before returning. The successful return is a
+        * VduInfo object containing the updated VDU state.
+     * 
+     * An update failure will result in an undefined deployment state - the components may
+     * or may not have been all or partially modified, deleted, recreated, etc.  So the resulting
+     * VDU must be considered invalid.
+     * 
+     * @param cloudSiteId The target cloud for the VDU.  Maps to a CloudConfig entry.
+     * @param tenantId The cloud tenant in which to deploy the VDU.  The meaning may differ by
+     *                 cloud provider, but every cloud supports some sort of tenant partitioning.
+     * @param vduInstanceId The unique ID for the VDU instance to update.
+     * @param vduBlueprint Object containing the collection of templates and files that comprise
+     *                 the blueprint for this VDU.
+     * @param inputs A map of key/value inputs.  Values may be strings, numbers, or JSON objects.
+     * @param environmentFile A file containing default parameter name/value pairs.  This is
+     *                 primarily for Heat, though ASDC may create a similar file for other orchestrators.
+     * @param timeoutMinutes Timeout after which the instantiation attempt will be cancelled
+     * 
+     * @return A VduInfo object
+     * @throws MsoException Thrown if the sub-orchestrator API calls fail or if a timeout occurs.
+     * Various subclasses of MsoException may be thrown.
+     */
+    public VduInfo updateVdu (
+                               String cloudSiteId,
+                               String tenantId,
+                               String vduInstanceId,
+                               VduBlueprint vduBlueprint,
+                               Map <String, ? extends Object> inputs,
+                               String environmentFile,
+                               int timeoutMinutes)
+                       throws MsoException;
+
+    
+    /**
+     * Check if a blueprint package has been installed in the sub-orchestrator and available
+     * for use at a targeted cloud site.  If the specific sub-orchestrator does not support
+     * pre-installation, then those implementations should always return False.
+     * 
+     * @param cloudSiteId The cloud site where the blueprint is needed
+     * @param vduModelId Unique ID of the VDU model to query
+     * 
+     * @throws MsoException Thrown if the API call fails.
+     */
+    public boolean isBlueprintLoaded (String cloudSiteId, String vduModelId)
+                       throws MsoException;
+
+    
+    /**
+     * Install a blueprint package to the target sub-orchestrator for a cloud site.
+     * The blueprints currently must be structured as a single directory with all of the
+     * required files.  One of those files is designated the "main file" for the blueprint.
+     * Files are provided as byte arrays, though expect only text files will be distributed
+     * from ASDC and stored by MSO.
+     * 
+     * @param cloudSiteId The cloud site where the blueprint is needed
+     * @param vduBlueprint Object containing the collection of templates and files that comprise
+     *                 the blueprint for this VDU.
+     * @param failIfExists Flag to return an error if blueprint already exists
+     * 
+     * @throws MsoException Thrown if the API call fails.
+     */
+    public void uploadBlueprint (String cloudSiteId,
+                                                       VduBlueprint vduBlueprint,
+                                                       boolean failIfExists)
+       throws MsoException;
+
+    /**
+     * Indicator that this VIM sub-orchestrator implementation supports independent upload
+     * of blueprint packages.  Each implementation should return a constant value.
+     * 
+     * @returns True if the sub-orchestrator supports blueprint pre-installation (upload).
+     */
+    public boolean blueprintUploadSupported ();
+
+}
diff --git a/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/vdu/utils/VduStatus.java b/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/vdu/utils/VduStatus.java
new file mode 100755 (executable)
index 0000000..0f4611a
--- /dev/null
@@ -0,0 +1,37 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OPENECOMP - MSO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.mso.vdu.utils;
+
+
+/*
+ * Enum status values to capture the state of a generic (cloud-agnostic) VDU.
+ */
+public enum VduStatus {
+       NOTFOUND,
+       INSTANTIATING,
+       INSTANTIATED,
+       DELETING,
+       DELETED,                // Note - only returned in success response to deleteVdu call.
+       UPDATING,
+       FAILED,
+       UNKNOWN
+}
+
index b680170..a045b00 100644 (file)
@@ -22,18 +22,10 @@ package org.openecomp.mso.adapters.vnf.test;
 \r
 import java.util.HashMap;\r
 import java.util.Map;\r
-\r
 import org.junit.Test;\r
 import org.openecomp.mso.adapters.vnf.MsoVnfAdapterAsyncImpl;\r
 import org.openecomp.mso.entity.MsoRequest;\r
-import org.openecomp.mso.openstack.beans.HeatStatus;\r
-import org.openecomp.mso.openstack.beans.StackInfo;\r
 import org.openecomp.mso.openstack.beans.VnfRollback;\r
-import org.openecomp.mso.openstack.exceptions.MsoException;\r
-import org.openecomp.mso.openstack.utils.MsoHeatUtils;\r
-\r
-import mockit.Mock;\r
-import mockit.MockUp;\r
 \r
 public class MsoVnfAdapterAsyncImplTest {\r
 \r
@@ -45,15 +37,6 @@ public class MsoVnfAdapterAsyncImplTest {
 \r
        @Test\r
        public void createVNFTest() {\r
-               new MockUp<MsoHeatUtils>() {\r
-                       @Mock\r
-                       public StackInfo queryStack(String cloudSiteId, String tenantId, String stackName) throws MsoException {\r
-                               StackInfo info = new StackInfo();\r
-                               info.setStatus(HeatStatus.CREATED);\r
-                               return info;\r
-                       }\r
-               };\r
-\r
                MsoVnfAdapterAsyncImpl instance = new MsoVnfAdapterAsyncImpl();\r
                MsoRequest msoRequest = new MsoRequest();\r
                msoRequest.setRequestId("12345");\r
index 7787908..6f01954 100644 (file)
@@ -22,24 +22,11 @@ package org.openecomp.mso.adapters.vnf.test;
 \r
 import java.util.HashMap;\r
 import java.util.Map;\r
-\r
 import javax.xml.ws.Holder;\r
-\r
 import org.junit.Test;\r
 import org.openecomp.mso.adapters.vnf.MsoVnfAdapterImpl;\r
-import org.openecomp.mso.db.catalog.CatalogDatabase;\r
-import org.openecomp.mso.db.catalog.beans.VfModule;\r
-import org.openecomp.mso.db.catalog.beans.VfModuleCustomization;\r
-import org.openecomp.mso.db.catalog.beans.VnfResource;\r
 import org.openecomp.mso.entity.MsoRequest;\r
-import org.openecomp.mso.openstack.beans.HeatStatus;\r
-import org.openecomp.mso.openstack.beans.StackInfo;\r
 import org.openecomp.mso.openstack.beans.VnfRollback;\r
-import org.openecomp.mso.openstack.exceptions.MsoException;\r
-import org.openecomp.mso.openstack.utils.MsoHeatUtils;\r
-\r
-import mockit.Mock;\r
-import mockit.MockUp;\r
 \r
 public class MsoVnfAdapterImplTest {\r
 \r
@@ -51,16 +38,6 @@ public class MsoVnfAdapterImplTest {
 \r
        @Test\r
        public void createVnfTest() {\r
-\r
-               new MockUp<MsoHeatUtils>() {\r
-                       @Mock\r
-                       public StackInfo queryStack(String cloudSiteId, String tenantId, String stackName) throws MsoException {\r
-                               StackInfo info = new StackInfo();\r
-                               info.setStatus(HeatStatus.CREATED);\r
-                               return info;\r
-                       }\r
-               };\r
-\r
                MsoVnfAdapterImpl instance = new MsoVnfAdapterImpl();\r
                MsoRequest msoRequest = new MsoRequest();\r
                msoRequest.setRequestId("12345");\r
@@ -80,37 +57,6 @@ public class MsoVnfAdapterImplTest {
 \r
        @Test\r
        public void updateVnfTest() {\r
-\r
-               new MockUp<MsoHeatUtils>() {\r
-                       @Mock\r
-                       public StackInfo queryStack(String cloudSiteId, String tenantId, String stackName) throws MsoException {\r
-                               StackInfo info = new StackInfo();\r
-                               info.setStatus(HeatStatus.CREATED);\r
-                               return info;\r
-                       }\r
-               };\r
-\r
-               new MockUp<CatalogDatabase>() {\r
-                       @Mock\r
-                       public VfModuleCustomization getVfModuleCustomizationByModelCustomizationId(String modelCustomizationUuid) {\r
-                               VfModuleCustomization vfcModule = new VfModuleCustomization();\r
-                               VfModule vfm = new VfModule();\r
-                               vfm.setVnfResourceModelUUId("88a6ca3ee0394ade9403f075db23167e");\r
-                               vfcModule.setVfModule(vfm);\r
-                               return vfcModule;\r
-                       }\r
-               };\r
-\r
-               new MockUp<CatalogDatabase>() {\r
-                       @Mock\r
-                       public VnfResource getVnfResourceByModelUuid(String modelUuid) {\r
-                               VnfResource vnfResource = new VnfResource();\r
-                               vnfResource.setAicVersionMin("1");\r
-                               vnfResource.setAicVersionMax("2");\r
-                               return vnfResource;\r
-                       }\r
-               };\r
-\r
                MsoVnfAdapterImpl instance = new MsoVnfAdapterImpl();\r
                MsoRequest msoRequest = new MsoRequest();\r
                msoRequest.setRequestId("12345");\r
@@ -130,17 +76,6 @@ public class MsoVnfAdapterImplTest {
 \r
        @Test\r
        public void deleteVnfTest() {\r
-               new MockUp<MsoHeatUtils>() {\r
-                       @Mock\r
-                       public Map<String, Object> queryStackForOutputs(String cloudSiteId, String tenantId, String stackName)\r
-                                       throws MsoException {\r
-                               \r
-                               Map<String, Object> outputs = new HashMap<>();\r
-                               outputs.put("Key1", "value1");\r
-                               return outputs;\r
-                       }\r
-               };\r
-\r
                MsoVnfAdapterImpl instance = new MsoVnfAdapterImpl();\r
                MsoRequest msoRequest = new MsoRequest();\r
                msoRequest.setRequestId("12345");\r
index 315db2e..f6e79e1 100644 (file)
 package org.openecomp.mso.adapters.vnf.test;
 
 
-import java.util.Map;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
 
+import java.util.Map;
 import javax.xml.ws.Holder;
-
 import mockit.Mock;
 import mockit.MockUp;
 import org.junit.Test;
 import org.openecomp.mso.adapters.vnf.MsoVnfAdapter;
 import org.openecomp.mso.adapters.vnf.MsoVnfAdapterImpl;
+import org.openecomp.mso.adapters.vnf.exceptions.VnfException;
 import org.openecomp.mso.openstack.beans.HeatStatus;
 import org.openecomp.mso.openstack.beans.StackInfo;
 import org.openecomp.mso.openstack.beans.VnfStatus;
-import org.openecomp.mso.adapters.vnf.exceptions.VnfException;
-import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound;
 import org.openecomp.mso.openstack.exceptions.MsoException;
 import org.openecomp.mso.openstack.utils.MsoHeatUtils;
 
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
 public class QueryTest {
 
     @Test
@@ -49,8 +46,7 @@ public class QueryTest {
             new MockUp<MsoHeatUtils>() {
                 @Mock
                 public StackInfo queryStack(String cloudSiteId, String tenantId, String stackName) throws MsoException {
-                    StackInfo info = new StackInfo();
-                    info.setStatus(HeatStatus.CREATED);
+                    StackInfo info = new StackInfo("stackName", HeatStatus.CREATED);
                     return info;
                 }
             };
@@ -77,8 +73,7 @@ public class QueryTest {
             new MockUp<MsoHeatUtils>() {
                 @Mock
                 public StackInfo queryStack(String cloudSiteId, String tenantId, String stackName) throws MsoException {
-                    StackInfo info = new StackInfo();
-                    info.setStatus(HeatStatus.NOTFOUND);
+                    StackInfo info = new StackInfo("stackName", HeatStatus.NOTFOUND);
                     return info;
                 }
             };
@@ -102,13 +97,6 @@ public class QueryTest {
     @Test(expected = VnfException.class)
     public void testQueryVnfWithException() throws VnfException {
         {
-            new MockUp<MsoHeatUtils>() {
-                @Mock
-                public StackInfo queryStack(String cloudSiteId, String tenantId, String stackName) throws MsoException {
-                    throw new MsoCloudSiteNotFound(cloudSiteId);
-                }
-            };
-
             MsoVnfAdapter vnfAdapter = new MsoVnfAdapterImpl();
             String cloudId = "MT";
             String tenantId = "MSO_Test";
index 3501dd5..46e4a2b 100644 (file)
@@ -2,11 +2,11 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>adapters</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
-       <groupId>org.openecomp.so.adapters</groupId>
+       <groupId>org.onap.so.adapters</groupId>
        <artifactId>mso-workflow-message-adapter</artifactId>
        <packaging>war</packaging>
        <name>mso-workflow-message-adapter</name>
@@ -30,7 +30,7 @@
 
        <dependencies>
                <dependency>
-                       <groupId>org.openecomp.so.adapters</groupId>
+                       <groupId>org.onap.so.adapters</groupId>
                        <artifactId>mso-adapters-rest-interface</artifactId>
                        <version>${project.version}</version>
                </dependency>
@@ -58,7 +58,7 @@
                        <version>4.5.2</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>status-control</artifactId>
                        <version>${project.version}</version>
                </dependency>
index 97c2506..6877d76 100644 (file)
@@ -2,12 +2,12 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>so</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
 
-       <groupId>org.openecomp.so</groupId>
+       <groupId>org.onap.so</groupId>
        <artifactId>adapters</artifactId>
        <name>MSO Adapters</name>
        <description>Adapters for MSO</description>
index 402d3c1..f35403c 100755 (executable)
@@ -1,3 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
 <!--
 /*
  * ============LICENSE_START===================================================
@@ -17,7 +18,6 @@
  * ============LICENSE_END====================================================
 */
 -->
-<?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
old mode 100755 (executable)
new mode 100644 (file)
index a4e4533..5de2203
-/*\r
- * ============LICENSE_START===================================================\r
- * Copyright (c) 2017 Cloudify.co.  All rights reserved.\r
- * ===================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
- * use this file except in compliance with the License. You may obtain a copy\r
- * of the License at\r
- *\r
- *       http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
- * License for the specific language governing permissions and limitations under\r
- * the License.\r
- * ============LICENSE_END====================================================\r
-*/\r
-package com.gigaspaces.aria.rest.client;\r
-\r
-import com.gigaspaces.aria.rest.client.exceptions.StorageException;\r
-import com.gigaspaces.aria.rest.client.exceptions.ValidationException;\r
-import org.codehaus.jackson.JsonFactory;\r
-import org.codehaus.jackson.JsonNode;\r
-import org.codehaus.jackson.jaxrs.JacksonJsonProvider;\r
-import org.codehaus.jackson.map.ObjectMapper;\r
-import sun.reflect.generics.reflectiveObjects.NotImplementedException;\r
-\r
-import javax.ws.rs.client.Client;\r
-import javax.ws.rs.client.ClientBuilder;\r
-import javax.ws.rs.client.Entity;\r
-import javax.ws.rs.client.WebTarget;\r
-import javax.ws.rs.core.GenericType;\r
-import javax.ws.rs.core.MediaType;\r
-import javax.ws.rs.core.Response;\r
-import java.net.URI;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-\r
-import static javax.ws.rs.client.Entity.entity;\r
-\r
-/**\r
- * Created by DeWayne on 7/12/2017.\r
- */\r
-public class AriaRestClient implements AriaClient {\r
-    private Client client=null;\r
-    private WebTarget base_target=null;\r
-\r
-    /**\r
-     * Construct an Aria REST client\r
-     *\r
-     * @param protocol either http or https\r
-     * @param address the IP address or host name\r
-     * @param port the port of the service\r
-     * @param version the api version\r
-     */\r
-    public AriaRestClient(String protocol, String address, int port, String version){\r
-        this.client = ClientBuilder.newBuilder().register(JacksonJsonProvider.class).build();\r
-        base_target = client.target(protocol+"://"+address+":"+port+"/api/"+version);\r
-    }\r
-\r
-    /**\r
-     * Installs a service template\r
-     *\r
-     * @param template the template object\r
-     * @throws ValidationException\r
-     * @throws StorageException\r
-     */\r
-    public void install_service_template(ServiceTemplate template) throws ValidationException, StorageException, Exception {\r
-\r
-        Response response = base_target.path("templates/"+template.getName()).request(MediaType.APPLICATION_JSON).put(Entity.entity(\r
-                "{\"service-template-path\":\""+template.getURI().toString()+"\""+\r
-                        ",\"service-template-filename\":\""+template.getFilename()+"\"", MediaType.APPLICATION_JSON));\r
-\r
-        if(response.getStatus() == 500){\r
-            throw new StorageException(response.readEntity(String.class));\r
-        }\r
-        else if(response.getStatus() == 400){\r
-            throw new ValidationException(response.readEntity(String.class));\r
-        }\r
-        else if(response.getStatus()>199 && response.getStatus() <300){\r
-            return;\r
-        }\r
-        else{\r
-            throw new Exception("Error installing template: "+response.getStatus()+" "+ response.readEntity(String.class));\r
-        }\r
-    }\r
-\r
-    public ValidationResult validate_service_template(ServiceTemplate template)throws Exception{\r
-        Response response = base_target.path("templates").request(MediaType.APPLICATION_JSON).post(Entity.entity(\r
-                "{\"service-template-path\":\""+template.getURI().toString()+"\""+\r
-                ",\"service-template-filename\":\""+template.getFilename()+"\"}", MediaType.APPLICATION_JSON));\r
-\r
-        ValidationResultImpl result = new ValidationResultImpl();\r
-        if(response.getStatus() >= 200 && response.getStatus() < 300){\r
-            result.setFailed(false);\r
-        }\r
-        else if(response.getStatus()==400){\r
-            result.setFailed(true);\r
-        }\r
-        else{\r
-            throw new Exception("received error response '"+ response.getStatus()+"':"+response.readEntity(String.class));\r
-        }\r
-        return result;\r
-\r
-    }\r
-\r
-    /**\r
-     *\r
-     * @return a list of service templates\r
-     */\r
-    public List<? extends ServiceTemplate> list_service_templates(){\r
-        List<? extends ServiceTemplate> templates = base_target.path("templates").request(MediaType.APPLICATION_JSON).get(new GenericType<List<ServiceTemplateImpl>>(){});\r
-\r
-        return templates;\r
-    }\r
-\r
-\r
-    /**\r
-     * Deletes the specified template.\r
-     *\r
-     * TODO: Error handling is a little blunt. Need to describe failures better\r
-     *\r
-     * @param template_id the template id to delete\r
-     * @throws IllegalArgumentException thrown when the template can't be deleted\r
-     * @throws Exception other server side errors\r
-     */\r
-    public void delete_service_template(int template_id) throws IllegalArgumentException, Exception{\r
-        Response response = base_target.path("templates/"+template_id).request(MediaType.APPLICATION_JSON).delete();\r
-\r
-        if(response.getStatus()>=200 && response.getStatus()<300){\r
-            return;\r
-        }\r
-        else if(response.getStatus()==400){\r
-            throw new IllegalArgumentException("Error deleting template '"+template_id+"'");\r
-        }\r
-        else{\r
-            throw new Exception("Error processing request. Return code = "+response.getStatus());\r
-        }\r
-    }\r
-\r
-    /**\r
-     * List the node templates for a given template id\r
-     *\r
-     * @param template_id\r
-     * @return\r
-     */\r
-    public List<? extends NodeTemplate> list_nodes(int template_id) {\r
-        List<? extends NodeTemplate> nodes = base_target.path("templates/"+template_id+"/nodes").request(MediaType.APPLICATION_JSON).get(new GenericType<List<NodeTemplateImpl>>(){});\r
-        return nodes;\r
-    }\r
-\r
-    /**\r
-     * Get a specific node by id\r
-     *\r
-     * @param node_id the node id\r
-     * @return\r
-     * @throws IllegalArgumentException\r
-     */\r
-    public NodeTemplate get_node(int node_id) throws IllegalArgumentException {\r
-        NodeTemplate node = base_target.path("nodes/"+node_id).request(MediaType.APPLICATION_JSON).get(NodeTemplateImpl.class);\r
-        return node;\r
-    }\r
-\r
-    public List<? extends Service> list_services() {\r
-        List<? extends Service> services = base_target.path("services").request(MediaType.APPLICATION_JSON).get(new GenericType<List<ServiceImpl>>(){});\r
-        return services;\r
-    }\r
-\r
-    public Service get_service(int service_id) throws IllegalArgumentException {\r
-        throw new NotImplementedException();\r
-    }\r
-\r
-    public List<? extends Output> list_service_outputs(int service_id) throws IllegalArgumentException {\r
-        List<? extends Output> outputs = base_target.path("services").request(MediaType.APPLICATION_JSON).get(new GenericType<List<OutputImpl>>(){});\r
-        return outputs;\r
-    }\r
-\r
-    public List<? extends Input> list_service_inputs(int service_id) throws IllegalArgumentException {\r
-        List<? extends Input> inputs = base_target.path("services").request(MediaType.APPLICATION_JSON).get(new GenericType<List<InputImpl>>(){});\r
-        return inputs;\r
-    }\r
-\r
-    /**\r
-     * Create a service based on the supplied template\r
-     *\r
-     * @param template_id the template to create the service for\r
-     * @param service_name a name for the service\r
-     * @param inputs an optional list of inputs for the service (can be null)\r
-     * @throws Exception\r
-     */\r
-    public void create_service(int template_id, String service_name, List<Input> inputs) throws Exception {\r
-\r
-        String json="{"+inputsToJson(inputs)+"}";\r
-\r
-        Response response = base_target.path("templates/"+template_id+"/services/"+service_name).\r
-                request(MediaType.APPLICATION_JSON).post(\r
-                Entity.entity(json, MediaType.APPLICATION_JSON)\r
-        );\r
-\r
-        if( response.getStatus()< 200 || response.getStatus()>299){\r
-            throw new Exception("create service failed:"+response.getStatus()+" "+ response.readEntity(String.class));\r
-        }\r
-    }\r
-\r
-    public void delete_service(int service_id) throws Exception {\r
-        Response response = base_target.path("services/"+service_id).request(MediaType.APPLICATION_JSON).delete();\r
-        if(!responseOK(response)){\r
-            throw new Exception("delete service failed: "+response.getStatus()+" "+ response.readEntity(String.class));\r
-        }\r
-    }\r
-\r
-    /**\r
-     * List user workflows for supplied service\r
-     *\r
-     * @param service_id\r
-     * @return\r
-     * @throws IllegalArgumentException\r
-     */\r
-    public List<? extends Workflow> list_workflows(int service_id) throws IllegalArgumentException {\r
-        List<? extends Workflow> workflows = base_target.path("services/"+service_id+"/workflows").request(MediaType.APPLICATION_JSON).get(new GenericType<List<WorkflowImpl>>(){});\r
-        return workflows;\r
-    }\r
-\r
-    public Workflow get_workflow(int workflow_id) throws IllegalArgumentException {\r
-        throw new NotImplementedException();\r
-    }\r
-\r
-    /**\r
-     * List all executions\r
-     *\r
-     * @return\r
-     * @throws Exception\r
-     */\r
-    public List<? extends Execution> list_executions() throws Exception {\r
-        List<? extends Execution> executions = base_target.path("executions").request(MediaType.APPLICATION_JSON).get(new GenericType<List<ExecutionImpl>>(){});\r
-        return executions;\r
-    }\r
-\r
-    /**\r
-     * List executions for specified service\r
-     *\r
-     * @param service_id\r
-     * @return\r
-     * @throws Exception\r
-     */\r
-    public List<? extends Execution> list_executions(int service_id) throws Exception {\r
-        List<? extends Execution> executions = base_target.path("services/"+service_id+"/executions").request(MediaType.APPLICATION_JSON).get(new GenericType<List<ExecutionImpl>>(){});\r
-        return executions;\r
-    }\r
-\r
-    /**\r
-     * Get details about a specified execution\r
-     *\r
-     * @param execution_id\r
-     * @return\r
-     * @throws IllegalArgumentException\r
-     */\r
-    public Execution get_execution(int execution_id) throws IllegalArgumentException {\r
-        Execution execution = base_target.path("executions/"+execution_id).request(MediaType.APPLICATION_JSON).get(ExecutionImpl.class);\r
-        return execution;\r
-    }\r
-\r
-    /**\r
-     * Start an execution for the specified service\r
-     *\r
-     * @param service_id the service to run the execution for\r
-     * @param workflow_name the name of the workflow to execute\r
-     * @param details details controlling execution operation\r
-     * @return the execution id\r
-     * @throws Exception\r
-     */\r
-    public int start_execution(int service_id, String workflow_name, ExecutionDetails details) throws Exception {\r
-        StringBuilder json=new StringBuilder("{");\r
-        if(details.getExecutor().length()>0){\r
-            json.append("\"executor\":\"").append(details.getExecutor()).append("\",");\r
-        }\r
-        if(details.getInputs()!=null){\r
-            json.append(inputsToJson(details.getInputs()));\r
-        }\r
-        json.append("\"task_max_attempts\":").append(details.getTaskMaxAttempts()).append(",");\r
-        json.append("\"task_retry_interval\":").append(details.getTaskRetryInterval()).append("}");\r
-\r
-        System.out.println("JSON="+json.toString());\r
-\r
-        Response response = base_target.path("services/"+service_id+"/executions/"+workflow_name).request(MediaType.APPLICATION_JSON).\r
-                post(Entity.entity(json.toString(), MediaType.APPLICATION_JSON));\r
-\r
-        if(!responseOK(response)){\r
-            throw new Exception("start execution failed: "+response.getStatus()+" "+response.readEntity(String.class));\r
-        }\r
-\r
-        ObjectMapper mapper = new ObjectMapper(new JsonFactory());\r
-        JsonNode rootNode = mapper.readTree(response.readEntity(String.class));\r
-        int id=rootNode.get("id").asInt(-1);\r
-        return id;\r
-    }\r
-\r
-    public void resume_execution(int execution_id, ExecutionDetails details) throws IllegalArgumentException {\r
-        StringBuilder json=new StringBuilder("{");\r
-        if(details.getExecutor().length()>0){\r
-            json.append("\"executor\":\"").append(details.getExecutor()).append("\",");\r
-        }\r
-        json.append("\"retry_failed_tasks\":").append(details.isRetry_failed_tasks()).append("}");\r
-        Response response = base_target.path("executions/"+execution_id).request(MediaType.APPLICATION_JSON).\r
-                post(Entity.entity(json.toString(), MediaType.APPLICATION_JSON));\r
-    }\r
-\r
-    public void cancel_execution(int execution_id) throws Exception {\r
-        Response response = base_target.path("executions/"+execution_id).request(MediaType.APPLICATION_JSON).delete();\r
-        if(!responseOK(response)){\r
-            throw new Exception("delete service failed: "+response.getStatus()+" "+ response.readEntity(String.class));\r
-        }\r
-    }\r
-\r
-    /**\r
-     * -----\r
-     * ----- PRIVATE METHODS\r
-     * -----\r
-     */\r
-\r
-    private boolean responseOK(Response response){\r
-        return response.getStatus()>199 && response.getStatus()<300;\r
-    }\r
-\r
-    private String inputsToJson(List<Input> inputs){\r
-        if(inputs==null)return null;\r
-\r
-        StringBuilder sb=new StringBuilder("\"inputs\":{");\r
-        for(Input input:inputs){\r
-            sb.append("\"").append(input.getName()).append("\":\"").append(input.getValue()).append("\",");\r
-        }\r
-        if(inputs.size()>0)sb.deleteCharAt(sb.length()-1); //trim comma\r
-\r
-        return sb.toString();\r
-    }\r
-}\r
+/*
+ * ============LICENSE_START===================================================
+ * Copyright (c) 2017 Cloudify.co.  All rights reserved.
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ * ============LICENSE_END====================================================
+*/
+package com.gigaspaces.aria.rest.client;
+
+import java.util.List;
+
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.core.GenericType;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.codehaus.jackson.JsonFactory;
+import org.codehaus.jackson.JsonNode;
+import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
+import org.codehaus.jackson.map.ObjectMapper;
+import com.gigaspaces.aria.rest.client.exceptions.StorageException;
+import com.gigaspaces.aria.rest.client.exceptions.ValidationException;
+
+import sun.reflect.generics.reflectiveObjects.NotImplementedException;
+
+/**
+ * Created by DeWayne on 7/12/2017.
+ */
+public class AriaRestClient implements AriaClient {
+       private Client client = null;
+       private WebTarget base_target = null;
+
+       /**
+        * Construct an Aria REST client
+        *
+        * @param protocol
+        *            either http or https
+        * @param address
+        *            the IP address or host name
+        * @param port
+        *            the port of the service
+        * @param version
+        *            the api version
+        */
+       public AriaRestClient(String protocol, String address, int port, String version) {
+               this.client = ClientBuilder.newBuilder().register(JacksonJsonProvider.class).build();
+               base_target = client.target(protocol + "://" + address + ":" + port + "/api/" + version);
+       }
+
+       /**
+        * Installs a service template
+        *
+        * @param template
+        *            the template object
+        * @throws ValidationException
+        * @throws StorageException
+        */
+       public void install_service_template(ServiceTemplate template)
+                       throws ValidationException, StorageException, Exception {
+
+               byte[] csarBytes = template.getCSARBytes();
+               Response response = null;
+               if (csarBytes == null) {
+                       response = base_target.path("templates/" + template.getName()).request(MediaType.APPLICATION_JSON)
+                                       .put(Entity.entity(
+                                                       "{\"service-template-path\":\"" + template.getURI().toString() + "\""
+                                                                       + ",\"service-template-filename\":\"" + template.getFilename() + "\"",
+                                                       MediaType.APPLICATION_JSON));
+               }
+               else {
+                       
+                       response = base_target.path("templates/" + template.getName()).request("application/zip")
+                                       .put(Entity.entity(csarBytes, "application/zip"));
+               }
+
+               if (response.getStatus() == 500) {
+                       throw new StorageException(response.readEntity(String.class));
+               } else if (response.getStatus() == 400) {
+                       throw new ValidationException(response.readEntity(String.class));
+               } else if (response.getStatus() > 199 && response.getStatus() < 300) {
+                       return;
+               } else {
+                       throw new Exception(
+                                       "Error installing template: " + response.getStatus() + " " + response.readEntity(String.class));
+               }
+       }
+
+       public ValidationResult validate_service_template(ServiceTemplate template) throws Exception {
+               Response response = base_target.path("templates").request(MediaType.APPLICATION_JSON)
+                               .post(Entity.entity(
+                                               "{\"service-template-path\":\"" + template.getURI().toString() + "\""
+                                                               + ",\"service-template-filename\":\"" + template.getFilename() + "\"}",
+                                               MediaType.APPLICATION_JSON));
+
+               ValidationResultImpl result = new ValidationResultImpl();
+               if (response.getStatus() >= 200 && response.getStatus() < 300) {
+                       result.setFailed(false);
+               } else if (response.getStatus() == 400) {
+                       result.setFailed(true);
+               } else {
+                       throw new Exception(
+                                       "received error response '" + response.getStatus() + "':" + response.readEntity(String.class));
+               }
+               return result;
+
+       }
+
+       /**
+        *
+        * @return a list of service templates
+        */
+       public List<? extends ServiceTemplate> list_service_templates() {
+               List<? extends ServiceTemplate> templates = base_target.path("templates").request(MediaType.APPLICATION_JSON)
+                               .get(new GenericType<List<ServiceTemplateImpl>>() {
+                               });
+
+               return templates;
+       }
+
+       /**
+        * Deletes the specified template.
+        *
+        * TODO: Error handling is a little blunt. Need to describe failures better
+        *
+        * @param template_id
+        *            the template id to delete
+        * @throws IllegalArgumentException
+        *             thrown when the template can't be deleted
+        * @throws Exception
+        *             other server side errors
+        */
+       public void delete_service_template(int template_id) throws IllegalArgumentException, Exception {
+               Response response = base_target.path("templates/" + template_id).request(MediaType.APPLICATION_JSON).delete();
+
+               if (response.getStatus() >= 200 && response.getStatus() < 300) {
+                       return;
+               } else if (response.getStatus() == 400) {
+                       throw new IllegalArgumentException("Error deleting template '" + template_id + "'");
+               } else {
+                       throw new Exception("Error processing request. Return code = " + response.getStatus());
+               }
+       }
+
+       /**
+        * List the node templates for a given template id
+        *
+        * @param template_id
+        * @return
+        */
+       public List<? extends NodeTemplate> list_nodes(int template_id) {
+               List<? extends NodeTemplate> nodes = base_target.path("templates/" + template_id + "/nodes")
+                               .request(MediaType.APPLICATION_JSON).get(new GenericType<List<NodeTemplateImpl>>() {
+                               });
+               return nodes;
+       }
+
+       /**
+        * Get a specific node by id
+        *
+        * @param node_id
+        *            the node id
+        * @return
+        * @throws IllegalArgumentException
+        */
+       public NodeTemplate get_node(int node_id) throws IllegalArgumentException {
+               NodeTemplate node = base_target.path("nodes/" + node_id).request(MediaType.APPLICATION_JSON)
+                               .get(NodeTemplateImpl.class);
+               return node;
+       }
+
+       public List<? extends Service> list_services() {
+               List<? extends Service> services = base_target.path("services").request(MediaType.APPLICATION_JSON)
+                               .get(new GenericType<List<ServiceImpl>>() {
+                               });
+               return services;
+       }
+
+       public Service get_service(int service_id) throws IllegalArgumentException {
+               throw new NotImplementedException();
+       }
+
+       public List<? extends Output> list_service_outputs(int service_id) throws IllegalArgumentException {
+               List<? extends Output> outputs = base_target.path("services").request(MediaType.APPLICATION_JSON)
+                               .get(new GenericType<List<OutputImpl>>() {
+                               });
+               return outputs;
+       }
+
+       public List<? extends Input> list_service_inputs(int service_id) throws IllegalArgumentException {
+               List<? extends Input> inputs = base_target.path("services").request(MediaType.APPLICATION_JSON)
+                               .get(new GenericType<List<InputImpl>>() {
+                               });
+               return inputs;
+       }
+
+       /**
+        * Create a service based on the supplied template
+        *
+        * @param template_id
+        *            the template to create the service for
+        * @param service_name
+        *            a name for the service
+        * @param inputs
+        *            an optional list of inputs for the service (can be null)
+        * @throws Exception
+        */
+       public void create_service(int template_id, String service_name, List<Input> inputs) throws Exception {
+
+               String json = "{" + inputsToJson(inputs) + "}";
+
+               Response response = base_target.path("templates/" + template_id + "/services/" + service_name)
+                               .request(MediaType.APPLICATION_JSON).post(Entity.entity(json, MediaType.APPLICATION_JSON));
+
+               if (response.getStatus() < 200 || response.getStatus() > 299) {
+                       throw new Exception(
+                                       "create service failed:" + response.getStatus() + " " + response.readEntity(String.class));
+               }
+       }
+
+       public void delete_service(int service_id) throws Exception {
+               Response response = base_target.path("services/" + service_id).request(MediaType.APPLICATION_JSON).delete();
+               if (!responseOK(response)) {
+                       throw new Exception(
+                                       "delete service failed: " + response.getStatus() + " " + response.readEntity(String.class));
+               }
+       }
+
+       /**
+        * List user workflows for supplied service
+        *
+        * @param service_id
+        * @return
+        * @throws IllegalArgumentException
+        */
+       public List<? extends Workflow> list_workflows(int service_id) throws IllegalArgumentException {
+               List<? extends Workflow> workflows = base_target.path("services/" + service_id + "/workflows")
+                               .request(MediaType.APPLICATION_JSON).get(new GenericType<List<WorkflowImpl>>() {
+                               });
+               return workflows;
+       }
+
+       public Workflow get_workflow(int workflow_id) throws IllegalArgumentException {
+               throw new NotImplementedException();
+       }
+
+       /**
+        * List all executions
+        *
+        * @return
+        * @throws Exception
+        */
+       public List<? extends Execution> list_executions() throws Exception {
+               List<? extends Execution> executions = base_target.path("executions").request(MediaType.APPLICATION_JSON)
+                               .get(new GenericType<List<ExecutionImpl>>() {
+                               });
+               return executions;
+       }
+
+       /**
+        * List executions for specified service
+        *
+        * @param service_id
+        * @return
+        * @throws Exception
+        */
+       public List<? extends Execution> list_executions(int service_id) throws Exception {
+               List<? extends Execution> executions = base_target.path("services/" + service_id + "/executions")
+                               .request(MediaType.APPLICATION_JSON).get(new GenericType<List<ExecutionImpl>>() {
+                               });
+               return executions;
+       }
+
+       /**
+        * Get details about a specified execution
+        *
+        * @param execution_id
+        * @return
+        * @throws IllegalArgumentException
+        */
+       public Execution get_execution(int execution_id) throws IllegalArgumentException {
+               Execution execution = base_target.path("executions/" + execution_id).request(MediaType.APPLICATION_JSON)
+                               .get(ExecutionImpl.class);
+               return execution;
+       }
+
+       /**
+        * Start an execution for the specified service
+        *
+        * @param service_id
+        *            the service to run the execution for
+        * @param workflow_name
+        *            the name of the workflow to execute
+        * @param details
+        *            details controlling execution operation
+        * @return the execution id
+        * @throws Exception
+        */
+       public int start_execution(int service_id, String workflow_name, ExecutionDetails details) throws Exception {
+               StringBuilder json = new StringBuilder("{");
+               if (details.getExecutor().length() > 0) {
+                       json.append("\"executor\":\"").append(details.getExecutor()).append("\",");
+               }
+               if (details.getInputs() != null) {
+                       json.append(inputsToJson(details.getInputs()));
+               }
+               json.append("\"task_max_attempts\":").append(details.getTaskMaxAttempts()).append(",");
+               json.append("\"task_retry_interval\":").append(details.getTaskRetryInterval()).append("}");
+
+               System.out.println("JSON=" + json.toString());
+
+               Response response = base_target.path("services/" + service_id + "/executions/" + workflow_name)
+                               .request(MediaType.APPLICATION_JSON).post(Entity.entity(json.toString(), MediaType.APPLICATION_JSON));
+
+               if (!responseOK(response)) {
+                       throw new Exception(
+                                       "start execution failed: " + response.getStatus() + " " + response.readEntity(String.class));
+               }
+
+               ObjectMapper mapper = new ObjectMapper(new JsonFactory());
+               JsonNode rootNode = mapper.readTree(response.readEntity(String.class));
+               int id = rootNode.get("id").asInt(-1);
+               return id;
+       }
+
+       public void resume_execution(int execution_id, ExecutionDetails details) throws IllegalArgumentException {
+               StringBuilder json = new StringBuilder("{");
+               if (details.getExecutor().length() > 0) {
+                       json.append("\"executor\":\"").append(details.getExecutor()).append("\",");
+               }
+               json.append("\"retry_failed_tasks\":").append(details.isRetry_failed_tasks()).append("}");
+               Response response = base_target.path("executions/" + execution_id).request(MediaType.APPLICATION_JSON)
+                               .post(Entity.entity(json.toString(), MediaType.APPLICATION_JSON));
+       }
+
+       public void cancel_execution(int execution_id) throws Exception {
+               Response response = base_target.path("executions/" + execution_id).request(MediaType.APPLICATION_JSON).delete();
+               if (!responseOK(response)) {
+                       throw new Exception(
+                                       "delete service failed: " + response.getStatus() + " " + response.readEntity(String.class));
+               }
+       }
+
+       /**
+        * ----- ----- PRIVATE METHODS -----
+        */
+
+       private boolean responseOK(Response response) {
+               return response.getStatus() > 199 && response.getStatus() < 300;
+       }
+
+       private String inputsToJson(List<Input> inputs) {
+               if (inputs == null)
+                       return null;
+
+               StringBuilder sb = new StringBuilder("\"inputs\":{");
+               for (Input input : inputs) {
+                       sb.append("\"").append(input.getName()).append("\":\"").append(input.getValue()).append("\",");
+               }
+               if (inputs.size() > 0)
+                       sb.deleteCharAt(sb.length() - 1); // trim comma
+
+               return sb.toString();
+       }
+}
diff --git a/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ServiceImpl.java b/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ServiceImpl.java
new file mode 100644 (file)
index 0000000..456335c
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * ============LICENSE_START===================================================
+ * Copyright (c) 2017 Cloudify.co.  All rights reserved.
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ * ============LICENSE_END====================================================
+*/
+package com.gigaspaces.aria.rest.client;
+
+import java.net.URI;
+import java.util.Date;
+
+/**
+ * 
+ *
+ * Created by DeWayne on 7/17/2017.
+ */
+public class ServiceImpl implements Service {
+    private int id;
+    private String description, name, template;
+    private Date created, updated;
+
+    public int getId(){
+        return id;
+    }
+
+    public String getDescription(){
+        return description;
+    }
+
+    public String getName(){
+        return name;
+    }
+
+    public String getServiceTemplate(){
+       return template;
+    }
+
+    public Date getCreated(){
+        return created;
+    }
+
+    public Date getUpdated(){
+        return updated;
+    }
+    
+        
+}    
old mode 100755 (executable)
new mode 100644 (file)
index 0df6d60..a2ca8cf
@@ -1,31 +1,32 @@
-/*\r
- * ============LICENSE_START===================================================\r
- * Copyright (c) 2017 Cloudify.co.  All rights reserved.\r
- * ===================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not\r
- * use this file except in compliance with the License. You may obtain a copy\r
- * of the License at\r
- *\r
- *       http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\r
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r
- * License for the specific language governing permissions and limitations under\r
- * the License.\r
- * ============LICENSE_END====================================================\r
-*/\r
-package com.gigaspaces.aria.rest.client;\r
-\r
-import java.net.URI;\r
-\r
-/**\r
- * Created by DeWayne on 7/12/2017.\r
- */\r
-public interface ServiceTemplate {\r
-    String getName();\r
-    URI getURI();\r
-    int getId();\r
-    String getFilename();\r
-    String getDescription();\r
-}\r
+/*
+ * ============LICENSE_START===================================================
+ * Copyright (c) 2017 Cloudify.co.  All rights reserved.
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy
+ * of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ * ============LICENSE_END====================================================
+*/
+package com.gigaspaces.aria.rest.client;
+
+import java.net.URI;
+
+/**
+ * Created by DeWayne on 7/12/2017.
+ */
+public interface ServiceTemplate {
+    String getName();
+    URI getURI();
+    int getId();
+    String getFilename();
+    String getDescription();
+    byte[] getCSARBytes();
+}
old mode 100755 (executable)
new mode 100644 (file)
index 9e158a2..a41d5b7
@@ -31,6 +31,7 @@ public class ServiceTemplateImpl implements ServiceTemplate {
     private URI uri;
     private String filename = DEFAULT_TEMPLATE_NAME;
     private String description;
+    private byte[] csar_blob; // for opaque binary
 
     public ServiceTemplateImpl(){}
 
@@ -40,7 +41,7 @@ public class ServiceTemplateImpl implements ServiceTemplate {
     }
 
     /**
-     * Construct an instance
+     * Construct an instance based on CSAR
      * @param name a textual name for the template
      * @param uri a URI to a CSAR
      * @param filename the filename in the CSAR representing main yaml template
@@ -51,6 +52,13 @@ public class ServiceTemplateImpl implements ServiceTemplate {
         this.filename=filename;
         this.description=description;
     }
+    
+    /**
+     * Construct an instance based on CSAR array
+     */
+    public ServiceTemplateImpl(byte[] csar_bytes) {
+       this.csar_blob = csar_bytes;
+    }
 
     public int getId(){
         return id;
@@ -76,6 +84,9 @@ public class ServiceTemplateImpl implements ServiceTemplate {
     public void setFilename(String filename){
         this.filename=filename;
     }
+    public byte[] getCSARBytes() {
+       return csar_blob;
+    }
 
     public String getDescription(){ return description;}
 }
index 5836e4c..c3add03 100644 (file)
@@ -2,12 +2,12 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>so</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
 
-       <groupId>org.openecomp.so</groupId>
+       <groupId>org.onap.so</groupId>
        <artifactId>asdc-controller</artifactId>
        <name>asdc-controller</name>
        <description>ASDC CLient and Controller</description>
@@ -47,7 +47,7 @@
                        <scope>test</scope>
                </dependency>  
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>mso-catalog-db</artifactId>
                        <version>${project.version}</version>
                </dependency>
                </dependency>
 
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>common</artifactId>
                        <version>${project.version}</version>
                </dependency>
                        <scope>provided</scope>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>status-control</artifactId>
                        <version>${project.version}</version>
                </dependency>
index f6ac480..be86574 100644 (file)
@@ -79,13 +79,9 @@ public final class VfModuleStructure {
                artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_ENV));
                artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_VOL));
 
-               for (VfModuleArtifact artifact:(artifactsMap.get(ASDCConfiguration.HEAT_NESTED))) {
-                       artifactsList.add(artifact);
-               }
+               artifactsList.addAll((artifactsMap.get(ASDCConfiguration.HEAT_NESTED)));
 
-               for (VfModuleArtifact artifact:(artifactsMap.get(ASDCConfiguration.HEAT_ARTIFACT))) {
-                       artifactsList.add(artifact);
-               }
+               artifactsList.addAll((artifactsMap.get(ASDCConfiguration.HEAT_ARTIFACT)));
 
                artifactsList.addAll(artifactsMap.get(ASDCConfiguration.HEAT_VOL));
 
index 7557f5e..e64f68b 100644 (file)
@@ -1,13 +1,13 @@
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">\r
        <parent>\r
-               <groupId>org.openecomp.so</groupId>\r
+               <groupId>org.onap.so</groupId>\r
                <artifactId>bpmn</artifactId>\r
                <version>1.2.0-SNAPSHOT</version>\r
        </parent>\r
 \r
        <modelVersion>4.0.0</modelVersion>\r
-       <groupId>org.openecomp.so</groupId>\r
+       <groupId>org.onap.so</groupId>\r
        <artifactId>MSOCockpit</artifactId>\r
        <packaging>pom</packaging>\r
        <name>MSOCockpit</name>\r
                </dependency>\r
                \r
                <dependency>\r
-                       <groupId>org.openecomp.so</groupId>\r
+                       <groupId>org.onap.so</groupId>\r
                        <artifactId>common</artifactId>\r
                        <version>${project.version}</version>\r
                </dependency>\r
                <!--<dependency>\r
-                       <groupId>org.openecomp.so</groupId>\r
+                       <groupId>org.onap.so</groupId>\r
                        <artifactId>cockpit-urnmap-plugin</artifactId>\r
                        <version>${project.version}</version>\r
                </dependency> -->\r
                <dependency>\r
-                       <groupId>org.openecomp.so</groupId>\r
+                       <groupId>org.onap.so</groupId>\r
                        <artifactId>MSOCoreBPMN</artifactId>\r
                        <version>${project.version}</version>\r
                </dependency>\r
index 4a7cb59..71626f5 100644 (file)
@@ -4,7 +4,7 @@
        xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>bpmn</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
                        <version>3.4</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>MSOCoreBPMN</artifactId>
                        <version>${project.version}</version>
                </dependency>
                <dependency>
                        <!-- unit test utilities -->
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>MSOCoreBPMN</artifactId>
                        <version>${project.version}</version>
                        <classifier>tests</classifier>
                        <scope>test</scope>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>common</artifactId>
                        <version>${project.version}</version>
                </dependency>
                        <version>2.0</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>MSORESTClient</artifactId>
                        <version>${project.version}</version>
                </dependency>
                        <artifactId>guava</artifactId>
                        <version>22.0</version>
                </dependency>
+               <dependency>
+                       <groupId>org.assertj</groupId>
+                       <artifactId>assertj-core</artifactId>
+                       <version>3.9.0</version>
+                       <scope>test</scope>
+               </dependency>
+               <dependency>
+                       <groupId>pl.pragmatists</groupId>
+                       <artifactId>JUnitParams</artifactId>
+                       <version>1.1.1</version>
+               </dependency>
        </dependencies>
 </project>
index 06cc284..2645ea3 100644 (file)
@@ -17,7 +17,9 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-package org.openecomp.mso.bpmn.common.scripts;
+package org.openecomp.mso.bpmn.common.scripts
+
+import org.openecomp.mso.bpmn.core.json.DecomposeJsonUtil;
 
 import static org.apache.commons.lang3.StringUtils.*;
 
@@ -96,12 +98,12 @@ public class DecomposeService extends AbstractServiceTaskProcessor {
                        // check for input
                        String serviceModelInvariantId = execution.getVariable("DDS_serviceModelInvariantId")
                        String modelVersion = execution.getVariable("DDS_modelVersion")
-                       
+
                        utils.log("DEBUG", "serviceModelInvariantId: " + serviceModelInvariantId, isDebugEnabled)
-                       utils.log("DEBUG", "modelVersion: " + modelVersion, isDebugEnabled)                     
-                       
+                       utils.log("DEBUG", "modelVersion: " + modelVersion, isDebugEnabled)
+
                        JSONObject catalogDbResponse = null
-                       
+
                        if (modelVersion != null && modelVersion.length() > 0)
                                catalogDbResponse = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidAndServiceModelVersion(execution, serviceModelInvariantId, modelVersion, "v2")
                        else
@@ -140,7 +142,7 @@ public class DecomposeService extends AbstractServiceTaskProcessor {
                        utils.log("DEBUG", "getting service decomposition", isDebugEnabled)
 
                        String catalogDbResponse = execution.getVariable("DDS_catalogDbResponse")
-                       ServiceDecomposition serviceDecomposition = new ServiceDecomposition(catalogDbResponse, serviceInstanceId)
+                       ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.jsonToServiceDecomposition(catalogDbResponse, serviceInstanceId)
 
                        execution.setVariable("serviceDecomposition", serviceDecomposition)
                        execution.setVariable("serviceDecompositionString", serviceDecomposition.toJsonString())
index 14f9135..cfc5171 100644 (file)
 \r
 package org.openecomp.mso.bpmn.common.scripts\r
 \r
-import static org.apache.commons.lang3.StringUtils.*\r
-\r
-import org.apache.commons.lang3.*\r
+import org.apache.commons.lang3.StringEscapeUtils\r
 import org.camunda.bpm.engine.delegate.BpmnError\r
 import org.camunda.bpm.engine.runtime.Execution\r
 import org.openecomp.mso.rest.APIResponse\r
 import org.springframework.web.util.UriUtils\r
 \r
+import static org.apache.commons.lang3.StringUtils.isBlank\r
+\r
 \r
 /**\r
  * This class supports the GenericGetService Sub Flow.\r
@@ -301,7 +301,9 @@ class GenericGetService extends AbstractServiceTaskProcessor{
                        if(responseCode == 200){\r
                                utils.log("DEBUG", "  Query for Service Instance Url Received a Good Response Code", isDebugEnabled)\r
                                execution.setVariable("GENGS_SuccessIndicator", true)\r
-                               if(utils.nodeExists(aaiResponse, "result-data")){\r
+                               String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")\r
+                               boolean nodeExists = isBlank(globalCustomerId) ? utils.nodeExists(aaiResponse, "result-data") : hasCustomerServiceInstance(aaiResponse, globalCustomerId)\r
+                               if(nodeExists){\r
                                        utils.log("DEBUG", "Query for Service Instance Url Response Does Contain Data" , isDebugEnabled)\r
                                        execution.setVariable("GENGS_FoundIndicator", true)\r
                                        String resourceLink = utils.getNodeText1(aaiResponse, "resource-link")\r
@@ -439,4 +441,30 @@ class GenericGetService extends AbstractServiceTaskProcessor{
                utils.log("DEBUG", " *** COMPLETED GenericGetService GetServiceObject Process*** ", isDebugEnabled)\r
        }\r
 \r
+       /**\r
+        * An utility method which check whether a service(by name) is already present within a globalCustomerId or not.\r
+        * @param jsonResponse raw response received from AAI by searching ServiceInstance by Name.\r
+        * @param globalCustomerId\r
+        * @return {@code true} if globalCustomerId is found at 6th position within "resource-link", {@code false} in any other cases.\r
+        */\r
+       public boolean hasCustomerServiceInstance(String aaiResponse, final String globalCustomerId) {\r
+               if (isBlank(aaiResponse)) {\r
+                       return false\r
+               }\r
+               aaiResponse = utils.removeXmlNamespaces(aaiResponse)\r
+               ArrayList<String> linksArray = utils.getMultNodeObjects(aaiResponse, "resource-link")\r
+               if (linksArray == null || linksArray.size() == 0) {\r
+                       return false\r
+               }\r
+               for (String resourceLink : linksArray) {\r
+                       int custStart = resourceLink.indexOf("customer/")\r
+                       int custEnd = resourceLink.indexOf("/service-subscriptions/")\r
+                       String receivedCustomerId = resourceLink.substring(custStart + 9, custEnd)\r
+                       if (globalCustomerId.equals(receivedCustomerId)) {\r
+                               return true\r
+                       }\r
+               }\r
+               return false\r
+       }\r
+\r
 }
\ No newline at end of file
index ca815cf..214be06 100644 (file)
@@ -32,13 +32,9 @@ import com.fasterxml.jackson.databind.JsonMappingException;
 
 public interface AAIRestClient {
        
-       Pservers getPhysicalServers(String hostName, String uuid);
-       
-       List<Pserver> getPhysicalServerByVnfId(String vnfId, String transactionLoggingUuid) throws UnsupportedEncodingException, JsonParseException, JsonMappingException, IOException;
-       
-       void updateMaintenceFlag(String vnfId,boolean inMaint, String transactionLoggingUuid) throws Exception;
-
-       void updateMaintenceFlagVnfId(String vnfId, boolean inMaint, String transactionLoggingUuid) throws Exception;
-       
-       GenericVnf getVnfByName(String vnfId,  String transactionLoggingUuid) throws Exception;
+Pservers getPhysicalServers(String hostName, String uuid);     
+List<Pserver> getPhysicalServerByVnfId(String vnfId, String transactionLoggingUuid) throws UnsupportedEncodingException, JsonParseException, JsonMappingException, IOException;        
+void updateMaintenceFlag(String vnfId,boolean inMaint, String transactionLoggingUuid) throws JsonParseException, JsonMappingException, IOException;
+void updateMaintenceFlagVnfId(String vnfId, boolean inMaint, String transactionLoggingUuid) throws JsonParseException, JsonMappingException , IOException;
+GenericVnf getVnfByName(String vnfId,  String transactionLoggingUuid) throws JsonParseException, JsonMappingException , IOException;
 }
index ae8638f..af1eddf 100644 (file)
@@ -139,14 +139,14 @@ public class AAIRestClientImpl implements AAIRestClient {
        }
        
        @Override
-       public void updateMaintenceFlag(String vnfName, boolean inMaint, String transactionLoggingUuid) throws Exception {
+       public void updateMaintenceFlag(String vnfName, boolean inMaint, String transactionLoggingUuid) throws JsonParseException, JsonMappingException, IOException {
                GenericVnfs genericVnfs = webTarget.register(AAIResourcesObjectMapperProvider.class).path(ENDPOINT_GET_ALL_VNFS)
                                .queryParam("vnf-name", vnfName).request().header("X-FromAppId", "MSO")
                                .header("X-TransactionId", transactionLoggingUuid).header("Content-Type", "application/json")
                                .accept(MediaType.APPLICATION_JSON_TYPE).get().readEntity(GenericVnfs.class);
 
                if (genericVnfs.getGenericVnf().size() > 1)
-                       throw new Exception("Multiple Generic Vnfs Returned");
+                       throw new IndexOutOfBoundsException ("Multiple Generic Vnfs Returned");
 
                GenericVnf genericVnf = genericVnfs.getGenericVnf().get(0);
                updateMaintenceFlagVnfId(genericVnf.getVnfId(), inMaint, transactionLoggingUuid);
@@ -154,7 +154,7 @@ public class AAIRestClientImpl implements AAIRestClient {
 
        @Override
        public void updateMaintenceFlagVnfId(String vnfId, boolean inMaint, String transactionLoggingUuid)
-                       throws Exception {
+                       throws JsonParseException, JsonMappingException, IOException {
                GenericVnf genericVnf = new GenericVnf();
                genericVnf.setInMaint(inMaint);
                webTarget.register(AAIResourcesObjectMapperProvider.class).path(GENERIC_VNF_PATH + "/" + vnfId).request()
@@ -165,7 +165,7 @@ public class AAIRestClientImpl implements AAIRestClient {
        }
 
        @Override
-       public GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) throws Exception {
+       public GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) throws JsonParseException, JsonMappingException, IOException {
                return webTarget.register(AAIResourcesObjectMapperProvider.class).path(GENERIC_VNF_PATH + "/" + vnfId).request()
                                .header("X-FromAppId", "MSO").header("X-TransactionId", transactionLoggingUuid)
                                .header("Content-Type", "application/json").accept(MediaType.APPLICATION_JSON_TYPE).get()
index 26c1c4a..f66034f 100644 (file)
@@ -76,7 +76,7 @@ public class ApplicationControllerClient {
        private LifeCycleManagerStateful client;
 
        public Status runCommand(Action action, ActionIdentifiers identifier, Flags flags, Payload payload,
-                       String requestID) throws Exception {
+                       String requestID) throws IllegalAccessException,NoSuchMethodException,AppcClientException,JsonProcessingException,InvocationTargetException {
                Object requestObject = createRequest(action, identifier, flags, payload, requestID);
                client = getAppCClient();
                Method lcmMethod = appCSupport.getAPIMethod(action.name(), client, false);
@@ -118,7 +118,7 @@ public class ApplicationControllerClient {
        }
 
        public Object createRequest(Action action, ActionIdentifiers identifier, Flags flags, Payload payload,
-                       String requestId) throws Exception {
+                       String requestId) throws IllegalAccessException,NoSuchMethodException,InvocationTargetException {
                Object requestObject = appCSupport.getInput(action.name());
                try {
                        org.openecomp.appc.client.lcm.model.CommonHeader commonHeader = buildCommonHeader(requestId);
@@ -129,7 +129,7 @@ public class ApplicationControllerClient {
                                        .invoke(requestObject, identifier);
                } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                    LOGGER.debug("Exception:", e);
-                       throw new Exception("Error Building AppC Request: " + e.getMessage());
+                       throw new IllegalAccessException("Error Building AppC Request: " + e.getMessage());
                }
                return requestObject;
        }
index ab7ee7a..5949c3a 100644 (file)
  * See the License for the specific language governing permissions and 
  * limitations under the License. 
  * ============LICENSE_END========================================================= 
- */ 
+ */
 
 package org.openecomp.mso.bpmn.common.scripts
 
-import org.junit.runner.RunWith;
-import static org.junit.Assert.*
-import static org.mockito.Mockito.*
-
 import org.camunda.bpm.engine.delegate.BpmnError
 import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity
 import org.junit.Before
 import org.junit.Test
 import org.junit.runner.RunWith
+import org.mockito.ArgumentCaptor
 import org.mockito.MockitoAnnotations
 import org.mockito.runners.MockitoJUnitRunner
 import org.openecomp.mso.bpmn.core.WorkflowException
 
+import static org.assertj.core.api.Assertions.assertThat
+import static org.assertj.core.api.Assertions.assertThatThrownBy
+import static org.mockito.Matchers.eq
+import static org.mockito.Mockito.*
 
 @RunWith(MockitoJUnitRunner.class)
 class CompleteMsoProcessTest {
@@ -128,7 +129,7 @@ class CompleteMsoProcessTest {
                when(mockExecution.getVariable("CMSO_mso-bpel-name")).thenReturn("BPEL")
                when(mockExecution.getVariable("URN_mso_adapters_db_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC");
                when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7");
-               
+
                CompleteMsoProcess completeMsoProcess = new CompleteMsoProcess()
                completeMsoProcess.setUpdateDBstatustoSuccessPayload(mockExecution)
 
@@ -145,29 +146,25 @@ class CompleteMsoProcessTest {
 </sdncadapterworkflow:MsoCompletionResponse>"""
 */
        @Test
-       public void testbuildDataError(){
-
-               boolean thrown = false;
-               String msg = "Some-Message";
-               
-               ExecutionEntity mockExecution = mock(ExecutionEntity.class)
-               when(mockExecution.getVariable("CMSO_mso-bpel-name")).thenReturn("BPEL-NAME")
-               when(mockExecution.getVariable("testProcessKey")).thenReturn("CompleteMsoProcess")
-               
-               WorkflowException exception = new WorkflowException("CompleteMsoProcess", 500, msg);
-
-               try{
-               CompleteMsoProcess completeMsoProcess = new CompleteMsoProcess()
-               completeMsoProcess.buildDataError(mockExecution, msg)
-               }
-               catch (BpmnError e){
-                       thrown = true;
-               }
-
-               
-               verify(mockExecution).setVariable("CompleteMsoProcessResponse",msoCompletionResponse)
-               // Can't seem to figure out how to verify the exception and have spent way too much time on fixing this test case!
-               //verify(mockExecution).setVariable("WorkflowException",exception)
-               assertTrue(thrown);
-       }
+    void testBuildDataError() {
+               // given
+               def message = "Some-Message"
+
+               def mockExecution = mock ExecutionEntity.class
+               when mockExecution.getVariable("CMSO_mso-bpel-name") thenReturn "BPEL-NAME"
+               when mockExecution.getVariable("testProcessKey") thenReturn "CompleteMsoProcess"
+
+               def completeMsoProcess = new CompleteMsoProcess()
+               // when
+               assertThatThrownBy { completeMsoProcess.buildDataError(mockExecution, message) } isInstanceOf BpmnError
+               // then
+               verify mockExecution setVariable("CompleteMsoProcessResponse", msoCompletionResponse)
+               def argumentCaptor = ArgumentCaptor.forClass WorkflowException.class
+               verify mockExecution setVariable(eq("WorkflowException"), argumentCaptor.capture())
+               def capturedException = argumentCaptor.value
+
+               assertThat capturedException.processKey isEqualTo "CompleteMsoProcess"
+               assertThat capturedException.errorCode isEqualTo 500
+               assertThat capturedException.errorMessage isEqualTo message
+    }
 }
\ No newline at end of file
index b117283..82cceb0 100644 (file)
@@ -482,6 +482,61 @@ public class GenericGetServiceTest extends WorkflowTest {
                assertEquals(expectedWorkflowException, workflowException);\r
        }\r
 \r
+    @Test\r
+    @Deployment(resources = {"subprocess/GenericGetService.bpmn"})\r
+    public void testGenericGetService_success_serviceInstance_byNameServicePresent() throws Exception{\r
+\r
+        MockNodeQueryServiceInstanceByName("1604-MVM-26", "GenericFlows/getSIUrlByNameMultiCustomer.xml");\r
+        MockGetServiceInstance("XyCorporation", "123456789", "MIS%252F1604%252F0026%252FSW_INTERNET", "GenericFlows/getServiceInstance.xml");\r
+\r
+        Map<String, String> variables = new HashMap<String, String>();\r
+        setVariablesInstance(variables, null, "1604-MVM-26", "XyCorporation", null);\r
+\r
+        WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables);\r
+        waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID());\r
+\r
+        String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator");\r
+        String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator");\r
+        String resourceLink = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_resourceLink");\r
+        String response = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowResponse");\r
+        String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException");\r
+        String siUrlResponseCode = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainSIUrlResponseCode");\r
+\r
+        assertEquals("true", successIndicator);\r
+        assertEquals("true", found);\r
+               assertNotNull(resourceLink);\r
+        assertNotNull(response);\r
+        assertEquals("200", siUrlResponseCode);\r
+        assertEquals(null, workflowException);\r
+    }\r
+\r
+       @Test\r
+       @Deployment(resources = {"subprocess/GenericGetService.bpmn"})\r
+       public void testGenericGetService_success_serviceInstance_byNameServiceNotPresent() throws Exception{\r
+\r
+               MockNodeQueryServiceInstanceByName("1604-MVM-26", "GenericFlows/getSIUrlByNameMultiCustomer.xml");\r
+               MockGetServiceInstance("CorporationNotPresent", "123456789", "MIS%252F1604%252F0026%252FSW_INTERNET", "GenericFlows/getServiceInstance.xml");\r
+\r
+               Map<String, String> variables = new HashMap<String, String>();\r
+               setVariablesInstance(variables, null, "1604-MVM-26", "CorporationNotPresent", null);\r
+\r
+               WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables);\r
+               waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID());\r
+\r
+               String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator");\r
+               String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator");\r
+               String resourceLink = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_resourceLink");\r
+               String response = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowResponse");\r
+               String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException");\r
+               String siUrlResponseCode = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainSIUrlResponseCode");\r
+\r
+               assertEquals("true", successIndicator);\r
+               assertEquals("false", found);\r
+               assertEquals(null, resourceLink);\r
+               assertEquals("  ", response);\r
+               assertEquals("200", siUrlResponseCode);\r
+               assertEquals(null, workflowException);\r
+       }\r
 \r
        private void setVariablesInstance(Map<String, String> variables, String siId, String siName, String globalCustId, String serviceType) {\r
                variables.put("isDebugLogEnabled", "true");\r
index ce8eb7a..df15a2a 100644 (file)
@@ -1634,10 +1634,10 @@ public class WorkflowTest {
                                return null;\r
                        }\r
 \r
-                       Collections.sort(processInstanceList, new Comparator<HistoricProcessInstance>() {\r
-                           public int compare(HistoricProcessInstance m1, HistoricProcessInstance m2) {\r
-                               return m1.getStartTime().compareTo(m2.getStartTime());\r
-                           }\r
+                       processInstanceList.sort(new Comparator<HistoricProcessInstance>() {\r
+                               public int compare(HistoricProcessInstance m1, HistoricProcessInstance m2) {\r
+                                       return m1.getStartTime().compareTo(m2.getStartTime());\r
+                               }\r
                        });\r
 \r
                        HistoricProcessInstance processInstance = processInstanceList.get(0);\r
@@ -1672,10 +1672,10 @@ public class WorkflowTest {
                                return null;\r
                        }\r
 \r
-                       Collections.sort(processInstanceList, new Comparator<HistoricProcessInstance>() {\r
-                           public int compare(HistoricProcessInstance m1, HistoricProcessInstance m2) {\r
-                               return m1.getStartTime().compareTo(m2.getStartTime());\r
-                           }\r
+                       processInstanceList.sort(new Comparator<HistoricProcessInstance>() {\r
+                               public int compare(HistoricProcessInstance m1, HistoricProcessInstance m2) {\r
+                                       return m1.getStartTime().compareTo(m2.getStartTime());\r
+                               }\r
                        });\r
 \r
                        HistoricProcessInstance processInstance = processInstanceList.get(subflowInstanceIndex);\r
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/client/ResponseExceptionMapperImplTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/client/ResponseExceptionMapperImplTest.java
new file mode 100644 (file)
index 0000000..8943014
--- /dev/null
@@ -0,0 +1,111 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.mso.client;
+
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.common.base.Charsets;
+import javax.ws.rs.BadRequestException;
+import javax.ws.rs.ForbiddenException;
+import javax.ws.rs.InternalServerErrorException;
+import javax.ws.rs.NotAcceptableException;
+import javax.ws.rs.NotAllowedException;
+import javax.ws.rs.NotAuthorizedException;
+import javax.ws.rs.NotFoundException;
+import javax.ws.rs.NotSupportedException;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.client.ClientResponseContext;
+import javax.ws.rs.core.Response.Status;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+import org.apache.commons.io.IOUtils;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(JUnitParamsRunner.class)
+public class ResponseExceptionMapperImplTest {
+
+    private static final ResponseExceptionMapperImpl mapper = new ResponseExceptionMapperImpl();
+
+    public static Object[][] statusesAndCorrespondingExceptions() {
+        return new Object[][]{
+                {Status.BAD_REQUEST, BadRequestException.class},
+                {Status.UNAUTHORIZED, NotAuthorizedException.class},
+                {Status.FORBIDDEN, ForbiddenException.class},
+                {Status.NOT_FOUND, NotFoundException.class},
+                {Status.METHOD_NOT_ALLOWED, NotAllowedException.class},
+                {Status.NOT_ACCEPTABLE, NotAcceptableException.class},
+                {Status.PRECONDITION_FAILED, PreconditionFailedException.class},
+                {Status.UNSUPPORTED_MEDIA_TYPE, NotSupportedException.class},
+                {Status.INTERNAL_SERVER_ERROR, InternalServerErrorException.class},
+                {Status.SERVICE_UNAVAILABLE, WebApplicationException.class},
+                {Status.BAD_GATEWAY, WebApplicationException.class},
+        };
+    }
+
+    @Test
+    @Parameters(method = "statusesAndCorrespondingExceptions")
+    public void shouldThrowExceptionWhenStatusIsNotOk(Status status, Class<Exception> expectedException) {
+        // given
+        ClientResponseContext responseContext = createMockResponseContext(status);
+        // when, then
+        assertThatThrownBy(() -> mapper.filter(null, responseContext)).isInstanceOf(expectedException);
+    }
+
+    @Test
+    public void shouldNotThrowExceptionWhenStatusIsOk() {
+        // given
+        ClientResponseContext responseContext = createMockResponseContext(Status.OK);
+        // when, then
+        assertThatCode(() -> mapper.filter(null, responseContext)).doesNotThrowAnyException();
+    }
+
+    @Test
+    public void shouldThrowExceptionWithCustomMessageWhenResponseHasEntity() {
+        // given
+        ClientResponseContext responseContext = createMockResponseContext(Status.BAD_REQUEST);
+        when(responseContext.hasEntity()).thenReturn(true);
+        when(responseContext.getEntityStream()).thenReturn(IOUtils.toInputStream("test message", Charsets.UTF_8));
+        // when, then
+        assertThatThrownBy(() -> mapper.filter(null, responseContext)).isInstanceOf(BadRequestException.class)
+                .hasMessage("test message");
+    }
+
+    @Test
+    public void shouldThrowExceptionWithDefaultMessageWhenResponseHasNoEntity() {
+        // given
+        ClientResponseContext responseContext = createMockResponseContext(Status.BAD_REQUEST);
+        when(responseContext.hasEntity()).thenReturn(false);
+        // when, then
+        assertThatThrownBy(() -> mapper.filter(null, responseContext)).isInstanceOf(BadRequestException.class)
+                .hasMessage("empty message");
+    }
+
+    private static ClientResponseContext createMockResponseContext(Status status) {
+        ClientResponseContext responseContext = mock(ClientResponseContext.class);
+        when(responseContext.getStatusInfo()).thenReturn(status);
+        when(responseContext.getStatus()).thenReturn(status.getStatusCode());
+        return responseContext;
+    }
+}
\ No newline at end of file
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/client/appc/ApplicationControllerSupportTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/client/appc/ApplicationControllerSupportTest.java
new file mode 100644 (file)
index 0000000..0a323e4
--- /dev/null
@@ -0,0 +1,83 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.mso.client.appc;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.appc.client.lcm.model.Status;
+import org.openecomp.mso.client.appc.ApplicationControllerSupport.StatusCategory;
+
+@RunWith(JUnitParamsRunner.class)
+public class ApplicationControllerSupportTest {
+
+    public static Object[][] statusesAndCategories() {
+        return new Object[][]{
+                {100, StatusCategory.NORMAL},
+                {200, StatusCategory.ERROR},
+                {300, StatusCategory.ERROR},
+                {400, StatusCategory.NORMAL},
+                {401, StatusCategory.ERROR},
+                {500, StatusCategory.NORMAL},
+                {501, StatusCategory.ERROR},
+                {502, StatusCategory.WARNING},
+                {800, StatusCategory.WARNING},
+        };
+    }
+
+    public static Object[][] statusesAndFinalities() {
+        return new Object[][]{
+                {100, false},
+                {200, true},
+                {300, true},
+                {400, true},
+                {500, false},
+                {800, true},
+        };
+    }
+
+    @Test
+    @Parameters(method = "statusesAndCategories")
+    public void shouldReturnCategoryForCode(int code, StatusCategory category) throws Exception {
+        // when
+        StatusCategory detectedCategory = ApplicationControllerSupport.getCategoryOf(createStatus(code));
+        // then
+        assertThat(detectedCategory).isEqualTo(category);
+    }
+
+    @Test
+    @Parameters(method = "statusesAndFinalities")
+    public void shouldReturnFinalityForCode(int code, boolean expectedFinality) throws Exception {
+        // when
+        boolean finality = ApplicationControllerSupport.getFinalityOf(createStatus(code));
+        // then
+        assertThat(finality).isEqualTo(expectedFinality);
+    }
+
+    private Status createStatus(int code) {
+        Status status = new Status();
+        status.setCode(code);
+        return status;
+    }
+}
\ No newline at end of file
diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlByNameMultiCustomer.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlByNameMultiCustomer.xml
new file mode 100644 (file)
index 0000000..fce47fc
--- /dev/null
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<search-results xmlns="http://org.openecomp.aai.inventory/v11">
+    <result-data>
+        <resource-type>service-instance</resource-type>
+        <resource-link>/aai/v11/business/customers/customer/AbcBank/service-subscriptions/service-subscription/ABC-ST/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET</resource-link>
+    </result-data>
+    <result-data>
+        <resource-type>service-instance</resource-type>
+        <resource-link>/aai/v11/business/customers/customer/XyCorporation/service-subscriptions/service-subscription/XY-ST/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET</resource-link>
+    </result-data>
+</search-results>
\ No newline at end of file
index 267f175..960a553 100644 (file)
@@ -2,12 +2,12 @@
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <parent>
-        <groupId>org.openecomp.so</groupId>
+        <groupId>org.onap.so</groupId>
         <artifactId>bpmn</artifactId>
         <version>1.2.0-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
-    <groupId>org.openecomp.so</groupId>
+    <groupId>org.onap.so</groupId>
     <artifactId>MSOCoreBPMN</artifactId>
     <packaging>jar</packaging>
 
             <artifactId>Saxon-HE</artifactId>
         </dependency>
         <dependency>
-            <groupId>org.openecomp.so</groupId>
+            <groupId>org.onap.so</groupId>
             <artifactId>common</artifactId>
             <version>${project.version}</version>
         </dependency>
             <scope>test</scope>
         </dependency>
         <dependency>
-            <groupId>org.openecomp.so</groupId>
+            <groupId>org.onap.so</groupId>
             <artifactId>status-control</artifactId>
             <version>${project.version}</version>
         </dependency>
index 66edaaa..64068d2 100644 (file)
@@ -23,6 +23,7 @@ package org.openecomp.mso.bpmn.core;
 import java.io.Serializable;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.stream.Collectors;
 
 /**
  * An object that stores data for rollbacks.  Data is organized by type.  A
@@ -30,79 +31,72 @@ import java.util.Map;
  * in the same object for separate rollback operations.
  */
 public class RollbackData implements Serializable {
-       private static final long serialVersionUID = 1L;
 
-       private Map<String, Map<String, Serializable>> dictionary =
-               new HashMap<String, Map<String, Serializable>>();
-       
-       /**
-        * Returns true if the specified type is stored in this object.
-        * @param type the data type
-        */
-       public boolean hasType(String type) {
-               return dictionary.containsKey(type);
-       }
+    private static final long serialVersionUID = 1L;
 
-       /**
-        * Stores a single item.
-        * @param type the data type
-        * @param key the key
-        * @param value the value
-        */
-       public void put(String type, String key, String value) {
-               Map<String, Serializable> mapForType = dictionary.get(type);
+    private Map<String, Map<String, Serializable>> dictionary =
+            new HashMap<String, Map<String, Serializable>>();
 
-               if (mapForType == null) {
-                       mapForType = new HashMap<String, Serializable>();
-                       dictionary.put(type, mapForType);
-               }
+    /**
+     * Returns true if the specified type is stored in this object.
+     *
+     * @param type the data type
+     */
+    public boolean hasType(String type) {
+        return dictionary.containsKey(type);
+    }
 
-               mapForType.put(key, value);
-       }
+    /**
+     * Stores a single item.
+     *
+     * @param type the data type
+     * @param key the key
+     * @param value the value
+     */
+    public void put(String type, String key, String value) {
+        Map<String, Serializable> mapForType = dictionary.get(type);
 
-       /**
-        * Gets a single item.
-        * @param type the data type
-        * @param key the key
-        * @return the item or null if there is no item for the specified type and key
-        */
-       public Serializable get(String type, String key) {
-               Map<String, Serializable> mapForType = dictionary.get(type);
+        if (mapForType == null) {
+            mapForType = new HashMap<String, Serializable>();
+            dictionary.put(type, mapForType);
+        }
 
-               if (mapForType == null) {
-                       return null;
-               }
+        mapForType.put(key, value);
+    }
 
-               return mapForType.get(key);
-       }
+    /**
+     * Gets a single item.
+     *
+     * @param type the data type
+     * @param key the key
+     * @return the item or null if there is no item for the specified type and key
+     */
+    public Serializable get(String type, String key) {
+        Map<String, Serializable> mapForType = dictionary.get(type);
 
-       /**
-        * Gets a map containing all items associated with the specified data type.
-        * @param type the data type
-        * @return a map, or null if there are no items associated with the specified
-        *         data type
-        */
-       public Map<String, Serializable> get(String type) {
-               return dictionary.get(type);
-       }
+        if (mapForType == null) {
+            return null;
+        }
 
-       /**
-        * Returns a string representation of this object.
-        */
-       public String toString() {
-               StringBuilder out = new StringBuilder();
-               out.append(getClass().getSimpleName());
-               out.append('[');
-               boolean hasOne = false;
-               for (String type : dictionary.keySet()) {
-                       if (hasOne) {
-                               out.append(',');
-                       }
-                       out.append(type);
-                       out.append(dictionary.get(type));
-                       hasOne = true;
-               }
-               out.append(']');
-               return out.toString();
-       }
+        return mapForType.get(key);
+    }
+
+    /**
+     * Gets a map containing all items associated with the specified data type.
+     *
+     * @param type the data type
+     * @return a map, or null if there are no items associated with the specified data type
+     */
+    public Map<String, Serializable> get(String type) {
+        return dictionary.get(type);
+    }
+
+    /**
+     * Returns a string representation of this object.
+     */
+    @Override
+    public String toString() {
+        return dictionary.entrySet().stream().map(entry -> entry.getKey() + entry.getValue())
+                .collect(Collectors.joining(",", "[", "]"));
+    }
 }
index ce66e06..4d895f3 100644 (file)
@@ -142,6 +142,7 @@ public abstract class JsonWrapper implements Serializable  {
        /**\r
         * Returns a string representation of this object.\r
         */\r
+        @Override\r
        public String toString() {\r
                return this.toJsonString();\r
        }\r
index 1e68c84..0e985cc 100644 (file)
@@ -31,9 +31,8 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
 import com.fasterxml.jackson.annotation.JsonProperty;\r
 import com.fasterxml.jackson.annotation.JsonRootName;\r
 \r
-import org.json.JSONObject;\r
 import org.openecomp.mso.bpmn.core.json.DecomposeJsonUtil;\r
-\r
+import org.openecomp.mso.bpmn.core.json.JsonDecomposingException;\r
 \r
 \r
 /**\r
@@ -50,7 +49,6 @@ import org.openecomp.mso.bpmn.core.json.DecomposeJsonUtil;
 public class ServiceDecomposition extends JsonWrapper implements Serializable {\r
 \r
        private static final long serialVersionUID = 1L;\r
-       DecomposeJsonUtil jsonUtils = new DecomposeJsonUtil();\r
 \r
        @JsonProperty("modelInfo")\r
        private ModelInfo modelInfo;\r
@@ -67,48 +65,6 @@ public class ServiceDecomposition extends JsonWrapper implements Serializable {
        private List <AllottedResource>  allottedResources;\r
 \r
        public ServiceDecomposition () {\r
-               super();\r
-       }\r
-\r
-       public ServiceDecomposition (String catalogRestOutput) {\r
-\r
-               ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.JsonToServiceDecomposition(catalogRestOutput);\r
-               this.modelInfo = serviceDecomposition.getModelInfo();\r
-               this.vnfResources = serviceDecomposition.getServiceVnfs();\r
-               this.allottedResources = serviceDecomposition.getServiceAllottedResources();\r
-               this.networkResources = serviceDecomposition.getServiceNetworks();\r
-               this.serviceRole = serviceDecomposition.getServiceRole();\r
-               this.serviceType = serviceDecomposition.getServiceType();\r
-       }\r
-\r
-       /**\r
-        * Constructor taking Catalog DB Adapter REST output (serviceResources model) + service Instance ID\r
-        * @param catalogRestOutput\r
-        * @param serviceInstanceId\r
-        */\r
-       public ServiceDecomposition (String catalogRestOutput, String serviceInstanceId) {\r
-\r
-               ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.JsonToServiceDecomposition(catalogRestOutput);\r
-               this.modelInfo = serviceDecomposition.getModelInfo();\r
-               this.vnfResources = serviceDecomposition.getServiceVnfs();\r
-               this.allottedResources = serviceDecomposition.getServiceAllottedResources();\r
-               this.networkResources = serviceDecomposition.getServiceNetworks();\r
-\r
-               this.serviceRole = serviceDecomposition.getServiceRole();\r
-               this.serviceType = serviceDecomposition.getServiceType();\r
-               \r
-               this.serviceInstance = new ServiceInstance();\r
-               this.serviceInstance.setInstanceId(serviceInstanceId);\r
-       }\r
-\r
-       /**\r
-        * Constructor taking a Service Decomposition JSON serialization\r
-        * @param catalogRestOutput\r
-        * @param serviceInstanceId\r
-        */\r
-       public ServiceDecomposition (JSONObject jsonServiceDecomposition, String serviceInstanceId) {\r
-               //TODO provide constructor implementation\r
-\r
        }\r
 \r
        //*****\r
@@ -278,7 +234,7 @@ public class ServiceDecomposition extends JsonWrapper implements Serializable {
         * Add resource to the list\r
         * Given a ResourceDecomposition (subclass) object, add it to the Service Decomposition (in the appropriate category, e.g. as a VNF, Network, or Allotted Resource).\r
         * As dependencies are not currently supported, add it to the end of any ordered lists.\r
-        * @param Resource\r
+        * @param resource\r
         */\r
        public void addResource(Resource resource) {\r
                //create resource based upon type\r
@@ -299,36 +255,36 @@ public class ServiceDecomposition extends JsonWrapper implements Serializable {
 \r
        /**\r
         * Add resource to the list\r
-        * @param Resource\r
+        * @param jsonResource\r
         */\r
-       public void addVnfResource(String jsonResource) {\r
+       public void addVnfResource(String jsonResource) throws JsonDecomposingException {\r
                VnfResource vnfResource = null;\r
-               vnfResource = DecomposeJsonUtil.JsonToVnfResource(jsonResource);\r
+               vnfResource = DecomposeJsonUtil.jsonToVnfResource(jsonResource);\r
                this.addVnfResource(vnfResource);\r
        }\r
        /**\r
         * Add resource to the list\r
-        * @param Resource\r
+        * @param jsonResource\r
         */\r
-       public void addNetworkResource(String jsonResource) {\r
+       public void addNetworkResource(String jsonResource) throws JsonDecomposingException {\r
                NetworkResource networkResource = null;\r
-               networkResource = DecomposeJsonUtil.JsonToNetworkResource(jsonResource);\r
+               networkResource = DecomposeJsonUtil.jsonToNetworkResource(jsonResource);\r
                this.addVnfResource(networkResource);\r
        }\r
        /**\r
         * Add resource to the list\r
-        * @param Resource\r
+        * @param jsonResource\r
         */\r
-       public void addAllottedResource(String jsonResource) {\r
+       public void addAllottedResource(String jsonResource) throws JsonDecomposingException {\r
                AllottedResource allottedResource = null;\r
-               allottedResource = DecomposeJsonUtil.JsonToAllottedResource(jsonResource);\r
+               allottedResource = DecomposeJsonUtil.jsonToAllottedResource(jsonResource);\r
                this.addVnfResource(allottedResource);\r
        }\r
 \r
        /**\r
         * Given a ResourceDecomposition (subclass) object, locate it in the Service Decomposition by its unique ID, and replace the current version with the new one.\r
         * This method should support concurrency control via an auto-incrementing field in the ResourceDecomposition class.\r
-        * @param Resource\r
+        * @param newResource\r
         * @return TRUE if replacement was a success\r
         */\r
        public boolean replaceResource(Resource newResource){\r
@@ -365,7 +321,7 @@ public class ServiceDecomposition extends JsonWrapper implements Serializable {
 \r
        /**\r
         *  Given a resource object ID, locate it in the Service Decomposition by its unique ID, and delete it.\r
-        * @param Resource\r
+        * @param resource\r
         * @return TRUE if delete was a success\r
         */\r
        public boolean deleteResource(Resource resource){\r
index 71ef09c..dcd9e3b 100644 (file)
 \r
 package org.openecomp.mso.bpmn.core.json;\r
 \r
-import java.io.Serializable;\r
+import com.fasterxml.jackson.databind.DeserializationFeature;\r
+import com.fasterxml.jackson.databind.ObjectMapper;\r
 import java.io.IOException;\r
-\r
-\r
 import org.openecomp.mso.bpmn.core.domain.AllottedResource;\r
 import org.openecomp.mso.bpmn.core.domain.NetworkResource;\r
 import org.openecomp.mso.bpmn.core.domain.ServiceDecomposition;\r
+import org.openecomp.mso.bpmn.core.domain.ServiceInstance;\r
 import org.openecomp.mso.bpmn.core.domain.VnfResource;\r
 \r
-import com.fasterxml.jackson.core.JsonParseException;\r
-import com.fasterxml.jackson.databind.DeserializationFeature;\r
-import com.fasterxml.jackson.databind.JsonMappingException;\r
-import com.fasterxml.jackson.databind.ObjectMapper;\r
+public class DecomposeJsonUtil {\r
 \r
-import org.openecomp.mso.logger.MsoLogger;\r
+    private static final ObjectMapper OBJECT_MAPPER = createObjectMapper();\r
 \r
-public class DecomposeJsonUtil implements Serializable {\r
-       private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);\r
-       /**\r
-        * \r
-        */\r
-       private static final long serialVersionUID = 1L;\r
+    private DecomposeJsonUtil() {\r
+    }\r
 \r
-       /**\r
-        * Method to construct Service Decomposition object converting\r
-        * JSON structure\r
-        * \r
-        * @param jsonString - input in JSON format confirming ServiceDecomposition\r
-        * @return - ServiceDecomposition object\r
-        * @throws IOException \r
-        * @throws JsonMappingException \r
-        * @throws JsonParseException \r
-        */\r
-       public static ServiceDecomposition JsonToServiceDecomposition(String jsonString) {\r
-        \r
-        ServiceDecomposition serviceDecomposition = new ServiceDecomposition();\r
-        ObjectMapper om = new ObjectMapper();\r
-        om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);\r
-       \r
-               try {\r
-                       serviceDecomposition = om.readValue(jsonString, ServiceDecomposition.class);\r
-               } catch (JsonParseException e) {\r
-                       LOGGER.debug("JsonParseException :",e);\r
-               } catch (JsonMappingException e) {\r
-                       LOGGER.debug("JsonMappingException :",e);\r
-               } catch (IOException e) {\r
-                       LOGGER.debug("IOException :",e);\r
-               }\r
-               \r
-               return serviceDecomposition;\r
-       }\r
-       \r
-       /**\r
-        * Method to construct Resource Decomposition object converting\r
-        * JSON structure\r
-        * \r
-        * @param jsonString - input in JSON format confirming ResourceDecomposition\r
-        * @return - ServiceDecomposition object\r
-        * @throws IOException \r
-        * @throws JsonMappingException \r
-        * @throws JsonParseException \r
-        */\r
-       public static VnfResource JsonToVnfResource(String jsonString) {\r
-        \r
-        VnfResource vnfResource = new VnfResource();\r
+    private static ObjectMapper createObjectMapper() {\r
         ObjectMapper om = new ObjectMapper();\r
         om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);\r
-       \r
-               try {\r
-                       vnfResource = om.readValue(jsonString, VnfResource.class);\r
-               } catch (JsonParseException e) {\r
-                       LOGGER.debug("JsonParseException :",e);\r
-               } catch (JsonMappingException e) {\r
-                       LOGGER.debug("JsonMappingException :",e);\r
-               } catch (IOException e) {\r
-                       LOGGER.debug("IOException :",e);\r
-               }\r
-               return vnfResource;\r
-       }\r
-       \r
-       /**\r
-        * Method to construct Resource Decomposition object converting\r
-        * JSON structure\r
-        * \r
-        * @param jsonString - input in JSON format confirming ResourceDecomposition\r
-        * @return - ServiceDecomposition object\r
-        * @throws IOException \r
-        * @throws JsonMappingException \r
-        * @throws JsonParseException \r
-        */\r
-       public static NetworkResource JsonToNetworkResource(String jsonString) {\r
-        \r
-        NetworkResource networkResource = new NetworkResource();\r
-        ObjectMapper om = new ObjectMapper();\r
-        om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);\r
-       \r
-               try {\r
-                       networkResource = om.readValue(jsonString, NetworkResource.class);\r
-               } catch (JsonParseException e) {\r
-                       LOGGER.debug("Exception :",e);\r
-               } catch (JsonMappingException e) {\r
-                       LOGGER.debug("Exception :",e);\r
-               } catch (IOException e) {\r
-                       LOGGER.debug("Exception :",e);\r
-               }\r
-               return networkResource;\r
-       }\r
-       \r
-       /**\r
-        * Method to construct Resource Decomposition object converting\r
-        * JSON structure\r
-        * \r
-        * @param jsonString - input in JSON format confirming ResourceDecomposition\r
-        * @return - ServiceDecomposition object\r
-        * @throws IOException \r
-        * @throws JsonMappingException \r
-        * @throws JsonParseException \r
-        */\r
-       public static AllottedResource JsonToAllottedResource(String jsonString) {\r
-        \r
-               AllottedResource allottedResource = new AllottedResource();\r
-        ObjectMapper om = new ObjectMapper();\r
-        om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);\r
-       \r
-               try {\r
-                       allottedResource = om.readValue(jsonString, AllottedResource.class);\r
-               } catch (JsonParseException e) {\r
-                       LOGGER.debug("Exception :",e);\r
-               } catch (JsonMappingException e) {\r
-                       LOGGER.debug("Exception :",e);\r
-               } catch (IOException e) {\r
-                       LOGGER.debug("Exception :",e);\r
-               }\r
-               return allottedResource;\r
-       }\r
+        return om;\r
+    }\r
+\r
+    /**\r
+     * Method to construct Service Decomposition object converting JSON structure\r
+     *\r
+     * @param jsonString input in JSON format confirming ServiceDecomposition\r
+     * @return decoded object\r
+     * @throws JsonDecomposingException thrown when decoding json fails\r
+     */\r
+    public static ServiceDecomposition jsonToServiceDecomposition(String jsonString) throws JsonDecomposingException {\r
+        try {\r
+            return OBJECT_MAPPER.readValue(jsonString, ServiceDecomposition.class);\r
+        } catch (IOException e) {\r
+            throw new JsonDecomposingException("Exception while converting json to service decomposition", e);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Method to construct Service Decomposition object converting JSON structure\r
+     *\r
+     * @param jsonString input in JSON format confirming ServiceDecomposition\r
+     * @param serviceInstanceId service instance id to be put in decoded ServiceDecomposition\r
+     * @return decoded object\r
+     * @throws JsonDecomposingException thrown when decoding json fails\r
+     */\r
+    public static ServiceDecomposition jsonToServiceDecomposition(String jsonString, String serviceInstanceId)\r
+            throws JsonDecomposingException {\r
+        ServiceDecomposition serviceDecomposition = jsonToServiceDecomposition(jsonString);\r
+        ServiceInstance serviceInstance = new ServiceInstance();\r
+        serviceInstance.setInstanceId(serviceInstanceId);\r
+        serviceDecomposition.setServiceInstance(serviceInstance);\r
+        return serviceDecomposition;\r
+    }\r
+\r
+    /**\r
+     * Method to construct Resource Decomposition object converting JSON structure\r
+     *\r
+     * @param jsonString input in JSON format confirming ResourceDecomposition\r
+     * @return decoded object\r
+     * @throws JsonDecomposingException thrown when decoding json fails\r
+     */\r
+    public static VnfResource jsonToVnfResource(String jsonString) throws JsonDecomposingException {\r
+        try {\r
+            return OBJECT_MAPPER.readValue(jsonString, VnfResource.class);\r
+        } catch (IOException e) {\r
+            throw new JsonDecomposingException("Exception while converting json to vnf resource", e);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Method to construct Resource Decomposition object converting JSON structure\r
+     *\r
+     * @param jsonString input in JSON format confirming ResourceDecomposition\r
+     * @return decoded object\r
+     * @throws JsonDecomposingException thrown when decoding json fails\r
+     */\r
+    public static NetworkResource jsonToNetworkResource(String jsonString) throws JsonDecomposingException {\r
+        try {\r
+            return OBJECT_MAPPER.readValue(jsonString, NetworkResource.class);\r
+        } catch (IOException e) {\r
+            throw new JsonDecomposingException("Exception while converting json to network resource", e);\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Method to construct Resource Decomposition object converting JSON structure\r
+     *\r
+     * @param jsonString - input in JSON format confirming ResourceDecomposition\r
+     * @return decoded object\r
+     * @throws JsonDecomposingException thrown when decoding json fails\r
+     */\r
+    public static AllottedResource jsonToAllottedResource(String jsonString) throws JsonDecomposingException {\r
+        try {\r
+            return OBJECT_MAPPER.readValue(jsonString, AllottedResource.class);\r
+        } catch (IOException e) {\r
+            throw new JsonDecomposingException("Exception while converting json to allotted resource", e);\r
+        }\r
+    }\r
 }
\ No newline at end of file
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonDecomposingException.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonDecomposingException.java
new file mode 100644 (file)
index 0000000..352979e
--- /dev/null
@@ -0,0 +1,30 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.mso.bpmn.core.json;
+
+import java.io.IOException;
+
+public class JsonDecomposingException extends IOException {
+
+    public JsonDecomposingException(String message, Throwable cause) {
+        super(message, cause);
+    }
+}
index 71ed0ea..c346308 100644 (file)
@@ -323,6 +323,7 @@ public class LoggingAndURNMappingPlugin extends AbstractProcessEnginePlugin {
                private void loadFromDB(DelegateExecution execution, ProcessEngineConfigurationImpl processEngineConfiguration) {
                        Command<List<URNMapping>> command = new Command<List<URNMapping>>() {
                                @SuppressWarnings("unchecked")
+                               @Override
                                public List<URNMapping> execute(CommandContext commandContext) {
                                        return (List<URNMapping>) commandContext.getDbSqlSession().selectList(
                                                "mso.urnMapping.selectAll", null);
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/RollbackDataTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/RollbackDataTest.java
new file mode 100644 (file)
index 0000000..c51af23
--- /dev/null
@@ -0,0 +1,85 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.mso.bpmn.core;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.entry;
+
+import org.junit.Test;
+
+public class RollbackDataTest {
+
+    private final static String TYPE_A = "typeA";
+    private final static String TYPE_B = "typeB";
+    private static final String KEY_1 = "key1";
+    private static final String VALUE_1 = "value1";
+    private static final String VALUE_2 = "value2";
+
+    @Test
+    public void shouldReturnStringRepresentationOfDataInAnyPermutation() throws Exception {
+        // given
+        RollbackData data = new RollbackData();
+        data.put(TYPE_A, KEY_1, VALUE_1);
+        data.put(TYPE_A, "key2", "value2");
+        data.put(TYPE_B, "key3", "value3");
+        // when, then
+        assertThat(data.toString()).isIn(
+                "[typeB{key3=value3},typeA{key1=value1, key2=value2}]",
+                "[typeB{key3=value3},typeA{key2=value2, key1=value1}]",
+                "[typeA{key1=value1, key2=value2},typeB{key3=value3}]",
+                "[typeA{key2=value2, key1=value1},typeB{key3=value3}]");
+    }
+
+    @Test
+    public void shouldBeEmptyOnCreation() throws Exception {
+        // given
+        RollbackData data = new RollbackData();
+        // then
+        assertThat(data.hasType(TYPE_A)).isFalse();
+        assertThat(data.get(TYPE_A, KEY_1)).isNull();
+    }
+
+    @Test
+    public void shouldHaveTypeAfterPuttingDataOfThatType() throws Exception {
+        // given
+        RollbackData data = new RollbackData();
+        // when
+        data.put(TYPE_A, KEY_1, VALUE_1);
+        // then
+        assertThat(data.hasType(TYPE_A)).isTrue();
+        assertThat(data.hasType(TYPE_B)).isFalse();
+        assertThat(data.get(TYPE_A, KEY_1)).isEqualTo(VALUE_1);
+    }
+
+    @Test
+    public void shouldKeepTwoValuesWithSameKeysButDifferentTypes() throws Exception {
+        // given
+        RollbackData data = new RollbackData();
+        // when
+        data.put(TYPE_A, KEY_1, VALUE_1);
+        data.put(TYPE_B, KEY_1, VALUE_2);
+        // then
+        assertThat(data.get(TYPE_A, KEY_1)).isEqualTo(VALUE_1);
+        assertThat(data.get(TYPE_A)).containsExactly(entry(KEY_1, VALUE_1));
+        assertThat(data.get(TYPE_B, KEY_1)).isEqualTo(VALUE_2);
+        assertThat(data.get(TYPE_B)).containsExactly(entry(KEY_1, VALUE_2));
+    }
+}
\ No newline at end of file
index 908fcce..a722409 100644 (file)
@@ -1,7 +1,7 @@
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">\r
        <parent>\r
-               <groupId>org.openecomp.so</groupId>\r
+               <groupId>org.onap.so</groupId>\r
                <artifactId>bpmn</artifactId>\r
                <version>1.2.0-SNAPSHOT</version>\r
        </parent>\r
                        <version>3.4</version>\r
                </dependency>\r
                <dependency>\r
-                       <groupId>org.openecomp.so</groupId>\r
+                       <groupId>org.onap.so</groupId>\r
                        <artifactId>MSOCoreBPMN</artifactId>\r
                        <version>${project.version}</version>\r
                </dependency>\r
                <dependency>\r
-                       <groupId>org.openecomp.so</groupId>\r
+                       <groupId>org.onap.so</groupId>\r
                        <artifactId>MSOCommonBPMN</artifactId>\r
                        <version>${project.version}</version>\r
                </dependency>\r
                <dependency>\r
-                       <groupId>org.openecomp.so</groupId>\r
+                       <groupId>org.onap.so</groupId>\r
                        <artifactId>MSOCommonBPMN</artifactId>\r
                        <version>${project.version}</version>\r
                        <classifier>tests</classifier>\r
                </dependency>\r
                <dependency>\r
                        <!-- unit test utilities -->\r
-                       <groupId>org.openecomp.so</groupId>\r
+                       <groupId>org.onap.so</groupId>\r
                        <artifactId>MSOCoreBPMN</artifactId>\r
                        <version>${project.version}</version>\r
                        <classifier>tests</classifier>\r
        <version>4.3.2.RELEASE</version>\r
        </dependency>\r
        <dependency>\r
-         <groupId>org.openecomp.so</groupId>\r
+         <groupId>org.onap.so</groupId>\r
          <artifactId>MSORESTClient</artifactId>\r
          <version>${project.version}</version>\r
        </dependency>\r
 \r
                <!--for yang tools-->\r
 <!--           <dependency>\r
-                       <groupId>org.openecomp.so</groupId>\r
+                       <groupId>org.onap.so</groupId>\r
                        <artifactId>common</artifactId>\r
                        <version>1.2.0-SNAPSHOT</version>\r
                </dependency>\r
index 862c46a..3088340 100644 (file)
@@ -54,7 +54,6 @@ class DoCreateVnfAndModules extends AbstractServiceTaskProcessor {
    JsonUtils jsonUtil = new JsonUtils()
    VidUtils vidUtils = new VidUtils(this)
    CatalogDbUtils cutils = new CatalogDbUtils()
-   DecomposeJsonUtil decomposeJsonUtil = new DecomposeJsonUtil()
 
    /**
        * This method gets and validates the incoming
@@ -185,7 +184,7 @@ class DoCreateVnfAndModules extends AbstractServiceTaskProcessor {
                           utils.log("DEBUG", "obtained VNF list")
                           // Only one match here
                           JSONObject vnfObject = vnfs[0]
-                          vnf = decomposeJsonUtil.JsonToVnfResource(vnfObject.toString())                         
+                          vnf = DecomposeJsonUtil.jsonToVnfResource(vnfObject.toString())
                   }
                   utils.log("DEBUG", "Read vnfResource", isDebugLogEnabled)
                   if (vnf == null) {
index 823223f..dfa390c 100644 (file)
@@ -115,14 +115,11 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
 
     protected String httpPost(String url, HttpPost httpPost) throws RouteException {
         logger.info("AbstractSdncOperationTask.httpPost begin!");
-        CloseableHttpClient httpClient = HttpClients.createDefault();
         String result = null;
-        boolean var15 = false;
 
         String errorMsg;
         label91: {
-            try {
-                var15 = true;
+            try(CloseableHttpClient httpClient = HttpClients.createDefault()) {
                 CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost);
                 result = EntityUtils.toString(closeableHttpResponse.getEntity());
                 logger.info("result = {}", result);
@@ -133,42 +130,14 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
                 }
 
                 closeableHttpResponse.close();
-                var15 = false;
                 break label91;
-            } catch (IOException var19) {
+            } catch (IOException e) {
                 errorMsg = url + ":httpPostWithJSON connect faild";
                 logger.info("exception: POST_CONNECT_FAILD : {}", errorMsg);
-                throwsRouteException(errorMsg, var19, "POST_CONNECT_FAILD");
-                var15 = false;
-            } finally {
-                if(var15) {
-                    try {
-                        httpClient.close();
-                    } catch (IOException var16) {
-                        String errorMsg1 = url + ":close  httpClient faild";
-                        logger.info("exception: CLOSE_CONNECT_FAILD : {}", errorMsg1);
-                        throwsRouteException(errorMsg1, var16, "CLOSE_CONNECT_FAILD");
-                    }
-
-                }
-            }
-
-            try {
-                httpClient.close();
-            } catch (IOException var17) {
-                errorMsg = url + ":close  httpClient faild";
-                logger.info("exception: CLOSE_CONNECT_FAILD : {}", errorMsg);
-                throwsRouteException(errorMsg, var17, "CLOSE_CONNECT_FAILD");
+                throwsRouteException(errorMsg, e, "POST_CONNECT_FAILD");
             }
         }
 
-        try {
-            httpClient.close();
-        } catch (IOException var18) {
-            errorMsg = url + ":close  httpClient faild";
-            logger.info("exception: CLOSE_CONNECT_FAILD : {}", errorMsg);
-            throwsRouteException(errorMsg, var18, "CLOSE_CONNECT_FAILD");
-        }
         logger.info("AbstractSdncOperationTask.httpPost end!");
         return result;
     }
@@ -223,78 +192,27 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
 
     private String httpGet(String url, HttpGet httpGet) throws RouteException {
         logger.info("AbstractSdncOperationTask.httpGet begin!");
-        boolean var16 = false;
-        CloseableHttpClient httpClient = HttpClients.createDefault();
         String result = "";
         String errorMsg;
-        label109:
-        {
-            label110:
-            {
-                try {
-                    var16 = true;
-                    CloseableHttpResponse e = httpClient.execute(httpGet);
-                    result = EntityUtils.toString(e.getEntity());
-                    logger.info("result = {}", result);
-                    if (e.getStatusLine().getStatusCode() != 200) {
-                        logger.info("exception: fail for status code = {}", e.getStatusLine().getStatusCode());
+        try(CloseableHttpClient httpClient = HttpClients.createDefault()) {
+                   CloseableHttpResponse e = httpClient.execute(httpGet);
+                   result = EntityUtils.toString(e.getEntity());
+                   logger.info("result = {}", result);
+               if (e.getStatusLine().getStatusCode() != 200) {
+                       logger.info("exception: fail for status code = {}", e.getStatusLine().getStatusCode());
                         throw new RouteException(result, "SERVICE_GET_ERR");
                     }
-
                     e.close();
-                    var16 = false;
-                    break label110;
-                } catch (ClientProtocolException var21) {
-                    errorMsg = url + ":httpGetWithJSON connect faild";
-                    logger.info("exception: GET_CONNECT_FAILD {}", errorMsg);
-                    throwsRouteException(errorMsg, var21, "GET_CONNECT_FAILD");
-                    var16 = false;
-                } catch (IOException var22) {
-                    errorMsg = url + ":httpGetWithJSON connect faild";
-                    logger.info("exception: GET_CONNECT_FAILD {}", errorMsg);
-                    throwsRouteException(errorMsg, var22, "GET_CONNECT_FAILD");
-                    var16 = false;
-                    break label109;
-                } finally {
-                    if (var16) {
-                        try {
-                            httpClient.close();
-                        } catch (IOException var17) {
-                            String errorMsg1 = url + ":close  httpClient faild";
-                            logger.info("exception: CLOSE_CONNECT_FAILD {}", errorMsg1);
-                            throwsRouteException(errorMsg1, var17, "CLOSE_CONNECT_FAILD");
-                        }
-
-                    }
-                }
+           } catch (ClientProtocolException e) {
+                   errorMsg = url + ":httpGetWithJSON connect faild";
+                   logger.info("exception: GET_CONNECT_FAILD {}", errorMsg);
+                   throwsRouteException(errorMsg, e, "GET_CONNECT_FAILD");
+           } catch (IOException e) {
+                   errorMsg = url + ":httpGetWithJSON connect faild";
+                   logger.info("exception: GET_CONNECT_FAILD {}", errorMsg);
+                   throwsRouteException(errorMsg, e, "GET_CONNECT_FAILD");
+           }
 
-                try {
-                    httpClient.close();
-                } catch (IOException var19) {
-                    errorMsg = url + ":close  httpClient faild";
-                    logger.info("exception: CLOSE_CONNECT_FAILD {}", errorMsg);
-                    throwsRouteException(errorMsg, var19, "CLOSE_CONNECT_FAILD");
-                }
-
-            }
-
-            try {
-                httpClient.close();
-            } catch (IOException var20) {
-                errorMsg = url + ":close  httpClient faild";
-                logger.info("exception: CLOSE_CONNECT_FAILD {}", errorMsg);
-                throwsRouteException(errorMsg, var20, "CLOSE_CONNECT_FAILD");
-            }
-
-        }
-
-        try {
-            httpClient.close();
-        } catch (IOException var18) {
-            errorMsg = url + ":close  httpClient faild";
-            logger.info("exception: CLOSE_CONNECT_FAILD {}", errorMsg);
-            throwsRouteException(errorMsg, var18, "CLOSE_CONNECT_FAILD");
-        }
         logger.info("AbstractSdncOperationTask.httpGet end!");
         return result;
     }
index 698f0c5..60bc83b 100644 (file)
@@ -77,7 +77,7 @@ public class SdncNetworkTopologyOperationTask extends AbstractSdncOperationTask
         httpPost.addHeader("Authorization", defaulAuth);
         httpPost.addHeader("Content-type", "application/json");
         String postBody = getPostbody(inputEntity);
-        LOGGER.info(MessageEnum.RA_SEND_REQUEST_SDNC, postBody.toString(), "SDNC", "");
+        LOGGER.info(MessageEnum.RA_SEND_REQUEST_SDNC, postBody, "SDNC", "");
         httpPost.setEntity(new StringEntity(postBody, ContentType.APPLICATION_XML));
         httpPost(url, httpPost);
         logger.info("SdncNetworkTopologyOperationTask.Send2SdncDirectly end!");
index 89d0958..6028944 100644 (file)
@@ -77,7 +77,7 @@ public class SdncServiceTopologyOperationTask extends AbstractSdncOperationTask
         httpPost.addHeader("Authorization", defaulAuth);
         httpPost.addHeader("Content-type", "application/json");
         String postBody = getPostbody(inputEntity);
-        LOGGER.info(MessageEnum.RA_SEND_REQUEST_SDNC, postBody.toString(), "SDNC", "");
+        LOGGER.info(MessageEnum.RA_SEND_REQUEST_SDNC, postBody, "SDNC", "");
         httpPost.setEntity(new StringEntity(postBody, ContentType.APPLICATION_XML));
         httpPost(url, httpPost);
         logger.info("SdncServiceTopologyOperationTask.Send2SdncDirectly end!");
index 21c0091..571db76 100644 (file)
@@ -79,8 +79,8 @@ public class CreateGenericALaCarteServiceInstanceTest extends WorkflowTest {
                MockGetCustomer("MCBH-1610", "CreateServiceInstance/createServiceInstance_queryGlobalCustomerId_AAIResponse_Success.xml");
                MockPutServiceInstance("MCBH-1610", "viprsvc", "RaaTest-1-id", "");
                MockGetServiceInstance("MCBH-1610", "viprsvc", "RaaTest-1-id", "GenericFlows/getServiceInstance.xml");
-               MockNodeQueryServiceInstanceByName("RAATest-1", "");
-               MockNodeQueryServiceInstanceById("RaaTest-1-id", "");
+               MockNodeQueryServiceInstanceByName("RAATest-1", null);
+               MockNodeQueryServiceInstanceById("RaaTest-1-id", null);
                //SDNC
                mockSDNCAdapter(200);
                //DB
index c17015c..5d89e29 100644 (file)
@@ -4,12 +4,12 @@
        <modelVersion>4.0.0</modelVersion>\r
        \r
        <parent>\r
-               <groupId>org.openecomp.so</groupId>\r
+               <groupId>org.onap.so</groupId>\r
         <artifactId>bpmn</artifactId>\r
                <version>1.2.0-SNAPSHOT</version>\r
        </parent>\r
        \r
-       <groupId>org.openecomp.so</groupId>\r
+       <groupId>org.onap.so</groupId>\r
        <artifactId>MSORESTClient</artifactId>\r
        \r
        <packaging>jar</packaging>\r
@@ -31,7 +31,7 @@
                </dependency>\r
 \r
                <dependency>\r
-            <groupId>org.openecomp.so</groupId>\r
+            <groupId>org.onap.so</groupId>\r
             <artifactId>common</artifactId>\r
             <version>${project.version}</version>\r
         </dependency>\r
index 79acccb..d36d4c7 100644 (file)
@@ -4,12 +4,12 @@
   <modelVersion>4.0.0</modelVersion>
 
   <parent>
-    <groupId>org.openecomp.so</groupId>
+    <groupId>org.onap.so</groupId>
     <artifactId>so</artifactId>
     <version>1.2.0-SNAPSHOT</version>
   </parent>
 
-  <groupId>org.openecomp.so</groupId>
+  <groupId>org.onap.so</groupId>
   <artifactId>bpmn</artifactId>
   <name>BPMN Subsystem</name>
   <description>BPMN Subsystem for MSO</description>
index 6a304c2..48518ae 100644 (file)
@@ -2,12 +2,12 @@
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <parent>
-        <groupId>org.openecomp.so</groupId>
+        <groupId>org.onap.so</groupId>
         <artifactId>so</artifactId>
         <version>1.2.0-SNAPSHOT</version>
     </parent>
 
-    <groupId>org.openecomp.so</groupId>
+    <groupId>org.onap.so</groupId>
     <artifactId>common</artifactId>
     <name>MSO Common classes</name>
     <description>MSO Common classes:- Logger</description>
                        </executions>
                        <dependencies>
                                <dependency>
-                                       <groupId>org.openecomp.so</groupId>
+                                       <groupId>org.onap.so</groupId>
                                        <artifactId>common</artifactId>
                                        <version>${project.version}</version>
                                </dependency>
index 86aedc1..b8c4aed 100644 (file)
@@ -144,15 +144,16 @@ public class MsoLogger {
     // For internal logging of the initialization of MSO logs
     private static final Logger LOGGER      = Logger.getLogger(MsoLogger.class.getName());
 
-    private MsoLogger(MsoLogger.Catalog cat) {
-        this.logger = EELFManager.getInstance().getErrorLogger();
-        this.auditLogger = EELFManager.getInstance().getAuditLogger();
-        this.metricsLogger = EELFManager.getInstance().getMetricsLogger();
-        MsoLogger.initialization();
-        setDefaultLogCatalog(cat);
-    }
 
-    private static synchronized void initialization() {
+    // Since four adaptors are using the instance of  MsoLogger which will be referenced everywhere
+    // hence limiting the number of MsoLogger instances to five.
+    private static final MsoLogger generalMsoLogger = new MsoLogger(Catalog.GENERAL);
+    private static final MsoLogger apihLogger = new MsoLogger(Catalog.APIH);
+    private static final MsoLogger asdcLogger = new MsoLogger(Catalog.ASDC);
+    private static final MsoLogger raLogger = new MsoLogger(Catalog.RA);
+    private static final MsoLogger bpelLogger = new MsoLogger(Catalog.BPEL);
+
+    static {
         if (instanceUUID == null || ("").equals(instanceUUID)) {
             instanceUUID = getInstanceUUID();
         }
@@ -170,15 +171,40 @@ public class MsoLogger {
         }
     }
 
+    // Singleton instances of the EELFLogger of all types are referenced by MsoLogger
+    private MsoLogger(Catalog cat) {
+        this.logger = EELFManager.getInstance().getErrorLogger();
+        this.auditLogger = EELFManager.getInstance().getAuditLogger();
+        this.metricsLogger = EELFManager.getInstance().getMetricsLogger();
+        this.setDefaultLogCatalog(cat);
+    }
+
+
+
     /**
      * Get the MsoLogger based on the catalog
-     * 
+     * This method is fixed now to resolve the total number of objects that are getting created
+     * everytime this function gets called. Its supposed to have fixed number of instance per java process.
+     *
      * @param cat
      *            Catalog of the logger
      * @return the MsoLogger
      */
     public static synchronized MsoLogger getMsoLogger(MsoLogger.Catalog cat) {
-        return new MsoLogger(cat);
+        switch (cat) {
+            case GENERAL:
+                return generalMsoLogger;
+            case APIH:
+                return apihLogger;
+            case RA:
+                return raLogger;
+            case BPEL:
+                return bpelLogger;
+            case ASDC:
+                return asdcLogger;
+            default:
+                return generalMsoLogger;
+        }
     }
 
     /**
index 54b01a5..7b559df 100644 (file)
@@ -153,7 +153,7 @@ public class MsoPropertiesFactoryTest {
                
                assertFalse(msoPropChanged.equals(null));
                assertFalse(msoPropChanged.equals(msoPropCache));
-               assertFalse(msoPropChanged.equals(new Boolean(true)));
+               assertFalse(msoPropChanged.equals(Boolean.TRUE));
                
                assertTrue(msoPropChanged.equals(msoPropChanged));
        }
index eaab61c..8eab5d6 100644 (file)
@@ -3,13 +3,13 @@
        <modelVersion>4.0.0</modelVersion>
 
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>mso-api-handlers</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
 
 
-       <groupId>org.openecomp.so</groupId>
+       <groupId>org.onap.so</groupId>
        <artifactId>mso-api-handler-common</artifactId>
 
        <name>ECOMP MSO API Handler common</name>
                </dependency>
 
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>mso-catalog-db</artifactId>
                        <version>${project.version}</version>
                </dependency>
 
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>mso-requests-db</artifactId>
                        <version>${project.version}</version>
                </dependency>
index c8889be..b9c0725 100644 (file)
@@ -36,6 +36,7 @@ import java.io.IOException;
 
 public class CamundaClient extends RequestClient{
        private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH);
+       private static final String CAMUNDA_URL_MESAGE = "Camunda url is: ";
 
        public CamundaClient() {
                super(CommonConstants.CAMUNDA);
@@ -47,13 +48,13 @@ public class CamundaClient extends RequestClient{
                        String requestTimeout, String schemaVersion, String serviceInstanceId, String action)
                                        throws ClientProtocolException, IOException{
                HttpPost post = new HttpPost(url);
-               msoLogger.debug("Camunda url is: "+ url);
+               msoLogger.debug(CAMUNDA_URL_MESAGE + url);
                String jsonReq = wrapRequest(camundaReqXML, requestId, serviceInstanceId, requestTimeout,  schemaVersion);
 
                StringEntity input = new StringEntity(jsonReq);
                input.setContentType(CommonConstants.CONTENT_TYPE_JSON);
 
-               String encryptedCredentials = null;
+               String encryptedCredentials;
                if(props!=null){
                        encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH,null);
                        if(encryptedCredentials != null){
@@ -65,22 +66,18 @@ public class CamundaClient extends RequestClient{
                }
 
                post.setEntity(input);
-               HttpResponse response = client.execute(post);
-
-               return response;
+        return client.execute(post);
        }
 
        @Override
-       public HttpResponse post(String jsonReq)
-                                       throws ClientProtocolException, IOException{
+       public HttpResponse post(String jsonReq) throws ClientProtocolException, IOException{
                HttpPost post = new HttpPost(url);
-               msoLogger.debug("Camunda url is: "+ url);
-               //String jsonReq = wrapRequest(camundaReqXML, requestId, serviceInstanceId, requestTimeout,  schemaVersion);
+               msoLogger.debug(CAMUNDA_URL_MESAGE + url);
 
                StringEntity input = new StringEntity(jsonReq);
                input.setContentType(CommonConstants.CONTENT_TYPE_JSON);
 
-               String encryptedCredentials = null;
+               String encryptedCredentials;
                if(props!=null){
                        encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH,null);
                        if(encryptedCredentials != null){
@@ -92,9 +89,8 @@ public class CamundaClient extends RequestClient{
                }
 
                post.setEntity(input);
-               HttpResponse response = client.execute(post);
 
-               return response;
+        return client.execute(post);
        }
 
        @Override
@@ -105,7 +101,7 @@ public class CamundaClient extends RequestClient{
                        String requestDetails)
                                        throws ClientProtocolException, IOException{
                HttpPost post = new HttpPost(url);
-               msoLogger.debug("Camunda url is: "+ url);
+               msoLogger.debug(CAMUNDA_URL_MESAGE + url);
                String jsonReq = wrapVIDRequest(requestId, isBaseVfModule, recipeTimeout, requestAction,
                                serviceInstanceId, vnfId, vfModuleId, volumeGroupId, networkId,
                                serviceType, vnfType, vfModuleType, networkType, requestDetails);
@@ -113,7 +109,7 @@ public class CamundaClient extends RequestClient{
                StringEntity input = new StringEntity(jsonReq);
                input.setContentType(CommonConstants.CONTENT_TYPE_JSON);
 
-               String encryptedCredentials = null;
+               String encryptedCredentials;
                if(props!=null){
                        encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH,null);
                        if(encryptedCredentials != null){
@@ -125,9 +121,8 @@ public class CamundaClient extends RequestClient{
                }
 
                post.setEntity(input);
-               HttpResponse response = client.execute(post);
 
-               return response;
+        return client.execute(post);
        }
        
        @Override
index b4e7b7e..64193cf 100644 (file)
 \r
 package org.openecomp.mso.apihandler.common;\r
 \r
-import org.openecomp.mso.logger.MessageEnum;\r
 import org.openecomp.mso.logger.MsoLogger;\r
 import org.apache.http.HttpResponse;\r
 import org.apache.http.client.ClientProtocolException;\r
 import org.apache.http.client.methods.HttpGet;\r
 import org.apache.http.client.methods.HttpPost;\r
 import org.apache.http.entity.StringEntity;\r
-import org.codehaus.jackson.map.ObjectMapper;\r
-import org.codehaus.jackson.map.SerializationConfig;\r
 \r
 import javax.xml.bind.DatatypeConverter;\r
-import java.io.BufferedReader;\r
-import java.io.InputStreamReader;\r
 import java.io.IOException;\r
 \r
 public class CamundaTaskClient extends RequestClient{\r
@@ -63,9 +58,7 @@ public class CamundaTaskClient extends RequestClient{
                }\r
 \r
                post.setEntity(input);\r
-               HttpResponse response = client.execute(post);\r
-\r
-               return response;\r
+               return client.execute(post);\r
        }\r
        \r
        @Override\r
@@ -88,8 +81,7 @@ public class CamundaTaskClient extends RequestClient{
        }\r
        \r
        @Override\r
-       public HttpResponse get()\r
-                       throws ClientProtocolException, IOException{\r
+       public HttpResponse get() throws ClientProtocolException, IOException{\r
                HttpGet get = new HttpGet(url);\r
                msoLogger.debug("Camunda Task url is: "+ url);  \r
                String encryptedCredentials;\r
@@ -103,12 +95,7 @@ public class CamundaTaskClient extends RequestClient{
                        }\r
                }\r
                \r
-               HttpResponse getResponse = client.execute(get); \r
-\r
-               return getResponse;\r
-}\r
-       \r
-       \r
-\r
+               return client.execute(get);\r
+       }\r
 \r
 }\r
index 72f72c2..2cafef3 100644 (file)
@@ -22,6 +22,9 @@ package org.openecomp.mso.apihandler.common;
  
 public final class ErrorNumbers {
 
+    private ErrorNumbers() {
+    }
+
     public static final String REQUEST_FAILED_SCHEMA_VALIDATION = "1000";
     public static final String RECIPE_DOES_NOT_EXIST = "1010";
     public static final String VFMODULE_TYPE_DOES_NOT_EXIST = "1011";
index 42d77f5..b39b534 100644 (file)
@@ -37,9 +37,6 @@ public class LSInputImpl implements LSInput {
     protected String fEncoding;
     protected boolean fCertifiedText;
 
-    public LSInputImpl () {
-    }
-
     @Override
     public InputStream getByteStream () {
         return fByteStream;
index 1324e12..addf4e1 100644 (file)
@@ -22,7 +22,6 @@ package org.openecomp.mso.apihandler.common;
 
 import java.io.IOException;
 import java.security.GeneralSecurityException;
-import java.util.Properties;
 
 import org.apache.http.HttpResponse;
 import org.apache.http.client.ClientProtocolException;
@@ -83,16 +82,11 @@ public abstract class RequestClient {
        
        protected String getEncryptedPropValue (String prop, String defaultValue, String encryptionKey) {
                 try {
-                        String result = CryptoUtils.decrypt(prop, encryptionKey);
-                        return result;
+                        return CryptoUtils.decrypt(prop, encryptionKey);
                 }      
                 catch (GeneralSecurityException e) {
                         msoLogger.debug("Security exception", e);
                 }
                 return defaultValue;
         }
-
-       
-
-
 }
index 773c5b0..8f91986 100644 (file)
 package org.openecomp.mso.apihandler.common;
 
 
-import java.util.Properties;
-
 import org.apache.http.impl.client.DefaultHttpClient;
 
 import org.openecomp.mso.properties.MsoJavaProperties;
 
 public class RequestClientFactory {
-       
+
+    private RequestClientFactory() {
+    }
+
        //based on URI, returns BPEL, CamundaTask or Camunda client
        public static RequestClient getRequestClient(String orchestrationURI, MsoJavaProperties props) throws IllegalStateException{
                RequestClient retClient;
index 6722a93..4e7cf4c 100644 (file)
@@ -41,6 +41,7 @@ public class ResponseHandler {
        private HttpResponse httpResponse;
        private int type;
        private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH);
+    private static final String RESPONSE_BODY_MSG = "response body is: ";
 
        public ResponseHandler(HttpResponse httpResponse, int type) {
                this.httpResponse = httpResponse;
@@ -84,7 +85,7 @@ public class ResponseHandler {
                        if(response!=null){
                                responseBody = response.getResponse();
                        }
-                       msoLogger.debug("response body is: " + responseBody);
+                       msoLogger.debug(RESPONSE_BODY_MSG + responseBody);
                        
                
                if(status!=HttpStatus.SC_ACCEPTED){
@@ -99,7 +100,7 @@ public class ResponseHandler {
                try {
                        if (bpelEntity!=null) {
                                responseBody = EntityUtils.toString(bpelEntity);
-                               msoLogger.debug("response body is: " + responseBody);
+                               msoLogger.debug(RESPONSE_BODY_MSG + responseBody);
 
                        }
                        if(status!=HttpStatus.SC_ACCEPTED){
@@ -118,7 +119,7 @@ public class ResponseHandler {
                try {
                        if (camundataskEntity!=null) {
                                responseBody = EntityUtils.toString(camundataskEntity);
-                               msoLogger.debug("response body is: " + responseBody);
+                               msoLogger.debug(RESPONSE_BODY_MSG + responseBody);
 
                        }
                        if(status!=HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_ACCEPTED){
index bf2088e..73bf020 100644 (file)
@@ -31,17 +31,18 @@ public class ValidationException extends Exception {
      **/
 
     private static final long serialVersionUID = 1L;
-    private static final String validationFailMessage = "No valid $ELEMENT is specified";
-    private static final String invalidElementMessage = "$ELEMENT is not valid in the $VERSION version";
+    private static final String VALIDATION_FAIL_MESSAGE = "No valid $ELEMENT is specified";
+    private static final String INVALID_ELEMENT_MESSAGE = "$ELEMENT is not valid in the $VERSION version";
+    private static final String ELEMENT_MESSAGE = "\\$ELEMENT";
 
     public ValidationException (String msg) {
-        super (validationFailMessage.replaceAll ("\\$ELEMENT", msg));
+        super (VALIDATION_FAIL_MESSAGE.replaceAll (ELEMENT_MESSAGE, msg));
     }
 
     public ValidationException (String msg, Exception cause) {
-        super (validationFailMessage.replaceAll ("\\$ELEMENT", msg), cause);
+        super (VALIDATION_FAIL_MESSAGE.replaceAll (ELEMENT_MESSAGE, msg), cause);
     }
     public ValidationException(String msg, String version) {
-        super(invalidElementMessage.replaceAll("\\$ELEMENT", msg).replaceAll("\\$VERSION", version));
+        super(INVALID_ELEMENT_MESSAGE.replaceAll(ELEMENT_MESSAGE, msg).replaceAll("\\$VERSION", version));
     }
 }
index b498259..ebb1dd2 100644 (file)
@@ -40,14 +40,14 @@ import org.openecomp.mso.logger.MsoLogger;
 
 public class XMLValidator {
 
-    private static String XSDS_PATH;
+    private static String xsdsPath;
 
     static {
         String prefixMsoPropertiesPath = System.getProperty ("mso.config.path");
         if (prefixMsoPropertiesPath == null) {
             prefixMsoPropertiesPath = "";
         }
-        XSDS_PATH = prefixMsoPropertiesPath + "xsds/";
+        xsdsPath = prefixMsoPropertiesPath + "xsds/";
     }
 
     private String stringXsd;
@@ -60,12 +60,12 @@ public class XMLValidator {
 
     public XMLValidator (String xsdFile) {
 
-        try (FileInputStream xsdStream = new FileInputStream (XSDS_PATH + xsdFile)) {
+        try (FileInputStream xsdStream = new FileInputStream (xsdsPath + xsdFile)) {
 
             stringXsd = IOUtils.toString (xsdStream);
 
             factory = SchemaFactory.newInstance (XMLConstants.W3C_XML_SCHEMA_NS_URI);
-            factory.setResourceResolver (new PathResourceResolver (XSDS_PATH));
+            factory.setResourceResolver (new PathResourceResolver (xsdsPath));
             factory.setFeature (XMLConstants.FEATURE_SECURE_PROCESSING, true);
 
             String quotedXsd = stringXsd.replaceAll ("&#34;", "\"");
@@ -73,7 +73,7 @@ public class XMLValidator {
             schema = factory.newSchema (src);
 
         } catch (IOException | SAXException e) {
-            msoLogger.debug ("Cannot open file " + XSDS_PATH + xsdFile, e);
+            msoLogger.debug ("Cannot open file " + xsdsPath + xsdFile, e);
             errorMsg = "ErrorDetails: xsd file " + xsdFile + "could not be opened - " + e.getMessage ();
         }
     }
index f152116..08ff9fe 100644 (file)
@@ -3,7 +3,7 @@
        <modelVersion>4.0.0</modelVersion>
 
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>mso-api-handlers</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
                        <version>${spring-version}</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>mso-catalog-db</artifactId>
                        <version>${project.version}</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>mso-requests-db</artifactId>
                        <version>${project.version}</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>mso-api-handler-common</artifactId>
                        <version>${project.version}</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>status-control</artifactId>
                        <version>${project.version}</version>
                </dependency>
index 2f32e80..d60915b 100644 (file)
@@ -160,7 +160,7 @@ public class OrchestrationRequests {
 
                        orchestrationList = new GetOrchestrationListResponse();
 
-                       List<RequestList> requestLists = new ArrayList<RequestList>();
+                       List<RequestList> requestLists = new ArrayList<>();
 
                        for (InfraActiveRequests infraActive : activeRequests) {
 
index a61ca5f..a55c13b 100644 (file)
@@ -711,12 +711,12 @@ public class VnfRequestHandler {
                 requestClient = RequestClientFactory.getRequestClient (orchestrationURI, props);
                 // Capture audit event
                 msoLogger.debug ("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl ());
-                response = requestClient.post (msoRequest.getRequestXML (),
-                        requestId,
-                        Integer.toString (recipe.getRecipeTimeout ()).toString (),
-                        version,
-                        null,
-                        null);
+                response = requestClient.post(msoRequest.getRequestXML(),
+                    requestId,
+                    Integer.toString(recipe.getRecipeTimeout()),
+                    version,
+                    null,
+                    null);
                 msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from BPMN engine", "BPMN", orchestrationURI, null);
             } catch (Exception e) {
                 msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN", orchestrationURI, null);
index 9a8bf35..2c1f506 100644 (file)
@@ -652,12 +652,12 @@ public class VolumeRequestHandler {
                 requestClient = RequestClientFactory.getRequestClient (orchestrationURI, props);
                 // Capture audit event
                 msoLogger.debug ("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl ());
-                response = requestClient.post (msoRequest.getRequestXML (),
-                        requestId,
-                        Integer.toString (recipe.getRecipeTimeout ()).toString (),
-                        version,
-                        null,
-                        null);
+                response = requestClient.post(msoRequest.getRequestXML(),
+                    requestId,
+                    Integer.toString(recipe.getRecipeTimeout()),
+                    version,
+                    null,
+                    null);
                 msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from BPMN engine", "BPMN", orchestrationURI, null);
             } catch (Exception e) {
                 msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN", orchestrationURI, null);
index 6a4941e..b14c87a 100644 (file)
@@ -3,7 +3,7 @@
        <modelVersion>4.0.0</modelVersion>
 
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>mso-api-handlers</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
                                </exclusion>
                        </exclusions>
                </dependency>
+               <dependency>
+                       <groupId>junit</groupId>
+                       <artifactId>junit</artifactId>
+                       <version>4.12</version>
+                       <scope>test</scope>
+               </dependency>
                <dependency>
                        <groupId>org.hibernate</groupId>
                        <artifactId>hibernate-entitymanager</artifactId>
                        <version>1.0.0.Final</version>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>common</artifactId>
                        <version>${project.version}</version>
                </dependency>
+               <dependency>
+                       <groupId>org.jmockit</groupId>
+                       <artifactId>jmockit</artifactId>
+                       <version>1.19</version>
+                       <scope>test</scope>
+               </dependency>
        </dependencies>
        <packaging>jar</packaging>
        <build>
diff --git a/mso-api-handlers/mso-requests-db/src/test/java/org/openecomp/mso/requestsdb/RequestsDatabaseTest.java b/mso-api-handlers/mso-requests-db/src/test/java/org/openecomp/mso/requestsdb/RequestsDatabaseTest.java
new file mode 100644 (file)
index 0000000..0bb126f
--- /dev/null
@@ -0,0 +1,283 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.mso.requestsdb;
+
+
+import mockit.Expectations;
+import mockit.Mocked;
+import mockit.integration.junit4.JMockit;
+import org.hibernate.Criteria;
+import org.hibernate.Query;
+import org.hibernate.SQLQuery;
+import org.hibernate.Session;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.mso.db.AbstractSessionFactoryManager;
+
+import java.util.Arrays;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+@RunWith(JMockit.class)
+public class RequestsDatabaseTest {
+
+    RequestsDatabase requestsDatabase = RequestsDatabase.getInstance();
+
+    @Test
+    public void getInstanceTest() throws Exception {
+        RequestsDatabase instance = RequestsDatabase.getInstance();
+        assertEquals(RequestsDatabase.class, instance.getClass());
+    }
+
+    @Test
+    public void healthCheckTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                @Mocked Session session,
+                                @Mocked SQLQuery query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            session.createSQLQuery(" show tables "); result = query;
+            query.list(); result = Arrays.asList("table1", "table2");
+        }};
+
+        assertTrue(requestsDatabase.healthCheck());
+    }
+
+    @Test
+    public void updateInfraStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                      @Mocked Session session,
+                                      @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            query.executeUpdate(); result = 1;
+        }};
+        assertEquals(1, requestsDatabase.updateInfraStatus("123", "unknown", "unknown"));
+    }
+
+    @Test
+    public void updateInfraStatus1Test(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                       @Mocked Session session,
+                                       @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            query.executeUpdate(); result = 1;
+        }};
+        assertEquals(1, requestsDatabase.updateInfraStatus("123", "unknown", 0, "unknown"));
+    }
+
+    @Test
+    public void updateInfraFinalStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                           @Mocked Session session,
+                                           @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            query.executeUpdate(); result = 1;
+        }};
+        assertEquals(1, requestsDatabase.updateInfraFinalStatus("123",
+                "unknown",
+                "statusMessage",
+                0,
+                "responsebody",
+                "lastmodifiedby"));
+    }
+
+    @Test
+    public void getRequestFromInfraActiveTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                              @Mocked Session session,
+                                              @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            query.uniqueResult(); result = new InfraActiveRequests("123", "action");
+        }};
+        assertEquals("123",
+                requestsDatabase.getRequestFromInfraActive("123").getRequestId());
+    }
+
+    @Test
+    public void getOrchestrationFiltersFromInfraActiveTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                                           @Mocked Session session,
+                                                           @Mocked Criteria criteria) throws Exception {
+
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            session.createCriteria(InfraActiveRequests.class); result = criteria;
+            criteria.list(); result = Arrays.asList(new InfraActiveRequests("123", "action"));
+        }};
+        assertEquals(1,
+                requestsDatabase.getRequestListFromInfraActive("queryattr",
+                        "queryvalue",
+                        "type").size());
+    }
+
+    @Test
+    public void getRequestListFromInfraActiveTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                                  @Mocked Session session,
+                                                  @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            session.createQuery("from InfraActiveRequests where (requestId = :requestId OR clientRequestId = :requestId) and requestType = :requestType"); result = query;
+            query.uniqueResult(); result = new InfraActiveRequests("123", "action");
+        }};
+        assertEquals("123",
+                requestsDatabase.getRequestFromInfraActive("123", "requestType").getRequestId());
+    }
+
+    @Test
+    public void getRequestFromInfraActive1Test(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                               @Mocked Session session,
+                                               @Mocked Criteria criteria) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            session.createCriteria(InfraActiveRequests.class); result = criteria;
+            criteria.list(); result = Arrays.asList(new InfraActiveRequests());
+        }};
+        assertEquals(1,
+                requestsDatabase.getRequestListFromInfraActive("queryAttr",
+                        "queryvalue",
+                        "type").size());
+    }
+
+    @Test
+    public void checkDuplicateByVnfNameTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                            @Mocked Session session,
+                                            @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            session.createQuery("from InfraActiveRequests where vnfName = :vnfName and action = :action and (requestStatus = 'PENDING' or requestStatus = 'IN_PROGRESS' or requestStatus = 'TIMEOUT') and requestType = :requestType ORDER BY startTime DESC"); result = query;
+            query.list(); result = Arrays.asList(new InfraActiveRequests("123", "action"));
+        }};
+        assertEquals("123",
+                requestsDatabase.checkDuplicateByVnfName("vnfname",
+                        "action",
+                        "requesttype").getRequestId());
+    }
+
+    @Test
+    public void checkDuplicateByVnfIdTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                          @Mocked Session session,
+                                          @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            session.createQuery("from InfraActiveRequests where vnfId = :vnfId and action = :action and (requestStatus = 'PENDING' or requestStatus = 'IN_PROGRESS' or requestStatus = 'TIMEOUT') and requestType = :requestType ORDER BY startTime DESC"); result = query;
+            query.list(); result = Arrays.asList(new InfraActiveRequests("123", "action"));
+        }};
+        assertEquals("123",
+                requestsDatabase.checkDuplicateByVnfId("vnfname",
+                        "action",
+                        "requesttype").getRequestId());
+    }
+
+    @Test
+    public void setMockDBTest() throws Exception {
+        requestsDatabase.setMockDB(null);
+    }
+
+    @Test
+    public void getSiteStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                  @Mocked Session session,
+                                  @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            session.createQuery("FROM SiteStatus WHERE siteName = :site_name"); result = query;
+            query.uniqueResult(); result = new SiteStatus();
+        }};
+        assertEquals(SiteStatus.class,
+                requestsDatabase.getSiteStatus("site").getClass());
+    }
+
+    @Test
+    public void updateSiteStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                     @Mocked Session session,
+                                     @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            session.createQuery("FROM SiteStatus WHERE siteName = :site_name"); result = query;
+            query.uniqueResult(); result = new SiteStatus();
+        }};
+        requestsDatabase.updateSiteStatus("site", true);
+    }
+
+    @Test
+    public void getOperationStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                       @Mocked Session session,
+                                       @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            session.createQuery("FROM OperationStatus WHERE SERVICE_ID = :service_id and OPERATION_ID = :operation_id"); result = query;
+            query.uniqueResult(); result = new OperationStatus();
+        }};
+        assertEquals(OperationStatus.class,
+                requestsDatabase.getOperationStatus("123",
+                        "Unknown").getClass());
+    }
+
+    @Test
+    public void getOperationStatusByServiceIdTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                                  @Mocked Session session,
+                                                  @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            session.createQuery("FROM OperationStatus WHERE SERVICE_ID = :service_id"); result = query;
+            query.uniqueResult(); result = new OperationStatus();
+        }};
+        assertEquals(OperationStatus.class,
+                requestsDatabase.getOperationStatusByServiceId("123").getClass());
+    }
+
+    @Test
+    public void getOperationStatusByServiceNameTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                                    @Mocked Session session,
+                                                    @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            session.createQuery("FROM OperationStatus WHERE SERVICE_NAME = :service_name"); result = query;
+            query.uniqueResult(); result = new OperationStatus();
+        }};
+        assertEquals(OperationStatus.class,
+                requestsDatabase.getOperationStatusByServiceName("servicename").getClass());
+    }
+
+    @Test
+    public void updateOperationStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                          @Mocked Session session,
+                                          @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            session.createQuery("FROM OperationStatus WHERE SERVICE_ID = :service_id and OPERATION_ID = :operation_id"); result = query;
+            query.uniqueResult(); result = new OperationStatus();
+        }};
+        requestsDatabase.updateOperationStatus(new OperationStatus());
+    }
+
+    @Test
+    public void getResourceOperationStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager,
+                                               @Mocked Session session,
+                                               @Mocked Query query) throws Exception {
+        new Expectations() {{
+            sessionFactoryManager.getSessionFactory().openSession(); result = session;
+            session.createQuery("FROM ResourceOperationStatus WHERE serviceId = :service_id and operationId = :operation_id and resourceTemplateUUID= :uuid"); result = query;
+            query.uniqueResult(); result = new ResourceOperationStatus();
+        }};
+        assertEquals(ResourceOperationStatus.class,
+                requestsDatabase.getResourceOperationStatus("serviceId",
+                        "operationid",
+                        "123-uuid").getClass());
+    }
+}
index 4399c75..06eedc5 100644 (file)
@@ -2,12 +2,12 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>so</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
 
-       <groupId>org.openecomp.so</groupId>
+       <groupId>org.onap.so</groupId>
        <artifactId>mso-api-handlers</artifactId>
        <name>API Handler</name>
        <description>API Handler for MSO</description>
index 0dc9e34..e3115f1 100644 (file)
@@ -2,12 +2,12 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>so</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
 
-       <groupId>org.openecomp.so</groupId>
+       <groupId>org.onap.so</groupId>
        <artifactId>mso-catalog-db</artifactId>
        <name>mso-catalog-db</name>
        <description>MSO Catalog Database definition and Hibernate objects</description>
                        </exclusions>
                </dependency>
                <dependency>
-                       <groupId>org.openecomp.so</groupId>
+                       <groupId>org.onap.so</groupId>
                        <artifactId>common</artifactId>
                        <version>${project.version}</version>
                </dependency>
index aefe0d5..891b0b2 100644 (file)
@@ -2166,9 +2166,7 @@ public class CatalogDatabase implements Closeable {
                String networkModelCustomizationUuid = stn.getResourceModelCustomizationUUID();
             LOGGER.debug("Now searching for NetworkResourceCustomization for " + networkModelCustomizationUuid);
             List<NetworkResourceCustomization> resultSet = this.getAllNetworksByNetworkModelCustomizationUuid(networkModelCustomizationUuid);
-            for (NetworkResourceCustomization nrc : resultSet) {
-                masterList.add(nrc);
-            }
+            masterList.addAll(resultSet);
         }
         LOGGER.debug("Returning " + masterList.size() + " NRC records");
         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllNetworksByServiceModelUuid", null);
@@ -2465,9 +2463,7 @@ public class CatalogDatabase implements Closeable {
                String arModelCustomizationUuid = star.getResourceModelCustomizationUUID();
             LOGGER.debug("Now searching for AllottedResourceCustomization for " + arModelCustomizationUuid);
             List<AllottedResourceCustomization> resultSet = this.getAllAllottedResourcesByArModelCustomizationUuid(arModelCustomizationUuid);
-            for (AllottedResourceCustomization arc : resultSet) {
-                masterList.add(arc);
-            }
+            masterList.addAll(resultSet);
         }
         LOGGER.debug("Returning " + masterList.size() + " ARC records");
         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllAllottedResourcesByServiceModelUuid", null);
index b0a8c3e..8db4902 100644 (file)
@@ -109,7 +109,7 @@ public class VnfComponent implements Serializable {
     public int hashCode () {
         // return the hashCode of the concat string of type+vnfId - should be okay.
         int result = 0;
-        result = (this.componentType + this.vnfId).toString().hashCode();
+        result = (this.componentType + this.vnfId).hashCode();
         return result;
     }
 }
index 0872f14..7495015 100644 (file)
@@ -226,9 +226,7 @@ public class VnfResource extends MavenLikeVersioning implements Serializable {
                        return null;
        }
                ArrayList<VfModule> list = new ArrayList<VfModule>();
-               for (VfModule vfm : this.vfModules) {
-                       list.add(vfm);
-       }
+               list.addAll(this.vfModules);
                return list;
        }
        
index c3d5357..cf79d5b 100644 (file)
@@ -67,7 +67,7 @@ public class HeatTemplateTest {
         heatTemplate.setParameters (set);
         String heatStr = heatTemplate.toString (); 
         assertTrue (heatStr.contains ("param name"));
-        assertTrue (heatStr.toString ().contains ("param 2(reqd)"));
+        assertTrue (heatStr.contains ("param 2(reqd)"));
 
         File tempFile;
         try {
index 0abe819..8420cf4 100644 (file)
@@ -2,12 +2,12 @@
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
-    <groupId>org.openecomp.so</groupId>
+    <groupId>org.onap.so</groupId>
     <artifactId>packages</artifactId>
     <version>1.2.0-SNAPSHOT</version>
   </parent>
 
-  <groupId>org.openecomp.so.packages</groupId>
+  <groupId>org.onap.so.packages</groupId>
   <name>Arquillian Unit Testing on MSO</name>
   <artifactId>arquillian-unit-tests</artifactId>
 
     </dependency>
 
     <dependency>
-      <groupId>org.openecomp.so</groupId>
+      <groupId>org.onap.so</groupId>
       <artifactId>asdc-controller</artifactId>
       <version>${project.version}</version>
       <scope>test</scope>
     </dependency>
 
     <dependency>
-      <groupId>org.openecomp.so</groupId>
+      <groupId>org.onap.so</groupId>
       <artifactId>mso-catalog-db</artifactId>
       <version>${project.version}</version>
       <scope>test</scope>
index 9ce0ac8..a905688 100644 (file)
@@ -2,12 +2,12 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>packages</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
 
-       <groupId>org.openecomp.so.packages</groupId>
+       <groupId>org.onap.so.packages</groupId>
        <artifactId>mso-deliveries</artifactId>
        <packaging>pom</packaging>
 
index 41086ea..1957dc7 100644 (file)
@@ -3,13 +3,13 @@
        <modelVersion>4.0.0</modelVersion>
 
        <parent>
-               <groupId>org.openecomp.so</groupId>
+               <groupId>org.onap.so</groupId>
                <artifactId>packages</artifactId>
                <version>1.2.0-SNAPSHOT</version>
        </parent>
 
        <packaging>pom</packaging>
-       <groupId>org.openecomp.so</groupId>
+       <groupId>org.onap.so</groupId>
        <artifactId>docker</artifactId>
 
        <name>MSO Docker Deliveries</name>
index ff1be1f..74d4c30 100644 (file)
@@ -2,12 +2,12 @@
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">\r
        <modelVersion>4.0.0</modelVersion>\r
        <parent>\r
-               <groupId>org.openecomp.so</groupId>\r
+               <groupId>org.onap.so</groupId>\r
                <artifactId>so</artifactId>\r
                <version>1.2.0-SNAPSHOT</version>\r
        </parent>\r
 \r
-       <groupId>org.openecomp.so</groupId>\r
+       <groupId>org.onap.so</groupId>\r
        <artifactId>packages</artifactId>\r
        <packaging>pom</packaging>\r
        <name>MSO Packages</name>\r
diff --git a/pom.xml b/pom.xml
index 049c0e6..f06a04b 100644 (file)
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
     <relativePath />
   </parent>
 
-  <groupId>org.openecomp.so</groupId>
+  <groupId>org.onap.so</groupId>
   <artifactId>so</artifactId>
   <packaging>pom</packaging>
   <!-- <version>1.2.0-SNAPSHOT</version> -->
index 2339825..e8ba05e 100644 (file)
@@ -4,29 +4,29 @@
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">\r
     <modelVersion>4.0.0</modelVersion>\r
     <parent>\r
-        <groupId>org.openecomp.so</groupId>\r
+        <groupId>org.onap.so</groupId>\r
         <artifactId>so</artifactId>\r
         <version>1.2.0-SNAPSHOT</version>\r
     </parent>\r
 \r
-    <groupId>org.openecomp.so</groupId>\r
+    <groupId>org.onap.so</groupId>\r
     <artifactId>status-control</artifactId>\r
     <name>MSO Status Control module</name>\r
     <description>Contains classes to update and query the MSO status per site</description>\r
 \r
     <dependencies>\r
         <dependency>\r
-            <groupId>org.openecomp.so</groupId>\r
+            <groupId>org.onap.so</groupId>\r
             <artifactId>common</artifactId>\r
             <version>${project.version}</version>\r
         </dependency>\r
         <dependency>\r
-            <groupId>org.openecomp.so</groupId>\r
+            <groupId>org.onap.so</groupId>\r
             <artifactId>mso-catalog-db</artifactId>\r
             <version>${project.version}</version>\r
         </dependency>\r
         <dependency>\r
-            <groupId>org.openecomp.so</groupId>\r
+            <groupId>org.onap.so</groupId>\r
             <artifactId>mso-requests-db</artifactId>\r
             <version>${project.version}</version>\r
         </dependency>\r