diff options
59 files changed, 3083 insertions, 665 deletions
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 13d736e747..9527986f52 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 @@ -25,6 +25,8 @@ INSERT INTO northbound_request_ref_lookup(MACRO_ACTION, ACTION, REQUEST_SCOPE, I ('VolumeGroup-Delete', 'deleteInstance', 'VolumeGroup', true,true, '7','7', 'DEFAULT', '*'), ('VFModule-Create', 'createInstance', 'VfModule', true,true, '7','7', 'DEFAULT', '*'), ('VFModule-Delete', 'deleteInstance', 'VfModule', true,true, '7','7', 'DEFAULT', '*'), +('VFModule-Replace', 'replaceInstance', 'VfModule', true,true, '7','7', 'DEFAULT', '*'), +('VFModule-Replace-Retain-Assignments', 'replaceInstanceRetainAssignments', 'VfModule', true,true, '7','7', 'DEFAULT', '*'), ('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', '*'); @@ -147,7 +149,35 @@ INSERT INTO orchestration_flow_reference(COMPOSITE_ACTION, SEQ_NO, FLOW_NAME, FL ('VFModule-ScaleOut', '3', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'DEFAULT')), ('VFModule-ScaleOut', '4', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'DEFAULT')), ('VFModule-ScaleOut', '5', 'ConfigurationScaleOutBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'DEFAULT')), -('VFModule-ScaleOut', '6', 'GenericVnfHealthCheckBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'DEFAULT')); +('VFModule-ScaleOut', '6', 'GenericVnfHealthCheckBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '1', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '2', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '3', 'DeactivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '4', 'DeleteVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '5', 'UnassignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '6', 'UnassignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '7', 'AssignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '8', 'AssignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '9', 'CreateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '10', 'ActivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '11', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '12', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '13', 'ChangeModelVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '14', 'ChangeModelServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '1', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '2', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '3', 'DeactivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '4', 'DeleteVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '5', 'UnassignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '6', 'AssignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '7', 'ChangeModelVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '8', 'CreateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '9', 'ActivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '10', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '11', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '12', 'ChangeModelVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '13', 'ChangeModelServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')); + INSERT INTO rainy_day_handler_macro (FLOW_NAME, SERVICE_TYPE, VNF_TYPE, ERROR_CODE, WORK_STEP, POLICY) VALUES @@ -815,3 +845,7 @@ VALUES UPDATE rainy_day_handler_macro SET reg_ex_error_message = '*' WHERE reg_ex_error_message IS null; UPDATE rainy_day_handler_macro SET SERVICE_ROLE = '*' WHERE SERVICE_ROLE IS null; + +INSERT INTO vnf_components_recipe (VNF_TYPE, VNF_COMPONENT_TYPE, ACTION, VERSION, ORCHESTRATION_URI, RECIPE_TIMEOUT) +VALUES +(NULL, 'vfModule', 'replaceInstanceRetainAssignments', '1', '/mso/async/services/WorkflowActionBB', 180); diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7.1__WorkFlowDesignerTables.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7.1__WorkFlowDesignerTables.sql index e44a6b97ba..8641e51862 100644 --- a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7.1__WorkFlowDesignerTables.sql +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7.1__WorkFlowDesignerTables.sql @@ -40,6 +40,27 @@ CREATE TABLE IF NOT EXISTS `catalogdb`.`vnf_resource_to_workflow` ( ENGINE = InnoDB DEFAULT CHARACTER SET = latin1; +CREATE TABLE IF NOT EXISTS `catalogdb`.`pnf_resource_to_workflow` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `PNF_RESOURCE_MODEL_UUID` VARCHAR(200) NOT NULL, + `WORKFLOW_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_pnf_resource_to_workflow` (`PNF_RESOURCE_MODEL_UUID` ASC, `WORKFLOW_ID` ASC), + INDEX `fk_pnf_resource_to_workflow__workflow1_idx` (`WORKFLOW_ID` ASC), + INDEX `fk_pnf_resource_to_workflow__pnf_res_mod_uuid_idx` (`PNF_RESOURCE_MODEL_UUID` ASC), + CONSTRAINT `fk_pnf_resource_to_workflow__pnf_resource1` + FOREIGN KEY (`PNF_RESOURCE_MODEL_UUID`) + REFERENCES `catalogdb`.`pnf_resource` (`MODEL_UUID`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_pnf_resource_to_workflow__workflow1` + FOREIGN KEY (`WORKFLOW_ID`) + REFERENCES `catalogdb`.`workflow` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + CREATE TABLE IF NOT EXISTS `catalogdb`.`activity_spec` ( `ID` INT(11) NOT NULL AUTO_INCREMENT, `NAME` VARCHAR(200) NOT NULL, diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java index 347bce5b17..69a23a0eba 100644 --- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java @@ -21,21 +21,11 @@ package org.onap.so.adapters.catalogdb.catalogrest; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.INVOCATION_ID; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.LOG_TIMESTAMP; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.PARTNER_NAME; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_CODE; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.SERVICE_NAME; import java.io.IOException; -import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.json.JSONException; import org.junit.Test; -import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.adapters.catalogdb.CatalogDbAdapterBaseTest; import org.onap.so.db.catalog.beans.ServiceRecipe; import org.skyscreamer.jsonassert.JSONAssert; @@ -46,7 +36,6 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; -import ch.qos.logback.classic.spi.ILoggingEvent; public class CatalogDBRestTest extends CatalogDbAdapterBaseTest { @@ -109,26 +98,6 @@ public class CatalogDBRestTest extends CatalogDbAdapterBaseTest { restTemplate.exchange(createURLWithPort("/manage/health"), HttpMethod.GET, entity, String.class); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INSTANCE_UUID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("/manage/health", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("200", mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("/manage/health", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("COMPLETED", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } } /* Service Resources Endpoint */ @@ -815,31 +784,6 @@ public class CatalogDBRestTest extends CatalogDbAdapterBaseTest { assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); JSONAssert.assertEquals(badQueryParamResponse, response.getBody().toString(), false); - - - for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("UNKNOWN", mdc.get(PARTNER_NAME)); - assertEquals("v2/vfModules", mdc.get(SERVICE_NAME)); - assertEquals("INPROGRESS", mdc.get(RESPONSE_STATUS_CODE)); - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker().getName().equals("EXIT")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNotNull(mdc.get(LOG_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("500", mdc.get(RESPONSE_CODE)); - assertEquals("UNKNOWN", mdc.get(PARTNER_NAME)); - assertEquals("v2/vfModules", mdc.get(SERVICE_NAME)); - assertEquals("ERROR", mdc.get(RESPONSE_STATUS_CODE)); - assertNotNull(mdc.get(RESPONSE_DESCRIPTION)); - } } @Test diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java index 92d3114ebe..eacd413df6 100644 --- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java +++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java @@ -23,17 +23,14 @@ package org.onap.so.adapters.requestsdb.adapters; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; -import java.util.Map; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.adapters.requestsdb.MsoRequestsDbAdapter; import org.onap.so.adapters.requestsdb.RequestStatusType; import org.onap.so.adapters.requestsdb.RequestsAdapterBase; @@ -47,7 +44,6 @@ import org.onap.so.db.request.data.repository.ResourceOperationStatusRepository; import org.onap.so.requestsdb.RequestsDbConstant; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.server.LocalServerPort; -import ch.qos.logback.classic.spi.ILoggingEvent; public class MSORequestDBImplTest extends RequestsAdapterBase { @@ -423,28 +419,5 @@ public class MSORequestDBImplTest extends RequestsAdapterBase { ResourceOperationStatus actualResource = dbAdapter.getResourceOperationStatus(serviceId, operationId, "template1"); assertThat(actualResource, sameBeanAs(expectedResource)); - - for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.cxf.interceptor.SOAPLoggingInInterceptor") - && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INSTANCE_UUID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("UNKNOWN", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("/services/RequestsDbAdapter", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.cxf.interceptor.SOAPLoggingOutInterceptor") - && logEvent.getMarker().getName().equals("EXIT")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals(null, mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertEquals("UNKNOWN", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("/services/RequestsDbAdapter", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("COMPLETE", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } } - - } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java index fc6d0a6fc9..55a05436f0 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java @@ -23,7 +23,9 @@ package org.onap.so.adapters.sdnc; import java.util.concurrent.Executor; +import org.onap.logging.filter.base.Constants; import org.onap.logging.filter.spring.MDCTaskDecorator; +import org.onap.so.utils.Components; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -52,6 +54,7 @@ public class SDNCAdapterApplication { } public static void main(String[] args) { + System.setProperty(Constants.Property.PARTNER_NAME, Components.SDNC_ADAPTER.toString()); SpringApplication.run(SDNCAdapterApplication.class, args); System.getProperties().setProperty("server.name", "Springboot"); setLogsDir(); diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java index 8a1a7559b5..631be2f9ff 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java @@ -24,27 +24,30 @@ package org.onap.so.adapters.sdnc.sdncrest; +import java.net.URI; import javax.xml.bind.DatatypeConverter; -import org.onap.so.logger.LoggingAnchor; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.util.EntityUtils; -import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.logging.filter.spring.SpringClientPayloadFilter; import org.onap.so.adapters.sdnc.impl.Constants; import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; +import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; +import org.onap.so.utils.CryptoUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.onap.so.utils.CryptoUtils; -import org.slf4j.MDC; import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; /** * Sends asynchronous messages to the BPMN WorkflowMessage service. @@ -95,81 +98,72 @@ public class BPRestCallback { logger.info(LoggingAnchor.THREE, MessageEnum.RA_CALLBACK_BPEL.toString(), message == null ? "[no content]" : message, CAMUNDA); - - HttpPost method = null; - HttpResponse httpResponse = null; - try { int timeout = 60 * 1000; + RestTemplate restTemplate = setRestTemplate(timeout); - RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout) - .setConnectionRequestTimeout(timeout).build(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); - HttpClient client = HttpClientBuilder.create().build(); - method = new HttpPost(url); - method.setConfig(requestConfig); - - if (message != null) { - method.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON)); - } - - boolean error = false; - - try { - String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.BPEL_AUTH_PROP), - env.getProperty(Constants.ENCRYPTION_KEY_PROP)); - String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()); - method.setHeader("Authorization", authorization); - method.setHeader(ONAPLogConstants.Headers.REQUEST_ID, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); - method.setHeader(ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - method.setHeader(ONAPLogConstants.Headers.PARTNER_NAME, "SO-SDNCAdapter"); - } catch (Exception e) { - logger.error(LoggingAnchor.FOUR, MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA, - ErrorCode.BusinessProcessError.getValue(), "Unable to set authorization in callback request", - e); - error = true; - } + boolean error = setAuthorizationHeader(headers); + HttpEntity<String> requestEntity = new HttpEntity<>(message, headers); if (!error) { - httpResponse = client.execute(method); - - @SuppressWarnings("unused") - String responseContent = null; - - if (httpResponse.getEntity() != null) { - responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); - } - - if (httpResponse.getStatusLine().getStatusCode() >= 300) { - String msg = "Received error response to callback request: " + httpResponse.getStatusLine(); - logger.error(LoggingAnchor.FOUR, MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, - ErrorCode.BusinessProcessError.getValue(), msg); - - } + postRequest(restTemplate, url, requestEntity); } + logger.info(LoggingAnchor.TWO, MessageEnum.RA_CALLBACK_BPEL_COMPLETE.toString(), CAMUNDA); return true; } catch (Exception e) { logger.error(LoggingAnchor.FOUR, MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, ErrorCode.BusinessProcessError.getValue(), "Error sending callback request", e); return false; - } finally { - if (httpResponse != null) { - try { - EntityUtils.consume(httpResponse.getEntity()); - httpResponse = null; - } catch (Exception e) { - logger.debug("Exception:", e); - } - } + } + } - if (method != null) { - try { - method.reset(); - } catch (Exception e) { - logger.debug("Exception:", e); - } - } - logger.info(LoggingAnchor.TWO, MessageEnum.RA_CALLBACK_BPEL_COMPLETE.toString(), CAMUNDA); + protected boolean setAuthorizationHeader(HttpHeaders headers) { + boolean error = false; + try { + String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.BPEL_AUTH_PROP), + env.getProperty(Constants.ENCRYPTION_KEY_PROP)); + String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()); + headers.set("Authorization", authorization); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA, + ErrorCode.BusinessProcessError.getValue(), "Unable to set authorization in callback request", e); + error = true; + } + return error; + } + + private void postRequest(RestTemplate restTemplate, String url, HttpEntity<String> requestEntity) { + ResponseEntity<String> response = null; + try { + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url); + URI uri = builder.build(true).toUri(); + response = restTemplate.postForEntity(uri, requestEntity, String.class); + } catch (HttpStatusCodeException e) { + logResponseError(e.getStatusCode()); + } + if (response != null && response.getStatusCode().is3xxRedirection()) { + logResponseError(response.getStatusCode()); } } + + private void logResponseError(HttpStatus statusCode) { + String msg = "Received error response to callback request: " + statusCode; + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, + ErrorCode.BusinessProcessError.getValue(), msg); + } + + protected RestTemplate setRestTemplate(int timeout) { + RestTemplate restTemplate = new RestTemplate(); + HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); + factory.setConnectionRequestTimeout(timeout); + factory.setReadTimeout(timeout); + factory.setConnectTimeout(timeout); + restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory)); + restTemplate.getInterceptors().add(new SOSpringClientFilter()); + restTemplate.getInterceptors().add((new SpringClientPayloadFilter())); + return restTemplate; + } } diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallbackUnitTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallbackUnitTest.java new file mode 100644 index 0000000000..09089890ab --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallbackUnitTest.java @@ -0,0 +1,142 @@ +package org.onap.so.adapters.sdnc.sdncrest; + + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Paths; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.adapters.sdnc.impl.Constants; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; + +@RunWith(MockitoJUnitRunner.class) +public class BPRestCallbackUnitTest { + @Mock + private Environment env; + + @Mock + private RestTemplate restTemplate; + + @Spy + @InjectMocks + private BPRestCallback bpRestCallback; + + private HttpEntity<String> requestEntity; + private String message; + private HttpHeaders headers; + private URI uri; + + @Before + public void setUp() throws IOException { + headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + message = input("BPRestCallbackRequest.json"); + requestEntity = new HttpEntity<>(message, headers); + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("http://localhost:8000/sdnc"); + uri = builder.build(true).toUri(); + } + + public String input(String JsonInput) throws IOException { + JsonInput = "src/test/resources/" + JsonInput; + return new String(Files.readAllBytes(Paths.get(JsonInput))); + } + + @Test + public void sendTest() throws IOException { + ResponseEntity<String> postResponse = new ResponseEntity<String>("response", HttpStatus.OK); + doReturn(restTemplate).when(bpRestCallback).setRestTemplate(60000); + doReturn(false).when(bpRestCallback).setAuthorizationHeader(headers); + when(restTemplate.postForEntity(uri, requestEntity, String.class)).thenReturn(postResponse); + boolean response = bpRestCallback.send("http://localhost:8000/sdnc", message); + assertTrue(response); + } + + @Test + public void sendNoAuthHeaderTest() throws IOException { + doReturn(true).when(bpRestCallback).setAuthorizationHeader(headers); + doReturn(restTemplate).when(bpRestCallback).setRestTemplate(60000); + boolean response = bpRestCallback.send("http://localhost:8000/sdnc", message); + assertTrue(response); + } + + @Test + public void sendErrorTest() throws IOException { + doReturn(false).when(bpRestCallback).setAuthorizationHeader(headers); + doReturn(restTemplate).when(bpRestCallback).setRestTemplate(60000); + when(restTemplate.postForEntity(uri, requestEntity, String.class)) + .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, null, null, null)); + boolean response = bpRestCallback.send("http://localhost:8000/sdnc", message); + assertTrue(response); + } + + @Test + public void sendResponse3xxTest() throws IOException { + ResponseEntity<String> postResponse = new ResponseEntity<String>("response", HttpStatus.MULTIPLE_CHOICES); + doReturn(false).when(bpRestCallback).setAuthorizationHeader(headers); + doReturn(restTemplate).when(bpRestCallback).setRestTemplate(60000); + when(restTemplate.postForEntity(uri, requestEntity, String.class)).thenReturn(postResponse); + boolean response = bpRestCallback.send("http://localhost:8000/sdnc", message); + assertTrue(response); + } + + @Test + public void sendResponseNullMessageTest() throws IOException { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setContentType(MediaType.APPLICATION_JSON); + HttpEntity<String> requestEntityNoMessage = new HttpEntity<>(null, httpHeaders); + ResponseEntity<String> postResponse = new ResponseEntity<String>("response", HttpStatus.OK); + doReturn(false).when(bpRestCallback).setAuthorizationHeader(httpHeaders); + doReturn(restTemplate).when(bpRestCallback).setRestTemplate(60000); + when(restTemplate.postForEntity(uri, requestEntityNoMessage, String.class)).thenReturn(postResponse); + boolean response = bpRestCallback.send("http://localhost:8000/sdnc", null); + assertTrue(response); + } + + @Test + public void postThrowsExceptionTest() throws IOException { + doReturn(false).when(bpRestCallback).setAuthorizationHeader(headers); + doReturn(restTemplate).when(bpRestCallback).setRestTemplate(60000); + when(restTemplate.postForEntity(uri, requestEntity, String.class)) + .thenThrow(new ResourceAccessException("ResourceAccessException")); + boolean response = bpRestCallback.send("http://localhost:8000/sdnc", message); + assertFalse(response); + } + + @Test + public void setAuthorizationHeaderTest() { + HttpHeaders authHeaders = new HttpHeaders(); + when(env.getProperty(Constants.BPEL_AUTH_PROP)) + .thenReturn("5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C"); + when(env.getProperty(Constants.ENCRYPTION_KEY_PROP)).thenReturn("07a7159d3bf51a0e53be7a8f89699be7"); + boolean result = bpRestCallback.setAuthorizationHeader(authHeaders); + assertFalse(result); + } + + @Test + public void setAuthorizationHeaderErrorTest() { + HttpHeaders authHeaders = new HttpHeaders(); + when(env.getProperty(Constants.BPEL_AUTH_PROP)).thenReturn("test"); + when(env.getProperty(Constants.ENCRYPTION_KEY_PROP)).thenReturn("test"); + boolean result = bpRestCallback.setAuthorizationHeader(authHeaders); + assertTrue(result); + } +} diff --git a/adapters/mso-sdnc-adapter/src/test/resources/BPRestCallbackRequest.json b/adapters/mso-sdnc-adapter/src/test/resources/BPRestCallbackRequest.json new file mode 100644 index 0000000000..21f3dab7e0 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/test/resources/BPRestCallbackRequest.json @@ -0,0 +1 @@ +{"SDNCServiceResponse":{"sdncRequestId":"b5b763aa-0d8a-4438-b900-83af45d21d10","responseCode":"200","ackFinalIndicator":"N"}}
\ No newline at end of file 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 9d9e33a524..f828a12c8b 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml @@ -105,5 +105,9 @@ <artifactId>okio</artifactId> <version>1.13.0</version> </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> </dependencies> </project> diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/Sol003PackageManagementControllerExceptionHandler.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/Sol003PackageManagementControllerExceptionHandler.java new file mode 100644 index 0000000000..713bf01249 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/Sol003PackageManagementControllerExceptionHandler.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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; + +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.ProblemDetails; +import org.onap.so.adapters.vnfmadapter.rest.Sol003PackageManagementController; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.EtsiCatalogManagerRequestFailureException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfPkgConflictException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfPkgNotFoundException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +/** + * Exception Handler for the Package Management Controller {@link Sol003PackageManagementController Sol003Controller} + * + * @author gareth.roper@est.tech + */ +@ControllerAdvice(assignableTypes = Sol003PackageManagementController.class) + +public class Sol003PackageManagementControllerExceptionHandler { + + @ExceptionHandler(EtsiCatalogManagerRequestFailureException.class) + public ResponseEntity<ProblemDetails> handleEtsiCatalogManagerRequestFailureException( + EtsiCatalogManagerRequestFailureException etsiCatalogManagerRequestFailureException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(etsiCatalogManagerRequestFailureException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(problemDetails); + } + + @ExceptionHandler(VnfPkgConflictException.class) + public ResponseEntity<ProblemDetails> handleVnfPkgConflictException( + VnfPkgConflictException vnfPkgConflictException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(vnfPkgConflictException.getMessage()); + return ResponseEntity.status(HttpStatus.CONFLICT).body(problemDetails); + } + + @ExceptionHandler(VnfPkgNotFoundException.class) + public ResponseEntity<ProblemDetails> handleVnfPkgNotFoundException( + VnfPkgNotFoundException vnfPkgNotFoundException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(vnfPkgNotFoundException.getMessage()); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(problemDetails); + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/AbstractServiceProviderConfiguration.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/AbstractServiceProviderConfiguration.java new file mode 100644 index 0000000000..8f6d853997 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/AbstractServiceProviderConfiguration.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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; + +import com.google.gson.Gson; +import java.util.Iterator; +import org.onap.vnfmadapter.v1.JSON; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.GsonHttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.client.RestTemplate; + +/** + * A base class that can be extended by classes for configuring HttpRestServiceProvider classes. Provides common methods + * that will be useful to some such classes. + * + * @author gareth.roper@est.tech + */ +public abstract class AbstractServiceProviderConfiguration { + + public void setGsonMessageConverter(final RestTemplate restTemplate) { + final Iterator<HttpMessageConverter<?>> iterator = restTemplate.getMessageConverters().iterator(); + while (iterator.hasNext()) { + if (iterator.next() instanceof MappingJackson2HttpMessageConverter) { + iterator.remove(); + } + } + final Gson gson = new JSON().getGson(); + restTemplate.getMessageConverters().add(new GsonHttpMessageConverter(gson)); + } +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java new file mode 100644 index 0000000000..39efc8dc23 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.etsicatalog; + +import java.util.Optional; + +/** + * Provides methods for invoking REST calls to the ETSI Catalog Manager. + * + * @author gareth.roper@est.tech + */ +public interface EtsiCatalogServiceProvider { + + /** + * GET Package Content, from VNF Package. + * + * @param vnfPkgId The ID of the VNF Package from which the "package_content" will be retrieved. + * @return The Package Content of a VNF Package ("vnfPkgId"). + */ + + Optional<byte[]> getVnfPackageContent(final String vnfPkgId); + +} 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 new file mode 100644 index 0000000000..6840dd388b --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.etsicatalog; + +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.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.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +/** + * Configures the HttpRestServiceProvider to make REST calls to the ETSI Catalog Manager + * + * @author gareth.roper@est.tech + */ + +@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()); + } + + private HttpRestServiceProvider getHttpRestServiceProvider(final RestTemplate restTemplate, + final HttpHeadersProvider httpHeadersProvider) { + setGsonMessageConverter(restTemplate); + return new HttpRestServiceProviderImpl(restTemplate, httpHeadersProvider); + } + +} 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 new file mode 100644 index 0000000000..9a59620993 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.etsicatalog; + +import java.util.Optional; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.EtsiCatalogManagerRequestFailureException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfPkgConflictException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfPkgNotFoundException; +import org.onap.so.rest.exceptions.HttpResouceNotFoundException; +import org.onap.so.rest.exceptions.RestProcessingException; +import org.onap.so.rest.service.HttpRestServiceProvider; +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.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +/** + * Provides the implementations of the REST Requests to the ETSI Catalog Manager. + * + * @author gareth.roper@est.tech + */ +@Service +public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvider { + private static final Logger logger = LoggerFactory.getLogger(EtsiCatalogServiceProviderImpl.class); + + @Qualifier + private final HttpRestServiceProvider httpServiceProvider; + private final EtsiCatalogUrlProvider etsiCatalogUrlProvider; + + @Autowired + public EtsiCatalogServiceProviderImpl(final EtsiCatalogUrlProvider etsiCatalogUrlProvider, + final HttpRestServiceProvider httpServiceProvider) { + this.etsiCatalogUrlProvider = etsiCatalogUrlProvider; + this.httpServiceProvider = httpServiceProvider; + } + + @Override + public Optional<byte[]> getVnfPackageContent(String vnfPkgId) throws EtsiCatalogManagerRequestFailureException { + try { + ResponseEntity<byte[]> response = httpServiceProvider + .getHttpResponse(etsiCatalogUrlProvider.getVnfPackageContentUrl(vnfPkgId), byte[].class); + logger.info("getVnfPackageContent Request to ETSI Catalog Manager Status Code: {}", + response.getStatusCodeValue()); + if (response.getStatusCode() == HttpStatus.OK) { + return Optional.ofNullable(response.getBody()); + } + } catch (HttpResouceNotFoundException httpResouceNotFoundException) { + logger.error("Caught HttpResouceNotFoundException", httpResouceNotFoundException); + throw new VnfPkgNotFoundException("No Vnf Package found with vnfPkgId: " + vnfPkgId); + } catch (RestProcessingException restProcessingException) { + logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), + restProcessingException); + if (restProcessingException.getStatusCode() == HttpStatus.CONFLICT.value()) { + throw new VnfPkgConflictException("A conflict occurred with the state of the resource,\n" + + "due to the attribute: onboardingState not being set to ONBOARDED."); + } + } + throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); + } +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogUrlProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogUrlProvider.java new file mode 100644 index 0000000000..e8188b9c7d --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogUrlProvider.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.etsicatalog; + +import static org.slf4j.LoggerFactory.getLogger; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +/** + * Provides the URLs for the REST Requests to the ETSI Catalog Manager. + * + * @author gareth.roper@est.tech + */ +@Service +public class EtsiCatalogUrlProvider { + + private static final Logger logger = getLogger(EtsiCatalogUrlProvider.class); + + @Value("${msb.endpoint:#{\"http://msb_iag.onap:80\"}}") + private String msbEndpoint; + @Value("${msb.catalogServiceUrl:#{null}}") + private String catalogServiceUrl; + @Value("${msb.vnfpkgmServiceUrl:#{\"/api/vnfpkgm/v1\"}}") + private String vnfpkgmServiceUrl; + + public EtsiCatalogUrlProvider() {} + + /** + * Get the URL for retrieving the Package Content from the ETSI Catalog.". + * + * @param vnfPkgId The ID of the VNF Package + * @return the URL for the GET operation + */ + + public String getVnfPackageContentUrl(final String vnfPkgId) { + final String url = msbEndpoint + vnfpkgmServiceUrl + "/vnf_packages/" + vnfPkgId + "/package_content"; + logger.info("getEtsiCatalogVnfPackageContentUrl: {}", url); + return url; + } +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderConfiguration.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderConfiguration.java index ae9316cfdf..073fc93107 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderConfiguration.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderConfiguration.java @@ -21,7 +21,6 @@ package org.onap.so.adapters.vnfmadapter.extclients.vnfm; import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; -import com.google.gson.Gson; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStore; @@ -29,7 +28,6 @@ import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; -import java.util.Iterator; import java.util.ListIterator; import java.util.Map; import java.util.UUID; @@ -43,7 +41,7 @@ import org.apache.http.ssl.SSLContextBuilder; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.aai.domain.yang.EsrVnfm; import org.onap.logging.filter.spring.SpringClientPayloadFilter; -import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.JSON; +import org.onap.so.adapters.vnfmadapter.extclients.AbstractServiceProviderConfiguration; import org.onap.so.configuration.rest.BasicHttpHeadersProvider; import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; import org.onap.so.rest.service.HttpRestServiceProvider; @@ -58,9 +56,6 @@ import org.springframework.core.io.Resource; import org.springframework.http.client.BufferingClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.GsonHttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; import org.springframework.web.client.RestTemplate; @@ -69,7 +64,7 @@ import org.springframework.web.client.RestTemplate; * Configures the HttpRestServiceProvider for REST call to a VNFM. */ @Configuration -public class VnfmServiceProviderConfiguration { +public class VnfmServiceProviderConfiguration extends AbstractServiceProviderConfiguration { private static final Logger logger = LoggerFactory.getLogger(VnfmServiceProviderConfiguration.class); private Map<String, HttpRestServiceProvider> mapOfVnfmIdToHttpRestServiceProvider = new ConcurrentHashMap<>(); @@ -135,17 +130,6 @@ public class VnfmServiceProviderConfiguration { return new OAuth2RestTemplate(resourceDetails); } - private void setGsonMessageConverter(final RestTemplate restTemplate) { - final Iterator<HttpMessageConverter<?>> iterator = restTemplate.getMessageConverters().iterator(); - while (iterator.hasNext()) { - if (iterator.next() instanceof MappingJackson2HttpMessageConverter) { - iterator.remove(); - } - } - final Gson gson = new JSON().getGson(); - restTemplate.getMessageConverters().add(new GsonHttpMessageConverter(gson)); - } - private void setTrustStore(final RestTemplate restTemplate) { SSLContext sslContext; try { diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java index 1da1159be0..e12729a2e3 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java @@ -24,9 +24,13 @@ import static org.onap.so.adapters.vnfmadapter.Constants.APPLICATION_ZIP; import static org.onap.so.adapters.vnfmadapter.Constants.PACKAGE_MANAGEMENT_BASE_URL; import static org.slf4j.LoggerFactory.getLogger; import java.util.List; +import java.util.Optional; import javax.ws.rs.core.MediaType; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.EtsiCatalogServiceProvider; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.ProblemDetails; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2001; import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -45,13 +49,21 @@ import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping(value = PACKAGE_MANAGEMENT_BASE_URL, consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public class Sol003PackageManagementController { - private static final String LOG_REQUEST_RECEIVED = "VNF Package Management Controller: {} {} {} {} {}"; + private final EtsiCatalogServiceProvider etsiCatalogServiceProvider; + + @Autowired + Sol003PackageManagementController(final EtsiCatalogServiceProvider etsiCatalogServiceProvider) { + this.etsiCatalogServiceProvider = etsiCatalogServiceProvider; + } + + + private static final String LOG_REQUEST_RECEIVED = "VNF PackageManagement Controller: {} {} {}"; private static final Logger logger = getLogger(Sol003PackageManagementController.class); /** - * GET VNF packages information. Direction: VNFM -> VNFM-Adapter. Will return zero or more VNF package - * representations that match the attribute filter. These representations will be in a list. Section Number: 10.4.2 - * + * GET VNF packages information. Will return zero or more VNF package representations that match the attribute + * filter. These representations will be in a list. Section Number: 10.4.2 + * * @return A List of all VNF packages. Object: List<InlineResponse2001> Response Code: 200 OK */ @@ -62,9 +74,9 @@ public class Sol003PackageManagementController { } /** - * GET VNF package information. Direction: VNFM -> VNFM-Adapter. Will return a specific VNF package representation - * that match the attribute filter. Section Number: 10.4.3 - * + * GET VNF package information. Will return a specific VNF package representation that match the attribute filter. + * Section Number: 10.4.3 + * * @param vnfPkgId The ID of the VNF Package that you want to query. * @return A VNF package based on vnfPkgId. Object: VnfPkgInfo Response Code: 200 OK */ @@ -75,44 +87,67 @@ public class Sol003PackageManagementController { } /** - * GET VNFD, from VNF package. Direction: VNFM -> VNFM-Adapter. Will return a copy of the file representing the VNFD - * or a ZIP file that contains the file/multiple files representing the VNFD specified. Section Number: 10.4.4 - * + * GET VNFD, from VNF package. Will return a copy of the file representing the VNFD or a ZIP file that contains the + * file/multiple files representing the VNFD specified. Section Number: 10.4.4 + * * @param vnfPkgId The ID of the VNF Package that you want to retrieve the VNFD from. * @return The VNFD of a VNF Package as a single file or within a ZIP file. Object: byte[] Response Code: 200 OK */ - @GetMapping(value = "/vnf_packages/{vnfPkgId}/vnfd", produces = {MediaType.TEXT_PLAIN, APPLICATION_ZIP}) + @GetMapping(value = "/vnf_packages/{vnfPkgId}/vnfd", + produces = {MediaType.TEXT_PLAIN, APPLICATION_ZIP, MediaType.APPLICATION_JSON}) public ResponseEntity<byte[]> getVnfPackageVnfd(@PathVariable("vnfPkgId") final String vnfPkgId) { logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageVnfd: ", vnfPkgId); return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** - * GET Package Content, from VNF Package. Direction: VNFM -> VNFM-Adapter. Will return a copy of the VNF package - * file that you specified. Section Number: 10.4.5 - * + * GET Package Content, from VNF Package. Will return a copy of the VNF package file that you specified. Section + * Number: 10.4.5 + * * @param vnfPkgId The ID of the VNF Package that you want to retrieve the "package_content" from. * @return The Package Content of a VNF Package. Object: byte[] Response Code: 200 OK */ - @GetMapping(value = "/vnf_packages/{vnfPkgId}/package_content", produces = {APPLICATION_ZIP}) - public ResponseEntity<byte[]> getVnfPackageContent(@PathVariable("vnfPkgId") final String vnfPkgId) { - logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageContent: ", vnfPkgId); - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + @GetMapping(value = "/vnf_packages/{vnfPkgId}/package_content", + produces = {MediaType.APPLICATION_JSON, APPLICATION_ZIP, MediaType.APPLICATION_OCTET_STREAM}) + public ResponseEntity getVnfPackageContent(@PathVariable("vnfPkgId") final String vnfPkgId) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageContent Endpoint Invoked with VNF Package ID: ", vnfPkgId); + final Optional<byte[]> response = etsiCatalogServiceProvider.getVnfPackageContent(vnfPkgId); + if (response.isPresent()) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageContent Response: ", HttpStatus.OK); + return new ResponseEntity(response.get(), HttpStatus.OK); + } + logger.error("Null response was received from the EtsiCatalogManager using the GET \"package_content\""); + return new ResponseEntity(buildProblemDetails("An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"package_content\" \n" + + "endpoint."), HttpStatus.INTERNAL_SERVER_ERROR); } /** - * GET Artifact, from VNF Package. Direction: VNFM -> VNFM-Adapter. Will return a the content of the artifact that - * you specified. Section Number: 10.4.6 - * + * GET Artifact, from VNF Package Will return a the content of the artifact that you specified. Section Number: + * 10.4.6 + * * @param vnfPkgId The ID of the VNF Package that you want to retrieve an artifact from. * @param artifactPath The path of the artifact that you want to retrieve. * @return An Artifact from a VNF Package. Object: byte[] Response Code: 200 OK */ @GetMapping(value = "/vnf_packages/{vnfPkgId}/artifacts/{artifactPath}", - produces = {MediaType.APPLICATION_OCTET_STREAM}) + produces = {MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON}) public ResponseEntity<byte[]> getVnfPackageArtifact(@PathVariable("vnfPkgId") final String vnfPkgId, @PathVariable("artifactPath") final String artifactPath) { logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageArtifact: vnfPkgId=", vnfPkgId, " artifactPath=", artifactPath); return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } + + /** + * Builds the ProblemDetails Object, using the provided error message. + * + * @param detail The error message retrieved from the exception thrown. + * @return ProblemDetails Object, containing error information. + */ + private ProblemDetails buildProblemDetails(String detail) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(detail); + return problemDetails; + } + } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementController.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementController.java index 6fac952aa8..16650d4a3d 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementController.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementController.java @@ -53,9 +53,9 @@ public class Sol003SubscriptionManagementController { private static final Logger logger = getLogger(Sol003SubscriptionManagementController.class); /** - * POST Subscribe request. Direction: VNFM -> VNFM Adapter. Will send request and respond with the subscription that - * you subscribed to, if successful. Section Number: 10.4.7 - * + * POST Subscribe request. Will send request and respond with the subscription that you subscribed to, if + * successful. Section Number: 10.4.7 + * * @param pkgmSubscriptionRequest This includes the details of the subscription to be created. * @return The subscription requested, if successful. Object: InlineRespone2002 Response Code: 201 Created Response * Code: 303 Duplicate Subscription @@ -68,9 +68,8 @@ public class Sol003SubscriptionManagementController { } /** - * GET all subscriptions. Direction: VNFM -> VNFM Adapter. Will return a list of all subscriptions currently active. - * Section Number: 10.4.7 - * + * GET all subscriptions. Will return a list of all subscriptions currently active. Section Number: 10.4.7 + * * @return All of the current active subscriptions. Object: List<InlineResponse2002> Response Code: 200 OK */ @GetMapping(value = "/subscriptions") @@ -80,8 +79,8 @@ public class Sol003SubscriptionManagementController { } /** - * GET a specific subscription, by subscriptionId. Direction: VNFM -> VNFM Adapter. Section Number: 10.4.8 - * + * GET a specific subscription, by subscriptionId. Section Number: 10.4.8 + * * @param subscriptionId The ID of the subscription that you wish to retrieve. * @return A subscription based on subscriptionId. Object: InlineResponse2002 Response Code: 200 OK */ @@ -93,8 +92,8 @@ public class Sol003SubscriptionManagementController { } /** - * DELETE a specific subscription, by subscriptionId. Direction: VNFM -> VNFM Adapter. Section Number: 10.4.7 - * + * DELETE a specific subscription, by subscriptionId. Section Number: 10.4.7 + * * @param subscriptionId The ID of the subscription that you wish to delete. * @return Empty response if successful. Object: Void Response Code: 204 No Content */ diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/EtsiCatalogManagerRequestFailureException.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/EtsiCatalogManagerRequestFailureException.java new file mode 100644 index 0000000000..dbdc354f4e --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/EtsiCatalogManagerRequestFailureException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for an ETSI Catalog Manager Request Failure + * + * @author gareth.roper@est.tech + */ +@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) +public class EtsiCatalogManagerRequestFailureException extends RuntimeException { + + private static final long serialVersionUID = 66862444537194516L; + + public EtsiCatalogManagerRequestFailureException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/VnfPkgConflictException.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/VnfPkgConflictException.java new file mode 100644 index 0000000000..0cc9c5bd7e --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/VnfPkgConflictException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for a Vnfpkg Conflict failure, due to state of resource. + * + * @author gareth.roper@est.tech + */ +@ResponseStatus(code = HttpStatus.CONFLICT) +public class VnfPkgConflictException extends RuntimeException { + + private static final long serialVersionUID = 26862444537198441L; + + public VnfPkgConflictException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/VnfPkgNotFoundException.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/VnfPkgNotFoundException.java new file mode 100644 index 0000000000..0f9f214643 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/VnfPkgNotFoundException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for a Vnfpkg Not Found Failure + * + * @author gareth.roper@est.tech + */ +@ResponseStatus(code = HttpStatus.NOT_FOUND) +public class VnfPkgNotFoundException extends RuntimeException { + + private static final long serialVersionUID = 26862444537198441L; + + public VnfPkgNotFoundException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } +} 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 801c468018..59dfd50b32 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 @@ -1,74 +1,236 @@ -package org.onap.so.adapters.vnfmadapter.rest; +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.rest; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +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 java.net.URISyntaxException; -import java.util.List; +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; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +import java.util.Random; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.onap.so.adapters.vnfmadapter.VnfmAdapterApplication; -import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2001; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.ProblemDetails; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +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.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; +/** + * @author gareth.roper@est.tech + */ @RunWith(SpringRunner.class) @SpringBootTest(classes = VnfmAdapterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") public class Sol003PackageManagementControllerTest { - private static final String vnfPackageId = "myVnfPackageId"; - private static final String artifactPath = "myArtifactPath"; + private static final Logger logger = LoggerFactory.getLogger(Sol003PackageManagementControllerTest.class); + + @LocalServerPort + private int port; @Autowired @Qualifier(CONFIGURABLE_REST_TEMPLATE) private RestTemplate testRestTemplate; - private MockRestServiceServer mockRestServer; @Autowired private Sol003PackageManagementController controller; + @Autowired + private TestRestTemplate restTemplate; + + private static final String VNF_PACKAGE_ID = "myVnfPackageId"; + private static final String ARTIFACT_PATH = "myArtifactPath"; + private static final String MSB_BASE_URL = "http://msb_iag.onap:80/api/vnfpkgm/v1/vnf_packages"; + private static final String VNFPKGM_BASE_URL = PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages"; + private static final String localhostUrl = "http://localhost:"; + + private MockRestServiceServer mockRestServer; + private BasicHttpHeadersProvider basicHttpHeadersProvider; + + + public Sol003PackageManagementControllerTest() {} + @Before - public void setUp() throws Exception { - mockRestServer = MockRestServiceServer.bindTo(testRestTemplate).build(); + public void setUp() { + MockRestServiceServer.MockRestServiceServerBuilder builder = MockRestServiceServer.bindTo(testRestTemplate); + builder.ignoreExpectOrder(true); + mockRestServer = builder.build(); + basicHttpHeadersProvider = new BasicHttpHeadersProvider(); + } + + @Test + public void testGetPackageContent_ValidArray_Success() { + byte[] responseArray = buildByteArrayWithRandomData(10); + + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(responseArray, MediaType.APPLICATION_OCTET_STREAM)); + + final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + + 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); + + assertEquals(byte[].class, responseEntity.getBody().getClass()); + assertArrayEquals(responseEntity.getBody(), responseArray); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); } @Test - public void getVnfPackages() throws URISyntaxException, InterruptedException { - final ResponseEntity<List<InlineResponse2001>> response = controller.getVnfPackages(); - assertEquals(HttpStatus.NOT_IMPLEMENTED, response.getStatusCode()); + public void testOnGetPackageContent_Conflict_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.CONFLICT)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.CONFLICT, responseEntity.getStatusCode()); } @Test - public void getVnfPackage() throws URISyntaxException, InterruptedException { - final ResponseEntity<InlineResponse2001> response = controller.getVnfPackage(vnfPackageId); - assertEquals(HttpStatus.NOT_IMPLEMENTED, response.getStatusCode()); + public void testOnGetPackageContent_NotFound_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); } @Test - public void getVnfPackageVnfd() throws URISyntaxException, InterruptedException { - final ResponseEntity<byte[]> response = controller.getVnfPackageVnfd(vnfPackageId); - assertEquals(HttpStatus.NOT_IMPLEMENTED, response.getStatusCode()); + public void testOnGetPackageContent_UnauthorizedClient_Fail() { + final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + + VNF_PACKAGE_ID + "/package_content"; + final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + final ResponseEntity<ProblemDetails> responseEntity = + restTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.UNAUTHORIZED, responseEntity.getStatusCode()); } @Test - public void getVnfPackageContents() throws URISyntaxException, InterruptedException { - final ResponseEntity<byte[]> response = controller.getVnfPackageContent(vnfPackageId); - assertEquals(HttpStatus.NOT_IMPLEMENTED, response.getStatusCode()); + public void testOnGetPackageContent_InternalServerError_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); } @Test - public void getVnfPackageArtifact() throws URISyntaxException, InterruptedException { - final ResponseEntity<byte[]> response = controller.getVnfPackageArtifact(vnfPackageId, artifactPath); - assertEquals(HttpStatus.NOT_IMPLEMENTED, response.getStatusCode()); + public void testOnGetPackageContent_BadRequest_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); } + @Test + public void testOnGetPackageContent_UnauthorizedServer_InternalError_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testGetPackageContent_SuccessResponseFromServerWithNullPackage_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withSuccess()); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertEquals(ProblemDetails.class, responseEntity.getBody().getClass()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + // The below 4 test methods are here to improve code coverage and provide a foundation for writing future tests + @Test + public void testGetVnfPackage_Not_Implemented() { + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID); + assertEquals(HttpStatus.NOT_IMPLEMENTED, responseEntity.getStatusCode()); + } + + @Test + public void testGetVnfPackages_Not_Implemented() { + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(""); + assertEquals(HttpStatus.NOT_IMPLEMENTED, responseEntity.getStatusCode()); + } + + @Test + public void testGetVnfd_Not_Implemented() { + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); + assertEquals(HttpStatus.NOT_IMPLEMENTED, responseEntity.getStatusCode()); + } + + @Test + public void testGetArtifact_Not_Implemented() { + final ResponseEntity<ProblemDetails> responseEntity = + sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); + assertEquals(HttpStatus.NOT_IMPLEMENTED, responseEntity.getStatusCode()); + } + + // Simply returns a byte array filled with random data, for use in the tests. + private byte[] buildByteArrayWithRandomData(int sizeInKb) { + final Random rnd = new Random(); + final byte[] b = new byte[sizeInKb * 1024]; // converting kb to byte + rnd.nextBytes(b); + return b; + } + + private ResponseEntity<ProblemDetails> sendHttpRequest(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, + ProblemDetails.class); + } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementControllerTest.java index 999dd02f0f..8fc27c5943 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementControllerTest.java @@ -20,6 +20,10 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; +/** + * @author gareth.roper@est.tech + */ + @RunWith(SpringRunner.class) @SpringBootTest(classes = VnfmAdapterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java index 5987c5ad93..240bb83862 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java @@ -583,7 +583,7 @@ public class ToscaResourceInstaller { String resourceSeqStr = resouceSequence.stream().collect(Collectors.joining(",")); service.setResourceOrder(resourceSeqStr); - logger.debug(" resourceSeq for service uuid(" + service.getModelUUID() + ") : " + resourceSeqStr); + logger.debug(" resourceSeq for service uuid {}: {}", service.getModelUUID(), resourceSeqStr); } @@ -644,8 +644,7 @@ public class ToscaResourceInstaller { String jsonStr = objectMapper.writeValueAsString(resouceRequest); jsonStr = jsonStr.replace("\"", "\\\""); - logger.debug( - "resource request for resource customization id (" + resourceCustomizationUuid + ") : " + jsonStr); + logger.debug("resource request for resource customization id {}: {}", resourceCustomizationUuid, jsonStr); return jsonStr; } catch (JsonProcessingException e) { logger.error("resource input could not be deserialized for resource customization id (" @@ -688,8 +687,8 @@ public class ToscaResourceInstaller { networkCustomization.setResourceInput( getResourceInput(toscaResourceStruct, networkCustomization.getModelCustomizationUUID())); service.getNetworkCustomizations().add(networkCustomization); - logger.debug("No NetworkResourceName found in TempNetworkHeatTemplateLookup for " - + networkResourceModelName); + logger.debug("No NetworkResourceName found in TempNetworkHeatTemplateLookup for {}", + networkResourceModelName); } } @@ -1014,25 +1013,25 @@ public class ToscaResourceInstaller { String vfCustomizationCategory = vfEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY); - logger.debug("VF Category is : " + vfCustomizationCategory); + logger.debug("VF Category is: {} ", vfCustomizationCategory); String vfCustomizationUUID = vfEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); - logger.debug("VFCustomizationUUID=" + vfCustomizationUUID); + logger.debug("VFCustomizationUUID= {}", vfCustomizationUUID); IResourceInstance vfNotificationResource = vfResourceStructure.getResourceInstance(); // Make sure the VF ResourceCustomizationUUID from the notification and tosca customizations match before // comparing their VF Modules UUID's - logger.debug("Checking if Notification VF ResourceCustomizationUUID: " - + vfNotificationResource.getResourceCustomizationUUID() + " matches Tosca VF Customization UUID: " - + vfCustomizationUUID); + logger.debug( + "Checking if Notification VF ResourceCustomizationUUID: {} matches Tosca VF Customization UUID: {}", + vfNotificationResource.getResourceCustomizationUUID(), vfCustomizationUUID); if (vfCustomizationUUID.equals(vfNotificationResource.getResourceCustomizationUUID())) { - logger.debug("vfCustomizationUUID: " + vfCustomizationUUID - + " matches vfNotificationResource CustomizationUUID"); + logger.debug("vfCustomizationUUID: {} matches vfNotificationResource CustomizationUUID ", + vfCustomizationUUID); VnfResourceCustomization vnfResource = createVnfResource(vfEntityDetails, toscaResourceStruct, service); @@ -1044,7 +1043,7 @@ public class ToscaResourceInstaller { for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()) { - logger.debug("vfModuleStructure:" + vfModuleStructure.toString()); + logger.debug("vfModuleStructure: {}", vfModuleStructure); List<IEntityDetails> vfModuleEntityList = getEntityDetails(toscaResourceStruct, @@ -1093,7 +1092,7 @@ public class ToscaResourceInstaller { if (!CollectionUtils.isEmpty(seqResult)) { String resultStr = seqResult.stream().collect(Collectors.joining(",")); vnfResource.setVnfcInstanceGroupOrder(resultStr); - logger.debug("vnfcGroupOrder result for service uuid(" + service.getModelUUID() + ") : " + resultStr); + logger.debug("vnfcGroupOrder result for service uuid {}: {}", service.getModelUUID(), resultStr); } // add this vnfResource with existing vnfResource for this service addVnfCustomization(service, vnfResource); @@ -1203,7 +1202,7 @@ public class ToscaResourceInstaller { watchdogDistributionStatusRepository.saveAndFlush(distributionStatus); } catch (ObjectOptimisticLockingFailureException e) { - logger.debug("ObjectOptimisticLockingFailureException in processWatchdog : " + e.toString()); + logger.debug("ObjectOptimisticLockingFailureException in processWatchdog : {} ", e); throw e; } } @@ -2037,8 +2036,8 @@ public class ToscaResourceInstaller { ObjectMapper objectMapper = new ObjectMapper(); jsonStr = objectMapper.writeValueAsString(resouceRequest); jsonStr = jsonStr.replace("\"", "\\\""); - logger.debug("vfcResource request for resource customization id (" + resourceCustomizationUuid + ") : " - + jsonStr); + logger.debug("vfcResource request for resource customization id {}: {}", resourceCustomizationUuid, + jsonStr); } catch (JsonProcessingException e) { logger.debug("Json Exception: {}", e.getMessage()); logger.error("Exception occurred", e); diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java index ebf722ef74..0bce305f1d 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java @@ -144,6 +144,8 @@ public class GenericVnf implements Serializable, ShallowCopy<GenericVnf> { private String blueprintName; @JsonProperty("CDS_BLUEPRINT_VERSION") private String blueprintVersion; + @JsonProperty("application-id") + private String applicationId; public String getBlueprintName() { @@ -530,6 +532,15 @@ public class GenericVnf implements Serializable, ShallowCopy<GenericVnf> { this.callHoming = callHoming; } + + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } + @Override public boolean equals(final Object other) { if (!(other instanceof GenericVnf)) { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestContext.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestContext.java index 632e61b85c..0193469d93 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestContext.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestContext.java @@ -55,6 +55,8 @@ public class RequestContext implements Serializable { private RequestParameters requestParameters; @JsonProperty("configurationParameters") private List<Map<String, String>> configurationParameters = new ArrayList<>(); + @JsonProperty("application-id") + private String applicationId; public String getServiceURI() { return serviceURI; @@ -143,4 +145,12 @@ public class RequestContext implements Serializable { public void setConfigurationParameters(List<Map<String, String>> configurationParameters) { this.configurationParameters = configurationParameters; } + + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java index 3f664cb821..88c36bec3a 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java @@ -62,6 +62,7 @@ import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds; import org.onap.so.bpmn.servicedecomposition.generalobjects.OrchestrationContext; import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext; import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.NoServiceInstanceFoundException; +import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.ServiceModelNotFoundException; import org.onap.so.client.aai.AAICommonObjectMapperProvider; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.entities.AAIResultWrapper; @@ -116,6 +117,7 @@ public class BBInputSetup implements JavaDelegate { private static final String VNF = "Vnf"; private static final String NETWORK_COLLECTION = "NetworkCollection"; private static final String PREPROV = "PREPROV"; + private static final String CREATEVOLUME = "CreateVolume"; @Autowired private BBInputSetupUtils bbInputSetupUtils; @@ -253,41 +255,46 @@ public class BBInputSetup implements JavaDelegate { String bbName = executeBB.getBuildingBlock().getBpmnFlowName(); String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID); org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = null; - if (serviceInstanceId != null) { - aaiServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId); - } Service service = null; boolean isReplace = false; - if (aaiServiceInstance != null) { - if (requestAction.equalsIgnoreCase("replaceInstance")) { - RelatedInstanceList[] relatedInstanceList = requestDetails.getRelatedInstanceList(); - if (relatedInstanceList != null) { - for (RelatedInstanceList relatedInstList : relatedInstanceList) { - RelatedInstance relatedInstance = relatedInstList.getRelatedInstance(); - if (relatedInstance.getModelInfo().getModelType().equals(ModelType.service)) { - service = bbInputSetupUtils - .getCatalogServiceByModelUUID(relatedInstance.getModelInfo().getModelVersionId()); - isReplace = true; + if (serviceInstanceId != null) { + aaiServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId); + if (aaiServiceInstance != null) { + if (requestAction.equalsIgnoreCase("replaceInstance")) { + RelatedInstanceList[] relatedInstanceList = requestDetails.getRelatedInstanceList(); + if (relatedInstanceList != null) { + for (RelatedInstanceList relatedInstList : relatedInstanceList) { + RelatedInstance relatedInstance = relatedInstList.getRelatedInstance(); + if (relatedInstance.getModelInfo().getModelType().equals(ModelType.service)) { + service = bbInputSetupUtils.getCatalogServiceByModelUUID( + relatedInstance.getModelInfo().getModelVersionId()); + isReplace = true; + } } } + } else { + service = bbInputSetupUtils.getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); + } + if (service == null) { + String message = String.format( + "Related service instance model not found in MSO CatalogDB: model-version-id=%s", + aaiServiceInstance.getModelVersionId()); + throw new ServiceModelNotFoundException(message); } } else { - service = bbInputSetupUtils.getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); + String message = String.format("Related service instance from AAI not found: service-instance-id=%s", + serviceInstanceId); + throw new NoServiceInstanceFoundException(message); } } - if (aaiServiceInstance != null && service != null) { - ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance); - serviceInstance.setModelInfoServiceInstance(this.mapperLayer.mapCatalogServiceIntoServiceInstance(service)); - this.populateObjectsOnAssignAndCreateFlows(executeBB.getRequestId(), requestDetails, service, bbName, - serviceInstance, lookupKeyMap, resourceId, vnfType, executeBB.getBuildingBlock().getKey(), - executeBB.getConfigurationResourceKeys(), isReplace); - return this.populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, - null); - } else { - logger.debug("Related Service Instance from AAI: {}", aaiServiceInstance); - logger.debug("Related Service Instance Model Info from AAI: {}", service); - throw new Exception("Could not find relevant information for related Service Instance"); - } + + ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance); + serviceInstance.setModelInfoServiceInstance(this.mapperLayer.mapCatalogServiceIntoServiceInstance(service)); + this.populateObjectsOnAssignAndCreateFlows(executeBB.getRequestId(), requestDetails, service, bbName, + serviceInstance, lookupKeyMap, resourceId, vnfType, executeBB.getBuildingBlock().getKey(), + executeBB.getConfigurationResourceKeys(), isReplace); + return this.populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, null); + } protected GeneralBuildingBlock getGBBCM(ExecuteBuildingBlock executeBB, RequestDetails requestDetails, @@ -361,6 +368,10 @@ public class BBInputSetup implements JavaDelegate { org.onap.so.serviceinstancebeans.Platform platform = requestDetails.getPlatform(); org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness = requestDetails.getLineOfBusiness(); + String applicationId = ""; + if (requestDetails.getRequestInfo().getApplicationId() != null) { + applicationId = requestDetails.getRequestInfo().getApplicationId(); + } if (modelType.equals(ModelType.network)) { lookupKeyMap.put(ResourceKey.NETWORK_ID, resourceId); @@ -369,8 +380,10 @@ public class BBInputSetup implements JavaDelegate { } else if (modelType.equals(ModelType.vnf)) { lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, resourceId); this.populateGenericVnf(requestId, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, - serviceInstance, lookupKeyMap, relatedInstanceList, resourceId, vnfType, null, productFamilyId); - } else if (modelType.equals(ModelType.volumeGroup)) { + serviceInstance, lookupKeyMap, relatedInstanceList, resourceId, vnfType, null, productFamilyId, + applicationId); + } else if (modelType.equals(ModelType.volumeGroup) || (modelType.equals(ModelType.vfModule) + && (bbName.equalsIgnoreCase(AssignFlows.VOLUME_GROUP.toString()) || bbName.startsWith(CREATEVOLUME)))) { lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, resourceId); this.populateVolumeGroup(requestId, modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId, relatedInstanceList, instanceName, vnfType, null); @@ -594,6 +607,7 @@ public class BBInputSetup implements JavaDelegate { bbInputSetupUtils.getAAIVolumeGroup(cloudOwner, cloudRegionId, volumeGroup.getVolumeGroupId()) .getModelCustomizationId(); if (modelInfo.getModelCustomizationId().equalsIgnoreCase(volumeGroupCustId)) { + logger.debug("Found volume group for vfModule: " + volumeGroup.getVolumeGroupId()); return Optional.of(volumeGroup.getVolumeGroupId()); } } @@ -748,7 +762,7 @@ public class BBInputSetup implements JavaDelegate { org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness, Service service, String bbName, ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, RelatedInstanceList[] relatedInstanceList, String resourceId, String vnfType, - List<Map<String, String>> instanceParams, String productFamilyId) { + List<Map<String, String>> instanceParams, String productFamilyId, String applicationId) { GenericVnf vnf = null; ModelInfo instanceGroupModelInfo = null; String instanceGroupId = null; @@ -777,7 +791,7 @@ public class BBInputSetup implements JavaDelegate { } if (vnf == null && bbName.equalsIgnoreCase(AssignFlows.VNF.toString())) { vnf = createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness, resourceId, generatedVnfType, - instanceParams, productFamilyId); + instanceParams, productFamilyId, applicationId); serviceInstance.getVnfs().add(vnf); mapVnfcCollectionInstanceGroup(vnf, modelInfo, service); } @@ -831,7 +845,7 @@ public class BBInputSetup implements JavaDelegate { protected GenericVnf createGenericVnf(Map<ResourceKey, String> lookupKeyMap, String instanceName, org.onap.so.serviceinstancebeans.Platform platform, org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness, String vnfId, String vnfType, - List<Map<String, String>> instanceParams, String productFamilyId) { + List<Map<String, String>> instanceParams, String productFamilyId, String applicationId) { lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnfId); GenericVnf genericVnf = new GenericVnf(); genericVnf.setVnfId(vnfId); @@ -840,6 +854,7 @@ public class BBInputSetup implements JavaDelegate { genericVnf.setVnfType(vnfType); genericVnf.setProvStatus(PREPROV); genericVnf.setServiceId(productFamilyId); + genericVnf.setApplicationId(applicationId); if (platform != null) { genericVnf.setPlatform(this.mapperLayer.mapRequestPlatform(platform)); } @@ -1279,24 +1294,30 @@ public class BBInputSetup implements JavaDelegate { String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID); RequestDetails requestDetails = executeBB.getRequestDetails(); GeneralBuildingBlock gBB = null; + Service service = null; if (serviceInstanceId != null) { aaiServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId); + if (aaiServiceInstance != null) { + service = bbInputSetupUtils.getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); + if (service == null) { + String message = String.format( + "Related service instance model not found in MSO CatalogDB: model-version-id=%s", + aaiServiceInstance.getModelVersionId()); + throw new ServiceModelNotFoundException(message); + } + } else { + String message = String.format("Related service instance from AAI not found: service-instance-id=%s", + serviceInstanceId); + throw new NoServiceInstanceFoundException(message); + } } - Service service = null; - if (aaiServiceInstance != null) { - service = bbInputSetupUtils.getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); - } - if (aaiServiceInstance != null && service != null) { - ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance); - serviceInstance.setModelInfoServiceInstance(this.mapperLayer.mapCatalogServiceIntoServiceInstance(service)); - updateInstanceName(executeBB.getRequestId(), ModelType.service, serviceInstance.getServiceInstanceName()); - gBB = populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, null); - } else { - logger.debug("Related Service Instance from AAI: {}", aaiServiceInstance); - logger.debug("Related Service Instance Model Info from AAI: {}", service); - throw new Exception("Could not find relevant information for related Service Instance"); - } - ServiceInstance serviceInstance = gBB.getServiceInstance(); + + ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance); + serviceInstance.setModelInfoServiceInstance(this.mapperLayer.mapCatalogServiceIntoServiceInstance(service)); + updateInstanceName(executeBB.getRequestId(), ModelType.service, serviceInstance.getServiceInstanceName()); + gBB = populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, null); + + serviceInstance = gBB.getServiceInstance(); CloudRegion cloudRegion = null; if (cloudConfiguration == null) { Optional<CloudRegion> cloudRegionOp = cloudInfoFromAAI.getCloudInfoFromAAI(serviceInstance); @@ -1431,9 +1452,10 @@ public class BBInputSetup implements JavaDelegate { this.bbInputSetupUtils.updateInfraActiveRequestVnfId(request, vnfId); } String productFamilyId = requestDetails.getRequestInfo().getProductFamilyId(); + String applicationId = ""; this.populateGenericVnf(executeBB.getRequestId(), vnfs.getModelInfo(), vnfs.getInstanceName(), vnfs.getPlatform(), vnfs.getLineOfBusiness(), service, bbName, serviceInstance, lookupKeyMap, null, - vnfId, vnfType, vnfs.getInstanceParams(), productFamilyId); + vnfId, vnfType, vnfs.getInstanceParams(), productFamilyId, applicationId); } else if (bbName.contains(VF_MODULE) || bbName.contains(VOLUME_GROUP)) { Pair<Vnfs, VfModules> vnfsAndVfModules = getVfModulesAndItsVnfsByKey(key, resources); if (vnfsAndVfModules != null) { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java index fcac86b251..994abda083 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java @@ -359,7 +359,7 @@ public class BBInputSetupUtils { } public Optional<ServiceInstance> getAAIServiceInstanceByName(String globalCustomerId, String serviceType, - String serviceInstanceName) throws Exception { + String serviceInstanceName) throws MultipleObjectsFoundException { ServiceInstance aaiServiceInstance = null; ServiceInstances aaiServiceInstances = null; aaiServiceInstances = getAAIServiceInstancesByName(globalCustomerId, serviceType, serviceInstanceName); @@ -367,7 +367,10 @@ public class BBInputSetupUtils { if (aaiServiceInstances == null) { return Optional.empty(); } else if (aaiServiceInstances.getServiceInstance().size() > 1) { - throw new Exception("Multiple Service Instances Returned"); + String message = String.format( + "Multiple service instances found for customer-id: %s, service-type: %s and service-instance-name: %s.", + globalCustomerId, serviceType, serviceInstanceName); + throw new MultipleObjectsFoundException(message); } else { aaiServiceInstance = aaiServiceInstances.getServiceInstance().get(0); } @@ -472,7 +475,9 @@ public class BBInputSetupUtils { if (serviceInstances.get().getServiceInstance().isEmpty()) { throw new NoServiceInstanceFoundException("No ServiceInstances Returned"); } else if (serviceInstances.get().getServiceInstance().size() > 1) { - throw new MultipleObjectsFoundException("Multiple ServiceInstances Returned"); + String message = String.format("Mulitple service instances were found for instance-group-id: %s.", + instanceGroupId); + throw new MultipleObjectsFoundException(message); } else { serviceInstance = serviceInstances.get().getServiceInstance().get(0); } @@ -481,7 +486,7 @@ public class BBInputSetupUtils { } public Optional<L3Network> getRelatedNetworkByNameFromServiceInstance(String serviceInstanceId, String networkName) - throws Exception { + throws MultipleObjectsFoundException { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId); uri.relatedTo(AAIObjectPlurals.L3_NETWORK).queryParam("network-name", networkName); Optional<L3Networks> networks = injectionHelper.getAaiClient().get(L3Networks.class, uri); @@ -491,7 +496,10 @@ public class BBInputSetupUtils { return Optional.empty(); } else { if (networks.get().getL3Network().size() > 1) { - throw new Exception("Multiple Networks Returned"); + String message = + String.format("Multiple networks found for service-instance-id: %s and network-name: %s.", + serviceInstanceId, networkName); + throw new MultipleObjectsFoundException(message); } else { network = networks.get().getL3Network().get(0); } @@ -500,7 +508,7 @@ public class BBInputSetupUtils { } public Optional<GenericVnf> getRelatedVnfByNameFromServiceInstance(String serviceInstanceId, String vnfName) - throws Exception { + throws MultipleObjectsFoundException { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId); uri.relatedTo(AAIObjectPlurals.GENERIC_VNF).queryParam("vnf-name", vnfName); Optional<GenericVnfs> vnfs = injectionHelper.getAaiClient().get(GenericVnfs.class, uri); @@ -510,7 +518,9 @@ public class BBInputSetupUtils { return Optional.empty(); } else { if (vnfs.get().getGenericVnf().size() > 1) { - throw new Exception("Multiple Vnfs Returned"); + String message = String.format("Multiple vnfs found for service-instance-id: %s and vnf-name: %s.", + serviceInstanceId, vnfName); + throw new MultipleObjectsFoundException(message); } else { vnf = vnfs.get().getGenericVnf().get(0); } @@ -519,7 +529,7 @@ public class BBInputSetupUtils { } public Optional<VolumeGroup> getRelatedVolumeGroupByNameFromVnf(String vnfId, String volumeGroupName) - throws Exception { + throws MultipleObjectsFoundException { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId); uri.relatedTo(AAIObjectPlurals.VOLUME_GROUP).queryParam("volume-group-name", volumeGroupName); Optional<VolumeGroups> volumeGroups = injectionHelper.getAaiClient().get(VolumeGroups.class, uri); @@ -529,7 +539,9 @@ public class BBInputSetupUtils { return Optional.empty(); } else { if (volumeGroups.get().getVolumeGroup().size() > 1) { - throw new Exception("Multiple VolumeGroups Returned"); + String message = String.format("Multiple volume-groups found for vnf-id: %s and volume-group-name: %s.", + vnfId, volumeGroupName); + throw new MultipleObjectsFoundException(message); } else { volumeGroup = volumeGroups.get().getVolumeGroup().get(0); } @@ -538,7 +550,7 @@ public class BBInputSetupUtils { } public Optional<VolumeGroup> getRelatedVolumeGroupByNameFromVfModule(String vnfId, String vfModuleId, - String volumeGroupName) throws Exception { + String volumeGroupName) throws MultipleObjectsFoundException { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId); uri.relatedTo(AAIObjectPlurals.VOLUME_GROUP).queryParam("volume-group-name", volumeGroupName); Optional<VolumeGroups> volumeGroups = injectionHelper.getAaiClient().get(VolumeGroups.class, uri); @@ -548,6 +560,27 @@ public class BBInputSetupUtils { return Optional.empty(); } else { if (volumeGroups.get().getVolumeGroup().size() > 1) { + String message = String.format( + "Multiple voulme-groups found for vnf-id: %s, vf-module-id: %s and volume-group-name: %s.", + vnfId, vfModuleId, volumeGroupName); + throw new MultipleObjectsFoundException(message); + } else { + volumeGroup = volumeGroups.get().getVolumeGroup().get(0); + } + return Optional.of(volumeGroup); + } + } + + public Optional<VolumeGroup> getRelatedVolumeGroupFromVfModule(String vnfId, String vfModuleId) throws Exception { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId); + uri.relatedTo(AAIObjectPlurals.VOLUME_GROUP); + Optional<VolumeGroups> volumeGroups = injectionHelper.getAaiClient().get(VolumeGroups.class, uri); + VolumeGroup volumeGroup = null; + if (!volumeGroups.isPresent()) { + logger.debug("VfModule does not have a volume group attached"); + return Optional.empty(); + } else { + if (volumeGroups.get().getVolumeGroup().size() > 1) { throw new Exception("Multiple VolumeGroups Returned"); } else { volumeGroup = volumeGroups.get().getVolumeGroup().get(0); @@ -587,6 +620,24 @@ public class BBInputSetupUtils { return aaiRC.exists(l3networkUri); } + public boolean existsAAIVfModuleGloballyByName(String vfModuleName) { + AAIResourceUri vfModuleUri = + AAIUriFactory.createNodesUri(AAIObjectPlurals.VF_MODULE).queryParam("vf-module-name", vfModuleName); + return injectionHelper.getAaiClient().exists(vfModuleUri); + } + + public boolean existsAAIConfigurationGloballyByName(String configurationName) { + AAIResourceUri configUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.CONFIGURATION) + .queryParam("configuration-name", configurationName); + return injectionHelper.getAaiClient().exists(configUri); + } + + public boolean existsAAIVolumeGroupGloballyByName(String volumeGroupName) { + AAIResourceUri volumeGroupUri = AAIUriFactory.createNodesUri(AAIObjectPlurals.VOLUME_GROUP) + .queryParam("volume-group-name", volumeGroupName); + return injectionHelper.getAaiClient().exists(volumeGroupUri); + } + public GenericVnfs getAAIVnfsGloballyByName(String vnfName) { return injectionHelper.getAaiClient() @@ -599,7 +650,7 @@ public class BBInputSetupUtils { } public Optional<Configuration> getRelatedConfigurationByNameFromServiceInstance(String serviceInstanceId, - String configurationName) throws Exception { + String configurationName) throws MultipleObjectsFoundException { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId); uri.relatedTo(AAIObjectPlurals.CONFIGURATION).queryParam("configuration-name", configurationName); Optional<Configurations> configurations = injectionHelper.getAaiClient().get(Configurations.class, uri); @@ -609,7 +660,10 @@ public class BBInputSetupUtils { return Optional.empty(); } else { if (configurations.get().getConfiguration().size() > 1) { - throw new Exception("Multiple Configurations Returned"); + String message = String.format( + "Multiple configurations found for service-instance-d: %s and configuration-name: %s.", + serviceInstanceId, configurationName); + throw new MultipleObjectsFoundException(message); } else { configuration = configurations.get().getConfiguration().get(0); } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/ServiceModelNotFoundException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/ServiceModelNotFoundException.java new file mode 100644 index 0000000000..b9daad6626 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/ServiceModelNotFoundException.java @@ -0,0 +1,15 @@ +package org.onap.so.bpmn.servicedecomposition.tasks.exceptions; + +public class ServiceModelNotFoundException extends Exception { + + private static final long serialVersionUID = -5551887892983898061L; + + public ServiceModelNotFoundException() { + super(); + } + + public ServiceModelNotFoundException(String message) { + super(message); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java index 955cf94618..483b626f95 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java @@ -46,7 +46,9 @@ import java.util.Optional; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.junit.Assert; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; @@ -87,6 +89,8 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoNetwork; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceInstance; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceProxy; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule; +import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.NoServiceInstanceFoundException; +import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.ServiceModelNotFoundException; import org.onap.so.client.aai.AAICommonObjectMapperProvider; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.entities.AAIResultWrapper; @@ -149,6 +153,9 @@ public class BBInputSetupTest { @Mock private RequestsDbClient requestsDbClient; + @Rule + public ExpectedException expectedException = ExpectedException.none(); + @Before public void setup() { SPY_bbInputSetup.setBbInputSetupUtils(SPY_bbInputSetupUtils); @@ -462,19 +469,50 @@ public class BBInputSetupTest { assertThat(actual, sameBeanAs(expected)); } - @Test(expected = Exception.class) + @Test public void testGetGBBALaCarteNonServiceWithoutServiceModelInfo() throws Exception { ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"), ExecuteBuildingBlock.class); RequestDetails requestDetails = mapper.readValue( new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class); Map<ResourceKey, String> lookupKeyMap = new HashMap<>(); + lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "si123"); + String requestAction = "createInstance"; + org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance(); + aaiServiceInstance.setModelVersionId("modelVersionId"); + String resourceId = "123"; + String vnfType = "vnfType"; + + doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("si123"); + doReturn(null).when(SPY_bbInputSetupUtils).getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); + + expectedException.expect(ServiceModelNotFoundException.class); + expectedException.expectMessage( + "Related service instance model not found in MSO CatalogDB: model-version-id=modelVersionId"); + + SPY_bbInputSetup.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, + vnfType); + } + + @Test + public void testGetGBBALaCarteNonServiceServiceInstanceNotFoundInAAI() throws Exception { + ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"), + ExecuteBuildingBlock.class); + RequestDetails requestDetails = mapper.readValue( + new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class); + Map<ResourceKey, String> lookupKeyMap = new HashMap<>(); + lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "si123"); String requestAction = "createInstance"; org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance(); aaiServiceInstance.setModelVersionId("modelVersionId"); String resourceId = "123"; String vnfType = "vnfType"; + doReturn(null).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("si123"); + + expectedException.expect(NoServiceInstanceFoundException.class); + expectedException.expectMessage("Related service instance from AAI not found: service-instance-id=si123"); + SPY_bbInputSetup.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); } @@ -780,6 +818,7 @@ public class BBInputSetupTest { String vnfType = "vnfType"; String resourceId = "networkId"; String productFamilyId = "productFamilyId"; + String applicationId = "applicationId"; Service service = Mockito.mock(Service.class); ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class); RequestDetails requestDetails = Mockito.mock(RequestDetails.class); @@ -803,6 +842,7 @@ public class BBInputSetupTest { doReturn(lineOfBusiness).when(requestDetails).getLineOfBusiness(); doReturn(relatedInstanceList).when(requestDetails).getRelatedInstanceList(); doReturn(cloudConfiguration).when(requestDetails).getCloudConfiguration(); + doReturn(applicationId).when(requestInfo).getApplicationId(); doReturn(ModelType.network).when(modelInfo).getModelType(); SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(REQUEST_ID, requestDetails, service, bbName, @@ -814,14 +854,16 @@ public class BBInputSetupTest { doReturn(ModelType.vnf).when(modelInfo).getModelType(); resourceId = "vnfId"; + doNothing().when(SPY_bbInputSetup).populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, relatedInstanceList, resourceId, - vnfType, null, productFamilyId); + vnfType, null, productFamilyId, applicationId); + SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(REQUEST_ID, requestDetails, service, bbName, serviceInstance, lookupKeyMap, resourceId, vnfType, null, null, false); verify(SPY_bbInputSetup, times(1)).populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, relatedInstanceList, resourceId, - vnfType, null, productFamilyId); + vnfType, null, productFamilyId, applicationId); assertEquals("VnfId populated", true, lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID).equalsIgnoreCase(resourceId)); @@ -846,6 +888,18 @@ public class BBInputSetupTest { lookupKeyMap, resourceId, relatedInstanceList, instanceName, null, cloudConfiguration, false); assertEquals("VfModuleId populated", true, lookupKeyMap.get(ResourceKey.VF_MODULE_ID).equalsIgnoreCase(resourceId)); + + String bbNameAssignVolume = AssignFlows.VOLUME_GROUP.toString(); + doReturn(ModelType.vfModule).when(modelInfo).getModelType(); + resourceId = "vfModuleId"; + doNothing().when(SPY_bbInputSetup).populateVolumeGroup(REQUEST_ID, modelInfo, service, bbNameAssignVolume, + serviceInstance, lookupKeyMap, resourceId, relatedInstanceList, instanceName, vnfType, null); + SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(REQUEST_ID, requestDetails, service, bbNameAssignVolume, + serviceInstance, lookupKeyMap, resourceId, vnfType, null, null, false); + verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(REQUEST_ID, modelInfo, service, bbNameAssignVolume, + serviceInstance, lookupKeyMap, resourceId, relatedInstanceList, instanceName, vnfType, null); + assertEquals("VolumeGroupId populated", true, + lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID).equalsIgnoreCase(resourceId)); } @Test @@ -1354,6 +1408,7 @@ public class BBInputSetupTest { vnf.setVnfName("vnfName"); serviceInstance.getVnfs().add(vnf); String vnfType = "vnfType"; + String applicationId = "applicationId"; RequestDetails requestDetails = mapper.readValue(new File(RESOURCE_PATH + "RequestDetails_CreateVnf.json"), RequestDetails.class); @@ -1380,20 +1435,20 @@ public class BBInputSetupTest { SPY_bbInputSetup.populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, - null, requestDetails.getRequestInfo().getProductFamilyId()); + null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); SPY_bbInputSetup.populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, - null, requestDetails.getRequestInfo().getProductFamilyId()); + null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); verify(SPY_bbInputSetup, times(1)).mapCatalogVnf(vnf, modelInfo, service); instanceName = "vnfName2"; GenericVnf vnf2 = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness, - resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId()); + resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); doReturn(vnf2).when(SPY_bbInputSetup).createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness, - resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId()); + resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); doNothing().when(SPY_bbInputSetup).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}"); doNothing().when(SPY_bbInputSetup).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service); @@ -1401,7 +1456,7 @@ public class BBInputSetupTest { SPY_bbInputSetup.populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, - null, requestDetails.getRequestInfo().getProductFamilyId()); + null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); verify(SPY_bbInputSetup, times(2)).mapCatalogVnf(vnf2, modelInfo, service); verify(SPY_bbInputSetup, times(2)).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}"); verify(SPY_bbInputSetup, times(2)).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service); @@ -1463,6 +1518,7 @@ public class BBInputSetupTest { Platform expectedPlatform = new Platform(); LineOfBusiness expectedLineOfBusiness = new LineOfBusiness(); String resourceId = "123"; + String applicationId = "applicationId"; doReturn(expectedPlatform).when(bbInputSetupMapperLayer).mapRequestPlatform(platform); doReturn(expectedLineOfBusiness).when(bbInputSetupMapperLayer).mapRequestLineOfBusiness(lineOfBusiness); org.onap.aai.domain.yang.GenericVnf vnfAAI = new org.onap.aai.domain.yang.GenericVnf(); @@ -1477,18 +1533,18 @@ public class BBInputSetupTest { SPY_bbInputSetup.populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, - null, requestDetails.getRequestInfo().getProductFamilyId()); + null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); SPY_bbInputSetup.populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, - null, requestDetails.getRequestInfo().getProductFamilyId()); + null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); verify(SPY_bbInputSetup, times(1)).mapCatalogVnf(vnf, modelInfo, service); instanceName = "vnfName2"; GenericVnf vnf2 = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness, - resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId()); + resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); org.onap.aai.domain.yang.GenericVnf vnf2AAI = new org.onap.aai.domain.yang.GenericVnf(); vnfAAI.setModelCustomizationId("modelCustId2"); @@ -1497,7 +1553,7 @@ public class BBInputSetupTest { doNothing().when(SPY_bbInputSetup).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}"); SPY_bbInputSetup.populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, - null, requestDetails.getRequestInfo().getProductFamilyId()); + null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); verify(SPY_bbInputSetup, times(2)).mapCatalogVnf(vnf2, modelInfo, service); verify(SPY_bbInputSetup, times(2)).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}"); verify(SPY_bbInputSetup, times(1)).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service); @@ -1933,7 +1989,6 @@ public class BBInputSetupTest { configResourceKeys.setVfModuleCustomizationUUID("vfModuleCustomizationUUID"); configResourceKeys.setVnfResourceCustomizationUUID("vnfResourceCustomizationUUID"); executeBB.setConfigurationResourceKeys(configResourceKeys); - executeBB.setRequestDetails(requestDetails); doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID)); @@ -1959,7 +2014,7 @@ public class BBInputSetupTest { any(String.class), isA(org.onap.so.serviceinstancebeans.Platform.class), isA(org.onap.so.serviceinstancebeans.LineOfBusiness.class), isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(), any(String.class), any(String.class), any(), - any(String.class)); + any(String.class), any(String.class)); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VF_MODULE.toString()); @@ -2218,7 +2273,6 @@ public class BBInputSetupTest { Service service = Mockito.mock(Service.class); String requestAction = "createInstance"; - executeBB.setRequestDetails(requestDetails); doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID)); @@ -2243,7 +2297,7 @@ public class BBInputSetupTest { any(String.class), isA(org.onap.so.serviceinstancebeans.Platform.class), isA(org.onap.so.serviceinstancebeans.LineOfBusiness.class), isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), ArgumentMatchers.isNull(), any(String.class), - ArgumentMatchers.isNull(), any(), any(String.class)); + ArgumentMatchers.isNull(), any(), any(String.class), any()); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VF_MODULE.toString()); @@ -2308,7 +2362,7 @@ public class BBInputSetupTest { any(String.class), isA(org.onap.so.serviceinstancebeans.Platform.class), isA(org.onap.so.serviceinstancebeans.LineOfBusiness.class), isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(), any(String.class), any(String.class), any(), - any(String.class)); + any(String.class), any(String.class)); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VF_MODULE.toString()); @@ -2668,6 +2722,48 @@ public class BBInputSetupTest { } @Test + public void testGetGBBMacroExistingServiceServiceinstancenotFoundInAai() throws Exception { + ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"), + ExecuteBuildingBlock.class); + Map<ResourceKey, String> lookupKeyMap = new HashMap<>(); + lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "si123"); + + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + cloudConfiguration.setLcpCloudRegionId("cloudRegionId"); + + doReturn(null).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("si123"); + + expectedException.expect(NoServiceInstanceFoundException.class); + expectedException.expectMessage("Related service instance from AAI not found: service-instance-id=si123"); + + SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap, "AssignVnfBB", "assign", + cloudConfiguration); + } + + @Test + public void testGetGBBMacroExistingServiceServiceModelNotFound() throws Exception { + ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"), + ExecuteBuildingBlock.class); + Map<ResourceKey, String> lookupKeyMap = new HashMap<>(); + lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "si123"); + org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance(); + aaiServiceInstance.setModelVersionId("modelVersionId"); + + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + cloudConfiguration.setLcpCloudRegionId("cloudRegionId"); + + doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("si123"); + doReturn(null).when(SPY_bbInputSetupUtils).getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); + + expectedException.expect(ServiceModelNotFoundException.class); + expectedException.expectMessage( + "Related service instance model not found in MSO CatalogDB: model-version-id=modelVersionId"); + + SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap, "AssignVnfBB", "assign", + cloudConfiguration); + } + + @Test public void testGetVnfId() { String expected = "vnfId"; ExecuteBuildingBlock executeBB = new ExecuteBuildingBlock(); @@ -2767,6 +2863,7 @@ public class BBInputSetupTest { String platformName = "platformName"; String lineOfBusinessName = "lineOfBusinessName"; String productFamilyId = "productFamilyId"; + String applicationId = "applicationId"; Platform platform = new Platform(); platform.setPlatformName(platformName); LineOfBusiness lineOfBusiness = new LineOfBusiness(); @@ -2783,6 +2880,7 @@ public class BBInputSetupTest { expected.setLineOfBusiness(lineOfBusiness); expected.setProvStatus("PREPROV"); expected.setServiceId(productFamilyId); + expected.setApplicationId(applicationId); Map<ResourceKey, String> lookupKeyMap = new HashMap<>(); List<Map<String, String>> instanceParams = new ArrayList<>(); instanceParams.add(cloudParams); @@ -2796,14 +2894,14 @@ public class BBInputSetupTest { doReturn(lineOfBusiness).when(bbInputSetupMapperLayer).mapRequestLineOfBusiness(requestLineOfBusiness); GenericVnf actual = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, requestPlatform, - requestLineOfBusiness, vnfId, vnfType, instanceParams, productFamilyId); + requestLineOfBusiness, vnfId, vnfType, instanceParams, productFamilyId, applicationId); assertThat(actual, sameBeanAs(expected)); assertEquals("LookupKeyMap is populated", vnfId, lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID)); expected.getCloudParams().clear(); actual = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, requestPlatform, requestLineOfBusiness, - vnfId, vnfType, null, productFamilyId); + vnfId, vnfType, null, productFamilyId, applicationId); assertThat(actual, sameBeanAs(expected)); } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java index 7780837714..3fdbf39756 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java @@ -22,6 +22,7 @@ package org.onap.so.bpmn.servicedecomposition.tasks; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; @@ -480,7 +481,9 @@ public class BBInputSetupUtilsTest { @Test public void testGetOptionalAAIServiceInstanceByNameException() throws Exception { - expectedException.expect(Exception.class); + expectedException.expect(MultipleObjectsFoundException.class); + expectedException.expectMessage(containsString( + "Multiple service instances found for customer-id: globalCustomerId, service-type: serviceType and service-instance-name: serviceInstanceId.")); String globalCustomerId = "globalCustomerId"; String serviceType = "serviceType"; @@ -628,7 +631,9 @@ public class BBInputSetupUtilsTest { @Test public void getRelatedNetworkByNameFromServiceInstanceMultipleNetworksExceptionTest() throws Exception { - expectedException.expect(Exception.class); + expectedException.expect(MultipleObjectsFoundException.class); + expectedException.expectMessage(containsString( + "Multiple networks found for service-instance-id: serviceInstanceId and network-name: networkName.")); String serviceInstanceId = "serviceInstanceId"; String networkName = "networkName"; @@ -637,11 +642,12 @@ public class BBInputSetupUtilsTest { network.setNetworkId("id123"); network.setNetworkName("name123"); - L3Networks expected = new L3Networks(); - expected.getL3Network().add(network); - expected.getL3Network().add(network); + L3Networks l3Networks = new L3Networks(); + l3Networks.getL3Network().add(network); + l3Networks.getL3Network().add(network); + Optional<L3Networks> optNetworks = Optional.of(l3Networks); - doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(L3Networks.class), any(AAIResourceUri.class)); + doReturn(optNetworks).when(MOCK_aaiResourcesClient).get(eq(L3Networks.class), any(AAIResourceUri.class)); bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance(serviceInstanceId, networkName); } @@ -711,7 +717,9 @@ public class BBInputSetupUtilsTest { @Test public void getRelatedVnfByNameFromServiceInstanceMultipleVnfsExceptionTest() throws Exception { - expectedException.expect(Exception.class); + expectedException.expect(MultipleObjectsFoundException.class); + expectedException.expectMessage(containsString( + "Multiple vnfs found for service-instance-id: serviceInstanceId and vnf-name: vnfName.")); String serviceInstanceId = "serviceInstanceId"; String vnfName = "vnfName"; @@ -720,11 +728,13 @@ public class BBInputSetupUtilsTest { vnf.setVnfId("id123"); vnf.setVnfName("name123"); - GenericVnfs expectedVnf = new GenericVnfs(); - expectedVnf.getGenericVnf().add(vnf); - expectedVnf.getGenericVnf().add(vnf); + GenericVnfs vnfs = new GenericVnfs(); + vnfs.getGenericVnf().add(vnf); + vnfs.getGenericVnf().add(vnf); + + Optional<GenericVnfs> optVnfs = Optional.of(vnfs); - doReturn(expectedVnf).when(MOCK_aaiResourcesClient).get(eq(GenericVnfs.class), any(AAIResourceUri.class)); + doReturn(optVnfs).when(MOCK_aaiResourcesClient).get(eq(GenericVnfs.class), any(AAIResourceUri.class)); bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance(serviceInstanceId, vnfName); } @@ -756,7 +766,10 @@ public class BBInputSetupUtilsTest { @Test public void getRelatedVolumeGroupByNameFromVnfMultipleVolumeGroupsExceptionTest() throws Exception { - expectedException.expect(Exception.class); + expectedException.expect(MultipleObjectsFoundException.class); + expectedException.expectMessage(containsString( + "Multiple volume-groups found for vnf-id: vnfId and volume-group-name: volumeGroupName.")); + String vnfId = "vnfId"; String volumeGroupName = "volumeGroupName"; @@ -765,12 +778,12 @@ public class BBInputSetupUtilsTest { volumeGroup.setVolumeGroupId("id123"); volumeGroup.setVolumeGroupName("name123"); - VolumeGroups expectedVolumeGroup = new VolumeGroups(); - expectedVolumeGroup.getVolumeGroup().add(volumeGroup); - expectedVolumeGroup.getVolumeGroup().add(volumeGroup); + VolumeGroups volumeGroups = new VolumeGroups(); + volumeGroups.getVolumeGroup().add(volumeGroup); + volumeGroups.getVolumeGroup().add(volumeGroup); + Optional<VolumeGroups> optVolumeGroups = Optional.of(volumeGroups); - doReturn(expectedVolumeGroup).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), - any(AAIResourceUri.class)); + doReturn(optVolumeGroups).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class)); bbInputSetupUtils.getRelatedVolumeGroupByNameFromVnf(vnfId, volumeGroupName); } @@ -802,12 +815,11 @@ public class BBInputSetupUtilsTest { } @Test - public void getRelatedVolumeGroupByNameFromVfModuleMultipleVolumeGroupsExceptionTest() throws Exception { + public void getRelatedVolumeGroupFromVfModuleMultipleVolumeGroupsExceptionTest() throws Exception { expectedException.expect(Exception.class); String vnfId = "vnfId"; String volumeGroupId = "volumeGroupId"; - String volumeGroupName = "volumeGroupName"; VolumeGroup volumeGroup = new VolumeGroup(); volumeGroup.setVolumeGroupId("id123"); @@ -820,6 +832,54 @@ public class BBInputSetupUtilsTest { doReturn(expectedVolumeGroup).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class)); + bbInputSetupUtils.getRelatedVolumeGroupFromVfModule(vnfId, volumeGroupId); + } + + @Test + public void getRelatedVolumeGroupFromVfModuleNotFoundTest() throws Exception { + String vnfId = "vnfId"; + String volumeGroupId = "volumeGroupId"; + + doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class)); + + Optional<VolumeGroup> actualVolumeGroup = + bbInputSetupUtils.getRelatedVolumeGroupFromVfModule(vnfId, volumeGroupId); + + assertEquals(actualVolumeGroup, Optional.empty()); + } + + @Test + public void getRelatedVolumeGroupFromVfModuleTest() throws Exception { + Optional<VolumeGroups> expected = Optional.of(new VolumeGroups()); + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("id123"); + expected.get().getVolumeGroup().add(volumeGroup); + doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class)); + Optional<VolumeGroup> actual = this.bbInputSetupUtils.getRelatedVolumeGroupFromVfModule("id123", "id123"); + assertEquals(actual.get().getVolumeGroupId(), expected.get().getVolumeGroup().get(0).getVolumeGroupId()); + } + + @Test + public void getRelatedVolumeGroupByNameFromVfModuleMultipleVolumeGroupsExceptionTest() throws Exception { + expectedException.expect(MultipleObjectsFoundException.class); + expectedException.expectMessage(containsString( + "Multiple voulme-groups found for vnf-id: vnfId, vf-module-id: volumeGroupId and volume-group-name: volumeGroupName.")); + String vnfId = "vnfId"; + String volumeGroupId = "volumeGroupId"; + String volumeGroupName = "volumeGroupName"; + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("id123"); + volumeGroup.setVolumeGroupName("name123"); + + VolumeGroups volumeGroups = new VolumeGroups(); + volumeGroups.getVolumeGroup().add(volumeGroup); + volumeGroups.getVolumeGroup().add(volumeGroup); + + Optional<VolumeGroups> optVolumeGroups = Optional.of(volumeGroups); + + doReturn(optVolumeGroups).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class)); + bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule(vnfId, volumeGroupId, volumeGroupName); } @@ -837,6 +897,7 @@ public class BBInputSetupUtilsTest { assertEquals(actualVolumeGroup, Optional.empty()); } + @Test public void loadOriginalFlowExecutionPathTest() throws Exception { @@ -867,6 +928,33 @@ public class BBInputSetupUtilsTest { } @Test + public void getRelatedConfigurationByNameFromServiceInstanceExceptionTest() throws Exception { + Configuration configuration = new Configuration(); + configuration.setConfigurationId("id123"); + + Configurations configurations = new Configurations(); + configurations.getConfiguration().add(configuration); + configurations.getConfiguration().add(configuration); + + Optional<Configurations> optConfigurations = Optional.of(configurations); + + doReturn(optConfigurations).when(MOCK_aaiResourcesClient).get(eq(Configurations.class), + any(AAIResourceUri.class)); + + expectedException.expect(MultipleObjectsFoundException.class); + this.bbInputSetupUtils.getRelatedConfigurationByNameFromServiceInstance("id123", "name123"); + } + + @Test + public void getRelatedConfigurationByNameFromServiceInstanceNotFoundTest() throws Exception { + doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(Configurations.class), + any(AAIResourceUri.class)); + Optional<Configuration> actualConfiguration = + bbInputSetupUtils.getRelatedConfigurationByNameFromServiceInstance("id123", "name123"); + assertEquals(actualConfiguration, Optional.empty()); + } + + @Test public void getRelatedConfigurationByNameFromServiceInstanceTest() throws Exception { Optional<Configurations> expected = Optional.of(new Configurations()); Configuration configuration = new Configuration(); @@ -878,4 +966,35 @@ public class BBInputSetupUtilsTest { assertEquals(actual.get().getConfigurationId(), expected.get().getConfiguration().get(0).getConfigurationId()); } + @Test + public void existsAAIVfModuleGloballyByNameTest() throws Exception { + AAIResourceUri expectedUri = + AAIUriFactory.createNodesUri(AAIObjectPlurals.VF_MODULE).queryParam("vf-module-name", "testVfModule"); + bbInputSetupUtils.existsAAIVfModuleGloballyByName("testVfModule"); + verify(MOCK_aaiResourcesClient, times(1)).exists(expectedUri); + } + + @Test + public void existsAAIConfigurationGloballyByNameTest() throws Exception { + AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.CONFIGURATION) + .queryParam("configuration-name", "testConfig"); + bbInputSetupUtils.existsAAIConfigurationGloballyByName("testConfig"); + verify(MOCK_aaiResourcesClient, times(1)).exists(expectedUri); + } + + @Test + public void existsAAINetworksGloballyByNameTest() throws Exception { + AAIResourceUri expectedUri = + AAIUriFactory.createResourceUri(AAIObjectPlurals.L3_NETWORK).queryParam("network-name", "testNetwork"); + bbInputSetupUtils.existsAAINetworksGloballyByName("testNetwork"); + verify(MOCK_aaiResourcesClient, times(1)).exists(expectedUri); + } + + @Test + public void existsAAIVolumeGroupGloballyByNameTest() throws Exception { + AAIResourceUri expectedUri = AAIUriFactory.createNodesUri(AAIObjectPlurals.VOLUME_GROUP) + .queryParam("volume-group-name", "testVoumeGroup"); + bbInputSetupUtils.existsAAIVolumeGroupGloballyByName("testVoumeGroup"); + verify(MOCK_aaiResourcesClient, times(1)).exists(expectedUri); + } } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/ServiceModelNotFoundExceptionTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/ServiceModelNotFoundExceptionTest.java new file mode 100644 index 0000000000..1ab1d7aa9a --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/ServiceModelNotFoundExceptionTest.java @@ -0,0 +1,19 @@ +package org.onap.so.bpmn.servicedecomposition.tasks.exceptions; + +import org.junit.Assert; +import org.junit.Test; + + +public class ServiceModelNotFoundExceptionTest { + + @Test + public void testRequestValidationException() { + + ServiceModelNotFoundException serviceModelNotFoundException = new ServiceModelNotFoundException(); + Assert.assertNull(serviceModelNotFoundException.getMessage()); + + serviceModelNotFoundException = new ServiceModelNotFoundException("test message"); + Assert.assertEquals("test message", serviceModelNotFoundException.getMessage()); + + } +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java index bd60fbe38c..b9f73f3f0e 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java @@ -372,6 +372,7 @@ public class AAICreateTasks { logger.info("VolumeGroup not found. Skipping Connect between VfModule and VolumeGroup"); } if (volumeGroup != null) { + logger.debug("Connecting VfModule to VolumGroup"); aaiVfModuleResources.connectVfModuleToVolumeGroup(vnf, vfModule, volumeGroup, execution.getGeneralBuildingBlock().getCloudRegion()); } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowAction.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowAction.java index 92dd03289c..e876e20b38 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowAction.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowAction.java @@ -54,6 +54,7 @@ import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds; import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetup; import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils; import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.DuplicateNameException; +import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.MultipleObjectsFoundException; import org.onap.so.client.aai.AAICommonObjectMapperProvider; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.entities.AAIResultWrapper; @@ -62,6 +63,7 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.exception.ExceptionBuilder; import org.onap.so.client.orchestration.AAIConfigurationResources; +import org.onap.so.client.orchestration.AAIEntityNotFoundException; import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization; import org.onap.so.db.catalog.beans.CollectionResourceCustomization; import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization; @@ -109,6 +111,8 @@ public class WorkflowAction { private static final String CONFIGURATION = "Configuration"; private static final String ASSIGNINSTANCE = "assignInstance"; private static final String CREATEINSTANCE = "createInstance"; + private static final String REPLACEINSTANCE = "replaceInstance"; + private static final String REPLACEINSTANCERETAINASSIGNMENTS = "replaceInstanceRetainAssignments"; private static final String USERPARAMSERVICE = "service"; private static final String SUPPORTEDTYPES = "vnfs|vfModules|networks|networkCollections|volumeGroups|serviceInstances|instanceGroups"; @@ -128,6 +132,8 @@ public class WorkflowAction { private static final String NAME_EXISTS_WITH_DIFF_PARENT = "(%s) id (%s) and different parent relationship"; private static final String CREATENETWORKBB = "CreateNetworkBB"; private static final String ACTIVATENETWORKBB = "ActivateNetworkBB"; + private static final String VOLUMEGROUP_DELETE_PATTERN = "(Un|De)(.*)Volume(.*)"; + private static final String VOLUMEGROUP_CREATE_PATTERN = "(A|C)(.*)Volume(.*)"; @Autowired protected BBInputSetup bbInputSetup; @@ -184,7 +190,14 @@ public class WorkflowAction { execution.setVariable(BBConstants.G_ISTOPLEVELFLOW, true); ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class); RequestDetails requestDetails = sIRequest.getRequestDetails(); - execution.setVariable("suppressRollback", isSuppressRollback(requestDetails.getRequestInfo())); + boolean suppressRollback = false; + try { + suppressRollback = requestDetails.getRequestInfo().getSuppressRollback(); + } catch (Exception ex) { + logger.error("Exception in getSuppressRollback", ex); + suppressRollback = false; + } + execution.setVariable("suppressRollback", suppressRollback); boolean isResume = false; if (isUriResume(uri)) { isResume = true; @@ -253,6 +266,18 @@ public class WorkflowAction { } orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().contains(FABRIC_CONFIGURATION)) .collect(Collectors.toList()); + + if ((requestAction.equalsIgnoreCase(REPLACEINSTANCE) + || requestAction.equalsIgnoreCase(REPLACEINSTANCERETAINASSIGNMENTS)) + && resourceType.equals(WorkflowType.VFMODULE)) { + logger.debug("Build a BB list for replacing BB modules"); + orchFlows = getVfModuleReplaceBuildingBlocks( + new ConfigBuildingBlocksDataObject().setsIRequest(sIRequest).setOrchFlows(orchFlows) + .setRequestId(requestId).setResourceKey(resourceKey).setApiVersion(apiVersion) + .setResourceId(resourceId).setRequestAction(requestAction).setaLaCarte(aLaCarte) + .setVnfType(vnfType).setWorkflowResourceIds(workflowResourceIds) + .setRequestDetails(requestDetails).setExecution(execution)); + } for (OrchestrationFlow orchFlow : orchFlows) { ExecuteBuildingBlock ebb = buildExecuteBuildingBlock(orchFlow, requestId, resourceKey, apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds, @@ -263,7 +288,8 @@ public class WorkflowAction { boolean foundRelated = false; boolean containsService = false; if (resourceType == WorkflowType.SERVICE && requestAction.equalsIgnoreCase(ASSIGNINSTANCE)) { - // SERVICE-MACRO-ASSIGN will always get user params with a + // SERVICE-MACRO-ASSIGN will always get user params with + // a // service. if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) { List<Map<String, Object>> userParams = @@ -281,7 +307,8 @@ public class WorkflowAction { "Service-Macro-Assign request details must contain user params with a service"); } } else if (resourceType == WorkflowType.SERVICE && requestAction.equalsIgnoreCase(CREATEINSTANCE)) { - // SERVICE-MACRO-CREATE will get user params with a service, + // SERVICE-MACRO-CREATE will get user params with a + // service, // a service with a network, a service with a // networkcollection, OR an empty service. // If user params is just a service or null and macro @@ -310,7 +337,8 @@ public class WorkflowAction { || requestAction.equalsIgnoreCase("activate" + FABRIC_CONFIGURATION))) { // SERVICE-MACRO-ACTIVATE, SERVICE-MACRO-UNASSIGN, and // SERVICE-MACRO-DELETE - // Will never get user params with service, macro will have + // Will never get user params with service, macro will + // have // to query the SI in AAI to find related instances. traverseAAIService(execution, resourceCounter, resourceId, aaiResourceIds); } else if (resourceType == WorkflowType.SERVICE @@ -348,7 +376,8 @@ public class WorkflowAction { logger.info("Sorting for Vlan Tagging"); flowsToExecute = sortExecutionPathByObjectForVlanTagging(flowsToExecute, requestAction); } - // By default, enable homing at VNF level for CREATEINSTANCE and ASSIGNINSTANCE + // By default, enable homing at VNF level for CREATEINSTANCE + // and ASSIGNINSTANCE if (resourceType == WorkflowType.SERVICE && (requestAction.equals(CREATEINSTANCE) || requestAction.equals(ASSIGNINSTANCE)) && !resourceCounter.stream().filter(x -> WorkflowType.VNF.equals(x.getResourceType())) @@ -365,7 +394,8 @@ public class WorkflowAction { } } } - // If the user set "Homing_Solution" to "none", disable homing, else if "Homing_Solution" is specified, + // If the user set "Homing_Solution" to "none", disable homing, else + // if "Homing_Solution" is specified, // enable it. if (sIRequest.getRequestDetails().getRequestParameters() != null && sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) { @@ -403,7 +433,7 @@ public class WorkflowAction { execution.setVariable("isRollbackComplete", false); } catch (Exception ex) { - buildAndThrowException(execution, "Exception in create execution list. " + ex.getMessage(), ex); + buildAndThrowException(execution, "Exception in execution list. ", ex); } } @@ -479,7 +509,8 @@ public class WorkflowAction { return false; } - protected List<ExecuteBuildingBlock> getConfigBuildingBlocks(ConfigBuildingBlocksDataObject dataObj) { + protected List<ExecuteBuildingBlock> getConfigBuildingBlocks(ConfigBuildingBlocksDataObject dataObj) + throws Exception { List<ExecuteBuildingBlock> flowsToExecuteConfigs = new ArrayList<>(); List<OrchestrationFlow> result = dataObj.getOrchFlows().stream() @@ -488,8 +519,17 @@ public class WorkflowAction { String vfModuleId = dataObj.getWorkflowResourceIds().getVfModuleId(); String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId(); - String vfModuleCustomizationUUID = - bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId(); + String vfModuleCustomizationUUID = ""; + org.onap.aai.domain.yang.VfModule aaiVfModule = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId); + + if (aaiVfModule == null) { + logger.error("No matching VfModule is found in Generic-Vnf in AAI for vnfId: {} and vfModuleId : {}", vnfId, + vfModuleId); + throw new AAIEntityNotFoundException("No matching VfModule is found in Generic-Vnf in AAI for vnfId: " + + vnfId + " and vfModuleId : " + vfModuleId); + } else { + vfModuleCustomizationUUID = aaiVfModule.getModelCustomizationId(); + } List<org.onap.aai.domain.yang.Vnfc> vnfcs = getRelatedResourcesInVfModule(vnfId, vfModuleId, org.onap.aai.domain.yang.Vnfc.class, AAIObjectType.VNFC); @@ -526,6 +566,68 @@ public class WorkflowAction { return flowsToExecuteConfigs; } + protected List<OrchestrationFlow> getVfModuleReplaceBuildingBlocks(ConfigBuildingBlocksDataObject dataObj) + throws Exception { + + List<ExecuteBuildingBlock> flowsToExecuteConfigs = new ArrayList<>(); + + String vnfId = dataObj.getWorkflowResourceIds().getVnfId(); + String vfModuleId = dataObj.getWorkflowResourceIds().getVfModuleId(); + + logger.debug("BUILDING REPLACE LIST"); + + boolean volumeGroupExisted = false; + boolean volumeGroupWillExist = false; + boolean keepVolumeGroup = false; + + boolean rebuildVolumeGroups = false; + if (dataObj.getRequestDetails().getRequestParameters() != null + && dataObj.getRequestDetails().getRequestParameters().getRebuildVolumeGroups() != null) { + rebuildVolumeGroups = + dataObj.getRequestDetails().getRequestParameters().getRebuildVolumeGroups().booleanValue(); + } + + Optional<VolumeGroup> volumeGroupFromVfModule = + bbInputSetupUtils.getRelatedVolumeGroupFromVfModule(vnfId, vfModuleId); + if (volumeGroupFromVfModule.isPresent()) { + String volumeGroupId = volumeGroupFromVfModule.get().getVolumeGroupId(); + logger.debug("Volume group id of the existing volume group is: " + volumeGroupId); + volumeGroupExisted = true; + dataObj.getWorkflowResourceIds().setVolumeGroupId(volumeGroupId); + } + + List<OrchestrationFlow> orchFlows = dataObj.getOrchFlows(); + VfModuleCustomization vfModuleCustomization = catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID( + dataObj.getRequestDetails().getModelInfo().getModelCustomizationUuid()); + if (vfModuleCustomization != null && vfModuleCustomization.getVfModule() != null + && vfModuleCustomization.getVfModule().getVolumeHeatTemplate() != null + && vfModuleCustomization.getVolumeHeatEnv() != null) { + volumeGroupWillExist = true; + if (!volumeGroupExisted) { + String newVolumeGroupId = UUID.randomUUID().toString(); + dataObj.getWorkflowResourceIds().setVolumeGroupId(newVolumeGroupId); + logger.debug("newVolumeGroupId: " + newVolumeGroupId); + } + } + + if (volumeGroupExisted && volumeGroupWillExist && !rebuildVolumeGroups) { + keepVolumeGroup = true; + } + + if (!volumeGroupExisted || keepVolumeGroup) { + logger.debug("Filtering out deletion of volume groups"); + orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().matches(VOLUMEGROUP_DELETE_PATTERN)) + .collect(Collectors.toList()); + } + if (!volumeGroupWillExist || keepVolumeGroup) { + logger.debug("Filtering out creation of volume groups"); + orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().matches(VOLUMEGROUP_CREATE_PATTERN)) + .collect(Collectors.toList()); + } + + return orchFlows; + } + protected String getVnfcNameForConfiguration(org.onap.aai.domain.yang.Configuration configuration) { AAIResultWrapper wrapper = new AAIResultWrapper(configuration); Optional<Relationships> relationshipsOp = wrapper.getRelationships(); @@ -1175,142 +1277,21 @@ public class WorkflowAction { RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) throws Exception { try { if ("SERVICE".equalsIgnoreCase(type.toString())) { - // Service name verification based upon name + model-version-id - // + service-type + global-customer-id per requirements - String globalCustomerId = reqDetails.getSubscriberInfo().getGlobalSubscriberId(); - String serviceType = reqDetails.getRequestParameters().getSubscriptionServiceType(); - if (instanceName != null) { - Optional<ServiceInstance> serviceInstanceAAI = - bbInputSetupUtils.getAAIServiceInstanceByName(globalCustomerId, serviceType, instanceName); - if (serviceInstanceAAI.isPresent()) { - if (serviceInstanceAAI.get().getModelVersionId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelVersionId())) { - return serviceInstanceAAI.get().getServiceInstanceId(); - } else { - throw new DuplicateNameException(SERVICE_INSTANCE, - String.format(NAME_EXISTS_WITH_DIFF_VERSION_ID, instanceName, - reqDetails.getModelInfo().getModelVersionId())); - } - } else { - ServiceInstances aaiServiceInstances = - bbInputSetupUtils.getAAIServiceInstancesGloballyByName(instanceName); - if (aaiServiceInstances != null) { - if (aaiServiceInstances.getServiceInstance() != null - && !aaiServiceInstances.getServiceInstance().isEmpty()) { - if (aaiServiceInstances.getServiceInstance().size() > 1) { - throw new DuplicateNameException(SERVICE_INSTANCE, - String.format(NAME_EXISTS_MULTIPLE, instanceName)); - } else { - ServiceInstance si = - aaiServiceInstances.getServiceInstance().stream().findFirst().get(); - Map<String, String> keys = - bbInputSetupUtils.getURIKeysFromServiceInstance(si.getServiceInstanceId()); - - throw new DuplicateNameException(SERVICE_INSTANCE, - String.format(NAME_EXISTS_WITH_DIFF_COMBINATION, instanceName, - keys.get("global-customer-id"), keys.get("service-type"), - si.getModelVersionId())); - } - } - } - } - } + return validateServiceResourceIdInAAI(generatedResourceId, instanceName, reqDetails); } else if ("NETWORK".equalsIgnoreCase(type.toString())) { - Optional<L3Network> network = bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance( - workflowResourceIds.getServiceInstanceId(), instanceName); - if (network.isPresent()) { - if (network.get().getModelCustomizationId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { - return network.get().getNetworkId(); - } else { - throw new DuplicateNameException("l3Network", - String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, instanceName, - network.get().getModelCustomizationId())); - } - } - - if (bbInputSetupUtils.existsAAINetworksGloballyByName(instanceName)) { - throw new DuplicateNameException("l3Network", String.format(NAME_EXISTS_WITH_DIFF_PARENT, - instanceName, workflowResourceIds.getServiceInstanceId())); - } - + return validateNetworkResourceIdInAAI(generatedResourceId, instanceName, reqDetails, + workflowResourceIds); } else if ("VNF".equalsIgnoreCase(type.toString())) { - Optional<GenericVnf> vnf = bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance( - workflowResourceIds.getServiceInstanceId(), instanceName); - if (vnf.isPresent()) { - if (vnf.get().getModelCustomizationId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { - return vnf.get().getVnfId(); - } else { - throw new DuplicateNameException("generic-vnf", - String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, instanceName, - vnf.get().getModelCustomizationId())); - } - } - GenericVnfs vnfs = bbInputSetupUtils.getAAIVnfsGloballyByName(instanceName); - if (vnfs != null) { - throw new DuplicateNameException("generic-vnf", String.format(NAME_EXISTS_WITH_DIFF_PARENT, - instanceName, vnfs.getGenericVnf().get(0).getVnfId())); - } + return validateVnfResourceIdInAAI(generatedResourceId, instanceName, reqDetails, workflowResourceIds); } else if ("VFMODULE".equalsIgnoreCase(type.toString())) { - GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId()); - if (vnf != null && vnf.getVfModules() != null) { - for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) { - if (vfModule.getVfModuleName().equalsIgnoreCase(instanceName)) { - if (vfModule.getModelCustomizationId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { - return vfModule.getVfModuleId(); - } else { - throw new DuplicateNameException("vfModule", - String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, instanceName, - reqDetails.getModelInfo().getModelCustomizationId())); - } - } - } - } + return validateVfModuleResourceIdInAAI(generatedResourceId, instanceName, reqDetails, + workflowResourceIds); } else if ("VOLUMEGROUP".equalsIgnoreCase(type.toString())) { - GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId()); - Optional<VolumeGroup> volumeGroup = bbInputSetupUtils - .getRelatedVolumeGroupByNameFromVnf(workflowResourceIds.getVnfId(), instanceName); - if (volumeGroup.isPresent()) { - if (vnf.getModelCustomizationId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { - return volumeGroup.get().getVolumeGroupId(); - } else { - throw new DuplicateNameException("volumeGroup", volumeGroup.get().getVolumeGroupName()); - } - } - if (vnf != null && vnf.getVfModules() != null) { - for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) { - Optional<VolumeGroup> volumeGroupFromVfModule = - bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule(vnf.getVnfId(), - vfModule.getVfModuleId(), instanceName); - if (volumeGroupFromVfModule.isPresent()) { - if (vnf.getModelCustomizationId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { - return volumeGroupFromVfModule.get().getVolumeGroupId(); - } else { - throw new DuplicateNameException("volumeGroup", - String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, instanceName, - volumeGroupFromVfModule.get().getModelCustomizationId())); - } - } - } - } + return validateVolumeGroupResourceIdInAAI(generatedResourceId, instanceName, reqDetails, + workflowResourceIds); } else if ("CONFIGURATION".equalsIgnoreCase(type.toString())) { - Optional<org.onap.aai.domain.yang.Configuration> configuration = - bbInputSetupUtils.getRelatedConfigurationByNameFromServiceInstance( - workflowResourceIds.getServiceInstanceId(), instanceName); - if (configuration.isPresent()) { - if (configuration.get().getModelCustomizationId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { - return configuration.get().getConfigurationId(); - } else { - throw new DuplicateNameException("configuration", - String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, instanceName, - configuration.get().getConfigurationId())); - } - } + return validateConfigurationResourceIdInAAI(generatedResourceId, instanceName, reqDetails, + workflowResourceIds); } return generatedResourceId; } catch (DuplicateNameException dne) { @@ -1468,6 +1449,11 @@ public class WorkflowAction { requestDetails, false, null, false)); } } else if (orchFlow.getFlowName().contains(VOLUMEGROUP)) { + if (requestAction.equalsIgnoreCase(REPLACEINSTANCE) + || requestAction.equalsIgnoreCase(REPLACEINSTANCERETAINASSIGNMENTS)) { + logger.debug("Replacing workflow resource id by volume group id"); + resourceId = workflowResourceIds.getVolumeGroupId(); + } for (int i = 0; i < resourceCounter.stream() .filter(x -> WorkflowType.VOLUMEGROUP == x.getResourceType()).collect(Collectors.toList()) .size(); i++) { @@ -1528,6 +1514,13 @@ public class WorkflowAction { executeBuildingBlock.setApiVersion(apiVersion); executeBuildingBlock.setaLaCarte(aLaCarte); executeBuildingBlock.setRequestAction(requestAction); + + if (resource != null + && (orchFlow.getFlowName().contains(VOLUMEGROUP) && (requestAction.equalsIgnoreCase(REPLACEINSTANCE) + || requestAction.equalsIgnoreCase(REPLACEINSTANCERETAINASSIGNMENTS)))) { + logger.debug("Setting resourceId to volume group id for volume group flow on replace"); + resourceId = workflowResourceIds.getVolumeGroupId(); + } executeBuildingBlock.setResourceId(resourceId); executeBuildingBlock.setVnfType(vnfType); executeBuildingBlock.setWorkflowResourceIds(workflowResourceIds); @@ -1640,5 +1633,151 @@ public class WorkflowAction { && (serviceInstanceId != null && serviceInstanceId.trim().length() > 1) && (bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId) != null)); } -} + protected String validateServiceResourceIdInAAI(String generatedResourceId, String instanceName, + RequestDetails reqDetails) throws DuplicateNameException, MultipleObjectsFoundException { + String globalCustomerId = reqDetails.getSubscriberInfo().getGlobalSubscriberId(); + String serviceType = reqDetails.getRequestParameters().getSubscriptionServiceType(); + if (instanceName != null) { + Optional<ServiceInstance> serviceInstanceAAI = + bbInputSetupUtils.getAAIServiceInstanceByName(globalCustomerId, serviceType, instanceName); + if (serviceInstanceAAI.isPresent()) { + if (serviceInstanceAAI.get().getModelVersionId() + .equalsIgnoreCase(reqDetails.getModelInfo().getModelVersionId())) { + return serviceInstanceAAI.get().getServiceInstanceId(); + } else { + throw new DuplicateNameException(SERVICE_INSTANCE, String.format(NAME_EXISTS_WITH_DIFF_VERSION_ID, + instanceName, reqDetails.getModelInfo().getModelVersionId())); + } + } else { + ServiceInstances aaiServiceInstances = + bbInputSetupUtils.getAAIServiceInstancesGloballyByName(instanceName); + if (aaiServiceInstances != null) { + if (aaiServiceInstances.getServiceInstance() != null + && !aaiServiceInstances.getServiceInstance().isEmpty()) { + if (aaiServiceInstances.getServiceInstance().size() > 1) { + throw new DuplicateNameException(SERVICE_INSTANCE, + String.format(NAME_EXISTS_MULTIPLE, instanceName)); + } else { + ServiceInstance si = aaiServiceInstances.getServiceInstance().stream().findFirst().get(); + Map<String, String> keys = + bbInputSetupUtils.getURIKeysFromServiceInstance(si.getServiceInstanceId()); + + throw new DuplicateNameException(SERVICE_INSTANCE, + String.format(NAME_EXISTS_WITH_DIFF_COMBINATION, instanceName, + keys.get("global-customer-id"), keys.get("service-type"), + si.getModelVersionId())); + } + } + } + } + } + return generatedResourceId; + } + + protected String validateNetworkResourceIdInAAI(String generatedResourceId, String instanceName, + RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) + throws DuplicateNameException, MultipleObjectsFoundException { + Optional<L3Network> network = bbInputSetupUtils + .getRelatedNetworkByNameFromServiceInstance(workflowResourceIds.getServiceInstanceId(), instanceName); + if (network.isPresent()) { + if (network.get().getModelCustomizationId() + .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { + return network.get().getNetworkId(); + } else { + throw new DuplicateNameException("l3Network", String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, + instanceName, network.get().getModelCustomizationId())); + } + } + if (bbInputSetupUtils.existsAAINetworksGloballyByName(instanceName)) { + throw new DuplicateNameException("l3Network", String.format(NAME_EXISTS_WITH_DIFF_PARENT, instanceName, + workflowResourceIds.getServiceInstanceId())); + } + return generatedResourceId; + } + + protected String validateVnfResourceIdInAAI(String generatedResourceId, String instanceName, + RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) + throws DuplicateNameException, MultipleObjectsFoundException { + Optional<GenericVnf> vnf = bbInputSetupUtils + .getRelatedVnfByNameFromServiceInstance(workflowResourceIds.getServiceInstanceId(), instanceName); + if (vnf.isPresent()) { + if (vnf.get().getModelCustomizationId() + .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { + return vnf.get().getVnfId(); + } else { + throw new DuplicateNameException("generic-vnf", String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, + instanceName, vnf.get().getModelCustomizationId())); + } + } + GenericVnfs vnfs = bbInputSetupUtils.getAAIVnfsGloballyByName(instanceName); + if (vnfs != null) { + throw new DuplicateNameException("generic-vnf", + String.format(NAME_EXISTS_WITH_DIFF_PARENT, instanceName, vnfs.getGenericVnf().get(0).getVnfId())); + } + return generatedResourceId; + } + + protected String validateVfModuleResourceIdInAAI(String generatedResourceId, String instanceName, + RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) throws DuplicateNameException { + GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId()); + if (vnf != null && vnf.getVfModules() != null) { + for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) { + if (vfModule.getVfModuleName().equalsIgnoreCase(instanceName)) { + if (vfModule.getModelCustomizationId() + .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { + return vfModule.getVfModuleId(); + } else { + throw new DuplicateNameException("vfModule", + String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, instanceName, + reqDetails.getModelInfo().getModelCustomizationId())); + } + } + } + } + if (bbInputSetupUtils.existsAAIVfModuleGloballyByName(instanceName)) { + throw new DuplicateNameException("vfModule", instanceName); + } + return generatedResourceId; + } + + protected String validateVolumeGroupResourceIdInAAI(String generatedResourceId, String instanceName, + RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) + throws DuplicateNameException, MultipleObjectsFoundException { + Optional<VolumeGroup> volumeGroup = + bbInputSetupUtils.getRelatedVolumeGroupByNameFromVnf(workflowResourceIds.getVnfId(), instanceName); + if (volumeGroup.isPresent()) { + if (volumeGroup.get().getVfModuleModelCustomizationId() + .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { + return volumeGroup.get().getVolumeGroupId(); + } else { + throw new DuplicateNameException("volumeGroup", volumeGroup.get().getVolumeGroupName()); + } + } + if (bbInputSetupUtils.existsAAIVolumeGroupGloballyByName(instanceName)) { + throw new DuplicateNameException("volumeGroup", instanceName); + } + return generatedResourceId; + } + + protected String validateConfigurationResourceIdInAAI(String generatedResourceId, String instanceName, + RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) + throws DuplicateNameException, MultipleObjectsFoundException { + Optional<org.onap.aai.domain.yang.Configuration> configuration = + bbInputSetupUtils.getRelatedConfigurationByNameFromServiceInstance( + workflowResourceIds.getServiceInstanceId(), instanceName); + if (configuration.isPresent()) { + if (configuration.get().getModelCustomizationId() + .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { + return configuration.get().getConfigurationId(); + } else { + throw new DuplicateNameException("configuration", String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, + instanceName, configuration.get().getConfigurationId())); + } + } + if (bbInputSetupUtils.existsAAIConfigurationGloballyByName(instanceName)) { + throw new DuplicateNameException("configuration", instanceName); + } + return generatedResourceId; + } +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionTest.java index 6c959703e4..ed3ee0a3a1 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionTest.java @@ -83,6 +83,7 @@ import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.Relationships; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.client.orchestration.AAIEntityNotFoundException; import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization; import org.onap.so.db.catalog.beans.CollectionResource; import org.onap.so.db.catalog.beans.CollectionResourceCustomization; @@ -124,6 +125,16 @@ public class WorkflowActionTest extends BaseTaskTest { private String RESOURCE_PATH = "src/test/resources/__files/"; + private List<OrchestrationFlow> replaceVfModuleOrchFlows = + createFlowList("DeactivateVfModuleBB", "DeleteVfModuleATTBB", "DeactivateVolumeGroupBB", + "DeleteVolumeGroupBB", "UnassignVFModuleBB", "UnassignVolumeGroupBB", "AssignVolumeGroupBB", + "AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB", "CreateVolumeGroupBB", + "ActivateVolumeGroupBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + private List<OrchestrationFlow> replaceRetainAssignmentsVfModuleOrchFlows = createFlowList("DeactivateVfModuleBB", + "DeleteVfModuleATTBB", "DeactivateVolumeGroupBB", "DeleteVolumeGroupBB", "UnassignVolumeGroupBB", + "AssignVolumeGroupBB", "ChangeModelVfModuleBB", "CreateVolumeGroupBB", "ActivateVolumeGroupBB", + "CreateVfModuleBB", "ActivateVfModuleBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + @Before public void before() throws Exception { execution = new DelegateExecutionFake(); @@ -1092,6 +1103,362 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test + public void selectExecutionListALaCarteVfModuleNoVolumeGroupReplaceTest() throws Exception { + String gAction = "replaceInstance"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "UnassignVFModuleBB", + "AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB", "ChangeModelVnfBB", + "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleNoVolumeGroupReplaceRetainAssignmentsTest() throws Exception { + String gAction = "replaceInstanceRetainAssignments"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceRetainAssignmentsVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "ChangeModelVfModuleBB", + "CreateVfModuleBB", "ActivateVfModuleBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleVolumeGroupToNoVolumeGroupReplaceTest() throws Exception { + String gAction = "replaceInstance"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("volumeGroupId"); + doReturn(Optional.of(volumeGroup)).when(bbSetupUtils) + .getRelatedVolumeGroupFromVfModule("b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", "1234"); + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "DeactivateVolumeGroupBB", + "DeleteVolumeGroupBB", "UnassignVFModuleBB", "UnassignVolumeGroupBB", "AssignVfModuleBB", + "CreateVfModuleBB", "ActivateVfModuleBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleVolumeGroupToNoVolumeGroupReplaceRetainAssignmentsTest() + throws Exception { + String gAction = "replaceInstanceRetainAssignments"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("volumeGroupId"); + doReturn(Optional.of(volumeGroup)).when(bbSetupUtils) + .getRelatedVolumeGroupFromVfModule("b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", "1234"); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceRetainAssignmentsVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "DeactivateVolumeGroupBB", + "DeleteVolumeGroupBB", "UnassignVolumeGroupBB", "ChangeModelVfModuleBB", "CreateVfModuleBB", + "ActivateVfModuleBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleKeepVolumeGroupReplaceTest() throws Exception { + String gAction = "replaceInstance"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("volumeGroupId"); + doReturn(Optional.of(volumeGroup)).when(bbSetupUtils) + .getRelatedVolumeGroupFromVfModule("b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", "1234"); + + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + vfModuleCustomization.setVolumeHeatEnv(new HeatEnvironment()); + org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule(); + vfModule.setVolumeHeatTemplate(new HeatTemplate()); + vfModuleCustomization.setVfModule(vfModule); + when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("9a6d01fd-19a7-490a-9800-460830a12e0b")) + .thenReturn(vfModuleCustomization); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "UnassignVFModuleBB", + "AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB", "ChangeModelVnfBB", + "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleKeepVolumeGroupReplaceRetainAssignmentsTest() throws Exception { + String gAction = "replaceInstanceRetainAssignments"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("volumeGroupId"); + doReturn(Optional.of(volumeGroup)).when(bbSetupUtils) + .getRelatedVolumeGroupFromVfModule("b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", "1234"); + + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + vfModuleCustomization.setVolumeHeatEnv(new HeatEnvironment()); + org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule(); + vfModule.setVolumeHeatTemplate(new HeatTemplate()); + vfModuleCustomization.setVfModule(vfModule); + when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("9a6d01fd-19a7-490a-9800-460830a12e0b")) + .thenReturn(vfModuleCustomization); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceRetainAssignmentsVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "ChangeModelVfModuleBB", + "CreateVfModuleBB", "ActivateVfModuleBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleNoVolumeGroupToVolumeGroupReplaceTest() throws Exception { + String gAction = "replaceInstance"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + vfModuleCustomization.setVolumeHeatEnv(new HeatEnvironment()); + org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule(); + vfModule.setVolumeHeatTemplate(new HeatTemplate()); + vfModuleCustomization.setVfModule(vfModule); + when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("9a6d01fd-19a7-490a-9800-460830a12e0b")) + .thenReturn(vfModuleCustomization); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "UnassignVFModuleBB", + "AssignVolumeGroupBB", "AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB", + "CreateVolumeGroupBB", "ActivateVolumeGroupBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleNoVolumeGroupToVolumeGroupReplaceRetainAssignmentsTest() + throws Exception { + String gAction = "replaceInstanceRetainAssignments"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + vfModuleCustomization.setVolumeHeatEnv(new HeatEnvironment()); + org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule(); + vfModule.setVolumeHeatTemplate(new HeatTemplate()); + vfModuleCustomization.setVfModule(vfModule); + when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("9a6d01fd-19a7-490a-9800-460830a12e0b")) + .thenReturn(vfModuleCustomization); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceRetainAssignmentsVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "AssignVolumeGroupBB", + "ChangeModelVfModuleBB", "CreateVolumeGroupBB", "ActivateVolumeGroupBB", "CreateVfModuleBB", + "ActivateVfModuleBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleRebuildVolumeGroupReplaceTest() throws Exception { + String gAction = "replaceInstance"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = new String( + Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleReplaceRebuildVolumeGroups.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("volumeGroupId"); + doReturn(Optional.of(volumeGroup)).when(bbSetupUtils) + .getRelatedVolumeGroupFromVfModule("b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", "1234"); + + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + vfModuleCustomization.setVolumeHeatEnv(new HeatEnvironment()); + org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule(); + vfModule.setVolumeHeatTemplate(new HeatTemplate()); + vfModuleCustomization.setVfModule(vfModule); + when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("9a6d01fd-19a7-490a-9800-460830a12e0b")) + .thenReturn(vfModuleCustomization); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "DeactivateVolumeGroupBB", + "DeleteVolumeGroupBB", "UnassignVFModuleBB", "UnassignVolumeGroupBB", "AssignVolumeGroupBB", + "AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB", "CreateVolumeGroupBB", + "ActivateVolumeGroupBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleRebuildVolumeGroupReplaceRetainAssignmentsTest() throws Exception { + String gAction = "replaceInstanceRetainAssignments"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = new String( + Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleReplaceRebuildVolumeGroups.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("volumeGroupId"); + doReturn(Optional.of(volumeGroup)).when(bbSetupUtils) + .getRelatedVolumeGroupFromVfModule("b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", "1234"); + + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + vfModuleCustomization.setVolumeHeatEnv(new HeatEnvironment()); + org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule(); + vfModule.setVolumeHeatTemplate(new HeatTemplate()); + vfModuleCustomization.setVfModule(vfModule); + when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("9a6d01fd-19a7-490a-9800-460830a12e0b")) + .thenReturn(vfModuleCustomization); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceRetainAssignmentsVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "DeactivateVolumeGroupBB", + "DeleteVolumeGroupBB", "UnassignVolumeGroupBB", "AssignVolumeGroupBB", "ChangeModelVfModuleBB", + "CreateVolumeGroupBB", "ActivateVolumeGroupBB", "CreateVfModuleBB", "ActivateVfModuleBB", + "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + + @Test public void selectExecutionListALaCarteVfModuleFabricDeleteTest() throws Exception { String gAction = "deleteInstance"; String resource = "VfModule"; @@ -1149,6 +1516,56 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test + public void getConfigBuildingBlocksNoVfModuleFabricDeleteTest() throws Exception { + String gAction = "deleteInstance"; + ObjectMapper mapper = new ObjectMapper(); + WorkflowType resourceType = WorkflowType.VFMODULE; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("vnfId", "1234"); + execution.setVariable("vfModuleId", "vfModuleId1234"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules"); + ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class); + RequestDetails requestDetails = sIRequest.getRequestDetails(); + String requestAction = "deleteInstance"; + String requestId = "9c944122-d161-4280-8594-48c06a9d96d5"; + boolean aLaCarte = true; + String apiVersion = "7"; + String vnfType = "vnfType"; + String key = "00d15ebb-c80e-43c1-80f0-90c40dde70b0"; + String resourceId = "d1d35800-783d-42d3-82f6-d654c5054a6e"; + Resource resourceKey = new Resource(resourceType, key, aLaCarte); + WorkflowResourceIds workflowResourceIds = SPY_workflowAction.populateResourceIdsFromApiHandler(execution); + + thrown.expect(AAIEntityNotFoundException.class); + thrown.expectMessage(containsString( + "No matching VfModule is found in Generic-Vnf in AAI for vnfId: 1234 and vfModuleId : vfModuleId1234")); + + List<OrchestrationFlow> orchFlows = createFlowList("DeactivateVfModuleBB", "DeleteVfModuleBB", + "UnassignVfModuleBB", "DeactivateFabricConfigurationBB", "UnassignFabricConfigurationBB"); + + ConfigBuildingBlocksDataObject dataObj = new ConfigBuildingBlocksDataObject().setsIRequest(sIRequest) + .setOrchFlows(orchFlows).setRequestId(requestId).setResourceKey(resourceKey).setApiVersion(apiVersion) + .setResourceId(resourceId).setRequestAction(requestAction).setaLaCarte(aLaCarte).setVnfType(vnfType) + .setWorkflowResourceIds(workflowResourceIds).setRequestDetails(requestDetails).setExecution(execution); + + org.onap.aai.domain.yang.GenericVnf vnf = new org.onap.aai.domain.yang.GenericVnf(); + vnf.setVnfId("vnf0"); + vnf.setModelCustomizationId("modelCustomizationId"); + when(bbSetupUtils.getAAIGenericVnf(anyObject())).thenReturn(vnf); + + org.onap.aai.domain.yang.VfModule vfModule = new org.onap.aai.domain.yang.VfModule(); + vfModule.setModelCustomizationId("modelCustomizationId"); + when(bbSetupUtils.getAAIVfModule(anyObject(), anyObject())).thenReturn(null); + + SPY_workflowAction.getConfigBuildingBlocks(dataObj); + } + + @Test public void selectExecutionListALaCarteVfModuleNoFabricDeleteTest() throws Exception { String gAction = "deleteInstance"; String resource = "VfModule"; @@ -1544,7 +1961,7 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateVnfResourceIdInAAITest() throws Exception { + public void validateResourceIdInAAIVnfTest() throws Exception { RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); @@ -1577,7 +1994,7 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateVnfResourceNameInAAITest() throws Exception { + public void validateResourceIdInAAIVnfNotGloballyUniqueTest() throws Exception { RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); @@ -1599,7 +2016,7 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateNetworkResourceIdInAAITest() throws Exception { + public void validateResourceIdInAAINetworkTest() throws Exception { RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); @@ -1659,7 +2076,7 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateVfModuleResourceIdInAAITest() throws Exception { + public void validateResourceIdInAAIVfModuleTest() throws Exception { RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); @@ -1702,11 +2119,28 @@ public class WorkflowActionTest extends BaseTaskTest { "vfModule with name (vFModName222), same parent and different customization id (1234567) already exists. The name must be unique.")); workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VFMODULE, "vFModName222", reqDetails, workflowResourceIds); + } + + @Test + public void validateResourceIdInAAIVfModuleNotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("id111"); + + GenericVnf vnf1 = new GenericVnf(); + workflowResourceIds.setVnfId("id111"); + when(bbSetupUtils.getAAIGenericVnf("id111")).thenReturn(vnf1); + when(bbSetupUtils.existsAAIVfModuleGloballyByName("vFModName333")).thenReturn(true); + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage( + containsString("vfModule with name vFModName333 already exists. The name must be unique.")); + workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VFMODULE, "vFModName333", reqDetails, + workflowResourceIds); } @Test - public void validateVolumeGroupResourceIdInAAITest() throws Exception { + public void validateResourceIdInAAIVolumeGroupTest() throws Exception { RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); @@ -1725,6 +2159,7 @@ public class WorkflowActionTest extends BaseTaskTest { VolumeGroup volumeGroup = new VolumeGroup(); volumeGroup.setVolumeGroupId("id123"); volumeGroup.setVolumeGroupName("name123"); + volumeGroup.setVfModuleModelCustomizationId("1234567"); workflowResourceIds.setVnfId("id123"); Optional<VolumeGroup> opVolumeGroup = Optional.of(volumeGroup); @@ -1747,7 +2182,25 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateConfigurationResourceIdInAAITest() throws Exception { + public void validatesourceIdInAAIVolumeGroupNotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("id123"); + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId("id123"); + when(bbSetupUtils.getAAIGenericVnf("id123")).thenReturn(vnf); + when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("id123", "testVolumeGroup")).thenReturn(Optional.empty()); + + when(bbSetupUtils.existsAAIVolumeGroupGloballyByName("testVolumeGroup")).thenReturn(true); + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage( + containsString("volumeGroup with name testVolumeGroup already exists. The name must be unique.")); + workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VOLUMEGROUP, "testVolumeGroup", + reqDetails, workflowResourceIds); + } + + @Test + public void validateResourceIdInAAIConfigurationTest() throws Exception { RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); @@ -1789,7 +2242,23 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateServiceInstanceResourceIdInAAITest() throws Exception { + public void validateResourceIdInAAIConfigurationNotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + when(bbSetupUtils.getRelatedConfigurationByNameFromServiceInstance("siId123", "testConfig")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAIConfigurationGloballyByName("testConfig")).thenReturn(true); + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage( + containsString("configuration with name testConfig already exists. The name must be unique.")); + workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.CONFIGURATION, "testConfig", reqDetails, + workflowResourceIds); + } + + @Test + public void validateResourceIdInAAISITest() throws Exception { WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); @@ -1831,7 +2300,7 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateServiceInstanceResourceIdInAAIMultipleTest() throws Exception { + public void validateResourceIdInAAIMultipleSITest() throws Exception { WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); @@ -1862,7 +2331,7 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateServiceInstanceResourceIdInAAIExistsTest() throws Exception { + public void validateResourceIdInAAISIExistsTest() throws Exception { WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); @@ -1893,6 +2362,490 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test + public void validateServiceResourceIdInAAINoDupTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + reqDetails.getModelInfo().setModelVersionId("1234567"); + when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "siName123")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.getAAIServiceInstancesGloballyByName("siName123")).thenReturn(null); + String id = workflowAction.validateServiceResourceIdInAAI("generatedId123", "siName123", reqDetails); + assertEquals("generatedId123", id); + } + + @Test + public void validateServiceResourceIdInAAISameModelVersionId() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + reqDetails.getModelInfo().setModelVersionId("1234567"); + + ServiceInstance si = new ServiceInstance(); + si.setServiceInstanceId("siId123"); + si.setModelVersionId("1234567"); + Optional<ServiceInstance> siOp = Optional.of(si); + + when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "siName123")).thenReturn(siOp); + String id = workflowAction.validateServiceResourceIdInAAI("generatedId123", "siName123", reqDetails); + assertEquals("siId123", id); + } + + @Test + public void validateServiceResourceIdInAAIDifferentModelVersionId() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + reqDetails.getModelInfo().setModelVersionId("1234567"); + + ServiceInstance si = new ServiceInstance(); + si.setServiceInstanceId("siId123"); + si.setModelVersionId("9999999"); + ServiceInstances serviceInstances = new ServiceInstances(); + serviceInstances.getServiceInstance().add(si); + Optional<ServiceInstance> siOp = Optional.of(si); + + when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "siName123")).thenReturn(siOp); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "serviceInstance with name (siName123) and different version id (1234567) already exists. The name must be unique.")); + + String id = workflowAction.validateServiceResourceIdInAAI("generatedId123", "siName123", reqDetails); + assertEquals("siId123", id); + } + + @Test + public void validateServiceResourceIdInAAIDuplicateNameTest() throws Exception { + + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + reqDetails.getModelInfo().setModelVersionId("1234567"); + + ServiceInstance si = new ServiceInstance(); + si.setServiceInstanceId("siId123"); + si.setModelVersionId("1234567"); + + ServiceInstances serviceInstances = new ServiceInstances(); + serviceInstances.getServiceInstance().add(si); + + when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "siName")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.getAAIServiceInstancesGloballyByName("siName")).thenReturn(serviceInstances); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "serviceInstance with name (siName) and global-customer-id (null), service-type (null), model-version-id (1234567) already exists. The name must be unique.")); + + workflowAction.validateServiceResourceIdInAAI("generatedId123", "siName", reqDetails); + } + + @Test + public void validateServiceResourceIdInAAIDuplicateNameMultipleTest() throws Exception { + + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + reqDetails.getModelInfo().setModelVersionId("1234567"); + + ServiceInstance si = new ServiceInstance(); + si.setServiceInstanceId("siId123"); + si.setModelVersionId("1234567"); + + ServiceInstance si2 = new ServiceInstance(); + si2.setServiceInstanceId("siId222"); + si2.setModelVersionId("22222"); + si2.setServiceInstanceName("siName222"); + + ServiceInstances serviceInstances = new ServiceInstances(); + serviceInstances.getServiceInstance().add(si); + serviceInstances.getServiceInstance().add(si2); + + when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "siName")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.getAAIServiceInstancesGloballyByName("siName")).thenReturn(serviceInstances); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "serviceInstance with name (siName) and multiple combination of model-version-id + service-type + global-customer-id already exists. The name must be unique.")); + + workflowAction.validateServiceResourceIdInAAI("generatedId123", "siName", reqDetails); + } + + @Test + public void validateNetworkResourceIdInAAITest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + when(bbSetupUtils.getRelatedNetworkByNameFromServiceInstance("siId123", "name123")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAINetworksGloballyByName("name123")).thenReturn(false); + + String id = workflowAction.validateNetworkResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("generatedId123", id); + } + + @Test + public void validateNetworkResourceIdInAAISameModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + L3Network network = new L3Network(); + network.setNetworkId("id123"); + network.setNetworkName("name123"); + network.setModelCustomizationId("1234567"); + Optional<L3Network> opNetwork = Optional.of(network); + + when(bbSetupUtils.getRelatedNetworkByNameFromServiceInstance("siId123", "name123")).thenReturn(opNetwork); + + String id = workflowAction.validateNetworkResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("id123", id); + } + + @Test + public void validateNetworkResourceIdInAAIDuplicateNameTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + L3Network network = new L3Network(); + network.setNetworkId("id123"); + network.setNetworkName("name123"); + network.setModelCustomizationId("9999999"); + Optional<L3Network> opNetwork = Optional.of(network); + + when(bbSetupUtils.getRelatedNetworkByNameFromServiceInstance("siId123", "name123")).thenReturn(opNetwork); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "l3Network with name (name123), same parent and different customization id (9999999) already exists. The name must be unique.")); + + workflowAction.validateNetworkResourceIdInAAI("generatedId123", "name123", reqDetails, workflowResourceIds); + } + + @Test + public void validateNetworkResourceIdInAAINotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + when(bbSetupUtils.getRelatedNetworkByNameFromServiceInstance("siId123", "name123")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAINetworksGloballyByName("name123")).thenReturn(true); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "l3Network with name (name123) id (siId123) and different parent relationship already exists. The name must be unique.")); + + workflowAction.validateNetworkResourceIdInAAI("generatedId123", "name123", reqDetails, workflowResourceIds); + } + + @Test + public void validateVnfResourceIdInAAITest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + when(bbSetupUtils.getRelatedVnfByNameFromServiceInstance("siId123", "vnfName123")).thenReturn(Optional.empty()); + String id = workflowAction.validateVnfResourceIdInAAI("generatedId123", "vnfName123", reqDetails, + workflowResourceIds); + assertEquals("generatedId123", id); + } + + @Test + public void validateVnfResourceIdInAAISameModelCustomizationIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId("id123"); + vnf.setVnfName("vnfName123"); + vnf.setModelCustomizationId("1234567"); + Optional<GenericVnf> opVnf = Optional.of(vnf); + + when(bbSetupUtils.getRelatedVnfByNameFromServiceInstance("siId123", "vnfName123")).thenReturn(opVnf); + String id = workflowAction.validateVnfResourceIdInAAI("generatedId123", "vnfName123", reqDetails, + workflowResourceIds); + assertEquals("id123", id); + } + + @Test + public void validateVnfResourceIdInAAIDiffModelCustomizationIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId("id123"); + vnf.setVnfName("vnfName123"); + vnf.setModelCustomizationId("9999999"); + Optional<GenericVnf> opVnf = Optional.of(vnf); + + when(bbSetupUtils.getRelatedVnfByNameFromServiceInstance("siId123", "vnfName123")).thenReturn(opVnf); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "generic-vnf with name (vnfName123), same parent and different customization id (9999999) already exists. The name must be unique.")); + + workflowAction.validateVnfResourceIdInAAI("generatedId123", "vnfName123", reqDetails, workflowResourceIds); + } + + @Test + public void validateVnfResourceIdInAAINotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId("id123"); + vnf.setVnfName("vnfName123"); + GenericVnfs genericVnfs = new GenericVnfs(); + genericVnfs.getGenericVnf().add(vnf); + + when(bbSetupUtils.getRelatedVnfByNameFromServiceInstance("siId123", "vnfName123")).thenReturn(Optional.empty()); + when(bbSetupUtils.getAAIVnfsGloballyByName("vnfName123")).thenReturn(genericVnfs); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "generic-vnf with name (vnfName123) id (id123) and different parent relationship already exists. The name must be unique.")); + + workflowAction.validateVnfResourceIdInAAI("generatedId123", "vnfName123", reqDetails, workflowResourceIds); + } + + @Test + public void validateVfModuleResourceIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("vnfId123"); + + when(bbSetupUtils.getAAIGenericVnf("id123")).thenReturn(null); + when(bbSetupUtils.existsAAIVfModuleGloballyByName("name123")).thenReturn(false); + + String id = workflowAction.validateVfModuleResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("generatedId123", id); + } + + @Test + public void validateVfModuleResourceIdSameModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("vnfId123"); + + VfModules vfModules = new VfModules(); + VfModule vfModule = new VfModule(); + vfModule.setVfModuleId("id123"); + vfModule.setVfModuleName("name123"); + vfModule.setModelCustomizationId("1234567"); + vfModules.getVfModule().add(vfModule); + + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId("id123"); + vnf.setVnfName("vnfName123"); + vnf.setVfModules(vfModules); + + when(bbSetupUtils.getAAIGenericVnf("vnfId123")).thenReturn(vnf); + + String id = workflowAction.validateVfModuleResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("id123", id); + } + + @Test + public void validateVfModuleResourceIdDifferentModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("vnfId123"); + + VfModules vfModules = new VfModules(); + VfModule vfModule = new VfModule(); + vfModule.setVfModuleId("id123"); + vfModule.setVfModuleName("name123"); + vfModule.setModelCustomizationId("9999999"); + vfModules.getVfModule().add(vfModule); + + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId("id123"); + vnf.setVnfName("vnfName123"); + vnf.setVfModules(vfModules); + + when(bbSetupUtils.getAAIGenericVnf("vnfId123")).thenReturn(vnf); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "vfModule with name (name123), same parent and different customization id (1234567) already exists. The name must be unique.")); + + workflowAction.validateVfModuleResourceIdInAAI("generatedId123", "name123", reqDetails, workflowResourceIds); + + } + + @Test + public void validateVfModuleResourceIdNotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("vnfId123"); + + when(bbSetupUtils.getAAIGenericVnf("id123")).thenReturn(null); + when(bbSetupUtils.existsAAIVfModuleGloballyByName("name123")).thenReturn(true); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException + .expectMessage(containsString("vfModule with name name123 already exists. The name must be unique.")); + + workflowAction.validateVfModuleResourceIdInAAI("generatedId123", "name123", reqDetails, workflowResourceIds); + } + + @Test + public void validateVolumeGroupResourceIdInAAITest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("vnfId123"); + + when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("id123", "name123")).thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAIVolumeGroupGloballyByName("name123")).thenReturn(false); + + String id = workflowAction.validateVolumeGroupResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("generatedId123", id); + } + + @Test + public void validateVolumeGroupResourceIdInAAISameModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + workflowResourceIds.setVnfId("vnfId123"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("id123"); + volumeGroup.setVolumeGroupName("name123"); + volumeGroup.setVfModuleModelCustomizationId("1234567"); + + Optional<VolumeGroup> opVolumeGroup = Optional.of(volumeGroup); + + when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("vnfId123", "name123")).thenReturn(opVolumeGroup); + String id = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VOLUMEGROUP, "name123", + reqDetails, workflowResourceIds); + + assertEquals("id123", id); + } + + @Test + public void validateVolumeGroupResourceIdInAAIDifferentModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + workflowResourceIds.setVnfId("vnfId123"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("id123"); + volumeGroup.setVolumeGroupName("name123"); + volumeGroup.setVfModuleModelCustomizationId("9999999"); + + Optional<VolumeGroup> opVolumeGroup = Optional.of(volumeGroup); + + when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("vnfId123", "name123")).thenReturn(opVolumeGroup); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage( + containsString("volumeGroup with name name123 already exists. The name must be unique.")); + + workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VOLUMEGROUP, "name123", reqDetails, + workflowResourceIds); + } + + @Test + public void validateVolumeGroupResourceIdInAAINotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("vnfId123"); + + when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("vnfId123", "name123")).thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAIVolumeGroupGloballyByName("name123")).thenReturn(true); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage( + containsString("volumeGroup with name name123 already exists. The name must be unique.")); + + workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VOLUMEGROUP, "name123", reqDetails, + workflowResourceIds); + } + + @Test + public void validateConfigurationResourceIdInAAITest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + when(bbSetupUtils.getRelatedConfigurationByNameFromServiceInstance("siId123", "name123")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAIConfigurationGloballyByName("name123")).thenReturn(false); + + String id = workflowAction.validateConfigurationResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("generatedId123", id); + } + + @Test + public void validateConfigurationResourceIdInAAISameModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + org.onap.aai.domain.yang.Configuration configuration = new org.onap.aai.domain.yang.Configuration(); + configuration.setConfigurationId("id123"); + configuration.setConfigurationName("name123"); + configuration.setModelCustomizationId("1234567"); + Optional<org.onap.aai.domain.yang.Configuration> opConfiguration = Optional.of(configuration); + + when(bbSetupUtils.getRelatedConfigurationByNameFromServiceInstance("siId123", "name123")) + .thenReturn(opConfiguration); + when(bbSetupUtils.existsAAIConfigurationGloballyByName("name123")).thenReturn(false); + + String id = workflowAction.validateConfigurationResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("id123", id); + } + + @Test + public void validateConfigurationResourceIdInAAIDifferentModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + org.onap.aai.domain.yang.Configuration configuration = new org.onap.aai.domain.yang.Configuration(); + configuration.setConfigurationId("id123"); + configuration.setConfigurationName("name123"); + configuration.setModelCustomizationId("9999999"); + Optional<org.onap.aai.domain.yang.Configuration> opConfiguration = Optional.of(configuration); + + when(bbSetupUtils.getRelatedConfigurationByNameFromServiceInstance("siId123", "name123")) + .thenReturn(opConfiguration); + when(bbSetupUtils.existsAAIConfigurationGloballyByName("name123")).thenReturn(false); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "configuration with name (name123), same parent and different customization id (id123) already exists. The name must be unique.")); + + workflowAction.validateConfigurationResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + } + + @Test + public void validateConfigurationResourceIdInAAINotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + when(bbSetupUtils.getRelatedConfigurationByNameFromServiceInstance("siId123", "name123")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAIConfigurationGloballyByName("name123")).thenReturn(true); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage( + containsString("configuration with name name123 already exists. The name must be unique.")); + + workflowAction.validateConfigurationResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + } + + @Test public void handleRuntimeExceptionTest() { execution.setVariable("BPMN_javaExpMsg", "test runtime error message"); execution.setVariable("testProcessKey", "testProcessKeyValue"); diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/VfModuleReplaceRebuildVolumeGroups.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/VfModuleReplaceRebuildVolumeGroups.json new file mode 100644 index 0000000000..aa2462f371 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/VfModuleReplaceRebuildVolumeGroups.json @@ -0,0 +1,66 @@ +{ + "requestDetails": { + "modelInfo": { + "modelCustomizationName": "model-cust-name", + "modelInvariantId": "db86e4a6-c027-452e-a559-3a23b3128367", + "modelType": "vfModule", + "modelName": "test-model-name", + "modelVersion": "1", + "modelCustomizationUuid": "9a6d01fd-19a7-490a-9800-460830a12e0b", + "modelVersionId": "14c8f313-fb0f-4cf6-8caf-c7cce8137b60", + "modelCustomizationId": "9a6d01fd-19a7-490a-9800-460830a12e0b", + "modelUuid": "14c8f313-fb0f-4cf6-8caf-c7cce8137b60", + "modelInvariantUuid": "db86e4a6-c027-452e-a559-3a23b3128367", + "modelInstanceName": "test-model-instance-name" + }, + "requestInfo": { + "source": "VID", + "instanceName": "instanceName", + "suppressRollback": false, + "requestorId": "user" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f647e3ef-6d2e-4cd3-bff4-8df4634208de", + "modelInfo": { + "modelInvariantId": "86adb376-5303-441a-b50e-96c0cd643b0f", + "modelType": "service", + "modelName": "model-name", + "modelVersion": "1.0", + "modelVersionId": "599e21ed-803d-4d1f-83df-20005339b83f", + "modelUuid": "599e21ed-803d-4d1f-83df-20005339b83f", + "modelInvariantUuid": "86adb376-5303-441a-b50e-96c0cd643b0f" + } + } + }, + { + "relatedInstance": { + "instanceId": "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", + "modelInfo": { + "modelCustomizationName": "modle-cust-name", + "modelInvariantId": "5cca9285-4ed4-4e11-a609-921ed3344811", + "modelType": "vnf", + "modelName": "modle-name", + "modelVersion": "1.0", + "modelCustomizationUuid": "fc25201d-36d6-43a3-8d39-fdae88e526ae", + "modelVersionId": "7cae703a-b20d-481a-863a-b862236c00f7", + "modelCustomizationId": "fc25201d-36d6-43a3-8d39-fdae88e526ae", + "modelUuid": "7cae703a-b20d-481a-863a-b862236c00f7", + "modelInvariantUuid": "5cca9285-4ed4-4e11-a609-921ed3344811", + "modelInstanceName": "model-inst-name" + } + } + } + ], + "cloudConfiguration": { + "tenantId": "872f331350c54e59991a8de2cbffb40c", + "cloudOwner": "my-custom-cloud-owner", + "lcpCloudRegionId": "cloud-region" + }, + "requestParameters": { + "usePreload": true, + "rebuildVolumeGroups": true + } + } +}
\ No newline at end of file diff --git a/common/pom.xml b/common/pom.xml index 3690d7b5a1..aa1ac654da 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -58,7 +58,7 @@ <dependency> <groupId>org.onap.aai.schema-service</groupId> <artifactId>aai-schema</artifactId> - <version>1.0.5</version> + <version>1.6.1-SNAPSHOT</version> </dependency> <dependency> <groupId>org.modelmapper</groupId> diff --git a/common/src/main/java/org/onap/so/client/aai/AAIVersion.java b/common/src/main/java/org/onap/so/client/aai/AAIVersion.java index 3a59b2b337..4f06b787f7 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIVersion.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIVersion.java @@ -23,7 +23,7 @@ package org.onap.so.client.aai; import org.onap.so.client.graphinventory.GraphInventoryVersion; public enum AAIVersion implements GraphInventoryVersion { - V13("v13"), V14("v14"), V15("v15"), V16("v16"), V17("v17"); + V13("v13"), V14("v14"), V15("v15"), V16("v16"), V17("v17"), V18("v18"), V19("v19"); public static final AAIVersion LATEST = AAIVersion.values()[AAIVersion.values().length - 1]; private final String value; diff --git a/common/src/main/java/org/onap/so/constants/OrchestrationRequestFormat.java b/common/src/main/java/org/onap/so/constants/OrchestrationRequestFormat.java index ccfd2f4de6..641bbb28c7 100644 --- a/common/src/main/java/org/onap/so/constants/OrchestrationRequestFormat.java +++ b/common/src/main/java/org/onap/so/constants/OrchestrationRequestFormat.java @@ -21,5 +21,5 @@ package org.onap.so.constants; public enum OrchestrationRequestFormat { - DETAIL, STATUSDETAIL + DETAIL, STATUSDETAIL, SIMPLE } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java index 61192c3147..250c5df5ce 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java @@ -55,6 +55,8 @@ public class RequestInfo implements Serializable { protected boolean suppressRollback; @JsonProperty("requestorId") protected String requestorId; + @JsonProperty("applicationId") + protected String applicationId; /** * Gets the value of the callbackUrl property. @@ -201,12 +203,21 @@ public class RequestInfo implements Serializable { this.requestorId = requestorId; } + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } + @Override public String toString() { return "RequestInfo [billingAccountNumber=" + billingAccountNumber + ", callbackUrl=" + callbackUrl + ", correlator=" + correlator + ", orderNumber=" + orderNumber + ", productFamilyId=" + productFamilyId + ", orderVersion=" + orderVersion + ", source=" + source + ", instanceName=" + instanceName - + ", suppressRollback=" + suppressRollback + ", requestorId=" + requestorId + "]"; + + ", suppressRollback=" + suppressRollback + ", requestorId=" + requestorId + ", applicationId=" + + applicationId + "]"; } diff --git a/common/src/main/java/org/onap/so/utils/Components.java b/common/src/main/java/org/onap/so/utils/Components.java index d8d703affc..5af8c5aa56 100644 --- a/common/src/main/java/org/onap/so/utils/Components.java +++ b/common/src/main/java/org/onap/so/utils/Components.java @@ -6,10 +6,11 @@ import org.onap.logging.filter.base.ONAPComponents; import org.onap.logging.filter.base.ONAPComponentsList; public enum Components implements ONAPComponentsList { - OPENSTACK, UNKNOWN, ASDC_CONTROLLER, APIH; + OPENSTACK, UNKNOWN, ASDC_CONTROLLER, APIH, SDNC_ADAPTER; + public static Set<Components> getSOInternalComponents() { - return EnumSet.of(ASDC_CONTROLLER, APIH); + return EnumSet.of(ASDC_CONTROLLER, APIH, SDNC_ADAPTER); } @Override diff --git a/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java b/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java index f6ac449057..d1f509f476 100644 --- a/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java +++ b/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java @@ -83,6 +83,7 @@ public class SOAPLoggingInInterceptor extends AbstractSoapInterceptor { String invocationId = getValueOrDefault(headers, ONAPLogConstants.Headers.INVOCATION_ID.toLowerCase(), UUID.randomUUID().toString()); MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); + MDC.put(ONAPLogConstants.MDCs.SERVER_INVOCATION_ID, invocationId); } private void setRequestId(Map<String, List<String>> headers) { diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java index 0f51341a61..4517811494 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java @@ -357,5 +357,4 @@ public class CamundaVIDRequest { public void setGenerateIds(CamundaBooleanInput generateIds) { this.generateIds = generateIds; } - } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientParameter.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientParameter.java index e098ea4354..3cf3907424 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientParameter.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientParameter.java @@ -302,6 +302,4 @@ public class RequestClientParameter { } } - - } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java index fb7ab3a61e..e9f17c42d0 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java @@ -61,7 +61,8 @@ public class CamundaRequestHandler { if (context.getRetryCount() == 0) { logger.info("Querying Camunda for process-instance history for requestId: {}", requestId); } else { - logger.info("Retry: Querying Camunda for process-instance history for requestId: {}", + logger.info( + "Retry: Querying Camunda for process-instance history for retryCount: {} and requestId: {}", context.getRetryCount(), requestId); } return restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java index 6ccef65e46..ae68cc6032 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java @@ -44,6 +44,7 @@ import javax.ws.rs.core.UriInfo; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.EnumUtils; import org.apache.http.HttpStatus; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.exceptions.ApiException; @@ -70,6 +71,7 @@ import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.onap.so.utils.UUIDChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; @@ -130,31 +132,36 @@ public class OrchestrationRequests { infraActiveRequest = infraActiveRequestLookup(requestId); - try { - requestProcessingData = requestsDbClient.getExternalRequestProcessingDataBySoRequestId(requestId); - } catch (Exception e) { - logger.error("Exception occurred while communicating with RequestDb during requestProcessingData lookup ", - e); - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build(); + if (isRequestProcessingDataRequired(format)) { + try { + requestProcessingData = requestsDbClient.getExternalRequestProcessingDataBySoRequestId(requestId); + } catch (Exception e) { + logger.error( + "Exception occurred while communicating with RequestDb during requestProcessingData lookup ", + e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError) + .build(); - ValidateException validateException = new ValidateException.Builder( - "Exception occurred while communicating with RequestDb during requestProcessingData lookup", - HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) - .errorInfo(errorLoggerInfo).build(); + ValidateException validateException = new ValidateException.Builder( + "Exception occurred while communicating with RequestDb during requestProcessingData lookup", + HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) + .errorInfo(errorLoggerInfo).build(); - throw validateException; + throw validateException; + } } Request request = mapInfraActiveRequestToRequest(infraActiveRequest, includeCloudRequest, format); - if (!requestProcessingData.isEmpty()) { + if (null != requestProcessingData && !requestProcessingData.isEmpty()) { request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); } request.setRequestId(requestId); orchestrationResponse.setRequest(request); - return builder.buildResponse(HttpStatus.SC_OK, requestId, orchestrationResponse, apiVersion); + return builder.buildResponse(HttpStatus.SC_OK, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID), orchestrationResponse, + apiVersion); } @GET @@ -196,21 +203,26 @@ public class OrchestrationRequests { orchestrationList = new GetOrchestrationListResponse(); List<RequestList> requestLists = new ArrayList<>(); + for (InfraActiveRequests infraActive : activeRequests) { - List<RequestProcessingData> requestProcessingData = - requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId()); RequestList requestList = new RequestList(); Request request = mapInfraActiveRequestToRequest(infraActive, includeCloudRequest, format); - if (!requestProcessingData.isEmpty()) { - request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); + if (isRequestProcessingDataRequired(format)) { + List<RequestProcessingData> requestProcessingData = + requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId()); + if (null != requestProcessingData && !requestProcessingData.isEmpty()) { + request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); + } } + requestList.setRequest(request); requestLists.add(requestList); } orchestrationList.setRequestList(requestLists); - return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion); + return builder.buildResponse(HttpStatus.SC_OK, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID), orchestrationList, + apiVersion); } @POST @@ -524,6 +536,14 @@ public class OrchestrationRequests { return addedRequestProcessingData; } + protected boolean isRequestProcessingDataRequired(String format) { + if (StringUtils.isNotEmpty(format) && format.equalsIgnoreCase(OrchestrationRequestFormat.SIMPLE.name())) { + return false; + } else { + return true; + } + } + protected InfraActiveRequests infraActiveRequestLookup(String requestId) throws ApiException { InfraActiveRequests infraActiveRequest = null; try { diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java index 8881a08ff3..99542f02ff 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java @@ -26,24 +26,13 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static com.shazam.shazamcrest.MatcherAssert.assertThat; -import static org.onap.logging.filter.base.Constants.HttpHeaders.ECOMP_REQUEST_ID; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.INVOCATION_ID; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.PARTNER_NAME; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_CODE; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.LOG_TIMESTAMP; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.SERVICE_NAME; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE; import static org.onap.logging.filter.base.Constants.HttpHeaders.CLIENT_ID; +import static org.onap.logging.filter.base.Constants.HttpHeaders.ECOMP_REQUEST_ID; import java.io.IOException; -import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; import org.junit.Test; -import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandlerinfra.tasksbeans.RequestDetails; import org.onap.so.apihandlerinfra.tasksbeans.RequestInfo; import org.onap.so.apihandlerinfra.tasksbeans.TaskRequestReference; @@ -59,7 +48,6 @@ import org.springframework.web.util.UriComponentsBuilder; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.http.Fault; -import ch.qos.logback.classic.spi.ILoggingEvent; public class ManualTasksTest extends BaseTest { @@ -108,34 +96,6 @@ public class ManualTasksTest extends BaseTest { // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); assertThat(realResponse, sameBeanAs(expectedResponse)); - - for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("UNKNOWN", mdc.get(PARTNER_NAME)); - assertEquals("tasks/v1/55/complete", mdc.get(SERVICE_NAME)); - assertEquals("INPROGRESS", mdc.get(RESPONSE_STATUS_CODE)); - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNotNull(mdc.get(LOG_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("202", mdc.get(RESPONSE_CODE)); - assertEquals("UNKNOWN", mdc.get(PARTNER_NAME)); - assertEquals("tasks/v1/55/complete", mdc.get(SERVICE_NAME)); - assertEquals("COMPLETE", mdc.get(RESPONSE_STATUS_CODE)); - assertNotNull(mdc.get(RESPONSE_DESCRIPTION)); - assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); - assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); - assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); - assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - } } @Test diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java index e64f689624..aa6a3836c1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java @@ -45,6 +45,7 @@ import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; @@ -64,7 +65,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -143,6 +143,7 @@ public class OrchestrationRequestsTest extends BaseTest { HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); + headers.set(ONAPLogConstants.Headers.REQUEST_ID, "1e45215d-b7b3-4c5a-9316-65bdddaf649f"); HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); UriComponentsBuilder builder = UriComponentsBuilder @@ -158,7 +159,41 @@ public class OrchestrationRequestsTest extends BaseTest { assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - assertEquals("00032ab7-1a18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0)); + assertEquals("1e45215d-b7b3-4c5a-9316-65bdddaf649f", response.getHeaders().get("X-TransactionID").get(0)); + assertNotNull(response.getBody().getRequest().getFinishTime()); + } + + @Test + public void getOrchestrationRequestSimpleTest() throws Exception { + setupTestGetOrchestrationRequest(); + // TEST VALID REQUEST + GetOrchestrationResponse testResponse = new GetOrchestrationResponse(); + + Request request = ORCHESTRATION_LIST.getRequestList().get(1).getRequest(); + request.setRequestProcessingData(null); + testResponse.setRequest(request); + + String testRequestId = request.getRequestId(); + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + headers.set(ONAPLogConstants.Headers.REQUEST_ID, "e5e3c007-9fe9-4a20-8691-bdd20e14504d"); + HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); + UriComponentsBuilder builder = UriComponentsBuilder + .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)) + .queryParam("format", "simple"); + + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("request.startTime") + .ignoring("request.finishTime").ignoring("request.requestStatus.timeStamp")); + assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); + assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); + assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); + assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); + assertEquals("e5e3c007-9fe9-4a20-8691-bdd20e14504d", response.getHeaders().get("X-TransactionID").get(0)); assertNotNull(response.getBody().getRequest().getFinishTime()); } @@ -230,6 +265,7 @@ public class OrchestrationRequestsTest extends BaseTest { HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); + headers.set(ONAPLogConstants.Headers.REQUEST_ID, "0321e28d-3dde-4b31-9b28-1e0f07231b93"); HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort( @@ -246,7 +282,7 @@ public class OrchestrationRequestsTest extends BaseTest { assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - assertEquals("00032ab7-3fb3-42e5-965d-8ea592502017", response.getHeaders().get("X-TransactionID").get(0)); + assertEquals("0321e28d-3dde-4b31-9b28-1e0f07231b93", response.getHeaders().get("X-TransactionID").get(0)); } @Test @@ -448,6 +484,7 @@ public class OrchestrationRequestsTest extends BaseTest { assertThat(actualProcessingData, sameBeanAs(expectedDataList)); } + public void setupTestGetOrchestrationRequest() throws Exception { // For testGetOrchestrationRequest wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-1a18-42e5-965d-8ea592502018")) diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java index 39308058b5..9f742784d4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java @@ -29,14 +29,13 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import static org.onap.logging.filter.base.Constants.HttpHeaders.CLIENT_ID; import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_REQUEST_ID; -import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; import static org.onap.logging.filter.base.Constants.HttpHeaders.TRANSACTION_ID; -import static org.onap.logging.filter.base.Constants.HttpHeaders.CLIENT_ID; +import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; @@ -81,7 +80,6 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.http.Fault; -import ch.qos.logback.classic.spi.ILoggingEvent; public class ServiceInstancesTest extends BaseTest { @@ -214,37 +212,6 @@ public class ServiceInstancesTest extends BaseTest { assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); - - - - for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("UNKNOWN", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances", - mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("202", mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertEquals("UNKNOWN", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances", - mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("COMPLETE", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION)); - assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); - assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); - assertEquals("5.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - } } @Test @@ -397,15 +364,6 @@ public class ServiceInstancesTest extends BaseTest { .withStatus(HttpStatus.SC_NOT_FOUND))); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value()); - - for (ILoggingEvent logEvent : TestAppender.events) { - if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.SOAuditLogContainerFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertEquals("32807a28-1a14-4b88-b7b3-2950918aa76d", mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get("PartnerName")); - } - } } @Test @@ -1419,7 +1377,7 @@ public class ServiceInstancesTest extends BaseTest { @Test public void replaceVfModuleInstanceNoCloudConfigurationTest() throws IOException { wireMockServer.stubFor( - get(urlPathEqualTo("/aai/v17/network/generic-vnfs/generic-vnf/ff305d54-75b4-431b-adb2-eb6b9e5ff000")) + get(urlPathEqualTo("/aai/v19/network/generic-vnfs/generic-vnf/ff305d54-75b4-431b-adb2-eb6b9e5ff000")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("infra/Vnf.json").withStatus(org.apache.http.HttpStatus.SC_OK))); wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) @@ -2645,15 +2603,6 @@ public class ServiceInstancesTest extends BaseTest { ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertEquals(response.getHeaders().get(TRANSACTION_ID).get(0), "32807a28-1a14-4b88-b7b3-2950918aa76d"); - - for (ILoggingEvent logEvent : TestAppender.events) { - if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertEquals("32807a28-1a14-4b88-b7b3-2950918aa76d", mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertEquals("VID", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - } - } } @Test diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java index cfb865c9e1..2e9576cf7c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java @@ -28,12 +28,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import java.io.File; import java.nio.file.Files; import java.util.List; -import java.util.Map; import javax.ws.rs.core.MediaType; import org.junit.BeforeClass; import org.junit.Rule; @@ -48,7 +45,6 @@ import org.onap.so.client.grm.beans.ServiceEndPointLookupRequest; import org.onap.so.client.grm.beans.ServiceEndPointRequest; import org.onap.so.client.grm.exceptions.GRMClientCallFailed; import org.slf4j.MDC; -import ch.qos.logback.classic.spi.ILoggingEvent; public class GRMClientTest extends BaseTest { @@ -79,36 +75,10 @@ public class GRMClientTest extends BaseTest { List<ServiceEndPoint> list = sel.getServiceEndPointList(); assertEquals(3, list.size()); - boolean foundInvoke = false; - boolean foundInvokeReturn = false; - for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOMetricLogClientFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("INVOKE")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("GRM", mdc.get("TargetEntity")); - assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - foundInvoke = true; - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOMetricLogClientFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("INVOKE-RETURN")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("200", mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertEquals("COMPLETED", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - foundInvokeReturn = true; - } - - if (!foundInvoke) - fail("INVOKE Marker not found"); - - if (!foundInvokeReturn) - fail("INVOKE RETURN Marker not found"); - wireMockServer.verify(postRequestedFor(urlEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")) .withHeader(ONAPLogConstants.Headers.INVOCATION_ID.toString(), matching(uuidRegex)) .withHeader(ONAPLogConstants.Headers.REQUEST_ID.toString(), matching(uuidRegex)) - .withHeader(ONAPLogConstants.Headers.PARTNER_NAME.toString(), equalTo("SO"))); - TestAppender.events.clear(); + .withHeader(ONAPLogConstants.Headers.PARTNER_NAME.toString(), equalTo("SO.APIH"))); } @Test diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceWorkflow.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceWorkflow.java new file mode 100644 index 0000000000..6e48938f19 --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceWorkflow.java @@ -0,0 +1,91 @@ +package org.onap.so.db.catalog.beans; + +import java.io.Serializable; +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import com.openpojo.business.annotation.BusinessKey; +import uk.co.blackpepper.bowman.annotation.LinkedResource; + +@Entity +@Table(name = "pnf_resource_to_workflow") +public class PnfResourceWorkflow implements Serializable { + + private static final long serialVersionUID = 4897166645148426088L; + + @Id + @Column(name = "ID", nullable = false, updatable = false) + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer ID; + + @BusinessKey + @Column(name = "PNF_RESOURCE_MODEL_UUID") + private String pnfResourceModelUUID; + + @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinColumn(name = "PNF_RESOURCE_MODEL_UUID", updatable = false, insertable = false) + private PnfResource pnfResource; + + @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinColumn(name = "WORKFLOW_ID") + private Workflow workflow; + + @Override + public String toString() { + return new ToStringBuilder(this).append("pnfResourceModelUUID", pnfResourceModelUUID).toString(); + } + + @Override + public boolean equals(final Object other) { + if (!(other instanceof PnfResourceWorkflow)) { + return false; + } + PnfResourceWorkflow castOther = (PnfResourceWorkflow) other; + return new EqualsBuilder().append(pnfResourceModelUUID, castOther.pnfResourceModelUUID).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(pnfResourceModelUUID).toHashCode(); + } + + public Integer getID() { + return ID; + } + + public String getPnfResourceModelUUID() { + return pnfResourceModelUUID; + } + + public void setPnfResourceModelUUID(String pnfResourceModelUUID) { + this.pnfResourceModelUUID = pnfResourceModelUUID; + } + + @LinkedResource + public PnfResource getPnfResource() { + return pnfResource; + } + + public void setPnfResource(PnfResource pnfResource) { + this.pnfResource = pnfResource; + } + + @LinkedResource + public Workflow getWorkflow() { + return workflow; + } + + public void setWorkflow(Workflow workflow) { + this.workflow = workflow; + } +} diff --git a/mso-catalog-db/src/test/resources/data.sql b/mso-catalog-db/src/test/resources/data.sql index eaad15ca57..e5963c183f 100644 --- a/mso-catalog-db/src/test/resources/data.sql +++ b/mso-catalog-db/src/test/resources/data.sql @@ -768,10 +768,15 @@ insert into pnf_resource_customization_to_service(service_model_uuid, resource_m insert into workflow(artifact_uuid, artifact_name, name, operation_name, version, description, body, resource_target, source) values ('5b0c4322-643d-4c9f-b184-4516049e99b1', 'testingWorkflow.bpmn', 'testingWorkflow', 'create', 1, 'Test Workflow', null, 'vnf', 'sdc'); +insert into workflow(artifact_uuid, artifact_name, name, operation_name, version, description, body, resource_target, source) values +('b2fd5627-55e4-4f4f-8064-9e6f443e9152','DummyPnfWorkflow','Dummy Pnf Workflow','DummyPnfWorkflow',1.0,'Dummy Pnf Workflow to test custom Pnf workflow',null,'pnf','native'); insert into vnf_resource_to_workflow(vnf_resource_model_uuid, workflow_id) values ('ff2ae348-214a-11e7-93ae-92361f002671', '1'); +Insert into pnf_resource_to_workflow (`PNF_RESOURCE_MODEL_UUID`,`WORKFLOW_ID`) values +("ff2ae348-214a-11e7-93ae-92361f002680", 2); + insert into activity_spec(name, description, version) values ('testActivity1', 'Test Activity 1', 1); diff --git a/mso-catalog-db/src/test/resources/schema.sql b/mso-catalog-db/src/test/resources/schema.sql index 573d391980..9037e431d4 100644 --- a/mso-catalog-db/src/test/resources/schema.sql +++ b/mso-catalog-db/src/test/resources/schema.sql @@ -1243,6 +1243,18 @@ CREATE TABLE IF NOT EXISTS `vnf_resource_to_workflow` ( CONSTRAINT `fk_vnf_resource_to_workflow__workflow1` FOREIGN KEY (`WORKFLOW_ID`) REFERENCES `workflow` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1; +CREATE TABLE IF NOT EXISTS `pnf_resource_to_workflow` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `PNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, + `WORKFLOW_ID` int(11) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE KEY `UK_pnf_resource_to_workflow` (`PNF_RESOURCE_MODEL_UUID`,`WORKFLOW_ID`), + KEY `fk_pnf_resource_to_workflow__workflow1_idx` (`WORKFLOW_ID`), + KEY `fk_pnf_resource_to_workflow__pnf_res_mod_uuid_idx` (`PNF_RESOURCE_MODEL_UUID`), + CONSTRAINT `fk_pnf_resource_to_workflow__pnf_resource1` FOREIGN KEY (`PNF_RESOURCE_MODEL_UUID`) REFERENCES `pnf_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_pnf_resource_to_workflow__workflow1` FOREIGN KEY (`WORKFLOW_ID`) REFERENCES `workflow` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + CREATE TABLE IF NOT EXISTS `activity_spec` ( `ID` INT(11) NOT NULL AUTO_INCREMENT, `NAME` VARCHAR(200) NOT NULL, @@ -630,17 +630,17 @@ <dependency> <groupId>org.onap.logging-analytics</groupId> <artifactId>logging-slf4j</artifactId> - <version>1.6.2-SNAPSHOT</version> + <version>1.6.3-SNAPSHOT</version> </dependency> <dependency> <groupId>org.onap.logging-analytics</groupId> <artifactId>logging-filter-base</artifactId> - <version>1.6.2-SNAPSHOT</version> + <version>1.6.3-SNAPSHOT</version> </dependency> <dependency> <groupId>org.onap.logging-analytics</groupId> <artifactId>logging-filter-spring</artifactId> - <version>1.6.2-SNAPSHOT</version> + <version>1.6.3-SNAPSHOT</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> diff --git a/so-simulator/src/main/java/org/onap/so/simulator/actions/aai/ProcessVnfc.java b/so-simulator/src/main/java/org/onap/so/simulator/actions/aai/ProcessVnfc.java index 1d90f7cffb..e061d2b79d 100644 --- a/so-simulator/src/main/java/org/onap/so/simulator/actions/aai/ProcessVnfc.java +++ b/so-simulator/src/main/java/org/onap/so/simulator/actions/aai/ProcessVnfc.java @@ -49,7 +49,7 @@ public class ProcessVnfc extends AbstractTestAction { aaiResourceClient.create(vnfcURI, vnfc); AAIResourceUri vfModuleURI = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, context.getVariable("vnfId"), context.getVariable("vfModuleId")); - AAIResourceUri pserverURI = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "rdm52r19c001"); + AAIResourceUri pserverURI = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "test"); AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, context.getVariable("cloudOwner"), context.getVariable("cloudRegion"), context.getVariable("tenant"), "d29f3151-592d-4011-9356-ad047794e236"); diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryResourcesByStackNameModuleReplaceVolume.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryResourcesByStackNameModuleReplaceVolume.java new file mode 100644 index 0000000000..5e4bb98926 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryResourcesByStackNameModuleReplaceVolume.java @@ -0,0 +1,25 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Query-Replace-Volume-ID-Name-Resources") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/replace_module_volume_id/resources", method = RequestMethod.GET) +public class QueryResourcesByStackNameModuleReplaceVolume extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("stackName", "replace_module_volume_id"); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("openstack/gr_api/GetStackResourcesMacro.json")); + + } +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdReplaceModuleVolume.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdReplaceModuleVolume.java new file mode 100644 index 0000000000..170c3105b3 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdReplaceModuleVolume.java @@ -0,0 +1,51 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.onap.so.simulator.actions.aai.DeleteVServers; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-Replace-VF-Module-Volume-Get") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/replace_module_volume_id/*") +public class QueryStackByIdReplaceModuleVolume extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + // Get to see if stack exists + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "replace_module_volume_id"); + scenario.variable("cloudOwner", "cloudOwner"); + scenario.variable("cloudRegion", "regionOne"); + scenario.variable("tenantId", "0422ffb57ba042c0800a29dc85ca70f8"); + scenario.variable("vServerId", "92272b67-d23f-42ca-87fa-7b06a9ec81f3"); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Initial Get from Openstack Adapter prior to deletion of the stack + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Delete of the stack + scenario.http().receive().delete(); + scenario.action(new DeleteVServers()); + scenario.http().send().response(HttpStatus.NO_CONTENT); + + // Final Get from Openstack Adapter after the deletion of the stack + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + } + +} diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetwork2.json b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetwork2.json index c66fecb8cd..725c896b8d 100644 --- a/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetwork2.json +++ b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetwork2.json @@ -43,10 +43,10 @@ "port_filter": false, "vlan": "181" }, - "binding:vnic_type": "direct", + "binding:vnic_type": "normal", "binding:vif_type": "hw_veb", "mac_address": "fa:16:3e:0c:29:94", "project_id": "872f331350c54e59991a8de2cbffb40c", "created_at": "2019-02-11T19:11:39Z" } -}
\ No newline at end of file +} diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetNovaServer.json b/so-simulator/src/main/resources/openstack/gr_api/GetNovaServer.json index 82158772e4..622bf8e3ef 100644 --- a/so-simulator/src/main/resources/openstack/gr_api/GetNovaServer.json +++ b/so-simulator/src/main/resources/openstack/gr_api/GetNovaServer.json @@ -62,7 +62,7 @@ "status": "ACTIVE", "updated": "2019-02-11T19:12:46Z", "hostId": "50197c55fc934e7b3947e17db762f0839320f94983df774d84991ad2", - "OS-EXT-SRV-ATTR:host": "rdm52r19c001", + "OS-EXT-SRV-ATTR:host": "test", "OS-SRV-USG:terminated_at": null, "key_name": null, "OS-EXT-SRV-ATTR:hypervisor_hostname": "test.com", @@ -72,4 +72,4 @@ "os-extended-volumes:volumes_attached": [], "config_drive": "True" } -}
\ No newline at end of file +} |