diff options
Diffstat (limited to 'adapters')
38 files changed, 740 insertions, 281 deletions
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java index 0a3c6acd84..50ebcc66ee 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java @@ -198,7 +198,9 @@ public class MsoCommonUtils { // Generate an alarm for 5XX and higher errors. if (re.getStatus() >= 500) { - + logger.error("{} {} OpenStackResponseException with response code {} on {}: ", + MessageEnum.RA_CONNECTION_EXCEPTION, ErrorCode.DataError.getValue(), re.getStatus(), context, + e); } } else if (e instanceof OpenStackConnectException) { OpenStackConnectException ce = (OpenStackConnectException) e; @@ -281,7 +283,9 @@ public class MsoCommonUtils { // Generate an alarm for 5XX and higher errors. if (re.getStatus() >= 500) { - + logger.error("{} {} OpenStackBaseException with response code {} on {}: ", + MessageEnum.RA_CONNECTION_EXCEPTION, ErrorCode.DataError.getValue(), re.getStatus(), context, + e); } } else if (e instanceof OpenStackConnectException) { OpenStackConnectException ce = (OpenStackConnectException) e; @@ -334,32 +338,6 @@ public class MsoCommonUtils { protected CreateStackParam createStackParam(String stackName, String heatTemplate, Map<String, ?> stackInputs, int timeoutMinutes, String environment, Map<String, Object> files, Map<String, Object> heatFiles) { - // Create local variables checking to see if we have an environment, nested, get_files - // Could later add some checks to see if it's valid. - boolean haveEnvtVariable = true; - if (environment == null || "".equalsIgnoreCase(environment.trim())) { - haveEnvtVariable = false; - logger.debug("createStackParam called with no environment variable"); - } else { - logger.debug("createStackParam called with an environment variable: {}", environment); - } - - boolean haveFiles = true; - if (files == null || files.isEmpty()) { - haveFiles = false; - logger.debug("createStackParam called with no files / child template ids"); - } else { - logger.debug("createStackParam called with {} files / child template ids", files.size()); - } - - boolean haveHeatFiles = true; - if (heatFiles == null || heatFiles.isEmpty()) { - haveHeatFiles = false; - logger.debug("createStackParam called with no heatFiles"); - } else { - logger.debug("createStackParam called with {} heatFiles", heatFiles.size()); - } - // force entire stackInput object to generic Map<String, Object> for openstack compatibility ObjectMapper mapper = new ObjectMapper(); Map<String, Object> normalized = new HashMap<>(); @@ -370,6 +348,28 @@ public class MsoCommonUtils { logger.debug("could not map json", e1); } + CreateStackParam stack = + createStack(stackName, heatTemplate, timeoutMinutes, environment, files, heatFiles, normalized); + + // 1802 - attempt to add better formatted printout of request to openstack + try { + Map<String, Object> inputs = new HashMap<>(); + for (Entry<String, ?> entry : stackInputs.entrySet()) { + if (entry.getValue() != null) { + inputs.put(entry.getKey(), entry.getValue()); + } + } + logger.debug("stack request: {}", stack); + } catch (Exception e) { + // that's okay - this is a nice-to-have + logger.debug("(had an issue printing nicely formatted request to debuglog) {}", e); + } + + return stack; + } + + private CreateStackParam createStack(String stackName, String heatTemplate, int timeoutMinutes, String environment, + Map<String, Object> files, Map<String, Object> heatFiles, Map<String, Object> normalized) { // Build up the stack to create // Disable auto-rollback, because error reason is lost. Always rollback in the code. CreateStackParam stack = new CreateStackParam(); @@ -379,13 +379,13 @@ public class MsoCommonUtils { stack.setTemplate(heatTemplate); stack.setDisableRollback(true); // TJM New for PO Adapter - add envt variable - if (haveEnvtVariable) { + if (isEnvVariablePresent(environment)) { logger.debug("Found an environment variable - value: {}", environment); stack.setEnvironment(environment); } // Now handle nested templates or get_files - have to combine if we have both // as they're both treated as "files:" on the stack. - if (haveFiles && haveHeatFiles) { + if (isFilesPresent(files) && isHeatFilesPresent(heatFiles)) { // Let's do this here - not in the bean logger.debug("Found files AND heatFiles - combine and add!"); Map<String, Object> combinedFiles = new HashMap<>(); @@ -398,32 +398,50 @@ public class MsoCommonUtils { stack.setFiles(combinedFiles); } else { // Handle if we only have one or neither: - if (haveFiles) { + if (isFilesPresent(files)) { logger.debug("Found files - adding to stack"); stack.setFiles(files); } - if (haveHeatFiles) { + if (isHeatFilesPresent(heatFiles)) { logger.debug("Found heatFiles - adding to stack"); // the setFiles was modified to handle adding the entries stack.setFiles(heatFiles); } } + return stack; + } - // 1802 - attempt to add better formatted printout of request to openstack - try { - Map<String, Object> inputs = new HashMap<>(); - for (Entry<String, ?> entry : stackInputs.entrySet()) { - if (entry.getValue() != null) { - inputs.put(entry.getKey(), entry.getValue()); - } - } - logger.debug("stack request: {}", stack.toString()); - } catch (Exception e) { - // that's okay - this is a nice-to-have - logger.debug("(had an issue printing nicely formatted request to debuglog) {}", e.getMessage()); + private boolean isEnvVariablePresent(String environment) { + boolean haveEnvVariable = true; + if (environment == null || "".equalsIgnoreCase(environment.trim())) { + haveEnvVariable = false; + logger.debug("createStackParam called with no environment variable"); + } else { + logger.debug("createStackParam called with an environment variable: {}", environment); } + return haveEnvVariable; + } - return stack; + private boolean isFilesPresent(Map<String, Object> files) { + boolean haveFile = true; + if (files == null || files.isEmpty()) { + haveFile = false; + logger.debug("createStackParam called with no files / child template ids"); + } else { + logger.debug("createStackParam called with {} files / child template ids", files.size()); + } + return haveFile; + } + + private boolean isHeatFilesPresent(Map<String, Object> heatFiles) { + boolean haveHeatFile = true; + if (heatFiles == null || heatFiles.isEmpty()) { + haveHeatFile = false; + logger.debug("createStackParam called with no heatFiles"); + } else { + logger.debug("createStackParam called with {} heatFiles", heatFiles.size()); + } + return haveHeatFile; } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java index 8207c7c589..97ba7828c0 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java @@ -33,6 +33,7 @@ import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.onap.logging.filter.base.ErrorCode; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.adapters.vdu.CloudInfo; import org.onap.so.adapters.vdu.PluginAction; @@ -45,14 +46,11 @@ import org.onap.so.adapters.vdu.VduPlugin; import org.onap.so.adapters.vdu.VduStateType; import org.onap.so.adapters.vdu.VduStatus; import org.onap.so.cloud.authentication.KeystoneAuthHolder; -import org.onap.so.db.catalog.beans.CloudIdentity; -import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.HeatTemplate; import org.onap.so.db.catalog.beans.HeatTemplateParam; import org.onap.so.db.request.beans.CloudApiRequests; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; -import org.onap.logging.filter.base.ErrorCode; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.CreateStackRequest; import org.onap.so.openstack.beans.HeatStatus; @@ -70,6 +68,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Strings; @@ -1191,7 +1190,11 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { InfraActiveRequests request = new InfraActiveRequests(); request.setRequestId(requestId); request.setResourceStatusMessage(resourceStatusMessage); - requestDBClient.patchInfraActiveRequests(request); + try { + requestDBClient.patchInfraActiveRequests(request); + } catch (HttpClientErrorException e) { + logger.warn("Unable to update active request resource status"); + } } } diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceInfo.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceInfo.java index 6c1c81c6ef..195ada37f7 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceInfo.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceInfo.java @@ -24,8 +24,11 @@ import org.onap.so.db.catalog.beans.Service; import org.onap.so.db.catalog.beans.ServiceInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.util.CollectionUtils; import javax.xml.bind.annotation.XmlRootElement; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; @XmlRootElement(name = "serviceInfo") @@ -45,8 +48,10 @@ public class QueryServiceInfo extends CatalogQuery { this.serviceInfo = new ServiceInfo(); } - public QueryServiceInfo(ServiceInfo serviceInfo) { - this.serviceInfo = serviceInfo; + public QueryServiceInfo(List<ServiceInfo> serviceInfos) { + if (!CollectionUtils.isEmpty(serviceInfos)) { + this.serviceInfo = serviceInfos.get(0); + } } public ServiceInfo getServiceInfo() { diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java index d5aa472c8d..305d52a997 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java @@ -94,7 +94,7 @@ public class QueryServiceMacroHolder extends CatalogQuery { subitem = new QueryAllottedResourceCustomization(service.getAllottedCustomizations()).JSON2(true, true); valueMap.put("_SERVICEALLOTTEDRESOURCES_", subitem.replaceAll(LINE_BEGINNING, "\t")); - subitem = new QueryServiceInfo(serviceMacroHolder.getServiceInfo()).JSON2(true, true); + subitem = new QueryServiceInfo(service.getServiceInfos()).JSON2(true, true); valueMap.put("_SERVICEINFO_", subitem.replaceAll(LINE_BEGINNING, "\t")); subitem = new QueryServiceProxyCustomization(service.getServiceProxyCustomizations()).JSON2(true, true); diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java index f2e0762a79..98abf15645 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java @@ -46,32 +46,8 @@ import org.onap.so.adapters.catalogdb.catalogrest.QueryServiceMacroHolder; import org.onap.so.adapters.catalogdb.catalogrest.QueryServiceNetworks; import org.onap.so.adapters.catalogdb.catalogrest.QueryServiceVnfs; import org.onap.so.adapters.catalogdb.catalogrest.QueryVfModule; -import org.onap.so.db.catalog.beans.AllottedResource; -import org.onap.so.db.catalog.beans.AllottedResourceCustomization; -import org.onap.so.db.catalog.beans.InstanceGroup; -import org.onap.so.db.catalog.beans.NetworkResource; -import org.onap.so.db.catalog.beans.NetworkResourceCustomization; -import org.onap.so.db.catalog.beans.Recipe; -import org.onap.so.db.catalog.beans.Service; -import org.onap.so.db.catalog.beans.ToscaCsar; -import org.onap.so.db.catalog.beans.VfModule; -import org.onap.so.db.catalog.beans.VfModuleCustomization; -import org.onap.so.db.catalog.beans.VnfRecipe; -import org.onap.so.db.catalog.beans.VnfResource; -import org.onap.so.db.catalog.beans.VnfResourceCustomization; -import org.onap.so.db.catalog.data.repository.AllottedResourceCustomizationRepository; -import org.onap.so.db.catalog.data.repository.AllottedResourceRepository; -import org.onap.so.db.catalog.data.repository.ArRecipeRepository; -import org.onap.so.db.catalog.data.repository.InstanceGroupRepository; -import org.onap.so.db.catalog.data.repository.NetworkRecipeRepository; -import org.onap.so.db.catalog.data.repository.NetworkResourceCustomizationRepository; -import org.onap.so.db.catalog.data.repository.NetworkResourceRepository; -import org.onap.so.db.catalog.data.repository.ServiceRepository; -import org.onap.so.db.catalog.data.repository.ToscaCsarRepository; -import org.onap.so.db.catalog.data.repository.VFModuleRepository; -import org.onap.so.db.catalog.data.repository.VnfCustomizationRepository; -import org.onap.so.db.catalog.data.repository.VnfRecipeRepository; -import org.onap.so.db.catalog.data.repository.VnfResourceRepository; +import org.onap.so.db.catalog.beans.*; +import org.onap.so.db.catalog.data.repository.*; import org.onap.so.db.catalog.rest.beans.ServiceMacroHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__MacroData.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__MacroData.sql index e5daf24d6c..b70d409cd8 100644 --- a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__MacroData.sql +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__MacroData.sql @@ -30,7 +30,8 @@ INSERT INTO northbound_request_ref_lookup(MACRO_ACTION, ACTION, REQUEST_SCOPE, I ('NetworkCollection-Macro-Create', 'createInstance', 'NetworkCollection', false,true, '7','7', 'DEFAULT', '*'), ('NetworkCollection-Macro-Delete', 'deleteInstance', 'NetworkCollection', false,true, '7','7', 'DEFAULT', '*'), ('VFModule-ScaleOut', 'scaleOut', 'VfModule', true, true, '7','7', 'DEFAULT', '*'), -('VNF-InPlaceUpdate', 'inPlaceSoftwareUpdate', 'Vnf', true, true, '7','7', 'DEFAULT', '*'); +('VNF-InPlaceUpdate', 'inPlaceSoftwareUpdate', 'Vnf', true, true, '7','7', 'DEFAULT', '*'), +('VNF-Config-Update', 'applyUpdatedConfig', 'Vnf', true, true, '7','7', 'DEFAULT', '*'); INSERT INTO orchestration_flow_reference(COMPOSITE_ACTION, SEQ_NO, FLOW_NAME, FLOW_VERSION, NB_REQ_REF_LOOKUP_ID) VALUES @@ -198,9 +199,16 @@ INSERT INTO orchestration_flow_reference(COMPOSITE_ACTION, SEQ_NO, FLOW_NAME, FL ('VNF-InPlaceUpdate', '15', 'VNFResumeTrafficActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-InPlaceUpdate' and CLOUD_OWNER = 'DEFAULT')), ('VNF-InPlaceUpdate', '16', 'VNFUnlockActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-InPlaceUpdate' and CLOUD_OWNER = 'DEFAULT')), ('VNF-InPlaceUpdate', '17', 'VNFUnsetInMaintFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-InPlaceUpdate' and CLOUD_OWNER = 'DEFAULT')), -('VNF-InPlaceUpdate', '18', 'VNFUnsetClosedLoopDisabledFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-InPlaceUpdate' and CLOUD_OWNER = 'DEFAULT')); - - +('VNF-InPlaceUpdate', '18', 'VNFUnsetClosedLoopDisabledFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-InPlaceUpdate' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '1', 'VNFCheckPserversLockedFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '2', 'VNFCheckInMaintFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '3', 'VNFSetInMaintFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '4', 'VNFSetClosedLoopDisabledFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '5', 'VNFHealthCheckActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '6', 'VNFConfigModifyActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '7', 'VNFHealthCheckActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '8', 'VNFUnsetInMaintFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '9', 'VNFUnsetClosedLoopDisabledFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')); INSERT INTO rainy_day_handler_macro (FLOW_NAME, SERVICE_TYPE, VNF_TYPE, ERROR_CODE, WORK_STEP, POLICY) VALUES @@ -860,7 +868,8 @@ VALUES ('VNFUpgradePostCheckActivity', 'NO_VALIDATE', 'CUSTOM'), ('VNFUpgradePreCheckActivity', 'NO_VALIDATE', 'CUSTOM'), ('VNFUpgradeSoftwareActivity', 'NO_VALIDATE', 'CUSTOM'), -('VnfInPlaceSoftwareUpdate', 'NO_VALIDATE', 'CUSTOM'); +('VnfInPlaceSoftwareUpdate', 'NO_VALIDATE', 'CUSTOM'), +('VNFConfigModifyActivity', 'NO_VALIDATE', 'CUSTOM'); UPDATE northbound_request_ref_lookup SET SERVICE_TYPE = '*' WHERE SERVICE_TYPE IS NULL; @@ -881,6 +890,10 @@ UPDATE vnf_recipe SET ORCHESTRATION_URI = '/mso/async/services/WorkflowActionBB' WHERE NF_ROLE = 'GR-API-DEFAULT' AND ACTION = 'inPlaceSoftwareUpdate'; +UPDATE vnf_recipe +SET ORCHESTRATION_URI = '/mso/async/services/WorkflowActionBB' +WHERE NF_ROLE = 'GR-API-DEFAULT' AND ACTION = 'applyUpdatedConfig'; + INSERT INTO rainy_day_handler_macro (FLOW_NAME, SERVICE_TYPE, VNF_TYPE, ERROR_CODE, WORK_STEP, POLICY, SECONDARY_POLICY, REG_EX_ERROR_MESSAGE, SERVICE_ROLE) VALUES ('VNFCheckPserversLockedFlagActivity','*','*','*','*','Manual','Abort','*', '*'), diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V7.5.1__AddServiceArtifact.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V7.5.1__AddServiceArtifact.sql new file mode 100644 index 0000000000..60a9482707 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V7.5.1__AddServiceArtifact.sql @@ -0,0 +1,17 @@ +use catalogdb; + + +ALTER TABLE `service_info` + ADD COLUMN IF NOT EXISTS SERVICE_MODEL_UUID varchar (200) + NOT NULL; + + +ALTER TABLE `service_artifact` DROP FOREIGN KEY `fk_service_artifact_service_info1`; + +ALTER TABLE `service_info` + ADD CONSTRAINT `fk_service_info_service1` FOREIGN KEY (`SERVICE_MODEL_UUID`) REFERENCES `service` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE `service_artifact` + ADD CONSTRAINT `fk_service_artifact_service1` FOREIGN KEY (`SERVICE_MODEL_UUID`) REFERENCES `service` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE; + +DROP TABLE IF EXISTS `service_to_service_info`; diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.5__AddCloudOwner.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.5__AddCloudOwner.sql new file mode 100644 index 0000000000..92502e2696 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.5__AddCloudOwner.sql @@ -0,0 +1,13 @@ +use catalogdb; + + +ALTER TABLE cloud_sites + ADD COLUMN IF NOT EXISTS CLOUD_OWNER varchar(255); + + +CREATE TABLE IF NOT EXISTS `network_technology_reference` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `NETWORK_TECHNOLOGY` varchar(200) NOT NULL , + `CLOUD_OWNER` varchar(200) NOT NULL, + PRIMARY KEY (`ID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1;
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.6__Update_Service_Function.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.6__Update_Service_Function.sql new file mode 100644 index 0000000000..51be8be664 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.6__Update_Service_Function.sql @@ -0,0 +1,4 @@ +use catalogdb; + +ALTER TABLE service + ADD COLUMN IF NOT EXISTS service_function varchar(200) DEFAULT NULL;
\ No newline at end of file diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java index 35008b6120..585e001f1a 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java @@ -24,9 +24,13 @@ import java.util.List; import java.util.Optional; import java.util.Set; import org.onap.aai.domain.yang.LInterface; +import org.onap.aai.domain.yang.VfModule; +import org.onap.aai.domain.yang.VfModules; import org.onap.aai.domain.yang.Vserver; import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.so.client.aai.entities.uri.AAIPluralResourceUri; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; @@ -53,11 +57,12 @@ public class AuditVServer extends AbstractAudit { public Optional<AAIObjectAuditList> auditVserversThroughRelationships(String genericVnfId, String vfModuleName) { AAIObjectAuditList auditList = new AAIObjectAuditList(); - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, genericVnfId) + AAIPluralResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, genericVnfId) .queryParam("vf-module-name", vfModuleName); - if (getAaiClient().get(uri).getRelationships().isPresent()) { + Optional<AAIResultWrapper> wrapper = getAaiClient().getFirstWrapper(VfModules.class, VfModule.class, uri); + if (wrapper.isPresent() && wrapper.get().getRelationships().isPresent()) { List<AAIResourceUri> relatedVservers = - getAaiClient().get(uri).getRelationships().get().getRelatedUris(AAIObjectType.VSERVER); + wrapper.get().getRelationships().get().getRelatedUris(AAIObjectType.VSERVER); if (!relatedVservers.isEmpty()) { relatedVservers.forEach(vserverUri -> { Optional<Vserver> vserver = getAaiClient().get(vserverUri).asBean(Vserver.class); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRegionRestV1.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRegionRestV1.java index 780480507b..6cf42e1433 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRegionRestV1.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRegionRestV1.java @@ -56,7 +56,6 @@ public class CloudRegionRestV1 { private CloudRestImpl cloudRestImpl; @POST - @Path("{cloud-region-id}/{cloud-owner}") @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) @ApiOperation(value = "CreateCloudRegion", response = Response.class, @@ -65,9 +64,8 @@ public class CloudRegionRestV1 { @ApiResponse(code = 500, message = "Create Cloud Region has failed")}) public Response createCloudRegion( @ApiParam(value = "cloud-region-id", required = true) @PathParam("cloud-region-id") String cloudRegionId, - @ApiParam(value = "cloud-owner", required = true) @PathParam("cloud-owner") String cloudOwner, @ApiParam(value = "CloudSite", required = true) final CloudSite cloudSite) { - cloudRestImpl.createCloudRegion(cloudSite, cloudOwner); + cloudRestImpl.createCloudRegion(cloudSite); return Response.status(HttpStatus.SC_CREATED).build(); } @@ -96,7 +94,7 @@ public class CloudRegionRestV1 { @ApiParam(value = "cloud-region-id", required = true) @PathParam("cloud-region-id") String cloudRegionId, @ApiParam(value = "cloud-owner", required = true) @PathParam("cloud-owner") String cloudOwner, @ApiParam(value = "CloudSite", required = true) final CloudSite cloudSite) { - cloudRestImpl.updateCloudRegion(cloudSite, cloudOwner); + cloudRestImpl.updateCloudRegion(cloudSite); return Response.status(HttpStatus.SC_OK).build(); } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRestImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRestImpl.java index 4cde8655ae..380f42fa69 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRestImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRestImpl.java @@ -1,13 +1,21 @@ package org.onap.so.adapters.cloudregion; +import java.util.List; import java.util.Optional; import org.onap.aai.domain.yang.CloudRegion; +import org.onap.aai.domain.yang.Complex; +import org.onap.aai.domain.yang.NetworkTechnologies; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.uri.AAIPluralResourceUri; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.db.catalog.beans.CloudSite; +import org.onap.so.db.catalog.beans.NetworkTechnologyReference; import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.catalog.data.repository.NetworkTechnologyReferenceRepository; +import org.onap.so.db.catalog.utils.MavenLikeVersioning; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -21,14 +29,17 @@ public class CloudRestImpl { private AAIResourcesClient aaiClient; @Autowired + private NetworkTechnologyReferenceRepository ctrRepo; + + @Autowired private CatalogDbClient catalogDBClient; - public void createCloudRegion(CloudSite cloudSite, String cloudOwner) throws CloudException { + public void createCloudRegion(CloudSite cloudSite) throws CloudException { createRegionInCatalogDb(cloudSite); - createCloudRegionInAAI(cloudSite, cloudOwner); + createCloudRegionInAAI(cloudSite); } - public void updateCloudRegion(CloudSite cloudSite, String cloudOwner) throws CloudException { + public void updateCloudRegion(CloudSite cloudSite) throws CloudException { updateRegionInCatalogDb(cloudSite); } @@ -50,18 +61,49 @@ public class CloudRestImpl { } } - protected void createCloudRegionInAAI(CloudSite cloudSite, String cloudOwner) { + protected void createCloudRegionInAAI(CloudSite cloudSite) { try { - CloudRegion cloudRegion = mapCloudRegion(cloudSite, cloudOwner); - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, + CloudRegion cloudRegion = mapCloudRegion(cloudSite); + Optional<Complex> complex = retrieveComplex(cloudSite); + if (complex.isPresent()) { + cloudRegion.setComplexName(complex.get().getComplexName()); + } + AAIResourceUri cloudRegionURI = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, cloudRegion.getCloudOwner(), cloudRegion.getCloudRegionId()); - getAaiClient().createIfNotExists(uri, Optional.of(cloudRegion)); + getAaiClient().createIfNotExists(cloudRegionURI, Optional.of(cloudRegion)); + if (complex.isPresent()) { + AAIResourceUri complexURI = AAIUriFactory.createResourceUri(AAIObjectType.COMPLEX, cloudSite.getClli()); + getAaiClient().connect(cloudRegionURI, complexURI); + } + createCloudRegionNetworkTechnologyRelationship(cloudSite, cloudRegionURI); } catch (Exception e) { logger.error("Error creating cloud region in AAI", e); throw new CloudException("Error creating cloud region in AAI: " + e.getMessage(), e); } } + protected void createCloudRegionNetworkTechnologyRelationship(CloudSite cloudSite, AAIResourceUri cloudRegionURI) { + List<NetworkTechnologyReference> listOfNetworkTech = ctrRepo.findAllByCloudOwner(cloudSite.getCloudOwner()); + listOfNetworkTech.stream().forEach(tech -> linkCloudAndTechnology(tech.getNetworkTechnology(), cloudRegionURI)); + } + + protected Optional<Complex> retrieveComplex(CloudSite cloudSite) { + AAIResourceUri complexURI = AAIUriFactory.createResourceUri(AAIObjectType.COMPLEX, cloudSite.getClli()); + return getAaiClient().get(Complex.class, complexURI); + } + + protected void linkCloudAndTechnology(String networkTechnologyName, AAIResourceUri cloudRegionURI) { + AAIPluralResourceUri technologyPluralUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_TECHNOLOGY) + .queryParam("network-technology-name", networkTechnologyName); + Optional<NetworkTechnologies> networkTechnology = + getAaiClient().get(NetworkTechnologies.class, technologyPluralUri); + if (networkTechnology.isPresent()) { + AAIResourceUri networkTechnologyURI = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_TECHNOLOGY, + networkTechnology.get().getNetworkTechnology().get(0).getNetworkTechnologyId()); + getAaiClient().connect(cloudRegionURI, networkTechnologyURI); + } + } + protected void createRegionInCatalogDb(CloudSite cloudSite) throws CloudException { try { CloudSite existingCloudSite = catalogDBClient.getCloudSite(cloudSite.getRegionId()); @@ -74,16 +116,22 @@ public class CloudRestImpl { } } - protected CloudRegion mapCloudRegion(CloudSite cloudSite, String cloudOwner) { + protected CloudRegion mapCloudRegion(CloudSite cloudSite) { CloudRegion region = new CloudRegion(); - region.setCloudOwner(cloudOwner); + region.setCloudOwner(cloudSite.getCloudOwner()); region.setCloudRegionId(cloudSite.getRegionId()); region.setCloudRegionVersion(cloudSite.getCloudVersion()); region.setOwnerDefinedType("cLCP"); + region.setCloudType("openstack"); + MavenLikeVersioning cloudVersion = new MavenLikeVersioning(); + cloudVersion.setVersion(cloudSite.getCloudVersion()); + if (cloudVersion.isMoreRecentThan("3.0")) { + region.setCloudZone(cloudSite.getRegionId().substring(0, cloudSite.getRegionId().length() - 1)); + } else { + region.setCloudZone(cloudSite.getRegionId()); + } region.setOrchestrationDisabled(false); - region.setComplexName("NA"); region.setInMaint(false); - region.setCloudType("openstack"); return region; } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java index 257374fdb2..4728effdca 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java @@ -97,7 +97,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { private static final String NETWORK_CREATED_STATUS_MESSAGE = "The new network was successfully created in the cloud"; private static final String NETWORK_NOT_EXIST_STATUS_MESSAGE = - "The network as not found, thus no network was deleted in the cloud via this request"; + "The network was not found, thus no network was deleted in the cloud via this request"; private static final String NETWORK_DELETED_STATUS_MESSAGE = "The network was successfully deleted in the cloud"; private static final Logger logger = LoggerFactory.getLogger(MsoNetworkAdapterImpl.class); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java index 32e88d8cad..f495015261 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java @@ -33,6 +33,7 @@ import java.util.Optional; import javax.jws.WebService; import javax.xml.ws.Holder; import org.apache.commons.collections.CollectionUtils; +import org.onap.logging.filter.base.ErrorCode; import org.onap.so.adapters.vnf.exceptions.VnfException; import org.onap.so.adapters.vnf.exceptions.VnfNotFound; import org.onap.so.client.aai.AAIResourcesClient; @@ -53,7 +54,6 @@ import org.onap.so.entity.MsoRequest; import org.onap.so.heatbridge.HeatBridgeApi; import org.onap.so.heatbridge.HeatBridgeException; import org.onap.so.heatbridge.HeatBridgeImpl; -import org.onap.logging.filter.base.ErrorCode; import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.HeatStatus; @@ -104,8 +104,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { private static final String DELETE_VNF = "DeleteVNF"; private static final String QUERY_STACK = "QueryStack"; private static final String CREATE_VFM_MODULE = "CreateVFModule"; - private static final String CREATE_VF_STACK = "Create VF: Stack"; - private static final String STACK = "Stack"; private static final String USER_ERROR = "USER ERROR"; private static final String VERSION_MIN = "VersionMin"; private static final String VERSION_MAX = "VersionMax"; @@ -113,7 +111,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { "The vf module was found to already exist, thus no new vf module was created in the cloud via this request"; private static final String VF_CREATED_STATUS_MESSAGE = "The new vf module was successfully created in the cloud"; private static final String VF_NOT_EXIST_STATUS_MESSAGE = - "The vf module was not, thus no vf module was deleted in the cloud via this request"; + "The vf module was not found, thus no vf module was deleted in the cloud via this request"; private static final String VF_DELETED_STATUS_MESSAGE = "The vf module was successfully deleted in the cloud"; @Autowired @@ -1052,9 +1050,10 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { heatStack = msoHeatUtils.createStack(cloudSiteId, cloudOwner, tenantId, vfModuleName, null, template, goldenInputs, true, heatTemplate.getTimeoutMinutes(), newEnvironmentString, nestedTemplatesChecked, heatFilesObjects, backout.booleanValue(), failIfExists); - - msoHeatUtils.updateResourceStatus(msoRequest.getRequestId(), - heatStack.isOperationPerformed() ? VF_EXIST_STATUS_MESSAGE : VF_CREATED_STATUS_MESSAGE); + if (msoRequest.getRequestId() != null) { + msoHeatUtils.updateResourceStatus(msoRequest.getRequestId(), + heatStack.isOperationPerformed() ? VF_CREATED_STATUS_MESSAGE : VF_EXIST_STATUS_MESSAGE); + } } else { throw new MsoHeatNotFoundException(); } diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java index 3d9a128318..8e71ec46b0 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java @@ -22,17 +22,12 @@ package org.onap.so.adapters.audit; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashSet; -import java.util.List; import java.util.Optional; import java.util.Set; -import java.util.stream.Stream; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -43,9 +38,8 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.LInterface; import org.onap.aai.domain.yang.LInterfaces; -import org.onap.aai.domain.yang.Relationship; -import org.onap.aai.domain.yang.RelationshipList; import org.onap.aai.domain.yang.VfModule; +import org.onap.aai.domain.yang.VfModules; import org.onap.aai.domain.yang.Vserver; import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; @@ -60,8 +54,6 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.woorea.openstack.heat.model.Resource; -import com.woorea.openstack.heat.model.Resources; @RunWith(MockitoJUnitRunner.Silent.class) public class AuditVServerTest extends AuditVServer { @@ -399,9 +391,9 @@ public class AuditVServerTest extends AuditVServer { AAIResultWrapper wrapper = new AAIResultWrapper(vfModule); - doReturn(wrapper).when(aaiResourcesMock) - .get(AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, "genericVnfId") - .queryParam("vf-module-name", "vfModuleName")); + doReturn(Optional.of(wrapper)).when(aaiResourcesMock).getFirstWrapper(VfModules.class, VfModule.class, + AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, "genericVnfId").queryParam("vf-module-name", + "vfModuleName")); Optional<AAIObjectAuditList> auditList = auditNova.auditVserversThroughRelationships("genericVnfId", "vfModuleName"); @@ -417,9 +409,9 @@ public class AuditVServerTest extends AuditVServer { AAIResultWrapper wrapper = new AAIResultWrapper(vfModule); AAIResultWrapper vserverWrapper = new AAIResultWrapper(new Vserver()); - doReturn(wrapper).when(aaiResourcesMock) - .get(AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, "genericVnfId") - .queryParam("vf-module-name", "vfModuleName")); + doReturn(Optional.of(wrapper)).when(aaiResourcesMock).getFirstWrapper(VfModules.class, VfModule.class, + AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, "genericVnfId").queryParam("vf-module-name", + "vfModuleName")); doReturn(vserverWrapper).when(aaiResourcesMock).get(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, "cloud-owner", "cloud-region-id", "tenant-id", "VUSCHGA1")); diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/cloudregion/CloudRegionRestImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/cloudregion/CloudRegionRestImplTest.java index 9c62c286ac..2df56ede10 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/cloudregion/CloudRegionRestImplTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/cloudregion/CloudRegionRestImplTest.java @@ -23,6 +23,7 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.catalog.data.repository.NetworkTechnologyReferenceRepository; @RunWith(MockitoJUnitRunner.class) @@ -38,6 +39,9 @@ public class CloudRegionRestImplTest { @Mock private AAIResourcesClient aaiResClientMock; + @Mock + private NetworkTechnologyReferenceRepository ntRepoMock; + private CloudSite cloudSite = new CloudSite(); private CloudRegion testCloudRegion = new CloudRegion(); @@ -46,30 +50,52 @@ public class CloudRegionRestImplTest { public void setup() { cloudSite.setCloudVersion("1.0"); cloudSite.setRegionId("region1"); + cloudSite.setCloudOwner("bob"); Mockito.doReturn(aaiResClientMock).when(cloudRestImpl).getAaiClient(); testCloudRegion.setCloudOwner("bob"); testCloudRegion.setCloudRegionId("region1"); testCloudRegion.setCloudRegionVersion("1.0"); testCloudRegion.setInMaint(false); testCloudRegion.setOrchestrationDisabled(false); - testCloudRegion.setComplexName("NA"); testCloudRegion.setCloudRegionVersion("1.0"); testCloudRegion.setOwnerDefinedType("cLCP"); testCloudRegion.setCloudType("openstack"); + testCloudRegion.setCloudZone("region1"); } @Test public void mapCloudRegionTest() { - CloudRegion mappedRegion = cloudRestImpl.mapCloudRegion(cloudSite, "bob"); + CloudRegion mappedRegion = cloudRestImpl.mapCloudRegion(cloudSite); assertThat(mappedRegion, sameBeanAs(testCloudRegion)); } + + @Test + public void mapCloudRegionVersionGreaterThan3Test() { + CloudSite cloudSite2 = new CloudSite(); + cloudSite2.setCloudVersion("3.0.1"); + cloudSite2.setRegionId("region1"); + cloudSite2.setCloudOwner("bob"); + + CloudRegion mappedRegion = cloudRestImpl.mapCloudRegion(cloudSite2); + CloudRegion testRegion2 = new CloudRegion(); + testRegion2.setCloudOwner("bob"); + testRegion2.setCloudRegionId("region1"); + testRegion2.setCloudRegionVersion("3.0.1"); + testRegion2.setInMaint(false); + testRegion2.setOrchestrationDisabled(false); + testRegion2.setOwnerDefinedType("cLCP"); + testRegion2.setCloudType("openstack"); + testRegion2.setCloudZone("region"); + assertThat(mappedRegion, sameBeanAs(testRegion2)); + } + @Test public void createCloudRegionTest() { when(catalogDbClientMock.getCloudSite("region1")).thenReturn(null); when(catalogDbClientMock.postCloudSite(cloudSite)).thenReturn(cloudSite); AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, "bob", "region1"); - cloudRestImpl.createCloudRegion(cloudSite, "bob"); + cloudRestImpl.createCloudRegion(cloudSite); ArgumentCaptor<AAIResourceUri> actualURI = ArgumentCaptor.forClass(AAIResourceUri.class); ArgumentCaptor<Optional<Object>> actualCloudRegion = ArgumentCaptor.forClass(Optional.class); verify(catalogDbClientMock, times(1)).getCloudSite("region1"); @@ -82,7 +108,7 @@ public class CloudRegionRestImplTest { @Test public void updateCloudRegionTest() { when(catalogDbClientMock.updateCloudSite(cloudSite)).thenReturn(cloudSite); - cloudRestImpl.updateCloudRegion(cloudSite, "bob"); + cloudRestImpl.updateCloudRegion(cloudSite); verify(catalogDbClientMock, times(1)).updateCloudSite(cloudSite); } diff --git a/adapters/mso-openstack-adapters/src/test/resources/schema.sql b/adapters/mso-openstack-adapters/src/test/resources/schema.sql index 6b791e789c..3357fec109 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/schema.sql +++ b/adapters/mso-openstack-adapters/src/test/resources/schema.sql @@ -801,6 +801,7 @@ CREATE TABLE `service` ( `TOSCA_CSAR_ARTIFACT_UUID` varchar(200) DEFAULT NULL, `SERVICE_TYPE` varchar(200) DEFAULT NULL, `SERVICE_ROLE` varchar(200) DEFAULT NULL, + `SERVICE_FUNCTION` varchar(200) DEFAULT NULL, `ENVIRONMENT_CONTEXT` varchar(200) DEFAULT NULL, `WORKLOAD_CONTEXT` varchar(200) DEFAULT NULL, `SERVICE_CATEGORY` varchar(200) DEFAULT NULL, diff --git a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V8.2__Fix_Invalid_Request_Status.sql b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V8.2__Fix_Invalid_Request_Status.sql new file mode 100644 index 0000000000..9fee716326 --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V8.2__Fix_Invalid_Request_Status.sql @@ -0,0 +1,4 @@ +USE `requestdb`; + +UPDATE infra_active_requests SET request_status='COMPLETE' where request_status = 'COMPLETED'; +UPDATE archived_infra_requests SET request_status='COMPLETE' where request_status = 'COMPLETED';
\ No newline at end of file diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java index 431e9db87b..ea24a0ce3e 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java @@ -11,9 +11,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. @@ -27,6 +27,8 @@ package org.onap.so.adapters.sdnc.sdncrest; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; +import java.util.Arrays; +import java.util.List; import javax.xml.XMLConstants; import javax.xml.bind.DatatypeConverter; import javax.xml.parsers.DocumentBuilderFactory; @@ -71,7 +73,6 @@ import org.springframework.core.env.Environment; public abstract class SDNCConnector { private static final Logger logger = LoggerFactory.getLogger(SDNCConnector.class); - private static final String MSO_INTERNAL_ERROR = "MsoInternalError"; private static final String XPATH_EXCEPTION = "XPath Exception"; @Autowired private Environment env; @@ -84,32 +85,10 @@ public abstract class SDNCConnector { HttpResponse httpResponse = null; try { - int timeout = Integer.parseInt(rt.getTimeout()); - - RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout) - .setConnectionRequestTimeout(timeout).build(); HttpClient client = HttpClientBuilder.create().build(); - if ("POST".equals(rt.getReqMethod())) { - HttpPost httpPost = new HttpPost(rt.getSdncUrl()); - httpPost.setConfig(requestConfig); - httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_XML)); - method = httpPost; - } else if ("PUT".equals(rt.getReqMethod())) { - HttpPut httpPut = new HttpPut(rt.getSdncUrl()); - httpPut.setConfig(requestConfig); - httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_XML)); - method = httpPut; - } else if ("GET".equals(rt.getReqMethod())) { - HttpGet httpGet = new HttpGet(rt.getSdncUrl()); - httpGet.setConfig(requestConfig); - method = httpGet; - } else if ("DELETE".equals(rt.getReqMethod())) { - HttpDelete httpDelete = new HttpDelete(rt.getSdncUrl()); - httpDelete.setConfig(requestConfig); - method = httpDelete; - } + method = getHttpRequestMethod(content, rt); String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.SDNC_AUTH_PROP), @@ -122,8 +101,6 @@ public abstract class SDNCConnector { logger.debug("method is NULL:"); } - - httpResponse = client.execute(method); String responseContent = null; @@ -141,7 +118,7 @@ public abstract class SDNCConnector { String errMsg = "SDNC returned " + statusCode + " " + statusMessage; String errors = analyzeErrors(responseContent); - if (errors != null) { + if (errors != null && !errors.isEmpty()) { errMsg += " " + errors; } @@ -192,6 +169,36 @@ public abstract class SDNCConnector { } } + private HttpRequestBase getHttpRequestMethod(String content, TypedRequestTunables rt) { + + int timeout = Integer.parseInt(rt.getTimeout()); + HttpRequestBase method = null; + + RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout) + .setConnectionRequestTimeout(timeout).build(); + + if ("POST".equals(rt.getReqMethod())) { + HttpPost httpPost = new HttpPost(rt.getSdncUrl()); + httpPost.setConfig(requestConfig); + httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_XML)); + method = httpPost; + } else if ("PUT".equals(rt.getReqMethod())) { + HttpPut httpPut = new HttpPut(rt.getSdncUrl()); + httpPut.setConfig(requestConfig); + httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_XML)); + method = httpPut; + } else if ("GET".equals(rt.getReqMethod())) { + HttpGet httpGet = new HttpGet(rt.getSdncUrl()); + httpGet.setConfig(requestConfig); + method = httpGet; + } else if ("DELETE".equals(rt.getReqMethod())) { + HttpDelete httpDelete = new HttpDelete(rt.getSdncUrl()); + httpDelete.setConfig(requestConfig); + method = httpDelete; + } + return method; + } + protected void logError(String errMsg) { logger.error(LoggingAnchor.FOUR, MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC", ErrorCode.AvailabilityError.getValue(), errMsg); @@ -205,7 +212,7 @@ public abstract class SDNCConnector { /** * Generates a response object from content received from SDNC. The response object may be a success response object * or an error response object. This method must be overridden by the subclass to return the correct object type. - * + * * @param statusCode the response status code from SDNC (e.g. 200) * @param statusMessage the response status message from SDNC (e.g. "OK") * @param responseContent the body of the response from SDNC (possibly null) @@ -218,7 +225,7 @@ public abstract class SDNCConnector { /** * Generates an error response object. This method must be overridden by the subclass to return the correct object * type. - * + * * @param statusCode the response status code (from SDNC, or internally generated) * @param errMsg the error message (normally a verbose explanation of the error) * @param rt request tunables @@ -229,17 +236,17 @@ public abstract class SDNCConnector { /** * Called by the send() method to analyze errors that may be encoded in the content of non-2XX responses. By * default, this method tries to parse the content as a restconf error. - * + * * <pre> * xmlns = "urn:ietf:params:xml:ns:yang:ietf-restconf" * </pre> - * + * * If an error (or errors) can be obtained from the content, then the result is a string in this format: - * + * * <pre> * [error-type:TYPE, error-tag:TAG, error-message:MESSAGE] ... * </pre> - * + * * If no error could be obtained from the content, then the result is null. * <p> * The subclass can override this method to provide another implementation. @@ -262,7 +269,7 @@ public abstract class SDNCConnector { // </error> // </errors> - StringBuilder output = null; + String output = null; try { XPathFactory xpathFactory = XPathFactory.newInstance(); @@ -274,55 +281,47 @@ public abstract class SDNCConnector { InputSource source = new InputSource(new StringReader(content)); Document doc = documentBuilderFactory.newDocumentBuilder().parse(source); NodeList errors = (NodeList) xpath.evaluate("errors/error", doc, XPathConstants.NODESET); + StringBuilder errorDetails = getErrorDetails(xpath, errors); + if (errorDetails != null) { + output = errorDetails.toString(); + } + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_ANALYZE_ERROR_EXC.toString(), "SDNC", + ErrorCode.DataError.getValue(), "Exception while analyzing errors", e); + } - for (int i = 0; i < errors.getLength(); i++) { - Element error = (Element) errors.item(i); + return output; + } - String info = ""; + private StringBuilder getErrorDetails(XPath xpath, NodeList errors) { - try { - String errorType = xpath.evaluate("error-type", error); - info += "error-type:" + errorType; - } catch (XPathExpressionException e) { - logger.error(LoggingAnchor.SIX, MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-type", - error.toString(), "SDNC", ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e); - } + StringBuilder output = null; - try { - String errorTag = xpath.evaluate("error-tag", error); - if (!info.isEmpty()) { - info += ", "; - } - info += "error-tag:" + errorTag; - } catch (XPathExpressionException e) { - logger.error(LoggingAnchor.SIX, MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-tag", - error.toString(), "SDNC", ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e); - } + for (int i = 0; i < errors.getLength(); i++) { + Element error = (Element) errors.item(i); + + StringBuilder info = new StringBuilder(); + List<String> errorAttributesList = Arrays.asList("error-type", "error-tag", "error-message"); + + for (String errorAttrib : errorAttributesList) { try { - String errorMessage = xpath.evaluate("error-message", error); - if (!info.isEmpty()) { - info += ", "; - } - info += "error-message:" + errorMessage; - } catch (Exception e) { - logger.error(LoggingAnchor.SIX, MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-message", + String errorAttribValue = xpath.evaluate(errorAttrib, error); + info.append(errorAttrib).append(":").append(errorAttribValue); + } catch (XPathExpressionException e) { + logger.error(LoggingAnchor.SIX, MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), errorAttrib, error.toString(), "SDNC", ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e); } + } - if (!info.isEmpty()) { - if (output == null) { - output = new StringBuilder("[" + info + "]"); - } else { - output.append(" [").append(info).append("]"); - } + if (!info.toString().isEmpty()) { + if (output == null) { + output = new StringBuilder("[" + info + "]"); + } else { + output.append(" [").append(info).append("]"); } } - } catch (Exception e) { - logger.error(LoggingAnchor.FOUR, MessageEnum.RA_ANALYZE_ERROR_EXC.toString(), "SDNC", - ErrorCode.DataError.getValue(), "Exception while analyzing errors", e); } - - return output.toString(); + return output; } } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java index 6f76ea1eab..9dd95c6713 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnector.java @@ -11,9 +11,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. @@ -59,9 +59,6 @@ public class SDNCServiceRequestConnector extends SDNCConnector { TypedRequestTunables rt) { try { return parseResponseContent(responseContent); - } catch (ParseException e) { - logger.error("Error occured:", e); - return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage(), rt); } catch (Exception e) { logger.error("Error occured:", e); return createErrorResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage(), rt); @@ -79,10 +76,10 @@ public class SDNCServiceRequestConnector extends SDNCConnector { * response code contained in the content. For 2XX response codes, an SDNCServiceResponse is returned. Otherwise, an * SDNCServiceError is returned. If the content cannot be parsed, or if the content does not contain all required * elements, a parse exception is thrown. This method performs no logging or alarming. - * + * * @throws ParseException on error */ - public static SDNCResponseCommon parseResponseContent(String responseContent) + public SDNCResponseCommon parseResponseContent(String responseContent) throws ParseException, ParserConfigurationException, SAXException, IOException { // Note: this document builder is not namespace-aware, so namespaces are ignored. @@ -119,16 +116,24 @@ public class SDNCServiceRequestConnector extends SDNCConnector { List<Element> responseParameters = new ArrayList<>(); for (Element child : SDNCAdapterUtils.childElements(configurationResponseCommon)) { - if ("response-code".equals(child.getNodeName())) { - responseCode = child.getTextContent(); - } else if ("response-message".equals(child.getNodeName())) { - responseMessage = child.getTextContent(); - } else if ("svc-request-id".equals(child.getNodeName())) { - svcRequestId = child.getTextContent(); - } else if ("ack-final-indicator".equals(child.getNodeName())) { - ackFinalIndicator = child.getTextContent(); - } else if ("response-parameters".equals(child.getNodeName())) { - responseParameters.add(child); + + switch (child.getNodeName()) { + case "response-code": + responseCode = child.getTextContent(); + break; + case "response-message": + responseMessage = child.getTextContent(); + break; + case "svc-request-id": + svcRequestId = child.getTextContent(); + break; + case "ack-final-indicator": + ackFinalIndicator = child.getTextContent(); + break; + case "response-parameters": + responseParameters.add(child); + break; + default: } } @@ -167,8 +172,15 @@ public class SDNCServiceRequestConnector extends SDNCConnector { return new SDNCServiceError(svcRequestId, responseCode, responseMessage, ackFinalIndicator); } - // Create a success response object. + return createSDNCServiceResponse(responseCode, responseMessage, svcRequestId, ackFinalIndicator, + responseParameters); + + } + + private SDNCServiceResponse createSDNCServiceResponse(String responseCode, String responseMessage, + String svcRequestId, String ackFinalIndicator, List<Element> responseParameters) throws ParseException { + // Create a success response object. SDNCServiceResponse response = new SDNCServiceResponse(svcRequestId, responseCode, responseMessage, ackFinalIndicator); @@ -201,8 +213,6 @@ public class SDNCServiceRequestConnector extends SDNCConnector { response.addParam(tagName, tagValue); } - return response; - } } diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnectorTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnectorTest.java index 9911cae677..9adc6c52f5 100644 --- a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnectorTest.java +++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestConnectorTest.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. @@ -31,7 +31,8 @@ public class SDNCServiceRequestConnectorTest { public void parseResponseContentTest() throws Exception { String content = FileUtil.readResourceFile("SdncServiceResponse.xml"); - SDNCResponseCommon responseCommon = SDNCServiceRequestConnector.parseResponseContent(content); + SDNCServiceRequestConnector sdncServiceRequestConnector = new SDNCServiceRequestConnector(); + SDNCResponseCommon responseCommon = sdncServiceRequestConnector.parseResponseContent(content); assertNotNull(responseCommon); } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml index bb322eb1d8..54f05859d9 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml @@ -91,7 +91,57 @@ </execution> </executions> </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <executions> + <execution> + <id>add-source</id> + <phase>generate-sources</phase> + <goals> + <goal>add-source</goal> + </goals> + <configuration> + <sources> + <source>${project.basedir}/target/generated-sources/etsicatalog/notification/src/gen/java/main</source> + <source>${project.basedir}/target/generated-sources/sol003-vnf-packagemanagement/notification/src/gen/java/main</source> + <source>${project.basedir}/target/generated-sources/vnfmadapter/src/gen/java/main</source> + </sources> + </configuration> + </execution> + </executions> + </plugin> </plugins> + <pluginManagement> + <plugins> + <plugin> + <groupId>org.eclipse.m2e</groupId> + <artifactId>lifecycle-mapping</artifactId> + <version>1.0.0</version> + <configuration> + <lifecycleMappingMetadata> + <pluginExecutions> + <pluginExecution> + <pluginExecutionFilter> + <groupId>io.swagger</groupId> + <artifactId>swagger-codegen-maven-plugin</artifactId> + <goals> + <goal>generate</goal> + </goals> + <versionRange>[2.2.0,)</versionRange> + </pluginExecutionFilter> + <action> + <execute> + <runOnIncremental>false</runOnIncremental> + </execute> + </action> + </pluginExecution> + </pluginExecutions> + </lifecycleMappingMetadata> + </configuration> + </plugin> + </plugins> + </pluginManagement> </build> <dependencies> <dependency> diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/pom.xml b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/pom.xml index a643aaa5b8..ab524ca808 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/pom.xml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/pom.xml @@ -132,7 +132,60 @@ </execution> </executions> </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>build-helper-maven-plugin</artifactId> + <executions> + <execution> + <id>add-source</id> + <phase>generate-sources</phase> + <goals> + <goal>add-source</goal> + </goals> + <configuration> + <sources> + <source>${project.basedir}/target/generated-sources/etsicatalog/src/gen/java/main</source> + <source>${project.basedir}/target/generated-sources/sol003-vnf-packagemanagement/src/gen/java/main</source> + <source>${project.basedir}/target/generated-sources/sol003-vnf-grant/src/gen/java/main</source> + <source>${project.basedir}/target/generated-sources/sol003-vnf-lcn/src/gen/java/main</source> + <source>${project.basedir}/target/generated-sources/sol003-vnf-lcm/src/gen/java/main</source> + + </sources> + </configuration> + </execution> + </executions> + </plugin> </plugins> + <pluginManagement> + <plugins> + <plugin> + <groupId>org.eclipse.m2e</groupId> + <artifactId>lifecycle-mapping</artifactId> + <version>1.0.0</version> + <configuration> + <lifecycleMappingMetadata> + <pluginExecutions> + <pluginExecution> + <pluginExecutionFilter> + <groupId>io.swagger</groupId> + <artifactId>swagger-codegen-maven-plugin</artifactId> + <goals> + <goal>generate</goal> + </goals> + <versionRange>[2.2.0,)</versionRange> + </pluginExecutionFilter> + <action> + <execute> + <runOnIncremental>false</runOnIncremental> + </execute> + </action> + </pluginExecution> + </pluginExecutions> + </lifecycleMappingMetadata> + </configuration> + </plugin> + </plugins> + </pluginManagement> </build> <dependencies> diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/src/main/resources/ETSI-Catalog-API.json b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/src/main/resources/ETSI-Catalog-API.json index 3c5ec49b80..35a8c2bd3d 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/src/main/resources/ETSI-Catalog-API.json +++ b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/src/main/resources/ETSI-Catalog-API.json @@ -5,7 +5,7 @@ "description": "\n\nThe `swagger-ui` view can be found [here](/api/catalog/v1/swagger).\nThe `ReDoc` view can be found [here](/api/catalog/v1/redoc).\nThe swagger YAML document can be found [here](/api/catalog/v1/swagger.yaml).\nThe swagger JSON document can be found [here](/api/catalog/v1/swagger.json).", "version": "v1" }, - "host": "127.0.0.1:8000", + "host": "127.0.0.1:8806", "schemes": ["http"], "basePath": "/", "consumes": ["application/json"], @@ -2641,7 +2641,7 @@ "inputs": { "title": "Inputs", "description": "Inputs", - "type": "string" + "type": "object" } } }, @@ -2652,7 +2652,7 @@ "model": { "title": "Model", "description": "Model", - "type": "string" + "type": "object" } } }, @@ -2825,7 +2825,7 @@ "required": ["callbackUri"], "type": "object", "properties": { - "filters": { + "filter": { "$ref": "#/definitions/PkgmNotificationsFilter" }, "callbackUri": { diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java index f32a9b0fa9..caefe71993 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java @@ -55,7 +55,7 @@ public class PkgmSubscriptionRequestConverter implements new org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest(); etsiCatalogManagerSubscriptionRequest - .setFilters(getPkgmNotificationsFilter(pkgmSubscriptionRequest.getFilter())); + .setFilter(getPkgmNotificationsFilter(pkgmSubscriptionRequest.getFilter())); return etsiCatalogManagerSubscriptionRequest; } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java index 6840dd388b..860dfbbe9c 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java @@ -20,16 +20,41 @@ package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.ssl.SSLContextBuilder; +import org.onap.logging.filter.spring.SpringClientPayloadFilter; import org.onap.so.adapters.vnfmadapter.extclients.AbstractServiceProviderConfiguration; import org.onap.so.configuration.rest.BasicHttpHeadersProvider; -import org.onap.so.configuration.rest.HttpHeadersProvider; +import org.onap.so.configuration.rest.HttpClientConnectionConfiguration; +import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; import org.onap.so.rest.service.HttpRestServiceProvider; import org.onap.so.rest.service.HttpRestServiceProviderImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.Resource; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; /** @@ -41,16 +66,105 @@ import org.springframework.web.client.RestTemplate; @Configuration public class EtsiCatalogServiceProviderConfiguration extends AbstractServiceProviderConfiguration { - @Bean(name = "etsiCatalogServiceProvider") - public HttpRestServiceProvider httpRestServiceProvider( - @Qualifier(CONFIGURABLE_REST_TEMPLATE) @Autowired final RestTemplate restTemplate) { - return getHttpRestServiceProvider(restTemplate, new BasicHttpHeadersProvider()); + public static final String ETSI_CATALOG_REST_TEMPLATE_BEAN = "etsiCatalogRestTemplate"; + + public static final String ETSI_CATALOG_SERVICE_PROVIDER_BEAN = "etsiCatalogServiceProvider"; + + private final static Logger LOGGER = LoggerFactory.getLogger(EtsiCatalogServiceProviderConfiguration.class); + + private final HttpClientConnectionConfiguration clientConnectionConfiguration; + + @Value("${etsi-catalog-manager.http.client.ssl.trust-store:#{null}}") + private Resource trustStore; + @Value("${etsi-catalog-manager.http.client.ssl.trust-store-password:#{null}}") + private String trustStorePassword; + + @Autowired + public EtsiCatalogServiceProviderConfiguration( + final HttpClientConnectionConfiguration clientConnectionConfiguration) { + this.clientConnectionConfiguration = clientConnectionConfiguration; + } + + @Bean + @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) + public RestTemplate etsiCatalogRestTemplate() { + final RestTemplate restTemplate = new RestTemplate(); + restTemplate.getInterceptors().add(new SOSpringClientFilter()); + restTemplate.getInterceptors().add((new SpringClientPayloadFilter())); + return restTemplate; } - private HttpRestServiceProvider getHttpRestServiceProvider(final RestTemplate restTemplate, - final HttpHeadersProvider httpHeadersProvider) { + @Bean + @Qualifier(ETSI_CATALOG_SERVICE_PROVIDER_BEAN) + public HttpRestServiceProvider etsiCatalogHttpRestServiceProvider( + @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) final RestTemplate restTemplate) { setGsonMessageConverter(restTemplate); - return new HttpRestServiceProviderImpl(restTemplate, httpHeadersProvider); + + final HttpClientBuilder httpClientBuilder = getHttpClientBuilder(); + if (trustStore != null) { + try { + LOGGER.debug("Setting up HttpComponentsClientHttpRequestFactory with SSL Context"); + LOGGER.debug("Setting client trust-store: {}", trustStore.getURL()); + LOGGER.debug("Creating SSLConnectionSocketFactory with AllowAllHostsVerifier ... "); + final SSLContext sslContext = new SSLContextBuilder() + .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build(); + final SSLConnectionSocketFactory sslConnectionSocketFactory = + new SSLConnectionSocketFactory(sslContext, AllowAllHostsVerifier.INSTANCE); + httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory); + final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder + .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE) + .register("https", sslConnectionSocketFactory).build(); + + httpClientBuilder.setConnectionManager(getConnectionManager(socketFactoryRegistry)); + } catch (final KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException + | IOException exception) { + LOGGER.error("Error reading truststore, TLS connection will fail.", exception); + } + + } else { + LOGGER.debug("Setting connection manager without SSL ConnectionSocketFactory ..."); + httpClientBuilder.setConnectionManager(getConnectionManager()); + } + + final HttpComponentsClientHttpRequestFactory factory = + new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build()); + restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory)); + + return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders()); + } + + private PoolingHttpClientConnectionManager getConnectionManager( + final Registry<ConnectionSocketFactory> socketFactoryRegistry) { + return new PoolingHttpClientConnectionManager(socketFactoryRegistry, null, null, null, + clientConnectionConfiguration.getTimeToLiveInMins(), TimeUnit.MINUTES); + } + + private PoolingHttpClientConnectionManager getConnectionManager() { + return new PoolingHttpClientConnectionManager(clientConnectionConfiguration.getTimeToLiveInMins(), + TimeUnit.MINUTES); + } + + private HttpClientBuilder getHttpClientBuilder() { + return HttpClientBuilder.create().setMaxConnPerRoute(clientConnectionConfiguration.getMaxConnectionsPerRoute()) + .setMaxConnTotal(clientConnectionConfiguration.getMaxConnections()) + .setDefaultRequestConfig(getRequestConfig()); + } + + private RequestConfig getRequestConfig() { + return RequestConfig.custom().setSocketTimeout(clientConnectionConfiguration.getSocketTimeOutInMiliSeconds()) + .setConnectTimeout(clientConnectionConfiguration.getConnectionTimeOutInMilliSeconds()).build(); + } + + private static final class AllowAllHostsVerifier implements HostnameVerifier { + + private static final AllowAllHostsVerifier INSTANCE = new AllowAllHostsVerifier(); + + @Override + public boolean verify(final String hostname, final SSLSession session) { + LOGGER.debug("Skipping hostname verification ..."); + return true; + } + } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java index 30d084629c..cae413ce10 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java @@ -20,6 +20,7 @@ package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog; +import static org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_SERVICE_PROVIDER_BEAN; import java.util.Optional; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.NsdmSubscription; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscription; @@ -53,14 +54,14 @@ import org.springframework.stereotype.Service; public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvider { private static final Logger logger = LoggerFactory.getLogger(EtsiCatalogServiceProviderImpl.class); - @Qualifier("etsiCatalogServiceProvider") private final HttpRestServiceProvider httpServiceProvider; private final EtsiCatalogUrlProvider etsiCatalogUrlProvider; private final ConversionService conversionService; @Autowired public EtsiCatalogServiceProviderImpl(final EtsiCatalogUrlProvider etsiCatalogUrlProvider, - final HttpRestServiceProvider httpServiceProvider, final ConversionService conversionService) { + @Qualifier(ETSI_CATALOG_SERVICE_PROVIDER_BEAN) final HttpRestServiceProvider httpServiceProvider, + final ConversionService conversionService) { this.etsiCatalogUrlProvider = etsiCatalogUrlProvider; this.httpServiceProvider = httpServiceProvider; this.conversionService = conversionService; @@ -118,8 +119,10 @@ public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvide if (inlineResponse2001 != null) { responses[index] = inlineResponse2001; } + } else { + logger.error("Unable to find Converter for response class: {}", + vnfPackages[index].getClass()); } - logger.error("Unable to find Converter for response class: {}", vnfPackages[index].getClass()); } return Optional.of(responses); } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java new file mode 100644 index 0000000000..9ed17e4379 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.extclients.vnfm; + +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import org.onap.so.adapters.vnfmadapter.extclients.AbstractServiceProviderConfiguration; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.onap.so.rest.service.HttpRestServiceProviderImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Configuration +public class VnfmHttpServiceProviderConfiguration extends AbstractServiceProviderConfiguration { + public static final String VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN = "vnfmAdapterHttpServiceProvider"; + + @Bean + @Qualifier(VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN) + public HttpRestServiceProvider vnfmAdapterHttpRestServiceProvider( + @Autowired @Qualifier(CONFIGURABLE_REST_TEMPLATE) RestTemplate restTemplate) { + setGsonMessageConverter(restTemplate); + return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders()); + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java index 86ca59cffe..d6b7ae7201 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java @@ -19,16 +19,13 @@ */ package org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.onap.so.adapters.vnfmadapter.extclients.vnfm.VnfmHttpServiceProviderConfiguration.VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN; import java.nio.charset.StandardCharsets; import org.apache.commons.codec.binary.Base64; import org.onap.so.configuration.rest.BasicHttpHeadersProvider; -import org.onap.so.configuration.rest.HttpHeadersProvider; import org.onap.so.rest.service.HttpRestServiceProvider; -import org.onap.so.rest.service.HttpRestServiceProviderImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.web.client.RestTemplate; /** * A base class that can be extended by classes for providing notification services. Provides common methods that will @@ -40,12 +37,10 @@ import org.springframework.web.client.RestTemplate; public abstract class AbstractNotificationServiceProvider { @Autowired - @Qualifier(CONFIGURABLE_REST_TEMPLATE) - private RestTemplate restTemplate; + @Qualifier(VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN) + private HttpRestServiceProvider httpRestServiceProvider; - protected HttpRestServiceProvider getHttpRestServiceProvider(final HttpHeadersProvider httpHeadersProvider) { - final HttpRestServiceProvider httpRestServiceProvider = - new HttpRestServiceProviderImpl(restTemplate, httpHeadersProvider); + protected HttpRestServiceProvider getHttpRestServiceProvider() { return httpRestServiceProvider; } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java index 6f9d94e9de..cf0cdb085a 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java @@ -47,10 +47,10 @@ public class BasicAuthNotificationServiceProvider extends AbstractNotificationSe final HttpHeadersProvider httpHeadersProvider = getBasicHttpHeadersProviderWithBasicAuth(subscriptionsAuthentication.getParamsBasic().getUserName(), subscriptionsAuthentication.getParamsBasic().getPassword()); - final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(httpHeadersProvider); + final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(); - final ResponseEntity<Void> responseEntity = - httpRestServiceProvider.postHttpRequest(notification, callbackUri, Void.class); + final ResponseEntity<Void> responseEntity = httpRestServiceProvider.postHttpRequest(notification, callbackUri, + httpHeadersProvider.getHttpHeaders(), Void.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { logger.info("Notification sent successfully."); return true; diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java index 496fb083cf..c065203cd8 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java @@ -48,13 +48,14 @@ public class OAuthNotificationServiceProvider extends AbstractNotificationServic final String token = getAccessToken(subscriptionsAuthentication); if (token == null) { + logger.error("Failed to get access token"); return false; } final HttpHeadersProvider httpHeadersProvider = getHttpHeadersProvider(token); - final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(httpHeadersProvider); - final ResponseEntity<Void> responseEntity = - httpRestServiceProvider.postHttpRequest(notification, callbackUri, Void.class); + final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(); + final ResponseEntity<Void> responseEntity = httpRestServiceProvider.postHttpRequest(notification, callbackUri, + httpHeadersProvider.getHttpHeaders(), Void.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { logger.info("Notification sent successfully."); return true; @@ -83,9 +84,9 @@ public class OAuthNotificationServiceProvider extends AbstractNotificationServic subscriptionsAuthentication.getParamsOauth2ClientCredentials().getClientId(), subscriptionsAuthentication.getParamsOauth2ClientCredentials().getClientPassword()); - final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(httpHeadersProvider); - final ResponseEntity<OAuthTokenResponse> responseEntity = - httpRestServiceProvider.postHttpRequest(null, tokenEndpoint, OAuthTokenResponse.class); + final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(); + final ResponseEntity<OAuthTokenResponse> responseEntity = httpRestServiceProvider.postHttpRequest(null, + tokenEndpoint, httpHeadersProvider.getHttpHeaders(), OAuthTokenResponse.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { if (responseEntity.getBody() != null) { logger.info("Returning Access Token."); diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationControllerTest.java index 322251e753..29afa8c549 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationControllerTest.java @@ -278,7 +278,7 @@ public class EtsiSubscriptionNotificationControllerTest { mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) .andExpect(jsonPath("$.notificationType").value( - VnfPackageChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION.toString())) + VnfPackageChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION.getValue())) .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) .andExpect(jsonPath("$.timeStamp").value(TIMESTAMP.toString())) .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID.toString())) diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementControllerTest.java index c5194cf27e..31e612a812 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementControllerTest.java @@ -25,7 +25,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.onap.so.adapters.vnfmadapter.Constants.PACKAGE_MANAGEMENT_BASE_URL; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_REST_TEMPLATE_BEAN; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; @@ -74,11 +74,11 @@ public class Sol003PackageManagementControllerTest { private int port; @Autowired - @Qualifier(CONFIGURABLE_REST_TEMPLATE) - private RestTemplate testRestTemplate; + @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) + private RestTemplate restTemplate; @Autowired - private TestRestTemplate restTemplate; + private TestRestTemplate testRestTemplate; private static final String VNF_PACKAGE_ID = "myVnfPackageId"; private static final String ARTIFACT_PATH = "myArtifactPath"; @@ -104,8 +104,7 @@ public class Sol003PackageManagementControllerTest { @Before public void setUp() { - final MockRestServiceServer.MockRestServiceServerBuilder builder = - MockRestServiceServer.bindTo(testRestTemplate); + final MockRestServiceServer.MockRestServiceServerBuilder builder = MockRestServiceServer.bindTo(restTemplate); builder.ignoreExpectOrder(true); mockRestServer = builder.build(); basicHttpHeadersProvider = new BasicHttpHeadersProvider(); @@ -123,7 +122,7 @@ public class Sol003PackageManagementControllerTest { + VNF_PACKAGE_ID + "/package_content"; final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); final ResponseEntity<byte[]> responseEntity = - restTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); + testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); assertEquals(byte[].class, responseEntity.getBody().getClass()); assertArrayEquals(responseEntity.getBody(), responseArray); @@ -164,7 +163,7 @@ public class Sol003PackageManagementControllerTest { final ResponseEntity<ProblemDetails> responseEntity = - restTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); + testRestTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); assertTrue(responseEntity.getBody() instanceof ProblemDetails); assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); @@ -226,7 +225,7 @@ public class Sol003PackageManagementControllerTest { + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH; final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); final ResponseEntity<byte[]> responseEntity = - restTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); + testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); assertEquals(byte[].class, responseEntity.getBody().getClass()); assertArrayEquals(responseEntity.getBody(), responseArray); @@ -267,7 +266,7 @@ public class Sol003PackageManagementControllerTest { final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); final ResponseEntity<ProblemDetails> responseEntity = - restTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); + testRestTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); assertNotNull(responseEntity.getBody()); assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); @@ -331,7 +330,7 @@ public class Sol003PackageManagementControllerTest { final String testURL = localhostUrl + port + VNFPKGM_BASE_URL; final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - final ResponseEntity<InlineResponse2001[]> responseEntity = restTemplate.withBasicAuth("test", "test") + final ResponseEntity<InlineResponse2001[]> responseEntity = testRestTemplate.withBasicAuth("test", "test") .exchange(testURL, HttpMethod.GET, request, InlineResponse2001[].class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); @@ -412,7 +411,7 @@ public class Sol003PackageManagementControllerTest { final String testURL = localhostUrl + port + VNFPKGM_BASE_URL + "/" + VNF_PACKAGE_ID; final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - final ResponseEntity<InlineResponse2001> responseEntity = restTemplate.withBasicAuth("test", "test") + final ResponseEntity<InlineResponse2001> responseEntity = testRestTemplate.withBasicAuth("test", "test") .exchange(testURL, HttpMethod.GET, request, InlineResponse2001.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); @@ -484,7 +483,8 @@ public class Sol003PackageManagementControllerTest { + VNF_PACKAGE_ID + "\" \n" + "endpoint.", problemDetails.getDetail()); } - // The below test method is here to improve code coverage and provide a foundation for writing future tests + // The below test method is here to improve code coverage and provide a foundation for writing + // future tests @Test public void testGetPackageVnfd_ValidArray_Success() { final byte[] responseArray = buildByteArrayWithRandomData(10); @@ -497,7 +497,7 @@ public class Sol003PackageManagementControllerTest { "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + VNF_PACKAGE_ID + "/vnfd"; final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); final ResponseEntity<byte[]> responseEntity = - restTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); + testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); assertEquals(byte[].class, responseEntity.getBody().getClass()); assertArrayEquals(responseEntity.getBody(), responseArray); @@ -592,7 +592,7 @@ public class Sol003PackageManagementControllerTest { private ResponseEntity<ProblemDetails> sendHttpRequest(final String url) { final String testURL = localhostUrl + port + VNFPKGM_BASE_URL + "/" + url; final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - return restTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, + return testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); } @@ -652,4 +652,5 @@ public class Sol003PackageManagementControllerTest { final VNFPKGMLinkSerializer vnfpkgmLinkSerializer = new VNFPKGMLinkSerializer().self(uriLink); return vnfpkgmLinkSerializer; } + } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionControllerTest.java index 9016cad528..c269af8e68 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionControllerTest.java @@ -28,7 +28,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.onap.so.adapters.vnfmadapter.Constants.PACKAGE_MANAGEMENT_BASE_URL; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_REST_TEMPLATE_BEAN; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; @@ -102,7 +102,7 @@ public class Sol003PackageManagementSubscriptionControllerTest { private static final String LOCALHOST_URL = "http://localhost:"; @Autowired - @Qualifier(CONFIGURABLE_REST_TEMPLATE) + @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) private RestTemplate restTemplate; private MockRestServiceServer mockRestServiceServer; @Autowired @@ -324,7 +324,7 @@ public class Sol003PackageManagementSubscriptionControllerTest { private org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest getEtsiCatalogPkgmSubscriptionRequest() { return new org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest() - .filters(new PkgmNotificationsFilter() + .filter(new PkgmNotificationsFilter() .addNotificationTypesItem( PkgmNotificationsFilter.NotificationTypesEnum.VNFPACKAGEONBOARDINGNOTIFICATION) .addVnfdIdItem("VNFDID").addVnfPkgIdItem("VNFPKGID") diff --git a/adapters/so-appc-orchestrator/pom.xml b/adapters/so-appc-orchestrator/pom.xml index e8e5808eca..66dcc4dd30 100644 --- a/adapters/so-appc-orchestrator/pom.xml +++ b/adapters/so-appc-orchestrator/pom.xml @@ -14,7 +14,7 @@ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> - <appc.client.version>1.6.0-SNAPSHOT</appc.client.version> + <appc.client.version>1.7.1-SNAPSHOT</appc.client.version> </properties> <name>so-appc-orchestrator</name> <description>MSO APPC-C Orchestrator</description> diff --git a/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/client/beans/ConfigurationParameters.java b/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/client/beans/ConfigurationParameters.java index b065e9a0c3..e5321067ac 100644 --- a/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/client/beans/ConfigurationParameters.java +++ b/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/client/beans/ConfigurationParameters.java @@ -1,5 +1,10 @@ package org.onap.so.adapters.appc.orchestrator.client.beans; +import java.util.HashMap; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @@ -14,6 +19,8 @@ public class ConfigurationParameters { private String nodeList; @JsonProperty("file_parameter_content") private String fileParameterContent; + @JsonIgnore + private Map<String, String> additionalProperties = new HashMap<>(); @JsonProperty("vnf_name") @@ -50,4 +57,18 @@ public class ConfigurationParameters { this.fileParameterContent = fileParameterContent; } + @JsonAnyGetter + public Map<String, String> getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, String value) { + this.additionalProperties.put(name, value); + } + + public void setAdditionalProperties(Map<String, String> map) { + this.additionalProperties = map; + } + } diff --git a/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImpl.java b/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImpl.java index a174ccb05a..99d6b4dc12 100644 --- a/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImpl.java +++ b/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImpl.java @@ -32,10 +32,10 @@ public class ApplicationControllerTaskImpl { Optional<String> vserverId = Optional.empty(); Parameters parameters = new Parameters(); ConfigurationParameters configParams = new ConfigurationParameters(); + RequestParameters requestParams = new RequestParameters(); switch (request.getAction()) { case HealthCheck: - RequestParameters requestParams = new RequestParameters(); requestParams.setHostIpAddress(request.getApplicationControllerVnf().getVnfHostIpAddress()); parameters.setRequestParameters(requestParams); payload = Optional.of((mapper.getMapper().writeValueAsString(parameters))); @@ -75,6 +75,12 @@ public class ApplicationControllerTaskImpl { payload = Optional.of((mapper.getMapper().writeValueAsString(parameters))); break; case ConfigModify: + requestParams.setHostIpAddress(request.getApplicationControllerVnf().getVnfHostIpAddress()); + configParams.setAdditionalProperties(request.getConfigParams()); + parameters.setRequestParameters(requestParams); + parameters.setConfigurationParameters(configParams); + payload = Optional.of((mapper.getMapper().writeValueAsString(parameters))); + break; case ConfigScaleOut: break; case UpgradePreCheck: @@ -97,6 +103,7 @@ public class ApplicationControllerTaskImpl { vserverId = Optional .of(request.getApplicationControllerVnf().getApplicationControllerVm().getVserverId()); } + break; default: // errorMessage = "Unable to idenify Action request for AppCClient"; break; diff --git a/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImplTest.java b/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImplTest.java index 640e2dbd6e..973430c37e 100644 --- a/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImplTest.java +++ b/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImplTest.java @@ -1,5 +1,7 @@ package org.onap.so.adapters.appc.orchestrator.service; +import java.util.HashMap; +import java.util.Map; import java.util.Optional; import org.junit.Before; import org.junit.Test; @@ -50,6 +52,10 @@ public class ApplicationControllerTaskImplTest { request.setNewSoftwareVersion("2.0"); request.setExistingSoftwareVersion("1.0"); request.setOperationsTimeout("30"); + Map<String, String> reqConfigParams = new HashMap<>(); + reqConfigParams.put("name1", "value1"); + reqConfigParams.put("name2", "value2"); + request.setConfigParams(reqConfigParams); ApplicationControllerVnf applicationControllerVnf = new ApplicationControllerVnf(); applicationControllerVnf.setVnfHostIpAddress("100.100"); applicationControllerVnf.setVnfId("testVnfId"); @@ -228,6 +234,33 @@ public class ApplicationControllerTaskImplTest { } @Test + public void testExcute_configModify() throws JsonProcessingException, ApplicationControllerOrchestratorException { + request.setAction(Action.ConfigModify); + + Parameters parameters = new Parameters(); + RequestParameters requestParams = new RequestParameters(); + requestParams.setHostIpAddress(request.getApplicationControllerVnf().getVnfHostIpAddress()); + parameters.setRequestParameters(requestParams); + ConfigurationParameters configParams = new ConfigurationParameters(); + Map<String, String> configParamMap = new HashMap<>(); + configParamMap.put("name1", "value1"); + configParamMap.put("name2", "value2"); + configParams.setAdditionalProperties(configParamMap); + parameters.setConfigurationParameters(configParams); + Optional<String> payload = Optional.of((mapper.getMapper().writeValueAsString(parameters))); + + Mockito.when(applicationControllerClient.vnfCommand(request.getAction(), "testRequestId", + request.getApplicationControllerVnf().getVnfId(), Optional.empty(), payload, "testControllerType", + listener)).thenReturn(new Status()); + + Status status = applicationControllerTaskImpl.execute("testRequestId", request, listener); + + Mockito.verify(applicationControllerClient).vnfCommand(request.getAction(), "testRequestId", + request.getApplicationControllerVnf().getVnfId(), Optional.empty(), payload, "testControllerType", + listener); + } + + @Test public void testListener() throws Exception { request.setAction(Action.QuiesceTraffic); Status status = applicationControllerTaskImpl.execute("testRequestId", request, listener); |