diff options
16 files changed, 415 insertions, 252 deletions
diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfig.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfig.java index ef37f9f719..5d16a95e5f 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfig.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfig.java @@ -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(); diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtils.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtils.java index 8f21cfb2a3..acc6d72f63 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtils.java @@ -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; diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtilsWithUpdate.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtilsWithUpdate.java index dba52d4306..2465b30eca 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtilsWithUpdate.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtilsWithUpdate.java @@ -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); diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoKeystoneUtils.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoKeystoneUtils.java index ee89840c50..be36d67e0b 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoKeystoneUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoKeystoneUtils.java @@ -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 @@ -463,29 +404,6 @@ public class MsoKeystoneUtils extends MsoTenantUtils { } /* - * 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. * * @param adminClient an authenticated Keystone object diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoNeutronUtils.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoNeutronUtils.java index ad3eae4b01..50a594663e 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoNeutronUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoNeutronUtils.java @@ -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<>(); } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtils.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtils.java index 4a19828897..2cd4597c18 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtils.java @@ -21,27 +21,18 @@ 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 { diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtilsFactory.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtilsFactory.java index a659fb629e..e36d46841d 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtilsFactory.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtilsFactory.java @@ -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()); } diff --git a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoHeatUtilsWithUpdateTest.java b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoHeatUtilsWithUpdateTest.java index 714bb66e18..62043e83b8 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoHeatUtilsWithUpdateTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoHeatUtilsWithUpdateTest.java @@ -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 diff --git a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/CloudConfigTest.java b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/CloudConfigTest.java index a73e4359fc..1c2501e8e4 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/CloudConfigTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/CloudConfigTest.java @@ -26,6 +26,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import java.util.Optional; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; @@ -112,29 +113,29 @@ public class CloudConfigTest { @Test public void cloudSiteIsGotById_when_IdFound() throws MsoCloudIdentityNotFound { CloudConfig con = createTestObject(cloudConfigJsonFilePath); - CloudSite cloudSite = con.getCloudSite("MT"); - assertNotNull(cloudSite); - assertEquals("regionOne", cloudSite.getRegionId()); - assertEquals("MT_KEYSTONE", cloudSite.getIdentityServiceId()); + Optional<CloudSite> cloudSite = con.getCloudSite("MT"); + assertTrue(cloudSite.isPresent()); + assertEquals("regionOne", cloudSite.get().getRegionId()); + assertEquals("MT_KEYSTONE", cloudSite.get().getIdentityServiceId()); } @Test public void cloudSiteIsGotByClli_when_IdNotFound() throws MsoCloudIdentityNotFound { CloudConfig con = createTestObject(cloudConfigJsonFilePath); - CloudSite cloudSite = con.getCloudSite("CS_clli"); - assertNotNull(cloudSite); - assertEquals("clliRegion", cloudSite.getRegionId()); - assertEquals("CS_clli", cloudSite.getClli()); - assertEquals("CS_service", cloudSite.getIdentityServiceId()); + Optional<CloudSite> cloudSite = con.getCloudSite("CS_clli"); + assertTrue(cloudSite.isPresent()); + assertEquals("clliRegion", cloudSite.get().getRegionId()); + assertEquals("CS_clli", cloudSite.get().getClli()); + assertEquals("CS_service", cloudSite.get().getIdentityServiceId()); } @Test public void cloudSiteIsGotByDefault_when_IdAndClliNotFound() throws MsoCloudIdentityNotFound { CloudConfig con = createTestObject(cloudDefaultConfigJsonFilePath); - CloudSite cloudSite = con.getCloudSite("not_existing_id"); - assertNotNull(cloudSite); - assertEquals("not_existing_id", cloudSite.getId()); - assertEquals("not_existing_id", cloudSite.getRegionId()); + Optional<CloudSite> cloudSite = con.getCloudSite("not_existing_id"); + assertTrue(cloudSite.isPresent()); + assertEquals("not_existing_id", cloudSite.get().getId()); + assertEquals("not_existing_id", cloudSite.get().getRegionId()); } @Test diff --git a/adapters/mso-network-adapter/src/main/java/org/openecomp/mso/adapters/network/MsoNetworkAdapterImpl.java b/adapters/mso-network-adapter/src/main/java/org/openecomp/mso/adapters/network/MsoNetworkAdapterImpl.java index 687930673b..2c04ae9d6b 100644 --- a/adapters/mso-network-adapter/src/main/java/org/openecomp/mso/adapters/network/MsoNetworkAdapterImpl.java +++ b/adapters/mso-network-adapter/src/main/java/org/openecomp/mso/adapters/network/MsoNetworkAdapterImpl.java @@ -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"); } diff --git a/adapters/mso-tenant-adapter/src/main/java/org/openecomp/mso/adapters/tenant/MsoTenantAdapterImpl.java b/adapters/mso-tenant-adapter/src/main/java/org/openecomp/mso/adapters/tenant/MsoTenantAdapterImpl.java index 29f5630586..58169f6f92 100644 --- a/adapters/mso-tenant-adapter/src/main/java/org/openecomp/mso/adapters/tenant/MsoTenantAdapterImpl.java +++ b/adapters/mso-tenant-adapter/src/main/java/org/openecomp/mso/adapters/tenant/MsoTenantAdapterImpl.java @@ -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) { diff --git a/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/adapters/vnf/MsoVnfAdapterImpl.java b/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/adapters/vnf/MsoVnfAdapterImpl.java index f5a47bce01..7fe09be2b6 100644 --- a/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/adapters/vnf/MsoVnfAdapterImpl.java +++ b/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/adapters/vnf/MsoVnfAdapterImpl.java @@ -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); @@ -1701,26 +1700,25 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } if (minVersionVnf != null && maxVersionVnf != null) { MavenLikeVersioning aicV = new MavenLikeVersioning(); - CloudSite cloudSite = null; //String aicVersion = ""; if (this.cloudConfig == null) { this.cloudConfig = this.cloudConfigFactory.getCloudConfig(); } // double check if (this.cloudConfig != null) { - cloudSite = this.cloudConfig.getCloudSite(cloudSiteId); - if (cloudSite != null) { - aicV.setVersion(cloudSite.getAic_version()); + Optional<CloudSite> cloudSiteOpt = this.cloudConfig.getCloudSite(cloudSiteId); + if (cloudSiteOpt.isPresent()) { + aicV.setVersion(cloudSiteOpt.get().getAic_version()); if ((aicV.isMoreRecentThan(minVersionVnf) || aicV.isTheSameVersion(minVersionVnf)) // aic >= min && (aicV.isTheSameVersion(maxVersionVnf) || !(aicV.isMoreRecentThan(maxVersionVnf)))) { //aic <= max - LOGGER.debug("VNF Resource " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version()); + LOGGER.debug("VNF Resource " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version()); } else { // ERROR - String error = "VNF Resource type: " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version(); + String error = "VNF Resource type: " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version(); LOGGER.error(MessageEnum.RA_CONFIG_EXC, error, "OpenStack", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - setVersion"); LOGGER.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); - } + } } // let this error out downstream to avoid introducing uncertainty at this stage } else { LOGGER.debug("cloudConfig is NULL - cannot check cloud site version"); diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClient.java index ca815cf904..214be060e3 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClient.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClient.java @@ -32,13 +32,9 @@ import com.fasterxml.jackson.databind.JsonMappingException; public interface AAIRestClient { - Pservers getPhysicalServers(String hostName, String uuid); - - List<Pserver> getPhysicalServerByVnfId(String vnfId, String transactionLoggingUuid) throws UnsupportedEncodingException, JsonParseException, JsonMappingException, IOException; - - void updateMaintenceFlag(String vnfId,boolean inMaint, String transactionLoggingUuid) throws Exception; - - void updateMaintenceFlagVnfId(String vnfId, boolean inMaint, String transactionLoggingUuid) throws Exception; - - GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) throws Exception; +Pservers getPhysicalServers(String hostName, String uuid); +List<Pserver> getPhysicalServerByVnfId(String vnfId, String transactionLoggingUuid) throws UnsupportedEncodingException, JsonParseException, JsonMappingException, IOException; +void updateMaintenceFlag(String vnfId,boolean inMaint, String transactionLoggingUuid) throws JsonParseException, JsonMappingException, IOException; +void updateMaintenceFlagVnfId(String vnfId, boolean inMaint, String transactionLoggingUuid) throws JsonParseException, JsonMappingException , IOException; +GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) throws JsonParseException, JsonMappingException , IOException; } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClientImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClientImpl.java index ae8638f0b7..af1eddf491 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClientImpl.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClientImpl.java @@ -139,14 +139,14 @@ public class AAIRestClientImpl implements AAIRestClient { } @Override - public void updateMaintenceFlag(String vnfName, boolean inMaint, String transactionLoggingUuid) throws Exception { + public void updateMaintenceFlag(String vnfName, boolean inMaint, String transactionLoggingUuid) throws JsonParseException, JsonMappingException, IOException { GenericVnfs genericVnfs = webTarget.register(AAIResourcesObjectMapperProvider.class).path(ENDPOINT_GET_ALL_VNFS) .queryParam("vnf-name", vnfName).request().header("X-FromAppId", "MSO") .header("X-TransactionId", transactionLoggingUuid).header("Content-Type", "application/json") .accept(MediaType.APPLICATION_JSON_TYPE).get().readEntity(GenericVnfs.class); if (genericVnfs.getGenericVnf().size() > 1) - throw new Exception("Multiple Generic Vnfs Returned"); + throw new IndexOutOfBoundsException ("Multiple Generic Vnfs Returned"); GenericVnf genericVnf = genericVnfs.getGenericVnf().get(0); updateMaintenceFlagVnfId(genericVnf.getVnfId(), inMaint, transactionLoggingUuid); @@ -154,7 +154,7 @@ public class AAIRestClientImpl implements AAIRestClient { @Override public void updateMaintenceFlagVnfId(String vnfId, boolean inMaint, String transactionLoggingUuid) - throws Exception { + throws JsonParseException, JsonMappingException, IOException { GenericVnf genericVnf = new GenericVnf(); genericVnf.setInMaint(inMaint); webTarget.register(AAIResourcesObjectMapperProvider.class).path(GENERIC_VNF_PATH + "/" + vnfId).request() @@ -165,7 +165,7 @@ public class AAIRestClientImpl implements AAIRestClient { } @Override - public GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) throws Exception { + public GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) throws JsonParseException, JsonMappingException, IOException { return webTarget.register(AAIResourcesObjectMapperProvider.class).path(GENERIC_VNF_PATH + "/" + vnfId).request() .header("X-FromAppId", "MSO").header("X-TransactionId", transactionLoggingUuid) .header("Content-Type", "application/json").accept(MediaType.APPLICATION_JSON_TYPE).get() diff --git a/mso-api-handlers/mso-requests-db/pom.xml b/mso-api-handlers/mso-requests-db/pom.xml index 6a4941e53e..cdfa0fa8db 100644 --- a/mso-api-handlers/mso-requests-db/pom.xml +++ b/mso-api-handlers/mso-requests-db/pom.xml @@ -55,6 +55,12 @@ </exclusions> </dependency> <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>test</scope> + </dependency> + <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.6.Final</version> @@ -101,6 +107,12 @@ <artifactId>common</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>org.jmockit</groupId> + <artifactId>jmockit</artifactId> + <version>1.19</version> + <scope>test</scope> + </dependency> </dependencies> <packaging>jar</packaging> <build> diff --git a/mso-api-handlers/mso-requests-db/src/test/java/org/openecomp/mso/requestsdb/RequestsDatabaseTest.java b/mso-api-handlers/mso-requests-db/src/test/java/org/openecomp/mso/requestsdb/RequestsDatabaseTest.java new file mode 100644 index 0000000000..0bb126fa42 --- /dev/null +++ b/mso-api-handlers/mso-requests-db/src/test/java/org/openecomp/mso/requestsdb/RequestsDatabaseTest.java @@ -0,0 +1,283 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.mso.requestsdb; + + +import mockit.Expectations; +import mockit.Mocked; +import mockit.integration.junit4.JMockit; +import org.hibernate.Criteria; +import org.hibernate.Query; +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.mso.db.AbstractSessionFactoryManager; + +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(JMockit.class) +public class RequestsDatabaseTest { + + RequestsDatabase requestsDatabase = RequestsDatabase.getInstance(); + + @Test + public void getInstanceTest() throws Exception { + RequestsDatabase instance = RequestsDatabase.getInstance(); + assertEquals(RequestsDatabase.class, instance.getClass()); + } + + @Test + public void healthCheckTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked SQLQuery query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createSQLQuery(" show tables "); result = query; + query.list(); result = Arrays.asList("table1", "table2"); + }}; + + assertTrue(requestsDatabase.healthCheck()); + } + + @Test + public void updateInfraStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + query.executeUpdate(); result = 1; + }}; + assertEquals(1, requestsDatabase.updateInfraStatus("123", "unknown", "unknown")); + } + + @Test + public void updateInfraStatus1Test(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + query.executeUpdate(); result = 1; + }}; + assertEquals(1, requestsDatabase.updateInfraStatus("123", "unknown", 0, "unknown")); + } + + @Test + public void updateInfraFinalStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + query.executeUpdate(); result = 1; + }}; + assertEquals(1, requestsDatabase.updateInfraFinalStatus("123", + "unknown", + "statusMessage", + 0, + "responsebody", + "lastmodifiedby")); + } + + @Test + public void getRequestFromInfraActiveTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + query.uniqueResult(); result = new InfraActiveRequests("123", "action"); + }}; + assertEquals("123", + requestsDatabase.getRequestFromInfraActive("123").getRequestId()); + } + + @Test + public void getOrchestrationFiltersFromInfraActiveTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Criteria criteria) throws Exception { + + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createCriteria(InfraActiveRequests.class); result = criteria; + criteria.list(); result = Arrays.asList(new InfraActiveRequests("123", "action")); + }}; + assertEquals(1, + requestsDatabase.getRequestListFromInfraActive("queryattr", + "queryvalue", + "type").size()); + } + + @Test + public void getRequestListFromInfraActiveTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("from InfraActiveRequests where (requestId = :requestId OR clientRequestId = :requestId) and requestType = :requestType"); result = query; + query.uniqueResult(); result = new InfraActiveRequests("123", "action"); + }}; + assertEquals("123", + requestsDatabase.getRequestFromInfraActive("123", "requestType").getRequestId()); + } + + @Test + public void getRequestFromInfraActive1Test(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Criteria criteria) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createCriteria(InfraActiveRequests.class); result = criteria; + criteria.list(); result = Arrays.asList(new InfraActiveRequests()); + }}; + assertEquals(1, + requestsDatabase.getRequestListFromInfraActive("queryAttr", + "queryvalue", + "type").size()); + } + + @Test + public void checkDuplicateByVnfNameTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("from InfraActiveRequests where vnfName = :vnfName and action = :action and (requestStatus = 'PENDING' or requestStatus = 'IN_PROGRESS' or requestStatus = 'TIMEOUT') and requestType = :requestType ORDER BY startTime DESC"); result = query; + query.list(); result = Arrays.asList(new InfraActiveRequests("123", "action")); + }}; + assertEquals("123", + requestsDatabase.checkDuplicateByVnfName("vnfname", + "action", + "requesttype").getRequestId()); + } + + @Test + public void checkDuplicateByVnfIdTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("from InfraActiveRequests where vnfId = :vnfId and action = :action and (requestStatus = 'PENDING' or requestStatus = 'IN_PROGRESS' or requestStatus = 'TIMEOUT') and requestType = :requestType ORDER BY startTime DESC"); result = query; + query.list(); result = Arrays.asList(new InfraActiveRequests("123", "action")); + }}; + assertEquals("123", + requestsDatabase.checkDuplicateByVnfId("vnfname", + "action", + "requesttype").getRequestId()); + } + + @Test + public void setMockDBTest() throws Exception { + requestsDatabase.setMockDB(null); + } + + @Test + public void getSiteStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM SiteStatus WHERE siteName = :site_name"); result = query; + query.uniqueResult(); result = new SiteStatus(); + }}; + assertEquals(SiteStatus.class, + requestsDatabase.getSiteStatus("site").getClass()); + } + + @Test + public void updateSiteStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM SiteStatus WHERE siteName = :site_name"); result = query; + query.uniqueResult(); result = new SiteStatus(); + }}; + requestsDatabase.updateSiteStatus("site", true); + } + + @Test + public void getOperationStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM OperationStatus WHERE SERVICE_ID = :service_id and OPERATION_ID = :operation_id"); result = query; + query.uniqueResult(); result = new OperationStatus(); + }}; + assertEquals(OperationStatus.class, + requestsDatabase.getOperationStatus("123", + "Unknown").getClass()); + } + + @Test + public void getOperationStatusByServiceIdTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM OperationStatus WHERE SERVICE_ID = :service_id"); result = query; + query.uniqueResult(); result = new OperationStatus(); + }}; + assertEquals(OperationStatus.class, + requestsDatabase.getOperationStatusByServiceId("123").getClass()); + } + + @Test + public void getOperationStatusByServiceNameTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM OperationStatus WHERE SERVICE_NAME = :service_name"); result = query; + query.uniqueResult(); result = new OperationStatus(); + }}; + assertEquals(OperationStatus.class, + requestsDatabase.getOperationStatusByServiceName("servicename").getClass()); + } + + @Test + public void updateOperationStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM OperationStatus WHERE SERVICE_ID = :service_id and OPERATION_ID = :operation_id"); result = query; + query.uniqueResult(); result = new OperationStatus(); + }}; + requestsDatabase.updateOperationStatus(new OperationStatus()); + } + + @Test + public void getResourceOperationStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM ResourceOperationStatus WHERE serviceId = :service_id and operationId = :operation_id and resourceTemplateUUID= :uuid"); result = query; + query.uniqueResult(); result = new ResourceOperationStatus(); + }}; + assertEquals(ResourceOperationStatus.class, + requestsDatabase.getResourceOperationStatus("serviceId", + "operationid", + "123-uuid").getClass()); + } +} |