Fix most sonar issues 55/34255/3
authorDenes Nemeth <denes.nemeth@nokia.com>
Tue, 6 Mar 2018 10:24:26 +0000 (11:24 +0100)
committerDenes Nemeth <denes.nemeth@nokia.com>
Tue, 6 Mar 2018 13:26:49 +0000 (14:26 +0100)
Change-Id: I2dfae3f808aeaf94513a6e3c917eea52d6ab6322
Signed-off-by: Denes Nemeth <denes.nemeth@nokia.com>
Issue-ID: VFC-728

43 files changed:
nokiav2/.gitignore
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/api/IPackageProvider.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/api/VnfmInfoProvider.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/onap/core/GenericExternalSystemInfoProvider.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/onap/core/IpMappingProvider.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/onap/core/MsbApiProvider.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/onap/core/SelfRegistrationManager.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/onap/vfc/VfcGrantManager.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/onap/vfc/VfcNotificationSender.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/onap/vfc/VfcPackageProvider.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/packagetransformer/CbamVnfdBuilder.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/packagetransformer/OnapVnfPackageBuilder.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/packagetransformer/OnapVnfdBuilder.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/restapi/ConverterApi.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/restapi/LcnApi.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/restapi/SwaggerApi.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/spring/Conditions.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/CbamUtils.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/StoreLoader.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/SystemFunctions.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/UserInvisibleError.java [new file with mode: 0644]
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/UserVisibleError.java [new file with mode: 0644]
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/CatalogManager.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/CbamTokenProvider.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/DriverProperties.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/ILifecycleChangeNotificationManager.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/JobManager.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/LifecycleManager.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/notification/LifecycleChangeNotificationManager.java
nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/notification/ReportedAffectedCp.java
nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/FullUnitTestSuite.java
nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/onap/core/TestCbamRestApiProvider.java
nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/onap/vfc/TestVfcExternalSystemInfoProvider.java
nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/onap/vfc/TestVfcGrantManager.java
nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/onap/vfc/TestVfcPackageProvider.java
nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/TestUserInvisibleError.java [new file with mode: 0644]
nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/TestUserVisibleError.java [new file with mode: 0644]
nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/TestBase.java
nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/TestCbamTokenProvider.java
nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/TestJobManager.java
nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/TestLifecycleManager.java
nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/notification/TestLifecycleChangeNotificationManager.java
nokiav2/pom.xml

index dbffadf..88783a3 100644 (file)
@@ -3,3 +3,5 @@ bin
 *.iml
 .DS_Store
 tmp
+logs
+debug-logs
index a652354..2011118 100644 (file)
@@ -19,10 +19,6 @@ package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.api;
  * Provides a VNF package from ONAP repositories
  */
 public interface IPackageProvider {
-    /**
-     * The location of the CBAM package within the ONAP package
-     */
-    String CBAM_PACKAGE_NAME_IN_ZIP = "Artifacts/Deployment/OTHER/cbam.package.zip";
 
     /**
      * Download the package from ONAP
index cfcb1d4..3fe9e3f 100644 (file)
@@ -22,16 +22,6 @@ import org.onap.vnfmdriver.model.VnfmInfo;
  */
 public interface VnfmInfoProvider {
 
-    /**
-     * The name of the VNFM info cache eviction in the properties file
-     */
-    String VNFM_INFO_CACHE_EVICTION_IN_MS = "vnfmInfoCacheEvictionInMs";
-
-    /**
-     * The default VNFM info cache eviction in milliseconds
-     */
-    int DEFAULT_CACHE_EVICTION_TIMEOUT_IN_MS = 10 * 60 * 1000;
-
     /**
      * @param vnfmId the identifier of the VNFM
      * @return the description of the VNFM
index 3e1e05a..f13e2bb 100644 (file)
@@ -34,7 +34,15 @@ import static org.slf4j.LoggerFactory.getLogger;
 /**
  * Responsible for providing access to core systems
  */
-abstract public class GenericExternalSystemInfoProvider extends IpMappingProvider implements VnfmInfoProvider, VimInfoProvider, InitializingBean {
+public abstract class GenericExternalSystemInfoProvider extends IpMappingProvider implements VnfmInfoProvider, VimInfoProvider, InitializingBean {
+    /**
+     * The name of the VNFM info cache eviction in the properties file
+     */
+    public static final String VNFM_INFO_CACHE_EVICTION_IN_MS = "vnfmInfoCacheEvictionInMs";
+    /**
+     * The default VNFM info cache eviction in milliseconds
+     */
+    public static final int DEFAULT_CACHE_EVICTION_TIMEOUT_IN_MS = 10 * 60 * 1000;
     private static Logger logger = getLogger(GenericExternalSystemInfoProvider.class);
     private final Environment environment;
     private LoadingCache<String, VnfmInfo> vnfmInfoCache;
index a247228..ec6db5e 100644 (file)
@@ -23,7 +23,6 @@ import org.springframework.stereotype.Component;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Map;
-import java.util.function.Consumer;
 
 import static com.google.common.base.Splitter.on;
 import static com.google.common.collect.Lists.newArrayList;
@@ -48,12 +47,9 @@ public class IpMappingProvider implements InitializingBean {
      */
     @Override
     public void afterPropertiesSet() throws Exception {
-        on(",").trimResults().omitEmptyStrings().split(environment.getProperty(IP_MAP, String.class, "")).forEach(new Consumer<String>() {
-            @Override
-            public void accept(String item) {
-                ArrayList<String> ip = newArrayList(on("->").trimResults().split(item));
-                ipMap.put(ip.get(0), ip.get(1));
-            }
+        on(",").trimResults().omitEmptyStrings().split(environment.getProperty(IP_MAP, String.class, "")).forEach(item -> {
+            ArrayList<String> ip = newArrayList(on("->").trimResults().split(item));
+            ipMap.put(ip.get(0), ip.get(1));
         });
     }
 
index b652b59..195e776 100644 (file)
@@ -63,11 +63,10 @@ public class MsbApiProvider extends IpMappingProvider {
         //FIXME the enable_ssl field should be used, but it is not available in SDK depends on MSB-151 jira issue
         String protocol = (ipAnPort.endsWith(":8443") || ipAnPort.endsWith(":443")) ? "https://" : "http://";
         //the field name in A&AI is misleading the URL is relative path postfixed to http(s)://ip:port
-        String fullUrl = protocol + ipAnPort + microServiceFullInfo.getUrl();
-        return fullUrl;
+        return protocol + ipAnPort + microServiceFullInfo.getUrl();
     }
 
-    private MicroServiceFullInfo getMicroServiceInfo(String name, String version) throws RuntimeException {
+    private MicroServiceFullInfo getMicroServiceInfo(String name, String version) {
         try {
             return getMsbClient().queryMicroServiceInfo(name, version);
         } catch (RouteException e) {
@@ -77,10 +76,14 @@ public class MsbApiProvider extends IpMappingProvider {
 
     private String getNodeIpAnPort(MicroServiceFullInfo microServiceFullInfo) {
         for (NodeInfo nodeInfo : microServiceFullInfo.getNodes()) {
-            if (!nodeInfo.getIp().startsWith("172.")) { // FIXME how to know which of the multiple addresses to use?
+            if (isADokcerInternalAddress(nodeInfo)) {
                 return mapPrivateIpToPublicIp(nodeInfo.getIp()) + ":" + nodeInfo.getPort();
             }
         }
         throw fatalFailure(logger, "The " + microServiceFullInfo.getServiceName() + " service with " + microServiceFullInfo.getVersion() + " does not have any valid nodes" + microServiceFullInfo.getNodes());
     }
+
+    private boolean isADokcerInternalAddress(NodeInfo nodeInfo) {
+        return !nodeInfo.getIp().startsWith("172.");
+    }
 }
index 3b2f1d3..3c918f5 100644 (file)
@@ -35,6 +35,7 @@ import java.util.ArrayList;
 import java.util.HashSet;
 
 import static com.nokia.cbam.lcn.v32.model.SubscriptionAuthentication.TypeEnum.NONE;
+import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.fatalFailure;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCN_API_VERSION;
 import static org.slf4j.LoggerFactory.getLogger;
 
@@ -93,10 +94,9 @@ public class SelfRegistrationManager {
         } catch (RouteException e) {
             //ONAP throws 500 internal server error, but deletes the micro service
             try {
-                MicroServiceFullInfo microServiceFullInfo = msbApiProvider.getMsbClient().queryMicroServiceInfo(SERVICE_NAME, DRIVER_VERSION);
-                logger.error("Unable to deRegister Nokia VNFM driver", e);
+                msbApiProvider.getMsbClient().queryMicroServiceInfo(SERVICE_NAME, DRIVER_VERSION);
                 //the micro service still exists
-                throw new RuntimeException(e);
+                fatalFailure(logger, "Unable to deRegister Nokia VNFM driver", e);
             } catch (RouteException e1) {
                 // the micro service was deleted (even though 500 HTTP code was reported)
             }
@@ -119,15 +119,14 @@ public class SelfRegistrationManager {
         logger.info("Deleting CBAM LCN subscription");
         SubscriptionsApi lcnApi = cbamRestApiProvider.getCbamLcnApi(vnfmId);
         try {
-            String callbackUrl = getDriverVnfmUrl() + DriverProperties.LCN_PATH;
+            String callbackUrl = getDriverVnfmUrl() + DriverProperties.LCN_URL;
             for (Subscription subscription : lcnApi.subscriptionsGet(NOKIA_LCN_API_VERSION)) {
                 if (subscription.getCallbackUrl().equals(callbackUrl)) {
                     lcnApi.subscriptionsSubscriptionIdDelete(subscription.getId(), NOKIA_LCN_API_VERSION);
                 }
             }
         } catch (ApiException e) {
-            logger.error("Unable to delete CBAM LCN subscription");
-            throw new RuntimeException(e);
+            fatalFailure(logger, "Unable to delete CBAM LCN subscription", e);
         }
     }
 
@@ -151,14 +150,13 @@ public class SelfRegistrationManager {
         try {
             return msbApiProvider.getMsbClient().registerMicroServiceInfo(microServiceInfo);
         } catch (RouteException e) {
-            logger.error("Unable to register Nokia VNFM driver", e);
-            throw new RuntimeException(e);
+            throw fatalFailure(logger, "Unable to register Nokia VNFM driver", e);
         }
     }
 
     private void subscribeToLcn(String vnfmId) {
-        String callbackUrl = getDriverVnfmUrl() + DriverProperties.LCN_PATH;
-        logger.info("Subscribing to CBAM LCN " + driverProperties.getCbamLcnUrl() + " with callback to " + callbackUrl);
+        String callbackUrl = getDriverVnfmUrl() + DriverProperties.LCN_URL;
+        logger.info("Subscribing to CBAM LCN {} with callback to {}", driverProperties.getCbamLcnUrl(), callbackUrl);
         SubscriptionsApi lcnApi = cbamRestApiProvider.getCbamLcnApi(vnfmId);
         try {
             for (Subscription subscription : lcnApi.subscriptionsGet(NOKIA_LCN_API_VERSION)) {
@@ -176,12 +174,11 @@ public class SelfRegistrationManager {
             request.getFilter().addOperationTypesItem(OperationType.SCALE);
             request.getFilter().addOperationTypesItem(OperationType.TERMINATE);
             SubscriptionAuthentication subscriptionAuthentication = new SubscriptionAuthentication();
-            subscriptionAuthentication.setType(NONE);//FIXME improve authentication
+            subscriptionAuthentication.setType(NONE);
             request.setAuthentication(subscriptionAuthentication);
             lcnApi.subscriptionsPost(request, NOKIA_LCN_API_VERSION);
         } catch (ApiException e) {
-            logger.error("Unable to subscribe to CBAM LCN", e);
-            throw new RuntimeException(e);
+            fatalFailure(logger, "Unable to subscribe to CBAM LCN", e);
         }
     }
 
index fd68aeb..a268a73 100644 (file)
@@ -16,6 +16,7 @@
 
 package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.onap.vfc;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.gson.Gson;
 import com.google.gson.JsonArray;
 import com.google.gson.JsonElement;
@@ -37,7 +38,10 @@ import org.yaml.snakeyaml.Yaml;
 
 import java.util.*;
 
+import static com.nokia.cbam.lcm.v32.model.InstantiationState.INSTANTIATED;
+import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.fatalFailure;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCM_API_VERSION;
+import static org.onap.vnfmdriver.model.OperationType.TERMINAL;
 import static org.slf4j.LoggerFactory.getLogger;
 
 /**
@@ -79,47 +83,39 @@ public class VfcGrantManager implements IGrantManager {
             com.nokia.cbam.lcm.v32.model.VnfInfo vnf = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdGet(vnfId, NOKIA_LCM_API_VERSION);
             String vnfdContent = catalogManager.getCbamVnfdContent(vnfmId, vnf.getVnfdId());
             Set<ResourceChange> resourceChanges = calculateResourceChangeDuringScaling(vnfdContent, request.getAspectId(), Integer.parseInt(request.getNumberOfSteps()));
-            switch (request.getType()) {
-                case IN:
-                    grantRequest.getRemoveResource().addAll(resourceChanges);
-                    break;
-                case OUT:
-                    grantRequest.getAddResource().addAll(resourceChanges);
-                    break;
+            if (request.getType() == ScaleDirection.IN) {
+                grantRequest.getRemoveResource().addAll(resourceChanges);
+
+            } else {
+                grantRequest.getAddResource().addAll(resourceChanges);
             }
             grantRequest.setVnfInstanceId(vnfId);
             requestGrant(grantRequest);
         } catch (ApiException e) {
-            logger.error("Unable to query VNF " + vnfId, e);
-            throw new RuntimeException("Unable to query VNF " + vnfId, e);
+            fatalFailure(logger, "Unable to query VNF " + vnfId, e);
         }
     }
 
     @Override
     public void requestGrantForTerminate(String vnfmId, String vnfId, String vimId, String onapVnfdId, VnfInfo vnf, String jobId) {
-        switch (vnf.getInstantiationState()) {
-            case NOT_INSTANTIATED:
-                break;
-            case INSTANTIATED:
-                GrantVNFRequest grantRequest;
-                try {
-                    grantRequest = buildGrantRequest(vnfmId, vimId, onapVnfdId, jobId, OperationType.TERMINAL);
-                    if (vnf.getInstantiatedVnfInfo().getVnfcResourceInfo() != null) {
-                        for (VnfcResourceInfo vnfc : vnf.getInstantiatedVnfInfo().getVnfcResourceInfo()) {
-                            ResourceChange resourceChange = new ResourceChange();
-                            grantRequest.getRemoveResource().add(resourceChange);
-                            resourceChange.setVdu(vnfc.getVduId());
-                            resourceChange.setType(ChangeType.VDU);
-                            resourceChange.setResourceDefinitionId(UUID.randomUUID().toString());
-                        }
+        if (vnf.getInstantiationState() == INSTANTIATED) {
+            GrantVNFRequest grantRequest;
+            try {
+                grantRequest = buildGrantRequest(vnfmId, vimId, onapVnfdId, jobId, TERMINAL);
+                if (vnf.getInstantiatedVnfInfo().getVnfcResourceInfo() != null) {
+                    for (VnfcResourceInfo vnfc : vnf.getInstantiatedVnfInfo().getVnfcResourceInfo()) {
+                        ResourceChange resourceChange = new ResourceChange();
+                        grantRequest.getRemoveResource().add(resourceChange);
+                        resourceChange.setVdu(vnfc.getVduId());
+                        resourceChange.setType(ChangeType.VDU);
+                        resourceChange.setResourceDefinitionId(UUID.randomUUID().toString());
                     }
-                    grantRequest.setVnfInstanceId(vnfId);
-                } catch (Exception e) {
-                    logger.error("Unable to prepare grant request for termination", e);
-                    throw new RuntimeException("Unable to prepare grant request for termination", e);
                 }
-                requestGrant(grantRequest);
-                break;
+                grantRequest.setVnfInstanceId(vnfId);
+            } catch (Exception e) {
+                throw fatalFailure(logger, "Unable to prepare grant request for termination", e);
+            }
+            requestGrant(grantRequest);
         }
     }
 
@@ -132,8 +128,7 @@ public class VfcGrantManager implements IGrantManager {
             grantRequest.setAddResource(new ArrayList<>());
             grantRequest.getAddResource().addAll(calculateResourceChangeDuringInstantiate(cbamVnfdContent, instantiationLevelId));
         } catch (Exception e) {
-            logger.error("Unable to prepare grant request for instantiation", e);
-            throw new RuntimeException("Unable to prepare grant request for instantiation", e);
+            throw fatalFailure(logger, "Unable to prepare grant request for instantiation", e);
         }
         return requestGrant(grantRequest);
     }
@@ -154,8 +149,7 @@ public class VfcGrantManager implements IGrantManager {
         try {
             return vfcRestApiProvider.getNsLcmApi().grantvnf(grantRequest).getVim();
         } catch (org.onap.vnfmdriver.ApiException e) {
-            logger.error("Unable to request grant", e);
-            throw new RuntimeException(e);
+            throw fatalFailure(logger, "Unable to request grant", e);
         }
     }
 
@@ -166,8 +160,8 @@ public class VfcGrantManager implements IGrantManager {
         JsonObject instantiationLevels = CbamUtils.child(deploymentFlavorProperties, "instantiation_levels");
         Set<ResourceChange> resourceChanges = new HashSet<>();
         for (Map.Entry<String, JsonElement> vdu_level : CbamUtils.child(CbamUtils.child(instantiationLevels, instantiationLevelId), ("vdu_levels")).entrySet()) {
-            JsonElement number_of_instances = vdu_level.getValue().getAsJsonObject().get("number_of_instances");
-            for (int i = 0; i < number_of_instances.getAsLong(); i++) {
+            JsonElement numberOfInstances = vdu_level.getValue().getAsJsonObject().get("number_of_instances");
+            for (int i = 0; i < numberOfInstances.getAsLong(); i++) {
                 ResourceChange resourceChange = new ResourceChange();
                 resourceChanges.add(resourceChange);
                 resourceChange.setVdu(vdu_level.getKey());
@@ -187,28 +181,33 @@ public class VfcGrantManager implements IGrantManager {
                 JsonObject aspects = policy.getAsJsonObject().entrySet().iterator().next().getValue().getAsJsonObject().get("properties").getAsJsonObject().get("aspects").getAsJsonObject();
                 JsonObject aspect = aspects.get(aspectId).getAsJsonObject();
                 if (aspect.has("vdus")) {
-                    for (Map.Entry<String, JsonElement> vdu : aspect.get("vdus").getAsJsonObject().entrySet()) {
-                        String vduId = vdu.getKey();
-                        for (int step = 0; step < steps; step++) {
-                            for (int i = 0; i < vdu.getValue().getAsJsonArray().size(); i++) {
-                                ResourceChange resourceChange = new ResourceChange();
-                                resourceChange.setVdu(vduId);
-                                resourceChange.setType(ChangeType.VDU);
-                                resourceChange.setResourceDefinitionId(UUID.randomUUID().toString());
-                                resourceChanges.add(resourceChange);
-                            }
-                        }
-                    }
+                    addChangesForAspect(steps, resourceChanges, aspect);
                 }
             }
         }
         return resourceChanges;
     }
 
+    private void addChangesForAspect(int steps, Set<ResourceChange> resourceChanges, JsonObject aspect) {
+        for (Map.Entry<String, JsonElement> vdu : aspect.get("vdus").getAsJsonObject().entrySet()) {
+            String vduId = vdu.getKey();
+            for (int step = 0; step < steps; step++) {
+                for (int i = 0; i < vdu.getValue().getAsJsonArray().size(); i++) {
+                    ResourceChange resourceChange = new ResourceChange();
+                    resourceChange.setVdu(vduId);
+                    resourceChange.setType(ChangeType.VDU);
+                    resourceChange.setResourceDefinitionId(UUID.randomUUID().toString());
+                    resourceChanges.add(resourceChange);
+                }
+            }
+        }
+    }
+
     /**
      * Represents the mandatory parameters that must be sent during grant request to VF-C
      */
-    private static class AdditionalGrantParams {
+    @VisibleForTesting
+    static class AdditionalGrantParams {
         private final String vnfmId;
         private final String vimId;
 
@@ -216,5 +215,24 @@ public class VfcGrantManager implements IGrantManager {
             this.vnfmId = vnfmId;
             this.vimId = vimId;
         }
+
+        /**
+         * @return the identifier of the VNFM requesting the grant
+         */
+        public String getVnfmId() {
+            return vnfmId;
+        }
+
+        /**
+         * @return the identifier of the VIM for which the grant is requested
+         */
+        public String getVimId() {
+            //FIXME
+            //Currently the grant request sent to VF-C must contain the VIM identifier in the
+            //grant response (normally in ETSI VIM identifier is received in the grant response
+            //from ETSI orchestrator the vimId parameter should be removed from this POJO
+            //to be able to fix this https://jira.onap.org/browse/VFC-603 must be solved
+            return vimId;
+        }
     }
 }
index 98b9a22..f7667c5 100644 (file)
@@ -32,12 +32,11 @@ import org.springframework.context.annotation.Conditional;
 import org.springframework.stereotype.Component;
 
 import java.util.ArrayList;
-import java.util.List;
 
 import static com.google.common.base.Optional.of;
 import static com.google.common.collect.Iterables.tryFind;
+import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.SEPARATOR;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.fatalFailure;
-import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.ILifecycleChangeNotificationManager.SEPARATOR;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.JobManager.extractOnapJobId;
 import static org.slf4j.LoggerFactory.getLogger;
 
@@ -61,7 +60,7 @@ public class VfcNotificationSender implements INotificationSender {
     public void processNotification(VnfLifecycleChangeNotification recievedNotification, OperationExecution operationExecution, ReportedAffectedConnectionPoints affectedCps, String vimId) {
         VNFLCMNotification notificationToSend = new VNFLCMNotification();
         notificationToSend.setJobId(extractOnapJobId(operationExecution.getOperationParams()));
-        notificationToSend.setOperation(getOperation(driverProperties.getVnfmId(), recievedNotification.getVnfInstanceId(), operationExecution, recievedNotification.getOperation(), recievedNotification.getAffectedVnfcs()));
+        notificationToSend.setOperation(getOperation(operationExecution, recievedNotification.getOperation()));
         notificationToSend.setVnfInstanceId(recievedNotification.getVnfInstanceId());
         switch (recievedNotification.getStatus()) {
             case FINISHED:
@@ -80,7 +79,9 @@ public class VfcNotificationSender implements INotificationSender {
 
     private void sendNotification(VNFLCMNotification notification) {
         try {
-            logger.info("Sending LCN: " + new Gson().toJson(notification));
+            if (logger.isInfoEnabled()) {
+                logger.info("Sending LCN: " + new Gson().toJson(notification));
+            }
             vfcRestApiProvider.getNsLcmApi().vNFLCMNotification(driverProperties.getVnfmId(), notification.getVnfInstanceId(), notification);
         } catch (Exception e) {
             fatalFailure(logger, "Unable to send LCN to VF-C", e);
@@ -143,10 +144,9 @@ public class VfcNotificationSender implements INotificationSender {
     private Optional<VnfCpNotificationType> getChangeType(ReportedAffectedConnectionPoints affectedCps, ReportedAffectedCp affectedCp) {
         Optional<ReportedAffectedCp> cpBeforeOperation = tryFind(affectedCps.getPre(), pre -> affectedCp.getCpId().equals(pre.getCpId()));
         Optional<ReportedAffectedCp> cpAfterOperation = tryFind(affectedCps.getPost(), post -> affectedCp.getCpId().equals(post.getCpId()));
-        if(cpBeforeOperation.isPresent() && cpAfterOperation.isPresent()){
+        if (cpBeforeOperation.isPresent() && cpAfterOperation.isPresent()) {
             return cpAfterOperation.get().equals(cpBeforeOperation.get()) ? Optional.absent() : of(VnfCpNotificationType.CHANGED);
-        }
-        else{
+        } else {
             //the affected CP must be present in the pre or post
             return of((cpAfterOperation.isPresent() ? VnfCpNotificationType.ADDED : VnfCpNotificationType.REMOVED));
         }
@@ -157,13 +157,13 @@ public class VfcNotificationSender implements INotificationSender {
             notificationToSend.setAffectedCp(new ArrayList<>());
             for (ReportedAffectedCp pre : affectedCps.getPre()) {
                 Optional<VnfCpNotificationType> changeType = getChangeType(affectedCps, pre);
-                if(of(VnfCpNotificationType.REMOVED).equals(changeType)){
+                if (of(VnfCpNotificationType.REMOVED).equals(changeType)) {
                     addModifiedCp(vimId, notificationToSend, pre, changeType);
                 }
             }
             for (ReportedAffectedCp post : affectedCps.getPost()) {
                 Optional<VnfCpNotificationType> changeType = getChangeType(affectedCps, post);
-                if(of(VnfCpNotificationType.ADDED).equals(changeType) || of(VnfCpNotificationType.CHANGED).equals(changeType)){
+                if (of(VnfCpNotificationType.ADDED).equals(changeType) || of(VnfCpNotificationType.CHANGED).equals(changeType)) {
                     addModifiedCp(vimId, notificationToSend, post, changeType);
                 }
             }
@@ -183,7 +183,7 @@ public class VfcNotificationSender implements INotificationSender {
         }
     }
 
-    private org.onap.vnfmdriver.model.OperationType getOperation(String vnfmId, String vnfId, OperationExecution operationExecution, com.nokia.cbam.lcm.v32.model.OperationType type, List<com.nokia.cbam.lcm.v32.model.AffectedVnfc> affectedVnfcs) {
+    private org.onap.vnfmdriver.model.OperationType getOperation(OperationExecution operationExecution, com.nokia.cbam.lcm.v32.model.OperationType type) {
         switch (type) {
             case TERMINATE:
                 return org.onap.vnfmdriver.model.OperationType.TERMINAL;
@@ -191,11 +191,10 @@ public class VfcNotificationSender implements INotificationSender {
                 return org.onap.vnfmdriver.model.OperationType.INSTANTIATE;
             case SCALE:
                 ScaleVnfRequest originalRequest = new Gson().fromJson(new Gson().toJson(operationExecution.getOperationParams()), ScaleVnfRequest.class);
-                switch (originalRequest.getType()) {
-                    case IN:
-                        return org.onap.vnfmdriver.model.OperationType.SCALEIN;
-                    default: //OUT
-                        return org.onap.vnfmdriver.model.OperationType.SCALEOUT;
+                if (originalRequest.getType() == com.nokia.cbam.lcm.v32.model.ScaleDirection.IN) {
+                    return OperationType.SCALEIN;
+                } else {
+                    return OperationType.SCALEOUT;
                 }
             default:
                 return org.onap.vnfmdriver.model.OperationType.HEAL;
index b8de237..bc201f5 100644 (file)
@@ -33,7 +33,6 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Conditional;
 import org.springframework.stereotype.Component;
 
-import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.URL;
@@ -67,7 +66,7 @@ public class VfcPackageProvider implements IPackageProvider {
             JsonElement vnfdModel = new JsonParser().parse(vnfPackageDetails.getPackageInfo().getVnfdModel());
             return vnfdModel.getAsJsonObject().get("metadata").getAsJsonObject().get("resourceVendorModelNumber").getAsString();
         } catch (Exception e) {
-            throw fatalFailure(logger, "Unable to query VNF package with " + csarId + " from VF-C", e);
+            throw fatalFailure(logger, "Unable to query VNF package with " + csarId, e);
         }
     }
 
@@ -83,12 +82,12 @@ public class VfcPackageProvider implements IPackageProvider {
                 downloadUrl = downloadUrl.replaceFirst("://" + host, "://" + ipMappingProvider.mapPrivateIpToPublicIp(host));
             }
         } catch (Exception e) {
-            throw fatalFailure(logger, "Unable to query VNF package with " + csarId + " from VF-C", e);
+            throw fatalFailure(logger, "Unable to query VNF package with " + csarId, e);
         }
         try {
             return downloadCbamVnfPackage(downloadUrl);
         } catch (Exception e) {
-            throw fatalFailure(logger, "Unable to download package from " + downloadUrl + " from VF-C", e);
+            throw fatalFailure(logger, "Unable to download package from " + downloadUrl, e);
         }
     }
 
@@ -99,7 +98,6 @@ public class VfcPackageProvider implements IPackageProvider {
         CloseableHttpResponse response = client.execute(httpget);
         HttpEntity entity = response.getEntity();
         InputStream is = entity.getContent();
-        ByteArrayOutputStream cbamInZip = new ByteArrayOutputStream();
         byte[] bytes = ByteStreams.toByteArray(is);
         client.close();
         return bytes;
index ba17bbf..83b9351 100644 (file)
@@ -37,13 +37,13 @@ public class CbamVnfdBuilder {
      */
     public String build(String cbamVnfdContent) throws IOException {
         JsonObject root = new Gson().toJsonTree(new Yaml().load(cbamVnfdContent)).getAsJsonObject();
-        JsonObject substitution_mappings = child(child(root, "topology_template"), "substitution_mappings");
-        JsonObject extensions = addChild(addChild(addChild(addChild(addChild(substitution_mappings, "capabilities"), "vnf"), "properties"), "modifiable_attributes"), "extensions");
+        JsonObject substitutionMappings = child(child(root, "topology_template"), "substitution_mappings");
+        JsonObject extensions = addChild(addChild(addChild(addChild(addChild(substitutionMappings, "capabilities"), "vnf"), "properties"), "modifiable_attributes"), "extensions");
         JsonObject onapCsarId = addChild(extensions, "onapCsarId");
         onapCsarId.add("default", new JsonPrimitive("kuku"));
         JsonObject vimId = addChild(extensions, "vimId");
         vimId.add("default", new JsonPrimitive("kuku"));
-        JsonObject interfaces = child(substitution_mappings, "interfaces");
+        JsonObject interfaces = child(substitutionMappings, "interfaces");
         JsonObject basic = addChild(interfaces, "Basic");
         addOperationParams(addChild(basic, "instantiate"));
         addOperationParams(addChild(basic, "terminate"));
@@ -60,12 +60,12 @@ public class CbamVnfdBuilder {
     private void addOperationParams(JsonObject operation) {
         JsonObject inputs = addChild(operation, "inputs");
         JsonObject extensions = addChild(inputs, "extensions");
-        JsonArray pre_actions = addChildArray(extensions, "pre_actions");
-        pre_actions.add(addAction("javascript/cbam.pre.collectConnectionPoints.js"));
-        JsonArray post_actions = addChildArray(extensions, "post_actions");
-        post_actions.add(addAction("javascript/cbam.post.collectConnectionPoints.js"));
-        JsonObject additional_parameters = addChild(inputs, "additional_parameters");
-        additional_parameters.addProperty("jobId", "kuku");
+        JsonArray preActions = addChildArray(extensions, "pre_actions");
+        preActions.add(addAction("javascript/cbam.pre.collectConnectionPoints.js"));
+        JsonArray postActions = addChildArray(extensions, "post_actions");
+        postActions.add(addAction("javascript/cbam.post.collectConnectionPoints.js"));
+        JsonObject additionalParameters = addChild(inputs, "additional_parameters");
+        additionalParameters.addProperty("jobId", "kuku");
     }
 
     private JsonElement addAction(String jsAction) {
index f769bec..9fe4a29 100644 (file)
@@ -20,6 +20,7 @@ import com.google.common.io.ByteStreams;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
+import java.io.IOException;
 import java.io.InputStream;
 import java.nio.charset.StandardCharsets;
 import java.util.zip.ZipEntry;
@@ -49,7 +50,7 @@ public class OnapVnfPackageBuilder {
      * @param zip the original CBAM package
      * @return the converted ONAP package
      */
-    public byte[] covert(InputStream zip) throws Exception {
+    public byte[] covert(InputStream zip) throws IOException {
         byte[] cbamVnfPackage = ByteStreams.toByteArray(zip);
         String vnfdLocation = getVnfdLocation(new ByteArrayInputStream(cbamVnfPackage));
         ByteArrayOutputStream vnfdContent = getFileInZip(new ByteArrayInputStream(cbamVnfPackage), vnfdLocation);
@@ -59,7 +60,7 @@ public class OnapVnfPackageBuilder {
         return buildNewOnapPackage(modifiedCbamPackage, onapVnfd);
     }
 
-    private byte[] buildNewOnapPackage(byte[] modifiedCbamPackage, String onapVnfd) throws Exception {
+    private byte[] buildNewOnapPackage(byte[] modifiedCbamPackage, String onapVnfd) throws IOException {
         ByteArrayOutputStream result = new ByteArrayOutputStream();
         ZipOutputStream out = new ZipOutputStream(result);
         out.putNextEntry(new ZipEntry("Artifacts/Deployment/OTHER/cbam.package.zip"));
index d4ff6e4..01256aa 100644 (file)
@@ -20,6 +20,7 @@ import com.google.gson.Gson;
 import com.google.gson.JsonArray;
 import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
+import org.jetbrains.annotations.Nullable;
 import org.yaml.snakeyaml.Yaml;
 
 import java.util.Map;
@@ -34,20 +35,61 @@ import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.childElem
  */
 public class OnapVnfdBuilder {
 
+    public static final String DESCRIPTION = "description";
+    public static final String PROPERTIES = "properties";
+    public static final String REQUIREMENTS = "requirements";
+
+    /**
+     * @param cbamVnfd the CBAM VNFD
+     * @return the converted ONAP VNFD
+     */
+    public String toOnapVnfd(String cbamVnfd) {
+        JsonObject root = new Gson().toJsonTree(new Yaml().load(cbamVnfd)).getAsJsonObject();
+        JsonObject topologyTemplate = child(root, "topology_template");
+        if (topologyTemplate.has("node_templates")) {
+            Set<Map.Entry<String, JsonElement>> nodeTemplates = child(topologyTemplate, "node_templates").entrySet();
+            StringBuilder body = new StringBuilder();
+            for (Map.Entry<String, JsonElement> node : nodeTemplates) {
+                String type = childElement(node.getValue().getAsJsonObject(), "type").getAsString();
+                switch (type) {
+                    case "tosca.nodes.nfv.VDU":
+                        body.append(buildVdu(node.getKey(), node.getValue().getAsJsonObject(), nodeTemplates));
+                        break;
+                    case "tosca.nodes.nfv.VirtualStorage":
+                        body.append(buildVolume(node.getKey(), node.getValue().getAsJsonObject()));
+                        break;
+                    case "tosca.nodes.nfv.VL":
+                        body.append(buildVl(node.getKey()));
+                        break;
+                    case "tosca.nodes.nfv.ICP":
+                        body.append(buildIcp(node.getKey(), node.getValue().getAsJsonObject()));
+                        break;
+                    case "tosca.nodes.nfv.ECP":
+                        body.append(buildEcp(node.getKey(), node.getValue(), nodeTemplates));
+                        break;
+                    default:
+                        //
+                }
+            }
+            return buildHeader(topologyTemplate) + body.toString();
+        }
+        return buildHeader(topologyTemplate);
+    }
+
     private String buildHeader(JsonObject toplogyTemplate) {
-        JsonObject properties = child(child(toplogyTemplate, "substitution_mappings"), "properties");
-        String descriptor_version = properties.get("descriptor_version").getAsString();
+        JsonObject properties = child(child(toplogyTemplate, "substitution_mappings"), PROPERTIES);
+        String descriptorVersion = properties.get("descriptor_version").getAsString();
         return "tosca_definitions_version: tosca_simple_yaml_1_0\n" +
                 "\n" +
                 "metadata:\n" +
                 "  vendor: Nokia\n" +
-                "  csarVersion: " + descriptor_version + "\n" +
+                "  csarVersion: " + descriptorVersion + "\n" +
                 "  csarProvider: " + properties.get("provider").getAsString() + "\n" +
                 "  id: Simple\n" +
                 "  version: " + properties.get("software_version").getAsString() + "\n" +
                 "  csarType: NFAR\n" +
                 "  name: " + properties.get("product_name").getAsString() + "\n" +
-                "  vnfdVersion: " + descriptor_version + "\n\n" +
+                "  vnfdVersion: " + descriptorVersion + "\n\n" +
                 "topology_template:\n" +
                 "  node_templates:\n";
     }
@@ -65,23 +107,23 @@ public class OnapVnfdBuilder {
         String memorySize = "";
         String cpuCount = "";
         StringBuilder body = new StringBuilder();
-        JsonArray vduRequirements = childElement(vdu.getAsJsonObject(), "requirements").getAsJsonArray();
+        JsonArray vduRequirements = childElement(vdu.getAsJsonObject(), REQUIREMENTS).getAsJsonArray();
         for (int i = 0; i < vduRequirements.size(); i++) {
             JsonObject requirement = vduRequirements.get(i).getAsJsonObject();
             Map.Entry<String, JsonElement> next = requirement.entrySet().iterator().next();
-            switch (next.getKey()) {
-                case "virtual_compute":
-                    JsonObject virtualCompute = get(next.getValue().getAsString(), nodes).getAsJsonObject();
-                    cpuCount = childElement(child(child(virtualCompute, "properties"), "virtual_cpu"), "num_virtual_cpu").getAsString();
-                    memorySize = childElement(child(child(virtualCompute, "properties"), "virtual_memory"), "virtual_mem_size").getAsString();
-                    break;
-                case "virtual_storage":
-                    String item =
-                            "        - virtual_storage:\n" +
-                                    "            capability: tosca.capabilities.nfv.VirtualStorage\n" +
-                                    "            node: " + next.getValue().getAsString() + "\n";
-                    body.append(item);
-                    break;
+            String s = next.getKey();
+            if ("virtual_compute".equals(s)) {
+                JsonObject virtualCompute = get(next.getValue().getAsString(), nodes).getAsJsonObject();
+                cpuCount = childElement(child(child(virtualCompute, PROPERTIES), "virtual_cpu"), "num_virtual_cpu").getAsString();
+                memorySize = childElement(child(child(virtualCompute, PROPERTIES), "virtual_memory"), "virtual_mem_size").getAsString();
+
+            } else if ("virtual_storage".equals(s)) {
+                String item =
+                        "        - virtual_storage:\n" +
+                                "            capability: tosca.capabilities.nfv.VirtualStorage\n" +
+                                "            node: " + next.getValue().getAsString() + "\n";
+                body.append(item);
+
             }
             next.getValue();
         }
@@ -94,82 +136,22 @@ public class OnapVnfdBuilder {
                 "              virtual_mem_size: " + memorySize + "\n" +
                 "            virtual_cpu:\n" +
                 "              num_virtual_cpu: " + cpuCount + "\n" +
-                "      requirements:\n";
+                "      " + REQUIREMENTS + ":\n";
         return header + body.toString();
     }
 
-    /**
-     * @param cbamVnfd the CBAM VNFD
-     * @return the converted ONAP VNFD
-     */
-    public String toOnapVnfd(String cbamVnfd) {
-        JsonObject root = new Gson().toJsonTree(new Yaml().load(cbamVnfd)).getAsJsonObject();
-        JsonObject topology_template = child(root, "topology_template");
-        if (topology_template.has("node_templates")) {
-            Set<Map.Entry<String, JsonElement>> node_templates = child(topology_template, "node_templates").entrySet();
-            StringBuilder body = new StringBuilder();
-            for (Map.Entry<String, JsonElement> node : node_templates) {
-                String type = childElement(node.getValue().getAsJsonObject(), "type").getAsString();
-                switch (type) {
-                    case "tosca.nodes.nfv.VDU":
-                        body.append(buildVdu(node.getKey(), node.getValue().getAsJsonObject(), node_templates));
-                        break;
-                    case "tosca.nodes.nfv.VirtualStorage":
-                        body.append(buildVolume(node.getKey(), node.getValue().getAsJsonObject()));
-                        break;
-                    case "tosca.nodes.nfv.VL":
-                        body.append(buildVl(node.getKey()));
-                        break;
-                    case "tosca.nodes.nfv.ICP":
-                        body.append(buildIcp(node.getKey(), node.getValue().getAsJsonObject()));
-                        break;
-                    case "tosca.nodes.nfv.ECP":
-                        body.append(buildEcp(node.getKey(), node.getValue(), node_templates));
-                        break;
-                }
-            }
-            return buildHeader(topology_template) + body.toString();
-        }
-        return buildHeader(topology_template);
-    }
-
     private String buildEcp(String name, JsonElement ecp, Set<Map.Entry<String, JsonElement>> nodes) {
-        if (ecp.getAsJsonObject().has("requirements")) {
-            JsonArray requirements = ecp.getAsJsonObject().get("requirements").getAsJsonArray();
-            String icpName = null;
-            for (int i = 0; i < requirements.size(); i++) {
-                JsonElement requirement = requirements.get(i);
-                Map.Entry<String, JsonElement> next = requirement.getAsJsonObject().entrySet().iterator().next();
-                switch (next.getKey()) {
-                    case "internal_connection_point":
-                        icpName = next.getValue().getAsString();
-
-                }
-            }
+        if (ecp.getAsJsonObject().has(REQUIREMENTS)) {
+            JsonArray requirements = ecp.getAsJsonObject().get(REQUIREMENTS).getAsJsonArray();
+            String icpName = getIcpName(requirements);
             if (icpName != null) {
                 JsonObject icpNode = get(icpName, nodes).getAsJsonObject();
-                String vdu = null;
-                if (icpNode.has("requirements")) {
-                    requirements = icpNode.getAsJsonObject().get("requirements").getAsJsonArray();
-                    for (int i = 0; i < requirements.size(); i++) {
-                        JsonElement requirement = requirements.get(i);
-                        Map.Entry<String, JsonElement> next = requirement.getAsJsonObject().entrySet().iterator().next();
-                        switch (next.getKey()) {
-                            case "virtual_binding":
-                                vdu = next.getValue().getAsString();
-                        }
-                    }
+                if (icpNode.has(REQUIREMENTS)) {
+                    requirements = icpNode.getAsJsonObject().get(REQUIREMENTS).getAsJsonArray();
+                    String vdu = getVdu(requirements);
                     if (vdu != null) {
-                        JsonObject properties = child(icpNode, "properties");
-                        return "    " + name + ":\n" +
-                                "      type: tosca.nodes.nfv.VduCpd\n" +
-                                "      properties:\n" +
-                                "        layer_protocol: " + childElement(properties, "layer_protocol").getAsString() + "\n" +
-                                "        role: leaf\n" +
-                                (properties.has("description") ?
-                                        "        description: " + childElement(properties, "description").getAsString() + "\n" : "") +
-                                "      requirements:\n" +
-                                "        - virtual_binding: " + vdu + "\n";
+                        JsonObject properties = child(icpNode, PROPERTIES);
+                        return buildVduCpd(name, vdu, properties);
                     }
                 }
             }
@@ -177,30 +159,70 @@ public class OnapVnfdBuilder {
         return "";
     }
 
+    @Nullable
+    private String getVdu(JsonArray requirements) {
+        String vdu = null;
+        for (int i = 0; i < requirements.size(); i++) {
+            JsonElement requirement = requirements.get(i);
+            Map.Entry<String, JsonElement> next = requirement.getAsJsonObject().entrySet().iterator().next();
+            String s = next.getKey();
+            if ("virtual_binding".equals(s)) {
+                vdu = next.getValue().getAsString();
+            }
+        }
+        return vdu;
+    }
+
+    @Nullable
+    private String getIcpName(JsonArray requirements) {
+        String icpName = null;
+        for (int i = 0; i < requirements.size(); i++) {
+            JsonElement requirement = requirements.get(i);
+            Map.Entry<String, JsonElement> next = requirement.getAsJsonObject().entrySet().iterator().next();
+            String s = next.getKey();
+            if ("internal_connection_point".equals(s)) {
+                icpName = next.getValue().getAsString();
+            }
+        }
+        return icpName;
+    }
+
+    private String buildVduCpd(String name, String vdu, JsonObject properties) {
+        return "    " + name + ":\n" +
+                "      type: tosca.nodes.nfv.VduCpd\n" +
+                "      " + PROPERTIES + ":\n" +
+                "        layer_protocol: " + childElement(properties, "layer_protocol").getAsString() + "\n" +
+                "        role: leaf\n" +
+                (properties.has(DESCRIPTION) ?
+                        "        description: " + childElement(properties, DESCRIPTION).getAsString() + "\n" : "") +
+                "      requirements:\n" +
+                "        - virtual_binding: " + vdu + "\n";
+    }
+
     private String buildIcp(String name, JsonObject icp) {
-        if (icp.has("requirements")) {
-            JsonArray requirements = icp.get("requirements").getAsJsonArray();
+        if (icp.has(REQUIREMENTS)) {
+            JsonArray requirements = icp.get(REQUIREMENTS).getAsJsonArray();
             String vdu = null;
             String vl = null;
             for (int i = 0; i < requirements.size(); i++) {
                 JsonElement requirement = requirements.get(i);
                 Map.Entry<String, JsonElement> next = requirement.getAsJsonObject().entrySet().iterator().next();
-                switch (next.getKey()) {
-                    case "virtual_binding":
-                        vdu = next.getValue().getAsString();
-                    case "virtual_link":
-                        vl = next.getValue().getAsString();
-                        break;
+                String s = next.getKey();
+                if ("virtual_binding".equals(s)) {
+                    vdu = next.getValue().getAsString();
+
+                } else if ("virtual_link".equals(s)) {
+                    vl = next.getValue().getAsString();
                 }
             }
             if (vdu != null && vl != null) {
-                JsonObject properties = child(icp, "properties");
+                JsonObject properties = child(icp, PROPERTIES);
                 return "    " + name + ":\n" +
                         "      type: tosca.nodes.nfv.VduCpd\n" +
-                        "      properties:\n" +
+                        "      " + PROPERTIES + ":\n" +
                         "        layer_protocol: " + childElement(properties, "layer_protocol").getAsString() + "\n" +
-                        "        role: leaf\n" + (properties.has("description") ?
-                        "        description: " + childElement(properties, "description").getAsString() + "\n" : "") +
+                        "        role: leaf\n" + (properties.has(DESCRIPTION) ?
+                        "        description: " + childElement(properties, DESCRIPTION).getAsString() + "\n" : "") +
                         "      requirements:\n" +
                         "        - virtual_binding: " + vdu + "\n" +
                         "        - virtual_link: " + vl + "\n";
@@ -215,7 +237,7 @@ public class OnapVnfdBuilder {
                 "      properties:\n" +
                 "        id: " + nodeName + "\n" +
                 "        type_of_storage: volume\n" +
-                "        size_of_storage: " + childElement(child(volume, "properties"), "size_of_storage").getAsString() + "\n";
+                "        size_of_storage: " + childElement(child(volume, PROPERTIES), "size_of_storage").getAsString() + "\n";
     }
 
     private String buildVl(String name) {
index 4a73748..6af13c5 100644 (file)
  */
 package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.restapi;
 
-import org.apache.http.entity.ContentType;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.packagetransformer.OnapVnfPackageBuilder;
 import org.slf4j.Logger;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpStatus;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.ResponseBody;
@@ -27,16 +24,13 @@ import org.springframework.web.bind.annotation.ResponseBody;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.Part;
-
 import java.io.IOException;
 
 import static org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.SystemFunctions.systemFunctions;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.DriverProperties.BASE_URL;
 import static org.slf4j.LoggerFactory.getLogger;
-import static org.springframework.http.HttpHeaders.CONTENT_DISPOSITION;
-import static org.springframework.http.HttpHeaders.CONTENT_LENGTH;
-import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
+import static org.springframework.http.HttpHeaders.*;
 import static org.springframework.http.HttpStatus.OK;
 import static org.springframework.http.MediaType.TEXT_HTML_VALUE;
 import static org.springframework.web.bind.annotation.RequestMethod.GET;
index 883c270..df871b0 100644 (file)
@@ -28,7 +28,7 @@ import org.springframework.web.bind.annotation.ResponseStatus;
 import javax.servlet.http.HttpServletResponse;
 
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.DriverProperties.BASE_URL;
-import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.DriverProperties.LCN_PATH;
+import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.DriverProperties.LCN_URL;
 import static org.slf4j.LoggerFactory.getLogger;
 import static org.springframework.http.HttpStatus.NO_CONTENT;
 import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@@ -54,7 +54,7 @@ public class LcnApi {
      *
      * @param httpResponse the HTTP response
      */
-    @RequestMapping(value = LCN_PATH, method = GET)
+    @RequestMapping(value = LCN_URL, method = GET)
     public void testLcnConnectivity(HttpServletResponse httpResponse) {
         //used to test connectivity from CBAM to driver
     }
@@ -65,7 +65,7 @@ public class LcnApi {
      * @param lcn          the LCN notification
      * @param httpResponse the HTTP response
      */
-    @RequestMapping(value = LCN_PATH, method = POST, consumes = APPLICATION_JSON_VALUE)
+    @RequestMapping(value = LCN_URL, method = POST, consumes = APPLICATION_JSON_VALUE)
     @ResponseBody
     @ResponseStatus(code = NO_CONTENT)
     public void handleLcn(@RequestBody VnfLifecycleChangeNotification lcn, HttpServletResponse httpResponse) {
index 659e82f..15c8dc3 100644 (file)
@@ -18,14 +18,11 @@ package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.restapi;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.onap.core.SelfRegistrationManager;
 import org.slf4j.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.MediaType;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.ResponseBody;
 
 import javax.servlet.http.HttpServletResponse;
-
 import java.io.IOException;
 
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.DriverProperties.BASE_URL;
index 0554cbe..defa340 100644 (file)
@@ -29,21 +29,24 @@ import static com.google.common.collect.Sets.newHashSet;
  * Collects the possibilities of sources
  */
 public class Conditions {
-
     private static final String USE_DIRECT_INTEGRATION = "direct";
 
-    private static Set<Condition> getAllSources() {
-        return newHashSet(new UseForVfc(), new UseForDirect());
+    private Conditions() {
+        //use static way
     }
 
     /**
      * Represents the condition for using VF-C
      */
     public static class UseForVfc implements Condition {
+        private static Set<Condition> getAllSources() {
+            return newHashSet(new UseForVfc(), new UseForDirect());
+        }
+
         @Override
         public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
             boolean anyOtherSourceAvailable = false;
-            for (Condition condition : Conditions.getAllSources()) {
+            for (Condition condition : UseForVfc.getAllSources()) {
                 if (!(condition instanceof UseForVfc) && condition.matches(conditionContext, annotatedTypeMetadata)) {
                     anyOtherSourceAvailable = true;
                 }
index ebd4234..3bd715e 100644 (file)
@@ -25,14 +25,10 @@ import org.slf4j.Logger;
  */
 public class CbamUtils {
 
-    private static class OperationMustBeAborted extends RuntimeException{
-        OperationMustBeAborted(String msg){
-            super(msg);
-        }
-        OperationMustBeAborted(Exception e, String msg){
-            super(msg, e);
-        }
-    }
+    /**
+     * Separator for multiple keys concatenated into a single string
+     */
+    public static final String SEPARATOR = "_";
 
     private CbamUtils() {
         //use static way
@@ -84,4 +80,14 @@ public class CbamUtils {
         logger.error(msg);
         throw new OperationMustBeAborted(msg);
     }
+
+    private static class OperationMustBeAborted extends RuntimeException {
+        OperationMustBeAborted(String msg) {
+            super(msg);
+        }
+
+        OperationMustBeAborted(Exception e, String msg) {
+            super(msg, e);
+        }
+    }
 }
index 249925e..71ddd4e 100644 (file)
@@ -18,7 +18,6 @@ package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util;
 
 import org.apache.commons.codec.binary.Base64;
 
-import javax.swing.text.html.Option;
 import java.io.ByteArrayInputStream;
 import java.io.InputStream;
 import java.security.KeyFactory;
@@ -124,7 +123,7 @@ public final class StoreLoader {
             }
             return ks;
         } catch (Exception e) {
-            throw new RuntimeException("Unable to create keystore", e);
+            throw new UserInvisibleError("Unable to create keystore", e);
         }
     }
 
@@ -142,7 +141,7 @@ public final class StoreLoader {
             throw fatalFailure(logger, "Unable to load certificates", e);
         }
 
-        if (certificates.size() > 0) {
+        if (!certificates.isEmpty()) {
             return of(certificates.toArray(new Certificate[certificates.size()]));
         } else {
             return empty();
index 805be64..b8c50b1 100644 (file)
@@ -57,7 +57,7 @@ public class SystemFunctions {
             Thread.sleep(millis);
         } catch (InterruptedException e) {
             Thread.currentThread().interrupt();
-            throw new RuntimeException(e);
+            throw new UserInvisibleError("Interrupted while sleep", e);
         }
     }
 
@@ -92,7 +92,7 @@ public class SystemFunctions {
             InputStream stream = SystemFunctions.class.getClassLoader().getResourceAsStream(url);
             return ByteStreams.toByteArray(stream);
         } catch (Exception e) {
-            throw new RuntimeException("Unable to load " + url, e);
+            throw new UserVisibleError("Unable to load " + url, e);
         }
     }
 
@@ -108,8 +108,9 @@ public class SystemFunctions {
      * variable <code>out</code>, has been redirected to a file or other
      * destination that is typically not continuously monitored.
      */
+    @SuppressWarnings("squid:S106") // (intentional wrapping of system err)
     public PrintStream err() {
-        return System.err; //NO SONAR (intentional wrapping of system err
+        return System.err;
     }
 
     /**
@@ -137,8 +138,9 @@ public class SystemFunctions {
      * @see java.io.PrintStream#println(java.lang.Object)
      * @see java.io.PrintStream#println(java.lang.String)
      */
+    @SuppressWarnings("squid:S106") // (intentional wrapping of system err)
     public PrintStream out() {
-        return System.out; //NO SONAR (intentional wrapping of system out)
+        return System.out;
     }
 
     /**
diff --git a/nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/UserInvisibleError.java b/nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/UserInvisibleError.java
new file mode 100644 (file)
index 0000000..95e6425
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2016-2017, Nokia Corporation
+ *
+ * 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.
+ */
+
+package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util;
+
+/**
+ * Represents an error that should not be visible for the end user
+ * using the REST API
+ */
+public class UserInvisibleError extends RuntimeException {
+
+    /**
+     * @param message the error message
+     */
+    public UserInvisibleError(String message) {
+        super(message);
+    }
+
+    /**
+     * @param message the error message
+     * @param cause   the cause of the error
+     */
+    public UserInvisibleError(String message, Exception cause) {
+        super(message, cause);
+    }
+}
diff --git a/nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/UserVisibleError.java b/nokiav2/driver/src/main/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/UserVisibleError.java
new file mode 100644 (file)
index 0000000..afc5430
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2016-2017, Nokia Corporation
+ *
+ * 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.
+ */
+
+package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util;
+
+/**
+ * Represents an error that is meaningful for an end user
+ * using the REST interface
+ */
+public class UserVisibleError extends RuntimeException {
+
+    /**
+     * @param message the error message
+     */
+    public UserVisibleError(String message) {
+        super(message);
+    }
+
+    /**
+     * @param message the error message
+     * @param cause   the cause of the error
+     */
+    public UserVisibleError(String message, Exception cause) {
+        super(message, cause);
+    }
+}
index 414c013..3396d76 100644 (file)
@@ -21,7 +21,6 @@ import com.nokia.cbam.catalog.v1.ApiException;
 import com.nokia.cbam.catalog.v1.api.DefaultApi;
 import com.nokia.cbam.catalog.v1.model.CatalogAdapterVnfpackage;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.api.IPackageProvider;
-import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.onap.vfc.VfcPackageProvider;
 import org.slf4j.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
@@ -49,6 +48,10 @@ import static org.slf4j.LoggerFactory.getLogger;
  */
 @Component
 public class CatalogManager {
+    /**
+     * The location of the CBAM package within the ONAP package
+     */
+    public static final String CBAM_PACKAGE_NAME_IN_ZIP = "Artifacts/Deployment/OTHER/cbam.package.zip";
     private static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta";
     private static final String TOSCA_VNFD_KEY = "Entry-Definitions";
     private static Logger logger = getLogger(CatalogManager.class);
@@ -94,7 +97,7 @@ public class CatalogManager {
                 return byteArrayOutputStream;
             }
         }
-        logger.error("Unable to find the " + path + " in archive found: " + items);
+        logger.error("Unable to find the {} in archive found: {}", path, items);
         throw new NoSuchElementException("Unable to find the " + path + " in archive found: " + items);
     }
 
@@ -111,7 +114,7 @@ public class CatalogManager {
         if (!isPackageReplicated(cbamVnfdId, cbamCatalogApi)) {
             try {
                 Path tempFile = createTempFile("cbam", "zip");
-                ByteArrayOutputStream cbamPackage = getFileInZip(new ByteArrayInputStream(packageProvider.getPackage(csarId)), VfcPackageProvider.CBAM_PACKAGE_NAME_IN_ZIP);
+                ByteArrayOutputStream cbamPackage = getFileInZip(new ByteArrayInputStream(packageProvider.getPackage(csarId)), CBAM_PACKAGE_NAME_IN_ZIP);
                 write(tempFile, cbamPackage.toByteArray());
                 //FIXME delete file
                 return cbamCatalogApi.create(tempFile.toFile());
@@ -139,7 +142,6 @@ public class CatalogManager {
      */
     public String getCbamVnfdContent(String vnfmId, String vnfdId) {
         try {
-            DefaultApi cbamCatalogApi = cbamRestApiProvider.getCbamCatalogApi(vnfmId);
             File content = cbamRestApiProvider.getCbamCatalogApi(vnfmId).content(vnfdId);
             String vnfdPath = getVnfdLocation(new FileInputStream(content));
             return new String(getFileInZip(new FileInputStream(content), vnfdPath).toByteArray());
index e49c572..e32ee6b 100644 (file)
@@ -25,6 +25,7 @@ import org.apache.http.conn.ssl.DefaultHostnameVerifier;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.api.VnfmInfoProvider;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.StoreLoader;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.SystemFunctions;
+import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.UserVisibleError;
 import org.onap.vnfmdriver.model.VnfmInfo;
 import org.slf4j.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -38,9 +39,10 @@ import java.nio.charset.StandardCharsets;
 import java.security.*;
 import java.security.cert.CertificateException;
 import java.security.cert.X509Certificate;
-import java.security.spec.InvalidKeySpecException;
 import java.util.Set;
 
+import static java.util.UUID.randomUUID;
+import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.fatalFailure;
 import static org.slf4j.LoggerFactory.getLogger;
 import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
 import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE;
@@ -51,7 +53,9 @@ import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VAL
 @Component
 public class CbamTokenProvider {
     public static final int MAX_RETRY_COUNT = 5;
-    private static final String CBAM_TOKEN_PATH = "/realms/cbam/protocol/openid-connect/token";
+    public static final String GRANT_TYPE = "password";
+    public static final String CLIENT_SECRET = "password";
+    private static final String CBAM_TOKEN_URL = "/realms/cbam/protocol/openid-connect/token";
     private static Logger logger = getLogger(CbamTokenProvider.class);
     private final VnfmInfoProvider vnfmInfoProvider;
     @Value("${cbamKeyCloakBaseUrl}")
@@ -89,26 +93,24 @@ public class CbamTokenProvider {
                 if (token == null) {
                     logger.debug("No token: getting first token");
                 } else {
-                    logger.debug("Token expired " + (now - token.refreshAfter) + " ms ago");
+                    logger.debug("Token expired {} ms ago", (now - token.refreshAfter));
                 }
                 refresh(clientId, clientSecret);
             } else {
-                logger.debug("Token will expire in " + (now - token.refreshAfter) + " ms");
+                logger.debug("Token will expire in {} ms", (now - token.refreshAfter));
             }
         }
         return token.token.accessToken;
     }
 
-    ;
-
     private void refresh(String clientId, String clientSecret) {
         FormBody body = new FormBody.Builder()
-                .add("grant_type", "password")
+                .add("grant_type", GRANT_TYPE)
                 .add("client_id", clientId)
                 .add("client_secret", clientSecret)
                 .add("username", username)
-                .add("password", password).build();
-        Request request = new Request.Builder().url(cbamKeyCloakBaseUrl + CBAM_TOKEN_PATH).addHeader(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE).post(body).build();
+                .add(CLIENT_SECRET, password).build();
+        Request request = new Request.Builder().url(cbamKeyCloakBaseUrl + CBAM_TOKEN_URL).addHeader(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE).post(body).build();
         OkHttpClient.Builder builder = new OkHttpClient.Builder();
         SSLSocketFactory sslSocketFac = buildSSLSocketFactory();
         HostnameVerifier hostnameVerifier = buildHostnameVerifier();
@@ -124,15 +126,14 @@ public class CbamTokenProvider {
                     token = new CurrentToken(tokenResponse, getTokenRefreshTime(tokenResponse));
                     return;
                 } else {
-                    throw new RuntimeException();
+                    fatalFailure(logger, "Bad response from CBAM KeyStone");
                 }
             } catch (Exception e) {
                 lastException = e;
                 logger.warn("Unable to get token to access CBAM API (" + (i + 1) + "/" + MAX_RETRY_COUNT + ")", e);
             }
         }
-        logger.error("Unable to get token to access CBAM API (giving up retries)", lastException);
-        throw new RuntimeException(lastException);
+        throw fatalFailure(logger, "Unable to get token to access CBAM API (giving up retries)", lastException);
     }
 
     @VisibleForTesting
@@ -153,12 +154,7 @@ public class CbamTokenProvider {
 
     private HostnameVerifier buildHostnameVerifier() {
         if (skipHostnameVerification) {
-            return new HostnameVerifier() {
-                @Override
-                public boolean verify(String hostname, SSLSession session) {
-                    return true;
-                }
-            };
+            return (hostname, session) -> true;
         } else {
             return new DefaultHostnameVerifier();
         }
@@ -172,13 +168,12 @@ public class CbamTokenProvider {
             sslContext.init(null, trustManagers, new SecureRandom());
             return sslContext.getSocketFactory();
         } catch (GeneralSecurityException e) {
-            logger.error("Unable to create SSL socket factory", e);
-            throw new RuntimeException(e);
+            throw fatalFailure(logger, "Unable to create SSL socket factory", e);
         }
     }
 
     @VisibleForTesting
-    TrustManager[] buildTrustManager() throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
+    TrustManager[] buildTrustManager() throws KeyStoreException, NoSuchAlgorithmException {
         if (skipCertificateVerification) {
             return new TrustManager[]{new AllTrustedTrustManager()};
         } else {
@@ -189,9 +184,9 @@ public class CbamTokenProvider {
             try {
                 trustedPems = StoreLoader.getCertifacates(new String(BaseEncoding.base64().decode(trustedCertificates), StandardCharsets.UTF_8));
             } catch (Exception e) {
-                throw new RuntimeException("The trustedCertificates must be a base64 encoded collection of PEM certificates", e);
+                throw new UserVisibleError("The trustedCertificates must be a base64 encoded collection of PEM certificates", e);
             }
-            KeyStore keyStore = StoreLoader.loadStore(Joiner.on("\n").join(trustedPems), "password", "password");
+            KeyStore keyStore = StoreLoader.loadStore(Joiner.on("\n").join(trustedPems), randomUUID().toString(), randomUUID().toString());
             TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
             trustManagerFactory.init(keyStore);
             return trustManagerFactory.getTrustManagers();
@@ -212,11 +207,12 @@ public class CbamTokenProvider {
     static class AllTrustedTrustManager implements X509TrustManager {
         @Override
         public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
-
+            //no need to check certificates if everything is trusted
         }
 
         @Override
         public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+            //no need to check certificates if everything is trusted
         }
 
         @Override
@@ -228,7 +224,6 @@ public class CbamTokenProvider {
     /**
      * Represents the token received from CBAM
      */
-    //FIXME use authentication swagger client instead
     private static class TokenResponse {
         @SerializedName("access_token")
         String accessToken;
index dfa674b..3f50bcc 100644 (file)
@@ -29,7 +29,7 @@ import java.util.Objects;
 public class DriverProperties {
     public static final String BASE_SUFFIX = "/" + SelfRegistrationManager.SERVICE_NAME + "/v1";
     public static final String BASE_URL = "/api" + BASE_SUFFIX;
-    public static final String LCN_PATH = "/lcn";
+    public static final String LCN_URL = "/lcn";
 
     @Value("${cbamCatalogUrl}")
     private String cbamCatalogUrl;
index daf16fc..723bfb4 100644 (file)
@@ -23,15 +23,6 @@ import com.nokia.cbam.lcm.v32.model.VnfLifecycleChangeNotification;
  * Responsible for handling CBAM notifications
  */
 public interface ILifecycleChangeNotificationManager {
-    /**
-     * The key of the CBAM VNF extension for the identifier of the VNFM in ONAP
-     */
-    String EXTERNAL_VNFM_ID = "externalVnfmId";
-
-    /**
-     * Separator for multiple keys concatenated into a single string
-     */
-    String SEPARATOR = "_";
 
     /**
      * Order the operations by start time (latest first)
index d6b1cb2..5a21225 100644 (file)
@@ -43,10 +43,10 @@ import static com.google.common.collect.Iterables.tryFind;
 import static com.google.common.collect.Lists.newArrayList;
 import static java.util.Optional.empty;
 import static java.util.Optional.of;
+import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.SEPARATOR;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.fatalFailure;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.SystemFunctions.systemFunctions;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCM_API_VERSION;
-import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.ILifecycleChangeNotificationManager.SEPARATOR;
 import static org.slf4j.LoggerFactory.getLogger;
 import static org.springframework.util.StringUtils.isEmpty;
 
@@ -58,6 +58,7 @@ import static org.springframework.util.StringUtils.isEmpty;
  */
 @Component
 public class JobManager {
+    public static final String OPERATION_STARTED_DESCRIPTION = "Operation started";
     private static final Ordering<JobResponseInfo> OLDEST_FIRST = new Ordering<JobResponseInfo>() {
         @Override
         public int compare(JobResponseInfo left, JobResponseInfo right) {
@@ -130,7 +131,7 @@ public class JobManager {
      * @return the system has any ongoing jobs
      */
     public boolean hasOngoingJobs() {
-        return ongoingJobs.size() != 0;
+        return !ongoingJobs.isEmpty();
     }
 
 
@@ -155,7 +156,7 @@ public class JobManager {
      * @return detailed information of the job
      */
     public JobDetailInfo getJob(String vnfmId, String jobId) {
-        logger.debug("Retrieving the details for job with " + jobId);
+        logger.debug("Retrieving the details for job with {} identifier", jobId);
         ArrayList<String> jobParts = newArrayList(on(SEPARATOR).split(jobId));
         if (jobParts.size() != 2) {
             throw new IllegalArgumentException("The jobId should be in the <vnfId>" + SEPARATOR + "<UUID> format, but was " + jobId);
@@ -172,7 +173,7 @@ public class JobManager {
         if (!vnf.isPresent()) {
             return getJobDetailInfoForMissingVnf(jobId);
         } else {
-            return getJobInfoForExistingVnf(vnfmId, jobId, vnfId, vnf);
+            return getJobInfoForExistingVnf(vnfmId, jobId, vnfId, vnf.get());
         }
     }
 
@@ -184,34 +185,10 @@ public class JobManager {
         }
     }
 
-    private JobDetailInfo getJobInfoForExistingVnf(String vnfmId, String jobId, String vnfId, Optional<VnfInfo> vnf) {
+    private JobDetailInfo getJobInfoForExistingVnf(String vnfmId, String jobId, String vnfId, VnfInfo vnf) {
         try {
             OperationExecution operation = findOperationByJobId(vnfmId, vnf, jobId);
-            switch (operation.getStatus()) {
-                case STARTED:
-                    return reportOngoing(jobId);
-                case FINISHED:
-                case OTHER:
-                    switch (operation.getOperationType()) {
-                        case TERMINATE:
-                            //termination includes VNF deletion in ONAP terminology
-                            if (ongoingJobs.contains(jobId)) {
-                                return reportOngoing(jobId);
-                            } else {
-                                //the VNF must be queried again since it could have been deleted since the VNF has been terminated
-                                if (getVnf(vnfmId, vnfId).isPresent()) {
-                                    return reportFailed(jobId, "unable to delete VNF");
-                                } else {
-                                    return reportFinished(jobId);
-                                }
-                            }
-                        default:
-                            return reportFinished(jobId);
-                    }
-                default: //all cases handled
-                case FAILED:
-                    return reportFailed(jobId, operation.getError().getTitle() + ": " + operation.getError().getDetail());
-            }
+            return getJobDetailInfo(vnfmId, jobId, vnfId, operation);
         } catch (NoSuchElementException e) {
             if (ongoingJobs.contains(jobId)) {
                 return reportOngoing(jobId);
@@ -221,6 +198,33 @@ public class JobManager {
         }
     }
 
+    private JobDetailInfo getJobDetailInfo(String vnfmId, String jobId, String vnfId, OperationExecution operation) {
+        switch (operation.getStatus()) {
+            case STARTED:
+                return reportOngoing(jobId);
+            case FINISHED:
+            case OTHER:
+                //termination includes VNF deletion in ONAP terminology
+                if (operation.getOperationType() == com.nokia.cbam.lcm.v32.model.OperationType.TERMINATE) {
+                    if (ongoingJobs.contains(jobId)) {
+                        return reportOngoing(jobId);
+                    } else {
+                        //the VNF must be queried again since it could have been deleted since the VNF has been terminated
+                        if (getVnf(vnfmId, vnfId).isPresent()) {
+                            return reportFailed(jobId, "unable to delete VNF");
+                        } else {
+                            return reportFinished(jobId);
+                        }
+                    }
+                } else {
+                    return reportFinished(jobId);
+                }
+            case FAILED:
+            default: //all cases handled
+                return reportFailed(jobId, operation.getError().getTitle() + ": " + operation.getError().getDetail());
+        }
+    }
+
     private JobDetailInfo buildJob(String jobId, JobResponseInfo... history) {
         JobDetailInfo job = new JobDetailInfo();
         job.setJobId(jobId);
@@ -247,37 +251,36 @@ public class JobManager {
     }
 
     private JobDetailInfo reportOngoing(String jobId) {
-        return buildJob(jobId, buildJobPart("Operation started", JobStatus.STARTED, 50, 1));
+        return buildJob(jobId, buildJobPart(OPERATION_STARTED_DESCRIPTION, JobStatus.STARTED, 50, 1));
     }
 
     private JobDetailInfo reportFailed(String jobId, String reason) {
         return buildJob(jobId,
-                buildJobPart("Operation started", JobStatus.STARTED, 50, 1),
+                buildJobPart(OPERATION_STARTED_DESCRIPTION, JobStatus.STARTED, 50, 1),
                 buildJobPart("Operation failed due to " + reason, JobStatus.ERROR, 100, 2)
         );
     }
 
     private JobDetailInfo reportFinished(String jobId) {
         return buildJob(jobId,
-                buildJobPart("Operation started", JobStatus.STARTED, 50, 1),
+                buildJobPart(OPERATION_STARTED_DESCRIPTION, JobStatus.STARTED, 50, 1),
                 buildJobPart("Operation finished", JobStatus.FINISHED, 100, 2)
         );
     }
 
-    private OperationExecution findOperationByJobId(String vnfmId, Optional<VnfInfo> vnf, String jobId) {
+    private OperationExecution findOperationByJobId(String vnfmId, VnfInfo vnf, String jobId) {
         OperationExecutionsApi cbamOperationExecutionApi = cbamRestApiProvider.getCbamOperationExecutionApi(vnfmId);
         //the operations are sorted so that the newest operations are queried first
         //performance optimization that usually the core system is interested in the operations executed last
-        if (vnf.get().getOperationExecutions() != null) {
-            for (OperationExecution operationExecution : LifecycleChangeNotificationManager.NEWEST_OPERATIONS_FIRST.sortedCopy(vnf.get().getOperationExecutions())) {
+        if (vnf.getOperationExecutions() != null) {
+            for (OperationExecution operationExecution : LifecycleChangeNotificationManager.NEWEST_OPERATIONS_FIRST.sortedCopy(vnf.getOperationExecutions())) {
                 try {
                     Object operationParams = cbamOperationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(operationExecution.getId(), NOKIA_LCM_API_VERSION);
                     if (extractOnapJobId(operationParams).equals(jobId)) {
                         return operationExecution;
                     }
                 } catch (ApiException e) {
-                    logger.error("Unable to retrieve operation parameters", e);
-                    throw new RuntimeException(e);
+                    fatalFailure(logger, "Unable to retrieve operation parameters", e);
                 }
             }
         }
@@ -292,17 +295,15 @@ public class JobManager {
             List<VnfInfo> vnfs = cbamLcmApi.vnfsGet(NOKIA_LCM_API_VERSION);
             com.google.common.base.Optional<VnfInfo> vnf = tryFind(vnfs, vnfInfo -> vnfId.equals(vnfInfo.getId()));
             if (!vnf.isPresent()) {
-                logger.debug("VNF with " + vnfId + " is missing");
+                logger.debug("VNF with {} identifier is missing", vnfId);
                 return empty();
             } else {
-                logger.debug("VNF with " + vnfId + " still exists");
+                logger.debug("VNF with {} identifier still exists", vnfId);
                 //query the VNF again to get operation execution result
                 return of(cbamLcmApi.vnfsVnfInstanceIdGet(vnfId, NOKIA_LCM_API_VERSION));
             }
         } catch (ApiException e) {
-            logger.error("Unable to retrieve VNF", e);
-            throw new RuntimeException(e);
+            throw fatalFailure(logger, "Unable to retrieve VNF", e);
         }
     }
-
 }
index e835e35..e0ee8f8 100644 (file)
@@ -27,6 +27,7 @@ import com.nokia.cbam.lcm.v32.model.ScaleDirection;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.api.IGrantManager;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.api.VimInfoProvider;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.StoreLoader;
+import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.UserVisibleError;
 import org.onap.vnfmdriver.model.ExtVirtualLinkInfo;
 import org.onap.vnfmdriver.model.*;
 import org.onap.vnfmdriver.model.VimInfo;
@@ -44,6 +45,9 @@ import java.util.concurrent.Executors;
 import static com.google.common.base.Splitter.on;
 import static com.google.common.collect.Iterables.find;
 import static com.google.common.collect.Lists.newArrayList;
+import static com.google.common.collect.Sets.newHashSet;
+import static com.nokia.cbam.lcm.v32.model.InstantiationState.INSTANTIATED;
+import static com.nokia.cbam.lcm.v32.model.OperationStatus.FINISHED;
 import static com.nokia.cbam.lcm.v32.model.OperationType.INSTANTIATE;
 import static com.nokia.cbam.lcm.v32.model.VimInfo.VimInfoTypeEnum.*;
 import static java.lang.Integer.parseInt;
@@ -51,7 +55,7 @@ import static java.nio.charset.StandardCharsets.UTF_8;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.*;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.SystemFunctions.systemFunctions;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCM_API_VERSION;
-import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.ILifecycleChangeNotificationManager.*;
+import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.ILifecycleChangeNotificationManager.NEWEST_OPERATIONS_FIRST;
 import static org.slf4j.LoggerFactory.getLogger;
 import static org.springframework.util.StringUtils.isEmpty;
 
@@ -62,6 +66,10 @@ import static org.springframework.util.StringUtils.isEmpty;
 public class LifecycleManager {
     public static final String ONAP_CSAR_ID = "onapCsarId";
     public static final long OPERATION_STATUS_POLLING_INTERVAL_IN_MS = 5000L;
+    /**
+     * The key of the CBAM VNF extension for the identifier of the VNFM in ONAP
+     */
+    public static final String EXTERNAL_VNFM_ID = "externalVnfmId";
     private static Logger logger = getLogger(LifecycleManager.class);
     private final CatalogManager catalogManager;
     private final IGrantManager grantManager;
@@ -121,7 +129,9 @@ public class LifecycleManager {
      * @return the instantiation response
      */
     public VnfInstantiateResponse instantiate(String vnfmId, VnfInstantiateRequest request, HttpServletResponse httpResponse) {
-        logger.info("Additional parameters for instantiation: " + new Gson().toJson(request.getAdditionalParam()));
+        if (logger.isDebugEnabled()) {
+            logger.debug("Additional parameters for instantiation: {}", new Gson().toJson(request.getAdditionalParam()));
+        }
         AdditionalParams additionalParams = convertInstantiationAdditionalParams(request.getVnfPackageId(), request.getAdditionalParam());
         validateVimType(additionalParams);
         CatalogAdapterVnfpackage cbamPackage = catalogManager.preparePackageInCbam(vnfmId, request.getVnfPackageId());
@@ -133,49 +143,11 @@ public class LifecycleManager {
             com.nokia.cbam.lcm.v32.model.VnfInfo vnfInfo = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsPost(vnfCreateRequest, NOKIA_LCM_API_VERSION);
             VnfInstantiateResponse response = new VnfInstantiateResponse();
             response.setVnfInstanceId(vnfInfo.getId());
-            //FIXME the vimId should be send during grant response (VFC-604)
             String vimId = getVimId(request.getAdditionalParam());
             addVnfdIdToVnfModifyableAttributeExtensions(vnfmId, vnfInfo.getId(), request.getVnfPackageId());
-            JobInfo spawnJob = scheduleExecution(vnfInfo.getId(), httpResponse, "instantiate", (jobInfo) -> {
-                String vnfdContent = catalogManager.getCbamVnfdContent(vnfmId, cbamPackage.getId());
-                GrantVNFResponseVim vim = grantManager.requestGrantForInstantiate(vnfmId, vnfInfo.getId(), vimId, request.getVnfPackageId(), additionalParams.getInstantiationLevel(), vnfdContent, jobInfo.getJobId());
-                if (vim.getVimId() == null) {
-                    fatalFailure(logger, "VF-C did not send VIM identifier in grant response");
-                }
-                VimInfo vimInfo = vimInfoProvider.getVimInfo(vim.getVimId());
-                InstantiateVnfRequest instantiationRequest = new InstantiateVnfRequest();
-                addExernalLinksToRequest(request.getExtVirtualLink(), additionalParams, instantiationRequest, vimId);
-                switch (additionalParams.getVimType()) {
-                    case OPENSTACK_V2_INFO:
-                        instantiationRequest.getVims().add(buildOpenStackV2INFO(vimId, vim, vimInfo));
-                        break;
-                    case OPENSTACK_V3_INFO:
-                        instantiationRequest.getVims().add(buildOpenStackV3INFO(vimId, additionalParams, vim, vimInfo));
-                        break;
-                    case VMWARE_VCLOUD_INFO:
-                        instantiationRequest.getVims().add(buildVcloudInfo(vimId, vim, vimInfo));
-                        break;
-                }
-                instantiationRequest.setFlavourId(getFlavorId(vnfdContent));
-                instantiationRequest.setComputeResourceFlavours(additionalParams.getComputeResourceFlavours());
-                instantiationRequest.setGrantlessMode(true);
-                instantiationRequest.setInstantiationLevelId(additionalParams.getInstantiationLevel());
-                instantiationRequest.setSoftwareImages(additionalParams.getSoftwareImages());
-                instantiationRequest.setZones(additionalParams.getZones());
-                instantiationRequest.setExtManagedVirtualLinks(additionalParams.getExtManagedVirtualLinks());
-                for (ExtVirtualLinkData extVirtualLinkData : additionalParams.getExtVirtualLinks()) {
-                    instantiationRequest.addExtVirtualLinksItem(extVirtualLinkData);
-                }
-                JsonObject root = new Gson().toJsonTree(jobInfo).getAsJsonObject();
-                if (additionalParams.getAdditionalParams() != null && !isEmpty(additionalParams.getAdditionalParams().toString())) {
-                    for (Map.Entry<String, JsonElement> item : new Gson().toJsonTree(additionalParams.getAdditionalParams()).getAsJsonObject().entrySet()) {
-                        root.add(item.getKey(), item.getValue());
-                    }
-                }
-                instantiationRequest.setAdditionalParams(root);
-                OperationExecution operationExecution = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdInstantiatePost(vnfInfo.getId(), instantiationRequest, NOKIA_LCM_API_VERSION);
-                waitForOperationToFinish(vnfmId, vnfInfo.getId(), operationExecution.getId(), jobInfo.getJobId());
-            });
+            JobInfo spawnJob = scheduleExecution(vnfInfo.getId(), httpResponse, "instantiate", jobInfo ->
+                    instantiateVnf(vnfmId, request, additionalParams, cbamPackage, vnfInfo, vimId, jobInfo)
+            );
             response.setJobId(spawnJob.getJobId());
             return response;
         } catch (Exception e) {
@@ -183,6 +155,46 @@ public class LifecycleManager {
         }
     }
 
+    private void instantiateVnf(String vnfmId, VnfInstantiateRequest request, AdditionalParams additionalParams, CatalogAdapterVnfpackage cbamPackage, com.nokia.cbam.lcm.v32.model.VnfInfo vnfInfo, String vimId, JobInfo jobInfo) throws ApiException {
+        String vnfdContent = catalogManager.getCbamVnfdContent(vnfmId, cbamPackage.getId());
+        GrantVNFResponseVim vim = grantManager.requestGrantForInstantiate(vnfmId, vnfInfo.getId(), vimId, request.getVnfPackageId(), additionalParams.getInstantiationLevel(), vnfdContent, jobInfo.getJobId());
+        if (vim.getVimId() == null) {
+            fatalFailure(logger, "VF-C did not send VIM identifier in grant response");
+        }
+        VimInfo vimInfo = vimInfoProvider.getVimInfo(vim.getVimId());
+        InstantiateVnfRequest instantiationRequest = new InstantiateVnfRequest();
+        addExernalLinksToRequest(request.getExtVirtualLink(), additionalParams, instantiationRequest, vimId);
+        if (additionalParams.getVimType() == OPENSTACK_V2_INFO) {
+            instantiationRequest.getVims().add(buildOpenStackV2INFO(vimId, vim, vimInfo));
+
+        } else if (additionalParams.getVimType() == OPENSTACK_V3_INFO) {
+            instantiationRequest.getVims().add(buildOpenStackV3INFO(vimId, additionalParams, vim, vimInfo));
+
+        } else if (additionalParams.getVimType() == VMWARE_VCLOUD_INFO) {
+            instantiationRequest.getVims().add(buildVcloudInfo(vimId, vimInfo));
+
+        }
+        instantiationRequest.setFlavourId(getFlavorId(vnfdContent));
+        instantiationRequest.setComputeResourceFlavours(additionalParams.getComputeResourceFlavours());
+        instantiationRequest.setGrantlessMode(true);
+        instantiationRequest.setInstantiationLevelId(additionalParams.getInstantiationLevel());
+        instantiationRequest.setSoftwareImages(additionalParams.getSoftwareImages());
+        instantiationRequest.setZones(additionalParams.getZones());
+        instantiationRequest.setExtManagedVirtualLinks(additionalParams.getExtManagedVirtualLinks());
+        for (ExtVirtualLinkData extVirtualLinkData : additionalParams.getExtVirtualLinks()) {
+            instantiationRequest.addExtVirtualLinksItem(extVirtualLinkData);
+        }
+        JsonObject root = new Gson().toJsonTree(jobInfo).getAsJsonObject();
+        if (additionalParams.getAdditionalParams() != null && !isEmpty(additionalParams.getAdditionalParams().toString())) {
+            for (Map.Entry<String, JsonElement> item : new Gson().toJsonTree(additionalParams.getAdditionalParams()).getAsJsonObject().entrySet()) {
+                root.add(item.getKey(), item.getValue());
+            }
+        }
+        instantiationRequest.setAdditionalParams(root);
+        OperationExecution operationExecution = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdInstantiatePost(vnfInfo.getId(), instantiationRequest, NOKIA_LCM_API_VERSION);
+        waitForOperationToFinish(vnfmId, vnfInfo.getId(), operationExecution.getId());
+    }
+
     private void validateVimType(AdditionalParams additionalParams) {
         switch (additionalParams.getVimType()) {
             case OPENSTACK_V2_INFO:
@@ -250,9 +262,9 @@ public class LifecycleManager {
         request.setVnfConfigurableProperties(null);
         try {
             OperationExecution operationExecution = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdPatch(vnfId, request, NOKIA_LCM_API_VERSION);
-            waitForOperationToFinish(vnfmId, vnfId, operationExecution.getId(), NOKIA_LCM_API_VERSION);
+            waitForOperationToFinish(vnfmId, vnfId, operationExecution.getId());
         } catch (ApiException e) {
-            throw fatalFailure(logger, "Unable to set the " + ONAP_CSAR_ID + " property on the VNF", e);
+            fatalFailure(logger, "Unable to set the " + ONAP_CSAR_ID + " property on the VNF", e);
         }
     }
 
@@ -271,6 +283,9 @@ public class LifecycleManager {
         if (!isEmpty(vimInfo.getSslInsecure())) {
             interfaceInfoV3.setSkipCertificateVerification(Boolean.parseBoolean(vimInfo.getSslInsecure()));
             interfaceInfoV3.setSkipCertificateHostnameCheck(Boolean.parseBoolean(vimInfo.getSslInsecure()));
+        } else {
+            interfaceInfoV3.setSkipCertificateHostnameCheck(true);
+            interfaceInfoV3.setSkipCertificateVerification(true);
         }
         if (!interfaceInfoV3.isSkipCertificateVerification()) {
             interfaceInfoV3.setTrustedCertificates(new ArrayList<>());
@@ -296,6 +311,9 @@ public class LifecycleManager {
         if (!isEmpty(vimInfo.getSslInsecure())) {
             interfaceEndpoint.setSkipCertificateHostnameCheck(Boolean.parseBoolean(vimInfo.getSslInsecure()));
             interfaceEndpoint.setSkipCertificateVerification(Boolean.parseBoolean(vimInfo.getSslInsecure()));
+        } else {
+            interfaceEndpoint.setSkipCertificateHostnameCheck(true);
+            interfaceEndpoint.setSkipCertificateVerification(true);
         }
         interfaceEndpoint.setEndpoint(vimInfo.getUrl());
         if (!interfaceEndpoint.isSkipCertificateVerification()) {
@@ -309,7 +327,7 @@ public class LifecycleManager {
         return openstackv2INFO;
     }
 
-    private VMWAREVCLOUDINFO buildVcloudInfo(String vimId, GrantVNFResponseVim vim, org.onap.vnfmdriver.model.VimInfo vimInfo) {
+    private VMWAREVCLOUDINFO buildVcloudInfo(String vimId, org.onap.vnfmdriver.model.VimInfo vimInfo) {
         VMWAREVCLOUDINFO vcloudInfo = new VMWAREVCLOUDINFO();
         vcloudInfo.setVimInfoType(VMWARE_VCLOUD_INFO);
         VCloudAccessInfo accessInfo = new VCloudAccessInfo();
@@ -321,6 +339,9 @@ public class LifecycleManager {
         if (!isEmpty(vimInfo.getSslInsecure())) {
             interfaceEndpoint.setSkipCertificateHostnameCheck(Boolean.parseBoolean(vimInfo.getSslInsecure()));
             interfaceEndpoint.setSkipCertificateVerification(Boolean.parseBoolean(vimInfo.getSslInsecure()));
+        } else {
+            interfaceEndpoint.setSkipCertificateHostnameCheck(true);
+            interfaceEndpoint.setSkipCertificateVerification(true);
         }
         interfaceEndpoint.setEndpoint(vimInfo.getUrl());
         if (!interfaceEndpoint.isSkipCertificateVerification()) {
@@ -349,7 +370,7 @@ public class LifecycleManager {
      * @return the job for polling the progress of the termination
      */
     public JobInfo terminateVnf(String vnfmId, String vnfId, VnfTerminateRequest request, HttpServletResponse httpResponse) {
-        return scheduleExecution(vnfId, httpResponse, "terminate", (jobInfo) -> {
+        return scheduleExecution(vnfId, httpResponse, "terminate", jobInfo -> {
             TerminateVnfRequest cbamRequest = new TerminateVnfRequest();
             cbamRequest.setAdditionalParams(jobInfo);
             if (request.getTerminationType() == null) {
@@ -363,30 +384,32 @@ public class LifecycleManager {
                 }
             }
             com.nokia.cbam.lcm.v32.model.VnfInfo vnf = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdGet(vnfId, NOKIA_LCM_API_VERSION);
-            switch (vnf.getInstantiationState()) {
-                case INSTANTIATED:
-                    String vimId = getVimIdFromInstantiationRequest(vnfmId, vnf);
-                    grantManager.requestGrantForTerminate(vnfmId, vnfId, vimId, getVnfdIdFromModifyableAttributes(vnf), vnf, jobInfo.getJobId());
-                    OperationExecution terminationOperation = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdTerminatePost(vnfId, cbamRequest, NOKIA_LCM_API_VERSION);
-                    OperationExecution finishedOperation = waitForOperationToFinish(vnfmId, vnfId, terminationOperation.getId(), jobInfo.getJobId());
-                    switch (finishedOperation.getStatus()) {
-                        case FINISHED:
-                            notificationManager.waitForTerminationToBeProcessed(finishedOperation.getId());
-                            logger.info("Deleting VNF with " + vnfId);
-                            cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdDelete(vnfId, NOKIA_LCM_API_VERSION);
-                            logger.info("VNF with " + vnfId + " has been deleted");
-                            break;
-                        default:
-                            logger.error("Unable to terminate VNF the operation did not finish with success");
-                    }
-                    break;
-                case NOT_INSTANTIATED:
-                    cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdDelete(vnfId, NOKIA_LCM_API_VERSION);
-                    break;
+            if (vnf.getInstantiationState() == INSTANTIATED) {
+                terminateVnf(vnfmId, vnfId, jobInfo, cbamRequest, vnf);
+
+            } else {
+                cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdDelete(vnfId, NOKIA_LCM_API_VERSION);
+
             }
         });
     }
 
+    private void terminateVnf(String vnfmId, String vnfId, JobInfo jobInfo, TerminateVnfRequest cbamRequest, com.nokia.cbam.lcm.v32.model.VnfInfo vnf) throws ApiException {
+        String vimId = getVimIdFromInstantiationRequest(vnfmId, vnf);
+        grantManager.requestGrantForTerminate(vnfmId, vnfId, vimId, getVnfdIdFromModifyableAttributes(vnf), vnf, jobInfo.getJobId());
+        OperationExecution terminationOperation = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdTerminatePost(vnfId, cbamRequest, NOKIA_LCM_API_VERSION);
+        OperationExecution finishedOperation = waitForOperationToFinish(vnfmId, vnfId, terminationOperation.getId());
+        if (finishedOperation.getStatus() == FINISHED) {
+            notificationManager.waitForTerminationToBeProcessed(finishedOperation.getId());
+            logger.info("Deleting VNF with {}", vnfId);
+            cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdDelete(vnfId, NOKIA_LCM_API_VERSION);
+            logger.info("VNF with {} has been deleted", vnfId);
+
+        } else {
+            logger.error("Unable to terminate VNF the operation did not finish with success");
+        }
+    }
+
     private String getVimIdFromInstantiationRequest(String vnfmId, com.nokia.cbam.lcm.v32.model.VnfInfo vnf) throws ApiException {
         OperationExecution lastInstantiation = findLastInstantiation(vnf.getOperationExecutions());
         Object operationParameters = cbamRestApiProvider.getCbamOperationExecutionApi(vnfmId).operationExecutionsOperationExecutionIdOperationParamsGet(lastInstantiation.getId(), NOKIA_LCM_API_VERSION);
@@ -441,8 +464,10 @@ public class LifecycleManager {
      * @return the job for tracking the scale
      */
     public JobInfo scaleVnf(String vnfmId, String vnfId, VnfScaleRequest request, HttpServletResponse httpResponse) {
-        logger.info("Scale VNF " + vnfId + " " + new Gson().toJson(request));
-        return scheduleExecution(vnfId, httpResponse, "scale", (jobInfo) -> {
+        if (logger.isInfoEnabled()) {
+            logger.info("Scale VNF with {} identifier REST: {}", vnfId, new Gson().toJson(request));
+        }
+        return scheduleExecution(vnfId, httpResponse, "scale", jobInfo -> {
             ScaleVnfRequest cbamRequest = new ScaleVnfRequest();
             cbamRequest.setAspectId(request.getAspectId());
             cbamRequest.setNumberOfSteps(Integer.valueOf(request.getNumberOfSteps()));
@@ -458,11 +483,13 @@ public class LifecycleManager {
                         root.add(item.getKey(), item.getValue());
                     }
                 }
+            } else {
+                logger.warn("No additional parameters were passed for scaling");
             }
             cbamRequest.setAdditionalParams(root);
             grantManager.requestGrantForScale(vnfmId, vnfId, getVimIdFromInstantiationRequest(vnfmId, vnf), getVnfdIdFromModifyableAttributes(vnf), request, jobInfo.getJobId());
             OperationExecution operationExecution = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdScalePost(vnfId, cbamRequest, NOKIA_LCM_API_VERSION);
-            waitForOperationToFinish(vnfmId, vnfId, operationExecution.getId(), jobInfo.getJobId());
+            waitForOperationToFinish(vnfmId, vnfId, operationExecution.getId());
         });
     }
 
@@ -476,7 +503,7 @@ public class LifecycleManager {
      * @return the job for tracking the heal
      */
     public JobInfo healVnf(String vnfmId, String vnfId, VnfHealRequest request, HttpServletResponse httpResponse) {
-        return scheduleExecution(vnfId, httpResponse, "heal", (job) -> {
+        return scheduleExecution(vnfId, httpResponse, "heal", job -> {
             HealVnfRequest cbamHealRequest = new HealVnfRequest();
             Map<String, String> additionalParams = new HashMap<>();
             additionalParams.put("vmName", request.getAffectedvm().getVmname());
@@ -487,7 +514,7 @@ public class LifecycleManager {
             String vimId = getVimIdFromInstantiationRequest(vnfmId, vnf);
             grantManager.requestGrantForHeal(vnfmId, vnfId, vimId, getVnfdIdFromModifyableAttributes(vnf), request, job.getJobId());
             OperationExecution operationExecution = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdHealPost(vnfId, cbamHealRequest, NOKIA_LCM_API_VERSION);
-            waitForOperationToFinish(vnfmId, vnfId, operationExecution.getId(), job.getJobId());
+            waitForOperationToFinish(vnfmId, vnfId, operationExecution.getId());
         });
     }
 
@@ -506,22 +533,20 @@ public class LifecycleManager {
                 logger.error(msg, e);
                 //the job can only be signaled to be finished after the error is logged
                 jobManager.jobFinished(jobInfo.getJobId());
-                throw new RuntimeException(msg, e);
+                throw new UserVisibleError(msg, e);
             }
             jobManager.jobFinished(jobInfo.getJobId());
         });
         return jobInfo;
     }
 
-    private OperationExecution waitForOperationToFinish(String vnfmId, String vnfId, String operationExecutionId, String jobId) {
+    private OperationExecution waitForOperationToFinish(String vnfmId, String vnfId, String operationExecutionId) {
         while (true) {
             try {
                 OperationExecution operationExecution = find(cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdOperationExecutionsGet(vnfId, NOKIA_LCM_API_VERSION), opEx -> operationExecutionId.equals(opEx.getId()));
-                switch (operationExecution.getStatus()) {
-                    case FINISHED:
-                    case FAILED:
-                        logger.debug("Operation finished with " + operationExecution.getId());
-                        return operationExecution;
+                if (hasOperationFinished(operationExecution)) {
+                    logger.debug("Operation finished with " + operationExecution.getId());
+                    return operationExecution;
                 }
             } catch (Exception e) {
                 //swallow exception and retry
@@ -531,7 +556,12 @@ public class LifecycleManager {
         }
     }
 
+    private boolean hasOperationFinished(OperationExecution operationExecution) {
+        return newHashSet(FINISHED, OperationStatus.FAILED).contains(operationExecution.getStatus());
+    }
+
+    @FunctionalInterface
     private interface AsynchronousExecution {
-        void execute(JobInfo job) throws Exception;
+        void execute(JobInfo job) throws ApiException;
     }
 }
index 142072d..30195c9 100644 (file)
@@ -30,6 +30,7 @@ import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.SystemFunctions;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.DriverProperties;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.ILifecycleChangeNotificationManager;
+import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.LifecycleManager;
 import org.slf4j.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
@@ -99,7 +100,9 @@ public class LifecycleChangeNotificationManager implements ILifecycleChangeNotif
 
     @Override
     public void handleLcn(VnfLifecycleChangeNotification recievedNotification) {
-        logger.info("Received LCN: " + new Gson().toJson(recievedNotification));
+        if (logger.isInfoEnabled()) {
+            logger.info("Received LCN: " + new Gson().toJson(recievedNotification));
+        }
         VnfsApi cbamLcmApi = restApiProvider.getCbamLcmApi(driverProperties.getVnfmId());
         try {
             List<VnfInfo> vnfs = cbamLcmApi.vnfsGet(NOKIA_LCM_API_VERSION);
@@ -110,7 +113,7 @@ public class LifecycleChangeNotificationManager implements ILifecycleChangeNotif
                 return;
             } else {
                 VnfInfo vnf = cbamLcmApi.vnfsVnfInstanceIdGet(recievedNotification.getVnfInstanceId(), NOKIA_LCN_API_VERSION);
-                com.google.common.base.Optional<VnfProperty> externalVnfmId = tryFind(vnf.getExtensions(), prop -> prop.getName().equals(EXTERNAL_VNFM_ID));
+                com.google.common.base.Optional<VnfProperty> externalVnfmId = tryFind(vnf.getExtensions(), prop -> prop.getName().equals(LifecycleManager.EXTERNAL_VNFM_ID));
                 if (!externalVnfmId.isPresent()) {
                     logger.warn("The VNF with " + vnf.getId() + " identifier is not a managed VNF");
                     return;
@@ -121,29 +124,29 @@ public class LifecycleChangeNotificationManager implements ILifecycleChangeNotif
                 }
             }
         } catch (Exception e) {
-            logger.error("Unable to list VNFs / query VNF", e);
-            throw new RuntimeException("Unable to list VNFs / query VNF", e);
+            fatalFailure(logger, "Unable to list VNFs / query VNF", e);
         }
         OperationExecutionsApi cbamOperationExecutionApi = restApiProvider.getCbamOperationExecutionApi(driverProperties.getVnfmId());
         try {
             List<OperationExecution> operationExecutions = cbamLcmApi.vnfsVnfInstanceIdOperationExecutionsGet(recievedNotification.getVnfInstanceId(), NOKIA_LCM_API_VERSION);
             OperationExecution operationExecution = cbamOperationExecutionApi.operationExecutionsOperationExecutionIdGet(recievedNotification.getLifecycleOperationOccurrenceId(), NOKIA_LCM_API_VERSION);
             OperationExecution closestInstantiationToOperation = findLastInstantiationBefore(operationExecutions, operationExecution);
-            String vimId;
-            try {
-                Object operationParams = cbamOperationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(closestInstantiationToOperation.getId(), NOKIA_LCM_API_VERSION);
-                vimId = getVimId(operationParams);
-            } catch (Exception e) {
-                logger.error("Unable to detect last instantiation operation", e);
-                throw new RuntimeException("Unable to detect last instantiation operation", e);
-            }
+            String vimId = getVimId(cbamOperationExecutionApi, closestInstantiationToOperation);
             notificationSender.processNotification(recievedNotification, operationExecution, buildAffectedCps(operationExecution), vimId);
             if (OperationType.TERMINATE.equals(recievedNotification.getOperation()) && terminalStatus.contains(recievedNotification.getStatus())) {
                 processedNotifications.add(new ProcessedNotification(recievedNotification.getLifecycleOperationOccurrenceId(), recievedNotification.getStatus()));
             }
         } catch (ApiException e) {
-            logger.error("Unable to retrieve the current VNF " + recievedNotification.getVnfInstanceId(), e);
-            throw new RuntimeException("Unable to retrieve the current VNF " + recievedNotification.getVnfInstanceId(), e);
+            fatalFailure(logger, "Unable to retrieve the current VNF " + recievedNotification.getVnfInstanceId(), e);
+        }
+    }
+
+    private String getVimId(OperationExecutionsApi cbamOperationExecutionApi, OperationExecution closestInstantiationToOperation) {
+        try {
+            Object operationParams = cbamOperationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(closestInstantiationToOperation.getId(), NOKIA_LCM_API_VERSION);
+            return getVimId(operationParams);
+        } catch (Exception e) {
+            throw fatalFailure(logger, "Unable to detect last instantiation operation", e);
         }
     }
 
@@ -165,15 +168,14 @@ public class LifecycleChangeNotificationManager implements ILifecycleChangeNotif
     }
 
     private ReportedAffectedConnectionPoints buildAffectedCps(OperationExecution operationExecution) {
-        switch (operationExecution.getOperationType()) {
-            case TERMINATE:
-                String terminationType = childElement(new Gson().toJsonTree(operationExecution.getOperationParams()).getAsJsonObject(), "terminationType").getAsString();
-                if (TerminationType.FORCEFUL.name().equals(terminationType)) {
-                    //in case of force full termination the Ansible is not executed, so the connection points can not be
-                    //calculated from operation execution result
-                    logger.warn("Unable to send information related to affected connection points during forceful termination");
-                    return null;
-                }
+        if (operationExecution.getOperationType() == OperationType.TERMINATE) {
+            String terminationType = childElement(new Gson().toJsonTree(operationExecution.getOperationParams()).getAsJsonObject(), "terminationType").getAsString();
+            if (TerminationType.FORCEFUL.name().equals(terminationType)) {
+                //in case of force full termination the Ansible is not executed, so the connection points can not be
+                //calculated from operation execution result
+                logger.warn("Unable to send information related to affected connection points during forceful termination");
+                return null;
+            }
         }
         try {
             JsonElement root = new Gson().toJsonTree(operationExecution.getAdditionalData());
index f5f60fb..4ed4bf2 100644 (file)
@@ -30,11 +30,12 @@ import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.restapi.*;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.spring.TestConditions;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.spring.TestRealConfig;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.spring.TestServletInitializer;
-import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.TestCbamUtils;
-import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.TestStoreLoader;
-import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.TestSystemFunctions;
+import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.*;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.*;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.notification.TestLifecycleChangeNotificationManager;
+import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.notification.TestProcessedNotification;
+import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.notification.TestReportedAffectedConnectionPoints;
+import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.notification.TestReportedAffectedCp;
 
 @RunWith(Suite.class)
 @Suite.SuiteClasses({
@@ -68,6 +69,13 @@ import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.notification.TestLifecycle
         TestCbamUtils.class,
         TestStoreLoader.class,
         TestSystemFunctions.class,
+        TestUserInvisibleError.class,
+        TestUserVisibleError.class,
+
+        TestLifecycleChangeNotificationManager.class,
+        TestProcessedNotification.class,
+        TestReportedAffectedConnectionPoints.class,
+        TestReportedAffectedCp.class,
 
         TestAdditionalParams.class,
         TestCbamCatalogManager.class,
@@ -75,10 +83,8 @@ import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.notification.TestLifecycle
         TestDriverProperties.class,
         TestJobManager.class,
         TestVfcGrantManager.class,
-        TestLifecycleChangeNotificationManager.class,
         TestLifecycleManager.class,
         TestSelfRegistrationManager.class,
-
         TestNokiaSvnfmApplication.class,
 
 })
index 45a3216..0d036a6 100644 (file)
@@ -26,7 +26,6 @@ import org.junit.Test;
 import org.mockito.Mock;
 import org.onap.msb.sdk.discovery.entity.MicroServiceFullInfo;
 import org.onap.msb.sdk.discovery.entity.NodeInfo;
-import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.api.VnfmInfoProvider;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.TestUtil;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamTokenProvider;
@@ -61,7 +60,7 @@ public class TestCbamRestApiProvider extends TestBase {
         setField(real, "skipCertificateVerification", true);
         cbamRestApiProvider = spy(real);
         when(environment.getProperty(IpMappingProvider.IP_MAP, String.class, "")).thenReturn("");
-        when(environment.getProperty(VnfmInfoProvider.VNFM_INFO_CACHE_EVICTION_IN_MS, Long.class, Long.valueOf(10 * 60 * 1000))).thenReturn(10 * 60 * 1000L);
+        when(environment.getProperty(GenericExternalSystemInfoProvider.VNFM_INFO_CACHE_EVICTION_IN_MS, Long.class, Long.valueOf(10 * 60 * 1000))).thenReturn(10 * 60 * 1000L);
     }
 
     /**
index aec53e1..537093c 100644 (file)
@@ -63,8 +63,8 @@ public class TestVfcExternalSystemInfoProvider extends TestBase {
             vfcExternalSystemInfoProvider.getVimInfo(VIM_ID);
             fail();
         } catch (Exception e) {
-            assertEquals("Unable to query VIM from VF-C with " + VIM_ID +" identifier", e.getMessage());
-            verify(logger).error("Unable to query VIM from VF-C with " + VIM_ID+" identifier", expectedException);
+            assertEquals("Unable to query VIM from VF-C with " + VIM_ID + " identifier", e.getMessage());
+            verify(logger).error("Unable to query VIM from VF-C with " + VIM_ID + " identifier", expectedException);
         }
     }
 
index 7ca19d6..a2bf030 100644 (file)
@@ -283,7 +283,6 @@ public class TestVfcGrantManager extends TestBase {
         assertBasicGrantAttributes(request, org.onap.vnfmdriver.model.OperationType.SCALEIN);
     }
 
-
     /**
      * test grant request for healing
      */
@@ -303,6 +302,13 @@ public class TestVfcGrantManager extends TestBase {
         assertBasicGrantAttributes(request, org.onap.vnfmdriver.model.OperationType.HEAL);
     }
 
+    @Test
+    public void testPOJO() {
+        VfcGrantManager.AdditionalGrantParams additionalGrantParams = new VfcGrantManager.AdditionalGrantParams(VNFM_ID, VIM_ID);
+        assertEquals(VNFM_ID, additionalGrantParams.getVnfmId());
+        assertEquals(VIM_ID, additionalGrantParams.getVimId());
+    }
+
     private void assertBasicGrantAttributes(GrantVNFRequest request, org.onap.vnfmdriver.model.OperationType type) {
         assertEquals(JOB_ID, request.getJobId());
         assertEquals(type, request.getLifecycleOperation());
index 62ffdb4..b027cca 100644 (file)
@@ -107,7 +107,7 @@ public class TestVfcPackageProvider extends TestBase {
             vfcPackageProvider.getCbamVnfdId(CSAR_ID);
             fail();
         } catch (Exception e) {
-            verify(logger).error("Unable to query VNF package with csarId from VF-C", expectedException);
+            verify(logger).error("Unable to query VNF package with csarId", expectedException);
             assertEquals(expectedException, e.getCause());
         }
     }
@@ -132,7 +132,7 @@ public class TestVfcPackageProvider extends TestBase {
             vfcPackageProvider.getPackage(CSAR_ID);
             fail();
         } catch (Exception e) {
-            verify(logger).error("Unable to download package from http://1.2.3.4/a.csar from VF-C", expectedException);
+            verify(logger).error("Unable to download package from http://1.2.3.4/a.csar", expectedException);
             assertEquals(expectedException, e.getCause());
         }
     }
@@ -149,7 +149,7 @@ public class TestVfcPackageProvider extends TestBase {
             vfcPackageProvider.getPackage(CSAR_ID);
             fail();
         } catch (Exception e) {
-            verify(logger).error("Unable to query VNF package with csarId from VF-C", expectedException);
+            verify(logger).error("Unable to query VNF package with csarId", expectedException);
             assertEquals(expectedException, e.getCause());
         }
     }
diff --git a/nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/TestUserInvisibleError.java b/nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/TestUserInvisibleError.java
new file mode 100644 (file)
index 0000000..214c1ca
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2016-2017, Nokia Corporation
+ *
+ * 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.
+ */
+
+package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class TestUserInvisibleError {
+
+    /**
+     * test POJO
+     */
+    @Test
+    public void testPojo() throws Exception {
+        UserInvisibleError e = new UserInvisibleError("msg");
+        assertEquals("msg", e.getMessage());
+        Exception cause = new Exception();
+        UserInvisibleError e2 = new UserInvisibleError("msg", cause);
+        assertEquals("msg", e2.getMessage());
+        assertEquals(cause, e2.getCause());
+    }
+
+}
\ No newline at end of file
diff --git a/nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/TestUserVisibleError.java b/nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/util/TestUserVisibleError.java
new file mode 100644 (file)
index 0000000..0a10764
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2016-2017, Nokia Corporation
+ *
+ * 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.
+ */
+
+package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class TestUserVisibleError {
+
+    /**
+     * test POJO
+     */
+    @Test
+    public void testPojo() throws Exception {
+        UserVisibleError e = new UserVisibleError("msg");
+        assertEquals("msg", e.getMessage());
+        Exception cause = new Exception();
+        UserVisibleError e2 = new UserVisibleError("msg", cause);
+        assertEquals("msg", e2.getMessage());
+        assertEquals(cause, e2.getCause());
+    }
+
+}
\ No newline at end of file
index 5f1d600..7a1bf7f 100644 (file)
@@ -129,6 +129,10 @@ public class TestBase {
         when(response.getEntity()).thenReturn(entity);
         when(driverProperties.getVnfmId()).thenReturn(VNFM_ID);
         when(systemFunctions.getHttpClient()).thenReturn(httpClient);
+        when(logger.isInfoEnabled()).thenReturn(true);
+        when(logger.isDebugEnabled()).thenReturn(true);
+        when(logger.isWarnEnabled()).thenReturn(true);
+        when(logger.isErrorEnabled()).thenReturn(true);
     }
 
     @After
index 670aa77..44ba0e5 100644 (file)
@@ -42,10 +42,6 @@ import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.security.GeneralSecurityException;
 import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.cert.CertificateException;
-import java.security.spec.InvalidKeySpecException;
 import java.util.ArrayList;
 import java.util.Base64;
 import java.util.List;
@@ -321,7 +317,7 @@ public class TestCbamTokenProvider extends TestBase {
             //verify
             fail();
         } catch (RuntimeException e) {
-            assertTrue(e.getMessage().contains("unable to find valid certification path"));
+            assertTrue(e.getCause().getCause().getMessage().contains("unable to find valid certification path"));
             assertTrue(e.getCause() instanceof SSLHandshakeException);
         }
     }
@@ -361,7 +357,7 @@ public class TestCbamTokenProvider extends TestBase {
             //verify
             fail();
         } catch (RuntimeException e) {
-            assertTrue(e.getMessage().contains("Hostname 127.0.0.1 not verified"));
+            assertTrue(e.getCause().getMessage().contains("Hostname 127.0.0.1 not verified"));
             assertTrue(e.getCause() instanceof SSLPeerUnverifiedException);
         }
     }
@@ -382,7 +378,7 @@ public class TestCbamTokenProvider extends TestBase {
             //verify
             fail();
         } catch (RuntimeException e) {
-            assertTrue(e.getMessage().contains("Unable to load certificates"));
+            assertEquals("Unable to load certificates", e.getMessage());
             assertTrue(e.getCause() instanceof GeneralSecurityException);
         }
     }
@@ -411,7 +407,7 @@ public class TestCbamTokenProvider extends TestBase {
             }
 
             @Override
-            TrustManager[] buildTrustManager() throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
+            TrustManager[] buildTrustManager() throws KeyStoreException {
                 throw expectedException;
             }
         }
index 1ba58ab..aa3d63c 100644 (file)
@@ -45,8 +45,8 @@ import java.util.concurrent.Future;
 
 import static junit.framework.TestCase.*;
 import static org.mockito.Mockito.*;
+import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.SEPARATOR;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCM_API_VERSION;
-import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.ILifecycleChangeNotificationManager.SEPARATOR;
 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.JobManager.extractOnapJobId;
 import static org.onap.vnfmdriver.model.JobStatus.*;
 
index 64adaab..2c28bfc 100644 (file)
@@ -245,7 +245,7 @@ public class TestLifecycleManager extends TestBase {
         assertEquals(2, actualVnfModifyRequest.getValue().getExtensions().size());
         assertEquals(LifecycleManager.ONAP_CSAR_ID, actualVnfModifyRequest.getValue().getExtensions().get(0).getName());
         assertEquals(ONAP_CSAR_ID, actualVnfModifyRequest.getValue().getExtensions().get(0).getValue());
-        assertEquals(ILifecycleChangeNotificationManager.EXTERNAL_VNFM_ID, actualVnfModifyRequest.getValue().getExtensions().get(1).getName());
+        assertEquals(LifecycleManager.EXTERNAL_VNFM_ID, actualVnfModifyRequest.getValue().getExtensions().get(1).getName());
         assertEquals(VNFM_ID, actualVnfModifyRequest.getValue().getExtensions().get(1).getValue());
 
         //the 3.2 API does not accept empty array
@@ -303,6 +303,34 @@ public class TestLifecycleManager extends TestBase {
         assertTrue(!actualVim.getInterfaceInfo().isSkipCertificateHostnameCheck());
     }
 
+
+    /**
+     * non specified SSL verification means not verified
+     */
+    @Test
+    public void testInstantiationV2WithoutSsl() throws Exception {
+        VnfInstantiateRequest instantiationRequest = prepareInstantiationRequest(VimInfo.VimInfoTypeEnum.OPENSTACK_V2_INFO);
+
+        when(vnfApi.vnfsPost(createRequest.capture(), eq(NOKIA_LCM_API_VERSION))).thenReturn(vnfInfo);
+        additionalParam.setInstantiationLevel(INSTANTIATION_LEVEL);
+        when(vfcGrantManager.requestGrantForInstantiate(VNFM_ID, VNF_ID, VIM_ID, ONAP_CSAR_ID, INSTANTIATION_LEVEL, cbamVnfdContent, JOB_ID)).thenReturn(grantResponse);
+        grantResponse.setVimId(VIM_ID);
+        GrantVNFResponseVimAccessInfo accessInfo = new GrantVNFResponseVimAccessInfo();
+        accessInfo.setTenant(TENANT);
+        vimInfo.setSslInsecure(null);
+        grantResponse.setAccessInfo(accessInfo);
+        ArgumentCaptor<InstantiateVnfRequest> actualInstantiationRequest = ArgumentCaptor.forClass(InstantiateVnfRequest.class);
+        when(vnfApi.vnfsVnfInstanceIdInstantiatePost(eq(VNF_ID), actualInstantiationRequest.capture(), eq(NOKIA_LCM_API_VERSION))).thenReturn(instantiationOperationExecution);
+        //when
+        VnfInstantiateResponse response = lifecycleManager.instantiate(VNFM_ID, instantiationRequest, restResponse);
+        waitForJobToFinishInJobManager(finished);
+        assertEquals(1, actualInstantiationRequest.getValue().getVims().size());
+        //verify
+        OPENSTACKV2INFO actualVim = (OPENSTACKV2INFO) actualInstantiationRequest.getValue().getVims().get(0);
+        assertTrue(actualVim.getInterfaceInfo().isSkipCertificateVerification());
+        assertTrue(actualVim.getInterfaceInfo().isSkipCertificateHostnameCheck());
+    }
+
     /**
      * test instantiation with KeyStone V3 based
      */
@@ -379,6 +407,42 @@ public class TestLifecycleManager extends TestBase {
         assertTrue(!actualVim.getInterfaceInfo().isSkipCertificateHostnameCheck());
     }
 
+    /**
+     * non specified SSL verification meams not verified for KeyStone V3 based
+     */
+    @Test
+    public void testInstantiationV3WithNonSpecifiedSsl() throws Exception {
+        VnfInstantiateRequest instantiationRequest = prepareInstantiationRequest(VimInfo.VimInfoTypeEnum.OPENSTACK_V3_INFO);
+
+        when(vnfApi.vnfsPost(createRequest.capture(), eq(NOKIA_LCM_API_VERSION))).thenReturn(vnfInfo);
+        additionalParam.setInstantiationLevel(INSTANTIATION_LEVEL);
+        when(vfcGrantManager.requestGrantForInstantiate(VNFM_ID, VNF_ID, VIM_ID, ONAP_CSAR_ID, INSTANTIATION_LEVEL, cbamVnfdContent, JOB_ID)).thenReturn(grantResponse);
+        grantResponse.setVimId(VIM_ID);
+        GrantVNFResponseVimAccessInfo accessInfo = new GrantVNFResponseVimAccessInfo();
+        accessInfo.setTenant(TENANT);
+        vimInfo.setSslInsecure(null);
+        grantResponse.setAccessInfo(accessInfo);
+        ArgumentCaptor<InstantiateVnfRequest> actualInstantiationRequest = ArgumentCaptor.forClass(InstantiateVnfRequest.class);
+        when(vnfApi.vnfsVnfInstanceIdInstantiatePost(eq(VNF_ID), actualInstantiationRequest.capture(), eq(NOKIA_LCM_API_VERSION))).thenReturn(instantiationOperationExecution);
+        //when
+        VnfInstantiateResponse response = lifecycleManager.instantiate(VNFM_ID, instantiationRequest, restResponse);
+        waitForJobToFinishInJobManager(finished);
+        assertEquals(1, actualInstantiationRequest.getValue().getVims().size());
+        //verify
+        OPENSTACKV3INFO actualVim = (OPENSTACKV3INFO) actualInstantiationRequest.getValue().getVims().get(0);
+        assertEquals(VIM_ID, actualVim.getId());
+        assertEquals(VimInfo.VimInfoTypeEnum.OPENSTACK_V3_INFO, actualVim.getVimInfoType());
+        assertEquals("cloudUrl", actualVim.getInterfaceInfo().getEndpoint());
+        //FIXME assertEquals();actualVim.getInterfaceInfo().getTrustedCertificates());
+        assertEquals("vimPassword", actualVim.getAccessInfo().getPassword());
+        assertEquals("regionId", actualVim.getAccessInfo().getRegion());
+        assertEquals("myTenant", actualVim.getAccessInfo().getProject());
+        assertEquals("myDomain", actualVim.getAccessInfo().getDomain());
+        assertEquals("vimUsername", actualVim.getAccessInfo().getUsername());
+        assertTrue(actualVim.getInterfaceInfo().isSkipCertificateVerification());
+        assertTrue(actualVim.getInterfaceInfo().isSkipCertificateHostnameCheck());
+    }
+
     /**
      * test instantiation with vcloud
      */
@@ -451,6 +515,40 @@ public class TestLifecycleManager extends TestBase {
         assertTrue(!actualVim.getInterfaceInfo().isSkipCertificateHostnameCheck());
     }
 
+    /**
+     * test instantiation with vCloud with SSL
+     */
+    @Test
+    public void testInstantiationVcloudWithNonSecifedSSl() throws Exception {
+        VnfInstantiateRequest instantiationRequest = prepareInstantiationRequest(VimInfo.VimInfoTypeEnum.VMWARE_VCLOUD_INFO);
+
+        when(vnfApi.vnfsPost(createRequest.capture(), eq(NOKIA_LCM_API_VERSION))).thenReturn(vnfInfo);
+        additionalParam.setInstantiationLevel(INSTANTIATION_LEVEL);
+        when(vfcGrantManager.requestGrantForInstantiate(VNFM_ID, VNF_ID, VIM_ID, ONAP_CSAR_ID, INSTANTIATION_LEVEL, cbamVnfdContent, JOB_ID)).thenReturn(grantResponse);
+        grantResponse.setVimId(VIM_ID);
+        GrantVNFResponseVimAccessInfo accessInfo = new GrantVNFResponseVimAccessInfo();
+        accessInfo.setTenant(TENANT);
+        vimInfo.setSslInsecure(null);
+        grantResponse.setAccessInfo(accessInfo);
+        ArgumentCaptor<InstantiateVnfRequest> actualInstantiationRequest = ArgumentCaptor.forClass(InstantiateVnfRequest.class);
+        when(vnfApi.vnfsVnfInstanceIdInstantiatePost(eq(VNF_ID), actualInstantiationRequest.capture(), eq(NOKIA_LCM_API_VERSION))).thenReturn(instantiationOperationExecution);
+        //when
+        VnfInstantiateResponse response = lifecycleManager.instantiate(VNFM_ID, instantiationRequest, restResponse);
+        waitForJobToFinishInJobManager(finished);
+        assertEquals(1, actualInstantiationRequest.getValue().getVims().size());
+        //verify
+        VMWAREVCLOUDINFO actualVim = (VMWAREVCLOUDINFO) actualInstantiationRequest.getValue().getVims().get(0);
+        assertEquals(VIM_ID, actualVim.getId());
+        assertEquals(VimInfo.VimInfoTypeEnum.VMWARE_VCLOUD_INFO, actualVim.getVimInfoType());
+        assertEquals("cloudUrl", actualVim.getInterfaceInfo().getEndpoint());
+        //FIXME assertEquals();actualVim.getInterfaceInfo().getTrustedCertificates());
+        assertEquals("vimPassword", actualVim.getAccessInfo().getPassword());
+        assertEquals("regionId", actualVim.getAccessInfo().getOrganization());
+        assertEquals("vimUsername", actualVim.getAccessInfo().getUsername());
+        assertTrue(actualVim.getInterfaceInfo().isSkipCertificateVerification());
+        assertTrue(actualVim.getInterfaceInfo().isSkipCertificateHostnameCheck());
+    }
+
     /**
      * test failure in the instantiation request marks the job to be finished in job manager
      */
@@ -1058,6 +1156,41 @@ public class TestLifecycleManager extends TestBase {
         verify(jobManager).spawnJob(VNF_ID, restResponse);
     }
 
+    /**
+     * the VNFM should tolerate that no additional params were supplied
+     */
+    @Test
+    public void testScaleWithoutAddtionalParams() throws Exception {
+        VnfScaleRequest scaleRequest = new VnfScaleRequest();
+        scaleRequest.setNumberOfSteps("2");
+        scaleRequest.setAspectId("myAspect");
+        scaleRequest.setType(ScaleDirection.IN);
+        scaleRequest.setAdditionalParam(null);
+        scaleOperationExecution.setStatus(OperationStatus.FINISHED);
+        when(vnfApi.vnfsVnfInstanceIdGet(VNF_ID, NOKIA_LCM_API_VERSION)).thenReturn(vnfInfo);
+        VnfProperty prop = new VnfProperty();
+        prop.setValue(ONAP_CSAR_ID);
+        prop.setName(LifecycleManager.ONAP_CSAR_ID);
+        vnfInfo.getExtensions().add(prop);
+        vnfInfo.getOperationExecutions().add(instantiationOperationExecution);
+        String instantiationParams = "{ \"vims\" : [ { \"id\" : \"" + VIM_ID + "\" } ] }";
+        when(operationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(instantiationOperationExecution.getId(), NOKIA_LCM_API_VERSION)).thenReturn(new JsonParser().parse(instantiationParams));
+        //when
+        JobInfo job = lifecycleManager.scaleVnf(VNFM_ID, VNF_ID, scaleRequest, restResponse);
+        //verify
+        waitForJobToFinishInJobManager(finished);
+        assertEquals(1, actualScaleRequest.getAllValues().size());
+        ScaleVnfRequest sRequest = actualScaleRequest.getValue();
+        InOrder workflowOrder = Mockito.inOrder(vfcGrantManager, vnfApi);
+        workflowOrder.verify(vfcGrantManager).requestGrantForScale(eq(VNFM_ID), eq(VNF_ID), eq(VIM_ID), eq(ONAP_CSAR_ID), eq(scaleRequest), eq(JOB_ID));
+        workflowOrder.verify(vnfApi).vnfsVnfInstanceIdScalePost(VNF_ID, sRequest, NOKIA_LCM_API_VERSION);
+        assertEquals("myAspect", sRequest.getAspectId());
+        assertEquals(com.nokia.cbam.lcm.v32.model.ScaleDirection.IN, sRequest.getType());
+        assertEquals(Integer.valueOf(2), sRequest.getNumberOfSteps());
+        assertEquals("{\"jobId\":\"myJobId\"}", new Gson().toJson(sRequest.getAdditionalParams()));
+        verify(jobManager).spawnJob(VNF_ID, restResponse);
+    }
+
     /**
      * test scale out basic scenario
      */
index ed009b9..e26eab1 100644 (file)
@@ -24,7 +24,7 @@ import org.junit.Test;
 import org.mockito.ArgumentCaptor;
 import org.mockito.InjectMocks;
 import org.mockito.Mockito;
-import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.ILifecycleChangeNotificationManager;
+import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.LifecycleManager;
 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.TestBase;
 import org.threeten.bp.OffsetDateTime;
 
@@ -93,7 +93,7 @@ public class TestLifecycleChangeNotificationManager extends TestBase {
         vnfs.add(vnf);
         vnf.setId(VNF_ID);
         VnfProperty prop = new VnfProperty();
-        prop.setName(ILifecycleChangeNotificationManager.EXTERNAL_VNFM_ID);
+        prop.setName(LifecycleManager.EXTERNAL_VNFM_ID);
         prop.setValue(VNFM_ID);
         vnf.setExtensions(new ArrayList<>());
         vnf.getExtensions().add(prop);
index e7a20eb..c6de0f9 100644 (file)
 -->
 <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.onap.oparent</groupId>
+        <artifactId>oparent</artifactId>
+        <version>0.1.1</version>
+<!-- FIXME this artifact is not available in nexus
     <groupId>org.onap.vfc.nfvo.driver.vnfm.svnfm</groupId>
     <artifactId>vfc-nfvo-driver-vnfm-svnfm</artifactId>
     <version>1.1.0-SNAPSHOT</version>
-    <relativePath>../pom.xml</relativePath>
+-->
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.onap.vfc.nfvo.driver.vnfm.svnfm.nokiav2</groupId>