refactoring - add Optional 39/28039/9
authorLukasz Muszkieta <lukasz.muszkieta@nokia.com>
Mon, 8 Jan 2018 11:40:46 +0000 (12:40 +0100)
committerLukasz Muszkieta <lukasz.muszkieta@nokia.com>
Mon, 29 Jan 2018 11:58:05 +0000 (12:58 +0100)
change possible null return value to Optional

Change-Id: I70bf78a51b901a74932b00d1d8735bef5eeacef7
Issue-ID: SO-360
Signed-off-by: Lukasz Muszkieta <lukasz.muszkieta@nokia.com>
12 files changed:
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfig.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtils.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtilsWithUpdate.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoKeystoneUtils.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoNeutronUtils.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtils.java
adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtilsFactory.java
adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoHeatUtilsWithUpdateTest.java
adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/CloudConfigTest.java
adapters/mso-network-adapter/src/main/java/org/openecomp/mso/adapters/network/MsoNetworkAdapterImpl.java
adapters/mso-tenant-adapter/src/main/java/org/openecomp/mso/adapters/tenant/MsoTenantAdapterImpl.java
adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/adapters/vnf/MsoVnfAdapterImpl.java

index ef37f9f..5d16a95 100644 (file)
@@ -46,7 +46,6 @@ import org.openecomp.mso.openstack.exceptions.MsoCloudIdentityNotFound;
  *
  * This class also contains methods to query cloud sites and/or identity
  * services by ID.
- *
  */
 
 @JsonRootName("cloud_config")
@@ -89,21 +88,20 @@ public class CloudConfig {
      * individual entries to try and find one with a CLLI that matches the ID
      * and an AIC version of 2.5.
      *
-     * @param id
-     *            the ID to match
-     * @return a CloudSite, or null of no match found
+     * @param id the ID to match
+     * @return an Optional of CloudSite object.
      */
-    public synchronized CloudSite getCloudSite(String id) {
-        if (id != null) {
-            if (cloudSites.containsKey(id)) {
-                return cloudSites.get(id);
-            }
-            // check for id == CLLI now as well
-            return getCloudSiteWithClli(id);
+    public synchronized Optional<CloudSite> getCloudSite(String id) {
+        if (id == null) {
+            return Optional.empty();
         }
-        return null;
+        if (cloudSites.containsKey(id)) {
+            return Optional.ofNullable(cloudSites.get(id));
+        }
+        return Optional.ofNullable(getCloudSiteWithClli(id));
     }
 
+
     private CloudSite getCloudSiteWithClli(String clli) {
         Optional <CloudSite> cloudSiteOptional = cloudSites.values().stream().filter(cs ->
                 cs.getClli() != null && clli.equals(cs.getClli()) && (CLOUD_SITE_VERSION.equals(cs.getAic_version())))
@@ -111,7 +109,6 @@ public class CloudConfig {
         return cloudSiteOptional.orElse(getDefaultCloudSite(clli));
     }
 
-    // TODO in future the result will be optional
     private CloudSite getDefaultCloudSite(String clli) {
         Optional<CloudSite> cloudSiteOpt = cloudSites.values().stream()
                 .filter(cs -> cs.getId().equalsIgnoreCase(DEFAULT_CLOUD_SITE_ID)).findAny();
index 08ea84d..a8ee3ad 100644 (file)
@@ -258,7 +258,7 @@ public class MsoHeatUtils extends MsoCommonUtils {
      * @param cloudSiteId The cloud (may be a region) in which to create the stack.
      * @param tenantId The Openstack ID of the tenant in which to create the Stack
      * @param stackName The name of the stack to create
-     * @param stackTemplate The Heat template
+     * @param heatTemplate The Heat template
      * @param stackInputs A map of key/value inputs
      * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
      * @param environment An optional yaml-format string to specify environmental parameters
@@ -309,10 +309,8 @@ public class MsoHeatUtils extends MsoCommonUtils {
         }
 
         // Obtain the cloud site information where we will create the stack
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         LOGGER.debug("Found: " + cloudSite.toString());
         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
         // This could throw MsoTenantNotFound or MsoOpenstackException (both propagated)
@@ -632,10 +630,8 @@ public class MsoHeatUtils extends MsoCommonUtils {
         LOGGER.debug ("Query HEAT stack: " + stackName + " in tenant " + tenantId);
 
         // Obtain the cloud site information where we will create the stack
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         LOGGER.debug("Found: " + cloudSite.toString());
 
         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
@@ -696,10 +692,8 @@ public class MsoHeatUtils extends MsoCommonUtils {
                                   String stackName,
                                   boolean pollForCompletion) throws MsoException {
         // Obtain the cloud site information where we will create the stack
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         LOGGER.debug("Found: " + cloudSite.toString());
 
         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
@@ -838,11 +832,8 @@ public class MsoHeatUtils extends MsoCommonUtils {
      */
     public List <StackInfo> queryAllStacks (String tenantId, String cloudSiteId) throws MsoException {
         // Obtain the cloud site information where we will create the stack
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
-
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
         Heat heatClient = getHeatClient (cloudSite, tenantId);
 
@@ -950,8 +941,6 @@ public class MsoHeatUtils extends MsoCommonUtils {
      * tenantID + cloudId so that it can be reused without reauthenticating with
      * Openstack every time.
      *
-     * @param tenantName
-     * @param cloudId
      * @return an authenticated Heat object
      */
     public Heat getHeatClient (CloudSite cloudSite, String tenantId) throws MsoException {
@@ -1038,8 +1027,6 @@ public class MsoHeatUtils extends MsoCommonUtils {
      * the same Tenant Name is repeatedly used for creation/deletion.
      * <p>
      *
-     * @param tenantName
-     * @param cloudId
      */
     public static void expireHeatClient (String tenantId, String cloudId) {
         String cacheKey = cloudId + ":" + tenantId;
index dba52d4..2465b30 100644 (file)
@@ -21,7 +21,6 @@
 
 package org.openecomp.mso.openstack.utils;
 
-
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -160,7 +159,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
      * @param tenantId The Openstack ID of the tenant in which to create the Stack
      * @param cloudSiteId The cloud identifier (may be a region) in which to create the tenant.
      * @param stackName The name of the stack to update
-     * @param stackTemplate The Heat template
+     * @param heatTemplate The Heat template
      * @param stackInputs A map of key/value inputs
      * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
      * @param environment An optional yaml-format string to specify environmental parameters
@@ -194,10 +193,8 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils {
         }
 
         // Obtain the cloud site information where we will create the stack
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
         // This could throw MsoTenantNotFound or MsoOpenstackException (both propagated)
         Heat heatClient = getHeatClient (cloudSite, tenantId);
index ee89840..be36d67 100644 (file)
@@ -26,6 +26,7 @@ import java.util.Calendar;
 import java.util.HashMap;
 import java.util.Map;
 
+import java.util.Optional;
 import org.openecomp.mso.cloud.CloudIdentity;
 import org.openecomp.mso.cloud.CloudSite;
 import org.openecomp.mso.logger.MsoAlarmLogger;
@@ -58,7 +59,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
     // token will be used until it expires.
     //
     // The cache key is "cloudId"
-    private static Map <String, KeystoneCacheEntry> adminClientCache = new HashMap <String, KeystoneCacheEntry> ();
+    private static Map <String, KeystoneCacheEntry> adminClientCache = new HashMap<>();
 
        private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA);
        String msoPropID;
@@ -92,13 +93,12 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
                                 Map <String, String> metadata,
                                 boolean backout) throws MsoException {
         // Obtain the cloud site information where we will create the tenant
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
+        Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
+        if (!cloudSiteOpt.isPresent()) {
                LOGGER.error(MessageEnum.RA_CREATE_TENANT_ERR, "MSOCloudSite not found", "", "", MsoLogger.ErrorCode.DataError, "MSOCloudSite not found");
             throw new MsoCloudSiteNotFound (cloudSiteId);
         }
-        Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
-
+        Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSiteOpt.get());
         Tenant tenant = null;
         try {
             // Check if the tenant already exists
@@ -129,7 +129,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
         // Add MSO User to the tenant as a member and
         // apply tenant metadata if supported by the cloud site
         try {
-            CloudIdentity cloudIdentity = cloudSite.getIdentityService ();
+            CloudIdentity cloudIdentity = cloudSiteOpt.get().getIdentityService ();
 
             User msoUser = findUserByNameOrId (keystoneAdminClient, cloudIdentity.getMsoId ());
             Role memberRole = findRoleByNameOrId (keystoneAdminClient, cloudIdentity.getMemberRole ());
@@ -197,10 +197,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
      */
     public MsoTenant queryTenant (String tenantId, String cloudSiteId) throws MsoException {
         // Obtain the cloud site information where we will query the tenant
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
 
         Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
 
@@ -247,10 +245,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
      */
     public MsoTenant queryTenantByName (String tenantName, String cloudSiteId) throws MsoException {
         // Obtain the cloud site information where we will query the tenant
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
 
         try {
@@ -294,10 +290,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
      */
     public boolean deleteTenant (String tenantId, String cloudSiteId) throws MsoException {
         // Obtain the cloud site information where we will query the tenant
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
         Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
 
         try {
@@ -326,59 +320,6 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
         return true;
     }
 
-    /**
-     * Delete the specified Tenant (by Name) in the given cloud. This method returns true or
-     * false, depending on whether the tenant existed and was successfully deleted, or if
-     * the tenant already did not exist. Both cases are treated as success (no Exceptions).
-     * <p>
-     * Note for the AIC Cloud (DCP/LCP): all admin requests go to the centralized identity
-     * service in DCP. So deleting a tenant from one cloudSiteId will remove it from all
-     * sites managed by that identity service.
-     * <p>
-     *
-     * @param tenantName The name of the tenant to delete
-     * @param cloudSiteId The cloud identifier from which to delete the tenant.
-     * @return true if the tenant was deleted, false if the tenant did not exist.
-     * @throws MsoOpenstackException If the Openstack API call returns an exception.
-     */
-    public boolean deleteTenantByName (String tenantName, String cloudSiteId) throws MsoException {
-        // Obtain the cloud site information where we will query the tenant
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
-            throw new MsoCloudSiteNotFound (cloudSiteId);
-        }
-        Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite);
-
-        try {
-            // Need the Tenant ID to delete (can't directly delete by name)
-            Tenant tenant = findTenantByName (keystoneAdminClient, tenantName);
-            if (tenant == null) {
-                // OK if tenant already doesn't exist.
-               LOGGER.error(MessageEnum.RA_TENANT_NOT_FOUND, tenantName, cloudSiteId, "", "", MsoLogger.ErrorCode.DataError, "Tenant not found");
-                return false;
-            }
-
-            // Execute the Delete. It has no return value.
-            OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ());
-            executeAndRecordOpenstackRequest (request, msoProps);
-
-            LOGGER.debug ("Deleted Tenant " + tenant.getId () + " (" + tenant.getName () + ")");
-
-            // Clear any cached clients. Not really needed, ID will not be reused.
-            MsoHeatUtils.expireHeatClient (tenant.getId (), cloudSiteId);
-            MsoNeutronUtils.expireNeutronClient (tenant.getId (), cloudSiteId);
-        } catch (OpenStackBaseException e) {
-            // Note: It doesn't seem to matter if tenant doesn't exist, no exception is thrown.
-            // Convert Keystone OpenStackResponseException to MsoOpenstackException
-            throw keystoneErrorToMsoException (e, "DeleteTenant");
-        } catch (RuntimeException e) {
-            // Catch-all
-            throw runtimeExceptionToMsoException (e, "DeleteTenant");
-        }
-
-        return true;
-    }
-
     // -------------------------------------------------------------------
     // PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS
 
@@ -462,29 +403,6 @@ public class MsoKeystoneUtils extends MsoTenantUtils {
         return keystone;
     }
 
-    /*
-     * Find a tenant (or query its existance) by its Name or Id. Check first against the
-     * ID. If that fails, then try by name.
-     *
-     * @param adminClient an authenticated Keystone object
-     *
-     * @param tenantName the tenant name or ID to query
-     *
-     * @return a Tenant object or null if not found
-     */
-    public Tenant findTenantByNameOrId (Keystone adminClient, String tenantNameOrId) {
-        if (tenantNameOrId == null) {
-            return null;
-        }
-
-        Tenant tenant = findTenantById (adminClient, tenantNameOrId);
-        if (tenant == null) {
-            tenant = findTenantByName (adminClient, tenantNameOrId);
-        }
-
-        return tenant;
-    }
-
     /*
      * Find a tenant (or query its existance) by its Id.
      *
index ad3eae4..50a5946 100644 (file)
@@ -7,9 +7,9 @@
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -43,7 +43,6 @@ import org.openecomp.mso.openstack.exceptions.MsoIOException;
 import org.openecomp.mso.openstack.exceptions.MsoNetworkAlreadyExists;
 import org.openecomp.mso.openstack.exceptions.MsoNetworkNotFound;
 import org.openecomp.mso.openstack.exceptions.MsoOpenstackException;
-import org.openecomp.mso.openstack.exceptions.MsoTenantNotFound;
 import com.woorea.openstack.base.client.OpenStackBaseException;
 import com.woorea.openstack.base.client.OpenStackConnectException;
 import com.woorea.openstack.base.client.OpenStackRequest;
@@ -71,7 +70,7 @@ public class MsoNeutronUtils extends MsoCommonUtils
 
        private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA);
        private String msoPropID;
-       
+
        public enum NetworkType {
                BASIC, PROVIDER, MULTI_PROVIDER
        };
@@ -99,13 +98,11 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * @throws MsoCloudSiteNotFound Thrown if the cloudSite is invalid or unknown
         */
        public NetworkInfo createNetwork (String cloudSiteId, String tenantId, NetworkType type, String networkName, String provider, List<Integer> vlans)
-               throws MsoException, MsoNetworkAlreadyExists, MsoCloudSiteNotFound
+            throws MsoException
        {
                // Obtain the cloud site information where we will create the stack
-               CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId);
-               if (cloudSite == null) {
-                       throw new MsoCloudSiteNotFound(cloudSiteId);
-               }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
 
                Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
 
@@ -177,19 +174,15 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
         * @throws MsoCloudSiteNotFound
         */
-       public NetworkInfo queryNetwork (String networkNameOrId, String tenantId, String cloudSiteId)
-               throws MsoException, MsoCloudSiteNotFound
+    public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException
        {
                LOGGER.debug("In queryNetwork");
 
                // Obtain the cloud site information
-               CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId);
-               if (cloudSite == null) {
-                       throw new MsoCloudSiteNotFound(cloudSiteId);
-               }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
 
                Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
                // Check if the network exists and return its info
                try {
                        Network network = findNetworkByNameOrId (neutronClient, networkNameOrId);
@@ -215,24 +208,20 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * Delete the specified Network (by ID) in the given cloud.
         * If the network does not exist, success is returned.
         * <p>
-        * @param networkNameOrId The name or Openstack ID of the network to delete
-        * @param cloudId The cloud identifier (may be a region) from which to delete the network.
+        * @param networkId Openstack ID of the network to delete
+        * @param tenantId The Openstack tenant.
+        * @param cloudSiteId The cloud identifier (may be a region) from which to delete the network.
         * @return true if the network was deleted, false if the network did not exist
         * @throws MsoOpenstackException If the Openstack API call returns an exception, this local
         * exception will be thrown.
         * @throws MsoCloudSiteNotFound
         */
-       public boolean deleteNetwork (String networkId, String tenantId, String cloudSiteId)
-               throws MsoException, MsoCloudSiteNotFound
+    public boolean deleteNetwork(String networkId, String tenantId, String cloudSiteId) throws MsoException
        {
                // Obtain the cloud site information where we will create the stack
-               CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId);
-               if (cloudSite == null) {
-                       throw new MsoCloudSiteNotFound(cloudSiteId);
-               }
-
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
                Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
                try {
                        // Check that the network exists.
                        Network network = findNetworkById (neutronClient, networkId);
@@ -273,7 +262,7 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * to manage the virtual networking).
         *
         * @param cloudSiteId The cloud site ID (may be a region) in which to update the network.
-        * @param the Openstack ID of the tenant in which to update the network
+        * @param tenantId Openstack ID of the tenant in which to update the network
         * @param networkId The unique Openstack ID of the network to be updated
         * @param type The network type (Basic, Provider, Multi-Provider)
         * @param provider The provider network name.  This should not change.
@@ -284,15 +273,12 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * @throws MsoCloudSiteNotFound
         */
        public NetworkInfo updateNetwork (String cloudSiteId, String tenantId, String networkId, NetworkType type, String provider, List<Integer> vlans)
-               throws MsoException, MsoNetworkNotFound, MsoCloudSiteNotFound
+            throws MsoException
        {
                // Obtain the cloud site information where we will create the stack
-               CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId);
-               if (cloudSite == null) {
-                       throw new MsoCloudSiteNotFound(cloudSiteId);
-               }
+        CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                () -> new MsoCloudSiteNotFound(cloudSiteId));
                Quantum neutronClient = getNeutronClient (cloudSite, tenantId);
-
                // Check that the network exists
                Network network = findNetworkById (neutronClient, networkId);
 
@@ -359,8 +345,7 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * @param tenantId - Openstack tenant ID
         * @return an authenticated Quantum object
         */
-       private Quantum getNeutronClient (CloudSite cloudSite, String tenantId)
-               throws MsoTenantNotFound, MsoException
+    private Quantum getNeutronClient(CloudSite cloudSite, String tenantId) throws MsoException
        {
                String cloudId = cloudSite.getId();
 
@@ -440,9 +425,6 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * the KeystoneClient in case where a tenant is deleted.  In that case,
         * all cached credentials must be purged so that fresh authentication is
         * done on subsequent calls.
-        * <p>
-        * @param tenantName
-        * @param cloudId
         */
        public static void expireNeutronClient (String tenantId, String cloudId) {
                String cacheKey = cloudId + ":" + tenantId;
@@ -602,6 +584,6 @@ public class MsoNeutronUtils extends MsoCommonUtils
         * This may be useful if cached credentials get out of sync.
         */
        public static void neutronCacheReset () {
-               neutronClientCache = new HashMap<String,NeutronCacheEntry>();
+               neutronClientCache = new HashMap<>();
        }
 }
index 4a19828..2cd4597 100644 (file)
 package org.openecomp.mso.openstack.utils;
 
 
-import java.io.Serializable;
-import java.util.Calendar;
-import java.util.HashMap;
 import java.util.Map;
-
 import org.openecomp.mso.cloud.CloudConfig;
 import org.openecomp.mso.cloud.CloudConfigFactory;
 import org.openecomp.mso.cloud.CloudIdentity;
-import org.openecomp.mso.logger.MsoAlarmLogger;
-import org.openecomp.mso.logger.MsoLogger;
 import org.openecomp.mso.logger.MessageEnum;
+import org.openecomp.mso.logger.MsoLogger;
 import org.openecomp.mso.openstack.beans.MsoTenant;
-import org.openecomp.mso.openstack.exceptions.MsoAdapterException;
 import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound;
 import org.openecomp.mso.openstack.exceptions.MsoException;
-import org.openecomp.mso.openstack.exceptions.MsoOpenstackException;
-import org.openecomp.mso.openstack.exceptions.MsoTenantAlreadyExists;
 import org.openecomp.mso.properties.MsoJavaProperties;
 import org.openecomp.mso.properties.MsoPropertiesException;
 import org.openecomp.mso.properties.MsoPropertiesFactory;
-import com.woorea.openstack.keystone.Keystone;
 
 public abstract class MsoTenantUtils extends MsoCommonUtils {
 
index a659fb6..e36d468 100644 (file)
@@ -26,6 +26,7 @@ import org.openecomp.mso.cloud.CloudIdentity;
 import org.openecomp.mso.cloud.CloudSite;
 
 import java.lang.reflect.InvocationTargetException;
+import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound;
 
 
 public class MsoTenantUtilsFactory {
@@ -39,12 +40,11 @@ public class MsoTenantUtilsFactory {
        }
 
        //based on Cloud IdentityServerType returns ORM or KEYSTONE Utils
-       public MsoTenantUtils getTenantUtils(String cloudSiteId) {
-
+       public MsoTenantUtils getTenantUtils(String cloudSiteId) throws MsoCloudSiteNotFound {
                // Obtain the cloud site information
                cloudConfig = cloudConfigFactory.getCloudConfig();
-               CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-
+               CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
+                               () -> new MsoCloudSiteNotFound(cloudSiteId));
                return getTenantUtilsByServerType(cloudSite.getIdentityService().getIdentityServerType().toString());
        }
 
index 714bb66..62043e8 100644 (file)
@@ -26,6 +26,7 @@ import static org.mockito.Mockito.when;
 import java.util.HashMap;
 import java.util.Map;
 
+import java.util.Optional;
 import org.junit.Before;
 import org.junit.Ignore;
 import org.junit.Test;
@@ -68,8 +69,8 @@ public class MsoHeatUtilsWithUpdateTest {
         cloudIdentity.setKeystoneUrl ("toto");
         cloudIdentity.setMsoPass (CloudIdentity.encryptPassword ("mockId"));
         cloudSite.setIdentityService (cloudIdentity);
-        when (cloudConfig.getCloudSite ("cloud")).thenReturn (cloudSite);
-        when (cloudConfig.getCloudSite ("none")).thenReturn (null);
+        when(cloudConfig.getCloudSite("cloud")).thenReturn (Optional.of(cloudSite));
+        when(cloudConfig.getCloudSite("none")).thenReturn (Optional.empty());
     }
 
     @Test
index a73e435..1c2501e 100644 (file)
@@ -26,6 +26,7 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
+import java.util.Optional;
 import org.junit.Assert;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -112,29 +113,29 @@ public class CloudConfigTest {
     @Test
     public void cloudSiteIsGotById_when_IdFound() throws MsoCloudIdentityNotFound {
         CloudConfig con = createTestObject(cloudConfigJsonFilePath);
-        CloudSite cloudSite = con.getCloudSite("MT");
-        assertNotNull(cloudSite);
-        assertEquals("regionOne", cloudSite.getRegionId());
-        assertEquals("MT_KEYSTONE", cloudSite.getIdentityServiceId());
+        Optional<CloudSite> cloudSite = con.getCloudSite("MT");
+        assertTrue(cloudSite.isPresent());
+        assertEquals("regionOne", cloudSite.get().getRegionId());
+        assertEquals("MT_KEYSTONE", cloudSite.get().getIdentityServiceId());
     }
 
     @Test
     public void cloudSiteIsGotByClli_when_IdNotFound() throws MsoCloudIdentityNotFound {
         CloudConfig con = createTestObject(cloudConfigJsonFilePath);
-        CloudSite cloudSite = con.getCloudSite("CS_clli");
-        assertNotNull(cloudSite);
-        assertEquals("clliRegion", cloudSite.getRegionId());
-        assertEquals("CS_clli", cloudSite.getClli());
-        assertEquals("CS_service", cloudSite.getIdentityServiceId());
+        Optional<CloudSite> cloudSite = con.getCloudSite("CS_clli");
+        assertTrue(cloudSite.isPresent());
+        assertEquals("clliRegion", cloudSite.get().getRegionId());
+        assertEquals("CS_clli", cloudSite.get().getClli());
+        assertEquals("CS_service", cloudSite.get().getIdentityServiceId());
     }
 
     @Test
     public void cloudSiteIsGotByDefault_when_IdAndClliNotFound() throws MsoCloudIdentityNotFound {
         CloudConfig con = createTestObject(cloudDefaultConfigJsonFilePath);
-        CloudSite cloudSite = con.getCloudSite("not_existing_id");
-        assertNotNull(cloudSite);
-        assertEquals("not_existing_id", cloudSite.getId());
-        assertEquals("not_existing_id", cloudSite.getRegionId());
+        Optional<CloudSite> cloudSite = con.getCloudSite("not_existing_id");
+        assertTrue(cloudSite.isPresent());
+        assertEquals("not_existing_id", cloudSite.get().getId());
+        assertEquals("not_existing_id", cloudSite.get().getRegionId());
     }
 
     @Test
index 6879306..2c04ae9 100644 (file)
@@ -26,6 +26,7 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
+import java.util.Optional;
 import javax.jws.WebService;
 import javax.xml.ws.Holder;
 
@@ -271,8 +272,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
         // So this is just catching that error in a bit more obvious way up front.
 
         cloudConfig = cloudConfigFactory.getCloudConfig ();
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null)
+        Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
+        if (!cloudSiteOpt.isPresent())
         {
                String error = "Configuration Error. Stack " + networkName + " in "
                                + cloudSiteId
@@ -299,7 +300,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                                                             physicalNetworkName,
                                                             vlans,
                                                             routeTargets,
-                                                            cloudSite);
+                                                            cloudSiteOpt.get());
             String mode = networkResource.getOrchestrationMode ();
             NetworkType neutronNetworkType = NetworkType.valueOf (networkResource.getNeutronNetworkType ());
 
@@ -787,8 +788,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
         networkRollback.setMsoRequest (msoRequest);
 
         cloudConfig = cloudConfigFactory.getCloudConfig ();
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null) {
+        Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite (cloudSiteId);
+        if (!cloudSiteOpt.isPresent()) {
                   String error = "UpdateNetwork: Configuration Error. Stack " + networkName + " in "
                        + cloudSiteId
                        + "/"
@@ -814,7 +815,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                     physicalNetworkName,
                     vlans,
                     routeTargets,
-                    cloudSite);
+                    cloudSiteOpt.get());
             String mode = networkResource.getOrchestrationMode();
             NetworkType neutronNetworkType = NetworkType.valueOf(networkResource.getNeutronNetworkType());
 
@@ -1233,7 +1234,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                               Holder <NetworkStatus> status,
                               Holder <List <Integer>> vlans,
                               Holder <Map <String, String>> subnetIdMap) throws NetworkException {
-        queryNetwork (cloudSiteId,
+        queryNetworkInfo(cloudSiteId,
                       tenantId,
                       networkNameOrId,
                       msoRequest,
@@ -1242,7 +1243,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                       neutronNetworkId,
                       status,
                       vlans,
-                      null,
                       subnetIdMap);
     }
 
@@ -1257,7 +1257,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                                       Holder <NetworkStatus> status,
                                       Holder <List <String>> routeTargets,
                                       Holder <Map <String, String>> subnetIdMap) throws NetworkException {
-        queryNetwork (cloudSiteId,
+        queryNetworkInfo(cloudSiteId,
                       tenantId,
                       networkNameOrId,
                       msoRequest,
@@ -1266,18 +1266,17 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                       neutronNetworkId,
                       status,
                       null,
-                      routeTargets,
                       subnetIdMap);
     }
 
     /**
-     * This is the queryNetwork method. It returns the existence and status of
+     * This is the queryNetworkInfo method. It returns the existence and status of
      * the specified network, along with its Neutron UUID and list of VLANs.
      * This method attempts to find the network using both Heat and Neutron.
      * Heat stacks are first searched based on the provided network name/id.
      * If none is found, the Neutron is directly queried.
      */
-    private void queryNetwork (String cloudSiteId,
+    private void queryNetworkInfo(String cloudSiteId,
                               String tenantId,
                               String networkNameOrId,
                               MsoRequest msoRequest,
@@ -1286,7 +1285,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                               Holder <String> neutronNetworkId,
                               Holder <NetworkStatus> status,
                               Holder <List <Integer>> vlans,
-                              Holder <List <String>> routeTargets,
                               Holder <Map <String, String>> subnetIdMap) throws NetworkException {
         MsoLogger.setLogContext (msoRequest);
         MsoLogger.setServiceName ("QueryNetwork");
@@ -1309,9 +1307,9 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
             throw new NetworkException (error, MsoExceptionCategory.USERDATA);
         }
 
-        cloudConfig = cloudConfigFactory.getCloudConfig ();
-        CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId);
-        if (cloudSite == null)
+        cloudConfig = cloudConfigFactory.getCloudConfig();
+        Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId);
+        if (!cloudSiteOpt.isPresent())
         {
                String error = "Configuration Error. Stack " + networkNameOrId + " in "
                                + cloudSiteId
@@ -1414,7 +1412,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
                 status.value = NetworkStatus.NOTFOUND;
                 neutronNetworkId.value = null;
                 if (vlans != null)
-                       vlans.value = new ArrayList <Integer> ();
+                       vlans.value = new ArrayList<>();
 
                 LOGGER.debug ("Network " + networkNameOrId + " not found");
             }
index 29f5630..58169f6 100644 (file)
@@ -28,6 +28,7 @@ import javax.jws.WebService;
 import javax.xml.ws.Holder;
 import javax.xml.ws.WebServiceContext;
 
+import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound;
 import org.openecomp.mso.properties.MsoPropertiesFactory;
 import org.openecomp.mso.adapters.tenant.exceptions.TenantAlreadyExists;
 import org.openecomp.mso.adapters.tenant.exceptions.TenantException;
@@ -84,7 +85,7 @@ public class MsoTenantAdapterImpl implements MsoTenantAdapter {
                               Boolean backout,
                               MsoRequest msoRequest,
                               Holder <String> tenantId,
-                              Holder <TenantRollback> rollback) throws TenantException, TenantAlreadyExists {
+                              Holder <TenantRollback> rollback) throws TenantException {
         MsoLogger.setLogContext (msoRequest);
         MsoLogger.setServiceName (CREATE_TENANT);
 
@@ -99,15 +100,16 @@ public class MsoTenantAdapterImpl implements MsoTenantAdapter {
         TenantRollback tenantRollback = new TenantRollback ();
         tenantRollback.setCloudId (cloudSiteId);
         tenantRollback.setMsoRequest (msoRequest);
-        
-        MsoTenantUtils tUtils = tFactory.getTenantUtils (cloudSiteId);
 
+        MsoTenantUtils tUtils;
         MsoTenant newTenant = null;
         String newTenantId;
         long queryTenantStartTime = System.currentTimeMillis ();
         try {
+            tUtils = tFactory.getTenantUtils (cloudSiteId);
             newTenant = tUtils.queryTenantByName (tenantName, cloudSiteId);
             logger.recordMetricEvent (queryTenantStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from Open Stack", OPENSTACK, QUERY_TENANT, null);
+
         } catch (MsoException me) {
             logger.recordMetricEvent (queryTenantStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with Open Stack", OPENSTACK, QUERY_TENANT, null);
             String error = "Create Tenant " + tenantName + ": " + me;
@@ -166,11 +168,11 @@ public class MsoTenantAdapterImpl implements MsoTenantAdapter {
         // Will capture execution time for metrics
         long startTime = System.currentTimeMillis ();
 
-        MsoTenantUtils tUtils = tFactory.getTenantUtils (cloudSiteId);
-        
+        MsoTenantUtils tUtils = null;
         MsoTenant qTenant = null;
         long subStartTime = System.currentTimeMillis ();
         try {
+            tUtils = tFactory.getTenantUtils (cloudSiteId);
             qTenant = tUtils.queryTenant (tenantNameOrId, cloudSiteId);
             logger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from Open Stack", OPENSTACK, QUERY_TENANT, null);
             if (qTenant == null) {
index fb86b8c..be6e752 100644 (file)
@@ -21,7 +21,7 @@
 
 package org.openecomp.mso.adapters.vnf;
 
-
+import java.util.Optional;
 import org.codehaus.jackson.JsonNode;
 import org.codehaus.jackson.JsonParseException;
 import org.codehaus.jackson.map.ObjectMapper;
@@ -953,15 +953,14 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
             }
             if (minVersionVnf != null && maxVersionVnf != null) {
                 MavenLikeVersioning aicV = new MavenLikeVersioning();
-                CloudSite cloudSite = null;
                 if (this.cloudConfig == null) {
                     this.cloudConfig = this.cloudConfigFactory.getCloudConfig();
                 }
                 // double check
                 if (this.cloudConfig != null) {
-                    cloudSite = this.cloudConfig.getCloudSite(cloudSiteId);
-                    if (cloudSite != null) {
-                        aicV.setVersion(cloudSite.getAic_version());
+                    Optional<CloudSite> cloudSiteOpt = this.cloudConfig.getCloudSite(cloudSiteId);
+                    if (cloudSiteOpt.isPresent()) {
+                        aicV.setVersion(cloudSiteOpt.get().getAic_version());
                         // Add code to handle unexpected values in here
                         boolean moreThanMin = true;
                         boolean equalToMin = true;
@@ -980,10 +979,10 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
                         if (!doNotTest) {
                             if ((moreThanMin || equalToMin) // aic >= min
                                     && (equalToMax || !(moreThanMax))) { //aic <= max
-                                LOGGER.debug("VNF Resource " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUuid() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version());
+                                LOGGER.debug("VNF Resource " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUuid() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version());
                             } else {
                                 // ERROR
-                                String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUuid() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version();
+                                String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUuid() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version();
                                 LOGGER.error(MessageEnum.RA_CONFIG_EXC, error, "OpenStack", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - setVersion");
                                 LOGGER.debug(error);
                                 throw new VnfException(error, MsoExceptionCategory.USERDATA);
@@ -1703,26 +1702,25 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter {
                 }
             if (minVersionVnf != null && maxVersionVnf != null) {
                 MavenLikeVersioning aicV = new MavenLikeVersioning();
-                CloudSite cloudSite = null;
                 //String aicVersion = "";
                 if (this.cloudConfig == null) {
                     this.cloudConfig = this.cloudConfigFactory.getCloudConfig();
             }
                 // double check
                 if (this.cloudConfig != null) {
-                    cloudSite = this.cloudConfig.getCloudSite(cloudSiteId);
-                    if (cloudSite != null) {
-                        aicV.setVersion(cloudSite.getAic_version());
+                    Optional<CloudSite> cloudSiteOpt = this.cloudConfig.getCloudSite(cloudSiteId);
+                    if (cloudSiteOpt.isPresent()) {
+                        aicV.setVersion(cloudSiteOpt.get().getAic_version());
                         if ((aicV.isMoreRecentThan(minVersionVnf) || aicV.isTheSameVersion(minVersionVnf)) // aic >= min
                                 && (aicV.isTheSameVersion(maxVersionVnf) || !(aicV.isMoreRecentThan(maxVersionVnf)))) { //aic <= max
-                            LOGGER.debug("VNF Resource " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version());
+                            LOGGER.debug("VNF Resource " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version());
                         } else {
                             // ERROR
-                            String error = "VNF Resource type: " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version();
+                            String error = "VNF Resource type: " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version();
                             LOGGER.error(MessageEnum.RA_CONFIG_EXC, error, "OpenStack", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - setVersion");
                             LOGGER.debug(error);
                             throw new VnfException(error, MsoExceptionCategory.USERDATA);
-                    }
+                        }
                     } // let this error out downstream to avoid introducing uncertainty at this stage
                 } else {
                     LOGGER.debug("cloudConfig is NULL - cannot check cloud site version");