diff options
28 files changed, 282 insertions, 881 deletions
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/CinderClientImpl.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/CinderClientImpl.java index b0c2d9430a..71cdcf6078 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/CinderClientImpl.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/CinderClientImpl.java @@ -22,7 +22,6 @@ package org.onap.so.openstack.utils; import org.onap.so.cloud.authentication.KeystoneAuthHolder; -import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,7 +41,7 @@ public class CinderClientImpl extends MsoCommonUtils { /** * Gets the Cinder client. * - * @param cloudSite the cloud site + * @param cloudSiteId the cloud site * @param tenantId the tenant id * @return the glance client * @throws MsoException the mso exception @@ -62,15 +61,12 @@ public class CinderClientImpl extends MsoCommonUtils { * @param cloudSiteId the cloud site id * @param tenantId the tenant id * @param limit limits the number of records returned - * @param visibility visibility in the image in openstack * @param marker the last viewed record - * @param name the image names * @return the list of images in openstack - * @throws MsoCloudSiteNotFound the mso cloud site not found * @throws CinderClientException the glance client exception */ public Volumes queryVolumes(String cloudSiteId, String tenantId, int limit, String marker) - throws MsoCloudSiteNotFound, CinderClientException { + throws CinderClientException { try { Cinder cinderClient = getCinderClient(cloudSiteId, tenantId); // list is set to false, otherwise an invalid URL is appended @@ -78,22 +74,23 @@ public class CinderClientImpl extends MsoCommonUtils { cinderClient.volumes().list(false).queryParam("limit", limit).queryParam("marker", marker); return executeAndRecordOpenstackRequest(request, false); } catch (MsoException e) { - logger.error("Error building Cinder Client", e); - throw new CinderClientException("Error building Cinder Client", e); + String errorMsg = "Error building Cinder Client"; + logger.error(errorMsg, e); + throw new CinderClientException(errorMsg, e); } } - public Volume queryVolume(String cloudSiteId, String tenantId, String volumeId) - throws MsoCloudSiteNotFound, CinderClientException { + public Volume queryVolume(String cloudSiteId, String tenantId, String volumeId) throws CinderClientException { try { Cinder cinderClient = getCinderClient(cloudSiteId, tenantId); // list is set to false, otherwise an invalid URL is appended OpenStackRequest<Volume> request = cinderClient.volumes().show(volumeId); return executeAndRecordOpenstackRequest(request, false); } catch (MsoException e) { - logger.error("Error building Cinder Client", e); - throw new CinderClientException("Error building Cinder Client", e); + String errorMsg = "Error building Cinder Client"; + logger.error(errorMsg, e); + throw new CinderClientException(errorMsg, e); } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java index 1d75892138..6565db7ebc 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java @@ -44,7 +44,6 @@ import org.onap.so.adapters.vdu.VduModelInfo; import org.onap.so.adapters.vdu.VduPlugin; import org.onap.so.adapters.vdu.VduStateType; import org.onap.so.adapters.vdu.VduStatus; -import org.onap.so.cloud.CloudConfig; import org.onap.so.cloud.authentication.KeystoneAuthHolder; import org.onap.so.db.catalog.beans.CloudIdentity; import org.onap.so.db.catalog.beans.CloudSite; @@ -108,10 +107,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { "{} Create Stack: Nested exception rolling back stack: {} "; public static final String IN_PROGRESS = "in_progress"; - // Fetch cloud configuration each time (may be cached in CloudConfig class) - @Autowired - protected CloudConfig cloudConfig; - @Autowired private Environment environment; @@ -134,7 +129,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { protected static final String CREATE_POLL_INTERVAL_DEFAULT = "15"; private static final String DELETE_POLL_INTERVAL_DEFAULT = "15"; - private static final String pollingMultiplierDefault = "60"; + private static final String POLLING_MULTIPLIER_DEFAULT = "60"; private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); @@ -200,7 +195,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { * @param cloudOwner the cloud owner of the cloud site in which to create the stack * @param tenantId The Openstack ID of the tenant in which to create the Stack * @param stackName The name of the stack to create - * @param vduModelInfo contains information about the vdu model (added for plugin adapter) + * @param vduModel contains information about the vdu model (added for plugin adapter) * @param heatTemplate The Heat template * @param stackInputs A map of key/value inputs * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client @@ -287,42 +282,41 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { String cloudSiteId, String tenantId, CreateStackParam stackCreate) throws MsoException { if (stack == null) { throw new StackCreationException("Unknown Error in Stack Creation"); - } else { - logger.info("Performing post processing backout: {} cleanUpKeyPair: {}, stack {}", backout, cleanUpKeyPair, - stack); - if (!CREATE_COMPLETE.equals(stack.getStackStatus())) { - if (cleanUpKeyPair && !Strings.isNullOrEmpty(stack.getStackStatusReason()) - && isKeyPairFailure(stack.getStackStatusReason())) { - return handleKeyPairConflict(cloudSiteId, tenantId, stackCreate, timeoutMinutes, backout, stack); - } - if (!backout) { - logger.info("Status is not CREATE_COMPLETE, stack deletion suppressed"); - throw new StackCreationException("Stack rollback suppressed, stack not deleted"); - } else { - logger.info("Status is not CREATE_COMPLETE, stack deletion will be executed"); - String errorMessage = "Stack Creation Failed Openstack Status: " + stack.getStackStatus() - + " Status Reason: " + stack.getStackStatusReason(); - try { - Stack deletedStack = - handleUnknownCreateStackFailure(stack, timeoutMinutes, cloudSiteId, tenantId); - errorMessage = errorMessage + " , Rollback of Stack Creation completed with status: " - + deletedStack.getStackStatus() + " Status Reason: " - + deletedStack.getStackStatusReason(); - } catch (MsoException e) { - logger.error("Sync Error Deleting Stack during rollback", e); - if (e instanceof StackRollbackException) { - errorMessage = errorMessage + e.getMessage(); - } else { - errorMessage = errorMessage + " , Rollback of Stack Creation failed with sync error: " - + e.getMessage(); - } - } - throw new StackCreationException(errorMessage); - } + } + + logger.info("Performing post processing backout: {} cleanUpKeyPair: {}, stack {}", backout, cleanUpKeyPair, + stack); + if (!CREATE_COMPLETE.equals(stack.getStackStatus())) { + if (cleanUpKeyPair && !Strings.isNullOrEmpty(stack.getStackStatusReason()) + && isKeyPairFailure(stack.getStackStatusReason())) { + return handleKeyPairConflict(cloudSiteId, tenantId, stackCreate, timeoutMinutes, backout, stack); + } + if (!backout) { + logger.info("Status is not CREATE_COMPLETE, stack deletion suppressed"); + throw new StackCreationException("Stack rollback suppressed, stack not deleted"); } else { - return stack; + logger.info("Status is not CREATE_COMPLETE, stack deletion will be executed"); + String errorMessage = "Stack Creation Failed Openstack Status: " + stack.getStackStatus() + + " Status Reason: " + stack.getStackStatusReason(); + try { + Stack deletedStack = handleUnknownCreateStackFailure(stack, timeoutMinutes, cloudSiteId, tenantId); + errorMessage = errorMessage + " , Rollback of Stack Creation completed with status: " + + deletedStack.getStackStatus() + " Status Reason: " + deletedStack.getStackStatusReason(); + } catch (StackRollbackException se) { + logger.error("Sync Error Deleting Stack during rollback process", se); + errorMessage = errorMessage + se.getMessage(); + } catch (MsoException e) { + logger.error("Sync Error Deleting Stack during rollback", e); + + errorMessage = + errorMessage + " , Rollback of Stack Creation failed with sync error: " + e.getMessage(); + } + throw new StackCreationException(errorMessage); } + } else { + return stack; } + } protected Stack pollStackForStatus(int timeoutMinutes, Stack stack, String stackStatus, String cloudSiteId, @@ -330,7 +324,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { int pollingFrequency = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, CREATE_POLL_INTERVAL_DEFAULT)); int pollingMultiplier = - Integer.parseInt(this.environment.getProperty(pollingMultiplierProp, pollingMultiplierDefault)); + Integer.parseInt(this.environment.getProperty(pollingMultiplierProp, POLLING_MULTIPLIER_DEFAULT)); int numberOfPollingAttempts = Math.floorDiv((timeoutMinutes * pollingMultiplier), pollingFrequency); Heat heatClient = getHeatClient(cloudSiteId, tenantId); Stack latestStack = null; diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java index e840d5affd..e68364eab8 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java @@ -322,8 +322,8 @@ public class MsoHeatUtilsTest extends MsoHeatUtils { CreateStackParam createStackParam = new CreateStackParam(); createStackParam.setStackName("stackName"); - doReturn(mockResources).when(heatUtils).queryStackResources(cloudSiteId, tenantId, "stackName", 2); - doNothing().when(novaClient).deleteKeyPair(cloudSiteId, tenantId, "KeypairName"); + // doReturn(mockResources).when(heatUtils).queryStackResources(cloudSiteId, tenantId, "stackName", 2); + // doNothing().when(novaClient).deleteKeyPair(cloudSiteId, tenantId, "KeypairName"); doReturn(null).when(heatUtils).handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); doReturn(createdStack).when(heatUtils).createStack(createStackParam, cloudSiteId, tenantId); doReturn(createdStack).when(heatUtils).processCreateStack(cloudSiteId, tenantId, 120, true, createdStack, 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 486b53cf8a..13d736e747 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 @@ -813,3 +813,5 @@ VALUES ('ConfigDeployVnfBB', 'NO_VALIDATE', 'CUSTOM'); 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; diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.1.1__AddServiceRoleToRainyDayHandling.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.1.1__AddServiceRoleToRainyDayHandling.sql new file mode 100644 index 0000000000..8fe3caf88f --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.1.1__AddServiceRoleToRainyDayHandling.sql @@ -0,0 +1,2 @@ +use catalogdb; +ALTER TABLE rainy_day_handler_macro ADD COLUMN IF NOT EXISTS SERVICE_ROLE varchar(300) DEFAULT NULL;
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.1__AlterColumnActionCategoryControllerSelectionCategory.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.3__AlterColumnActionCategoryControllerSelectionCategory.sql index 6f61b830f2..6f61b830f2 100644 --- a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.1__AlterColumnActionCategoryControllerSelectionCategory.sql +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.3__AlterColumnActionCategoryControllerSelectionCategory.sql diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java index f65f521605..a955a2c3ce 100644 --- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java @@ -87,7 +87,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @Test public void testGetRainyDayHandler_Regex() { RainyDayHandlerStatus rainyDayHandlerStatus = client.getRainyDayHandlerStatus("AssignServiceInstanceBB", "*", - "*", "*", "*", "The Flavor ID (nd.c6r16d20) could not be found."); + "*", "*", "*", "The Flavor ID (nd.c6r16d20) could not be found.", "*"); Assert.assertEquals("Rollback", rainyDayHandlerStatus.getPolicy()); } @@ -95,7 +95,8 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { public void testGetRainyDayHandler__Encoding_Regex() { RainyDayHandlerStatus rainyDayHandlerStatus = client.getRainyDayHandlerStatus("AssignServiceInstanceBB", "*", "*", "*", "*", - "resources.lba_0_dmz_vmi_0: Unknown id: Error: oper 1 url /fqname-to-id body {\"fq_name\": [\"zrdm6bvota05-dmz_sec_group\"], \"type\": \"security-group\"} response Name ['zrdm6bvota05-dmz_sec_group'] not found"); + "resources.lba_0_dmz_vmi_0: Unknown id: Error: oper 1 url /fqname-to-id body {\"fq_name\": [\"zrdm6bvota05-dmz_sec_group\"], \"type\": \"security-group\"} response Name ['zrdm6bvota05-dmz_sec_group'] not found", + "*"); Assert.assertEquals("Rollback", rainyDayHandlerStatus.getPolicy()); } diff --git a/adapters/mso-catalog-db-adapter/src/test/resources/db/migration/afterMigrate.sql b/adapters/mso-catalog-db-adapter/src/test/resources/db/migration/afterMigrate.sql index 58b2983f82..32c51293c2 100644 --- a/adapters/mso-catalog-db-adapter/src/test/resources/db/migration/afterMigrate.sql +++ b/adapters/mso-catalog-db-adapter/src/test/resources/db/migration/afterMigrate.sql @@ -184,8 +184,8 @@ VALUES ( '9bcce658-9b37-11e8-98d0-529269fb1459', 'testVnfcCustomizationDescription', '2018-07-17 14:05:08'); -INSERT INTO `rainy_day_handler_macro` (`FLOW_NAME`,`SERVICE_TYPE`,`VNF_TYPE`,`ERROR_CODE`,`WORK_STEP`,`POLICY`,`SECONDARY_POLICY`,`REG_EX_ERROR_MESSAGE`) -VALUES ('AssignServiceInstanceBB','*','*','*','*','Rollback','Rollback','The Flavor ID.*could not be found.'); +INSERT INTO `rainy_day_handler_macro` (`FLOW_NAME`,`SERVICE_TYPE`,`VNF_TYPE`,`ERROR_CODE`,`WORK_STEP`,`POLICY`,`SECONDARY_POLICY`,`REG_EX_ERROR_MESSAGE`, `SERVICE_ROLE`) +VALUES ('AssignServiceInstanceBB','*','*','*','*','Rollback','Rollback','The Flavor ID.*could not be found.','*'); INSERT INTO `cvnfc_customization` (`id`, diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java index 999d27335b..6a42456715 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java @@ -40,6 +40,10 @@ public class AuditStackService { private static final Logger logger = LoggerFactory.getLogger(AuditStackService.class); + private static final String DEFAULT_AUDIT_LOCK_TIME = "60000"; + + private static final String DEFAULT_MAX_CLIENTS_FOR_TOPIC = "10"; + @Autowired public Environment env; @@ -53,41 +57,40 @@ public class AuditStackService { private AuditQueryStackService auditQueryStack; @PostConstruct - public void auditAddAAIInventory() throws Exception { + public void auditAddAAIInventory() { for (int i = 0; i < getMaxClients(); i++) { ExternalTaskClient client = createExternalTaskClient(); client.subscribe("InventoryAddAudit") - .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", "60000"))) + .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", DEFAULT_AUDIT_LOCK_TIME))) .handler(auditCreateStack::executeExternalTask).open(); } } @PostConstruct - public void auditDeleteAAIInventory() throws Exception { + public void auditDeleteAAIInventory() { for (int i = 0; i < getMaxClients(); i++) { ExternalTaskClient client = createExternalTaskClient(); client.subscribe("InventoryDeleteAudit") - .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", "60000"))) + .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", DEFAULT_AUDIT_LOCK_TIME))) .handler(auditDeleteStack::executeExternalTask).open(); } } @PostConstruct - public void auditQueryInventory() throws Exception { + public void auditQueryInventory() { for (int i = 0; i < getMaxClients(); i++) { ExternalTaskClient client = createExternalTaskClient(); client.subscribe("InventoryQueryAudit") - .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", "60000"))) + .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", DEFAULT_AUDIT_LOCK_TIME))) .handler(auditQueryStack::executeExternalTask).open(); } } - protected ExternalTaskClient createExternalTaskClient() throws Exception { + protected ExternalTaskClient createExternalTaskClient() { ClientRequestInterceptor interceptor = createClientRequestInterceptor(); - ExternalTaskClient client = ExternalTaskClient.create() - .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor) - .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build(); - return client; + return ExternalTaskClient.create().baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1) + .addInterceptor(interceptor).asyncResponseTimeout(120000) + .backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build(); } protected ClientRequestInterceptor createClientRequestInterceptor() { @@ -97,13 +100,11 @@ public class AuditStackService { } catch (IllegalStateException | GeneralSecurityException e) { logger.error("Error Decrypting Password", e); } - ClientRequestInterceptor interceptor = - new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth); - return interceptor; + return new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth); } protected int getMaxClients() { - return Integer.parseInt(env.getProperty("workflow.topics.maxClients", "10")); + return Integer.parseInt(env.getProperty("workflow.topics.maxClients", DEFAULT_MAX_CLIENTS_FOR_TOPIC)); } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java index fd2054c3d0..09a5424d47 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java @@ -144,9 +144,20 @@ public class ExecuteBuildingBlockRainyDay { // keep default workStep value } + String serviceRole = ASTERISK; + try { + serviceRole = gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0) + .getModelInfoServiceInstance().getServiceRole(); + if (serviceRole == null || serviceRole.isEmpty()) { + serviceRole = ASTERISK; + } + } catch (Exception ex) { + // keep default serviceRole value + } + RainyDayHandlerStatus rainyDayHandlerStatus; rainyDayHandlerStatus = catalogDbClient.getRainyDayHandlerStatus(bbName, serviceType, vnfType, - errorCode, workStep, errorMessage); + errorCode, workStep, errorMessage, serviceRole); if (rainyDayHandlerStatus == null) { handlingCode = "Abort"; diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java index 80373eb760..18e08917ed 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java @@ -105,7 +105,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { rainyDayHandlerStatus.setWorkStep(ASTERISK); doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB", - "st1", "vnft1", "7000", "*", "errorMessage"); + "st1", "vnft1", "7000", "*", "errorMessage", "*"); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); assertEquals("Rollback", delegateExecution.getVariable("handlingCode")); @@ -128,7 +128,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { rainyDayHandlerStatus.setWorkStep(ASTERISK); doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB", - "st1", "vnft1", ASTERISK, ASTERISK, "errorMessage"); + "st1", "vnft1", ASTERISK, ASTERISK, "errorMessage", "*"); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); assertEquals("Rollback", delegateExecution.getVariable("handlingCode")); assertEquals(5, delegateExecution.getVariable("maxRetries")); @@ -141,7 +141,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { vnf.setVnfType("vnft1"); delegateExecution.setVariable("aLaCarte", true); doReturn(null).when(MOCK_catalogDbClient).getRainyDayHandlerStatus(isA(String.class), isA(String.class), - isA(String.class), isA(String.class), isA(String.class), isA(String.class)); + isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class)); delegateExecution.setVariable("suppressRollback", false); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); @@ -152,7 +152,8 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { @Test public void queryRainyDayTableExceptionTest() { doThrow(RuntimeException.class).when(MOCK_catalogDbClient).getRainyDayHandlerStatus(isA(String.class), - isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class)); + isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class), + isA(String.class)); delegateExecution.setVariable("aLaCarte", true); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); delegateExecution.setVariable("suppressRollback", false); @@ -178,7 +179,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { rainyDayHandlerStatus.setSecondaryPolicy("Abort"); doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB", - "st1", "vnft1", "7000", "*", "errorMessage"); + "st1", "vnft1", "7000", "*", "errorMessage", "*"); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, false); @@ -203,7 +204,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { rainyDayHandlerStatus.setSecondaryPolicy("Abort"); doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB", - "st1", "vnft1", "7000", "*", "errorMessage"); + "st1", "vnft1", "7000", "*", "errorMessage", "*"); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); @@ -229,7 +230,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { rainyDayHandlerStatus.setSecondaryPolicy("Abort"); doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB", - "st1", "vnft1", "7000", "*", "errorMessage"); + "st1", "vnft1", "7000", "*", "errorMessage", "*"); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); @@ -255,7 +256,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { rainyDayHandlerStatus.setSecondaryPolicy("Abort"); doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB", - "st1", "vnft1", "7000", "*", "errorMessage"); + "st1", "vnft1", "7000", "*", "errorMessage", "*"); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); @@ -272,4 +273,52 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { assertEquals("Abort", delegateExecution.getVariable("handlingCode")); } + @Test + public void queryRainyDayTableServiceRoleNotDefined() throws Exception { + customer.getServiceSubscription().getServiceInstances().add(serviceInstance); + serviceInstance.getModelInfoServiceInstance().setServiceType("st1"); + serviceInstance.getModelInfoServiceInstance().setServiceRole("sr1"); + vnf.setVnfType("vnft1"); + delegateExecution.setVariable("aLaCarte", true); + delegateExecution.setVariable("suppressRollback", false); + delegateExecution.setVariable("WorkflowExceptionCode", "7000"); + RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus(); + rainyDayHandlerStatus.setErrorCode("7000"); + rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB"); + rainyDayHandlerStatus.setServiceType("st1"); + rainyDayHandlerStatus.setVnfType("vnft1"); + rainyDayHandlerStatus.setPolicy("Rollback"); + rainyDayHandlerStatus.setWorkStep(ASTERISK); + + doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB", + "st1", "vnft1", "7000", "*", "errorMessage", "sr1"); + + executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); + assertEquals("Rollback", delegateExecution.getVariable("handlingCode")); + } + + @Test + public void queryRainyDayTableServiceRoleNC() throws Exception { + customer.getServiceSubscription().getServiceInstances().add(serviceInstance); + serviceInstance.getModelInfoServiceInstance().setServiceType("st1"); + serviceInstance.getModelInfoServiceInstance().setServiceRole("NETWORK-COLLECTION"); + vnf.setVnfType("vnft1"); + delegateExecution.setVariable("aLaCarte", true); + delegateExecution.setVariable("suppressRollback", false); + delegateExecution.setVariable("WorkflowExceptionCode", "7000"); + RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus(); + rainyDayHandlerStatus.setErrorCode("7000"); + rainyDayHandlerStatus.setFlowName("ActivateServiceInstanceBB"); + rainyDayHandlerStatus.setServiceType("st1"); + rainyDayHandlerStatus.setVnfType("vnft1"); + rainyDayHandlerStatus.setPolicy("Abort"); + rainyDayHandlerStatus.setWorkStep(ASTERISK); + + doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB", + "st1", "vnft1", "7000", "*", "errorMessage", "NETWORK-COLLECTION"); + + executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); + assertEquals("Abort", delegateExecution.getVariable("handlingCode")); + } + } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java deleted file mode 100644 index 1442099286..0000000000 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java +++ /dev/null @@ -1,422 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.bpmn.core; - -import org.camunda.bpm.engine.delegate.DelegateExecution; -import org.camunda.bpm.engine.delegate.Expression; -import org.camunda.bpm.engine.delegate.JavaDelegate; -import org.onap.so.bpmn.core.internal.VariableNameExtractor; - -/** - * Base class for service tasks. - */ -public class BaseTask implements JavaDelegate { - - /** - * Get the value of a required field. This method throws MissingInjectedFieldException if the expression is null, - * and BadInjectedFieldException if the expression evaluates to a null value. - * - * @param expression the expression - * @param execution the execution - * @param fieldName the field name (for logging and exceptions) - * @return the field value - */ - protected Object getField(Expression expression, DelegateExecution execution, String fieldName) { - return getFieldImpl(expression, execution, fieldName, false); - } - - /** - * Gets the value of an optional field. There are three conditions in which this method returns null: - * <p> - * <ol> - * <li>The expression itself is null (i.e. the field is missing altogether.</li> - * <li>The expression evaluates to a null value.</li> - * <li>The expression references a single variable which has not been set.</li> - * </ol> - * <p> - * Examples:<br> - * Expression ${x} when x is null: return null<br> - * Expression ${x} when x is unset: return null<br> - * Expression ${x+y} when x and/or y are unset: exception<br> - * - * @param expression the expression - * @param execution the execution - * @param fieldName the field name (for logging and exceptions) - * @return the field value, possibly null - */ - protected Object getOptionalField(Expression expression, DelegateExecution execution, String fieldName) { - return getFieldImpl(expression, execution, fieldName, true); - } - - /** - * Get the value of a required output variable field. This method throws MissingInjectedFieldException if the - * expression is null, and BadInjectedFieldException if the expression produces a null or illegal variable name. - * Legal variable names contain only letters, numbers, and the underscore character ('_'). - * - * @param expression the expression - * @param execution the execution - * @param fieldName the field name (for logging and exceptions) - * @return the output variable name - */ - protected String getOutputField(Expression expression, DelegateExecution execution, String fieldName) { - Object o = getFieldImpl(expression, execution, fieldName, false); - if (o instanceof String) { - String variable = (String) o; - if (!isLegalVariable(variable)) { - throw new BadInjectedFieldException(fieldName, getTaskName(), - "'" + variable + "' is not a legal variable name"); - } - return variable; - } else { - if (o != null) { - throw new BadInjectedFieldException(fieldName, getTaskName(), - "expected a variable name string, got object of type " + o.getClass().getName()); - } else { - throw new BadInjectedFieldException(fieldName, getTaskName(), - "expected a variable name string, got null object"); - } - } - } - - /** - * Get the value of an optional output variable field. This method throws BadInjectedFieldException if the - * expression produces an illegal variable name. Legal variable names contain only letters, numbers, and the - * underscore character ('_'). - * - * @param expression the expression - * @param execution the execution - * @param fieldName the field name (for logging and exceptions) - * @return the output variable name, possibly null - */ - protected String getOptionalOutputField(Expression expression, DelegateExecution execution, String fieldName) { - Object o = getFieldImpl(expression, execution, fieldName, true); - if (o instanceof String) { - String variable = (String) o; - if (!isLegalVariable(variable)) { - throw new BadInjectedFieldException(fieldName, getTaskName(), - "'" + variable + "' is not a legal variable name"); - } - return variable; - } else if (o == null) { - return null; - } else { - throw new BadInjectedFieldException(fieldName, getTaskName(), - "expected a variable name string, got object of type " + o.getClass().getName()); - } - } - - /** - * Get the value of a required string field. This method throws MissingInjectedFieldException if the expression is - * null, and BadInjectedFieldException if the expression evaluates to a null value. - * <p> - * Note: the result is coerced to a string value, if necessary. - * - * @param expression the expression - * @param execution the execution - * @param fieldName the field name (for logging and exceptions) - * @return the field value - */ - protected String getStringField(Expression expression, DelegateExecution execution, String fieldName) { - Object o = getFieldImpl(expression, execution, fieldName, false); - if (o instanceof String) { - return (String) o; - } else if (o != null) { - throw new BadInjectedFieldException(fieldName, getTaskName(), - "cannot convert '" + o.toString() + "' to Integer"); - } else { - throw new MissingInjectedFieldException(fieldName, getTaskName()); - } - } - - /** - * Gets the value of an optional string field. There are three conditions in which this method returns null: - * <p> - * <ol> - * <li>The expression itself is null (i.e. the field is missing altogether.</li> - * <li>The expression evaluates to a null value.</li> - * <li>The expression references a single variable which has not been set.</li> - * </ol> - * <p> - * Examples:<br> - * Expression ${x} when x is null: return null<br> - * Expression ${x} when x is unset: return null<br> - * Expression ${x+y} when x and/or y are unset: exception<br> - * <p> - * Note: the result is coerced to a string value, if necessary. - * - * @param expression the expression - * @param execution the execution - * @param fieldName the field name (for logging and exceptions) - * @return the field value, possibly null - */ - protected String getOptionalStringField(Expression expression, DelegateExecution execution, String fieldName) { - Object o = getFieldImpl(expression, execution, fieldName, true); - if (o instanceof String) { - return (String) o; - } else if (o == null) { - return null; - } else { - return o.toString(); - } - } - - /** - * Get the value of a required integer field. This method throws MissingInjectedFieldException if the expression is - * null, and BadInjectedFieldException if the expression evaluates to a null value or a value that cannot be coerced - * to an integer. - * - * @param expression the expression - * @param execution the execution - * @param fieldName the field name (for logging and exceptions) - * @return the field value - */ - protected Integer getIntegerField(Expression expression, DelegateExecution execution, String fieldName) { - Object o = getFieldImpl(expression, execution, fieldName, false); - if (o instanceof Integer) { - return (Integer) o; - } else { - try { - return Integer.parseInt(o.toString()); - } catch (NumberFormatException e) { - if (o != null) { - throw new BadInjectedFieldException(fieldName, getTaskName(), - "cannot convert '" + o.toString() + "' to Integer"); - } else { - throw new MissingInjectedFieldException(fieldName, getTaskName()); - } - } - } - } - - /** - * Gets the value of an optional integer field. There are three conditions in which this method returns null: - * <p> - * <ol> - * <li>The expression itself is null (i.e. the field is missing altogether.</li> - * <li>The expression evaluates to a null value.</li> - * <li>The expression references a single variable which has not been set.</li> - * </ol> - * <p> - * Examples:<br> - * Expression ${x} when x is null: return null<br> - * Expression ${x} when x is unset: return null<br> - * Expression ${x+y} when x and/or y are unset: exception<br> - * <p> - * Note: the result is coerced to an integer value, if necessary. This method throws BadInjectedFieldException if - * the result cannot be coerced to an integer. - * - * @param expression the expression - * @param execution the execution - * @param fieldName the field name (for logging and exceptions) - * @return the field value, possibly null - */ - protected Integer getOptionalIntegerField(Expression expression, DelegateExecution execution, String fieldName) { - Object o = getFieldImpl(expression, execution, fieldName, true); - if (o instanceof Integer) { - return (Integer) o; - } else if (o == null) { - return null; - } else { - try { - return Integer.parseInt(o.toString()); - } catch (NumberFormatException e) { - throw new BadInjectedFieldException(fieldName, getTaskName(), - "cannot convert '" + o.toString() + "' to Integer"); - } - } - } - - /** - * Gets the value of an optional long field. There are three conditions in which this method returns null: - * <p> - * <ol> - * <li>The expression itself is null (i.e. the field is missing altogether.</li> - * <li>The expression evaluates to a null value.</li> - * <li>The expression references a single variable which has not been set.</li> - * </ol> - * <p> - * Examples:<br> - * Expression ${x} when x is null: return null<br> - * Expression ${x} when x is unset: return null<br> - * Expression ${x+y} when x and/or y are unset: exception<br> - * <p> - * Note: the result is coerced to a long value, if necessary. This method throws BadInjectedFieldException if the - * result cannot be coerced to a long. - * - * @param expression the expression - * @param execution the execution - * @param fieldName the field name (for logging and exceptions) - * @return the field value, possibly null - */ - protected Long getOptionalLongField(Expression expression, DelegateExecution execution, String fieldName) { - Object o = getFieldImpl(expression, execution, fieldName, true); - if (o instanceof Long) { - return (Long) o; - } else if (o == null) { - return null; - } else { - try { - return Long.parseLong(o.toString()); - } catch (NumberFormatException e) { - throw new BadInjectedFieldException(fieldName, getTaskName(), - "cannot convert '" + o.toString() + "' to Long"); - } - } - } - - /** - * Get the value of a required long field. This method throws MissingInjectedFieldException if the expression is - * null, and BadInjectedFieldException if the expression evaluates to a null value or a value that cannot be coerced - * to a long. - * - * @param expression the expression - * @param execution the execution - * @param fieldName the field name (for logging and exceptions) - * @return the field value - */ - protected Long getLongField(Expression expression, DelegateExecution execution, String fieldName) { - Object o = getFieldImpl(expression, execution, fieldName, false); - if (o instanceof Long) { - return (Long) o; - } else { - try { - return Long.parseLong(o.toString()); - } catch (NumberFormatException e) { - if (o != null) { - throw new BadInjectedFieldException(fieldName, getTaskName(), - "cannot convert '" + o.toString() + "' to Long"); - } else { - throw new MissingInjectedFieldException(fieldName, getTaskName()); - } - } - } - } - - /** - * Common implementation for field "getter" methods. - * - * @param expression the expression - * @param execution the execution - * @param fieldName the field name (for logging and exceptions) - * @param optional true if the field is optional - * @return the field value, possibly null - */ - private Object getFieldImpl(Expression expression, DelegateExecution execution, String fieldName, - boolean optional) { - if (expression == null) { - if (!optional) { - throw new MissingInjectedFieldException(fieldName, getTaskName()); - } - return null; - } - - Object value = null; - - try { - value = expression.getValue(execution); - } catch (Exception e) { - if (!optional) { - throw new BadInjectedFieldException(fieldName, getTaskName(), e.getClass().getSimpleName(), e); - } - - // At this point, we have an exception that occurred while - // evaluating an expression for an optional field. A common - // problem is that the expression is a simple reference to a - // variable which has never been set, e.g. the expression is - // ${x}. The normal activiti behavior is to throw an exception, - // but we don't like that, so we have the following workaround, - // which parses the expression text to see if it is a "simple" - // variable reference, and if so, returns null. If the - // expression is anything other than a single variable - // reference, then an exception is thrown, as it would have - // been without this workaround. - - // Get the expression text so we can parse it - String s = expression.getExpressionText(); - new VariableNameExtractor(s).extract().ifPresent(name -> { - if (execution.hasVariable(name)) { - throw new BadInjectedFieldException(fieldName, getTaskName(), e.getClass().getSimpleName(), e); - } - }); - } - - if (value == null && !optional) { - throw new BadInjectedFieldException(fieldName, getTaskName(), "required field has null value"); - } - - return value; - } - - /** - * Tests if a character is a "word" character. - * - * @param c the character - * @return true if the character is a "word" character. - */ - private static boolean isWordCharacter(char c) { - return (Character.isLetterOrDigit(c) || c == '_'); - } - - /** - * Tests if the specified string is a legal flow variable name. - * - * @param name the string - * @return true if the string is a legal flow variable name - */ - private boolean isLegalVariable(String name) { - if (name == null) { - return false; - } - - int len = name.length(); - - if (len == 0) { - return false; - } - - char c = name.charAt(0); - - if (!Character.isLetter(c) && c != '_') { - return false; - } - - for (int i = 1; i < len; i++) { - c = name.charAt(i); - if (!Character.isLetterOrDigit(c) && c != '_') { - return false; - } - } - - return true; - } - - /** - * Returns the name of the task (normally the java class name). - * - * @return the name of the task - */ - public String getTaskName() { - return getClass().getSimpleName(); - } - - @Override - public void execute(DelegateExecution execution) throws Exception {} -} diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java deleted file mode 100644 index a9f33f20c5..0000000000 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * ============LICENSE_START======================================================= ONAP : SO - * ================================================================================ Copyright (C) 2018 AT&T Intellectual - * Property. All rights reserved. ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.bpmn.core; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import org.camunda.bpm.engine.ProcessEngineServices; -import org.camunda.bpm.engine.RepositoryService; -import org.camunda.bpm.engine.delegate.DelegateExecution; -import org.camunda.bpm.engine.delegate.Expression; -import org.camunda.bpm.engine.repository.ProcessDefinition; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -public class BaseTaskTest { - - private String prefix = "PRE_"; - private String processKey = "AnyProcessKey"; - private String definitionId = "100"; - private String anyVariable = "anyVariable"; - private String anyValueString = "anyValue"; - private String badValueString = "123abc"; - private int anyValueInt = 123; - private Integer anyValueInteger = Integer.valueOf(anyValueInt); - private long anyValuelong = 123L; - private Long anyValueLong = Long.valueOf(anyValuelong); - - private DelegateExecution mockExecution; - private Expression mockExpression; - private BaseTask baseTask; - private Object obj1; - private Object obj2; - private Object objectString; - private Object objectInteger; - private Object objectLong; - private Object objectBoolean; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Before - public void before() throws Exception { - baseTask = new BaseTask(); - ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class); - when(mockProcessDefinition.getKey()).thenReturn(processKey); - RepositoryService mockRepositoryService = mock(RepositoryService.class); - when(mockRepositoryService.getProcessDefinition(definitionId)).thenReturn(mockProcessDefinition); - ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class); - when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService); - mockExecution = mock(DelegateExecution.class); - when(mockExecution.getId()).thenReturn(definitionId); - when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices); - when(mockExecution.getProcessEngineServices().getRepositoryService() - .getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition); - when(mockExecution.getVariable("prefix")).thenReturn(prefix); - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true"); - mockExpression = mock(Expression.class); - } - - @Test - public void testExecution() throws Exception { - baseTask.execute(mockExecution); - assertEquals("BaseTask", baseTask.getTaskName()); - } - - @Test - public void testGetFieldAndMissingInjectedException() throws Exception { - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj1 = baseTask.getField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueString, obj1.toString()); - - expectedException.expect(MissingInjectedFieldException.class); - obj2 = baseTask.getField(null, mockExecution, anyVariable); - } - - @Test - public void testGetFieldAndBadInjectedFieldException() throws Exception { - expectedException.expect(BadInjectedFieldException.class); - obj1 = baseTask.getField(mockExpression, mockExecution, null); - } - - @Test - public void testGetOptionalField() throws Exception { - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj1 = baseTask.getOptionalField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueString, obj1.toString()); - } - - @Test - public void testGetStringFieldAndMissingInjectedFieldException() throws Exception { - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj1 = baseTask.getStringField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueString, obj1.toString()); - - expectedException.expect(MissingInjectedFieldException.class); - Object objectBoolean = Boolean.valueOf(true); // bad data - when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean); - obj2 = baseTask.getStringField(null, mockExecution, anyVariable); - } - - @Test - public void testGetStringFieldAndBadInjectedFieldException() throws Exception { - expectedException.expect(BadInjectedFieldException.class); - obj1 = baseTask.getStringField(mockExpression, mockExecution, null); - } - - @Test - public void testGetOptionalStringField() throws Exception { - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj1 = baseTask.getOptionalStringField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueString, obj1.toString()); - } - - @Test - public void testGetIntegerFieldAndMissingInjectedFieldException() throws Exception { - objectInteger = Integer.valueOf(anyValueInt); - when(mockExpression.getValue(mockExecution)).thenReturn(objectInteger); - obj1 = baseTask.getIntegerField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueInteger, (Integer) obj1); - - expectedException.expect(MissingInjectedFieldException.class); - objectString = new String(badValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj2 = baseTask.getIntegerField(null, mockExecution, anyVariable); - } - - @Test - public void testGetIntegerFieldAndBadInjectedFieldException() throws Exception { - expectedException.expect(BadInjectedFieldException.class); - obj1 = baseTask.getIntegerField(mockExpression, mockExecution, null); - } - - - @Test - public void testGetOptionalIntegerField() throws Exception { - objectInteger = Integer.valueOf(anyValueInt); - when(mockExpression.getValue(mockExecution)).thenReturn(objectInteger); - obj1 = baseTask.getOptionalIntegerField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueInteger, (Integer) obj1); - } - - @Test - public void testGetOptionalIntegerFieldAndBadInjectedFieldException() throws Exception { - expectedException.expect(BadInjectedFieldException.class); - objectBoolean = Boolean.valueOf(true); - when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean); - obj1 = baseTask.getOptionalIntegerField(mockExpression, mockExecution, anyVariable); - } - - @Test - public void testGetLongFieldAndMissingInjectedFieldException() throws Exception { - objectLong = Long.valueOf(anyValuelong); - when(mockExpression.getValue(mockExecution)).thenReturn(objectLong); - obj1 = baseTask.getLongField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueLong, (Long) obj1); - - expectedException.expect(MissingInjectedFieldException.class); - objectString = new String(badValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj2 = baseTask.getLongField(null, mockExecution, anyVariable); - } - - @Test - public void testGetLongFieldAndBadInjectedFieldException() throws Exception { - expectedException.expect(BadInjectedFieldException.class); - obj2 = baseTask.getLongField(mockExpression, mockExecution, null); - } - - @Test - public void testGetOptionalLongField() throws Exception { - objectLong = Long.valueOf(anyValuelong); - when(mockExpression.getValue(mockExecution)).thenReturn(objectLong); - obj1 = baseTask.getOptionalLongField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueLong, (Long) obj1); - } - - @Test - public void testGetOptionalLongFieldAndBadInjectedFieldException() throws Exception { - expectedException.expect(BadInjectedFieldException.class); - objectBoolean = Boolean.valueOf(true); - when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean); - obj1 = baseTask.getOptionalLongField(mockExpression, mockExecution, anyVariable); - } - - @Test - public void testGetOutputAndMissingInjectedFieldException() throws Exception { - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj1 = baseTask.getOutputField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueString, obj1.toString()); - - expectedException.expect(MissingInjectedFieldException.class); - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj2 = baseTask.getOutputField(null, mockExecution, anyVariable); - } - - @Test - public void testGetOutputAndBadInjectedFieldException() throws Exception { - expectedException.expect(BadInjectedFieldException.class); - obj2 = baseTask.getOutputField(null, mockExecution, anyVariable); - } - - @Test - public void testGetOptionalOutputField() throws Exception { - objectString = new String(anyValueString); - when(mockExpression.getValue(mockExecution)).thenReturn(objectString); - obj1 = baseTask.getOptionalOutputField(mockExpression, mockExecution, anyVariable); - assertEquals(anyValueString, obj1.toString()); - } - - @Test - public void testGetOptionalOutputFieldAndBadInjectedFieldException() throws Exception { - expectedException.expect(BadInjectedFieldException.class); - objectBoolean = Boolean.valueOf(true); - when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean); - obj1 = baseTask.getOptionalOutputField(mockExpression, mockExecution, anyVariable); - } - -} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java index f7708b69d3..f933277f3c 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java @@ -27,6 +27,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import org.camunda.bpm.engine.delegate.JavaDelegate; import org.onap.so.logger.LoggingAnchor; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.methods.CloseableHttpResponse; @@ -41,7 +42,6 @@ import org.json.JSONObject; import org.onap.msb.sdk.discovery.common.RouteException; import org.onap.msb.sdk.httpclient.RestServiceCreater; import org.onap.msb.sdk.httpclient.msb.MSBServiceClient; -import org.onap.so.bpmn.core.BaseTask; import org.onap.so.bpmn.core.UrnPropertiesReader; import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.GenericResourceApi; import org.onap.so.db.request.beans.ResourceOperationStatus; @@ -56,7 +56,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -public abstract class AbstractSdncOperationTask extends BaseTask { +public abstract class AbstractSdncOperationTask implements JavaDelegate { private static final Logger logger = LoggerFactory.getLogger(AbstractSdncOperationTask.class); @@ -284,7 +284,7 @@ public abstract class AbstractSdncOperationTask extends BaseTask { logger.info("exception: AbstractSdncOperationTask.updateProgress fail!"); logger.error("exception: AbstractSdncOperationTask.updateProgress fail:", exception); logger.error(LoggingAnchor.FIVE, MessageEnum.GENERAL_EXCEPTION.toString(), - " updateProgress catch exception: ", this.getTaskName(), ErrorCode.UnknownError.getValue(), + " updateProgress catch exception: ", ErrorCode.UnknownError.getValue(), exception.getClass().toString()); } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnPreprocessTask.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnPreprocessTask.java index 5b7f3bb432..16bd194f99 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnPreprocessTask.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnPreprocessTask.java @@ -22,12 +22,12 @@ package org.onap.so.bpmn.infrastructure.workflow.serviceTask; import org.apache.commons.lang3.StringUtils; import org.camunda.bpm.engine.delegate.DelegateExecution; -import org.onap.so.bpmn.core.BaseTask; +import org.camunda.bpm.engine.delegate.JavaDelegate; import org.onap.so.db.request.beans.ResourceOperationStatus; import org.springframework.stereotype.Component; @Component -public class SdncUnderlayVpnPreprocessTask extends BaseTask { +public class SdncUnderlayVpnPreprocessTask implements JavaDelegate { public static final String RESOURCE_OPER_TYPE = "resourceOperType"; @Override diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivity.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivity.java index a436f7b5c2..9340609ffc 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivity.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivity.java @@ -59,9 +59,18 @@ public class ExecuteActivity implements JavaDelegate { private static final String VNF_ID = "vnfId"; private static final String SERVICE_INSTANCE_ID = "serviceInstanceId"; private static final String WORKFLOW_SYNC_ACK_SENT = "workflowSyncAckSent"; + private static final String BUILDING_BLOCK = "buildingBlock"; + private static final String EXECUTE_BUILDING_BLOCK = "ExecuteBuildingBlock"; + private static final String RETRY_COUNT = "retryCount"; + private static final String A_LA_CARTE = "aLaCarte"; + private static final String SUPPRESS_ROLLBACK = "suppressRollback"; + private static final String WORKFLOW_EXCEPTION = "WorkflowException"; + private static final String HANDLING_CODE = "handlingCode"; + private static final String ABORT_HANDLING_CODE = "Abort"; private static final String SERVICE_TASK_IMPLEMENTATION_ATTRIBUTE = "implementation"; private static final String ACTIVITY_PREFIX = "activity:"; + private static final String EXECUTE_ACTIVITY_ERROR_MESSAGE = "ExecuteActivityErrorMessage"; private ObjectMapper mapper = new ObjectMapper(); @@ -75,7 +84,8 @@ public class ExecuteActivity implements JavaDelegate { @Override public void execute(DelegateExecution execution) throws Exception { final String requestId = (String) execution.getVariable(G_REQUEST_ID); - + WorkflowException workflowException = null; + String handlingCode = null; try { Boolean workflowSyncAckSent = (Boolean) execution.getVariable(WORKFLOW_SYNC_ACK_SENT); if (workflowSyncAckSent == null || workflowSyncAckSent == false) { @@ -95,31 +105,44 @@ public class ExecuteActivity implements JavaDelegate { ExecuteBuildingBlock executeBuildingBlock = buildExecuteBuildingBlock(execution, requestId, buildingBlock); Map<String, Object> variables = new HashMap<>(); - variables.put("buildingBlock", executeBuildingBlock); - variables.put(G_REQUEST_ID, requestId); - variables.put("retryCount", 1); - variables.put("aLaCarte", true); - variables.put("suppressRollback", true); - execution.getVariables().forEach((key, value) -> { - if (value instanceof Serializable) { - variables.put(key, (Serializable) value); - } - }); + if (execution.getVariables() != null) { + execution.getVariables().forEach((key, value) -> { + if (value instanceof Serializable) { + variables.put(key, (Serializable) value); + } + }); + } + + variables.put(BUILDING_BLOCK, executeBuildingBlock); + variables.put(G_REQUEST_ID, requestId); + variables.put(RETRY_COUNT, 1); + variables.put(A_LA_CARTE, true); + variables.put(SUPPRESS_ROLLBACK, true); ProcessInstanceWithVariables buildingBlockResult = - runtimeService.createProcessInstanceByKey("ExecuteBuildingBlock").setVariables(variables) + runtimeService.createProcessInstanceByKey(EXECUTE_BUILDING_BLOCK).setVariables(variables) .executeWithVariablesInReturn(); VariableMap variableMap = buildingBlockResult.getVariables(); - WorkflowException workflowException = (WorkflowException) variableMap.get("WorklfowException"); + workflowException = (WorkflowException) variableMap.get(WORKFLOW_EXCEPTION); if (workflowException != null) { logger.error("Workflow exception is: {}", workflowException.getErrorMessage()); } - execution.setVariable("WorkflowException", workflowException); + + handlingCode = (String) variableMap.get(HANDLING_CODE); + logger.debug("Handling code: " + handlingCode); + + execution.setVariable(WORKFLOW_EXCEPTION, workflowException); } catch (Exception e) { buildAndThrowException(execution, e.getMessage()); } + + if (workflowException != null && handlingCode != null && handlingCode.equals(ABORT_HANDLING_CODE)) { + logger.debug("Aborting execution of the custom workflow"); + buildAndThrowException(execution, workflowException.getErrorMessage()); + } + } protected BuildingBlock buildBuildingBlock(String activityName) { @@ -161,7 +184,7 @@ public class ExecuteActivity implements JavaDelegate { protected void buildAndThrowException(DelegateExecution execution, String msg) { logger.error(msg); - execution.setVariable("ExecuteActuvityErrorMessage", msg); + execution.setVariable(EXECUTE_ACTIVITY_ERROR_MESSAGE, msg); exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg); } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java index 7466df53b2..c9a937b824 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java @@ -30,8 +30,6 @@ import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.exception.ExceptionBuilder; import org.onap.so.client.orchestration.AAINetworkResources; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -61,10 +59,10 @@ public class UnassignNetworkBB { * @param execution - BuildingBlockExecution * @param relatedToValue - String, ex: vf-module * @return void - nothing - * @throws Exception + * */ - public void checkRelationshipRelatedTo(BuildingBlockExecution execution, String relatedToValue) throws Exception { + public void checkRelationshipRelatedTo(BuildingBlockExecution execution, String relatedToValue) { try { L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network); @@ -85,10 +83,10 @@ public class UnassignNetworkBB { * * @param execution - BuildingBlockExecution * @return void - nothing - * @throws Exception + * */ - public void getCloudSdncRegion(BuildingBlockExecution execution) throws Exception { + public void getCloudSdncRegion(BuildingBlockExecution execution) { try { String cloudRegionSdnc = networkBBUtils.getCloudRegion(execution, SourceSystem.SDNC); execution.setVariable("cloudRegionSdnc", cloudRegionSdnc); @@ -107,7 +105,7 @@ public class UnassignNetworkBB { String msg; boolean isRollbackNeeded = execution.getVariable("isRollbackNeeded") != null ? execution.getVariable("isRollbackNeeded") : false; - if (isRollbackNeeded == true) { + if (isRollbackNeeded) { msg = execution.getVariable("ErrorUnassignNetworkBB") + messageErrorRollback; } else { msg = execution.getVariable("ErrorUnassignNetworkBB"); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java index 21c0b971b8..d07574a1ad 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java @@ -57,10 +57,10 @@ public class SniroClient { * * @param homingRequest * @return - * @throws JsonProcessingException + * @throws BadResponseException * @throws BpmnError */ - public void postDemands(SniroManagerRequest homingRequest) throws BadResponseException, JsonProcessingException { + public void postDemands(SniroManagerRequest homingRequest) throws BadResponseException { logger.trace("Started Sniro Client Post Demands"); String url = managerProperties.getHost() + managerProperties.getUri().get("v2"); logger.debug("Post demands url: {}", url); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java index 554c794e3e..15572f2b39 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java @@ -216,7 +216,7 @@ public class InstanceManagement { try { recipeLookupResult = getCustomWorkflowUri(workflowUuid); - } catch (IOException e) { + } catch (Exception e) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); @@ -243,7 +243,7 @@ public class InstanceManagement { return recipeLookupResult; } - private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) throws IOException { + private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) { String recipeUri = null; Workflow workflow = catalogDbClient.findWorkflowByArtifactUUID(workflowUuid); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java index 7bd7f95286..3c4c90cc37 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java @@ -91,7 +91,7 @@ public class TasksHandler { @QueryParam("originalRequestDate") String originalRequestDate, @QueryParam("originalRequestorId") String originalRequestorId, @PathParam("version") String version) throws ApiException { - Response responseBack = null; + String apiVersion = version.substring(1); // Prepare the query string to /task interface @@ -159,60 +159,49 @@ public class TasksHandler { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) .build(); + throw new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(), + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo) + .build(); - - ValidateException validateException = - new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(), - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - - throw validateException; } catch (IOException e) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) .build(); - BPMNFailureException bpmnFailureException = - new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), - HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); - throw bpmnFailureException; + throw new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, + ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build(); } TasksGetResponse trr = new TasksGetResponse(); List<TaskList> taskList = new ArrayList<>(); ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); int bpelStatus = respHandler.getStatus(); - if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) { - String respBody = respHandler.getResponseBody(); - if (respBody != null) { - JSONArray data = new JSONArray(respBody); + String respBody = respHandler.getResponseBody(); + if ((bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) && (null != respBody)) { - for (int i = 0; i < data.length(); i++) { - JSONObject taskEntry = data.getJSONObject(i); - String id = taskEntry.getString("id"); - if (taskId != null && !taskId.equals(id)) { - continue; - } - // Get variables info for each task ID - TaskList taskListEntry = null; - taskListEntry = getTaskInfo(id); - - taskList.add(taskListEntry); + JSONArray data = new JSONArray(respBody); + for (int i = 0; i < data.length(); i++) { + JSONObject taskEntry = data.getJSONObject(i); + String id = taskEntry.getString("id"); + if (taskId != null && !taskId.equals(id)) { + continue; } - trr.setTaskList(taskList); + // Get variables info for each task ID + TaskList taskListEntry = null; + taskListEntry = getTaskInfo(id); + + taskList.add(taskListEntry); + } + trr.setTaskList(taskList); } else { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError) .build(); - - - BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), - bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); - - throw bpmnFailureException; + throw new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); } String jsonResponse = null; @@ -223,14 +212,10 @@ public class TasksHandler { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) .build(); + throw new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(), + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo) + .build(); - - ValidateException validateException = - new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(), - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - - throw validateException; } return builder.buildResponse(HttpStatus.SC_ACCEPTED, "", jsonResponse, apiVersion); @@ -250,10 +235,8 @@ public class TasksHandler { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) .build(); - BPMNFailureException validateException = - new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), - HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); - throw validateException; + throw new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, + ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build(); } ResponseHandler respHandler = new ResponseHandler(getResponse, requestClient.getType()); int bpelStatus = respHandler.getStatus(); @@ -264,14 +247,10 @@ public class TasksHandler { } else { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).build(); + throw new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), + HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo) + .build(); - - - BPMNFailureException bpmnFailureException = - new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), - HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); - - throw bpmnFailureException; } } else { @@ -279,20 +258,15 @@ public class TasksHandler { new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) .build(); - - - BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), - bpelStatus, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); - - - throw bpmnFailureException; + throw new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, + ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build(); } return taskList; } - private TaskList buildTaskList(String taskId, String respBody) throws JSONException { + private TaskList buildTaskList(String taskId, String respBody) { TaskList taskList = new TaskList(); JSONObject variables = new JSONObject(respBody); @@ -317,7 +291,7 @@ public class TasksHandler { return taskList; } - private String getOptVariableValue(JSONObject variables, String name) throws JSONException { + private String getOptVariableValue(JSONObject variables, String name) { String variableEntry = variables.optString(name); String value = ""; if (!variableEntry.isEmpty()) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java index b5b548a266..e11732ddc4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java @@ -23,7 +23,7 @@ package org.onap.so.apihandlerinfra.infra.rest.handler; import java.io.IOException; import java.net.URL; import java.sql.Timestamp; -import java.util.HashMap; +import java.util.Map; import java.util.Optional; import javax.ws.rs.container.ContainerRequestContext; import org.apache.http.HttpStatus; @@ -63,7 +63,7 @@ public abstract class AbstractRestHandler { private static final Logger logger = LoggerFactory.getLogger(AbstractRestHandler.class); - public static final String conflictFailMessage = "Error: Locked instance - This %s (%s) " + public static final String CONFLICT_FAIL_MESSAGE = "Error: Locked instance - This %s (%s) " + "already has a request being worked with a status of %s (RequestId - %s). The existing request must finish or be cleaned up before proceeding."; @@ -95,22 +95,19 @@ public abstract class AbstractRestHandler { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ValidateException validateException = - new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID", - HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER) - .errorInfo(errorLoggerInfo).build(); - - throw validateException; + throw new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID", + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo) + .build(); } } - public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime, + public InfraActiveRequests duplicateCheck(Actions action, Map<String, String> instanceIdMap, long startTime, MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { return duplicateCheck(action, instanceIdMap, startTime, instanceName, requestScope, currentActiveReq); } - public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime, + public InfraActiveRequests duplicateCheck(Actions action, Map<String, String> instanceIdMap, long startTime, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { InfraActiveRequests dup = null; try { @@ -134,19 +131,19 @@ public abstract class AbstractRestHandler { public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage) throws RequestDbFailureException { - if (aq != null) { - if ((status == Status.FAILED) || (status == Status.COMPLETE)) { - aq.setStatusMessage(errorMessage); - aq.setProgress(100L); - aq.setRequestStatus(status.toString()); - Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis()); - aq.setEndTime(endTimeStamp); - try { - infraActiveRequestsClient.updateInfraActiveRequests(aq); - } catch (Exception e) { - logger.error("Error updating status", e); - } + if ((aq != null) && ((status == Status.FAILED) || (status == Status.COMPLETE))) { + + aq.setStatusMessage(errorMessage); + aq.setProgress(100L); + aq.setRequestStatus(status.toString()); + Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis()); + aq.setEndTime(endTimeStamp); + try { + infraActiveRequestsClient.updateInfraActiveRequests(aq); + } catch (Exception e) { + logger.error("Error updating status", e); } + } } @@ -178,15 +175,15 @@ public abstract class AbstractRestHandler { selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath)); } catch (Exception e) { selfLinkUrl = Optional.empty(); // ignore - logger.info(e.getMessage()); + logger.error(e.getMessage()); } return selfLinkUrl; } /** - * @param vfmoduleInstanceId + * @param instanceId * @param requestId - * @param response + * @param requestContext */ public ServiceInstancesResponse createResponse(String instanceId, String requestId, ContainerRequestContext requestContext) { @@ -202,13 +199,13 @@ public abstract class AbstractRestHandler { return response; } - public void checkDuplicateRequest(HashMap<String, String> instanceIdMap, ModelType modelType, String instanceName, + public void checkDuplicateRequest(Map<String, String> instanceIdMap, ModelType modelType, String instanceName, String requestId) throws RequestConflictedException { InfraActiveRequests conflictedRequest = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, modelType.toString()); if (conflictedRequest != null && !conflictedRequest.getRequestId().equals(requestId)) { - throw new RequestConflictedException(String.format(conflictFailMessage, modelType.toString(), instanceName, - conflictedRequest.getRequestStatus(), conflictedRequest.getRequestId())); + throw new RequestConflictedException(String.format(CONFLICT_FAIL_MESSAGE, modelType.toString(), + instanceName, conflictedRequest.getRequestStatus(), conflictedRequest.getRequestId())); } } diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryCustom.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryCustom.java index 47f8c6b50e..5a8e2e2f6c 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryCustom.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryCustom.java @@ -33,7 +33,7 @@ public interface InfraActiveRequestsRepositoryCustom { public InfraActiveRequests getRequestFromInfraActive(String requestId); - public InfraActiveRequests checkInstanceNameDuplicate(HashMap<String, String> instanceIdMap, String instanceName, + public InfraActiveRequests checkInstanceNameDuplicate(Map<String, String> instanceIdMap, String instanceName, String requestScope); public List<InfraActiveRequests> getOrchestrationFiltersFromInfraActive(Map<String, List<String>> orchestrationMap); diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java index d8c7c8f971..13ca33c2cf 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java @@ -152,7 +152,7 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep * java.lang.String, java.lang.String) */ @Override - public InfraActiveRequests checkInstanceNameDuplicate(final HashMap<String, String> instanceIdMap, + public InfraActiveRequests checkInstanceNameDuplicate(final Map<String, String> instanceIdMap, final String instanceName, final String requestScope) { final List<Predicate> predicates = new LinkedList<>(); diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java index 4d16d9c272..9be92ad93a 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java @@ -217,7 +217,7 @@ public class RequestsDbClient { return restTemplate.exchange(uri, HttpMethod.GET, entity, InfraActiveRequests.class).getBody(); } - public InfraActiveRequests checkInstanceNameDuplicate(HashMap<String, String> instanceIdMap, String instanceName, + public InfraActiveRequests checkInstanceNameDuplicate(Map<String, String> instanceIdMap, String instanceName, String requestScope) { HttpHeaders headers = getHttpHeaders(); URI uri = getUri(checkInstanceNameDuplicate); diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/data/controller/InstanceNameDuplicateCheckRequest.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/data/controller/InstanceNameDuplicateCheckRequest.java index 548bc25815..169d2353ec 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/data/controller/InstanceNameDuplicateCheckRequest.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/data/controller/InstanceNameDuplicateCheckRequest.java @@ -20,28 +20,28 @@ package org.onap.so.db.request.data.controller; -import java.util.HashMap; +import java.util.Map; public class InstanceNameDuplicateCheckRequest { - private HashMap<String, String> instanceIdMap; + private Map<String, String> instanceIdMap; private String instanceName; private String requestScope; public InstanceNameDuplicateCheckRequest() {} - public InstanceNameDuplicateCheckRequest(HashMap<String, String> instanceIdMap, String instanceName, + public InstanceNameDuplicateCheckRequest(Map<String, String> instanceIdMap, String instanceName, String requestScope) { this.instanceIdMap = instanceIdMap; this.instanceName = instanceName; this.requestScope = requestScope; } - public HashMap<String, String> getInstanceIdMap() { + public Map<String, String> getInstanceIdMap() { return instanceIdMap; } - public void setInstanceIdMap(HashMap<String, String> instanceIdMap) { + public void setInstanceIdMap(Map<String, String> instanceIdMap) { this.instanceIdMap = instanceIdMap; } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java index 1882ad5964..39217c75fa 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java @@ -77,12 +77,16 @@ public class RainyDayHandlerStatus implements Serializable { @Column(name = "SECONDARY_POLICY") private String secondaryPolicy; + @BusinessKey + @Column(name = "SERVICE_ROLE") + private String serviceRole; + @Override public String toString() { return new ToStringBuilder(this).append("id", id).append("flowName", flowName) .append("serviceType", serviceType).append("vnfType", vnfType).append("errorCode", errorCode) .append("errorMessage", errorMessage).append("workStep", workStep).append("policy", policy) - .append("secondaryPolicy", secondaryPolicy).toString(); + .append("secondaryPolicy", secondaryPolicy).append("serviceRole", serviceRole).toString(); } @Override @@ -93,13 +97,14 @@ public class RainyDayHandlerStatus implements Serializable { RainyDayHandlerStatus castOther = (RainyDayHandlerStatus) other; return new EqualsBuilder().append(flowName, castOther.flowName).append(serviceType, castOther.serviceType) .append(vnfType, castOther.vnfType).append(errorCode, castOther.errorCode) - .append(workStep, castOther.workStep).append(policy, castOther.policy).isEquals(); + .append(workStep, castOther.workStep).append(policy, castOther.policy) + .append(serviceRole, castOther.serviceRole).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder().append(flowName).append(serviceType).append(vnfType).append(errorCode) - .append(workStep).append(policy).toHashCode(); + .append(workStep).append(policy).append(serviceRole).toHashCode(); } public Integer getId() { @@ -174,5 +179,12 @@ public class RainyDayHandlerStatus implements Serializable { this.errorMessage = errorMessage; } + public String getServiceRole() { + return serviceRole; + } + + public void setServiceRole(String serviceRole) { + this.serviceRole = serviceRole; + } } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java index a18f870970..a959f2f5a1 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java @@ -137,6 +137,7 @@ public class CatalogDbClient { private static final String CLOUD_OWNER = "cloudOwner"; private static final String FLOW_NAME = "flowName"; private static final String ERROR_MESSAGE = "errorMessage"; + private static final String SERVICE_ROLE = "serviceRole"; private static final String SERVICE_TYPE = "serviceType"; private static final String VNF_TYPE = "vnfType"; private static final String ERROR_CODE = "errorCode"; @@ -638,7 +639,7 @@ public class CatalogDbClient { } public RainyDayHandlerStatus getRainyDayHandlerStatus(String flowName, String serviceType, String vnfType, - String errorCode, String workStep, String errorMessage) { + String errorCode, String workStep, String errorMessage, String serviceRole) { logger.debug( "Get Rainy Day Status - Flow Name {}, Service Type: {} , vnfType {} , errorCode {}, workStep {}, errorMessage {}", flowName, serviceType, vnfType, errorCode, workStep, errorMessage); @@ -646,7 +647,8 @@ public class CatalogDbClient { UriComponentsBuilder.fromUriString(endpoint + RAINY_DAY_HANDLER_MACRO + SEARCH + findRainyDayHandler) .queryParam(FLOW_NAME, flowName).queryParam(SERVICE_TYPE, serviceType) .queryParam(VNF_TYPE, vnfType).queryParam(ERROR_CODE, errorCode).queryParam(WORK_STEP, workStep) - .queryParam(ERROR_MESSAGE, errorMessage).build().encode().toUri()); + .queryParam(ERROR_MESSAGE, errorMessage).queryParam(SERVICE_ROLE, serviceRole).build().encode() + .toUri()); } public ServiceRecipe getFirstByServiceModelUUIDAndAction(String modelUUID, String action) { diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java index 6819657b78..efe078bbfc 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java @@ -32,10 +32,11 @@ public interface RainyDayHandlerStatusRepository extends JpaRepository<RainyDayH @Query(value = "SELECT * FROM rainy_day_handler_macro WHERE (FLOW_NAME = :flowName ) AND SERVICE_TYPE IN (:serviceType ,'*') " + " AND VNF_TYPE IN ( :vnfType , '*') AND ERROR_CODE IN (:errorCode ,'*') AND WORK_STEP IN (:workStep , '*' ) " + " AND ( :errorMessage REGEXP rainy_day_handler_macro.REG_EX_ERROR_MESSAGE OR REG_EX_ERROR_MESSAGE = '*') " - + " ORDER BY CASE WHEN :errorMessage REGEXP REG_EX_ERROR_MESSAGE THEN 0 WHEN ERROR_CODE != '*' THEN 1 WHEN VNF_TYPE != '*' THEN 2 WHEN SERVICE_TYPE != '*' THEN 3 ELSE 4 END LIMIT 1;", + + " AND SERVICE_ROLE IN ( :serviceRole , '*') " + + " ORDER BY CASE WHEN :errorMessage REGEXP REG_EX_ERROR_MESSAGE THEN 0 WHEN ERROR_CODE != '*' THEN 1 WHEN VNF_TYPE != '*' THEN 2 WHEN SERVICE_TYPE != '*' THEN 3 WHEN SERVICE_ROLE != '*' THEN 4 ELSE 5 END LIMIT 1;", nativeQuery = true) RainyDayHandlerStatus findRainyDayHandler(@Param("flowName") String flowName, @Param("serviceType") String serviceType, @Param("vnfType") String vnfType, @Param("errorCode") String errorCode, @Param("workStep") String workStep, - @Param("errorMessage") String errorMessage); + @Param("errorMessage") String errorMessage, @Param("serviceRole") String serviceRole); } |