diff options
543 files changed, 14957 insertions, 6522 deletions
@@ -44,17 +44,17 @@ committers: email: 'byung-woo.jun@ericsson.com' company: 'Ericsson' id: 'byungwoojun' - timezone: '' + timezone: 'America/New_York' - name: 'DeWayne Filppi' email: 'dewayne@cloudify.co' company: 'Cloudify' id: 'dfilppi' - timezone: '' - - name: 'Rob Daugherty' - email: 'rd472p@att.com' + timezone: 'America/Los_Angeles' + - name: 'Max Benjamin' + email: 'max.benjamin@att.com' company: 'ATT' - id: 'rd472p' - timezone: '' + id: 'mfour' + timezone: 'America/New_York' - name: 'Yan Yang' email: 'yangyanyj@chinamobile.com' company: 'China Mobile' @@ -64,7 +64,7 @@ committers: email: 'marcus.williams@intel.com' company: 'Intel' id: 'mgkwill' - timezone: 'America/Los Angeles' + timezone: 'America/Los_Angeles' - name: 'Sanchita Pathak' email: 'sanchita@techmahindra.com' company: 'Tech Mahindra' @@ -110,4 +110,9 @@ tsc: name: 'Subhash Kumar Singh' name: 'Lukasz Muszkieta' link: 'https://lists.onap.org/g/onap-tsc/message/4320' + - type: 'removal' + name: 'Rob Daugherty' + - type: 'addition' + name: 'Max Benjamin' + link: 'https://lists.onap.org/g/onap-tsc/message/4981?p=,,,20,0,0,0::Created,,committer,20,2,0,31638681' 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 567f849b36..b0c2d9430a 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 @@ -76,7 +76,7 @@ public class CinderClientImpl extends MsoCommonUtils { // list is set to false, otherwise an invalid URL is appended OpenStackRequest<Volumes> request = cinderClient.volumes().list(false).queryParam("limit", limit).queryParam("marker", marker); - return executeAndRecordOpenstackRequest(request); + return executeAndRecordOpenstackRequest(request, false); } catch (MsoException e) { logger.error("Error building Cinder Client", e); throw new CinderClientException("Error building Cinder Client", e); @@ -90,7 +90,7 @@ public class CinderClientImpl extends MsoCommonUtils { 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); + return executeAndRecordOpenstackRequest(request, false); } catch (MsoException e) { logger.error("Error building Cinder Client", e); throw new CinderClientException("Error building Cinder Client", e); diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/GlanceClientImpl.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/GlanceClientImpl.java index 57faaac717..698b605be3 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/GlanceClientImpl.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/GlanceClientImpl.java @@ -74,7 +74,7 @@ public class GlanceClientImpl extends MsoCommonUtils { // list is set to false, otherwise an invalid URL is appended OpenStackRequest<Images> request = glanceClient.images().list(false).queryParam("visibility", visibility) .queryParam("limit", limit).queryParam("marker", marker).queryParam("name", name); - return executeAndRecordOpenstackRequest(request); + return executeAndRecordOpenstackRequest(request, false); } catch (MsoException e) { logger.error("Error building Glance Client", e); throw new GlanceClientException("Error building Glance Client", e); diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java index a6a2f8402f..576784ae3e 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java @@ -98,19 +98,23 @@ public class MsoCommonUtils { */ protected <T> T executeAndRecordOpenstackRequest(OpenStackRequest<T> request) { + return executeAndRecordOpenstackRequest(request, true); + } - String requestType; - if (request.getClass().getEnclosingClass() != null) { - requestType = - request.getClass().getEnclosingClass().getSimpleName() + "." + request.getClass().getSimpleName(); - } else { - requestType = request.getClass().getSimpleName(); - } + /* + * Method to execute an Openstack command and track its execution time. For the metrics log, a category of + * "Openstack" is used along with a sub-category that identifies the specific call (using the real + * openstack-java-sdk classname of the OpenStackRequest<T> parameter). boolean isNoRetry - true if No retry; and + * false if Retry. + */ + protected <T> T executeAndRecordOpenstackRequest(OpenStackRequest<T> request, boolean shouldRetry) { int retryDelay = poConfig.getRetryDelay(); int retryCount = poConfig.getRetryCount(); String retryCodes = poConfig.getRetryCodes(); - + if (!shouldRetry) { + retryCodes = null; + } // Run the actual command. All exceptions will be propagated while (true) { try { @@ -127,8 +131,8 @@ public class MsoCommonUtils { retryCount--; retry = true; logger.debug( - "OpenStackResponseException ResponseCode: {} request:{} Retry indicated. Attempts remaining:{}", - code, requestType, retryCount); + "OpenStackResponseException ResponseCode: {} Retry indicated. Attempts remaining:{}", + code, retryCount); break; } } catch (NumberFormatException e1) { @@ -152,7 +156,7 @@ public class MsoCommonUtils { // Connection to Openstack failed if (retryCount > 0) { retryCount--; - logger.debug(" request: {} Retry indicated. Attempts remaining:{}", requestType, retryCount); + logger.debug("Retry indicated. Attempts remaining:{}", retryCount); try { Thread.sleep(retryDelay * 1000L); } catch (InterruptedException e1) { @@ -223,40 +227,29 @@ public class MsoCommonUtils { try { // Failed Heat calls return an Explanation entity body. Explanation explanation = re.getResponse().getErrorEntity(Explanation.class); - logger.error("{} {} Exception - Openstack Error on {} : {}", MessageEnum.RA_CONNECTION_EXCEPTION, - ErrorCode.DataError.getValue(), context, explanation.toString()); + logger.error("Exception - Openstack Error on {} : {}", context, explanation); String fullError = explanation.getExplanation() + ", error.type=" + explanation.getError().getType() + ", error.message=" + explanation.getError().getMessage(); - logger.debug(fullError); - me = new MsoOpenstackException(explanation.getCode(), explanation.getTitle(), - // explanation.getExplanation ()); - fullError); + logger.error(fullError); + me = new MsoOpenstackException(explanation.getCode(), explanation.getTitle(), fullError); } catch (Exception e2) { // Couldn't parse the body as an "Explanation". Report the original HTTP error. logger.error("{} {} Exception - HTTP Error on {}: {}, ", MessageEnum.RA_CONNECTION_EXCEPTION, ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2); - me = new MsoOpenstackException(re.getStatus(), re.getMessage(), ""); + me = new MsoOpenstackException(re.getStatus(), re.getMessage(), re.getMessage()); } // Add the context of the error me.addContext(context); - // Generate an alarm for 5XX and higher errors. - if (re.getStatus() >= 500) { - - } } else if (e instanceof OpenStackConnectException) { OpenStackConnectException ce = (OpenStackConnectException) e; - me = new MsoIOException(ce.getMessage()); me.addContext(context); - // Generate an alarm for all connection errors. - logger.error("{} {} Openstack Heat connection error on {}: ", MessageEnum.RA_CONNECTION_EXCEPTION, ErrorCode.DataError.getValue(), context, e); } - return me; } @@ -435,7 +428,7 @@ public class MsoCommonUtils { /** - * Gets the Nova client + * Gets the Keystone Authorization * * @param cloudSite the cloud site * @param tenantId the tenant id 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 376ed20ed0..7174bc0e31 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 @@ -31,6 +31,8 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.adapters.vdu.CloudInfo; import org.onap.so.adapters.vdu.PluginAction; @@ -43,15 +45,11 @@ import org.onap.so.adapters.vdu.VduPlugin; import org.onap.so.adapters.vdu.VduStateType; import org.onap.so.adapters.vdu.VduStatus; import org.onap.so.cloud.CloudConfig; -import org.onap.so.cloud.authentication.AuthenticationMethodFactory; import org.onap.so.cloud.authentication.KeystoneAuthHolder; -import org.onap.so.cloud.authentication.KeystoneV3Authentication; -import org.onap.so.cloud.authentication.ServiceEndpointNotFoundException; import org.onap.so.db.catalog.beans.CloudIdentity; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.HeatTemplate; import org.onap.so.db.catalog.beans.HeatTemplateParam; -import org.onap.so.db.catalog.beans.ServerType; import org.onap.so.db.request.beans.CloudApiRequests; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; @@ -59,15 +57,12 @@ import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.HeatStatus; import org.onap.so.openstack.beans.StackInfo; -import org.onap.so.openstack.exceptions.MsoAdapterException; import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; -import org.onap.so.openstack.exceptions.MsoIOException; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.onap.so.openstack.exceptions.MsoStackAlreadyExists; import org.onap.so.openstack.exceptions.MsoTenantNotFound; import org.onap.so.openstack.mappers.StackInfoMapper; -import org.onap.so.utils.CryptoUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; @@ -77,28 +72,31 @@ import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Strings; import com.woorea.openstack.base.client.OpenStackConnectException; import com.woorea.openstack.base.client.OpenStackRequest; import com.woorea.openstack.base.client.OpenStackResponseException; import com.woorea.openstack.heat.Heat; import com.woorea.openstack.heat.model.CreateStackParam; import com.woorea.openstack.heat.model.Events; +import com.woorea.openstack.heat.model.Resource; import com.woorea.openstack.heat.model.Resources; import com.woorea.openstack.heat.model.Stack; import com.woorea.openstack.heat.model.Stack.Output; import com.woorea.openstack.heat.model.Stacks; -import com.woorea.openstack.keystone.Keystone; -import com.woorea.openstack.keystone.model.Access; -import com.woorea.openstack.keystone.model.Authentication; -import com.woorea.openstack.keystone.utils.KeystoneUtils; + @Primary @Component public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { - private static final String TOKEN_AUTH = "TokenAuth"; + private static final String CREATE_COMPLETE = "CREATE_COMPLETE"; + + private static final String DELETE_COMPLETE = "DELETE_COMPLETE"; + + private static final String DELETE_IN_PROGRESS = "DELETE_IN_PROGRESS"; - private static final String QUERY_ALL_STACKS = "QueryAllStacks"; + private static final String CREATE_IN_PROGRESS = "CREATE_IN_PROGRESS"; private static final String DELETE_STACK = "DeleteStack"; @@ -118,29 +116,25 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { private Environment environment; @Autowired - private AuthenticationMethodFactory authenticationMethodFactory; - - @Autowired - private MsoTenantUtilsFactory tenantUtilsFactory; - - @Autowired - private KeystoneV3Authentication keystoneV3Authentication; - - @Autowired RequestsDbClient requestDBClient; @Autowired StackStatusHandler statusHandler; + @Autowired + NovaClientImpl novaClient; + private static final Logger logger = LoggerFactory.getLogger(MsoHeatUtils.class); // Properties names and variables (with default values) protected String createPollIntervalProp = "org.onap.so.adapters.po.pollInterval"; private String deletePollIntervalProp = "org.onap.so.adapters.po.pollInterval"; private String deletePollTimeoutProp = "org.onap.so.adapters.po.pollTimeout"; + private String pollingMultiplierProp = "org.onap.so.adapters.po.pollMultiplier"; 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 ObjectMapper JSON_MAPPER = new ObjectMapper(); @@ -225,6 +219,25 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { int timeoutMinutes, String environment, Map<String, Object> files, Map<String, Object> heatFiles, boolean backout) throws MsoException { + stripMultiCloudInputs(stackInputs); + CreateStackParam createStack = + createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles); + Stack currentStack = createStack(createStack, cloudSiteId, tenantId); + currentStack.setStackName(stackName); + if (pollForCompletion) { + currentStack = + processCreateStack(cloudSiteId, tenantId, timeoutMinutes, backout, currentStack, createStack, true); + } else { + currentStack = + queryHeatStack(currentStack.getStackName() + "/" + currentStack.getId(), cloudSiteId, tenantId); + } + return new StackInfoMapper(currentStack).map(); + } + + /** + * @param stackInputs + */ + protected void stripMultiCloudInputs(Map<String, ?> stackInputs) { // Take out the multicloud inputs, if present. for (String key : MsoMulticloudUtils.MULTICLOUD_INPUTS) { if (stackInputs.containsKey(key)) { @@ -234,36 +247,20 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { } } } + } - CreateStackParam stack = - createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles); - - // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = - cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); - logger.debug(FOUND, cloudSite); - // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) - // This could throw MsoTenantNotFound or MsoOpenstackException (both propagated) - Heat heatClient = getHeatClient(cloudSite, tenantId); - logger.debug(FOUND, heatClient); - - logger.debug("Ready to Create Stack ({}) with input params: {}", heatTemplate, stackInputs); - - Stack heatStack = null; + protected Stack createStack(CreateStackParam stack, String cloudSiteId, String tenantId) throws MsoException { try { - OpenStackRequest<Stack> request = heatClient.getStacks().create(stack); - saveStackRequest(request, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID), stackName); - CloudIdentity cloudIdentity = cloudSite.getIdentityService(); - request.header("X-Auth-User", cloudIdentity.getMsoId()); - request.header("X-Auth-Key", CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass())); - heatStack = executeAndRecordOpenstackRequest(request); + OpenStackRequest<Stack> request = getHeatClient(cloudSiteId, tenantId).getStacks().create(stack); + saveStackRequest(stack, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID), stack.getStackName()); + return executeAndRecordOpenstackRequest(request); } catch (OpenStackResponseException e) { if (e.getStatus() == 409) { - MsoStackAlreadyExists me = new MsoStackAlreadyExists(stackName, tenantId, cloudSiteId); + MsoStackAlreadyExists me = new MsoStackAlreadyExists(stack.getStackName(), tenantId, cloudSiteId); me.addContext(CREATE_STACK); throw me; } else { - logger.debug("ERROR STATUS = {},\n{}\n{}", e.getStatus(), e.getMessage(), e.getLocalizedMessage()); + logger.error("ERROR STATUS = {},\n{}\n{}", e.getStatus(), e.getMessage(), e.getLocalizedMessage()); throw heatExceptionToMsoException(e, CREATE_STACK); } } catch (OpenStackConnectException e) { @@ -271,242 +268,158 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { } catch (RuntimeException e) { throw runtimeExceptionToMsoException(e, CREATE_STACK); } + } - // Subsequent access by the canonical name "<stack name>/<stack-id>". - // Otherwise, simple query by name returns a 302 redirect. - // NOTE: This is specific to the v1 Orchestration API. - String canonicalName = stackName + "/" + heatStack.getId(); - if (pollForCompletion) { - heatStack = pollStackForCompletion(cloudSiteId, tenantId, stackName, timeoutMinutes, backout, heatClient, - heatStack, canonicalName); + protected Stack processCreateStack(String cloudSiteId, String tenantId, int timeoutMinutes, boolean backout, + Stack heatStack, CreateStackParam stackCreate, boolean keyPairCleanUp) throws MsoException { + Stack latestStack = null; + try { + latestStack = pollStackForStatus(timeoutMinutes, heatStack, CREATE_IN_PROGRESS, cloudSiteId, tenantId); + } catch (MsoException me) { + logger.error("Exception in Create Stack", me); + } + return postProcessStackCreate(latestStack, backout, timeoutMinutes, keyPairCleanUp, cloudSiteId, tenantId, + stackCreate); + } + + protected Stack postProcessStackCreate(Stack stack, boolean backout, int timeoutMinutes, boolean cleanUpKeyPair, + String cloudSiteId, String tenantId, CreateStackParam stackCreate) throws MsoException { + if (stack == null) { + throw new StackCreationException("Unknown Error in Stack Creation"); } else { - // Get initial status, since it will have been null after the create. - heatStack = queryHeatStack(heatClient, canonicalName); - logger.debug(heatStack.getStackStatus()); + 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); + } + } else { + return stack; + } + } + } + + protected Stack pollStackForStatus(int timeoutMinutes, Stack stack, String stackStatus, String cloudSiteId, + String tenantId) throws MsoException { + int pollingFrequency = + Integer.parseInt(this.environment.getProperty(createPollIntervalProp, CREATE_POLL_INTERVAL_DEFAULT)); + int pollingMultiplier = + Integer.parseInt(this.environment.getProperty(pollingMultiplierProp, pollingMultiplierDefault)); + int numberOfPollingAttempts = Math.floorDiv((timeoutMinutes * pollingMultiplier), pollingFrequency); + Heat heatClient = getHeatClient(cloudSiteId, tenantId); + Stack latestStack = null; + while (true) { + latestStack = queryHeatStack(heatClient, stack.getStackName() + "/" + stack.getId()); + statusHandler.updateStackStatus(latestStack); + logger.debug("Polling: {} ({})", latestStack.getStackStatus(), latestStack.getStackName()); + if (stackStatus.equals(latestStack.getStackStatus())) { + if (numberOfPollingAttempts <= 0) { + logger.error("Polling of stack timed out with Status: {}", latestStack.getStackStatus()); + return latestStack; + } + sleep(pollingFrequency * 1000L); + numberOfPollingAttempts -= 1; + } else { + return latestStack; + } } - return new StackInfoMapper(heatStack).map(); } - private void saveStackRequest(OpenStackRequest<Stack> request, String requestId, String stackName) { + protected void saveStackRequest(CreateStackParam request, String requestId, String stackName) { try { ObjectMapper mapper = new ObjectMapper(); InfraActiveRequests foundRequest = requestDBClient.getInfraActiveRequestbyRequestId(requestId); - String stackRequest = mapper.writeValueAsString(request.entity()); + String stackRequest = mapper.writeValueAsString(request.getParameters()); CloudApiRequests cloudReq = new CloudApiRequests(); cloudReq.setCloudIdentifier(stackName); cloudReq.setRequestBody(stackRequest); cloudReq.setRequestId(requestId); - foundRequest.getCloudApiRequests().add(cloudReq); + CloudApiRequests foundCloudReq = foundRequest.getCloudApiRequests().stream() + .filter(cloudReqToFind -> stackName.equals(cloudReq.getCloudIdentifier())).findAny().orElse(null); + if (foundCloudReq != null) { + foundCloudReq.setRequestBody(stackRequest); + } else { + foundRequest.getCloudApiRequests().add(cloudReq); + } requestDBClient.updateInfraActiveRequests(foundRequest); } catch (Exception e) { logger.error("Error updating in flight request with Openstack Create Request", e); } } - private Stack pollStackForCompletion(String cloudSiteId, String tenantId, String stackName, int timeoutMinutes, - boolean backout, Heat heatClient, Stack heatStack, String canonicalName) - throws MsoException, MsoOpenstackException { - int createPollInterval = - Integer.parseInt(this.environment.getProperty(createPollIntervalProp, CREATE_POLL_INTERVAL_DEFAULT)); - int pollTimeout = (timeoutMinutes * 60) + createPollInterval; - int deletePollInterval = createPollInterval; - int deletePollTimeout = pollTimeout; - boolean createTimedOut = false; - StringBuilder stackErrorStatusReason = new StringBuilder(""); - logger.debug("createPollInterval={}, pollTimeout={}", createPollInterval, pollTimeout); - - while (true) { - try { - heatStack = queryHeatStack(heatClient, canonicalName); - statusHandler.updateStackStatus(heatStack, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); - logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName); - try { - logger.debug("Current stack {}", this.getOutputsAsStringBuilder(heatStack).toString()); - } catch (Exception e) { - logger.debug("an error occurred trying to print out the current outputs of the stack", e); - } - - if ("CREATE_IN_PROGRESS".equals(heatStack.getStackStatus())) { - if (pollTimeout <= 0) { - logger.error("{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Create stack timeout", - MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, - heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue()); - createTimedOut = true; - break; - } - sleep(createPollInterval * 1000L); - pollTimeout -= createPollInterval; - logger.debug("pollTimeout remaining: {}", pollTimeout); - } else { - stackErrorStatusReason.append( - "Stack error (" + heatStack.getStackStatus() + "): " + heatStack.getStackStatusReason()); - break; - } - } catch (MsoException me) { - // Cannot query the stack status. Something is wrong. - // Try to roll back the stack - if (!backout) { - logger.warn("{} Exception in Create Stack, stack deletion suppressed {}", - MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue()); - } else { - try { - logger.debug( - "Create Stack error - unable to query for stack status - attempting to delete stack: {}" - + " - This will likely fail and/or we won't be able to query to see if delete worked", - canonicalName); - OpenStackRequest<Void> request = heatClient.getStacks().deleteByName(canonicalName); - executeAndRecordOpenstackRequest(request); - boolean deleted = false; - while (!deleted) { - try { - heatStack = queryHeatStack(heatClient, canonicalName); - statusHandler.updateStackStatus(heatStack, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); - if (heatStack != null) { - logger.debug(heatStack.getStackStatus()); - if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) { - if (deletePollTimeout <= 0) { - logger.error( - "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout", - MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, - stackName, heatStack.getStackStatus(), - ErrorCode.AvailabilityError.getValue()); - break; - } else { - sleep(deletePollInterval * 1000L); - deletePollTimeout -= deletePollInterval; - } - } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())) { - logger.debug("DELETE_COMPLETE for {}", canonicalName); - deleted = true; - continue; - } else { - // got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and - // evaluate - break; - } - } else { - // assume if we can't find it - it's deleted - logger.debug("heatStack returned null - assume the stack {} has been deleted", - canonicalName); - deleted = true; - continue; - } - - } catch (Exception e3) { - // Just log this one. We will report the original exception. - logger.error(EXCEPTION_ROLLING_BACK_STACK, MessageEnum.RA_CREATE_STACK_ERR, - ErrorCode.BusinessProcesssError.getValue(), e3); - } - } - } catch (Exception e2) { - // Just log this one. We will report the original exception. - logger.error(EXCEPTION_ROLLING_BACK_STACK, MessageEnum.RA_CREATE_STACK_ERR, - ErrorCode.BusinessProcesssError.getValue(), e2); - } - } + protected boolean isKeyPairFailure(String errorMessage) { + return Pattern.compile(".*Key pair.*already exists.*").matcher(errorMessage).matches(); + } - // Propagate the original exception from Stack Query. - me.addContext(CREATE_STACK); - throw me; - } + protected Stack handleUnknownCreateStackFailure(Stack stack, int timeoutMinutes, String cloudSiteId, + String tenantId) throws MsoException { + if (stack != null && !Strings.isNullOrEmpty(stack.getStackName()) && !Strings.isNullOrEmpty(stack.getId())) { + OpenStackRequest<Void> request = getHeatClient(cloudSiteId, tenantId).getStacks() + .deleteByName(stack.getStackName() + "/" + stack.getId()); + executeAndRecordOpenstackRequest(request); + Stack currentStack = pollStackForStatus(timeoutMinutes, stack, DELETE_IN_PROGRESS, cloudSiteId, tenantId); + postProcessStackDelete(currentStack); + return currentStack; + } else { + throw new StackCreationException("Cannot Find Stack Name or Id"); } + } - if (!"CREATE_COMPLETE".equals(heatStack.getStackStatus())) { - logger.error("{} Create Stack error: Polling complete with non-success status: {}, {} {} ", - MessageEnum.RA_CREATE_STACK_ERR, heatStack.getStackStatus(), heatStack.getStackStatusReason(), - ErrorCode.BusinessProcesssError.getValue()); + protected void postProcessStackDelete(Stack stack) throws MsoException { + logger.info("Performing post processing on delete stack {}", stack); + if (stack != null && !Strings.isNullOrEmpty(stack.getStackStatus())) { + if (!DELETE_COMPLETE.equals(stack.getStackStatus())) + throw new StackRollbackException("Stack Deletion completed with status: " + stack.getStackStatus() + + " Status Reason: " + stack.getStackStatusReason()); + } else { + throw new StackRollbackException("Cannot Find Stack Name or Id"); + } + } - // Rollback the stack creation, since it is in an indeterminate state. - if (!backout) { - logger.warn( - "{} Create Stack errored, stack deletion suppressed {} Create Stack error, stack deletion suppressed", - MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue()); - } else { - try { - logger.debug("Create Stack errored - attempting to DELETE stack: {}", canonicalName); - logger.debug("deletePollInterval={}, deletePollTimeout={}", deletePollInterval, deletePollTimeout); - OpenStackRequest<Void> request = heatClient.getStacks().deleteByName(canonicalName); - executeAndRecordOpenstackRequest(request); - boolean deleted = false; - while (!deleted) { - try { - heatStack = queryHeatStack(heatClient, canonicalName); - if (heatStack != null) { - logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName); - if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) { - if (deletePollTimeout <= 0) { - logger.error( - "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout", - MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, - heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue()); - break; - } else { - sleep(deletePollInterval * 1000L); - deletePollTimeout -= deletePollInterval; - logger.debug("deletePollTimeout remaining: {}", deletePollTimeout); - } - } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())) { - logger.debug("DELETE_COMPLETE for {}", canonicalName); - deleted = true; - continue; - } else if ("DELETE_FAILED".equals(heatStack.getStackStatus())) { - // Warn about this (?) - but still throw the original exception - logger.warn( - "{} Create Stack errored, stack deletion FAILED {} Create Stack error, stack deletion FAILED", - MessageEnum.RA_CREATE_STACK_ERR, - ErrorCode.BusinessProcesssError.getValue()); - logger.debug( - "Stack deletion FAILED on a rollback of a create - {}, status={}, reason={}", - canonicalName, heatStack.getStackStatus(), - heatStack.getStackStatusReason()); - break; - } else { - // got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and - // evaluate - break; - } - } else { - // assume if we can't find it - it's deleted - logger.debug("heatStack returned null - assume the stack {} has been deleted", - canonicalName); - deleted = true; - continue; - } - - } catch (MsoException me2) { - // We got an exception on the delete - don't throw this exception - throw the original - - // just log. - logger.debug("Exception thrown trying to delete {} on a create->rollback: {} ", - canonicalName, me2.getContextMessage(), me2); - logger.warn("{} Create Stack errored, then stack deletion FAILED - exception thrown {} {}", - MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), - me2.getContextMessage()); - } + protected Stack handleKeyPairConflict(String cloudSiteId, String tenantId, CreateStackParam stackCreate, + int timeoutMinutes, boolean backout, Stack stack) throws MsoException { + logger.info("Keypair conflict found on stack, attempting to clean up"); - } // end while !deleted - StringBuilder errorContextMessage; - if (createTimedOut) { - errorContextMessage = new StringBuilder("Stack Creation Timeout"); - } else { - errorContextMessage = stackErrorStatusReason; - } - if (deleted) { - errorContextMessage.append(" - stack successfully deleted"); - } else { - errorContextMessage.append(" - encountered an error trying to delete the stack"); - } - } catch (Exception e2) { - // shouldn't happen - but handle - logger.error(EXCEPTION_ROLLING_BACK_STACK, MessageEnum.RA_CREATE_STACK_ERR, - ErrorCode.BusinessProcesssError.getValue(), e2); - } + Resources resources = queryStackResources(cloudSiteId, tenantId, stackCreate.getStackName(), 2); + List<Resource> keyPairs = resources.getList().stream() + .filter(p -> "OS::Nova::KeyPair".equalsIgnoreCase(p.getType())).collect(Collectors.toList()); + keyPairs.stream().forEach(keyPair -> { + try { + novaClient.deleteKeyPair(cloudSiteId, tenantId, keyPair.getLogicalResourceId()); + } catch (MsoCloudSiteNotFound | NovaClientException e) { + logger.warn("Could not delete keypair", e); } - MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString()); - me.addContext(CREATE_STACK); - throw me; - } - return heatStack; + }); + handleUnknownCreateStackFailure(stack, timeoutMinutes, cloudSiteId, tenantId); + Stack newStack = createStack(stackCreate, cloudSiteId, tenantId); + newStack.setStackName(stackCreate.getStackName()); + return processCreateStack(cloudSiteId, tenantId, timeoutMinutes, backout, newStack, stackCreate, false); } /** @@ -523,19 +436,9 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { public StackInfo queryStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName) throws MsoException { logger.debug("Query HEAT stack: {} in tenant {}", stackName, tenantId); - - // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = - cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); - logger.debug(FOUND, cloudSite.toString()); - - // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) Heat heatClient = null; try { - heatClient = getHeatClient(cloudSite, tenantId); - if (heatClient != null) { - logger.debug(FOUND, heatClient.toString()); - } + heatClient = getHeatClient(cloudSiteId, tenantId); } catch (MsoTenantNotFound e) { // Tenant doesn't exist, so stack doesn't either logger.debug("Tenant with id " + tenantId + "not found.", e); @@ -583,11 +486,9 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { */ public StackInfo deleteStack(String tenantId, String cloudOwner, String cloudSiteId, String stackName, boolean pollForCompletion) throws MsoException { - CloudSite cloudSite = - cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); Heat heatClient = null; try { - heatClient = getHeatClient(cloudSite, tenantId); + heatClient = getHeatClient(cloudSiteId, tenantId); } catch (MsoTenantNotFound e) { logger.debug("Tenant with id " + tenantId + "not found.", e); return new StackInfo(stackName, HeatStatus.NOTFOUND); @@ -600,7 +501,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { // OK if stack not found, perform a query first Stack heatStack = queryHeatStack(heatClient, stackName); - if (heatStack == null || "DELETE_COMPLETE".equals(heatStack.getStackStatus())) { + if (heatStack == null || DELETE_COMPLETE.equals(heatStack.getStackStatus())) { // Not found. Return a StackInfo with status NOTFOUND return new StackInfo(stackName, HeatStatus.NOTFOUND); } @@ -637,16 +538,16 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { // Requery the stack for current status. // It will probably still exist with "DELETE_IN_PROGRESS" status. heatStack = queryHeatStack(heatClient, canonicalName); - statusHandler.updateStackStatus(heatStack, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + statusHandler.updateStackStatus(heatStack); if (pollForCompletion) { int pollInterval = Integer .parseInt(this.environment.getProperty(deletePollIntervalProp, "" + DELETE_POLL_INTERVAL_DEFAULT)); int pollTimeout = Integer .parseInt(this.environment.getProperty(deletePollTimeoutProp, "" + DELETE_POLL_INTERVAL_DEFAULT)); - statusHandler.updateStackStatus(heatStack, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + statusHandler.updateStackStatus(heatStack); // When querying by canonical name, Openstack returns DELETE_COMPLETE status // instead of "404" (which would result from query by stack name). - while (heatStack != null && !"DELETE_COMPLETE".equals(heatStack.getStackStatus())) { + while (heatStack != null && !DELETE_COMPLETE.equals(heatStack.getStackStatus())) { logger.debug("Stack status: {}", heatStack.getStackStatus()); if ("DELETE_FAILED".equals(heatStack.getStackStatus())) { @@ -695,58 +596,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { } /** - * Query for all stacks in a tenant site. This call will return a List of StackInfo objects, one for each deployed - * stack. - * - * Note that this is limited to a single site. To ensure that a tenant is truly empty would require looping across - * all tenant endpoints. - * - * @param tenantId The Openstack ID of the tenant to query - * @param cloudSiteId The cloud identifier (may be a region) in which to query. - * @return A List of StackInfo objects - * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception. - * @throws MsoCloudSiteNotFound - */ - public List<StackInfo> queryAllStacks(String tenantId, String cloudSiteId) throws MsoException { - // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = - cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); - // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) - Heat heatClient = getHeatClient(cloudSite, tenantId); - - try { - OpenStackRequest<Stacks> request = heatClient.getStacks().list(); - Stacks stacks = executeAndRecordOpenstackRequest(request); - - List<StackInfo> stackList = new ArrayList<>(); - - // Not sure if returns an empty list or null if no stacks exist - if (stacks != null) { - for (Stack stack : stacks) { - stackList.add(new StackInfoMapper(stack).map()); - } - } - - return stackList; - } catch (OpenStackResponseException e) { - if (e.getStatus() == 404) { - // Not sure if this can happen, but return an empty list - logger.debug("queryAllStacks - stack not found: "); - return new ArrayList<>(); - } else { - // Convert the OpenStackResponseException to an MsoOpenstackException - throw heatExceptionToMsoException(e, QUERY_ALL_STACKS); - } - } catch (OpenStackConnectException e) { - // Error connecting to Openstack instance. Convert to an MsoException - throw heatExceptionToMsoException(e, QUERY_ALL_STACKS); - } catch (RuntimeException e) { - // Catch-all - throw runtimeExceptionToMsoException(e, QUERY_ALL_STACKS); - } - } - - /** * Validate parameters to be passed to Heat template. This method performs three functions: 1. Apply default values * to parameters which have them defined 2. Report any required parameters that are missing. This will generate an * exception in the caller, since stack create/update operations would fail. 3. Report and remove any extraneous @@ -802,8 +651,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { return updatedParams; } - // --------------------------------------------------------------- - // PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS /** * Get a Heat client for the Openstack Identity service. This requires a 'member'-level userId + password, which @@ -815,76 +662,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { * * @return an authenticated Heat object */ - public Heat getHeatClient(CloudSite cloudSite, String tenantId) throws MsoException { - String cloudId = cloudSite.getId(); - // For DCP/LCP, the region should be the cloudId. - String region = cloudSite.getRegionId(); - - // Obtain an MSO token for the tenant - CloudIdentity cloudIdentity = cloudSite.getIdentityService(); - logger.debug(FOUND, cloudIdentity.toString()); - MsoTenantUtils tenantUtils = - tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType()); - String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity); - logger.debug("keystoneUrl={}", keystoneUrl); - String heatUrl = null; - String tokenId = null; - try { - if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) { - Keystone keystoneTenantClient = new Keystone(keystoneUrl); - Access access = null; - - Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity); - - OpenStackRequest<Access> request = - keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId); - - access = executeAndRecordOpenstackRequest(request); - - try { - logger.debug("access={}", access.toString()); - heatUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "orchestration", region, - "public"); - logger.debug("heatUrl={}, region={}", heatUrl, region); - } catch (RuntimeException e) { - // This comes back for not found (probably an incorrect region ID) - String error = "AIC did not match an orchestration service for: region=" + region + ",cloud=" - + cloudIdentity.getIdentityUrl(); - throw new MsoAdapterException(error, e); - } - tokenId = access.getToken().getId(); - } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) { - try { - KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "orchestration"); - tokenId = holder.getId(); - heatUrl = holder.getServiceUrl(); - } catch (ServiceEndpointNotFoundException e) { - // This comes back for not found (probably an incorrect region ID) - String error = "cloud did not match an orchestration service for: region=" + region + ",cloud=" - + cloudIdentity.getIdentityUrl(); - throw new MsoAdapterException(error, e); - } - } - } catch (OpenStackResponseException e) { - if (e.getStatus() == 401) { - // Authentication error. - String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId(); - - throw new MsoAdapterException(error); - } else { - throw keystoneErrorToMsoException(e, TOKEN_AUTH); - } - } catch (OpenStackConnectException e) { - // Connection to Openstack failed - MsoIOException me = new MsoIOException(e.getMessage(), e); - me.addContext(TOKEN_AUTH); - throw me; - } catch (RuntimeException e) { - // Catch-all - throw runtimeExceptionToMsoException(e, TOKEN_AUTH); - } - Heat heatClient = new Heat(heatUrl); - heatClient.token(tokenId); + public Heat getHeatClient(String cloudSiteId, String tenantId) throws MsoException { + KeystoneAuthHolder keystone = getKeystoneAuthHolder(cloudSiteId, tenantId, "orchestration"); + Heat heatClient = new Heat(keystone.getServiceUrl()); + heatClient.token(keystone.getId()); return heatClient; } @@ -928,6 +709,13 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { } } + public Stack queryHeatStack(String stackName, String cloudSiteId, String tenantId) throws MsoException { + if (stackName == null) { + return null; + } + return queryHeatStack(getHeatClient(cloudSiteId, tenantId), stackName); + } + public Map<String, Object> queryStackForOutputs(String cloudSiteId, String cloudOwner, String tenantId, String stackName) throws MsoException { @@ -990,42 +778,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { return; } - public StringBuilder requestToStringBuilder(CreateStackParam stack) { - StringBuilder sb = new StringBuilder(); - sb.append("Stack:\n"); - sb.append("\tStackName: " + stack.getStackName()); - sb.append("\tTemplateUrl: " + stack.getTemplateUrl()); - sb.append("\tTemplate: " + stack.getTemplate()); - sb.append("\tEnvironment: " + stack.getEnvironment()); - sb.append("\tTimeout: " + stack.getTimeoutMinutes()); - sb.append("\tParameters:\n"); - Map<String, Object> params = stack.getParameters(); - if (params == null || params.size() < 1) { - sb.append("\nNONE"); - } else { - for (String key : params.keySet()) { - if (params.get(key) instanceof String) { - sb.append("\n").append(key).append("=").append((String) params.get(key)); - } else if (params.get(key) instanceof JsonNode) { - String jsonStringOut = this.convertNode((JsonNode) params.get(key)); - sb.append("\n").append(key).append("=").append(jsonStringOut); - } else if (params.get(key) instanceof Integer) { - String integerOut = "" + params.get(key); - sb.append("\n").append(key).append("=").append(integerOut); - - } else { - try { - String str = params.get(key).toString(); - sb.append("\n").append(key).append("=").append(str); - } catch (Exception e) { - logger.debug("Exception :", e); - } - } - } - } - return sb; - } - private String convertNode(final JsonNode node) { try { final Object obj = JSON_MAPPER.treeToValue(node, Object.class); @@ -1193,44 +945,32 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { HashMap<String, HeatTemplateParam> paramAliases = new HashMap<>(); if (inputs == null) { - logger.debug("convertInputMap - inputs is null - nothing to do here"); return new HashMap<>(); } - - logger.debug("convertInputMap in MsoHeatUtils called, with {} inputs, and template {}", inputs.size(), - template.getArtifactUuid()); try { - logger.debug(template.toString()); Set<HeatTemplateParam> paramSet = template.getParameters(); - logger.debug("paramSet has {} entries", paramSet.size()); } catch (Exception e) { logger.debug("Exception occurred in convertInputMap {} :", e.getMessage(), e); } for (HeatTemplateParam htp : template.getParameters()) { - logger.debug("Adding {}", htp.getParamName()); params.put(htp.getParamName(), htp); if (htp.getParamAlias() != null && !"".equals(htp.getParamAlias())) { logger.debug("\tFound ALIAS {} -> {}", htp.getParamName(), htp.getParamAlias()); paramAliases.put(htp.getParamAlias(), htp); } } - logger.debug("Now iterate through the inputs..."); + for (String key : inputs.keySet()) { - logger.debug("key={}", key); boolean alias = false; String realName = null; if (!params.containsKey(key)) { - logger.debug("{} is not a parameter in the template! - check for an alias", key); // add check here for an alias if (!paramAliases.containsKey(key)) { - logger.debug("The parameter {} is in the inputs, but it's not a parameter for this template - omit", - key); continue; } else { alias = true; realName = paramAliases.get(key).getParamName(); - logger.debug("FOUND AN ALIAS! Will use {} in lieu of give key/alias {}", realName, key); } } String type = params.get(key).getParamType(); @@ -1238,7 +978,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { logger.debug("**PARAM_TYPE is null/empty for {}, will default to string", key); type = "string"; } - logger.debug("Parameter: {} is of type {}", key, type); if ("string".equalsIgnoreCase(type)) { // Easiest! String str = inputs.get(key) != null ? inputs.get(key).toString() : null; @@ -1507,47 +1246,39 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { public Resources queryStackResources(String cloudSiteId, String tenantId, String stackName, int nestedDepth) throws MsoException { - CloudSite cloudSite = - cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); - Heat heatClient = getHeatClient(cloudSite, tenantId); + Heat heatClient = getHeatClient(cloudSiteId, tenantId); OpenStackRequest<Resources> request = heatClient.getResources().listResources(stackName).queryParam("nested_depth", nestedDepth); - return executeAndRecordOpenstackRequest(request); + return executeAndRecordOpenstackRequest(request, false); } public Events queryStackEvents(String cloudSiteId, String tenantId, String stackName, String stackId, int nestedDepth) throws MsoException { - CloudSite cloudSite = - cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); - Heat heatClient = getHeatClient(cloudSite, tenantId); + Heat heatClient = getHeatClient(cloudSiteId, tenantId); OpenStackRequest<Events> request = heatClient.getEvents().listEvents(stackName, stackId).queryParam("nested_depth", nestedDepth); - return executeAndRecordOpenstackRequest(request); + return executeAndRecordOpenstackRequest(request, false); } public Stacks queryStacks(String cloudSiteId, String tenantId, int limit, String marker) throws MsoCloudSiteNotFound, HeatClientException { - CloudSite cloudSite = - cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); Heat heatClient; try { - heatClient = getHeatClient(cloudSite, tenantId); + heatClient = getHeatClient(cloudSiteId, tenantId); } catch (MsoException e) { logger.error("Error Creating Heat Client", e); throw new HeatClientException("Error Creating Heat Client", e); } OpenStackRequest<Stacks> request = heatClient.getStacks().list().queryParam("limit", limit).queryParam("marker", marker); - return executeAndRecordOpenstackRequest(request); + return executeAndRecordOpenstackRequest(request, false); } public <R> R executeHeatClientRequest(String url, String cloudSiteId, String tenantId, Class<R> returnType) throws MsoException { - CloudSite cloudSite = - cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); - Heat heatClient = getHeatClient(cloudSite, tenantId); + Heat heatClient = getHeatClient(cloudSiteId, tenantId); OpenStackRequest<R> request = heatClient.get(url, returnType); - return executeAndRecordOpenstackRequest(request); + return executeAndRecordOpenstackRequest(request, false); } protected void sleep(long time) { diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java index a2e386adea..684fe98bf3 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java @@ -24,25 +24,14 @@ package org.onap.so.openstack.utils; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.woorea.openstack.base.client.OpenStackBaseException; -import com.woorea.openstack.base.client.OpenStackRequest; -import com.woorea.openstack.heat.Heat; -import com.woorea.openstack.heat.model.Stack; -import com.woorea.openstack.heat.model.Stack.Output; -import com.woorea.openstack.heat.model.UpdateStackParam; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.StackInfo; -import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.onap.so.openstack.exceptions.MsoStackNotFound; @@ -52,6 +41,15 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.woorea.openstack.base.client.OpenStackBaseException; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.heat.Heat; +import com.woorea.openstack.heat.model.Stack; +import com.woorea.openstack.heat.model.Stack.Output; +import com.woorea.openstack.heat.model.UpdateStackParam; @Component public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { @@ -138,12 +136,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { haveHeatFiles = false; } - // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = - cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); - // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) - // This could throw MsoTenantNotFound or MsoOpenstackException (both propagated) - Heat heatClient = getHeatClient(cloudSite, tenantId); + Heat heatClient = getHeatClient(cloudSiteId, tenantId); // Perform a query first to get the current status Stack heatStack = queryHeatStack(heatClient, stackName); diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java index ab93a6c4c6..f74a3f5f53 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java @@ -23,19 +23,6 @@ package org.onap.so.openstack.utils; -import com.woorea.openstack.base.client.OpenStackBaseException; -import com.woorea.openstack.base.client.OpenStackConnectException; -import com.woorea.openstack.base.client.OpenStackRequest; -import com.woorea.openstack.base.client.OpenStackResponseException; -import com.woorea.openstack.keystone.Keystone; -import com.woorea.openstack.keystone.model.Access; -import com.woorea.openstack.keystone.model.Authentication; -import com.woorea.openstack.keystone.model.Metadata; -import com.woorea.openstack.keystone.model.Role; -import com.woorea.openstack.keystone.model.Roles; -import com.woorea.openstack.keystone.model.Tenant; -import com.woorea.openstack.keystone.model.User; -import com.woorea.openstack.keystone.utils.KeystoneUtils; import java.util.HashMap; import java.util.Map; import java.util.Optional; @@ -54,6 +41,19 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import com.woorea.openstack.base.client.OpenStackBaseException; +import com.woorea.openstack.base.client.OpenStackConnectException; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.base.client.OpenStackResponseException; +import com.woorea.openstack.keystone.Keystone; +import com.woorea.openstack.keystone.model.Access; +import com.woorea.openstack.keystone.model.Authentication; +import com.woorea.openstack.keystone.model.Metadata; +import com.woorea.openstack.keystone.model.Role; +import com.woorea.openstack.keystone.model.Roles; +import com.woorea.openstack.keystone.model.Tenant; +import com.woorea.openstack.keystone.model.User; +import com.woorea.openstack.keystone.utils.KeystoneUtils; @Component public class MsoKeystoneUtils extends MsoTenantUtils { @@ -414,7 +414,6 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // Get the Identity service URL. Throws runtime exception if not found per region. String adminUrl = null; try { - // TODO: FOR TESTING!!!! adminUrl = KeystoneUtils.findEndpointURL(access.getServiceCatalog(), "identity", region, "public"); adminUrl = adminUrl.replaceFirst("5000", "35357"); } catch (RuntimeException e) { diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java index 1db0411f7c..49ba336e3f 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java @@ -157,7 +157,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { sdncDirectives = (String) stackInputs.get(key); } if (key == USER_DIRECTIVES) { - sdncDirectives = (String) stackInputs.get(key); + userDirectives = (String) stackInputs.get(key); } if (key == TEMPLATE_TYPE) { templateType = (String) stackInputs.get(key); diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java index 6f08afc55f..069c6c7c5b 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java @@ -382,7 +382,7 @@ public class MsoNeutronUtils extends MsoCommonUtils { Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity); OpenStackRequest<Access> request = keystoneTenantClient.tokens().authenticate(credentials).withTenantId(tenantId); - access = executeAndRecordOpenstackRequest(request); + access = executeAndRecordOpenstackRequest(request, true); try { @@ -499,7 +499,7 @@ public class MsoNeutronUtils extends MsoCommonUtils { try { OpenStackRequest<Port> request = neutronClient.ports().show(neutronPortId); - Port port = executeAndRecordOpenstackRequest(request); + Port port = executeAndRecordOpenstackRequest(request, false); return port; } catch (OpenStackResponseException e) { if (e.getStatus() == 404) { diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java index fc08201bcb..9fa4557a45 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateResponse.java @@ -22,13 +22,16 @@ package org.onap.so.openstack.utils; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.databind.JsonNode; import org.apache.commons.lang.builder.ToStringBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({"template_type", "workload_id", "template_response"}) +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonPropertyOrder({"template_type", "workload_id", "template_response", "workload_status_reason", "workload_status"}) public class MulticloudCreateResponse implements Serializable { private static final long serialVersionUID = -5215028275577848311L; @@ -37,12 +40,16 @@ public class MulticloudCreateResponse implements Serializable { @JsonProperty("workload_id") private String workloadId; @JsonProperty("template_response") - private MulticloudCreateStackResponse templateResponse; + private JsonNode templateResponse; + @JsonProperty("workload_status_reason") + private JsonNode workloadStatusReason; + @JsonProperty("workload_status") + private String workloadStatus; @JsonCreator public MulticloudCreateResponse(@JsonProperty("template_type") String templateType, @JsonProperty("workload_id") String workloadId, - @JsonProperty("template_response") MulticloudCreateStackResponse templateResponse) { + @JsonProperty("template_response") JsonNode templateResponse) { this.templateType = templateType; this.workloadId = workloadId; this.templateResponse = templateResponse; @@ -69,18 +76,41 @@ public class MulticloudCreateResponse implements Serializable { } @JsonProperty("template_response") - public void setTemplateResponse(MulticloudCreateStackResponse templateResponse) { + public void setTemplateResponse(JsonNode templateResponse) { this.templateResponse = templateResponse; } @JsonProperty("template_response") - public MulticloudCreateStackResponse getTemplateResponse() { + public JsonNode getTemplateResponse() { return templateResponse; } + @JsonProperty("workload_status_reason") + public void setWorkloadStatusReason(JsonNode workloadStatusReason) { + this.workloadStatusReason = workloadStatusReason; + } + + @JsonProperty("workload_status_reason") + public JsonNode getWorkloadStatusReason() { + return workloadStatusReason; + } + + @JsonProperty("workload_status") + public String getWorkloadSstatus() { + return workloadStatus; + } + + @JsonProperty("workload_status") + public void setWorkloadStatus(String workloadStatus) { + this.workloadStatus = workloadStatus; + } + + @Override public String toString() { return new ToStringBuilder(this).append("templateType", templateType).append("workloadId", workloadId) - .append("templateResponse", templateResponse).toString(); + .append("templateResponse", templateResponse) + .append("workload_status_reason", workloadStatusReason.toString()) + .append("workload_status", workloadStatus).toString(); } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/NeutronClientImpl.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/NeutronClientImpl.java index 93745de54a..938a888bbd 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/NeutronClientImpl.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/NeutronClientImpl.java @@ -75,7 +75,7 @@ public class NeutronClientImpl extends MsoCommonUtils { Quantum neutronClient = getNeutronClient(cloudSiteId, tenantId); OpenStackRequest<Networks> request = neutronClient.networks().list().queryParam("id", id) .queryParam("limit", limit).queryParam("marker", marker).queryParam("name", name); - return executeAndRecordOpenstackRequest(request); + return executeAndRecordOpenstackRequest(request, false); } catch (MsoException e) { logger.error("Error building Neutron Client", e); throw new NeutronClientException("Error building Neutron Client", e); @@ -103,7 +103,7 @@ public class NeutronClientImpl extends MsoCommonUtils { Quantum neutronClient = getNeutronClient(cloudSiteId, tenantId); OpenStackRequest<Subnets> request = neutronClient.subnets().list().queryParam("id", id) .queryParam("limit", limit).queryParam("marker", marker).queryParam("name", name); - return executeAndRecordOpenstackRequest(request); + return executeAndRecordOpenstackRequest(request, false); } catch (MsoException e) { logger.error("Error building Neutron Client", e); throw new NeutronClientException("Error building Neutron Client", e); diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/NovaClientImpl.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/NovaClientImpl.java index a342f770ef..99e8b589b1 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/NovaClientImpl.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/NovaClientImpl.java @@ -78,7 +78,7 @@ public class NovaClientImpl extends MsoCommonUtils { Nova novaClient = getNovaClient(cloudSiteId, tenantId); OpenStackRequest<Flavors> request = novaClient.flavors().list(false).queryParam("limit", limit).queryParam("marker", marker); - return executeAndRecordOpenstackRequest(request); + return executeAndRecordOpenstackRequest(request, false); } catch (MsoException e) { logger.error("Error building Nova Client", e); throw new NovaClientException("Error building Nova Client", e); @@ -103,7 +103,7 @@ public class NovaClientImpl extends MsoCommonUtils { Nova novaClient = getNovaClient(cloudSiteId, tenantId); novaClient = getNovaClient(cloudSiteId, tenantId); OpenStackRequest<Flavor> request = novaClient.flavors().show(id); - return executeAndRecordOpenstackRequest(request); + return executeAndRecordOpenstackRequest(request, false); } catch (MsoException e) { logger.error("Error building Nova Client", e); throw new NovaClientException("Error building Nova Client", e); @@ -128,7 +128,7 @@ public class NovaClientImpl extends MsoCommonUtils { Nova novaClient = getNovaClient(cloudSiteId, tenantId); OpenStackRequest<HostAggregates> request = novaClient.aggregates().list().queryParam("limit", limit).queryParam("marker", marker); - return executeAndRecordOpenstackRequest(request); + return executeAndRecordOpenstackRequest(request, false); } catch (MsoException e) { logger.error("Error building Nova Client", e); throw new NovaClientException("Error building Nova Client", e); @@ -152,7 +152,7 @@ public class NovaClientImpl extends MsoCommonUtils { try { Nova novaClient = getNovaClient(cloudSiteId, tenantId); OpenStackRequest<HostAggregate> request = novaClient.aggregates().showAggregate(id); - return executeAndRecordOpenstackRequest(request); + return executeAndRecordOpenstackRequest(request, false); } catch (MsoException e) { logger.error("Error building Nova Client", e); throw new NovaClientException("Error building Nova Client", e); @@ -176,11 +176,32 @@ public class NovaClientImpl extends MsoCommonUtils { try { Nova novaClient = getNovaClient(cloudSiteId, tenantId); OpenStackRequest<QuotaSet> request = novaClient.quotaSets().showQuota(tenantId); - return executeAndRecordOpenstackRequest(request); + return executeAndRecordOpenstackRequest(request, false); } catch (MsoException e) { logger.error("Error building Nova Client", e); throw new NovaClientException("Error building Nova Client", e); } } + /** + * Deletes a keypair inside openstack + * + * + * @param cloudSiteId the cloud site id + * @param tenantId the tenant id + * @param keyPairName name of the keypair to be deleted + * @throws MsoCloudSiteNotFound the mso cloud site not found + * @throws NeutronClientException if the client cannot be built this is thrown + */ + public void deleteKeyPair(String cloudSiteId, String tenantId, String keyPairName) + throws MsoCloudSiteNotFound, NovaClientException { + try { + Nova novaClient = getNovaClient(cloudSiteId, tenantId); + OpenStackRequest<Void> request = novaClient.keyPairs().delete(keyPairName); + executeAndRecordOpenstackRequest(request, false); + } catch (MsoException e) { + logger.error("Error building Nova Client", e); + throw new NovaClientException("Error building Nova Client", e); + } + } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeleteTasks.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackCreationException.java index 6d81cba41d..e3936e31f7 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeleteTasks.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackCreationException.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 - 2019 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. @@ -18,11 +18,14 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.infrastructure.sdnc.tasks; +package org.onap.so.openstack.utils; -import org.springframework.stereotype.Component; +import org.onap.so.openstack.exceptions.MsoException; -@Component -public class SDNCDeleteTasks { +public class StackCreationException extends MsoException { + + public StackCreationException(String error) { + super(error); + } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackResultWrapper.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackResultWrapper.java new file mode 100644 index 0000000000..5e52a0a2ae --- /dev/null +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackResultWrapper.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.openstack.utils; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import com.woorea.openstack.heat.model.Stack; + +public class StackResultWrapper { + + private Stack stack; + private boolean stackTimedOutPolling; + private boolean stackNotFound; + private String errorMessage; + private String errorCode; + + @Override + public String toString() { + return new ToStringBuilder(this).append("stack", stack).append("stackTimedOutPolling", stackTimedOutPolling) + .append("stackNotFound", stackNotFound).append("errorMessage", errorMessage) + .append("errorCode", errorCode).toString(); + } + + public Stack getStack() { + return stack; + } + + public void setStack(Stack stack) { + this.stack = stack; + } + + public boolean isStackTimedOutPolling() { + return stackTimedOutPolling; + } + + public void setStackTimedOutPolling(boolean stackTimedOutPolling) { + this.stackTimedOutPolling = stackTimedOutPolling; + } + + public boolean isStackNotFound() { + return stackNotFound; + } + + public void setStackNotFound(boolean stackNotFound) { + this.stackNotFound = stackNotFound; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + +} diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackRollbackException.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackRollbackException.java new file mode 100644 index 0000000000..ee284b11fe --- /dev/null +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackRollbackException.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.openstack.utils; + +import org.onap.so.openstack.exceptions.MsoException; + +public class StackRollbackException extends MsoException { + + public StackRollbackException(String error) { + super(error); + } + +} diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackStatusHandler.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackStatusHandler.java index 990e9a4543..bf29c39f99 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackStatusHandler.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackStatusHandler.java @@ -1,10 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.openstack.utils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.db.request.beans.RequestProcessingData; import org.onap.so.db.request.client.RequestsDbClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @@ -21,21 +43,25 @@ public class StackStatusHandler { private RequestsDbClient requestDBClient; @Async - public void updateStackStatus(Stack stack, String requestId) { + public void updateStackStatus(Stack stack) { try { + String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); String stackStatus = mapper.writeValueAsString(stack); RequestProcessingData requestProcessingData = - requestDBClient.getRequestProcessingDataBySoRequestIdAndNameAndGrouping(requestId, stack.getId(), - stack.getStackName()); + requestDBClient.getRequestProcessingDataBySoRequestIdAndNameAndGrouping(requestId, + stack.getStackName(), stack.getId()); if (requestProcessingData == null) { requestProcessingData = new RequestProcessingData(); requestProcessingData.setGroupingId(stack.getId()); requestProcessingData.setName(stack.getStackName()); requestProcessingData.setTag("StackInformation"); requestProcessingData.setSoRequestId(requestId); + requestProcessingData.setValue(stackStatus); + requestDBClient.saveRequestProcessingData(requestProcessingData); + } else { + requestProcessingData.setValue(stackStatus); + requestDBClient.updateRequestProcessingData(requestProcessingData); } - requestProcessingData.setValue(stackStatus); - requestDBClient.saveRequestProcessingData(requestProcessingData); } catch (Exception e) { logger.warn("Error adding stack status to request database", e); } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java index 5cf7c86522..622ad4f94f 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoCommonUtilsTest.java @@ -69,6 +69,7 @@ public class MsoCommonUtilsTest extends BaseTest { Mockito.when(openstackRequest.path()).thenReturn("/test"); // TODO:Must try a real connection assertNull(commonUtils.executeAndRecordOpenstackRequest(openstackRequest)); + assertNull(commonUtils.executeAndRecordOpenstackRequest(openstackRequest, true)); } @Test @@ -78,6 +79,7 @@ public class MsoCommonUtilsTest extends BaseTest { doThrow(OpenStackResponseException.class).when(openstackRequest).execute(); commonUtils.executeAndRecordOpenstackRequest(openstackRequest); + commonUtils.executeAndRecordOpenstackRequest(openstackRequest, true); } @Test @@ -86,7 +88,7 @@ public class MsoCommonUtilsTest extends BaseTest { doThrow(OpenStackConnectException.class).when(openstackRequest).execute(); - commonUtils.executeAndRecordOpenstackRequest(openstackRequest); + commonUtils.executeAndRecordOpenstackRequest(openstackRequest, true); } @Test diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsITTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsITTest.java new file mode 100644 index 0000000000..7e783aa7a4 --- /dev/null +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsITTest.java @@ -0,0 +1,219 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * 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.openstack.utils; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +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.assertNotNull; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.http.HttpStatus; +import org.junit.Assert; +import org.junit.Test; +import org.onap.so.BaseTest; +import org.onap.so.StubOpenStack; +import org.onap.so.adapters.vdu.CloudInfo; +import org.onap.so.adapters.vdu.PluginAction; +import org.onap.so.adapters.vdu.VduArtifact; +import org.onap.so.adapters.vdu.VduArtifact.ArtifactType; +import org.onap.so.adapters.vdu.VduInstance; +import org.onap.so.adapters.vdu.VduModelInfo; +import org.onap.so.adapters.vdu.VduStateType; +import org.onap.so.adapters.vdu.VduStatus; +import org.onap.so.db.catalog.beans.CloudIdentity; +import org.onap.so.db.catalog.beans.CloudSite; +import org.onap.so.openstack.beans.StackInfo; +import org.onap.so.openstack.exceptions.MsoAdapterException; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.exceptions.MsoOpenstackException; +import org.springframework.beans.factory.annotation.Autowired; +import com.woorea.openstack.heat.Heat; + +public class MsoHeatUtilsITTest extends BaseTest { + + @Autowired + private MsoHeatUtils heatUtils; + + @Test + public void instantiateVduTest() throws MsoException, IOException { + VduInstance expected = new VduInstance(); + expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b"); + expected.setVduInstanceName("name"); + VduStatus status = new VduStatus(); + status.setState(VduStateType.INSTANTIATED); + status.setLastAction((new PluginAction("create", "complete", null))); + expected.setStatus(status); + + CloudInfo cloudInfo = new CloudInfo(); + cloudInfo.setCloudSiteId("MTN13"); + cloudInfo.setTenantId("tenantId"); + VduModelInfo vduModel = new VduModelInfo(); + vduModel.setModelCustomizationUUID("blueprintId"); + vduModel.setTimeoutMinutes(1); + VduArtifact artifact = new VduArtifact(); + artifact.setName("name"); + artifact.setType(ArtifactType.MAIN_TEMPLATE); + byte[] content = new byte[1]; + artifact.setContent(content); + List<VduArtifact> artifacts = new ArrayList<>(); + artifacts.add(artifact); + vduModel.setArtifacts(artifacts); + Map<String, byte[]> blueprintFiles = new HashMap<>(); + blueprintFiles.put(artifact.getName(), artifact.getContent()); + String instanceName = "stackname"; + Map<String, Object> inputs = new HashMap<>(); + boolean rollbackOnFailure = true; + + StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); + StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json"); + + wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/stackname/stackId")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK))); + + VduInstance actual = heatUtils.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure); + + assertThat(actual, sameBeanAs(expected)); + } + + + @Test + public void queryVduTest() throws Exception { + VduInstance expected = new VduInstance(); + expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b"); + expected.setVduInstanceName("name"); + VduStatus status = new VduStatus(); + status.setState(VduStateType.INSTANTIATED); + status.setLastAction((new PluginAction("create", "complete", null))); + expected.setStatus(status); + + CloudInfo cloudInfo = new CloudInfo(); + cloudInfo.setCloudSiteId("mtn13"); + cloudInfo.setTenantId("tenantId"); + String instanceId = "instanceId"; + + StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); + StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json"); + + wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK))); + + VduInstance actual = heatUtils.queryVdu(cloudInfo, instanceId); + + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void deleteVduTest() throws Exception { + VduInstance expected = new VduInstance(); + expected.setVduInstanceId("instanceId"); + expected.setVduInstanceName("instanceId"); + VduStatus status = new VduStatus(); + status.setState(VduStateType.DELETED); + expected.setStatus(status); + + CloudInfo cloudInfo = new CloudInfo(); + cloudInfo.setCloudSiteId("mtn13"); + cloudInfo.setTenantId("tenantId"); + String instanceId = "instanceId"; + + int timeoutInMinutes = 1; + + StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); + wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId")) + .willReturn(aResponse().withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK))); + StubOpenStack.mockOpenStackDelete(wireMockServer, "name/da886914-efb2-4917-b335-c8381528d90b"); + wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/name/da886914-efb2-4917-b335-c8381528d90b")) + .willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_DeleteComplete.json") + .withStatus(HttpStatus.SC_OK))); + + VduInstance actual = heatUtils.deleteVdu(cloudInfo, instanceId, timeoutInMinutes); + + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public final void copyBaseOutputsToInputsTest() { + Map<String, Object> inputs = new HashMap<>(); + inputs.put("str1", "str"); + Map<String, Object> otherStackOutputs = new HashMap<>(); + otherStackOutputs.put("str", "str"); + List<String> paramNames = new ArrayList<>(); + Map<String, String> aliases = new HashMap<>(); + aliases.put("str", "str"); + heatUtils.copyBaseOutputsToInputs(inputs, otherStackOutputs, null, aliases); + Assert.assertEquals("str", otherStackOutputs.get("str")); + } + + @Test + public final void getHeatClientSuccessTest() throws MsoException, IOException { + CloudSite cloudSite = getCloudSite(getCloudIdentity()); + StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); + Heat heatClient = heatUtils.getHeatClient("MTN13", "TEST-tenant"); + assertNotNull(heatClient); + } + + @Test(expected = MsoOpenstackException.class) + public final void getHeatClientOpenStackResponseException404Test() throws MsoException, IOException { + CloudSite cloudSite = getCloudSite(getCloudIdentity()); + // mo mocks setup will cause 404 response from wiremock + heatUtils.getHeatClient("MTN13", "TEST-tenant"); + } + + @Test(expected = MsoAdapterException.class) + public final void getHeatClientOpenStackResponseException401Test() throws MsoException, IOException { + CloudSite cloudSite = getCloudSite(getCloudIdentity()); + StubOpenStack.mockOpenStackResponseUnauthorized(wireMockServer, wireMockPort); + heatUtils.getHeatClient("MTN13", "TEST-tenant"); + } + + @Test(expected = MsoOpenstackException.class) + public final void getHeatClientOpenStackConnectExceptionTest() throws MsoException, IOException { + CloudIdentity identity = getCloudIdentity(); + identity.setIdentityUrl("http://unreachable"); + CloudSite cloudSite = getCloudSite(identity); + // mo mocks setup will cause 404 response from wiremock + heatUtils.getHeatClient("MTN13", "TEST-tenant"); + } + + @Test + public final void createStackSuccessTest() throws MsoException, IOException { + CloudSite cloudSite = getCloudSite(getCloudIdentity()); + StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); + StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json"); + StubOpenStack.mockOpenStackGet(wireMockServer, "TEST-stack/stackId"); + StackInfo stackInfo = heatUtils.createStack(cloudSite.getId(), "CloudOwner", "tenantId", "TEST-stack", + "TEST-heat", new HashMap<>(), false, 1, "TEST-env", new HashMap<>(), new HashMap<>()); + assertNotNull(stackInfo); + } + + + +} 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 3f5402cc99..de55e85ad6 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 @@ -2,16 +2,14 @@ * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung + * Copyright (C) 2019 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. @@ -22,214 +20,520 @@ package org.onap.so.openstack.utils; -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -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.assertNotEquals; import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.http.HttpStatus; -import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; import org.junit.Test; -import org.onap.so.BaseTest; -import org.onap.so.StubOpenStack; -import org.onap.so.adapters.vdu.CloudInfo; -import org.onap.so.adapters.vdu.PluginAction; -import org.onap.so.adapters.vdu.VduArtifact; -import org.onap.so.adapters.vdu.VduArtifact.ArtifactType; -import org.onap.so.adapters.vdu.VduInstance; -import org.onap.so.adapters.vdu.VduModelInfo; -import org.onap.so.adapters.vdu.VduStateType; -import org.onap.so.adapters.vdu.VduStatus; -import org.onap.so.db.catalog.beans.CloudIdentity; -import org.onap.so.db.catalog.beans.CloudSite; -import org.onap.so.openstack.beans.StackInfo; -import org.onap.so.openstack.exceptions.MsoAdapterException; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.db.request.beans.CloudApiRequests; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.openstack.exceptions.MsoException; -import org.onap.so.openstack.exceptions.MsoIOException; import org.onap.so.openstack.exceptions.MsoOpenstackException; -import org.springframework.beans.factory.annotation.Autowired; +import org.onap.so.openstack.exceptions.MsoStackAlreadyExists; +import org.springframework.core.env.Environment; +import com.woorea.openstack.base.client.OpenStackResponseException; import com.woorea.openstack.heat.Heat; +import com.woorea.openstack.heat.StackResource; +import com.woorea.openstack.heat.StackResource.CreateStack; +import com.woorea.openstack.heat.StackResource.DeleteStack; import com.woorea.openstack.heat.model.CreateStackParam; +import com.woorea.openstack.heat.model.Resource; +import com.woorea.openstack.heat.model.Resources; +import com.woorea.openstack.heat.model.Stack; -public class MsoHeatUtilsTest extends BaseTest { +@RunWith(MockitoJUnitRunner.class) +public class MsoHeatUtilsTest extends MsoHeatUtils { - @Autowired + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + + @Spy + @InjectMocks private MsoHeatUtils heatUtils; - @Test - public void instantiateVduTest() throws MsoException, IOException { - VduInstance expected = new VduInstance(); - expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b"); - expected.setVduInstanceName("name"); - VduStatus status = new VduStatus(); - status.setState(VduStateType.INSTANTIATED); - status.setLastAction((new PluginAction("create", "complete", null))); - expected.setStatus(status); + @Mock + private RequestsDbClient requestDbClient; - CloudInfo cloudInfo = new CloudInfo(); - cloudInfo.setCloudSiteId("MTN13"); - cloudInfo.setTenantId("tenantId"); - VduModelInfo vduModel = new VduModelInfo(); - vduModel.setModelCustomizationUUID("blueprintId"); - vduModel.setTimeoutMinutes(1); - VduArtifact artifact = new VduArtifact(); - artifact.setName("name"); - artifact.setType(ArtifactType.MAIN_TEMPLATE); - byte[] content = new byte[1]; - artifact.setContent(content); - List<VduArtifact> artifacts = new ArrayList<>(); - artifacts.add(artifact); - vduModel.setArtifacts(artifacts); - Map<String, byte[]> blueprintFiles = new HashMap<>(); - blueprintFiles.put(artifact.getName(), artifact.getContent()); - String instanceName = "instanceName"; - Map<String, Object> inputs = new HashMap<>(); - boolean rollbackOnFailure = true; + @Mock + private Heat heatClient; - StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); - StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json"); + @Mock + private StackStatusHandler stackStatusHandler; - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceName/stackId")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK))); + @Mock + private Environment env; - VduInstance actual = heatUtils.instantiateVdu(cloudInfo, instanceName, inputs, vduModel, rollbackOnFailure); + @Mock + private StackResource stackResource; - assertThat(actual, sameBeanAs(expected)); - } + @Mock + private NovaClientImpl novaClient; + @Mock + private DeleteStack mockDeleteStack; + + @Mock + private Resources mockResources; + + @Mock + private CreateStack mockCreateStack; + + private String cloudSiteId = "cloudSiteId"; + private String tenantId = "tenantId"; + + @Before + public void setup() { + doReturn("15").when(env).getProperty("org.onap.so.adapters.po.pollInterval", "15"); + doReturn("1").when(env).getProperty("org.onap.so.adapters.po.pollMultiplier", "60"); + } @Test - public void queryVduTest() throws Exception { - VduInstance expected = new VduInstance(); - expected.setVduInstanceId("name/da886914-efb2-4917-b335-c8381528d90b"); - expected.setVduInstanceName("name"); - VduStatus status = new VduStatus(); - status.setState(VduStateType.INSTANTIATED); - status.setLastAction((new PluginAction("create", "complete", null))); - expected.setStatus(status); + public final void pollStackForStatus_Create_Complete_Test() throws MsoException, IOException { + Stack stack = new Stack(); + stack.setId("id"); + stack.setStackName("stackName"); + stack.setStackStatus("CREATE_IN_PROGRESS"); + stack.setStackStatusReason("Stack Finished"); + + Stack latestStack = new Stack(); + latestStack.setId("id"); + latestStack.setStackName("stackName"); + latestStack.setStackStatus("CREATE_COMPLETE"); + latestStack.setStackStatusReason("Stack Finished"); + doReturn(latestStack).when(heatUtils).queryHeatStack(isA(Heat.class), eq("stackName/id")); + doReturn(heatClient).when(heatUtils).getHeatClient(cloudSiteId, tenantId); + Stack actual = heatUtils.pollStackForStatus(1, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + Mockito.verify(stackStatusHandler, times(1)).updateStackStatus(latestStack); + Mockito.verify(heatUtils, times(1)).queryHeatStack(isA(Heat.class), eq("stackName/id")); + assertEquals(true, actual != null); + } - CloudInfo cloudInfo = new CloudInfo(); - cloudInfo.setCloudSiteId("mtn13"); - cloudInfo.setTenantId("tenantId"); - String instanceId = "instanceId"; - StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); - StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json"); + @Test + public final void pollStackForStatus_Polling_Exhausted_Test() throws MsoException, IOException { + Stack stack = new Stack(); + stack.setId("id"); + stack.setStackName("stackName"); + stack.setStackStatus("CREATE_IN_PROGRESS"); + stack.setStackStatusReason("Stack Finished"); + doNothing().when(stackStatusHandler).updateStackStatus(stack); + doReturn(stack).when(heatUtils).queryHeatStack(isA(Heat.class), eq("stackName/id")); + doReturn(heatClient).when(heatUtils).getHeatClient(cloudSiteId, tenantId); + Stack actual = heatUtils.pollStackForStatus(1, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + Mockito.verify(stackStatusHandler, times(1)).updateStackStatus(stack); + Mockito.verify(heatUtils, times(1)).queryHeatStack(isA(Heat.class), eq("stackName/id")); + assertEquals(true, actual != null); + } + + @Test + public final void postProcessStackCreate_CREATE_IN_PROGRESS_Test() throws MsoException, IOException { + Stack stack = new Stack(); + stack.setId("id"); + stack.setStackName("stackName"); + stack.setStackStatus("CREATE_IN_PROGRESS"); + stack.setStackStatusReason("Stack Finished"); + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + + exceptionRule.expect(StackCreationException.class); + exceptionRule.expectMessage("Stack rollback suppressed, stack not deleted"); + heatUtils.postProcessStackCreate(stack, false, 120, false, cloudSiteId, tenantId, createStackParam); + } - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK))); + @Test + public final void postProcessStackCreate_Backout_True_Test() throws MsoException, IOException { + Stack stack = new Stack(); + stack.setId("id"); + stack.setStackName("stackName"); + stack.setStackStatus("CREATE_IN_PROGRESS"); + stack.setStackStatusReason("Stack Finished"); + + Stack deletedStack = new Stack(); + deletedStack.setId("id"); + deletedStack.setStackName("stackName"); + deletedStack.setStackStatus("DELETE_COMPLETE"); + deletedStack.setStackStatusReason("Stack Deleted"); + + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + doReturn(deletedStack).when(heatUtils).handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); + exceptionRule.expect(StackCreationException.class); + exceptionRule.expectMessage( + "Stack Creation Failed Openstack Status: CREATE_IN_PROGRESS Status Reason: Stack Finished , Rollback of Stack Creation completed with status: DELETE_COMPLETE Status Reason: Stack Deleted"); + heatUtils.postProcessStackCreate(stack, true, 120, false, cloudSiteId, tenantId, createStackParam); + Mockito.verify(heatUtils, times(1)).handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); + } - VduInstance actual = heatUtils.queryVdu(cloudInfo, instanceId); + @Test + public final void postProcessStackCreate_Backout_True_Delete_Fail_Test() throws MsoException, IOException { + Stack stack = new Stack(); + stack.setId("id"); + stack.setStackName("stackName"); + stack.setStackStatus("CREATE_IN_PROGRESS"); + stack.setStackStatusReason("Stack Finished"); + + Stack deletedStack = new Stack(); + deletedStack.setId("id"); + deletedStack.setStackName("stackName"); + deletedStack.setStackStatus("DELETE_COMPLETE"); + deletedStack.setStackStatusReason("Stack Deleted"); + + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + doThrow(new MsoOpenstackException(500, "Error In Delete", "Error In Delete")).when(heatUtils) + .handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); + exceptionRule.expect(MsoException.class); + exceptionRule.expectMessage( + "Stack Creation Failed Openstack Status: CREATE_IN_PROGRESS Status Reason: Stack Finished , Rollback of Stack Creation failed with sync error: Error In Delete"); + heatUtils.postProcessStackCreate(stack, true, 120, false, cloudSiteId, tenantId, createStackParam); + Mockito.verify(heatUtils, times(1)).handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); + } - assertThat(actual, sameBeanAs(expected)); + @Test + public final void postProcessStackCreate_Keypair_True_Test() throws MsoException, IOException { + Stack stack = new Stack(); + stack.setId("id"); + stack.setStackName("stackName"); + stack.setStackStatus("CREATE_IN_PROGRESS"); + stack.setStackStatusReason( + "Resource CREATE failed: Conflict: resources.my_keypair: Key pair 'hst3bbfnm0011vm001' already exists. (HTTP 409) (Request-ID: req-941b0af6-63ae-4d6a-afbc-90b728bacf82"); + + Stack createdStack = new Stack(); + createdStack.setId("id"); + createdStack.setStackName("stackName"); + createdStack.setStackStatus("CREATE_COMPLETE"); + createdStack.setStackStatusReason("Stack Created"); + + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + doReturn(createdStack).when(heatUtils).handleKeyPairConflict(cloudSiteId, tenantId, createStackParam, 120, true, + stack); + heatUtils.postProcessStackCreate(stack, true, 120, true, cloudSiteId, tenantId, createStackParam); + Mockito.verify(heatUtils, times(1)).handleKeyPairConflict(cloudSiteId, tenantId, createStackParam, 120, true, + stack); } @Test - public void deleteVduTest() throws Exception { - VduInstance expected = new VduInstance(); - expected.setVduInstanceId("instanceId"); - expected.setVduInstanceName("instanceId"); - VduStatus status = new VduStatus(); - status.setState(VduStateType.DELETED); - expected.setStatus(status); + public final void handleUnknownCreateStackFailure_Test() throws MsoException, IOException { + + Stack stack = new Stack(); + stack.setId("id"); + stack.setStackName("stackName"); + stack.setStackStatus("CREATE_FAILED"); + stack.setStackStatusReason( + "Resource CREATE failed: Conflict: resources.my_keypair: Key pair 'hst3bbfnm0011vm001' already exists. (HTTP 409) (Request-ID: req-941b0af6-63ae-4d6a-afbc-90b728bacf82"); + + Stack deletedStack = new Stack(); + deletedStack.setId("id"); + deletedStack.setStackName("stackName"); + deletedStack.setStackStatus("DELETE_COMPLETE"); + deletedStack.setStackStatusReason("Stack Deleted"); + + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + doReturn(heatClient).when(heatUtils).getHeatClient(cloudSiteId, tenantId); + doNothing().when(heatUtils).postProcessStackDelete(deletedStack); + doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(mockDeleteStack); + doReturn(stackResource).when(heatClient).getStacks(); + doReturn(mockDeleteStack).when(stackResource).deleteByName("stackName/id"); + doReturn(deletedStack).when(heatUtils).pollStackForStatus(120, stack, "DELETE_IN_PROGRESS", cloudSiteId, + tenantId); + + heatUtils.handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); + Mockito.verify(heatUtils, times(1)).executeAndRecordOpenstackRequest(mockDeleteStack); + Mockito.verify(heatUtils, times(1)).pollStackForStatus(120, stack, "DELETE_IN_PROGRESS", cloudSiteId, tenantId); + Mockito.verify(heatUtils, times(1)).postProcessStackDelete(deletedStack); + } - CloudInfo cloudInfo = new CloudInfo(); - cloudInfo.setCloudSiteId("mtn13"); - cloudInfo.setTenantId("tenantId"); - String instanceId = "instanceId"; - int timeoutInMinutes = 1; + @Test + public final void handleUnknownCreateStackFailure_Null_Stack_Test() throws MsoException, IOException { + Stack stack = null; + exceptionRule.expect(StackCreationException.class); + exceptionRule.expectMessage("Cannot Find Stack Name or Id"); + heatUtils.handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); + } - StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/instanceId")) - .willReturn(aResponse().withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK))); - StubOpenStack.mockOpenStackDelete(wireMockServer, "name/da886914-efb2-4917-b335-c8381528d90b"); - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/name/da886914-efb2-4917-b335-c8381528d90b")) - .willReturn(aResponse().withBodyFile("OpenstackResponse_Stack_DeleteComplete.json") - .withStatus(HttpStatus.SC_OK))); + @Test + public final void postProcessStackDelete_Stack_Test() throws MsoException, IOException { + Stack deletedStack = new Stack(); + deletedStack.setId("id"); + deletedStack.setStackName("stackName"); + deletedStack.setStackStatus("DELETE_FAILED"); + deletedStack.setStackStatusReason("Stack DID NOT DELETE"); + exceptionRule.expect(StackRollbackException.class); + exceptionRule.expectMessage( + "Stack Deletion completed with status: DELETE_FAILED Status Reason: Stack DID NOT DELETE"); + heatUtils.postProcessStackDelete(deletedStack); + } - VduInstance actual = heatUtils.deleteVdu(cloudInfo, instanceId, timeoutInMinutes); + @Test + public final void postProcessStackDelete__Null_Stack_Test() throws MsoException, IOException { + Stack stack = null; + exceptionRule.expect(StackRollbackException.class); + exceptionRule.expectMessage("Cannot Find Stack Name or Id"); + heatUtils.postProcessStackDelete(stack); + } - assertThat(actual, sameBeanAs(expected)); + @Test + public final void isKeyPairFailure_Test() throws MsoException, IOException { + boolean actual = heatUtils.isKeyPairFailure( + "Exception during create VF 0 : Stack error (CREATE_FAILED): Resource CREATE failed: Conflict: resources.bfnm_my_keypair: Key pair 'hst3bbfnm0011vm001' already exists. (HTTP 409) (Request-ID:req-941b0af6-63ae-4d6a-afbc-90b728bacf82) - stack successfully deleted'rolledBack='true'"); + assertEquals(true, actual); } @Test - public final void requestToStringBuilderTest() { - CreateStackParam param = new CreateStackParam(); - param.setDisableRollback(false); - param.setEnvironment("environment"); - param.setFiles(new HashMap<String, Object>()); - param.setParameters(new HashMap<>()); - param.setStackName("stackName"); - param.setTemplate("template"); - param.setTemplateUrl("http://templateUrl"); - param.setTimeoutMinutes(1); + public final void handleKeyPairConflict_Test() throws MsoException, IOException, NovaClientException { + Stack stack = new Stack(); + stack.setId("id"); + stack.setStackName("stackName"); + stack.setStackStatus("CREATE_FAILED"); + stack.setStackStatusReason( + "Resource CREATE failed: Conflict: resources.my_keypair: Key pair 'hst3bbfnm0011vm001' already exists. (HTTP 409) (Request-ID: req-941b0af6-63ae-4d6a-afbc-90b728bacf82"); + + Stack createdStack = new Stack(); + createdStack.setId("id"); + createdStack.setStackName("stackName"); + createdStack.setStackStatus("CREATE_COMPLETE"); + createdStack.setStackStatusReason("Stack Created"); + + + + List<Resource> resources = new ArrayList<>(); + Resource resource = new Resource(); + resource.setName("KeypairName"); + resource.setLogicalResourceId("KeypairName"); + resource.setType("OS::Nova::KeyPair"); + resources.add(resource); + + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + + doReturn(resources).when(mockResources).getList(); + 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, + createStackParam, false); + + heatUtils.handleKeyPairConflict(cloudSiteId, tenantId, createStackParam, 120, true, stack); + Mockito.verify(heatUtils, times(1)).queryStackResources(cloudSiteId, tenantId, "stackName", 2); + Mockito.verify(novaClient, times(1)).deleteKeyPair(cloudSiteId, tenantId, "KeypairName"); + Mockito.verify(heatUtils, times(1)).handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); + Mockito.verify(heatUtils, times(1)).createStack(createStackParam, cloudSiteId, tenantId); + Mockito.verify(heatUtils, times(1)).processCreateStack(cloudSiteId, tenantId, 120, true, createdStack, + createStackParam, false); + } - StringBuilder stringBuilder = heatUtils.requestToStringBuilder(param); + @Test + public final void processCreateStack_Test() throws MsoException, IOException, NovaClientException { + Stack stack = new Stack(); + stack.setId("id"); + stack.setStackName("stackName"); + stack.setStackStatus("CREATE_FAILED"); + stack.setStackStatusReason( + "Resource CREATE failed: Conflict: resources.my_keypair: Key pair 'hst3bbfnm0011vm001' already exists. (HTTP 409) (Request-ID: req-941b0af6-63ae-4d6a-afbc-90b728bacf82"); + + Stack createdStack = new Stack(); + createdStack.setId("id"); + createdStack.setStackName("stackName"); + createdStack.setStackStatus("CREATE_COMPLETE"); + createdStack.setStackStatusReason("Stack Created"); + + + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + + doReturn(createdStack).when(heatUtils).pollStackForStatus(120, stack, "CREATE_IN_PROGRESS", cloudSiteId, + tenantId); + doReturn(createdStack).when(heatUtils).postProcessStackCreate(createdStack, true, 120, true, cloudSiteId, + tenantId, createStackParam); + + heatUtils.processCreateStack(cloudSiteId, tenantId, 120, true, stack, createStackParam, true); + Mockito.verify(heatUtils, times(1)).pollStackForStatus(120, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + Mockito.verify(heatUtils, times(1)).postProcessStackCreate(createdStack, true, 120, true, cloudSiteId, tenantId, + createStackParam); + } - Assert.assertTrue(stringBuilder.toString().contains("StackName:")); + @Test + public final void processCreateStack_Exception_Backout_Test() + throws MsoException, IOException, NovaClientException { + Stack stack = new Stack(); + stack.setId("id"); + stack.setStackName("stackName"); + stack.setStackStatus("CREATE_FAILED"); + stack.setStackStatusReason( + "Resource CREATE failed: Conflict: resources.my_keypair: Key pair 'hst3bbfnm0011vm001' already exists. (HTTP 409) (Request-ID: req-941b0af6-63ae-4d6a-afbc-90b728bacf82"); + + Stack deletedStack = new Stack(); + deletedStack.setId("id"); + deletedStack.setStackName("stackName"); + deletedStack.setStackStatus("DELETE_COMPLETE"); + deletedStack.setStackStatusReason("Stack Deleted"); + + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + + doThrow(new StackCreationException("Error")).when(heatUtils).pollStackForStatus(120, stack, + "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + exceptionRule.expect(MsoException.class); + exceptionRule.expectMessage("Error"); + heatUtils.processCreateStack(cloudSiteId, tenantId, 120, true, stack, createStackParam, true); + Mockito.verify(heatUtils, times(1)).pollStackForStatus(120, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + Mockito.verify(heatUtils, times(1)).postProcessStackCreate(stack, true, 120, true, cloudSiteId, tenantId, + createStackParam); } + @Test - public final void copyBaseOutputsToInputsTest() { - Map<String, Object> inputs = new HashMap<>(); - inputs.put("str1", "str"); - Map<String, Object> otherStackOutputs = new HashMap<>(); - otherStackOutputs.put("str", "str"); - List<String> paramNames = new ArrayList<>(); - Map<String, String> aliases = new HashMap<>(); - aliases.put("str", "str"); - heatUtils.copyBaseOutputsToInputs(inputs, otherStackOutputs, null, aliases); - Assert.assertEquals("str", otherStackOutputs.get("str")); + public final void createStack_Test() throws MsoException, IOException, NovaClientException { + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + + doReturn(heatClient).when(heatUtils).getHeatClient(cloudSiteId, tenantId); + doReturn(stackResource).when(heatClient).getStacks(); + doReturn(mockCreateStack).when(stackResource).create(createStackParam); + + doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(mockCreateStack); + + heatUtils.createStack(createStackParam, cloudSiteId, tenantId); + Mockito.verify(stackResource, times(1)).create(createStackParam); + Mockito.verify(heatUtils, times(1)).saveStackRequest(eq(createStackParam), isNull(), eq("stackName")); + Mockito.verify(heatClient, times(1)).getStacks(); + Mockito.verify(stackResource, times(1)).create(createStackParam); } @Test - public final void getHeatClientSuccessTest() throws MsoException, IOException { - CloudSite cloudSite = getCloudSite(getCloudIdentity()); - StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); - Heat heatClient = heatUtils.getHeatClient(cloudSite, "TEST-tenant"); - assertNotNull(heatClient); + public final void saveStack_Test() throws MsoException, IOException, NovaClientException { + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + Map<String, Object> parameters = new HashMap<String, Object>(); + parameters.put("test", "value"); + createStackParam.setParameters(parameters); + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId("requestId"); + doReturn(request).when(requestDbClient).getInfraActiveRequestbyRequestId("requestId"); + doNothing().when(requestDbClient).updateInfraActiveRequests(request); + heatUtils.saveStackRequest(createStackParam, "requestId", "stackName"); + Mockito.verify(requestDbClient, times(1)).updateInfraActiveRequests(request); + assertNotNull(request.getCloudApiRequests().get(0)); + assertEquals(request.getCloudApiRequests().get(0).getRequestId(), "requestId"); } - @Test(expected = MsoOpenstackException.class) - public final void getHeatClientOpenStackResponseException404Test() throws MsoException, IOException { - CloudSite cloudSite = getCloudSite(getCloudIdentity()); - // mo mocks setup will cause 404 response from wiremock - heatUtils.getHeatClient(cloudSite, "TEST-tenant"); + @Test + public final void saveStack__Exists_Test() throws MsoException, IOException, NovaClientException { + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + Map<String, Object> parameters = new HashMap<String, Object>(); + parameters.put("test", "value"); + createStackParam.setParameters(parameters); + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId("requestId"); + CloudApiRequests cloudRequest = new CloudApiRequests(); + cloudRequest.setCloudIdentifier("stackName"); + cloudRequest.setRequestBody("testMe"); + cloudRequest.setRequestId("requestId"); + request.getCloudApiRequests().add(cloudRequest); + doReturn(request).when(requestDbClient).getInfraActiveRequestbyRequestId("requestId"); + doNothing().when(requestDbClient).updateInfraActiveRequests(request); + heatUtils.saveStackRequest(createStackParam, "requestId", "stackName"); + Mockito.verify(requestDbClient, times(1)).updateInfraActiveRequests(request); + assertNotNull(request.getCloudApiRequests().get(0)); + assertEquals("requestId", request.getCloudApiRequests().get(0).getRequestId()); + assertNotEquals("testMe", request.getCloudApiRequests().get(0).getRequestBody()); } - @Test(expected = MsoAdapterException.class) - public final void getHeatClientOpenStackResponseException401Test() throws MsoException, IOException { - CloudSite cloudSite = getCloudSite(getCloudIdentity()); - StubOpenStack.mockOpenStackResponseUnauthorized(wireMockServer, wireMockPort); - heatUtils.getHeatClient(cloudSite, "TEST-tenant"); + @Test + public final void createStack_Error_Test() throws MsoException, IOException, NovaClientException { + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + + doReturn(heatClient).when(heatUtils).getHeatClient(cloudSiteId, tenantId); + doReturn(stackResource).when(heatClient).getStacks(); + doReturn(mockCreateStack).when(stackResource).create(createStackParam); + + doThrow(new OpenStackResponseException("Unknown Error", 500)).when(heatUtils) + .executeAndRecordOpenstackRequest(mockCreateStack); + exceptionRule.expect(MsoOpenstackException.class); + exceptionRule.expectMessage("Unknown Error"); + heatUtils.createStack(createStackParam, cloudSiteId, tenantId); + Mockito.verify(stackResource, times(1)).create(createStackParam); + Mockito.verify(heatUtils, times(1)).saveStackRequest(eq(createStackParam), isNull(), eq("stackName")); + Mockito.verify(heatClient, times(1)).getStacks(); + Mockito.verify(stackResource, times(1)).create(createStackParam); } - @Test(expected = MsoIOException.class) - public final void getHeatClientOpenStackConnectExceptionTest() throws MsoException, IOException { - CloudIdentity identity = getCloudIdentity(); - identity.setIdentityUrl("http://unreachable"); - CloudSite cloudSite = getCloudSite(identity); - // mo mocks setup will cause 404 response from wiremock - heatUtils.getHeatClient(cloudSite, "TEST-tenant"); + @Test + public final void createStack_Error_404_Test() throws MsoException, IOException, NovaClientException { + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + + doReturn(heatClient).when(heatUtils).getHeatClient(cloudSiteId, tenantId); + doReturn(stackResource).when(heatClient).getStacks(); + doReturn(mockCreateStack).when(stackResource).create(createStackParam); + + doThrow(new OpenStackResponseException("Not Found", 409)).when(heatUtils) + .executeAndRecordOpenstackRequest(mockCreateStack); + exceptionRule.expect(MsoStackAlreadyExists.class); + exceptionRule.expectMessage("Stack stackName already exists in Tenant tenantId in Cloud cloudSiteId"); + heatUtils.createStack(createStackParam, cloudSiteId, tenantId); + Mockito.verify(stackResource, times(1)).create(createStackParam); + Mockito.verify(heatUtils, times(1)).saveStackRequest(eq(createStackParam), isNull(), eq("stackName")); + Mockito.verify(heatClient, times(1)).getStacks(); + Mockito.verify(stackResource, times(1)).create(createStackParam); } @Test - public final void createStackSuccessTest() throws MsoException, IOException { - CloudSite cloudSite = getCloudSite(getCloudIdentity()); - StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); - StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json"); - StubOpenStack.mockOpenStackGet(wireMockServer, "TEST-stack/stackId"); - StackInfo stackInfo = heatUtils.createStack(cloudSite.getId(), "CloudOwner", "tenantId", "TEST-stack", null, - "TEST-heat", new HashMap<>(), false, 1, "TEST-env", new HashMap<>(), new HashMap<>(), false); - assertNotNull(stackInfo); + public final void processCreateStack_Exception_No_Backout_Test() + throws MsoException, IOException, NovaClientException { + Stack stack = new Stack(); + stack.setId("id"); + stack.setStackName("stackName"); + stack.setStackStatus("CREATE_FAILED"); + stack.setStackStatusReason( + "Resource CREATE failed: Conflict: resources.my_keypair: Key pair 'hst3bbfnm0011vm001' already exists. (HTTP 409) (Request-ID: req-941b0af6-63ae-4d6a-afbc-90b728bacf82"); + + Stack deletedStack = new Stack(); + deletedStack.setId("id"); + deletedStack.setStackName("stackName"); + deletedStack.setStackStatus("DELETE_COMPLETE"); + deletedStack.setStackStatusReason("Stack Deleted"); + + CreateStackParam createStackParam = new CreateStackParam(); + createStackParam.setStackName("stackName"); + + doThrow(new StackCreationException("Error")).when(heatUtils).pollStackForStatus(120, stack, + "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + + exceptionRule.expect(MsoException.class); + exceptionRule.expectMessage("Error"); + heatUtils.processCreateStack(cloudSiteId, tenantId, 120, false, stack, createStackParam, true); + Mockito.verify(heatUtils, times(1)).pollStackForStatus(120, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + Mockito.verify(heatUtils, times(0)).handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); } + } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java index 8951f8a304..acd42dd8da 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdateTest.java @@ -22,10 +22,8 @@ package org.onap.so.openstack.utils; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertThat; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.verify; import java.io.File; import java.io.IOException; import java.util.HashMap; @@ -98,7 +96,7 @@ public class MsoHeatUtilsWithUpdateTest extends TestDataSetup { expectedStackInfo.setCanonicalName("stackName/id"); doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class)); - doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class)); + doReturn(heatClient).when(heatUtils).getHeatClient(isA(String.class), isA(String.class)); doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class)); doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class)); doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class)); @@ -123,7 +121,7 @@ public class MsoHeatUtilsWithUpdateTest extends TestDataSetup { expectedStackInfo.setCanonicalName("stackName/id"); doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class)); - doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class)); + doReturn(heatClient).when(heatUtils).getHeatClient(isA(String.class), isA(String.class)); doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class)); doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class)); @@ -150,7 +148,7 @@ public class MsoHeatUtilsWithUpdateTest extends TestDataSetup { expectedStackInfo.setCanonicalName("stackName/id"); doReturn(Optional.of(cloudSite)).when(cloudConfig).getCloudSite(isA(String.class)); - doReturn(heatClient).when(heatUtils).getHeatClient(isA(CloudSite.class), isA(String.class)); + doReturn(heatClient).when(heatUtils).getHeatClient(isA(String.class), isA(String.class)); doReturn(null).when(heatUtils).executeAndRecordOpenstackRequest(isA(OpenStackRequest.class)); doReturn("0").when(environment).getProperty(isA(String.class), isA(String.class)); doReturn(updateStack).when(heatUtils).queryHeatStack(isA(Heat.class), isA(String.class)); diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/StackStatusHandlerTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/StackStatusHandlerTest.java new file mode 100644 index 0000000000..985a39a76b --- /dev/null +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/StackStatusHandlerTest.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.openstack.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import java.io.IOException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.db.request.beans.RequestProcessingData; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.openstack.exceptions.MsoException; +import com.woorea.openstack.heat.model.Stack; + +@RunWith(MockitoJUnitRunner.class) +public class StackStatusHandlerTest { + + @InjectMocks + StackStatusHandler statusHandler; + + @Mock + RequestsDbClient requestDBClient; + + @Test + public final void recordExists_Test() throws MsoException, IOException { + RequestProcessingData requestProcessingData = new RequestProcessingData(); + requestProcessingData.setValue("testMe"); + + doReturn(requestProcessingData).when(requestDBClient) + .getRequestProcessingDataBySoRequestIdAndNameAndGrouping(null, "stackName", "id"); + Stack latestStack = new Stack(); + latestStack.setId("id"); + latestStack.setStackName("stackName"); + latestStack.setStackStatus("CREATE_COMPLETE"); + latestStack.setStackStatusReason("Stack Finished"); + + statusHandler.updateStackStatus(latestStack); + Mockito.verify(requestDBClient, times(1)).updateRequestProcessingData(requestProcessingData); + assertNotEquals("testMe", requestProcessingData.getValue()); + } + + @Test + public final void record_Not_Exists_Test() throws MsoException, IOException { + ArgumentCaptor<RequestProcessingData> requestCaptor = ArgumentCaptor.forClass(RequestProcessingData.class); + doReturn(null).when(requestDBClient).getRequestProcessingDataBySoRequestIdAndNameAndGrouping(null, "stackName", + "id"); + Stack latestStack = new Stack(); + latestStack.setId("id"); + latestStack.setStackName("stackName"); + latestStack.setStackStatus("CREATE_COMPLETE"); + latestStack.setStackStatusReason("Stack Finished"); + statusHandler.updateStackStatus(latestStack); + Mockito.verify(requestDBClient, times(1)).saveRequestProcessingData(requestCaptor.capture()); + RequestProcessingData actualRequest = requestCaptor.getValue(); + assertEquals("id", actualRequest.getGroupingId()); + assertEquals("StackInformation", actualRequest.getTag()); + assertEquals("stackName", actualRequest.getName()); + assertNotNull(actualRequest.getValue()); + + } + + +} diff --git a/adapters/mso-adapter-utils/src/test/resources/__files/OpenstackResponse_Stack_Created.json b/adapters/mso-adapter-utils/src/test/resources/__files/OpenstackResponse_Stack_Created.json index 477acadf81..7eae6d14a4 100644 --- a/adapters/mso-adapter-utils/src/test/resources/__files/OpenstackResponse_Stack_Created.json +++ b/adapters/mso-adapter-utils/src/test/resources/__files/OpenstackResponse_Stack_Created.json @@ -2,7 +2,7 @@ "stack": { "description": null, "links": null, - "stack_status_reason": null, + "stack_status_reason": "Stack Created", "stack_name": "stackname", "updated_time": null, "creation_time": null, diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStateType.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStateType.java index 8870f5c7b5..d20e0494ae 100644 --- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStateType.java +++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduStateType.java @@ -25,7 +25,13 @@ package org.onap.so.adapters.vdu; * Enum status values to capture the state of a generic (cloud-agnostic) VDU. */ public enum VduStateType { - NOTFOUND, INSTANTIATING, INSTANTIATED, DELETING, DELETED, // Note - only returned in success response to deleteVdu - // call. - UPDATING, FAILED, UNKNOWN + NOTFOUND, + INSTANTIATING, + INSTANTIATED, + DELETING, + DELETED, // Note - only returned in success response to deleteVdu + // call. + UPDATING, + FAILED, + UNKNOWN } diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HostRoute.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HostRoute.java index 431870ba9e..afe9d71e92 100644 --- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HostRoute.java +++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/beans/HostRoute.java @@ -20,16 +20,16 @@ package org.onap.so.openstack.beans; - - +import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"prefix", "nextHop"}) -public class HostRoute { +public class HostRoute implements Serializable { + private static final long serialVersionUID = 2468793257174064133L; private String prefix; private String nextHop; diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapAdapter.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapAdapter.java index ef5d4316d7..90b8024c18 100644 --- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapAdapter.java +++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapAdapter.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -36,8 +38,8 @@ public class MapAdapter extends XmlAdapter<MapEntry, Map<String, Object>> { MapEntry map = new MapEntry(); - for (String key : v.keySet()) { - map.addEntry(key, v.get(key)); + for (Map.Entry<String, Object> entry : v.entrySet()) { + map.addEntry(entry.getKey(), entry.getValue()); } return map; @@ -49,9 +51,9 @@ public class MapAdapter extends XmlAdapter<MapEntry, Map<String, Object>> { return null; } - Map<String, Object> map = new HashMap<>(v.entry.size()); + Map<String, Object> map = new HashMap<>(v.getEntry().size()); - for (MapElements entry : v.entry) { + for (MapElements entry : v.getEntry()) { if (entry.value instanceof Element) { map.put(entry.key, ((Element) entry.value).getTextContent()); } else { diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapElements.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapElements.java index 0327fd67a3..3dd339dc68 100644 --- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapElements.java +++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapElements.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -35,7 +37,9 @@ public class MapElements { @XmlElement public Object value; - public MapElements() {} // Required by JAXB + public MapElements() { + // Required by JAXB + } public MapElements(String key, Object value) { this.key = key; @@ -46,7 +50,7 @@ public class MapElements { try { this.value = new ObjectMapper().writeValueAsString(value); } catch (JsonProcessingException e) { - logger.warn("could not marshal value to json, calling toString"); + logger.warn("could not marshal value to json, calling toString", e); this.value = value.toString(); } } else { diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapEntry.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapEntry.java index 489e11e111..b6b121c820 100644 --- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapEntry.java +++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/MapEntry.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -25,12 +27,23 @@ import java.util.List; public class MapEntry { - public List<MapElements> entry = new ArrayList<>(); + private List<MapElements> entry = new ArrayList<>(); - public MapEntry() {} // Required by JAXB + public MapEntry() { + // Required by JAXB + } - public void addEntry(String key, Object value) { + void addEntry(String key, Object value) { entry.add(new MapElements(key, value)); } + public List<MapElements> getEntry() { + // Required by JAXB + return entry; + } + + public void setEntry(List<MapElements> entry) { + // Required by JAXB + this.entry = entry; + } } diff --git a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/JAXBMarshallingTest.java b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/JAXBMarshallingTest.java index 189d4cca3e..5089ba1301 100644 --- a/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/JAXBMarshallingTest.java +++ b/adapters/mso-adapters-rest-interface/src/test/java/org/onap/so/openstack/mappers/JAXBMarshallingTest.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -24,12 +26,13 @@ import static org.junit.Assert.assertEquals; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import org.junit.Test; import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; -import com.fasterxml.jackson.databind.ObjectMapper; public class JAXBMarshallingTest { @@ -53,11 +56,16 @@ public class JAXBMarshallingTest { CreateVfModuleRequest request = new CreateVfModuleRequest(); request.getVfModuleParams().put("test-null", null); + request.getVfModuleParams().put("vcpe_image_name", "ubuntu-16-04-cloud-amd64"); + request.getVfModuleParams().put("test-empty", ""); request.getVfModuleParams().put("test array", Arrays.asList("a", "b", "c")); + request.getVfModuleParams().put("test map", Collections.singletonMap("d", "e")); + request.getVfModuleParams().put("marshalling error", new ArrayList()); - assertEquals("documents are equal", + assertEquals("documents should be equal", new String(Files - .readAllBytes(Paths.get("src/test/resources/VfRequest-marshalled-with-complex-object.xml"))), + .readAllBytes(Paths.get("src/test/resources/VfRequest-marshalled-with-complex-object.xml"))) + .replaceAll("\\R", "\n"), request.toXmlString()); } diff --git a/adapters/mso-adapters-rest-interface/src/test/resources/VfRequest-marshalled-with-complex-object.xml b/adapters/mso-adapters-rest-interface/src/test/resources/VfRequest-marshalled-with-complex-object.xml index ce175127df..d4955f1b18 100644 --- a/adapters/mso-adapters-rest-interface/src/test/resources/VfRequest-marshalled-with-complex-object.xml +++ b/adapters/mso-adapters-rest-interface/src/test/resources/VfRequest-marshalled-with-complex-object.xml @@ -4,12 +4,28 @@ <backout>true</backout> <vfModuleParams> <entry> + <key>vcpe_image_name</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">ubuntu-16-04-cloud-amd64</value> + </entry> + <entry> <key>test array</key> <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">["a","b","c"]</value> </entry> <entry> + <key>test map</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">{"d":"e"}</value> + </entry> + <entry> <key>test-null</key> </entry> + <entry> + <key>marshalling error</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">[]</value> + </entry> + <entry> + <key>test-empty</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string"></value> + </entry> </vfModuleParams> <msoRequest/> </createVfModuleRequest> 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 0f46e91311..4d11858960 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 @@ -7,147 +7,147 @@ DELETE FROM building_block_detail; DELETE FROM orchestration_status_state_transition_directive; -INSERT INTO northbound_request_ref_lookup(MACRO_ACTION, ACTION, REQUEST_SCOPE, IS_ALACARTE,IS_TOPLEVELFLOW, MIN_API_VERSION, MAX_API_VERSION, CLOUD_OWNER) VALUES -('Service-Create', 'createInstance', 'Service', true,true, '7','7', 'cloudOwner'), -('Service-Delete', 'deleteInstance', 'Service', true,true, '7','7', 'cloudOwner'), -('Service-Macro-Assign', 'assignInstance', 'Service', false,true, '7','7', 'cloudOwner'), -('Service-Macro-Activate', 'activateInstance', 'Service', false,true, '7','7', 'cloudOwner'), -('Service-Macro-Unassign', 'unassignInstance', 'Service', false,true, '7','7', 'cloudOwner'), -('Service-Macro-Create', 'createInstance', 'Service', false,true, '7','7', 'cloudOwner'), -('Service-Macro-Delete', 'deleteInstance', 'Service', false,true, '7','7', 'cloudOwner'), -('Network-Create', 'createInstance', 'Network', true,true, '7','7', 'cloudOwner'), -('Network-Delete', 'deleteInstance', 'Network', true,true, '7','7', 'cloudOwner'), -('VNF-Macro-Recreate', 'recreateInstance', 'Vnf', false,true, '7','7', 'cloudOwner'), -('VNF-Macro-Replace', 'replaceInstance', 'Vnf', false,true, '7','7', 'cloudOwner'), -('VNF-Create', 'createInstance', 'Vnf', true,true, '7', '7', 'cloudOwner'), -('VNF-Delete', 'deleteInstance', 'Vnf', true,true, '7', '7', 'cloudOwner'), -('VolumeGroup-Create', 'createInstance', 'VolumeGroup', true,true, '7','7', 'cloudOwner'), -('VolumeGroup-Delete', 'deleteInstance', 'VolumeGroup', true,true, '7','7', 'cloudOwner'), -('VFModule-Create', 'createInstance', 'VfModule', true,true, '7','7', 'cloudOwner'), -('VFModule-Delete', 'deleteInstance', 'VfModule', true,true, '7','7', 'cloudOwner'), -('NetworkCollection-Macro-Create', 'createInstance', 'NetworkCollection', false,true, '7','7', 'cloudOwner'), -('NetworkCollection-Macro-Delete', 'deleteInstance', 'NetworkCollection', false,true, '7','7', 'cloudOwner'), -('VFModule-ScaleOut', 'createInstance', 'VfModule', true, true, '7','7', 'cloudOwner'); +INSERT INTO northbound_request_ref_lookup(MACRO_ACTION, ACTION, REQUEST_SCOPE, IS_ALACARTE,IS_TOPLEVELFLOW, MIN_API_VERSION, MAX_API_VERSION, CLOUD_OWNER, SERVICE_TYPE) VALUES +('Service-Create', 'createInstance', 'Service', true,true, '7','7', 'CloudOwner', '*'), +('Service-Delete', 'deleteInstance', 'Service', true,true, '7','7', 'CloudOwner', '*'), +('Service-Macro-Assign', 'assignInstance', 'Service', false,true, '7','7', 'CloudOwner', '*'), +('Service-Macro-Activate', 'activateInstance', 'Service', false,true, '7','7', 'CloudOwner', '*'), +('Service-Macro-Unassign', 'unassignInstance', 'Service', false,true, '7','7', 'CloudOwner', '*'), +('Service-Macro-Create', 'createInstance', 'Service', false,true, '7','7', 'CloudOwner', '*'), +('Service-Macro-Delete', 'deleteInstance', 'Service', false,true, '7','7', 'CloudOwner', '*'), +('Network-Create', 'createInstance', 'Network', true,true, '7','7', 'CloudOwner', '*'), +('Network-Delete', 'deleteInstance', 'Network', true,true, '7','7', 'CloudOwner', '*'), +('VNF-Macro-Recreate', 'recreateInstance', 'Vnf', false,true, '7','7', 'CloudOwner', '*'), +('VNF-Macro-Replace', 'replaceInstance', 'Vnf', false,true, '7','7', 'CloudOwner', '*'), +('VNF-Create', 'createInstance', 'Vnf', true,true, '7', '7', 'CloudOwner', '*'), +('VNF-Delete', 'deleteInstance', 'Vnf', true,true, '7', '7', 'CloudOwner', '*'), +('VolumeGroup-Create', 'createInstance', 'VolumeGroup', true,true, '7','7', 'CloudOwner', '*'), +('VolumeGroup-Delete', 'deleteInstance', 'VolumeGroup', true,true, '7','7', 'CloudOwner', '*'), +('VFModule-Create', 'createInstance', 'VfModule', true,true, '7','7', 'CloudOwner', '*'), +('VFModule-Delete', 'deleteInstance', 'VfModule', true,true, '7','7', 'CloudOwner', '*'), +('NetworkCollection-Macro-Create', 'createInstance', 'NetworkCollection', false,true, '7','7', 'CloudOwner', '*'), +('NetworkCollection-Macro-Delete', 'deleteInstance', 'NetworkCollection', false,true, '7','7', 'CloudOwner', '*'), +('VFModule-ScaleOut', 'scaleOut', 'VfModule', true, true, '7','7', 'CloudOwner', '*'); INSERT INTO orchestration_flow_reference(COMPOSITE_ACTION, SEQ_NO, FLOW_NAME, FLOW_VERSION, NB_REQ_REF_LOOKUP_ID) VALUES -('Service-Create', '1', 'AssignServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Create', '2', 'ActivateServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Delete', '1', 'DeactivateServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Delete', '2', 'UnassignServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Assign', '1', 'AssignServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Assign' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Assign', '2', 'AssignNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Assign' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Assign', '3', 'AssignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Assign' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Assign', '4', 'AssignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Assign' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Assign', '5', 'AssignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Assign' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Assign', '6', 'ConfigAssignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Assign' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Activate', '1', 'CreateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Activate', '2', 'ActivateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Activate', '3', 'CreateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Activate', '4', 'ActivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Activate', '5', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Activate', '6', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Activate', '7', 'ConfigDeployVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Activate', '8', 'ActivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Activate', '9', 'ActivateServiceInstance', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Unassign', '1', 'UnassignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Unassign' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Unassign', '2', 'UnassignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Unassign' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Unassign', '3', 'UnassignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Unassign' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Unassign', '4', 'UnassignNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Unassign' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Unassign', '5', 'UnassignServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Unassign' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '1', 'AssignServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '2', 'CreateNetworkCollectionBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '3', 'AssignNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '4', 'AssignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '5', 'AssignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '6', 'AssignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '7', 'ConfigAssignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '8', 'CreateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '9', 'ActivateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '10', 'CreateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '11', 'ActivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '12', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '13', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '14', 'ConfigDeployVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '15', 'ActivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '16', 'ActivateNetworkCollectionBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Create', '17', 'ActivateServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '1', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '2', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '3', 'DeactivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '4', 'DeleteVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '5', 'DeactivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '6', 'DeactivateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '7', 'DeleteNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '8', 'DeactivateNetworkCollectionBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '9', 'DeleteNetworkCollectionBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '10', 'DeactivateServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '11', 'UnassignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '12', 'UnassignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '13', 'UnassignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '14', 'UnassignNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Service-Macro-Delete', '15', 'UnassignServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Network-Create', '1', 'AssignNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Create' and CLOUD_OWNER = 'cloudOwner')), -('Network-Create', '2', 'CreateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Create' and CLOUD_OWNER = 'cloudOwner')), -('Network-Create', '3', 'ActivateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Create' and CLOUD_OWNER = 'cloudOwner')), -('Network-Delete', '1', 'DeactivateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Network-Delete', '2', 'DeleteNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Delete' and CLOUD_OWNER = 'cloudOwner')), -('Network-Delete', '3', 'UnassignNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Delete' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Create', '1', 'AssignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Create' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Create', '2', 'ActivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Create' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Delete', '1', 'DeactivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Delete' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Delete', '2', 'UnassignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Delete' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Recreate', '1', 'AAICheckVnfInMaintBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Recreate', '2', 'AAISetVnfInMaintBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Recreate', '3', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Recreate', '4', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Recreate', '5', 'DeactivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Recreate', '6', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Recreate', '7', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Recreate', '8', 'ActivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Recreate', '9', 'SDNOVnfHealthCheckBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Recreate', '10', 'AAIUnsetVnfInMaintBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Replace', '1', 'AAICheckVnfInMaintBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Replace', '2', 'AAISetVnfInMaintBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Replace', '5', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Replace', '6', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Replace', '7', 'DeactivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Replace', '8', 'ChangeModelVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Replace', '9', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Replace', '10', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Replace', '13', 'ChangeModelVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Replace', '14', 'ActivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Replace', '15', 'ChangeModelServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Replace', '16', 'SDNOVnfHealthCheckBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'cloudOwner')), -('VNF-Macro-Replace', '17', 'AAIUnsetVnfInMaintBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'cloudOwner')), -('VolumeGroup-Create', '1', 'AssignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VolumeGroup-Create' and CLOUD_OWNER = 'cloudOwner')), -('VolumeGroup-Create', '2', 'CreateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VolumeGroup-Create' and CLOUD_OWNER = 'cloudOwner')), -('VolumeGroup-Create', '3', 'ActivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VolumeGroup-Create' and CLOUD_OWNER = 'cloudOwner')), -('VolumeGroup-Delete', '1', 'DeactivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VolumeGroup-Delete' and CLOUD_OWNER = 'cloudOwner')), -('VolumeGroup-Delete', '2', 'DeleteVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VolumeGroup-Delete' and CLOUD_OWNER = 'cloudOwner')), -('VolumeGroup-Delete', '3', 'UnassignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VolumeGroup-Delete' and CLOUD_OWNER = 'cloudOwner')), -('VFModule-Create', '1', 'AssignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Create' and CLOUD_OWNER = 'cloudOwner')), -('VFModule-Create', '2', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Create' and CLOUD_OWNER = 'cloudOwner')), -('VFModule-Create', '3', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Create' and CLOUD_OWNER = 'cloudOwner')), -('VFModule-Delete', '3', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Delete' and CLOUD_OWNER = 'cloudOwner')), -('VFModule-Delete', '4', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Delete' and CLOUD_OWNER = 'cloudOwner')), -('VFModule-Delete', '5', 'UnassignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Delete' and CLOUD_OWNER = 'cloudOwner')), -('NetworkCollection-Macro-Create', '1', 'CreateNetworkCollectionBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('NetworkCollection-Macro-Create', '2', 'AssignNetworkBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('NetworkCollection-Macro-Create', '3', 'CreateNetworkBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('NetworkCollection-Macro-Create', '4', 'ActivateNetworkBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('NetworkCollection-Macro-Create', '5', 'ActivateNetworkCollectionBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Create' and CLOUD_OWNER = 'cloudOwner')), -('NetworkCollection-Macro-Delete', '1', 'DeactivateNetworkBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('NetworkCollection-Macro-Delete', '2', 'DeleteNetworkBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('NetworkCollection-Macro-Delete', '3', 'UnassignNetworkBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('NetworkCollection-Macro-Delete', '4', 'DeactivateNetworkCollectionBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('NetworkCollection-Macro-Delete', '5', 'DeleteNetworkCollectionBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Delete' and CLOUD_OWNER = 'cloudOwner')), -('VFModule-ScaleOut', '1', 'GenericVnfHealthCheckBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'cloudOwner')), -('VFModule-ScaleOut', '2', 'AssignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'cloudOwner')), -('VFModule-ScaleOut', '3', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'cloudOwner')), -('VFModule-ScaleOut', '4', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'cloudOwner')), -('VFModule-ScaleOut', '5', 'ConfigurationScaleOutBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'cloudOwner')), -('VFModule-ScaleOut', '6', 'GenericVnfHealthCheckBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'cloudOwner')); +('Service-Create', '1', 'AssignServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Create', '2', 'ActivateServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Delete', '1', 'DeactivateServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Delete', '2', 'UnassignServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Assign', '1', 'AssignServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Assign' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Assign', '2', 'AssignNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Assign' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Assign', '3', 'AssignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Assign' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Assign', '4', 'AssignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Assign' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Assign', '5', 'AssignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Assign' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Assign', '6', 'ConfigAssignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Assign' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Activate', '1', 'CreateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Activate', '2', 'ActivateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Activate', '3', 'CreateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Activate', '4', 'ActivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Activate', '5', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Activate', '6', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Activate', '7', 'ConfigDeployVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Activate', '8', 'ActivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Activate', '9', 'ActivateServiceInstance', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Activate' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Unassign', '1', 'UnassignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Unassign' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Unassign', '2', 'UnassignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Unassign' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Unassign', '3', 'UnassignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Unassign' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Unassign', '4', 'UnassignNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Unassign' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Unassign', '5', 'UnassignServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Unassign' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '1', 'AssignServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '2', 'CreateNetworkCollectionBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '3', 'AssignNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '4', 'AssignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '5', 'AssignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '6', 'AssignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '7', 'ConfigAssignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '8', 'CreateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '9', 'ActivateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '10', 'CreateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '11', 'ActivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '12', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '13', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '14', 'ConfigDeployVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '15', 'ActivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '16', 'ActivateNetworkCollectionBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Create', '17', 'ActivateServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '1', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '2', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '3', 'DeactivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '4', 'DeleteVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '5', 'DeactivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '6', 'DeactivateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '7', 'DeleteNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '8', 'DeactivateNetworkCollectionBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '9', 'DeleteNetworkCollectionBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '10', 'DeactivateServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '11', 'UnassignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '12', 'UnassignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '13', 'UnassignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '14', 'UnassignNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Service-Macro-Delete', '15', 'UnassignServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Network-Create', '1', 'AssignNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Create' and CLOUD_OWNER = 'CloudOwner')), +('Network-Create', '2', 'CreateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Create' and CLOUD_OWNER = 'CloudOwner')), +('Network-Create', '3', 'ActivateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Create' and CLOUD_OWNER = 'CloudOwner')), +('Network-Delete', '1', 'DeactivateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Network-Delete', '2', 'DeleteNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Delete' and CLOUD_OWNER = 'CloudOwner')), +('Network-Delete', '3', 'UnassignNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Delete' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Create', '1', 'AssignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Create' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Create', '2', 'ActivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Create' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Delete', '1', 'DeactivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Delete' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Delete', '2', 'UnassignVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Delete' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Recreate', '1', 'AAICheckVnfInMaintBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Recreate', '2', 'AAISetVnfInMaintBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Recreate', '3', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Recreate', '4', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Recreate', '5', 'DeactivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Recreate', '6', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Recreate', '7', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Recreate', '8', 'ActivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Recreate', '9', 'SDNOVnfHealthCheckBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Recreate', '10', 'AAIUnsetVnfInMaintBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Recreate' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Replace', '1', 'AAICheckVnfInMaintBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Replace', '2', 'AAISetVnfInMaintBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Replace', '5', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Replace', '6', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Replace', '7', 'DeactivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Replace', '8', 'ChangeModelVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Replace', '9', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Replace', '10', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Replace', '13', 'ChangeModelVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Replace', '14', 'ActivateVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Replace', '15', 'ChangeModelServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Replace', '16', 'SDNOVnfHealthCheckBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'CloudOwner')), +('VNF-Macro-Replace', '17', 'AAIUnsetVnfInMaintBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Macro-Replace' and CLOUD_OWNER = 'CloudOwner')), +('VolumeGroup-Create', '1', 'AssignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VolumeGroup-Create' and CLOUD_OWNER = 'CloudOwner')), +('VolumeGroup-Create', '2', 'CreateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VolumeGroup-Create' and CLOUD_OWNER = 'CloudOwner')), +('VolumeGroup-Create', '3', 'ActivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VolumeGroup-Create' and CLOUD_OWNER = 'CloudOwner')), +('VolumeGroup-Delete', '1', 'DeactivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VolumeGroup-Delete' and CLOUD_OWNER = 'CloudOwner')), +('VolumeGroup-Delete', '2', 'DeleteVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VolumeGroup-Delete' and CLOUD_OWNER = 'CloudOwner')), +('VolumeGroup-Delete', '3', 'UnassignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VolumeGroup-Delete' and CLOUD_OWNER = 'CloudOwner')), +('VFModule-Create', '1', 'AssignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Create' and CLOUD_OWNER = 'CloudOwner')), +('VFModule-Create', '2', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Create' and CLOUD_OWNER = 'CloudOwner')), +('VFModule-Create', '3', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Create' and CLOUD_OWNER = 'CloudOwner')), +('VFModule-Delete', '3', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Delete' and CLOUD_OWNER = 'CloudOwner')), +('VFModule-Delete', '4', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Delete' and CLOUD_OWNER = 'CloudOwner')), +('VFModule-Delete', '5', 'UnassignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Delete' and CLOUD_OWNER = 'CloudOwner')), +('NetworkCollection-Macro-Create', '1', 'CreateNetworkCollectionBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('NetworkCollection-Macro-Create', '2', 'AssignNetworkBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('NetworkCollection-Macro-Create', '3', 'CreateNetworkBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('NetworkCollection-Macro-Create', '4', 'ActivateNetworkBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('NetworkCollection-Macro-Create', '5', 'ActivateNetworkCollectionBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Create' and CLOUD_OWNER = 'CloudOwner')), +('NetworkCollection-Macro-Delete', '1', 'DeactivateNetworkBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('NetworkCollection-Macro-Delete', '2', 'DeleteNetworkBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('NetworkCollection-Macro-Delete', '3', 'UnassignNetworkBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('NetworkCollection-Macro-Delete', '4', 'DeactivateNetworkCollectionBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('NetworkCollection-Macro-Delete', '5', 'DeleteNetworkCollectionBB',1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'NetworkCollection-Macro-Delete' and CLOUD_OWNER = 'CloudOwner')), +('VFModule-ScaleOut', '1', 'GenericVnfHealthCheckBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'CloudOwner')), +('VFModule-ScaleOut', '2', 'AssignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'CloudOwner')), +('VFModule-ScaleOut', '3', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'CloudOwner')), +('VFModule-ScaleOut', '4', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'CloudOwner')), +('VFModule-ScaleOut', '5', 'ConfigurationScaleOutBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'CloudOwner')), +('VFModule-ScaleOut', '6', 'GenericVnfHealthCheckBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'CloudOwner')); INSERT INTO rainy_day_handler_macro (FLOW_NAME, SERVICE_TYPE, VNF_TYPE, ERROR_CODE, WORK_STEP, POLICY) VALUES @@ -234,8 +234,8 @@ VALUES ('DeleteNetworkBB', 'NETWORK', 'DELETE'), ('DeleteNetworkCollectionBB', 'NETWORK', 'DELETE'), -('ConfigurationScaleOutBB', 'VF_MODULE', 'CREATE'), -('GenericVnfHealthCheckBB', 'VF_MODULE', 'CREATE'); +('ConfigurationScaleOutBB', 'NO_VALIDATE', 'CUSTOM'), +('GenericVnfHealthCheckBB', 'NO_VALIDATE', 'CUSTOM'); INSERT INTO orchestration_status_state_transition_directive (resource_type, orchestration_status, target_action, flow_directive) VALUES @@ -597,40 +597,40 @@ WHERE TARGET_ACTION = 'CHANGEMODEL'; INSERT INTO building_block_detail(BUILDING_BLOCK_NAME, RESOURCE_TYPE, TARGET_ACTION) VALUES ('UnassignVfModuleBB', 'VF_MODULE', 'UNASSIGN'), -('SniroHoming', 'CUSTOM', 'CUSTOM'), -('DeactivateAndUnassignVpnBondingLinksBB', 'CUSTOM', 'CUSTOM'), -('DeactivateNetworkCollectionBB', 'CUSTOM', 'CUSTOM'), -('AAICheckVnfInMaintBB', 'CUSTOM', 'CUSTOM'), -('AAISetVnfInMaintBB', 'CUSTOM', 'CUSTOM'), -('AAIUnsetVnfInMaintBB', 'CUSTOM', 'CUSTOM'), -('SDNOVnfHealthCheckBB', 'CUSTOM', 'CUSTOM'), -('VNF-Macro-Replace', 'CUSTOM', 'CUSTOM'), -('HomingBB', 'CUSTOM', 'CUSTOM'); +('SniroHoming', 'NO_VALIDATE', 'CUSTOM'), +('DeactivateAndUnassignVpnBondingLinksBB', 'NO_VALIDATE', 'CUSTOM'), +('DeactivateNetworkCollectionBB', 'NO_VALIDATE', 'CUSTOM'), +('AAICheckVnfInMaintBB', 'NO_VALIDATE', 'CUSTOM'), +('AAISetVnfInMaintBB', 'NO_VALIDATE', 'CUSTOM'), +('AAIUnsetVnfInMaintBB', 'NO_VALIDATE', 'CUSTOM'), +('SDNOVnfHealthCheckBB', 'NO_VALIDATE', 'CUSTOM'), +('VNF-Macro-Replace', 'NO_VALIDATE', 'CUSTOM'), +('HomingBB', 'NO_VALIDATE', 'CUSTOM'); INSERT INTO orchestration_status_state_transition_directive(RESOURCE_TYPE, ORCHESTRATION_STATUS, TARGET_ACTION, FLOW_DIRECTIVE) VALUES -('CUSTOM', 'ACTIVE', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'ASSIGNED', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'CREATED', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'INVENTORIED', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'PENDING', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'PENDING_ACTIVATION', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'PENDING_CREATE', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'PENDING_DELETE', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'PRECREATED', 'CUSTOM', 'CONTINUE'); - -INSERT INTO northbound_request_ref_lookup(MACRO_ACTION, ACTION, REQUEST_SCOPE, IS_ALACARTE, MIN_API_VERSION, MAX_API_VERSION, IS_TOPLEVELFLOW, CLOUD_OWNER) VALUES -('VFModule-DeactivateAndCloudDelete', 'deactivateAndCloudDelete', 'VfModule', true, '7','7', true, 'cloudOwner'); +('NO_VALIDATE', 'ACTIVE', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'ASSIGNED', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'CREATED', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'INVENTORIED', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'PENDING', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'PENDING_ACTIVATION', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'PENDING_CREATE', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'PENDING_DELETE', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'PRECREATED', 'CUSTOM', 'CONTINUE'); + +INSERT INTO northbound_request_ref_lookup(MACRO_ACTION, ACTION, REQUEST_SCOPE, IS_ALACARTE, MIN_API_VERSION, MAX_API_VERSION, IS_TOPLEVELFLOW, CLOUD_OWNER, SERVICE_TYPE) VALUES +('VFModule-DeactivateAndCloudDelete', 'deactivateAndCloudDelete', 'VfModule', true, '7','7', true, 'CloudOwner', '*'); INSERT INTO orchestration_flow_reference(COMPOSITE_ACTION, SEQ_NO, FLOW_NAME, FLOW_VERSION, NB_REQ_REF_LOOKUP_ID) VALUES -('VFModule-DeactivateAndCloudDelete', '1', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-DeactivateAndCloudDelete' and CLOUD_OWNER = 'cloudOwner')), -('VFModule-DeactivateAndCloudDelete', '2', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-DeactivateAndCloudDelete' and CLOUD_OWNER = 'cloudOwner')); +('VFModule-DeactivateAndCloudDelete', '1', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-DeactivateAndCloudDelete' and CLOUD_OWNER = 'CloudOwner')), +('VFModule-DeactivateAndCloudDelete', '2', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-DeactivateAndCloudDelete' and CLOUD_OWNER = 'CloudOwner')); -INSERT INTO northbound_request_ref_lookup (REQUEST_SCOPE, MACRO_ACTION, ACTION, IS_ALACARTE, MIN_API_VERSION, MAX_API_VERSION, IS_TOPLEVELFLOW, CLOUD_OWNER) -values ( 'Service', 'Service-Macro-Deactivate', 'deactivateInstance', '0', '7', '7', '1', 'cloudOwner'); +INSERT INTO northbound_request_ref_lookup (REQUEST_SCOPE, MACRO_ACTION, ACTION, IS_ALACARTE, MIN_API_VERSION, MAX_API_VERSION, IS_TOPLEVELFLOW, CLOUD_OWNER, SERVICE_TYPE) +values ( 'Service', 'Service-Macro-Deactivate', 'deactivateInstance', '0', '7', '7', '1', 'CloudOwner', '*'); INSERT INTO orchestration_flow_reference (COMPOSITE_ACTION, SEQ_NO, FLOW_NAME, FLOW_VERSION, NB_REQ_REF_LOOKUP_ID) -values ( 'Service-Macro-Deactivate', '1', 'DeactivateServiceInstanceBB', '1', (SELECT id FROM northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Deactivate' and CLOUD_OWNER = 'cloudOwner')); +values ( 'Service-Macro-Deactivate', '1', 'DeactivateServiceInstanceBB', '1', (SELECT id FROM northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Macro-Deactivate' and CLOUD_OWNER = 'CloudOwner')); UPDATE northbound_request_ref_lookup SET MIN_API_VERSION = 5 WHERE MACRO_ACTION = 'Service-Macro-Create'; @@ -639,10 +639,10 @@ UPDATE northbound_request_ref_lookup SET MIN_API_VERSION = 5 WHERE MACRO_ACTION UPDATE northbound_request_ref_lookup SET MIN_API_VERSION = 5 WHERE MACRO_ACTION = 'Service-Macro-Deactivate'; -INSERT INTO northbound_request_ref_lookup(MACRO_ACTION, ACTION, REQUEST_SCOPE, IS_ALACARTE, MIN_API_VERSION, MAX_API_VERSION, IS_TOPLEVELFLOW, CLOUD_OWNER) VALUES -('Network-Update', 'updateInstance', 'Network', true, '7','7','1', 'cloudOwner'); +INSERT INTO northbound_request_ref_lookup(MACRO_ACTION, ACTION, REQUEST_SCOPE, IS_ALACARTE, MIN_API_VERSION, MAX_API_VERSION, IS_TOPLEVELFLOW, CLOUD_OWNER, SERVICE_TYPE) VALUES +('Network-Update', 'updateInstance', 'Network', true, '7','7','1', 'CloudOwner', '*'); INSERT INTO orchestration_flow_reference(COMPOSITE_ACTION, SEQ_NO, FLOW_NAME, FLOW_VERSION, NB_REQ_REF_LOOKUP_ID) VALUES -('Network-Update', '1', 'UpdateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Update' and CLOUD_OWNER = 'cloudOwner')); +('Network-Update', '1', 'UpdateNetworkBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Network-Update' and CLOUD_OWNER = 'CloudOwner')); INSERT INTO building_block_detail(BUILDING_BLOCK_NAME,RESOURCE_TYPE,TARGET_ACTION) VALUES ('UpdateNetworkBB','NETWORK','UPDATE'); @@ -778,5 +778,38 @@ VALUES ('GenericVnfHealthCheckBB', '*', '*', '*', "*" , 'Retry'), ('ConfigurationScaleOutBB', '*', '*', '*', "*" , 'Retry'); +INSERT INTO building_block_detail(BUILDING_BLOCK_NAME, RESOURCE_TYPE, TARGET_ACTION) +VALUES +('VNFSetInMaintFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFCheckPserversLockedFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFCheckInMaintFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFCheckClosedLoopDisabledFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFSetClosedLoopDisabledFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUnsetClosedLoopDisabledFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFLockActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUnlockActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFStopActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFStartActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFSnapShotActivity', 'NO_VALIDATE', 'CUSTOM'), +('FlowCompleteActivity', 'NO_VALIDATE', 'CUSTOM'), +('PauseForManualTaskActivity', 'NO_VALIDATE', 'CUSTOM'), +('DistributeTrafficActivity', 'NO_VALIDATE', 'CUSTOM'), +('DistributeTrafficCheckActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFHealthCheckActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFQuiesceTrafficActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFResumeTrafficActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUnsetInMaintFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUpgradeBackupActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUpgradePostCheckActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUpgradePreCheckActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUpgradeSoftwareActivity', 'NO_VALIDATE', 'CUSTOM'), +('VnfInPlaceSoftwareUpdate', 'NO_VALIDATE', 'CUSTOM'); + +UPDATE northbound_request_ref_lookup SET SERVICE_TYPE = '*' WHERE SERVICE_TYPE IS NULL; + +INSERT INTO building_block_detail(BUILDING_BLOCK_NAME, RESOURCE_TYPE, TARGET_ACTION) +VALUES +('ConfigAssignVnfBB', 'NO_VALIDATE', 'CUSTOM'), +('ConfigDeployVnfBB', 'NO_VALIDATE', 'CUSTOM'); -UPDATE rainy_day_handler_macro SET reg_ex_error_message = '*' WHERE reg_ex_error_message IS null;
\ No newline at end of file +UPDATE rainy_day_handler_macro SET reg_ex_error_message = '*' WHERE reg_ex_error_message IS null; diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__WorkflowDesignerData.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__WorkflowDesignerData.sql index 054fb1af57..3f76334bd9 100644 --- a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__WorkflowDesignerData.sql +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__WorkflowDesignerData.sql @@ -148,6 +148,9 @@ VALUES ('existing_software_version','userParams','Existing Software Version','text','',1,50,''), ('tenantId','cloudConfiguration','Tenant/Project ID','text','',1,36,''), ('new_software_version','userParams','New Software Version','text','',1,50,''), +('book_name','userParams','Name of Commands Book Set','text','',1,50,''), +('node_list','userParams','List of Nodes','text','',1,200,''), +('file_parameter_content','userParams','Configuration File Content','text','',1,50000,''), ('lcpCloudRegionId','cloudConfiguration','Cloud Region ID','text','',1,7,''); INSERT INTO `activity_spec_to_user_parameters`(`ACTIVITY_SPEC_ID`,`USER_PARAMETERS_ID`) @@ -166,6 +169,18 @@ VALUES (select ID from user_parameters where NAME='tenantId')), ((select ID from activity_spec where NAME='VNFQuiesceTrafficActivity' and VERSION=1.0), (select ID from user_parameters where NAME='operations_timeout')), +((select ID from activity_spec where NAME='DistributeTrafficActivity' and VERSION=1.0), +(select ID from user_parameters where NAME='book_name')), +((select ID from activity_spec where NAME='DistributeTrafficActivity' and VERSION=1.0), +(select ID from user_parameters where NAME='node_list')), +((select ID from activity_spec where NAME='DistributeTrafficActivity' and VERSION=1.0), +(select ID from user_parameters where NAME='file_parameter_content')), +((select ID from activity_spec where NAME='DistributeTrafficCheckActivity' and VERSION=1.0), +(select ID from user_parameters where NAME='book_name')), +((select ID from activity_spec where NAME='DistributeTrafficCheckActivity' and VERSION=1.0), +(select ID from user_parameters where NAME='node_list')), +((select ID from activity_spec where NAME='DistributeTrafficCheckActivity' and VERSION=1.0), +(select ID from user_parameters where NAME='file_parameter_content')), ((select ID from activity_spec where NAME='VNFUpgradeBackupActivity' and VERSION=1.0), (select ID from user_parameters where NAME='existing_software_version')), ((select ID from activity_spec where NAME='VNFUpgradeBackupActivity' and VERSION=1.0), @@ -181,4 +196,10 @@ VALUES ((select ID from activity_spec where NAME='VNFUpgradeSoftwareActivity' and VERSION=1.0), (select ID from user_parameters where NAME='existing_software_version')), ((select ID from activity_spec where NAME='VNFUpgradeSoftwareActivity' and VERSION=1.0), -(select ID from user_parameters where NAME='new_software_version'));
\ No newline at end of file +(select ID from user_parameters where NAME='new_software_version')); + +INSERT INTO `workflow` (`ARTIFACT_UUID`,`ARTIFACT_NAME`,`NAME`,`OPERATION_NAME`,`VERSION`,`DESCRIPTION`,`RESOURCE_TARGET`,`SOURCE`) +VALUES +('9d45cd30-1a89-4993-87c1-6dd09c1696cf','VFModule-ScaleOut','VNF Scale Out','ScaleOut',1.0,'native static workflow to support ScaleOut','vfModule','native'), +('da6478e4-ea33-3346-ac12-ab121284a333','VnfInPlaceUpdate.bpmn','VNF In Place Software Update','inPlaceSoftwareUpdate',1.0,'native static workflow to support inPlaceSoftwareUpdate','vnf','native'), +('fdb3ac48-70f9-4584-bd92-253bdbdec1e1','VnfConfigUpdate.bpmn','VNF Config Update','applyConfigModify',1.0,'native static workflow to support applyConfigModify','vnf','native');
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.5.1__Correct_Default_NeutronNetwork.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.5.1__Correct_Default_NeutronNetwork.sql index 3d8f68408d..5d940fb9ea 100644 --- a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.5.1__Correct_Default_NeutronNetwork.sql +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.5.1__Correct_Default_NeutronNetwork.sql @@ -11,9 +11,9 @@ parameters: description: Name of the Neutron Network default: ONAP-NW1 shared: - type: boolean - description: Shared amongst tenants - default: False + type: boolean + description: Shared amongst tenants + default: False outputs: network_id: description: Openstack network identifier diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.0__AddNamingPolicyToService.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.0__AddNamingPolicyToService.sql new file mode 100644 index 0000000000..3c45507b81 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.0__AddNamingPolicyToService.sql @@ -0,0 +1,8 @@ +USE catalogdb; + +ALTER TABLE service +ADD IF NOT EXISTS ONAP_GENERATED_NAMING tinyint(1) DEFAULT NULL; + +ALTER TABLE service +ADD IF NOT EXISTS NAMING_POLICY varchar(200) DEFAULT NULL; + diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/CatalogDbAdapterBaseTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/CatalogDbAdapterBaseTest.java index 3fb156d68a..499310748e 100644 --- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/CatalogDbAdapterBaseTest.java +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/CatalogDbAdapterBaseTest.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.adapters.catalogdb; import org.junit.Test; diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java index b8161de6b2..8decd77656 100644 --- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.adapters.catalogdb.catalogrest; import static com.shazam.shazamcrest.MatcherAssert.assertThat; 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 31cb1248d6..f65f521605 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 @@ -77,8 +77,12 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @Before public void initialize() { client.wiremockPort = String.valueOf(port); + client.setEndpoint(getEndpoint(port)); } + protected String getEndpoint(int port) { + return "http://localhost:" + port; + } @Test public void testGetRainyDayHandler_Regex() { @@ -88,6 +92,14 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { } @Test + 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"); + Assert.assertEquals("Rollback", rainyDayHandlerStatus.getPolicy()); + } + + @Test public void testGetCloudSiteHappyPath() throws Exception { CloudSite cloudSite = client.getCloudSite(MTN13); Assert.assertNotNull(cloudSite); @@ -640,7 +652,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @Test public void getWorkflowByArtifactUUID_validUuid_expectedOutput() { Workflow workflow = client.findWorkflowByArtifactUUID("5b0c4322-643d-4c9f-b184-4516049e99b1"); - assertEquals("artifactName", "testingWorkflow", workflow.getArtifactName()); + assertEquals("artifactName", "testingWorkflow.bpmn", workflow.getArtifactName()); } @Test @@ -655,7 +667,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { assertTrue(workflows != null); assertTrue(workflows.size() != 0); - assertEquals("testingWorkflow", workflows.get(0).getArtifactName()); + assertEquals("testingWorkflow.bpmn", workflows.get(0).getArtifactName()); } @Test @@ -664,4 +676,19 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { Assert.assertNull(workflow); } + @Test + public void getWorkflowBySource_validSource_expectedOutput() { + List<Workflow> workflows = client.findWorkflowBySource("sdc"); + assertTrue(workflows != null); + assertTrue(workflows.size() != 0); + + assertEquals("testingWorkflow.bpmn", workflows.get(0).getArtifactName()); + } + + @Test + public void getWorkflowBySource_invalidSource_nullOutput() { + List<Workflow> workflow = client.findWorkflowBySource("abc"); + Assert.assertNull(workflow); + } + } 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 0e981f2b70..58b2983f82 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 @@ -228,7 +228,7 @@ insert into pnf_resource_customization_to_service(service_model_uuid, resource_m ('5df8b6de-2083-11e7-93ae-92361f002676', '68dc9a92-214c-11e7-93ae-92361f002680'); insert into workflow(artifact_uuid, artifact_name, name, operation_name, version, description, body, resource_target, source) values -('5b0c4322-643d-4c9f-b184-4516049e99b1', 'testingWorkflow', 'testingWorkflow', 'create', 1, 'Test Workflow', null, 'vnf', 'sdc'); +('5b0c4322-643d-4c9f-b184-4516049e99b1', 'testingWorkflow.bpmn', 'testingWorkflow', 'create', 1, 'Test Workflow', null, 'vnf', 'sdc'); insert into vnf_resource_to_workflow(vnf_resource_model_uuid, workflow_id) values ('ff2ae348-214a-11e7-93ae-92361f002671', '1'); 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 57d31bf308..576acb1fd8 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 @@ -53,8 +53,9 @@ public class AuditStackService { public void auditAddAAIInventory() throws Exception { for (int i = 0; i < getMaxClients(); i++) { ExternalTaskClient client = createExternalTaskClient(); - client.subscribe("InventoryAddAudit").lockDuration(60000).handler(auditCreateStack::executeExternalTask) - .open(); + client.subscribe("InventoryAddAudit") + .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", "60000"))) + .handler(auditCreateStack::executeExternalTask).open(); } } @@ -62,8 +63,9 @@ public class AuditStackService { public void auditDeleteAAIInventory() throws Exception { for (int i = 0; i < getMaxClients(); i++) { ExternalTaskClient client = createExternalTaskClient(); - client.subscribe("InventoryDeleteAudit").lockDuration(60000).handler(auditDeleteStack::executeExternalTask) - .open(); + client.subscribe("InventoryDeleteAudit") + .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", "60000"))) + .handler(auditDeleteStack::executeExternalTask).open(); } } @@ -71,7 +73,7 @@ public class AuditStackService { ClientRequestInterceptor interceptor = createClientRequestInterceptor(); ExternalTaskClient client = ExternalTaskClient.create() .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor) - .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(10000, 2, 120000)).build(); + .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build(); return client; } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java index 8bd813026f..49a9e7e171 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java @@ -59,7 +59,9 @@ public class CreateInventoryService { ExternalTaskClient client = ExternalTaskClient.create() .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor) .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build(); - client.subscribe("InventoryCreate").lockDuration(60000).handler(createInventory::executeExternalTask).open(); + client.subscribe("InventoryCreate") + .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", "60000"))) + .handler(createInventory::executeExternalTask).open(); } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java index 24fa9af7f9..ed31c1c67e 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.adapters.inventory.create; public class InventoryException extends Exception { diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImpl.java index 429948cef1..a9af3683f5 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImpl.java @@ -47,6 +47,7 @@ import org.onap.so.adapters.network.async.client.UpdateNetworkNotification; import org.onap.so.adapters.network.exceptions.NetworkException; import org.onap.so.entity.MsoRequest; import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.NetworkRollback; import org.onap.so.openstack.beans.NetworkStatus; @@ -404,7 +405,7 @@ public class MsoNetworkAdapterAsyncImpl implements MsoNetworkAdapterAsync { return; } - logger.info("{} {}", MessageEnum.RA_ASYNC_ROLLBACK, rollback.getNetworkStackId()); + logger.info(LoggingAnchor.TWO, MessageEnum.RA_ASYNC_ROLLBACK, rollback.getNetworkStackId()); // Use the synchronous method to perform the actual Create diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java index 029da43f48..d2c0d9cabd 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java @@ -33,6 +33,7 @@ import java.util.Map; import java.util.Optional; import javax.jws.WebService; import javax.xml.ws.Holder; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.adapters.network.beans.ContrailPolicyRef; import org.onap.so.adapters.network.beans.ContrailPolicyRefSeq; import org.onap.so.adapters.network.beans.ContrailSubnet; @@ -205,7 +206,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { String error = String.format( "Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration", networkName, cloudSiteId, tenantId); - logger.error("{} {} {}", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); // Set the detailed error as the Exception 'message' throw new NetworkException(error, MsoExceptionCategory.USERDATA); } @@ -240,8 +241,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { if (failIfExists != null && failIfExists) { String error = String.format("Create Nework: Network %s already exists in %s/%s with ID %s", networkName, cloudSiteId, tenantId, netInfo.getId()); - logger.error("{} {} {}", MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(), - error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_NETWORK_ALREADY_EXIST, + ErrorCode.DataError.getValue(), error); throw new NetworkException(error, MsoExceptionCategory.USERDATA); } else { // Populate the outputs from the existing network. @@ -285,7 +286,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { HeatTemplate heatTemplate = networkResource.getHeatTemplate(); if (heatTemplate == null) { String error = String.format("Network error - undefined Heat Template. Network Type = %s", networkType); - logger.error("{} {} {}", MessageEnum.RA_PARAM_NOT_FOUND, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_PARAM_NOT_FOUND, ErrorCode.DataError.getValue(), + error); throw new NetworkException(error, MsoExceptionCategory.INTERNAL); } @@ -322,8 +324,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { if (failIfExists != null && failIfExists) { String error = String.format("CreateNetwork: Stack %s already exists in %s/%s as %s", networkName, cloudSiteId, tenantId, heatStack.getCanonicalName()); - logger.error("{} {} {}", MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(), - error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_NETWORK_ALREADY_EXIST, + ErrorCode.DataError.getValue(), error); throw new NetworkException(error, MsoExceptionCategory.USERDATA); } else { // Populate the outputs from the existing stack. @@ -371,7 +373,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { stackParams = heat.validateStackParams(stackParams, heatTemplate); } catch (IllegalArgumentException e) { String error = "Create Network: Configuration Error: " + e.getMessage(); - logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error, e); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error, e); // Input parameters were not valid throw new NetworkException(error, MsoExceptionCategory.INTERNAL); } @@ -537,7 +539,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { String error = String.format( "UpdateNetwork: Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration", networkName, cloudSiteId, tenantId); - logger.error("{} {} {}", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); // Set the detailed error as the Exception 'message' throw new NetworkException(error, MsoExceptionCategory.USERDATA); } @@ -569,8 +571,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { if (netInfo == null) { String error = String.format("Update Nework: Network %s does not exist in %s/%s", networkId, cloudSiteId, tenantId); - logger.error("{} {} {}", MessageEnum.RA_NETWORK_NOT_FOUND, ErrorCode.BusinessProcesssError.getValue(), - error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_NETWORK_NOT_FOUND, + ErrorCode.BusinessProcesssError.getValue(), error); // Does not exist. Throw an exception (can't update a non-existent network) throw new NetworkException(error, MsoExceptionCategory.USERDATA); } @@ -613,7 +615,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { if (heatStack == null || (heatStack.getStatus() == HeatStatus.NOTFOUND)) { String error = String.format("UpdateNetwork: Stack %s does not exist in %s/%s", networkName, cloudSiteId, tenantId); - logger.error("{} {} {}", MessageEnum.RA_NETWORK_NOT_FOUND, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_NETWORK_NOT_FOUND, ErrorCode.DataError.getValue(), + error); // Network stack does not exist. Return an error throw new NetworkException(error, MsoExceptionCategory.USERDATA); } @@ -644,7 +647,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { HeatTemplate heatTemplate = networkResource.getHeatTemplate(); if (heatTemplate == null) { String error = "Network error - undefined Heat Template. Network Type=" + networkType; - logger.error("{} {} {}", MessageEnum.RA_PARAM_NOT_FOUND, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_PARAM_NOT_FOUND, ErrorCode.DataError.getValue(), + error); throw new NetworkException(error, MsoExceptionCategory.INTERNAL); } @@ -672,7 +676,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { stackParams = heat.validateStackParams(stackParams, heatTemplate); } catch (IllegalArgumentException e) { String error = "UpdateNetwork: Configuration Error: Network Type=" + networkType; - logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); throw new NetworkException(error, MsoExceptionCategory.INTERNAL, e); } @@ -802,7 +806,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { String error = String.format( "Create/UpdateNetwork: Unable to get network resource with NetworkType: %s or ModelCustomizationUUID:%s", networkType, modelCustomizationUuid); - logger.error("{} {} {} ", MessageEnum.RA_UNKOWN_PARAM, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_UNKOWN_PARAM, ErrorCode.DataError.getValue(), error); throw new NetworkException(error, MsoExceptionCategory.USERDATA); } @@ -814,8 +818,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { // All Networks are orchestrated via HEAT or Neutron if (!("HEAT".equals(mode) || NEUTRON_MODE.equals(mode))) { String error = "CreateNetwork: Configuration Error: Network Type = " + networkType; - logger.error("{} {} {}", MessageEnum.RA_NETWORK_ORCHE_MODE_NOT_SUPPORT, ErrorCode.DataError.getValue(), - error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_NETWORK_ORCHE_MODE_NOT_SUPPORT, + ErrorCode.DataError.getValue(), error); throw new NetworkException(error, MsoExceptionCategory.INTERNAL); } @@ -836,7 +840,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { "Network Type:%s Version_Min:%s Version_Max:%s not supported on Cloud:%s with AIC_Version:%s", networkType, networkType, networkResource.getAicVersionMin(), networkResource.getAicVersionMax(), cloudSiteId, cloudSite.getCloudVersion()); - logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); throw new NetworkException(error, MsoExceptionCategory.USERDATA); } @@ -845,7 +849,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { validateNetworkParams(neutronNetworkType, networkName, physicalNetworkName, vlans, routeTargets); if (!missing.isEmpty()) { String error = "Create Network: Missing parameters: " + missing; - logger.error("{} {} {}", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); throw new NetworkException(error, MsoExceptionCategory.USERDATA); } @@ -890,7 +894,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { || commonUtils.isNullOrEmpty(networkNameOrId)) { String error = "Missing mandatory parameter cloudSiteId, tenantId or networkId"; - logger.error("{} {} {}", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); throw new NetworkException(error, MsoExceptionCategory.USERDATA); } @@ -899,7 +903,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { String error = String.format( "Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration", networkNameOrId, cloudSiteId, tenantId); - logger.error("{} {} {}", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); // Set the detailed error as the Exception 'message' throw new NetworkException(error, MsoExceptionCategory.USERDATA); } @@ -1017,7 +1021,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { if (commonUtils.isNullOrEmpty(cloudSiteId) || commonUtils.isNullOrEmpty(tenantId) || commonUtils.isNullOrEmpty(networkId)) { String error = "Missing mandatory parameter cloudSiteId, tenantId or networkId"; - logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); throw new NetworkException(error, MsoExceptionCategory.USERDATA); } @@ -1309,8 +1313,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { logger.debug("Json PolicyRefs Data:{}", jsonString); } catch (Exception e) { String error = "Error creating JsonNode for policyRefs Data"; - logger.error("{} {} {} ", MessageEnum.RA_MARSHING_ERROR, ErrorCode.BusinessProcesssError.getValue(), error, - e); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_MARSHING_ERROR, ErrorCode.BusinessProcesssError.getValue(), + error, e); throw new MsoAdapterException(error); } // update parameters @@ -1386,7 +1390,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { logger.debug("Json Subnet List:{}", jsonString); } catch (Exception e) { String error = "Error creating JsonNode from input subnets"; - logger.error("{} {} {} ", MessageEnum.RA_MARSHING_ERROR, ErrorCode.DataError.getValue(), error, e); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_MARSHING_ERROR, ErrorCode.DataError.getValue(), error, e); throw new MsoAdapterException(error); } // update parameters @@ -1432,7 +1436,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { curR = curR.replace("%subnetId%", subnet.getSubnetId()); } else { String error = "Missing Required AAI SubnetId for subnet in HEAT Template"; - logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); throw new MsoAdapterException(error); } @@ -1446,7 +1450,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { curR = curR.replace("%cidr%", subnet.getCidr()); } else { String error = "Missing Required cidr for subnet in HEAT Template"; - logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); throw new MsoAdapterException(error); } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImpl.java index 9236945d37..b81efa38e5 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImpl.java @@ -45,6 +45,7 @@ import org.onap.so.adapters.vnf.async.client.VnfAdapterNotify_Service; import org.onap.so.adapters.vnf.exceptions.VnfException; import org.onap.so.entity.MsoRequest; import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.VnfRollback; import org.onap.so.openstack.beans.VnfStatus; @@ -153,7 +154,7 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { logger.error("{} {} Exception sending createVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, ErrorCode.BusinessProcesssError.getValue(), e1); } - logger.info("{}", MessageEnum.RA_ASYNC_CREATE_VNF_COMPLETE); + logger.info(LoggingAnchor.ONE, MessageEnum.RA_ASYNC_CREATE_VNF_COMPLETE); return; } logger.debug("Async Create VNF: {} VnfId:{}", vnfName, vnfId.value); @@ -245,7 +246,7 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { MsoRequest msoRequest, String notificationUrl) { String serviceName = "QueryVnfA"; - logger.info("{}", MessageEnum.RA_ASYNC_QUERY_VNF); + logger.info(LoggingAnchor.ONE, MessageEnum.RA_ASYNC_QUERY_VNF); // Use the synchronous method to perform the actual query MsoVnfAdapter vnfAdapter = vnfImpl; @@ -323,7 +324,7 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { MsoRequest msoRequest, String notificationUrl) { String serviceName = "DeleteVnfA"; - logger.info("{}", MessageEnum.RA_ASYNC_DELETE_VNF); + logger.info(LoggingAnchor.ONE, MessageEnum.RA_ASYNC_DELETE_VNF); // Use the synchronous method to perform the actual delete MsoVnfAdapter vnfAdapter = vnfImpl; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java index bac41a1f8b..8511f3cb49 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java @@ -36,6 +36,7 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; import javax.jws.WebService; import javax.xml.ws.Holder; +import org.onap.so.logger.LoggingAnchor; import org.apache.commons.collections.CollectionUtils; import org.onap.so.adapters.valet.GenericValetResponse; import org.onap.so.adapters.valet.ValetClient; @@ -64,9 +65,9 @@ import org.onap.so.db.catalog.data.repository.VFModuleCustomizationRepository; import org.onap.so.db.catalog.data.repository.VnfResourceRepository; import org.onap.so.db.catalog.utils.MavenLikeVersioning; import org.onap.so.entity.MsoRequest; -import org.onap.so.logger.ErrorCode; import org.onap.so.heatbridge.HeatBridgeApi; import org.onap.so.heatbridge.HeatBridgeImpl; +import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.HeatStatus; import org.onap.so.openstack.beans.StackInfo; @@ -79,10 +80,6 @@ import org.onap.so.openstack.exceptions.MsoHeatNotFoundException; import org.onap.so.openstack.utils.MsoHeatEnvironmentEntry; import org.onap.so.openstack.utils.MsoHeatUtils; import org.onap.so.openstack.utils.MsoHeatUtilsWithUpdate; -import org.openstack4j.model.compute.Flavor; -import org.openstack4j.model.compute.Image; -import org.openstack4j.model.compute.Server; -import org.openstack4j.model.heat.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -92,6 +89,10 @@ import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import org.openstack4j.model.compute.Flavor; +import org.openstack4j.model.compute.Image; +import org.openstack4j.model.compute.Server; +import org.openstack4j.model.heat.Resource; @WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter", targetNamespace = "http://org.onap.so/vnf") @@ -107,6 +108,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { private static final Logger logger = LoggerFactory.getLogger(MsoVnfAdapterImpl.class); + private static final String VNF_ADAPTER_SERVICE_NAME = "MSO-BPMN:MSO-VnfAdapter."; private static final String CHECK_REQD_PARAMS = "org.onap.so.adapters.vnf.checkRequiredParameters"; private static final String ADD_GET_FILES_ON_VOLUME_REQ = "org.onap.so.adapters.vnf.addGetFilesOnVolumeReq"; @@ -115,14 +117,19 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { private static final String FAIL_REQUESTS_ON_VALET_FAILURE = "org.onap.so.adapters.vnf.fail_requests_on_valet_failure"; private static final String OPENSTACK = "OpenStack"; + private static final String DELETE_VNF = "DeleteVNF"; + private static final String QUERY_STACK = "QueryStack"; + private static final String CREATE_VFM_MODULE = "CreateVFModule"; + private static final String CREATE_VF_STACK = "Create VF: Stack"; + private static final String STACK = "Stack"; + private static final String USER_ERROR = "USER ERROR"; + private static final String VERSION_MIN = "VersionMin"; + private static final String VERSION_MAX = "VersionMax"; @Autowired private VFModuleCustomizationRepository vfModuleCustomRepo; - - @Autowired private VnfResourceRepository vnfResourceRepo; - @Autowired private MsoHeatUtilsWithUpdate heatU; @Autowired @@ -264,8 +271,8 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // Convert to a generic VnfException String error = "Query VNF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudSiteId, - tenantId, OPENSTACK, "QueryVNF", ErrorCode.DataError.getValue(), "Exception - queryStack", me); + logger.error(LoggingAnchor.EIGHT, MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudSiteId, tenantId, + OPENSTACK, "QueryVNF", ErrorCode.DataError.getValue(), "Exception - " + QUERY_STACK, me); logger.debug(error); throw new VnfException(me); } @@ -312,14 +319,13 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { try { heat.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true); } catch (MsoException me) { - me.addContext("DeleteVNF"); + me.addContext(DELETE_VNF); // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException String error = "Delete VNF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, - cloudSiteId, tenantId, OPENSTACK, "DeleteVNF", ErrorCode.DataError.getValue(), - "Exception - DeleteVNF", me); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, + tenantId, OPENSTACK, DELETE_VNF, ErrorCode.DataError.getValue(), "Exception - " + DELETE_VNF, me); logger.debug(error); throw new VnfException(me); } @@ -361,9 +367,8 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { me.addContext("RollbackVNF"); String error = "Rollback VNF: " + vnfId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfId, cloudOwner, - cloudSiteId, tenantId, OPENSTACK, "DeleteStack", ErrorCode.DataError.getValue(), - "Exception - DeleteStack", me); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfId, cloudOwner, cloudSiteId, + tenantId, OPENSTACK, "DeleteStack", ErrorCode.DataError.getValue(), "Exception - DeleteStack", me); logger.debug(error); throw new VnfException(me); } @@ -606,7 +611,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { requestTypeString = requestTypeString.substring(1); } - // 1607 - let's parse out the request type we're being sent + // let's parse out the request type we're being sent boolean isBaseRequest = false; boolean isVolumeRequest = false; if (requestTypeString.startsWith("VOLUME")) { @@ -615,8 +620,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { logger.debug("requestTypeString = " + requestTypeString + ", nestedStackId = " + nestedStackId + ", nestedBaseStackId = " + nestedBaseStackId); - // Will capture execution time for metrics - long startTime = System.currentTimeMillis(); // Build a default rollback object (no actions performed) VnfRollback vfRollback = new VnfRollback(); @@ -636,57 +639,56 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } StackInfo heatStack = null; - long subStartTime1 = System.currentTimeMillis(); try { heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vfModuleName); } catch (MsoException me) { String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, OPENSTACK, "queryStack", ErrorCode.DataError.getValue(), - "Exception - queryStack", me); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), + "Exception - " + QUERY_STACK, me); logger.debug(error); // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException - me.addContext("CreateVFModule"); + me.addContext(CREATE_VFM_MODULE); throw new VnfException(me); } - // New with 1607 - more precise handling/messaging if the stack already exists + // more precise handling/messaging if the stack already exists if (heatStack != null && heatStack.getStatus() != HeatStatus.NOTFOUND) { // INIT, CREATED, NOTFOUND, FAILED, BUILDING, DELETING, UNKNOWN, UPDATING, UPDATED HeatStatus status = heatStack.getStatus(); if (status == HeatStatus.INIT || status == HeatStatus.BUILDING || status == HeatStatus.DELETING || status == HeatStatus.UPDATING) { // fail - it's in progress - return meaningful error - String error = "Create VF: Stack " + vfModuleName + " already exists and has status " + String error = CREATE_VF_STACK + " " + vfModuleName + " already exists and has status " + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; please wait for it to complete, or fix manually."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, OPENSTACK, "queryStack", ErrorCode.DataError.getValue(), - "Stack " + vfModuleName + " already exists"); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), + STACK + " " + vfModuleName + " already exists"); logger.debug(error); throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, heatStack.getCanonicalName()); } if (status == HeatStatus.FAILED) { // fail - it exists and is in a FAILED state - String error = "Create VF: Stack " + vfModuleName + " already exists and is in FAILED state in " + String error = CREATE_VF_STACK + " " + vfModuleName + " already exists and is in FAILED state in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, OPENSTACK, "queryStack", ErrorCode.DataError.getValue(), - "Stack " + vfModuleName + " already exists and is " + "in FAILED state"); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), + STACK + " " + vfModuleName + " already exists and is " + "in FAILED state"); logger.debug(error); throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, heatStack.getCanonicalName()); } if (status == HeatStatus.UNKNOWN || status == HeatStatus.UPDATED) { // fail - it exists and is in a FAILED state - String error = "Create VF: Stack " + vfModuleName + " already exists and has status " + String error = CREATE_VF_STACK + " " + vfModuleName + " already exists and has status " + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, OPENSTACK, "queryStack", ErrorCode.DataError.getValue(), - "Stack " + vfModuleName + " already exists and is " + "in UPDATED or UNKNOWN state"); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), + STACK + " " + vfModuleName + " already exists and is " + "in UPDATED or UNKNOWN state"); logger.debug(error); throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, heatStack.getCanonicalName()); @@ -694,11 +696,11 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (status == HeatStatus.CREATED) { // fail - it exists if (failIfExists != null && failIfExists) { - String error = "Create VF: Stack " + vfModuleName + " already exists in " + cloudOwner + "/" + String error = CREATE_VF_STACK + " " + vfModuleName + " already exists in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), - vfModuleName, cloudOwner, cloudSiteId, tenantId, OPENSTACK, "queryStack", - ErrorCode.DataError.getValue(), "Stack " + vfModuleName + " already exists"); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), + STACK + " " + vfModuleName + " already exists"); logger.debug(error); throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, heatStack.getCanonicalName()); @@ -716,7 +718,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // handle a nestedStackId if sent- this one would be for the volume - so applies to both Vf and Vnf StackInfo nestedHeatStack = null; - long subStartTime2 = System.currentTimeMillis(); + Map<String, Object> nestedVolumeOutputs = null; if (nestedStackId != null) { try { @@ -725,20 +727,20 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } catch (MsoException me) { // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException - me.addContext("CreateVFModule"); + me.addContext(CREATE_VFM_MODULE); String error = "Create VFModule: Attached heatStack ID Query " + nestedStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, OPENSTACK, "queryStack", - ErrorCode.BusinessProcesssError.getValue(), "MsoException trying to query nested stack", me); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.BusinessProcesssError.getValue(), + "MsoException trying to query nested stack", me); logger.debug("ERROR trying to query nested stack= {}", error); throw new VnfException(me); } if (nestedHeatStack == null || nestedHeatStack.getStatus() == HeatStatus.NOTFOUND) { String error = "Create VFModule: Attached heatStack ID DOES NOT EXIST " + nestedStackId + " in " - + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR"; - logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, error, OPENSTACK, "queryStack", + + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " " + USER_ERROR; + logger.error(LoggingAnchor.TEN, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, error, OPENSTACK, QUERY_STACK, ErrorCode.BusinessProcesssError.getValue(), "Create VFModule: Attached heatStack ID " + "DOES NOT EXIST"); logger.debug(error); @@ -751,7 +753,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // handle a nestedBaseStackId if sent- this is the stack ID of the base. Should be null for VNF requests StackInfo nestedBaseHeatStack = null; - long subStartTime3 = System.currentTimeMillis(); Map<String, Object> baseStackOutputs = null; if (nestedBaseStackId != null) { try { @@ -760,21 +761,20 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } catch (MsoException me) { // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException - me.addContext("CreateVFModule"); + me.addContext(CREATE_VFM_MODULE); String error = "Create VFModule: Attached baseHeatStack ID Query " + nestedBaseStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, OPENSTACK, "QueryStack", - ErrorCode.BusinessProcesssError.getValue(), "MsoException trying to query nested base stack", - me); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.BusinessProcesssError.getValue(), + "MsoException trying to query nested base stack", me); logger.debug("ERROR trying to query nested base stack= {}", error); throw new VnfException(me); } if (nestedBaseHeatStack == null || nestedBaseHeatStack.getStatus() == HeatStatus.NOTFOUND) { String error = "Create VFModule: Attached base heatStack ID DOES NOT EXIST " + nestedBaseStackId - + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR"; - logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, error, OPENSTACK, "QueryStack", + + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " " + USER_ERROR; + logger.error(LoggingAnchor.TEN, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, error, OPENSTACK, QUERY_STACK, ErrorCode.BusinessProcesssError.getValue(), "Create VFModule: Attached base heatStack ID DOES NOT EXIST"); logger.debug("Exception occurred", error); @@ -785,30 +785,24 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } } - // Ready to deploy the new VNF - - - try { // Retrieve the VF VfModule vf = null; VnfResource vnfResource = null; VfModuleCustomization vfmc = null; - logger.debug("version: {}", vfVersion); if (useMCUuid) { - // 1707 - db refactoring vfmc = vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(mcu); if (vfmc != null) vf = vfmc.getVfModule(); else vf = null; - // 1702 - this will be the new way going forward. We find the vf by mcu - otherwise, code is the same. + // this will be the new way going forward. We find the vf by mcu - otherwise, code is the same. if (vf == null) { logger.debug("Unable to find vfModuleCust with modelCustomizationUuid={}", mcu); String error = "Create vfModule error: Unable to find vfModuleCust with modelCustomizationUuid=" + mcu; - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), + logger.error(LoggingAnchor.SIX, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VF Module ModelCustomizationUuid", modelCustomizationUuid, OPENSTACK, ErrorCode.DataError.getValue(), "Create VF Module: Unable to find vfModule with " + "modelCustomizationUuid=" + mcu); @@ -818,7 +812,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { logger.trace("Found vfModuleCust entry {}", vfmc.toString()); } if (vf.getIsBase()) { - isBaseRequest = true; logger.debug("This is a BASE VF request!"); } else { logger.debug("This is *not* a BASE VF request!"); @@ -837,7 +830,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } if (vnfResource == null) { String error = "Create VNF: Unknown VNF Type: " + vnfType; - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VNF Type", vnfType, + logger.error(LoggingAnchor.SIX, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VNF Type", vnfType, OPENSTACK, ErrorCode.DataError.getValue(), "Create VNF: Unknown VNF Type"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); @@ -846,7 +839,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } // By here - we have either a vf or vnfResource - // 1607 - Add version check + // Add version check // First - see if it's in the VnfResource record // if we have a vf Module - then we have to query to get the VnfResource record. if (!oldWay && vf.getVnfResources() != null) { @@ -894,7 +887,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { equalToMax = aicV.isTheSameVersion(maxVersionVnf); } catch (Exception e) { logger.debug( - "An exception occurred while trying to test AIC Version {} - will default to not check", + "An exception occurred while trying to test Cloud Version {} - will default to not check", e.getMessage(), e); doNotTest = true; } @@ -902,35 +895,28 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if ((moreThanMin || equalToMin) // aic >= min && (equalToMax || !(moreThanMax))) { // aic <= max logger.debug("VNF Resource " + vnfResource.getModelName() + ", ModelUuid=" - + vnfResource.getModelUUID() + " VersionMin=" + minVersionVnf + " VersionMax:" - + maxVersionVnf + " supported on Cloud: " + cloudSiteId + " with AIC_Version:" - + cloudSiteOpt.get().getCloudVersion()); + + vnfResource.getModelUUID() + " " + VERSION_MIN + " =" + minVersionVnf + " " + + VERSION_MAX + " :" + maxVersionVnf + " supported on Cloud: " + cloudSiteId + + " with AIC_Version:" + cloudSiteOpt.get().getCloudVersion()); } else { // ERROR String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" - + vnfResource.getModelUUID() + " VersionMin=" + minVersionVnf + " VersionMax:" - + maxVersionVnf + " NOT supported on Cloud: " + cloudSiteId + + vnfResource.getModelUUID() + " " + VERSION_MIN + " =" + minVersionVnf + " " + + VERSION_MAX + " :" + maxVersionVnf + " NOT supported on Cloud: " + cloudSiteId + " with AIC_Version:" + cloudSiteOpt.get().getCloudVersion(); - logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, OPENSTACK, + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_CONFIG_EXC.toString(), error, OPENSTACK, ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } } else { - logger.debug("bypassing testing AIC version..."); + logger.debug("bypassing testing Cloud version..."); } } // let this error out downstream to avoid introducing uncertainty at this stage } else { logger.debug("cloudConfig is NULL - cannot check cloud site version"); } - } else { - logger.debug( - "AIC Version not set in VNF_Resource - this is expected thru 1607 - do not error here - not checked" - + "."); } - // End Version check 1607 - - // By the time we get here - heatTemplateId and heatEnvtId should be populated (or null) HeatTemplate heatTemplate = null; @@ -952,8 +938,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (heatTemplate == null) { String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType - + ", reqType=" + requestTypeString; - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", + + ", modelCustomizationUuid=" + mcu + ", vfModuleUuid=" + vf.getModelUUID() + + ", vnfResourceModelUuid=" + vnfResource.getModelUUID() + ", reqType=" + requestTypeString; + logger.error(LoggingAnchor.SIX, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template " + "ID", vfModuleType, OPENSTACK, ErrorCode.DataError.getValue(), error); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.INTERNAL); @@ -966,9 +953,11 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { logger.debug("No environment parameter found for this Type " + vfModuleType); } else { if (heatEnvironment == null) { - String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType; - logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", - OPENSTACK, ErrorCode.DataError.getValue(), error); + String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType + + ", modelCustomizationUuid=" + mcu + ", vfModuleUuid=" + vf.getModelUUID() + + ", vnfResourceModelUuid=" + vnfResource.getModelUUID() + ", reqType=" + requestTypeString; + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), + "Heat " + "Environment ID", OPENSTACK, ErrorCode.DataError.getValue(), error); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.INTERNAL); } else { @@ -994,7 +983,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { nestedTemplatesChecked = null; } - // 1510 - Also add the files: for any get_files associated with this vnf_resource_id + // Also add the files: for any get_files associated with this vnf_resource_id // *if* there are any List<HeatFiles> heatFiles = null; @@ -1015,11 +1004,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (!isVolumeRequest || addGetFilesOnVolumeReq) { if (oldWay) { - logger.debug( - "In MsoVnfAdapterImpl createVfModule, this should not happen - old way is gamma only - no heat " - + "files!"); + logger.debug("In MsoVnfAdapterImpl createVfModule, this should not happen, no heat files!"); } else { - // 1607 - now use VF_MODULE_TO_HEAT_FILES table + // now use VF_MODULE_TO_HEAT_FILES table logger.debug( "In MsoVnfAdapterImpl createVfModule, about to call db.getHeatFilesForVfModule avec vfModuleId=" + vf.getModelUUID()); @@ -1046,9 +1033,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { String missingParams = null; List<String> paramList = new ArrayList<>(); - // New for 1510 - consult the PARAM_ALIAS field to see if we've been + // consult the PARAM_ALIAS field to see if we've been // supplied an alias. Only check if we don't find it initially. - // Also new in 1510 - don't flag missing parameters if there's an environment - because they might be there. + // don't flag missing parameters if there's an environment - because they might be there. // And also new - add parameter to turn off checking all together if we find we're blocking orders we // shouldn't boolean checkRequiredParameters = true; @@ -1063,7 +1050,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // No problem - default is true logger.debug("An exception occured trying to get property {}", MsoVnfAdapterImpl.CHECK_REQD_PARAMS, e); } - // 1604 - Add enhanced environment & parameter checking // Part 1: parse envt entries to see if reqd parameter is there (before used a simple grep // Part 2: only submit to openstack the parameters in the envt that are in the heat template // Note this also removes any comments @@ -1071,7 +1057,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (heatEnvironment != null && heatEnvironment.getEnvironment() != null && heatEnvironment.getEnvironment().contains("parameters:")) { - logger.debug("Enhanced environment checking enabled - 1604"); StringBuilder sb = new StringBuilder(heatEnvironment.getEnvironment()); mhee = new MsoHeatEnvironmentEntry(sb); @@ -1089,10 +1074,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } else { logger.debug("NO ENVIRONMENT for this entry"); } - // New with 1707 - all variables converted to their native object types + // all variables converted to their native object types Map<String, Object> goldenInputs = null; - logger.debug("Now handle the inputs....first convert"); ArrayList<String> parameterNames = new ArrayList<>(); HashMap<String, String> aliasToParam = new HashMap<>(); StringBuilder sb = new StringBuilder("\nTemplate Parameters:\n"); @@ -1149,7 +1133,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (checkRequiredParameters) { // Problem - missing one or more required parameters String error = "Create VFModule: Missing Required inputs: " + missingParams; - logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, OPENSTACK, + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_MISSING_PARAM.toString(), missingParams, OPENSTACK, ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); @@ -1193,31 +1177,21 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // Have the tenant. Now deploy the stack itself // Ignore MsoTenantNotFound and MsoStackAlreadyExists exceptions // because we already checked for those. - long createStackStarttime = System.currentTimeMillis(); try { - // heatStack = heat.createStack(cloudSiteId, tenantId, vnfName, template, inputs, true, - // heatTemplate.getTimeoutMinutes()); if (backout == null) { backout = true; } if (heat != null) { - logger.debug("heat is not null!!"); heatStack = heat.createStack(cloudSiteId, cloudOwner, tenantId, vfModuleName, null, template, goldenInputs, true, heatTemplate.getTimeoutMinutes(), newEnvironmentString, nestedTemplatesChecked, heatFilesObjects, backout.booleanValue()); } else { - logger.debug("heat is null!"); throw new MsoHeatNotFoundException(); } } catch (MsoException me) { - me.addContext("CreateVFModule"); - String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" - + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, - cloudOwner, cloudSiteId, tenantId, OPENSTACK, ErrorCode.DataError.getValue(), - "MsoException - createStack", me); - logger.debug(error); + me.addContext(CREATE_VFM_MODULE); + logger.error("Error creating Stack", me); if (isValetEnabled && sendResponseToValet) { logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet"); try { @@ -1231,17 +1205,10 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } throw new VnfException(me); } catch (NullPointerException npe) { - String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" - + tenantId + ": " + npe; - logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, - cloudOwner, cloudSiteId, tenantId, OPENSTACK, ErrorCode.DataError.getValue(), - "NullPointerException - createStack", npe); - logger.debug(error); - logger.debug("NULL POINTER EXCEPTION at heat.createStack"); - // npe.addContext ("CreateVNF"); + logger.error("Error creating Stack", npe); throw new VnfException("NullPointerException during heat.createStack"); } catch (Exception e) { - logger.debug("unhandled exception at heat.createStack", e); + logger.error("Error creating Stack", e); throw new VnfException("Exception during heat.createStack! " + e.getMessage()); } // Reach this point if createStack is successful. @@ -1281,7 +1248,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // 1702 capture the output parameters on a delete // so we'll need to query first - Map<String, Object> stackOutputs = null; + Map<String, Object> stackOutputs; try { stackOutputs = heat.queryStackForOutputs(cloudSiteId, cloudOwner, tenantId, vnfName); } catch (MsoException me) { @@ -1290,9 +1257,8 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { me.addContext("DeleteVFModule"); String error = "Delete VFModule: Query to get outputs: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, - cloudSiteId, tenantId, OPENSTACK, "QueryStack", ErrorCode.DataError.getValue(), - "Exception - QueryStack", me); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, + tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), "Exception - " + QUERY_STACK, me); logger.debug(error); throw new VnfException(me); } @@ -1313,14 +1279,13 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { try { heat.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true); } catch (MsoException me) { - me.addContext("DeleteVNF"); + me.addContext(DELETE_VNF); // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException String error = "Delete VF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, - cloudSiteId, tenantId, OPENSTACK, "DeleteStack", ErrorCode.DataError.getValue(), - "Exception - deleteStack", me); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, + tenantId, OPENSTACK, "DeleteStack", ErrorCode.DataError.getValue(), "Exception - deleteStack", me); logger.debug(error); if (isValetEnabled && valetDeleteRequestSucceeded) { logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet"); @@ -1427,9 +1392,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { logger.debug("requestTypeString = " + requestTypeString + ", nestedVolumeStackId = " + nestedStackId + ", nestedBaseStackId = " + nestedBaseStackId); - // Will capture execution time for metrics - long startTime = System.currentTimeMillis(); - // Build a default rollback object (no actions performed) VnfRollback vfRollback = new VnfRollback(); vfRollback.setCloudSiteId(cloudSiteId); @@ -1443,8 +1405,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { vfRollback.setVfModuleStackId(vfModuleStackId); vfRollback.setModelCustomizationUuid(mcu); - StackInfo heatStack = null; - long queryStackStarttime = System.currentTimeMillis(); + StackInfo heatStack; logger.debug("UpdateVfModule - querying for {}", vfModuleName); try { heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vfModuleName); @@ -1454,9 +1415,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { me.addContext("UpdateVFModule"); String error = "Update VFModule: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, OPENSTACK, "QueryStack", ErrorCode.DataError.getValue(), - "Exception - QueryStack", me); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), + "Exception - " + QUERY_STACK, me); logger.debug(error); throw new VnfException(me); } @@ -1466,8 +1427,8 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // Not Found String error = "Update VF: Stack " + vfModuleName + " does not exist in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_NOT_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, OPENSTACK, "QueryStack", ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_NOT_EXIST.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), error); throw new VnfNotFound(cloudSiteId, cloudOwner, tenantId, vfModuleName); } else { logger.debug("Found Existing stack, status={}", heatStack.getStatus()); @@ -1478,7 +1439,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // 1604 Cinder Volume support - handle a nestedStackId if sent (volumeGroupHeatStackId): StackInfo nestedHeatStack = null; - long queryStackStarttime2 = System.currentTimeMillis(); Map<String, Object> nestedVolumeOutputs = null; if (nestedStackId != null) { try { @@ -1490,18 +1450,17 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { me.addContext("UpdateVFModule"); String error = "Update VF: Attached heatStack ID Query " + nestedStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, - cloudSiteId, tenantId, OPENSTACK, "QueryStack", ErrorCode.DataError.getValue(), + logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, + cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), "Exception - " + error, me); logger.debug("ERROR trying to query nested stack= {}", error); throw new VnfException(me); } if (nestedHeatStack == null || nestedHeatStack.getStatus() == HeatStatus.NOTFOUND) { String error = "Update VFModule: Attached volume heatStack ID DOES NOT EXIST " + nestedStackId + " in " - + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR"; - logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, - cloudOwner, cloudSiteId, tenantId, error, OPENSTACK, "QueryStack", - ErrorCode.DataError.getValue(), error); + + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " " + USER_ERROR; + logger.error(LoggingAnchor.TEN, MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, + cloudSiteId, tenantId, error, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), error); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } else { @@ -1514,7 +1473,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { StackInfo nestedBaseHeatStack = null; Map<String, Object> baseStackOutputs = null; if (nestedBaseStackId != null) { - long queryStackStarttime3 = System.currentTimeMillis(); try { logger.debug("Querying for nestedBaseStackId = {}", nestedBaseStackId); nestedBaseHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedBaseStackId); @@ -1524,18 +1482,17 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { me.addContext("UpdateVfModule"); String error = "Update VFModule: Attached baseHeatStack ID Query " + nestedBaseStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, OPENSTACK, "QueryStack", ErrorCode.DataError.getValue(), + logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), "Exception - " + error, me); logger.debug("ERROR trying to query nested base stack= {}", error); throw new VnfException(me); } if (nestedBaseHeatStack == null || nestedBaseHeatStack.getStatus() == HeatStatus.NOTFOUND) { String error = "Update VFModule: Attached base heatStack ID DOES NOT EXIST " + nestedBaseStackId - + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR"; - logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, error, OPENSTACK, "QueryStack", - ErrorCode.DataError.getValue(), error); + + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " " + USER_ERROR; + logger.error(LoggingAnchor.TEN, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, error, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), error); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } else { @@ -1564,8 +1521,8 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } if (vf == null) { String error = "Update VfModule: unable to find vfModule with modelCustomizationUuid=" + mcu; - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VF Module Type", - vfModuleType, OPENSTACK, ErrorCode.DataError.getValue(), error); + logger.error(LoggingAnchor.SIX, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VF Module Type", vfModuleType, + OPENSTACK, ErrorCode.DataError.getValue(), error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } logger.debug("Got VF module definition from Catalog: {}", vf.toString()); @@ -1637,15 +1594,15 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (!doNotTest) { if ((moreThanMin || equalToMin) // aic >= min && ((equalToMax) || !(moreThanMax))) { // aic <= max - logger.debug("VNF Resource " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf - + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSiteId - + " with AIC_Version:" + aicV); + logger.debug("VNF Resource " + vnfResource.getModelName() + " " + VERSION_MIN + " =" + + minVersionVnf + " " + VERSION_MAX + " :" + maxVersionVnf + " supported on Cloud: " + + cloudSiteId + " with AIC_Version:" + aicV); } else { // ERROR - String error = "VNF Resource type: " + vnfResource.getModelName() + " VersionMin=" - + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " - + cloudSiteId + " with AIC_Version:" + aicV; - logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, OPENSTACK, + String error = "VNF Resource type: " + vnfResource.getModelName() + " " + VERSION_MIN + " =" + + minVersionVnf + " " + VERSION_MAX + " :" + maxVersionVnf + + " NOT supported on Cloud: " + cloudSiteId + " with AIC_Version:" + aicV; + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_CONFIG_EXC.toString(), error, OPENSTACK, ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); @@ -1675,8 +1632,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (heatTemplate == null) { String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType - + ", reqType=" + requestTypeString; - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", + + ", modelCustomizationUuid=" + mcu + ", vfModuleUuid=" + vf.getModelUUID() + ", reqType=" + + requestTypeString; + logger.error(LoggingAnchor.SIX, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", vfModuleType, OPENSTACK, ErrorCode.DataError.getValue(), error); throw new VnfException(error, MsoExceptionCategory.INTERNAL); } else { @@ -1684,8 +1642,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } if (heatEnvironment == null) { - String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType; - logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", + String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType + ", modelCustomizationUuid=" + + mcu + ", vfModuleUuid=" + vf.getModelUUID() + ", reqType=" + requestTypeString; + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", OPENSTACK, ErrorCode.DataError.getValue(), error); throw new VnfException(error, MsoExceptionCategory.INTERNAL); } else { @@ -1893,14 +1852,12 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // Problem - missing one or more required parameters if (checkRequiredParameters) { String error = "Update VNF: Missing Required inputs: " + missingParams; - logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, OPENSTACK, + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_MISSING_PARAM.toString(), missingParams, OPENSTACK, ErrorCode.DataError.getValue(), error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } else { logger.debug("found missing parameters - but checkRequiredParameters is false - will not block"); } - } else { - logger.debug("No missing parameters found - ok to proceed"); } // Just submit the envt entry as received from the database @@ -1915,7 +1872,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // This is not a valid parameter for this template extraParams.removeAll(paramList); if (!extraParams.isEmpty()) { - logger.warn("{} {} {} {} {} {}", MessageEnum.RA_VNF_EXTRA_PARAM.toString(), vnfType, + logger.warn(LoggingAnchor.SIX, MessageEnum.RA_VNF_EXTRA_PARAM.toString(), vnfType, extraParams.toString(), OPENSTACK, ErrorCode.DataError.getValue(), "Extra params"); inputs.keySet().removeAll(extraParams); } @@ -1969,7 +1926,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // Have the tenant. Now deploy the stack itself // Ignore MsoTenantNotFound and MsoStackAlreadyExists exceptions // because we already checked for those. - long updateStackStarttime = System.currentTimeMillis(); try { heatStack = heatU.updateStack(cloudSiteId, cloudOwner, tenantId, vfModuleName, template, goldenInputs, true, heatTemplate.getTimeoutMinutes(), newEnvironmentString, @@ -1979,7 +1935,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { me.addContext("UpdateVFModule"); String error = "Update VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), vfModuleType, cloudOwner, + logger.error(LoggingAnchor.EIGHT, MessageEnum.RA_UPDATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId, tenantId, OPENSTACK, ErrorCode.DataError.getValue(), "Exception - " + error, me); if (isValetEnabled && sendResponseToValet) { logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet"); @@ -2062,7 +2018,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { Map<String, Object> nestedTemplates) { boolean haveGetFiles = true; boolean haveNestedTemplates = true; - Map<String, Object> files = new HashMap<String, Object>(); + Map<String, Object> files = new HashMap<>(); if (getFiles == null || getFiles.isEmpty()) { haveGetFiles = false; } @@ -2118,7 +2074,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (newInputs != null) { Map<String, Object> oldGold = goldenInputs; logger.debug("parameters before being modified by valet:{}", oldGold.toString()); - goldenInputs = new HashMap<String, Object>(); + goldenInputs = new HashMap<>(); for (String key : newInputs.keySet()) { goldenInputs.put(key, newInputs.get(key)); } @@ -2254,7 +2210,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { valetDeleteRequestSucceeded = false; valetErrorMessage = e.getMessage(); } - if (valetDeleteRequestSucceeded == false && failRequestOnValetFailure == true) { + if (!valetDeleteRequestSucceeded && failRequestOnValetFailure) { logger.error("ValetDeleteRequestFailed - del req still will be sent to openstack", new VnfException("ValetDeleteRequestFailedError")); } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java index 344daa83bc..96e5db7ce7 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java @@ -32,6 +32,8 @@ import java.util.Optional; import java.util.Set; import javax.jws.WebService; import javax.xml.ws.Holder; +import org.onap.so.logger.LoggingAnchor; +import com.woorea.openstack.heat.Heat; import org.onap.so.adapters.vnf.exceptions.VnfAlreadyExists; import org.onap.so.adapters.vnf.exceptions.VnfException; import org.onap.so.cloud.CloudConfig; @@ -83,7 +85,7 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { private static final String CLOUDIFY = "Cloudify"; private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); - private static final String BRACKETS = "{} {} {} {} {} {} {} {} {}"; + private static final String BRACKETS = LoggingAnchor.NINE; private static final String OPENSTACK = "OpenStack"; @Autowired @@ -237,7 +239,7 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { public void rollbackVnf(VnfRollback rollback) throws VnfException { // rollback may be null (e.g. if stack already existed when Create was called) if (rollback == null) { - logger.info("{} {} {}", MessageEnum.RA_ROLLBACK_NULL.toString(), OPENSTACK, "rollbackVnf"); + logger.info(LoggingAnchor.THREE, MessageEnum.RA_ROLLBACK_NULL.toString(), OPENSTACK, "rollbackVnf"); return; } @@ -499,7 +501,7 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { if (modelCustomizationUuid == null || modelCustomizationUuid.isEmpty()) { logger.debug("Missing required input: modelCustomizationUuid"); String error = "Create vfModule error: Missing required input: modelCustomizationUuid"; - logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VF Module ModelCustomizationUuid", CLOUDIFY, ErrorCode.DataError.getValue(), "Create VF Module: Missing required input: modelCustomizationUuid"); logger.debug(error); @@ -562,7 +564,7 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { String error = "Create vfModule error: Unable to find vfModuleCust with modelCustomizationUuid=" + modelCustomizationUuid; logger.debug(error); - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VF Module " + "ModelCustomizationUuid", modelCustomizationUuid, "CatalogDb", ErrorCode.DataError.getValue(), error); throw new VnfException(error, MsoExceptionCategory.USERDATA); @@ -598,7 +600,7 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUUID() + " VersionMin=" + vnfMin + " VersionMax:" + vnfMax + " NOT supported on Cloud: " + cloudSiteId + " with AIC_Version:" + cloudSite.getCloudVersion(); - logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, OPENSTACK, + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_CONFIG_EXC.toString(), error, OPENSTACK, ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); @@ -616,7 +618,7 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { // Failed to query the Deployment due to a cloudify exception. String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudSiteId, + logger.error(LoggingAnchor.EIGHT, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), "Exception - queryDeployment", me); logger.debug(error); @@ -805,8 +807,9 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { if (heatTemplate == null) { String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + + ", modelCustomizationUuid=" + modelCustomizationUuid + ", vfModuleUuid=" + vf.getModelUUID() + ", reqType=" + requestType; - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", + logger.error(LoggingAnchor.SIX, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", vfModuleType, OPENSTACK, ErrorCode.DataError.getValue(), error); throw new VnfException(error, MsoExceptionCategory.INTERNAL); } else { @@ -814,8 +817,9 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { } if (heatEnvironment == null) { - String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType; - logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", + String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType + ", modelCustomizationUuid=" + + modelCustomizationUuid + ", vfModuleUuid=" + vf.getModelUUID() + ", reqType=" + requestType; + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", OPENSTACK, ErrorCode.DataError.getValue(), error); // Alarm on this error, configuration must be fixed throw new VnfException(error, MsoExceptionCategory.INTERNAL); @@ -951,8 +955,8 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { if (checkRequiredParameters) { // Problem - missing one or more required parameters String error = "Create VFModule: Missing Required inputs: " + missingParams; - logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, CLOUDIFY, - ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs"); + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_MISSING_PARAM.toString(), missingParams, + CLOUDIFY, ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } else { @@ -1014,9 +1018,8 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { catch (MsoException me) { me.addContext("CreateVFModule"); String error = "Create VF Module: Upload blueprint failed. Blueprint=" + blueprintName + ": " + me; - logger.error("{} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, - cloudSiteId, tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), - "MsoException - uploadBlueprint", me); + logger.error(LoggingAnchor.SEVEN, MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudSiteId, + tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), "MsoException - uploadBlueprint", me); logger.debug(error); throw new VnfException(me); } @@ -1040,16 +1043,16 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { me.addContext("CreateVFModule"); String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, - cloudOwner, cloudSiteId, tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), + logger.error(LoggingAnchor.EIGHT, MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, + cloudSiteId, tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), "MsoException - createDeployment", me); logger.debug(error); throw new VnfException(me); } catch (NullPointerException npe) { String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + npe; - logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, - cloudOwner, cloudSiteId, tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), + logger.error(LoggingAnchor.EIGHT, MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, + cloudSiteId, tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), "NullPointerException - createDeployment", npe); logger.debug(error); logger.debug("NULL POINTER EXCEPTION at cloudify.createAndInstallDeployment"); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java index ed797f10d9..c22bb327d4 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java @@ -42,6 +42,7 @@ import java.util.Optional; import java.util.Set; import javax.jws.WebService; import javax.xml.ws.Holder; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.adapters.vdu.CloudInfo; import org.onap.so.adapters.vdu.VduException; import org.onap.so.adapters.vdu.VduInstance; @@ -203,7 +204,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { e.addContext("QueryVNF"); String error = "Query VNF (VDU): " + vnfNameOrId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + e; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfNameOrId, cloudOwner, + logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfNameOrId, cloudOwner, cloudSiteId, tenantId, "VDU", "QueryVNF", ErrorCode.DataError.getValue(), "Exception - queryVDU", e); logger.debug(error); @@ -254,7 +255,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { long startTime = System.currentTimeMillis(); // rollback may be null (e.g. if stack already existed when Create was called) if (rollback == null) { - logger.info("{} {} {}", MessageEnum.RA_ROLLBACK_NULL.toString(), "OpenStack", "rollbackVnf"); + logger.info(LoggingAnchor.THREE, MessageEnum.RA_ROLLBACK_NULL.toString(), "OpenStack", "rollbackVnf"); return; } @@ -291,7 +292,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { ve.addContext("RollbackVFModule"); String error = "Rollback VF Module: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + ve; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, + logger.error(LoggingAnchor.NINE, MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, cloudSiteId, tenantId, "VDU", "DeleteVdu", ErrorCode.DataError.getValue(), "Exception - DeleteVdu", ve); logger.debug(error); @@ -546,7 +547,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { if (modelCustomizationUuid == null || modelCustomizationUuid.isEmpty()) { logger.debug("Missing required input: modelCustomizationUuid"); String error = "Create vfModule error: Missing required input: modelCustomizationUuid"; - logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VF Module ModelCustomizationUuid", "VDU", ErrorCode.DataError, "Create VF Module: " + "Missing required input: modelCustomizationUuid"); logger.debug(error); @@ -610,7 +611,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { String error = "Create vfModule error: Unable to find vfModuleCust with modelCustomizationUuid=" + modelCustomizationUuid; logger.debug(error); - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), + logger.error(LoggingAnchor.SIX, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VF Module ModelCustomizationUuid", modelCustomizationUuid, "CatalogDb", ErrorCode.DataError, error); throw new VnfException(error, MsoExceptionCategory.USERDATA); @@ -649,7 +650,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUUID() + " VersionMin=" + vnfMin + " VersionMax:" + vnfMax + " NOT supported on Cloud: " + cloudSiteId + " with AIC_Version:" + cloudSite.getCloudVersion(); - logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack", + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack", ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); @@ -671,9 +672,9 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { // Failed to query the VDU due to a plugin exception. String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), - "Exception - queryVdu", me); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), "Exception - queryVdu", + me); logger.debug(error); // Convert to a generic VnfException me.addContext("CreateVFModule"); @@ -690,9 +691,9 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { // fail - it exists String error = "Create VF: Deployment " + vfModuleName + " already exists in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), - vfModuleName, cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", - ErrorCode.DataError.getValue(), "VF Module " + vfModuleName + " already exists"); + logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), + "VF Module " + vfModuleName + " already exists"); logger.debug(error); throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, vduInstance.getVduInstanceId()); @@ -712,8 +713,8 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { String error = "Create VF: Deployment " + vfModuleName + " already exists and has status " + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; please wait for it to complete, or fix manually."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), + logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), "VF Module " + vfModuleName + " already exists"); logger.debug(error); throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, @@ -722,8 +723,8 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { // fail - it exists and is in a FAILED state String error = "Create VF: Deployment " + vfModuleName + " already exists and is in FAILED state in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), + logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), "VF Module " + vfModuleName + " already exists and is in FAILED state"); logger.debug(error); throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, @@ -733,8 +734,8 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { String error = "Create VF: Deployment " + vfModuleName + " already exists and has status " + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), + logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), "VF Module " + vfModuleName + " already exists and is in " + status.toString() + " state"); logger.debug(error); throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, @@ -744,8 +745,8 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { String error = "Create VF: Deployment " + vfModuleName + " already exists with unexpected status " + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), + logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), "VF Module " + vfModuleName + " already exists and is in an unknown state"); logger.debug(error); throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, @@ -768,8 +769,8 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { // Failed to query the Volume Group VDU due to a plugin exception. String error = "Create VF Module: Query Volume Group " + volumeGroupId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu(volume)", ErrorCode.DataError.getValue(), + logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, cloudOwner, + cloudSiteId, tenantId, "VDU", "queryVdu(volume)", ErrorCode.DataError.getValue(), "Exception - queryVdu(volume)", me); logger.debug(error); // Convert to a generic VnfException @@ -780,8 +781,8 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { if (volumeVdu == null || volumeVdu.getStatus().getState() == VduStateType.NOTFOUND) { String error = "Create VFModule: Attached Volume Group DOES NOT EXIST " + volumeGroupId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR"; - logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, - cloudOwner, cloudSiteId, tenantId, error, "VDU", "queryVdu(volume)", + logger.error(LoggingAnchor.TEN, MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, cloudOwner, + cloudSiteId, tenantId, error, "VDU", "queryVdu(volume)", ErrorCode.BusinessProcesssError.getValue(), "Create VFModule: Attached Volume Group " + "DOES NOT EXIST"); logger.debug(error); @@ -818,7 +819,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { // Failed to query the Base VF Module due to a Vdu Plugin exception. String error = "Create VF Module: Query Base " + baseVfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, + logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu(Base)", ErrorCode.DataError.getValue(), "Exception - queryVdu(Base)", me); logger.debug(error); @@ -830,8 +831,8 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { if (baseVdu == null || baseVdu.getStatus().getState() == VduStateType.NOTFOUND) { String error = "Create VFModule: Base Module DOES NOT EXIST " + baseVfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR"; - logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), - baseVfModuleId, cloudOwner, cloudSiteId, tenantId, error, "VDU", "queryVdu(Base)", + logger.error(LoggingAnchor.TEN, MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, cloudOwner, + cloudSiteId, tenantId, error, "VDU", "queryVdu(Base)", ErrorCode.BusinessProcesssError.getValue(), "Create VFModule: Base Module DOES NOT EXIST"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); @@ -862,8 +863,9 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { if (heatTemplate == null) { String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + + ", modelCustomizationUuid=" + modelCustomizationUuid + ", vfModuleUuid=" + vfModule.getModelUUID() + ", reqType=" + requestType; - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", + logger.error(LoggingAnchor.SIX, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", vfModuleType, "VNF", ErrorCode.DataError.getValue(), error); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.INTERNAL); @@ -872,8 +874,9 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { } if (heatEnvironment == null) { - String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType; - logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", + String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType + ", modelCustomizationUuid=" + + modelCustomizationUuid + ", vfModuleUuid=" + vfModule.getModelUUID() + ", reqType=" + requestType; + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", "OpenStack", ErrorCode.DataError.getValue(), error); throw new VnfException(error, MsoExceptionCategory.INTERNAL); } else { @@ -1007,7 +1010,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { if (checkRequiredParameters) { // Problem - missing one or more required parameters String error = "Create VFModule: Missing Required inputs: " + missingParams; - logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "VDU", + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "VDU", ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); @@ -1044,7 +1047,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { me.addContext("CreateVFModule"); String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, + logger.error(LoggingAnchor.EIGHT, MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId, tenantId, "VDU", ErrorCode.DataError.getValue(), "MsoException - instantiateVdu", me); logger.debug(error); // Convert to a generic VnfException @@ -1052,7 +1055,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { } catch (NullPointerException npe) { String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + npe; - logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, + logger.error(LoggingAnchor.EIGHT, MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId, tenantId, "VDU", ErrorCode.DataError.getValue(), "NullPointerException - instantiateVdu", npe); logger.debug(error); @@ -1103,7 +1106,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { e.addContext("QueryVFModule"); String error = "Query VfModule (VDU): " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + e; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleId, cloudOwner, + logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleId, cloudOwner, cloudSiteId, tenantId, "VDU", "QueryVFModule", ErrorCode.DataError.getValue(), "Exception - queryVDU", e); logger.debug(error); @@ -1129,7 +1132,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { // Convert to a generic VnfException String error = "Delete VF: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, + logger.error(LoggingAnchor.NINE, MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, cloudSiteId, tenantId, "VDU", "DeleteVdu", ErrorCode.DataError.getValue(), "Exception - DeleteVdu: " + me.getMessage()); logger.debug(error); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java index 686410f14c..8c871c742e 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java @@ -40,6 +40,7 @@ import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.ws.Holder; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpStatus; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.adapters.vnf.exceptions.VnfException; @@ -183,7 +184,7 @@ public class VnfAdapterRest { response = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), Boolean.TRUE, req.getMessageId(), outputs.value); } catch (VnfException e) { - logger.error("{} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), + logger.error(LoggingAnchor.THREE, MessageEnum.RA_DELETE_VNF_ERR.toString(), ErrorCode.BusinessProcesssError.getValue(), "VnfException - Delete VNF Module", e); eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId()); @@ -241,7 +242,7 @@ public class VnfAdapterRest { logger.debug("Query vfModule exit"); return Response.status(respStatus).entity(new GenericEntity<QueryVfModuleResponse>(qryResp) {}).build(); } catch (VnfException e) { - logger.error("{} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule", + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule", ErrorCode.BusinessProcesssError.getValue(), "VnfException - queryVfModule", e); VfModuleExceptionResponse excResp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null); @@ -288,7 +289,7 @@ public class VnfAdapterRest { t1.start(); } catch (Exception e) { // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR, "createVfModule", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_CREATE_VNF_ERR, "createVfModule", ErrorCode.BusinessProcesssError, "Exception - createVfModule", e); return Response.serverError().build(); } @@ -403,7 +404,7 @@ public class VnfAdapterRest { t1.start(); } catch (Exception e) { // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), "updateVfModule", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_UPDATE_VNF_ERR.toString(), "updateVfModule", ErrorCode.BusinessProcesssError.getValue(), "Exception - updateVfModule", e); return Response.serverError().build(); } @@ -507,7 +508,7 @@ public class VnfAdapterRest { t1.start(); } catch (Exception e) { // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), "rollbackVfModule", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), "rollbackVfModule", ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e); return Response.serverError().build(); } @@ -559,7 +560,7 @@ public class VnfAdapterRest { vnfAdapter.rollbackVnf(vrb); response = new RollbackVfModuleResponse(Boolean.TRUE, req.getMessageId()); } catch (VnfException e) { - logger.error("{} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR, ErrorCode.BusinessProcesssError, + logger.error(LoggingAnchor.THREE, MessageEnum.RA_ROLLBACK_VNF_ERR, ErrorCode.BusinessProcesssError, "Exception" + " - " + "rollbackVfModule", e); eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, false, req.getMessageId()); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java index 5b831047ad..9a7354c40c 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java @@ -39,6 +39,7 @@ import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.ws.Holder; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpStatus; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.adapters.vnf.exceptions.VnfException; @@ -84,7 +85,7 @@ public class VnfAdapterRestV2 { private static Logger logger = LoggerFactory.getLogger(VnfAdapterRestV2.class); private static final String TESTING_KEYWORD = "___TESTING___"; private static final String RESP = ", resp="; - private static final String BRACKETS = "{} {} {} {}"; + private static final String BRACKETS = LoggingAnchor.FOUR; @Autowired private VnfAdapterRestUtils vnfAdapterRestUtils; @@ -199,7 +200,7 @@ public class VnfAdapterRestV2 { response = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), Boolean.TRUE, req.getMessageId(), outputs.value); } catch (VnfException e) { - logger.error("{} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), + logger.error(LoggingAnchor.THREE, MessageEnum.RA_DELETE_VNF_ERR.toString(), ErrorCode.BusinessProcesssError.getValue(), "VnfException - " + "Delete VNF Module", e); eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId()); @@ -269,7 +270,7 @@ public class VnfAdapterRestV2 { logger.debug("Query vfModule exit"); return Response.status(respStatus).entity(new GenericEntity<QueryVfModuleResponse>(qryResp) {}).build(); } catch (VnfException e) { - logger.error("{} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule", + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule", ErrorCode.BusinessProcesssError.getValue(), "VnfException - queryVfModule", e); VfModuleExceptionResponse excResp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null); @@ -610,7 +611,7 @@ public class VnfAdapterRestV2 { response = new RollbackVfModuleResponse(Boolean.TRUE, req.getMessageId()); } catch (VnfException e) { - logger.error("{} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), + logger.error(LoggingAnchor.THREE, MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e); eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, false, req.getMessageId()); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java index c6fd73d9cb..aebd04f32c 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + /* * Copyright (C) 2018 Bell Canada. All rights reserved. * diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java index 9bf2ec73f4..60dfded1f8 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + /* * Copyright (C) 2018 Bell Canada. All rights reserved. * diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java index a5e6a4558f..ae15b70b00 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + /* * Copyright (C) 2018 Bell Canada. All rights reserved. * @@ -50,16 +70,17 @@ import org.onap.so.heatbridge.helpers.AaiHelper; import org.onap.so.heatbridge.openstack.api.OpenstackClient; import org.onap.so.heatbridge.openstack.factory.OpenstackClientFactoryImpl; import org.onap.so.heatbridge.utils.HeatBridgeUtils; -import org.onap.so.logger.MessageEnum; import org.onap.so.logger.ErrorCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.onap.so.logger.LoggingAnchor; +import org.onap.so.logger.MessageEnum; import org.openstack4j.model.compute.Server; import org.openstack4j.model.heat.Resource; import org.openstack4j.model.network.IP; import org.openstack4j.model.network.Network; import org.openstack4j.model.network.NetworkType; import org.openstack4j.model.network.Port; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; @@ -323,9 +344,9 @@ public class HeatBridgeImpl implements HeatBridgeApi { } } catch (WebApplicationException e) { // Silently log that we failed to update the Pserver p-interface with PCI-ID - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.GENERAL_EXCEPTION, pserverHostName, - matchingPifName.get(), cloudOwner, tenantId, "OpenStack", "Heatbridge", - ErrorCode.DataError.getValue(), "Exception - Failed to add sriov-pf object to pserver", e); + logger.error(LoggingAnchor.NINE, MessageEnum.GENERAL_EXCEPTION, pserverHostName, matchingPifName.get(), + cloudOwner, tenantId, "OpenStack", "Heatbridge", ErrorCode.DataError.getValue(), + "Exception - Failed to add sriov-pf object to pserver", e); } } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java index 933b42e0b2..f2d61d2587 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + /* * Copyright (C) 2018 Bell Canada. All rights reserved. * diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java index edf5e2d339..018a4eac8d 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + /* * Copyright (C) 2018 Bell Canada. All rights reserved. * diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java index bd74bf6aa0..f0c5a0b434 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + /* * Copyright (C) 2018 Bell Canada. All rights reserved. * diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java index 515f2dc0e5..137aaa9f41 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + /* * Copyright (C) 2018 Bell Canada. * diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackAccess.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackAccess.java index fd5dabc784..69c76fad84 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackAccess.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackAccess.java @@ -1,4 +1,24 @@ /*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + +/*- * Copyright (C) 2018 Bell Canada. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java index 1fa41ee2a0..7184ec1e93 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java @@ -1,4 +1,24 @@ /*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + +/*- * Copyright (C) 2018 Bell Canada. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientException.java index a062ca826d..26d92ebb80 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientException.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientException.java @@ -1,4 +1,24 @@ /*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + +/*- * Copyright (C) 2018 Bell Canada. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java index 2843eb226e..5a2b0732dc 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java @@ -1,4 +1,24 @@ /*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + +/*- * Copyright (C) 2018 Bell Canada. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV2ClientImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV2ClientImpl.java index 760be72b3f..95b4cd7cfd 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV2ClientImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV2ClientImpl.java @@ -1,4 +1,24 @@ /*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + +/*- * Copyright (C) 2018 Bell Canada. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV3ClientImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV3ClientImpl.java index dddd82ce6a..a0c05b4dba 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV3ClientImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV3ClientImpl.java @@ -1,4 +1,24 @@ /*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + +/*- * Copyright (C) 2018 Bell Canada. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactory.java index 5019eec09b..b00f926e52 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactory.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactory.java @@ -1,4 +1,24 @@ /*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + +/*- * Copyright (C) 2018 Bell Canada. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java index 25b3f1dbeb..bbcd54e6f8 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java @@ -1,4 +1,24 @@ /*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + +/*- * Copyright (C) 2018 Bell Canada. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java index 788e038855..be086677db 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + /* * Copyright (C) 2018 Bell Canada. All rights reserved. * diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduStatus.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduStatus.java index 0c4b9e01b9..66b2e52570 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduStatus.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduStatus.java @@ -25,8 +25,14 @@ package org.onap.so.vdu.utils; * Enum status values to capture the state of a generic (cloud-agnostic) VDU. */ public enum VduStatus { - NOTFOUND, INSTANTIATING, INSTANTIATED, DELETING, DELETED, // Note - only returned in success response to deleteVdu - // call. - UPDATING, FAILED, UNKNOWN + NOTFOUND, + INSTANTIATING, + INSTANTIATED, + DELETING, + DELETED, // Note - only returned in success response to deleteVdu + // call. + UPDATING, + FAILED, + UNKNOWN } diff --git a/adapters/mso-openstack-adapters/src/main/resources/application-local.yaml b/adapters/mso-openstack-adapters/src/main/resources/application-local.yaml index 2ec5be7448..66d63d436b 100644 --- a/adapters/mso-openstack-adapters/src/main/resources/application-local.yaml +++ b/adapters/mso-openstack-adapters/src/main/resources/application-local.yaml @@ -51,6 +51,8 @@ tomcat: mso: msoKey: 07a7159d3bf51a0e53be7a8f89699be7 auth: 6B466C603A260F3655DBF91E53CE54667041C01406D10E8CAF9CC24D8FA5388D06F90BFE4C852052B436 + audit: + lock-time: 240000 logPath: logs msb-ip: localhost msb-port: ${wiremock.server.port} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceTest.java index 2eb8d8ef39..c9aef950f7 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceTest.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.adapters.audit; import static com.shazam.shazamcrest.MatcherAssert.assertThat; diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateInventoryTaskTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateInventoryTaskTest.java index 8513f30d4b..8dc9d7fe5c 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateInventoryTaskTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateInventoryTaskTest.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.adapters.inventory.create; import static org.mockito.Mockito.doReturn; diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MSONetworkAdapterImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MSONetworkAdapterImplTest.java index 4dcb7c8710..add1918748 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MSONetworkAdapterImplTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/MSONetworkAdapterImplTest.java @@ -20,18 +20,6 @@ package org.onap.so.adapters.network; -import org.apache.http.HttpStatus; -import org.junit.Test; -import org.onap.so.adapters.vnf.BaseRestTestUtils; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.web.util.UriComponentsBuilder; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; import static org.junit.Assert.assertEquals; import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackDeleteNeutronNetwork; import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackDeleteStack_200; @@ -52,6 +40,18 @@ import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPutStack; import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackResponseAccess; import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenstackGet; import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenstackPost; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.http.HttpStatus; +import org.junit.Test; +import org.onap.so.adapters.vnf.BaseRestTestUtils; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.util.UriComponentsBuilder; public class MSONetworkAdapterImplTest extends BaseRestTestUtils { @@ -142,12 +142,12 @@ public class MSONetworkAdapterImplTest extends BaseRestTestUtils { mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStack_404(wireMockServer, "dvspg-VCE_VPE-mtjnj40avbc"); + mockOpenStackGetStack_404(wireMockServer, "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"); mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack.json"); mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", - "dvspg-VCE_VPE-mtjnj40avbc/stackId"); + "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"); String uri = "/services/NetworkAdapter"; headers.set("X-ECOMP-RequestID", "123456789456127"); @@ -163,7 +163,7 @@ public class MSONetworkAdapterImplTest extends BaseRestTestUtils { mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack.json"); mockOpenStackGetStackCreated_200(wireMockServer, "OpenstackResponse_Stack_Created.json", - "dvspg-VCE_VPE-mtjnj40avbc"); + "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"); String uri = "/services/NetworkAdapter"; headers.set("X-ECOMP-RequestID", "123456789456127"); diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfMulticloudAdapterImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfMulticloudAdapterImplTest.java index 5f2057524f..48ca0fd79c 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfMulticloudAdapterImplTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfMulticloudAdapterImplTest.java @@ -55,8 +55,6 @@ public class MsoVnfMulticloudAdapterImplTest extends BaseRestTestUtils { @Autowired private CloudConfig cloudConfig; - private static final String CREATE_STACK_RESPONSE = "{\"template_type\": \"TEST-template\", \"workload_id\": " - + "\"workload-id\", \"template_response\": {\"stack\": {\"id\": \"TEST-stack\", \"links\": []}}}"; private static final String UPDATE_STACK_RESPONSE = "{\"template_type\": \"heat\", \"workload_id\": " + "\"workload-id\"}"; private static final String GET_CREATE_STACK_RESPONSE = "{\"template_type\": \"heat\", \"workload_id\": " @@ -125,6 +123,51 @@ public class MsoVnfMulticloudAdapterImplTest extends BaseRestTestUtils { } @Test + public void createVfModule2() throws Exception { + + Map<String, Object> stackInputs = new HashMap<>(); + stackInputs.put("oof_directives", "{}"); + stackInputs.put("sdnc_directives", "{}"); + stackInputs.put("user_directives", "{}"); + stackInputs.put("generic_vnf_id", "genVNFID"); + stackInputs.put("vf_module_id", "vfMODULEID"); + + MsoRequest msoRequest = new MsoRequest(); + msoRequest.setRequestId("12345"); + msoRequest.setServiceInstanceId("12345"); + + wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_NAME)).willReturn( + aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND))); + + wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_ID)).inScenario("CREATE") + .whenScenarioStateIs("CREATING").willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBody(GET_CREATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_ID)).inScenario("CREATE") + .whenScenarioStateIs("UPDATING").willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBody(GET_UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).inScenario("CREATE") + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("MulticloudResponse_Stack_Create2.json").withStatus(HttpStatus.SC_CREATED)) + .willSetStateTo("CREATING")); + + wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_UPDATE_PATH)) + .inScenario("CREATE").willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBody(UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_ACCEPTED)) + .willSetStateTo("UPDATING")); + + try { + instance.createVfModule("MTN13", "CloudOwner", "123", "vf", "v1", "genericVnfId", "vfname", "vfModuleId", + "create", null, "234", "9b339a61-69ca-465f-86b8-1c72c582b8e8", stackInputs, true, true, true, + msoRequest, new Holder<>(), new Holder<>(), new Holder<>()); + } catch (VnfException e) { + fail("createVfModule success expected, failed with exception: " + e.toString()); + } + wireMockServer.resetScenarios(); + } + + @Test public void createVfModuleAlreadyExists() throws Exception { Map<String, Object> stackInputs = new HashMap<>(); diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java index 0787cef75d..d611322c02 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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========================================================= + */ + /* * Copyright (C) 2018 Bell Canada. All rights reserved. * diff --git a/adapters/mso-openstack-adapters/src/test/resources/CreateNetwork.xml b/adapters/mso-openstack-adapters/src/test/resources/CreateNetwork.xml index b9fc419a65..5ee33ab3dc 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/CreateNetwork.xml +++ b/adapters/mso-openstack-adapters/src/test/resources/CreateNetwork.xml @@ -4,7 +4,7 @@ <cloudSiteId>mtn13</cloudSiteId> <tenantId>bef254252c5d44e6bcec65c180180ab5</tenantId> <networkType>CONTRAIL30_GNDIRECT</networkType> - <networkName>dvspg-VCE_VPE-mtjnj40avbc</networkName> + <networkName>DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001</networkName> <physicalNetworkName>dvs-mtjnj-01</physicalNetworkName> <vlans>3014</vlans> <failIfExists>false</failIfExists> diff --git a/adapters/mso-openstack-adapters/src/test/resources/__files/MulticloudResponse_Stack_Create2.json b/adapters/mso-openstack-adapters/src/test/resources/__files/MulticloudResponse_Stack_Create2.json new file mode 100644 index 0000000000..8532fae97c --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/resources/__files/MulticloudResponse_Stack_Create2.json @@ -0,0 +1,15 @@ +{ + "template_type": "HEAT", + "workload_id": "workload-id", + "workload_status_reason": + { + "id": "workload-id", + "links": [ + { + "href": "http://localhost:1234/v1/id12345678/stacks/workload-id/abcdef00-1234-abcd-5678-ef9123456789", + "rel": "self" + } + ] + }, + "workload_status": "CREATE_IN_PROGRESS" +} diff --git a/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_Stack.json b/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_Stack.json index af63ca7de4..be50d09ef6 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_Stack.json +++ b/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_Stack.json @@ -1,17 +1,15 @@ { - "stack": { - "description": null, - "links": null, - "stackStatusReason": null, - "stackName": null, - "updatedTime": null, - "creationTime": null, - "stackStatus": "NOT_FOUND", - "id": "stackId", - "files": null, - "outputs": null, - "parameters": { - - } - } -}
\ No newline at end of file + "stack": { + "creationTime": null, + "description": null, + "files": null, + "id": "stackId", + "links": null, + "outputs": null, + "parameters": {}, + "stack_name": "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001", + "stack_status": "CREATE_IN_PROGRESS", + "stack_status_reason": null, + "updatedTime": null + } +} diff --git a/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_Stack_Created_VfModule.json b/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_Stack_Created_VfModule.json index 29893ccb7b..e49d407766 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_Stack_Created_VfModule.json +++ b/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_Stack_Created_VfModule.json @@ -1,17 +1,15 @@ { - "stack": { - "description": null, - "links": null, - "stack_status_reason": null, - "stack_name": "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001", - "updated_time": null, - "creation_time": null, - "stack_status": "CREATE_COMPLETE", - "id": "stackId", - "files": null, - "outputs": null, - "parameters": { - - } - } -}
\ No newline at end of file + "stack": { + "creationTime": null, + "description": null, + "files": null, + "id": "stackId", + "links": null, + "outputs": null, + "parameters": {}, + "stack_name": "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001", + "stack_status": "CREATE_COMPLETE", + "stack_status_reason": "Create Completed", + "updatedTime": null + } +} diff --git a/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_Stack_DeleteComplete.json b/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_Stack_DeleteComplete.json index 8612258eee..bad85f37c8 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_Stack_DeleteComplete.json +++ b/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_Stack_DeleteComplete.json @@ -3,7 +3,7 @@ "description": null, "links": null, "stackStatusReason": null, - "stackName": null, + "stackName": "stackName", "updatedTime": null, "creationTime": null, "stack_status": "DELETE_COMPLETE", diff --git a/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_VnfBaseStackId.json b/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_VnfBaseStackId.json index f4a3c520ba..70c78a6047 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_VnfBaseStackId.json +++ b/adapters/mso-openstack-adapters/src/test/resources/__files/OpenstackResponse_VnfBaseStackId.json @@ -7,6 +7,7 @@ "rel" : "self" } ], - "stack_name": "vnfBaseStack" + "stack_name": "vnfBaseStack", + "stack_status": "CREATE_COMPLETE" } }
\ No newline at end of file diff --git a/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml b/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml index ce576f00e1..7cc7697129 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml +++ b/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml @@ -63,6 +63,8 @@ ssl-enable: false tomcat: max-threads: 50 mso: + audit: + lock-time: 240000 logPath: logs msb-ip: localhost msb-port: ${wiremock.server.port} diff --git a/adapters/mso-openstack-adapters/src/test/resources/logback-test.xml b/adapters/mso-openstack-adapters/src/test/resources/logback-test.xml index 5d6eee746f..8bfa6d83c3 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/logback-test.xml +++ b/adapters/mso-openstack-adapters/src/test/resources/logback-test.xml @@ -29,25 +29,15 @@ </appender> - <logger name="com.att.eelf.audit" level="INFO" additivity="false"> - <appender-ref ref="STDOUT" /> - </logger> - - <logger name="com.att.eelf.metrics" level="INFO" additivity="false"> - <appender-ref ref="STDOUT" /> - </logger> - <logger name="com.att.eelf.error" level="WARN" additivity="false"> + <logger name="com.woorea.openstack" level="${so.log.level:-DEBUG}" additivity="false"> <appender-ref ref="STDOUT" /> </logger> <logger name="org.onap" level="${so.log.level:-DEBUG}" additivity="false"> <appender-ref ref="STDOUT" /> </logger> - - <logger name="org.onap" level="${so.log.level:-DEBUG}" additivity="false"> - <appender-ref ref="STDOUT" /> - </logger> + <root level="WARN"> <appender-ref ref="STDOUT" /> diff --git a/adapters/mso-openstack-adapters/src/test/resources/schema.sql b/adapters/mso-openstack-adapters/src/test/resources/schema.sql index 83023e53db..7b3ffd7d30 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/schema.sql +++ b/adapters/mso-openstack-adapters/src/test/resources/schema.sql @@ -803,7 +803,9 @@ CREATE TABLE `service` ( `WORKLOAD_CONTEXT` varchar(200) DEFAULT NULL, `SERVICE_CATEGORY` varchar(200) DEFAULT NULL, `RESOURCE_ORDER` varchar(200) default NULL, - OVERALL_DISTRIBUTION_STATUS varchar(45), + `OVERALL_DISTRIBUTION_STATUS` varchar(45), + `ONAP_GENERATED_NAMING` TINYINT(1) DEFAULT NULL, + `NAMING_POLICY` varchar(200) DEFAULT NULL, PRIMARY KEY (`MODEL_UUID`), KEY `fk_service__tosca_csar1_idx` (`TOSCA_CSAR_ARTIFACT_UUID`), CONSTRAINT `fk_service__tosca_csar1` FOREIGN KEY (`TOSCA_CSAR_ARTIFACT_UUID`) REFERENCES `tosca_csar` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsScheduler.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsScheduler.java index 02b44efe1c..8c4150cd50 100644 --- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsScheduler.java +++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsScheduler.java @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.db.request.beans.ArchivedInfraRequests; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.data.repository.ArchivedInfraRequestsRepository; @@ -145,8 +146,8 @@ public class ArchiveInfraRequestsScheduler { newArchivedReqs.add(archivedInfra); oldInfraReqs.add(iar); } catch (Exception e) { - logger.error("{} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), ErrorCode.UnknownError.getValue(), - e); + logger.error(LoggingAnchor.TWO, MessageEnum.RA_GENERAL_EXCEPTION.toString(), + ErrorCode.UnknownError.getValue(), e); } } diff --git a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V5.10__Add_Column_IS_DATA_INTERNAL.sql b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V5.10__Add_Column_IS_DATA_INTERNAL.sql new file mode 100644 index 0000000000..2196d11e07 --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V5.10__Add_Column_IS_DATA_INTERNAL.sql @@ -0,0 +1,3 @@ +use requestdb; + +ALTER TABLE request_processing_data ADD COLUMN IF NOT EXISTS IS_DATA_INTERNAL TINYINT NOT NULL DEFAULT '0';
\ No newline at end of file diff --git a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V5.9__Add_Column_Ext_System_Error_Source.sql b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V5.9__Add_Column_Ext_System_Error_Source.sql new file mode 100644 index 0000000000..e76dbbe883 --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V5.9__Add_Column_Ext_System_Error_Source.sql @@ -0,0 +1,4 @@ +use requestdb; + +ALTER TABLE infra_active_requests ADD COLUMN IF NOT EXISTS EXT_SYSTEM_ERROR_SOURCE varchar(80); +ALTER TABLE archived_infra_requests ADD COLUMN IF NOT EXISTS EXT_SYSTEM_ERROR_SOURCE varchar(80);
\ No newline at end of file diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/RequestsAdapterBase.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/RequestsAdapterBase.java index cb6feacfb2..6ef228ef79 100644 --- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/RequestsAdapterBase.java +++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/RequestsAdapterBase.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.adapters.requestsdb; import org.junit.runner.RunWith; diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java index d48013b80d..b96a564b1a 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterService.java @@ -30,6 +30,7 @@ import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceFeature; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; @@ -59,18 +60,18 @@ public class SDNCAdapterService extends Service { try { wsdlUrl = Thread.currentThread().getContextClassLoader().getResource("main/resources/SDNCAdapter.wsdl"); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_ADAPTER_WSDL, + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_ADAPTER_WSDL, ErrorCode.DataError.getValue(), "Exception - WSDL not found", e); } if (wsdlUrl == null) { - logger.error("{} {} {} {}", MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_ADAPTER_WSDL, + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_ADAPTER_WSDL, ErrorCode.DataError.getValue(), "WSDL not found"); } else { try { - logger.info("{} {} {}", MessageEnum.RA_PRINT_URL.toString(), SDNC_ADAPTER_WSDL, + logger.info(LoggingAnchor.THREE, MessageEnum.RA_PRINT_URL.toString(), SDNC_ADAPTER_WSDL, wsdlUrl.toURI().toString()); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.RA_WSDL_URL_CONVENTION_EXC.toString(), SDNC_ADAPTER_WSDL, + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_WSDL_URL_CONVENTION_EXC.toString(), SDNC_ADAPTER_WSDL, ErrorCode.DataError.getValue(), "Exception - print URL", e); } } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java index 97a6860dfe..577b550be6 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCAdapterCallbackRequest.java @@ -31,6 +31,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; @@ -122,7 +123,7 @@ public class SDNCAdapterCallbackRequest { m.marshal(this, w); return w.toString(); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.RA_MARSHING_ERROR.toString(), ErrorCode.DataError.getValue(), + logger.error(LoggingAnchor.THREE, MessageEnum.RA_MARSHING_ERROR.toString(), ErrorCode.DataError.getValue(), "Exception - MARSHING_ERROR", e); } return ""; diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java index 72d18bd1ce..87620743d7 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/client/SDNCCallbackAdapterService.java @@ -29,6 +29,7 @@ import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceFeature; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; @@ -57,18 +58,18 @@ public class SDNCCallbackAdapterService extends Service { wsdlUrl = Thread.currentThread().getContextClassLoader() .getResource("main/resources/SDNCCallbackAdapter.wsdl"); } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_CALLBACK_ADAPTER_WSDL, "SDNC", - ErrorCode.DataError.getValue(), "Exception - WSDL not found", e); + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_CALLBACK_ADAPTER_WSDL, + "SDNC", ErrorCode.DataError.getValue(), "Exception - WSDL not found", e); } if (wsdlUrl == null) { - logger.error("{} {} {} {} {}", MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_CALLBACK_ADAPTER_WSDL, "SDNC", - ErrorCode.DataError.getValue(), "WSDL not found"); + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_WSDL_NOT_FOUND.toString(), SDNC_CALLBACK_ADAPTER_WSDL, + "SDNC", ErrorCode.DataError.getValue(), "WSDL not found"); } else { try { - logger.info("{} {} {} {}", MessageEnum.RA_PRINT_URL.toString(), SDNC_CALLBACK_ADAPTER_WSDL, + logger.info(LoggingAnchor.FOUR, MessageEnum.RA_PRINT_URL.toString(), SDNC_CALLBACK_ADAPTER_WSDL, wsdlUrl.toURI().toString(), "SDNC"); } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.RA_WSDL_URL_CONVENTION_EXC.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_WSDL_URL_CONVENTION_EXC.toString(), SDNC_CALLBACK_ADAPTER_WSDL, "SDNC", ErrorCode.DataError.getValue(), "Exception - URL convention problem", e); } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java index 2d43385700..880ef0a7b0 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/MapRequestTunables.java @@ -23,6 +23,7 @@ package org.onap.so.adapters.sdnc.impl; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; @@ -69,7 +70,7 @@ public class MapRequestTunables { String[] parts = value.split("\\|"); // escape pipe if (parts.length < 3) { - logger.warn("{} {} {} {} {} {}", MessageEnum.RA_SDNC_INVALID_CONFIG.toString(), key, value, "SDNC", + logger.warn(LoggingAnchor.SIX, MessageEnum.RA_SDNC_INVALID_CONFIG.toString(), key, value, "SDNC", ErrorCode.DataError.getValue(), "Invalid config"); } @@ -105,7 +106,7 @@ public class MapRequestTunables { error = "Missing configuration for:" + key; } if (error != null) { - logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), key, "SDNC", + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), key, "SDNC", ErrorCode.DataError.getValue(), "Missing config param"); } logger.debug("RequestTunables Key:{} Value:{} Tunables:{}", key, value, this.toString()); diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java index 3e3ec6f9bb..2b023f4c15 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCAdapterPortTypeImpl.java @@ -25,6 +25,7 @@ package org.onap.so.adapters.sdnc.impl; import javax.annotation.PostConstruct; import javax.jws.WebService; import javax.servlet.http.HttpServletResponse; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.adapters.sdnc.SDNCAdapterPortType; import org.onap.so.adapters.sdnc.SDNCAdapterRequest; import org.onap.so.adapters.sdnc.SDNCAdapterResponse; @@ -51,7 +52,7 @@ public class SDNCAdapterPortTypeImpl implements SDNCAdapterPortType { @PostConstruct public void init() { - logger.info("{} {} {}", MessageEnum.RA_INIT_SDNC_ADAPTER.toString(), "SDNC", "SDNCAdapterPortType"); + logger.info(LoggingAnchor.THREE, MessageEnum.RA_INIT_SDNC_ADAPTER.toString(), "SDNC", "SDNCAdapterPortType"); } /** @@ -71,7 +72,7 @@ public class SDNCAdapterPortTypeImpl implements SDNCAdapterPortType { sdncClient.executeRequest(bpelRequest); } catch (Exception e) { String respMsg = "Error sending request to SDNC. Failed to start SDNC Client thread " + e.getMessage(); - logger.error("{} {} {} {}", MessageEnum.RA_SEND_REQUEST_SDNC_ERR.toString(), "SDNC", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_SEND_REQUEST_SDNC_ERR.toString(), "SDNC", ErrorCode.DataError.getValue(), respMsg, e); SDNCResponse sdncResp = new SDNCResponse(bpelReqId); diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java index 7d412b77ad..012a19f1a9 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/SDNCRestClient.java @@ -45,6 +45,7 @@ import javax.xml.ws.handler.MessageContext; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.ErrorCode; import org.onap.so.utils.CryptoUtils; import org.onap.so.adapters.sdnc.SDNCAdapterRequest; @@ -89,7 +90,7 @@ public class SDNCRestClient { try { Thread.sleep(5000); } catch (InterruptedException e) { - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "SDNC", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "SDNC", ErrorCode.UnknownError.getValue(), "Exception processing request to SDNC", e); Thread.currentThread().interrupt(); @@ -176,7 +177,7 @@ public class SDNCRestClient { logger.info("{} :\n {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.name(), sdncResp.toString(), "SDNC"); return (sdncResp); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC", ErrorCode.BusinessProcesssError.getValue(), "Exception processing request to SDNC", e); // default sdncResp.setRespCode(HttpURLConnection.HTTP_INTERNAL_ERROR); @@ -213,7 +214,7 @@ public class SDNCRestClient { eType = xpath.evaluate("error-type", error); sdncErrMsg = new StringBuilder(". SDNC Returned-[error-type:" + eType); } catch (Exception e3) { - logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), + logger.error(LoggingAnchor.SIX, MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-type", error.toString(), "SDNC", ErrorCode.DataError.getValue(), EXCEPTION_MSG, e3); } @@ -223,7 +224,7 @@ public class SDNCRestClient { eTag = xpath.evaluate("error-tag", error); sdncErrMsg.append(", error-tag:").append(eTag); } catch (Exception e3) { - logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), + logger.error(LoggingAnchor.SIX, MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-tag", error.toString(), "SDNC", ErrorCode.DataError.getValue(), EXCEPTION_MSG, e3); } @@ -233,18 +234,18 @@ public class SDNCRestClient { eMsg = xpath.evaluate("error-message", error); sdncErrMsg.append(", error-message:").append(eMsg).append("]"); } catch (Exception e3) { - logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), + logger.error(LoggingAnchor.SIX, MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-message", error.toString(), "SDNC", ErrorCode.DataError.getValue(), EXCEPTION_MSG, e3); } } } catch (Exception e2) { - logger.error("{} {} {} {}", MessageEnum.RA_ANALYZE_ERROR_EXC.toString(), "SDNC", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_ANALYZE_ERROR_EXC.toString(), "SDNC", ErrorCode.DataError.getValue(), "Exception while analyse error", e2); } } // is != null } catch (Exception e1) { - logger.error("{} {} {} {}", MessageEnum.RA_ERROR_GET_RESPONSE_SDNC.toString(), "SDNC", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_ERROR_GET_RESPONSE_SDNC.toString(), "SDNC", ErrorCode.BusinessProcesssError.getValue(), "Exception while get SDNC response", e1); } } // con != null @@ -256,7 +257,7 @@ public class SDNCRestClient { sdncResp.setRespMsg(respMsg); - logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC", ErrorCode.AvailabilityError.getValue(), "Exception while communicate with SDNC", e); return sdncResp; @@ -282,7 +283,7 @@ public class SDNCRestClient { try { wsdlUrl = new URL(bpelUrl); } catch (MalformedURLException e1) { - logger.error("{} {} {} {}", MessageEnum.RA_INIT_CALLBACK_WSDL_ERR.toString(), CAMUNDA, + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_INIT_CALLBACK_WSDL_ERR.toString(), CAMUNDA, ErrorCode.DataError.getValue(), "Exception initializing Callback wsdl", e1); } @@ -310,7 +311,7 @@ public class SDNCRestClient { reqCtx.put(MessageContext.HTTP_REQUEST_HEADERS, headers); headers.put("Authorization", Collections.singletonList(basicAuth)); } catch (Exception e2) { - logger.error("{} {} {} {}", MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA, + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA, ErrorCode.BusinessProcesssError.getValue(), "Exception - Unable to set authorization in callback request", e2); diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java index 52164bdac7..1c47a2d6b0 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/impl/Utils.java @@ -31,6 +31,7 @@ import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; @@ -97,7 +98,7 @@ public class Utils { return s; } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC", ErrorCode.BusinessProcesssError.getValue(), "Exception in genSdncReq", e); } return null; @@ -131,7 +132,7 @@ public class Utils { return s; } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC", ErrorCode.DataError.getValue(), "Exception in genSdncPutReq", e); } return null; @@ -166,7 +167,7 @@ public class Utils { return s; } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_RESPONSE.toString(), "SDNC", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_ERROR_CREATE_SDNC_RESPONSE.toString(), "SDNC", ErrorCode.DataError.getValue(), "Exception in genMsoFailResp", e); } return null; @@ -191,7 +192,7 @@ public class Utils { s = s.replaceAll("xmlns=\"\"", ""); return s; } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.RA_ERROR_CONVERT_XML2STR.toString(), + logger.error(LoggingAnchor.THREE, MessageEnum.RA_ERROR_CONVERT_XML2STR.toString(), ErrorCode.DataError.getValue(), "Exception - domToStr", e); } } 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 6808230474..b50662a832 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 @@ -25,6 +25,7 @@ package org.onap.so.adapters.sdnc.sdncrest; 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; @@ -92,8 +93,8 @@ public class BPRestCallback { public boolean send(String url, String message) { logger.debug(getClass().getSimpleName() + ".send(" + "url=" + url + " message=" + message + ")"); - logger.info("{} {} {}", MessageEnum.RA_CALLBACK_BPEL.toString(), message == null ? "[no content]" : message, - CAMUNDA); + logger.info(LoggingAnchor.THREE, MessageEnum.RA_CALLBACK_BPEL.toString(), + message == null ? "[no content]" : message, CAMUNDA); HttpPost method = null; HttpResponse httpResponse = null; @@ -123,7 +124,7 @@ public class BPRestCallback { 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("{} {} {} {}", MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA, + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA, ErrorCode.BusinessProcesssError.getValue(), "Unable to set authorization in callback request", e); error = true; @@ -141,14 +142,14 @@ public class BPRestCallback { if (httpResponse.getStatusLine().getStatusCode() >= 300) { String msg = "Received error response to callback request: " + httpResponse.getStatusLine(); - logger.error("{} {} {} {}", MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, ErrorCode.BusinessProcesssError.getValue(), msg); } } return true; } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, ErrorCode.BusinessProcesssError.getValue(), "Error sending callback request", e); return false; } finally { @@ -168,7 +169,7 @@ public class BPRestCallback { logger.debug("Exception:", e); } } - logger.info("{} {}", MessageEnum.RA_CALLBACK_BPEL_COMPLETE.toString(), CAMUNDA); + logger.info(LoggingAnchor.TWO, MessageEnum.RA_CALLBACK_BPEL_COMPLETE.toString(), CAMUNDA); } } } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java index 70943c206f..ad99d0da36 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/MapTypedRequestTunablesData.java @@ -23,6 +23,7 @@ package org.onap.so.adapters.sdnc.sdncrest; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.adapters.sdnc.exception.SDNCAdapterException; import org.onap.so.adapters.sdnc.impl.Constants; import org.onap.so.logger.ErrorCode; @@ -54,7 +55,7 @@ public class MapTypedRequestTunablesData { if ("".equals(value)) { error = MISSING_CONFIGURATION_ERROR_MSG + reqTunable.getKey(); - logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), reqTunable.getKey(), + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), reqTunable.getKey(), "SDNC", ErrorCode.DataError.getValue(), MISSING_CONFIG_PARAM_ERROR_MSG); throw new SDNCAdapterException(error); @@ -64,7 +65,7 @@ public class MapTypedRequestTunablesData { if (parts.length != 5) { error = "Invalid configuration for: " + reqTunable.getKey(); - logger.error("{} {} {} {} {} {}", MessageEnum.RA_SDNC_INVALID_CONFIG.toString(), reqTunable.getKey(), value, + logger.error(LoggingAnchor.SIX, MessageEnum.RA_SDNC_INVALID_CONFIG.toString(), reqTunable.getKey(), value, "SDNC", ErrorCode.DataError.getValue(), "Invalid config"); throw new SDNCAdapterException(error); } @@ -80,7 +81,7 @@ public class MapTypedRequestTunablesData { if ("".equals(reqTunable.getSdncUrl())) { error = MISSING_CONFIGURATION_ERROR_MSG + urlPropKey; - logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), urlPropKey, "SDNC", + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), urlPropKey, "SDNC", ErrorCode.DataError.getValue(), MISSING_CONFIG_PARAM_ERROR_MSG); throw new SDNCAdapterException(error); @@ -98,7 +99,7 @@ public class MapTypedRequestTunablesData { if ("".equals(reqTunable.getMyUrl())) { error = MISSING_CONFIGURATION_ERROR_MSG + Constants.MY_URL_PROP; - logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), Constants.MY_URL_PROP, + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), Constants.MY_URL_PROP, "SDNC", ErrorCode.DataError.getValue(), MISSING_CONFIG_PARAM_ERROR_MSG); throw new SDNCAdapterException(error); diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java index a7c65d87a4..e184bbd110 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCConnector.java @@ -34,6 +34,7 @@ import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; @@ -159,7 +160,7 @@ public abstract class SDNCConnector { method = null; - logger.info("{} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), responseContent, "SDNC"); + logger.info(LoggingAnchor.THREE, MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), responseContent, "SDNC"); return createResponseFromContent(statusCode, statusMessage, responseContent, rt); } catch (SocketTimeoutException | ConnectTimeoutException e) { @@ -192,12 +193,12 @@ public abstract class SDNCConnector { } protected void logError(String errMsg) { - logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC", ErrorCode.AvailabilityError.getValue(), errMsg); } protected void logError(String errMsg, Throwable t) { - logger.error("{} {} {} {}", MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC.toString(), "SDNC", ErrorCode.AvailabilityError.getValue(), errMsg, t); } @@ -283,7 +284,7 @@ public abstract class SDNCConnector { String errorType = xpath.evaluate("error-type", error); info += "error-type:" + errorType; } catch (XPathExpressionException e) { - logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-type", + logger.error(LoggingAnchor.SIX, MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-type", error.toString(), "SDNC", ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e); } @@ -294,7 +295,7 @@ public abstract class SDNCConnector { } info += "error-tag:" + errorTag; } catch (XPathExpressionException e) { - logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-tag", + logger.error(LoggingAnchor.SIX, MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-tag", error.toString(), "SDNC", ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e); } @@ -305,7 +306,7 @@ public abstract class SDNCConnector { } info += "error-message:" + errorMessage; } catch (Exception e) { - logger.error("{} {} {} {} {} {}", MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-message", + logger.error(LoggingAnchor.SIX, MessageEnum.RA_EVALUATE_XPATH_ERROR.toString(), "error-message", error.toString(), "SDNC", ErrorCode.DataError.getValue(), XPATH_EXCEPTION, e); } @@ -318,7 +319,7 @@ public abstract class SDNCConnector { } } } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.RA_ANALYZE_ERROR_EXC.toString(), "SDNC", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_ANALYZE_ERROR_EXC.toString(), "SDNC", ErrorCode.DataError.getValue(), "Exception while analyzing errors", e); } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java index 7e82adf064..a68bd3e0be 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SDNCServiceRequestTask.java @@ -31,6 +31,7 @@ import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpStatus; import org.onap.so.adapters.sdnc.exception.SDNCAdapterException; import org.onap.so.adapters.sdncrest.RequestInformation; @@ -185,7 +186,7 @@ public class SDNCServiceRequestTask { addTextChild(agnosticServiceInformation, "content-type", contentType); addTextChild(agnosticServiceInformation, "anydata", anydata); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC", + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST.toString(), "SDNC", ErrorCode.BusinessProcesssError.getValue(), "Exception in genSdncReq", e); return null; } @@ -204,8 +205,8 @@ public class SDNCServiceRequestTask { transformer.transform(new DOMSource(doc), new StreamResult(writer)); xml = writer.toString(); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.RA_ERROR_CONVERT_XML2STR.toString(), ErrorCode.DataError.getValue(), - "Exception - domToStr", e); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_ERROR_CONVERT_XML2STR.toString(), + ErrorCode.DataError.getValue(), "Exception - domToStr", e); return null; } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java index 3921891ced..5f80c20b97 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/SNIROResponse.java @@ -31,6 +31,7 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.adapters.sdnc.impl.Constants; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; @@ -61,14 +62,14 @@ public class SNIROResponse { @Consumes("*/*") @Produces({MediaType.TEXT_PLAIN}) public Response serviceNotification(@PathParam("correlator") String correlator, String content) { - logger.info("{} {} {} {}", MessageEnum.RA_RECEIVE_SDNC_NOTIF.toString(), content, "SDNC", + logger.info(LoggingAnchor.FOUR, MessageEnum.RA_RECEIVE_SDNC_NOTIF.toString(), content, "SDNC", "SDNCNotify/SNIROResponse"); String bpUrl = env.getProperty(Constants.BPEL_REST_URL_PROP, ""); if (bpUrl == null || ("").equals(bpUrl)) { String error = "Missing configuration for: " + Constants.BPEL_REST_URL_PROP; - logger.error("{} {} {} {} {}", MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_SDNC_MISS_CONFIG_PARAM.toString(), Constants.BPEL_REST_URL_PROP, "SDNC", ErrorCode.DataError.getValue(), "Missing config param"); return Response.status(HttpServletResponse.SC_BAD_REQUEST).entity(error).build(); diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/JsonUtil.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/JsonUtil.java index cefaadbb63..e8b4cfd997 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/JsonUtil.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/JsonUtil.java @@ -24,6 +24,7 @@ package org.onap.so.adapters.vfc.util; import java.io.IOException; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.adapters.vfc.constant.HttpCode; import org.onap.so.adapters.vfc.exceptions.ApplicationException; import org.onap.so.logger.ErrorCode; @@ -83,8 +84,8 @@ public class JsonUtil { try { return MAPPER.readValue(jsonstr, type); } catch (IOException e) { - logger.error("{} {} {}", MessageEnum.RA_NS_EXC.toString(), ErrorCode.BusinessProcesssError.getValue(), - UNMARSHAL_FAIL_MSG, e); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_NS_EXC.toString(), + ErrorCode.BusinessProcesssError.getValue(), UNMARSHAL_FAIL_MSG, e); throw new ApplicationException(HttpCode.BAD_REQUEST, UNMARSHAL_FAIL_MSG); } } @@ -101,8 +102,8 @@ public class JsonUtil { try { return MAPPER.readValue(jsonstr, type); } catch (IOException e) { - logger.error("{} {} {}", MessageEnum.RA_NS_EXC.toString(), ErrorCode.BusinessProcesssError.getValue(), - UNMARSHAL_FAIL_MSG, e); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_NS_EXC.toString(), + ErrorCode.BusinessProcesssError.getValue(), UNMARSHAL_FAIL_MSG, e); throw new ApplicationException(HttpCode.BAD_REQUEST, UNMARSHAL_FAIL_MSG); } } @@ -118,8 +119,8 @@ public class JsonUtil { try { return MAPPER.writeValueAsString(srcObj); } catch (IOException e) { - logger.error("{} {} {}", MessageEnum.RA_NS_EXC.toString(), ErrorCode.BusinessProcesssError.getValue(), - "fail to marshal json", e); + logger.error(LoggingAnchor.THREE, MessageEnum.RA_NS_EXC.toString(), + ErrorCode.BusinessProcesssError.getValue(), "fail to marshal json", e); throw new ApplicationException(HttpCode.BAD_REQUEST, "srcObj marshal failed!"); } } diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/RestfulUtil.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/RestfulUtil.java index 3419e6d20c..647fcafa66 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/RestfulUtil.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/util/RestfulUtil.java @@ -27,6 +27,7 @@ package org.onap.so.adapters.vfc.util; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import javax.ws.rs.core.UriBuilder; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; @@ -79,6 +80,9 @@ public class RestfulUtil { @Autowired private Environment env; + @Autowired + private HttpClient client; + public String getMsbHost() { // MSB_IP will be set as ONAP_IP environment parameter in install flow. String msbIp = System.getenv().get(ONAP_IP); @@ -111,8 +115,6 @@ public class RestfulUtil { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout) .setConnectionRequestTimeout(timeout).build(); - HttpClient client = HttpClientBuilder.create().build(); - if ("POST".equalsIgnoreCase(methodType)) { HttpPost httpPost = new HttpPost(msbUrl); httpPost.setConfig(requestConfig); @@ -193,12 +195,12 @@ public class RestfulUtil { } private static void logError(String errMsg, Throwable t) { - logger.error("{} {} {} {}", MessageEnum.RA_NS_EXC.toString(), VFC_ADAPTER, + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_NS_EXC.toString(), VFC_ADAPTER, ErrorCode.AvailabilityError.getValue(), errMsg, t); } private static void logError(String errMsg) { - logger.error("{} {} {} {}", MessageEnum.RA_NS_EXC.toString(), VFC_ADAPTER, + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_NS_EXC.toString(), VFC_ADAPTER, ErrorCode.AvailabilityError.toString(), errMsg); } diff --git a/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/util/RestfulUtilTest.java b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/util/RestfulUtilTest.java new file mode 100644 index 0000000000..c388016ab4 --- /dev/null +++ b/adapters/mso-vfc-adapter/src/test/java/org/onap/so/adapters/vfc/util/RestfulUtilTest.java @@ -0,0 +1,156 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (c) 2019 Samsung. 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.adapters.vfc.util; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.StatusLine; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +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.vfc.model.RestfulResponse; +import org.springframework.http.HttpStatus; +import javax.ws.rs.HttpMethod; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class RestfulUtilTest { + + @InjectMocks + @Spy + private RestfulUtil restfulUtil; + + @Mock + private HttpClient client; + + private HttpEntity httpEntity; + private HttpResponse httpResponse; + private StatusLine statusLine; + + @Before + public void setUp() { + httpEntity = mock(HttpEntity.class); + httpResponse = mock(HttpResponse.class); + statusLine = mock(StatusLine.class); + } + + private void sendInit() throws IOException { + + doReturn("https://testHost/").when(restfulUtil).getMsbHost(); + + when(statusLine.getStatusCode()).thenReturn(HttpStatus.OK.value()); + when(httpResponse.getStatusLine()).thenReturn(statusLine); + when(httpResponse.getEntity()).thenReturn(httpEntity); + } + + @Test + public void sendGet() throws Exception { + + sendInit(); + + ByteArrayInputStream responseStream = new ByteArrayInputStream(new String("GET").getBytes()); + when(client.execute(any(HttpGet.class))).thenReturn(httpResponse); + when(httpEntity.getContent()).thenReturn(responseStream); + + RestfulResponse restfulResponse = restfulUtil.send("test", HttpMethod.GET, "some request content"); + + assertEquals(HttpStatus.OK.value(), restfulResponse.getStatus()); + assertEquals("GET", restfulResponse.getResponseContent()); + + } + + @Test + public void sendPost() throws Exception { + + sendInit(); + + + ByteArrayInputStream responseStream = new ByteArrayInputStream(new String("POST").getBytes()); + when(client.execute(any(HttpPost.class))).thenReturn(httpResponse); + when(httpEntity.getContent()).thenReturn(responseStream); + + RestfulResponse restfulResponse = restfulUtil.send("test", HttpMethod.POST, "some request content"); + + assertEquals(HttpStatus.OK.value(), restfulResponse.getStatus()); + assertEquals("POST", restfulResponse.getResponseContent()); + + } + + @Test + public void sendPut() throws Exception { + + sendInit(); + + ByteArrayInputStream responseStream = new ByteArrayInputStream(new String("PUT").getBytes()); + when(client.execute(any(HttpPut.class))).thenReturn(httpResponse); + when(httpEntity.getContent()).thenReturn(responseStream); + + RestfulResponse restfulResponse = restfulUtil.send("test", HttpMethod.PUT, "some request content"); + + assertEquals(HttpStatus.OK.value(), restfulResponse.getStatus()); + assertEquals("PUT", restfulResponse.getResponseContent()); + + } + + @Test + public void sendDelete() throws Exception { + + sendInit(); + + ByteArrayInputStream responseStream = new ByteArrayInputStream(new String("DELETE").getBytes()); + when(client.execute(any(HttpDelete.class))).thenReturn(httpResponse); + when(httpEntity.getContent()).thenReturn(responseStream); + + RestfulResponse restfulResponse = restfulUtil.send("test", HttpMethod.DELETE, "some request content"); + + assertEquals(HttpStatus.OK.value(), restfulResponse.getStatus()); + assertEquals("DELETE", restfulResponse.getResponseContent()); + + } + + @Test + public void sendOptions() throws Exception { + + doReturn("https://testHost/").when(restfulUtil).getMsbHost(); + + RestfulResponse restfulResponse = restfulUtil.send("test", HttpMethod.OPTIONS, "some request content"); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), restfulResponse.getStatus()); + assertEquals("Error processing request to VFC", restfulResponse.getResponseContent()); + + } + +} 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 164f12ea29..2aee1c06e3 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 @@ -20,6 +20,10 @@ 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.util.Iterator; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.JSON; import org.onap.so.configuration.rest.BasicHttpHeadersProvider; import org.onap.so.configuration.rest.HttpHeadersProvider; import org.onap.so.rest.service.HttpRestServiceProvider; @@ -32,8 +36,6 @@ 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; -import java.util.Iterator; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; /** * Configures the HttpRestServiceProvider for REST call to a VNFM. @@ -60,7 +62,8 @@ public class VnfmServiceProviderConfiguration { iterator.remove(); } } - restTemplate.getMessageConverters().add(new GsonHttpMessageConverter()); + 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/jobmanagement/JobManager.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/JobManager.java index 345ff5119a..b3552c780e 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/JobManager.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/JobManager.java @@ -93,6 +93,10 @@ public class JobManager { logger.debug("Job Id: " + jobId + ", operationId: " + operation.getId() + ", operation details: " + operation); + if (operation.getOperationState() == null) { + return response.operationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.WAITING_FOR_STATUS); + } + response.setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND); response.setId(operation.getId()); response.setOperation(OperationEnum.fromValue(operation.getOperation().getValue())); diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterControllerTest.java index 73a49e9c40..b48de30f88 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterControllerTest.java @@ -52,6 +52,7 @@ import org.onap.aai.domain.yang.RelationshipData; import org.onap.aai.domain.yang.RelationshipList; import org.onap.so.adapters.vnfmadapter.VnfmAdapterApplication; import org.onap.so.adapters.vnfmadapter.extclients.SdcPackageProvider; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.JSON; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse2001; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201; @@ -115,7 +116,7 @@ public class VnfmAdapterControllerTest { @Autowired VnfmAdapterController controller; - Gson gson = new Gson(); + Gson gson = new JSON().getGson(); @Before public void setUp() throws Exception { diff --git a/asdc-controller/pom.xml b/asdc-controller/pom.xml index 8317b660a6..60c517d944 100644 --- a/asdc-controller/pom.xml +++ b/asdc-controller/pom.xml @@ -16,8 +16,8 @@ <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <antlr.version>4.7.1</antlr.version> <java.version>1.8</java.version> - <sdc.tosca.version>1.5.0</sdc.tosca.version> - <jtosca.version>1.5.0</jtosca.version> + <sdc.tosca.version>1.5.1</sdc.tosca.version> + <jtosca.version>1.5.1</jtosca.version> </properties> <build> diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/Application.java b/asdc-controller/src/main/java/org/onap/so/asdc/Application.java index a05eeea466..eb2957c6f8 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/Application.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/Application.java @@ -22,6 +22,8 @@ package org.onap.so.asdc; import javax.annotation.PostConstruct; import org.onap.so.asdc.activity.DeployActivitySpecs; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -32,7 +34,7 @@ import org.springframework.scheduling.annotation.EnableScheduling; @EnableScheduling @EnableJpaRepositories("org.onap.so.db.catalog.data.repository") public class Application { - + private static final Logger logger = LoggerFactory.getLogger(Application.class); private static final String MSO_CONFIG_PATH = "mso.config.path"; private static final String LOGS_DIR = "logs_dir"; @@ -55,6 +57,7 @@ public class Application { try { deployActivitySpecs.deployActivities(); } catch (Exception e) { + logger.warn("{} {}", "Exception on deploying activitySpecs: ", e.getMessage()); } } diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/activity/ActivitySpecsActions.java b/asdc-controller/src/main/java/org/onap/so/asdc/activity/ActivitySpecsActions.java index c80e84b574..afa6ccced1 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/activity/ActivitySpecsActions.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/activity/ActivitySpecsActions.java @@ -22,6 +22,7 @@ package org.onap.so.asdc.activity; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpStatus; import org.apache.http.entity.ContentType; import org.onap.so.asdc.activity.beans.ActivitySpec; @@ -67,8 +68,10 @@ public class ActivitySpecsActions { Response response = httpClient.post(payload); int statusCode = response.getStatus(); - if (statusCode != HttpStatus.SC_OK) { - logger.warn("{} {} {}", "Error creating activity spec", activitySpec.getName(), statusCode); + if (statusCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) { + logger.warn(LoggingAnchor.THREE, "ActivitySpec", activitySpec.getName(), "already exists in SDC"); + } else if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { + logger.warn(LoggingAnchor.THREE, "Error creating activity spec", activitySpec.getName(), statusCode); } else { if (response.getEntity() != null) { ActivitySpecCreateResponse activitySpecCreateResponse = @@ -76,14 +79,14 @@ public class ActivitySpecsActions { if (activitySpecCreateResponse != null) { activitySpecId = activitySpecCreateResponse.getId(); } else { - logger.warn("{} {}", "Unable to read activity spec", activitySpec.getName()); + logger.warn(LoggingAnchor.TWO, "Unable to read activity spec", activitySpec.getName()); } } else { - logger.warn("{} {}", "No activity spec response returned", activitySpec.getName()); + logger.warn(LoggingAnchor.TWO, "No activity spec response returned", activitySpec.getName()); } } } catch (Exception e) { - logger.warn("{} {}", "Exception creating activitySpec", e.getMessage()); + logger.warn(LoggingAnchor.TWO, "Exception creating activitySpec", e.getMessage()); } return activitySpecId; @@ -108,14 +111,16 @@ public class ActivitySpecsActions { int statusCode = response.getStatus(); - if (statusCode != HttpStatus.SC_OK) { - logger.warn("{} {} {}", "Error certifying activity", activitySpecId, statusCode); + if (statusCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) { + logger.warn(LoggingAnchor.THREE, "ActivitySpec with id", activitySpecId, "is already certified in SDC"); + } else if (statusCode != HttpStatus.SC_OK) { + logger.warn(LoggingAnchor.THREE, "Error certifying activity", activitySpecId, statusCode); } else { certificationResult = true; } } catch (Exception e) { - logger.warn("{} {}", "Exception certifying activitySpec", e.getMessage()); + logger.warn(LoggingAnchor.TWO, "Exception certifying activitySpec", e.getMessage()); } return certificationResult; diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/activity/DeployActivitySpecs.java b/asdc-controller/src/main/java/org/onap/so/asdc/activity/DeployActivitySpecs.java index 43eb277d21..325ba913f8 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/activity/DeployActivitySpecs.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/activity/DeployActivitySpecs.java @@ -22,9 +22,11 @@ package org.onap.so.asdc.activity; import java.util.ArrayList; import java.util.List; +import org.onap.so.logger.LoggingAnchor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; import org.onap.so.asdc.activity.beans.ActivitySpec; import org.onap.so.asdc.activity.beans.Input; import org.onap.so.asdc.activity.beans.Output; @@ -52,26 +54,28 @@ public class DeployActivitySpecs { protected static final Logger logger = LoggerFactory.getLogger(DeployActivitySpecs.class); - + @Transactional public void deployActivities() throws Exception { String hostname = env.getProperty(SDC_ENDPOINT); + logger.debug("{} {}", "SDC ActivitySpec endpoint: ", hostname); if (hostname == null || hostname.isEmpty()) { return; } List<org.onap.so.db.catalog.beans.ActivitySpec> activitySpecsFromCatalog = activitySpecRepository.findAll(); for (org.onap.so.db.catalog.beans.ActivitySpec activitySpecFromCatalog : activitySpecsFromCatalog) { + logger.debug("{} {}", "Attempting to create activity ", activitySpecFromCatalog.getName()); ActivitySpec activitySpec = mapActivitySpecFromCatalogToSdc(activitySpecFromCatalog); String activitySpecId = activitySpecsActions.createActivitySpec(hostname, activitySpec); if (activitySpecId != null) { - logger.info("{} {}", "Successfully created activitySpec", activitySpec.getName()); + logger.info(LoggingAnchor.TWO, "Successfully created activitySpec", activitySpec.getName()); boolean certificationResult = activitySpecsActions.certifyActivitySpec(hostname, activitySpecId); if (certificationResult) { - logger.info("{} {}", "Successfully certified activitySpec", activitySpec.getName()); + logger.info(LoggingAnchor.TWO, "Successfully certified activitySpec", activitySpec.getName()); } else { - logger.info("{} {}", "Failed to certify activitySpec", activitySpec.getName()); + logger.info(LoggingAnchor.TWO, "Failed to certify activitySpec", activitySpec.getName()); } } else { - logger.info("{} {}", "Failed to create activitySpec", activitySpec.getName()); + logger.info(LoggingAnchor.TWO, "Failed to create activitySpec", activitySpec.getName()); } } } diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCConfiguration.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCConfiguration.java index 2eace7587f..60abdc33ef 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCConfiguration.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCConfiguration.java @@ -9,9 +9,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -57,9 +57,10 @@ public class ASDCConfiguration implements IConfiguration { public static final String TOSCA_CSAR = "TOSCA_CSAR"; public static final String WORKFLOW = "WORKFLOW"; public static final String VF_MODULES_METADATA = "VF_MODULES_METADATA"; + public static final String CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT = "CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT"; - private static final String[] SUPPORTED_ARTIFACT_TYPES = - {HEAT, HEAT_ARTIFACT, HEAT_ENV, HEAT_NESTED, HEAT_NET, HEAT_VOL, OTHER, TOSCA_CSAR, VF_MODULES_METADATA}; + private static final String[] SUPPORTED_ARTIFACT_TYPES = {HEAT, HEAT_ARTIFACT, HEAT_ENV, HEAT_NESTED, HEAT_NET, + HEAT_VOL, OTHER, TOSCA_CSAR, VF_MODULES_METADATA, CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT, WORKFLOW}; public static final List<String> SUPPORTED_ARTIFACT_TYPES_LIST = Collections.unmodifiableList(Arrays.asList(SUPPORTED_ARTIFACT_TYPES)); diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java index ea1d194c68..563291c479 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java @@ -36,6 +36,7 @@ import java.io.UnsupportedEncodingException; import java.nio.file.Paths; import java.util.List; import java.util.Optional; +import org.onap.so.logger.LoggingAnchor; import org.onap.sdc.api.IDistributionClient; import org.onap.sdc.api.consumer.IDistributionStatusMessage; import org.onap.sdc.api.consumer.IFinalDistrStatusMessage; @@ -232,7 +233,8 @@ public class ASDCController { } this.changeControllerStatus(ASDCControllerStatus.IDLE); - logger.info("{} {} {}", MessageEnum.ASDC_INIT_ASDC_CLIENT_SUC.toString(), "ASDC", "changeControllerStatus"); + logger.info(LoggingAnchor.THREE, MessageEnum.ASDC_INIT_ASDC_CLIENT_SUC.toString(), "ASDC", + "changeControllerStatus"); } /** @@ -264,7 +266,7 @@ public class ASDCController { if (toscaInstaller.isResourceAlreadyDeployed(resource, serviceDeployed)) { - logger.info("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_EXIST.toString(), + logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_ARTIFACT_ALREADY_EXIST.toString(), resource.getResourceInstance().getResourceInstanceName(), resource.getResourceInstance().getResourceUUID(), resource.getResourceInstance().getResourceName()); @@ -334,7 +336,7 @@ public class ASDCController { try { downloadResult = distributionClient.download(artifact); if (null == downloadResult) { - logger.info("{} {}", MessageEnum.ASDC_ARTIFACT_NULL.toString(), artifact.getArtifactUUID()); + logger.info(LoggingAnchor.TWO, MessageEnum.ASDC_ARTIFACT_NULL.toString(), artifact.getArtifactUUID()); return downloadResult; } } catch (RuntimeException e) { @@ -346,11 +348,12 @@ public class ASDCController { } if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult())) { - logger.info("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_DOWNLOAD_SUC.toString(), artifact.getArtifactURL(), - artifact.getArtifactUUID(), String.valueOf(downloadResult.getArtifactPayload().length)); + logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_ARTIFACT_DOWNLOAD_SUC.toString(), + artifact.getArtifactURL(), artifact.getArtifactUUID(), + String.valueOf(downloadResult.getArtifactPayload().length)); } else { - logger.error("{} {} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL.toString(), + logger.error(LoggingAnchor.SEVEN, MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL.toString(), artifact.getArtifactName(), artifact.getArtifactURL(), artifact.getArtifactUUID(), downloadResult.getDistributionMessageResult(), ErrorCode.DataError.getValue(), "ASDC artifact download fail"); @@ -391,12 +394,12 @@ public class ASDCController { byte[] payloadBytes = resultArtifact.getArtifactPayload(); try (FileOutputStream outFile = new FileOutputStream(filePath)) { - logger.info("{} {} {} {}", MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), "***WRITE FILE ARTIFACT NAME", - "ASDC", artifact.getArtifactName()); + logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), + "***WRITE FILE ARTIFACT NAME", "ASDC", artifact.getArtifactName()); outFile.write(payloadBytes, 0, payloadBytes.length); } catch (Exception e) { logger.debug("Exception :", e); - logger.error("{} {} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL.toString(), + logger.error(LoggingAnchor.SEVEN, MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL.toString(), artifact.getArtifactName(), artifact.getArtifactURL(), artifact.getArtifactUUID(), resultArtifact.getDistributionMessageResult(), ErrorCode.DataError.getValue(), "ASDC write to file failed"); @@ -444,7 +447,7 @@ public class ASDCController { protected void deployResourceStructure(ResourceStructure resourceStructure, ToscaResourceStructure toscaResourceStructure) throws ArtifactInstallerException { - logger.info("{} {} {} {}", MessageEnum.ASDC_START_DEPLOY_ARTIFACT.toString(), + logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_START_DEPLOY_ARTIFACT.toString(), resourceStructure.getResourceInstance().getResourceInstanceName(), resourceStructure.getResourceInstance().getResourceUUID(), "ASDC"); try { @@ -452,7 +455,7 @@ public class ASDCController { toscaInstaller.installTheResource(toscaResourceStructure, resourceStructure); } catch (ArtifactInstallerException e) { - logger.info("{} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL.toString(), + logger.info(LoggingAnchor.SIX, MessageEnum.ASDC_ARTIFACT_DOWNLOAD_FAIL.toString(), resourceStructure.getResourceInstance().getResourceName(), resourceStructure.getResourceInstance().getResourceUUID(), String.valueOf(resourceStructure.getNumberOfResources()), "ASDC", "deployResourceStructure"); @@ -461,7 +464,7 @@ public class ASDCController { } if (resourceStructure.isDeployedSuccessfully() || toscaResourceStructure.isDeployedSuccessfully()) { - logger.info("{} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC.toString(), + logger.info(LoggingAnchor.SIX, MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC.toString(), resourceStructure.getResourceInstance().getResourceName(), resourceStructure.getResourceInstance().getResourceUUID(), String.valueOf(resourceStructure.getNumberOfResources()), "ASDC", "deployResourceStructure"); @@ -484,7 +487,7 @@ public class ASDCController { if (errorReason != null) { event = event + "(" + errorReason + ")"; } - logger.info("{} {} {} {} {} {}", MessageEnum.ASDC_SEND_NOTIF_ASDC.toString(), notificationType.name(), + logger.info(LoggingAnchor.SIX, MessageEnum.ASDC_SEND_NOTIF_ASDC.toString(), notificationType.name(), status.name(), artifactURL, "ASDC", "sendASDCNotification"); logger.debug(event); @@ -514,7 +517,7 @@ public class ASDCController { break; } } catch (RuntimeException e) { - logger.warn("{} {} {} {} {}", MessageEnum.ASDC_SEND_NOTIF_ASDC_EXEC.toString(), "ASDC", + logger.warn(LoggingAnchor.FIVE, MessageEnum.ASDC_SEND_NOTIF_ASDC_EXEC.toString(), "ASDC", "sendASDCNotification", ErrorCode.SchemaError.getValue(), "RuntimeException - sendASDCNotification", e); } @@ -541,7 +544,7 @@ public class ASDCController { } catch (RuntimeException e) { logger.debug("Exception caught in sendFinalDistributionStatus {}", e.getMessage()); - logger.warn("{} {} {} {} {}", MessageEnum.ASDC_SEND_NOTIF_ASDC_EXEC.toString(), "ASDC", + logger.warn(LoggingAnchor.FIVE, MessageEnum.ASDC_SEND_NOTIF_ASDC_EXEC.toString(), "ASDC", "sendASDCNotification", ErrorCode.SchemaError.getValue(), "RuntimeException - sendASDCNotification", e); } @@ -570,11 +573,11 @@ public class ASDCController { for (IResourceInstance resource : iNotif.getResources()) { noOfArtifacts += resource.getArtifacts().size(); } - logger.info("{} {} {} {}", MessageEnum.ASDC_RECEIVE_CALLBACK_NOTIF.toString(), String.valueOf(noOfArtifacts), - iNotif.getServiceUUID(), "ASDC"); + logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_RECEIVE_CALLBACK_NOTIF.toString(), + String.valueOf(noOfArtifacts), iNotif.getServiceUUID(), "ASDC"); try { logger.debug(ASDCNotificationLogging.dumpASDCNotification(iNotif)); - logger.info("{} {} {} {}", MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), iNotif.getServiceUUID(), + logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), iNotif.getServiceUUID(), "ASDC", "treatNotification"); this.changeControllerStatus(ASDCControllerStatus.BUSY); @@ -665,7 +668,7 @@ public class ASDCController { "OptimisticLockingFailure for DistributionId: {} Another process " + "has already altered this distribution, so not going to process it on this site.", iNotif.getDistributionID()); - logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(), "Database concurrency exception: ", "ASDC", "treatNotification", ErrorCode.BusinessProcesssError.getValue(), "RuntimeException in treatNotification", e); @@ -787,27 +790,27 @@ public class ASDCController { errorMessage = e.getMessage(); logger.error("Exception occurred", e); } + } - if (!hasVFResource) { + if (!hasVFResource) { - logger.debug("No resources found for Service: " + iNotif.getServiceUUID()); + logger.debug("No resources found for Service: " + iNotif.getServiceUUID()); - logger.debug("Preparing to deploy Service: {}", iNotif.getServiceUUID()); - try { - this.deployResourceStructure(resourceStructure, toscaResourceStructure); - } catch (ArtifactInstallerException e) { - deployStatus = DistributionStatusEnum.DEPLOY_ERROR; - errorMessage = e.getMessage(); - logger.error("Exception occurred", e); - } + logger.debug("Preparing to deploy Service: {}", iNotif.getServiceUUID()); + try { + this.deployResourceStructure(resourceStructure, toscaResourceStructure); + } catch (ArtifactInstallerException e) { + deployStatus = DistributionStatusEnum.DEPLOY_ERROR; + errorMessage = e.getMessage(); + logger.error("Exception occurred", e); } - this.sendCsarDeployNotification(iNotif, resourceStructure, toscaResourceStructure, deployStatus, - errorMessage); } + this.sendCsarDeployNotification(iNotif, resourceStructure, toscaResourceStructure, deployStatus, + errorMessage); } catch (ASDCDownloadException | UnsupportedEncodingException e) { - logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.SIX, MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(), "Exception caught during Installation of artifact", "ASDC", "processResourceNotification", ErrorCode.BusinessProcesssError.getValue(), "Exception in processResourceNotification", e); } @@ -853,7 +856,7 @@ public class ASDCController { } catch (Exception e) { - logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.SIX, MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(), "Exception caught during processCsarServiceArtifacts", "ASDC", "processCsarServiceArtifacts", ErrorCode.BusinessProcesssError.getValue(), "Exception in processCsarServiceArtifacts", e); @@ -874,7 +877,7 @@ public class ASDCController { } catch (Exception e) { logger.info("Whats the error {}", e.getMessage()); - logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.SIX, MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(), "Exception caught during processCsarServiceArtifacts", "ASDC", "processCsarServiceArtifacts", ErrorCode.BusinessProcesssError.getValue(), "Exception in processCsarServiceArtifacts", e); diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/rest/ASDCRestInterface.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/rest/ASDCRestInterface.java index 6a9c1aa848..56690a8c38 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/rest/ASDCRestInterface.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/rest/ASDCRestInterface.java @@ -31,6 +31,7 @@ import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.asdc.client.ASDCController; import org.onap.so.asdc.client.exceptions.ASDCControllerException; import org.onap.so.asdc.client.exceptions.ASDCParametersException; @@ -104,11 +105,11 @@ public class ASDCRestInterface { toscaInstaller.installTheComponentStatus(statusData); controller.closeASDC(); - logger.info("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC.toString(), statusData.getDistributionID(), - "ASDC", "ASDC Updates Are Complete"); + logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC.toString(), + statusData.getDistributionID(), "ASDC", "ASDC Updates Are Complete"); } catch (Exception e) { logger.info("Error caught " + e.getMessage()); - logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION.toString(), + logger.error(LoggingAnchor.SIX, MessageEnum.ASDC_GENERAL_EXCEPTION.toString(), "Exception caught during ASDCRestInterface", "ASDC", "invokeASDCService", ErrorCode.BusinessProcesssError.getValue(), "Exception in invokeASDCService", e); } diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java index 749a397ee0..c49cb3e50f 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java @@ -25,6 +25,7 @@ package org.onap.so.asdc.installer; import java.io.File; import java.nio.file.Paths; import java.util.List; +import org.onap.so.logger.LoggingAnchor; import org.onap.sdc.api.notification.IArtifactInfo; import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory; @@ -142,14 +143,14 @@ public class ToscaResourceStructure { File spoolFile = new File(filePath); logger.debug("ASDC File path is: {}", spoolFile.getAbsolutePath()); - logger.info("{} {} {} {}", MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), "***PATH", "ASDC", + logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), "***PATH", "ASDC", spoolFile.getAbsolutePath()); sdcCsarHelper = factory.getSdcCsarHelper(spoolFile.getAbsolutePath(), false); } catch (Exception e) { logger.debug(e.getMessage(), e); - logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.SIX, MessageEnum.ASDC_GENERAL_EXCEPTION_ARG.toString(), "Exception caught during parser *****LOOK********* " + artifact.getArtifactName(), "ASDC", "processResourceNotification", ErrorCode.BusinessProcesssError.getValue(), "Exception in " + "processResourceNotification", e); diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfResourceStructure.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfResourceStructure.java index 16e9fda7c4..f954fe0c5a 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfResourceStructure.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/VfResourceStructure.java @@ -25,10 +25,11 @@ package org.onap.so.asdc.installer; import java.io.IOException; import java.io.UnsupportedEncodingException; -import java.util.HashMap; +import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.asdc.client.ASDCConfiguration; import org.onap.so.asdc.client.exceptions.ArtifactInstallerException; import org.onap.so.asdc.util.ASDCNotificationLogging; @@ -80,6 +81,7 @@ public class VfResourceStructure extends ResourceStructure { super(notificationdata, resourceinstance); this.resourceType = ResourceType.VF_RESOURCE; vfModulesStructureList = new LinkedList<>(); + vfModulesMetadataList = new ArrayList<>(); } public void addArtifactToStructure(IDistributionClient distributionClient, IArtifactInfo artifactinfo, @@ -105,7 +107,7 @@ public class VfResourceStructure extends ResourceStructure { } protected void addArtifactByType(IArtifactInfo artifactinfo, IDistributionClientDownloadResult clientResult, - VfModuleArtifact vfModuleArtifact) throws UnsupportedEncodingException { + VfModuleArtifact vfModuleArtifact) { switch (artifactinfo.getArtifactType()) { case ASDCConfiguration.HEAT: @@ -115,6 +117,7 @@ public class VfResourceStructure extends ResourceStructure { case ASDCConfiguration.HEAT_ARTIFACT: case ASDCConfiguration.HEAT_NET: case ASDCConfiguration.OTHER: + case ASDCConfiguration.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT: artifactsMapByUUID.put(artifactinfo.getArtifactUUID(), vfModuleArtifact); break; case ASDCConfiguration.VF_MODULES_METADATA: @@ -132,9 +135,9 @@ public class VfResourceStructure extends ResourceStructure { public void createVfModuleStructures() throws ArtifactInstallerException { // for vender tosca VNF there is no VFModule in VF - if (vfModulesMetadataList == null) { - logger.info("{} {} {} {}", MessageEnum.ASDC_GENERAL_INFO.toString(), "There is no VF mudules in the VF.", - "ASDC", "createVfModuleStructures"); + if (vfModulesMetadataList.isEmpty()) { + logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_GENERAL_INFO.toString(), + "There is no VF mudules in the VF.", "ASDC", "createVfModuleStructures"); return; } for (IVfModuleData vfModuleMeta : vfModulesMetadataList) { @@ -147,6 +150,7 @@ public class VfResourceStructure extends ResourceStructure { return vfModulesStructureList; } + @Override public Map<String, VfModuleArtifact> getArtifactsMapByUUID() { return artifactsMapByUUID; } @@ -203,6 +207,6 @@ public class VfResourceStructure extends ResourceStructure { } catch (IOException e) { logger.debug("IOException : ", e); } - return null; + return new ArrayList<>(); } } diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/BpmnInstaller.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/BpmnInstaller.java index 7945ad0174..095741c19b 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/BpmnInstaller.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/BpmnInstaller.java @@ -33,7 +33,9 @@ import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; +import org.onap.so.logger.LoggingAnchor; import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; @@ -45,6 +47,7 @@ import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.ByteArrayBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.HttpClientBuilder; +import org.onap.so.asdc.client.ASDCConfiguration; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; @@ -63,6 +66,9 @@ public class BpmnInstaller { @Autowired private Environment env; + @Autowired + private ASDCConfiguration asdcConfig; + public void installBpmn(String csarFilePath) { logger.info("Deploying BPMN files from {}", csarFilePath); try { @@ -83,7 +89,7 @@ public class BpmnInstaller { logger.debug("Response entity: {}", response.getEntity().toString()); if (response.getStatusLine().getStatusCode() != 200) { logger.debug("Failed deploying BPMN {}", name); - logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), + logger.error(LoggingAnchor.SIX, MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), name, fileName, Integer.toString(response.getStatusLine().getStatusCode()), ErrorCode.DataError.getValue(), "ASDC BPMN deploy failed"); } else { @@ -91,7 +97,7 @@ public class BpmnInstaller { } } catch (Exception e) { logger.debug("Exception :", e); - logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), name, + logger.error(LoggingAnchor.FIVE, MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), name, e.getMessage(), ErrorCode.DataError.getValue(), "ASDC BPMN deploy failed"); } } @@ -100,7 +106,7 @@ public class BpmnInstaller { csarFile.close(); } catch (IOException ex) { logger.debug("Exception :", ex); - logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), csarFilePath, + logger.error(LoggingAnchor.FIVE, MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), csarFilePath, ex.getMessage(), ErrorCode.DataError.getValue(), "ASDC reading CSAR with workflows failed"); } return; @@ -119,8 +125,8 @@ public class BpmnInstaller { } } catch (Exception e) { logger.debug("Exception :", e); - logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), csarFilePath, e.getMessage(), - ErrorCode.DataError.getValue(), "ASDC Unable to check CSAR entries"); + logger.error(LoggingAnchor.FIVE, MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), csarFilePath, + e.getMessage(), ErrorCode.DataError.getValue(), "ASDC Unable to check CSAR entries"); } return workflowsInCsar; } @@ -139,7 +145,7 @@ public class BpmnInstaller { protected HttpEntity buildMimeMultipart(String bpmnFileName, String version) throws Exception { FileInputStream bpmnFileStream = new FileInputStream( - Paths.get(System.getProperty("mso.config.path"), "ASDC", version, bpmnFileName).normalize().toString()); + Paths.get(getMsoConfigPath(), "ASDC", version, bpmnFileName).normalize().toString()); byte[] bytesToSend = IOUtils.toByteArray(bpmnFileStream); HttpEntity requestEntity = @@ -193,4 +199,14 @@ public class BpmnInstaller { logger.error("Unable to open file.", e); } } + + private String getMsoConfigPath() { + String msoConfigPath = System.getProperty("mso.config.path"); + if (msoConfigPath == null) { + logger.info("Unable to find the system property mso.config.path, use the default configuration"); + msoConfigPath = StringUtils.defaultString(asdcConfig.getPropertyOrNull("mso.config.defaultpath")); + } + logger.info("MSO config path is: {}", msoConfigPath); + return msoConfigPath; + } } diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/WorkflowResource.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/WorkflowResource.java index daeda2f976..b634c26cf0 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/WorkflowResource.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/WorkflowResource.java @@ -27,6 +27,7 @@ import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpResponse; import org.onap.sdc.api.notification.IArtifactInfo; import org.onap.so.asdc.installer.VfResourceStructure; @@ -88,7 +89,7 @@ public class WorkflowResource { logger.debug("Response entity: {}", response.getEntity().toString()); if (response.getStatusLine().getStatusCode() != 200) { logger.debug("Failed deploying BPMN {}", bpmnName); - logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), bpmnName, + logger.error(LoggingAnchor.SIX, MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), bpmnName, bpmnName, Integer.toString(response.getStatusLine().getStatusCode()), ErrorCode.DataError.getValue(), "ASDC BPMN deploy failed"); throw (new Exception("Error from Camunda on deploying the BPMN: " + bpmnName)); @@ -97,7 +98,7 @@ public class WorkflowResource { } } catch (Exception e) { logger.debug("Exception :", e); - logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), bpmnName, + logger.error(LoggingAnchor.FIVE, MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), bpmnName, e.getMessage(), ErrorCode.DataError.getValue(), "ASDC BPMN deploy failed"); throw e; } 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 edf8ff338c..d250021d19 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 @@ -38,7 +38,7 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; -import org.hibernate.StaleObjectStateException; +import org.onap.so.logger.LoggingAnchor; import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.LockAcquisitionException; import org.onap.sdc.api.notification.IArtifactInfo; @@ -81,6 +81,7 @@ import org.onap.so.db.catalog.beans.HeatEnvironment; import org.onap.so.db.catalog.beans.HeatFiles; import org.onap.so.db.catalog.beans.HeatTemplate; import org.onap.so.db.catalog.beans.HeatTemplateParam; +import org.onap.so.db.catalog.beans.InstanceGroup; import org.onap.so.db.catalog.beans.InstanceGroupType; import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization; import org.onap.so.db.catalog.beans.NetworkInstanceGroup; @@ -294,6 +295,7 @@ public class ToscaResourceInstaller { status = vfResourceStructure.isDeployedSuccessfully(); } catch (RuntimeException e) { status = false; + logger.debug("Exception :", e); } try { Service existingService = @@ -323,8 +325,8 @@ public class ToscaResourceInstaller { } return status; } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), ErrorCode.SchemaError.getValue(), - "Exception - isResourceAlreadyDeployed"); + logger.error(LoggingAnchor.THREE, MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), + ErrorCode.SchemaError.getValue(), "Exception - isResourceAlreadyDeployed"); throw new ArtifactInstallerException("Exception caught during checking existence of the VNF Resource.", e); } } @@ -394,7 +396,7 @@ public class ToscaResourceInstaller { if (dbExceptionToCapture instanceof ConstraintViolationException || dbExceptionToCapture instanceof LockAcquisitionException) { - logger.warn("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(), + logger.warn(LoggingAnchor.FIVE, MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(), resourceStruct.getResourceInstance().getResourceName(), resourceStruct.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(), "Exception - ASCDC Artifact already deployed", e); @@ -402,7 +404,7 @@ public class ToscaResourceInstaller { String elementToLog = (!artifactListForLogging.isEmpty() ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString() : "No element listed"); - logger.error("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog, + logger.error(LoggingAnchor.FOUR, MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog, ErrorCode.DataError.getValue(), "Exception caught during installation of " + resourceStruct.getResourceInstance().getResourceName() + ". Transaction rollback", e); @@ -431,7 +433,6 @@ public class ToscaResourceInstaller { for (NodeTemplate nodeTemplate : vfNodeTemplatesList) { Metadata metadata = nodeTemplate.getMetaData(); - String serviceType = toscaResourceStruct.getCatalogService().getServiceType(); String vfCustomizationCategory = toscaResourceStruct.getSdcCsarHelper() .getMetadataPropertyValue(metadata, SdcPropertyNames.PROPERTY_NAME_CATEGORY); processVfModules(toscaResourceStruct, vfResourceStructure, service, nodeTemplate, metadata, @@ -474,7 +475,7 @@ public class ToscaResourceInstaller { if (dbExceptionToCapture instanceof ConstraintViolationException || dbExceptionToCapture instanceof LockAcquisitionException) { - logger.warn("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(), + logger.warn(LoggingAnchor.FIVE, MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(), vfResourceStructure.getResourceInstance().getResourceName(), vfResourceStructure.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(), "Exception - ASCDC Artifact already deployed", e); @@ -482,7 +483,7 @@ public class ToscaResourceInstaller { String elementToLog = (!artifactListForLogging.isEmpty() ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString() : "No element listed"); - logger.error("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog, + logger.error(LoggingAnchor.FOUR, MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog, ErrorCode.DataError.getValue(), "Exception caught during installation of " + vfResourceStructure.getResourceInstance().getResourceName() @@ -498,7 +499,7 @@ public class ToscaResourceInstaller { List<NodeTemplate> getRequirementList(List<NodeTemplate> resultList, List<NodeTemplate> nodeTemplates, ISdcCsarHelper iSdcCsarHelper) { - List<NodeTemplate> nodes = new ArrayList<NodeTemplate>(); + List<NodeTemplate> nodes = new ArrayList<>(); nodes.addAll(nodeTemplates); for (NodeTemplate nodeTemplate : nodeTemplates) { @@ -529,12 +530,12 @@ public class ToscaResourceInstaller { // This method retrieve resource sequence from csar file void processResourceSequence(ToscaResourceStructure toscaResourceStructure, Service service) { - List<String> resouceSequence = new ArrayList<String>(); - List<NodeTemplate> resultList = new ArrayList<NodeTemplate>(); + List<String> resouceSequence = new ArrayList<>(); + List<NodeTemplate> resultList = new ArrayList<>(); ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper(); List<NodeTemplate> nodeTemplates = iSdcCsarHelper.getServiceNodeTemplates(); - List<NodeTemplate> nodes = new ArrayList<NodeTemplate>(); + List<NodeTemplate> nodes = new ArrayList<>(); nodes.addAll(nodeTemplates); for (NodeTemplate nodeTemplate : nodeTemplates) { @@ -696,14 +697,13 @@ public class ToscaResourceInstaller { .setModelCustomizationUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); configCustomizationResource.setModelInstanceName(nodeTemplate.getName()); - configCustomizationResource.setNfFunction(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)); - configCustomizationResource.setNfRole(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)); - configCustomizationResource.setNfType(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)); - configCustomizationResource - .setServiceProxyResourceCustomizationUUID(spResourceCustomization.getModelCustomizationUUID()); + configCustomizationResource.setFunction( + toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, "function")); + configCustomizationResource.setRole( + toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, "role")); + configCustomizationResource.setType( + toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, "type")); + configCustomizationResource.setServiceProxyResourceCustomization(spResourceCustomization); configCustomizationResource.setConfigurationResource(configResource); configCustomizationResource.setService(service); @@ -723,9 +723,8 @@ public class ToscaResourceInstaller { List<NodeTemplate> configurationNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION); - List<ServiceProxyResourceCustomization> serviceProxyList = new ArrayList<ServiceProxyResourceCustomization>(); - List<ConfigurationResourceCustomization> configurationResourceList = - new ArrayList<ConfigurationResourceCustomization>(); + List<ServiceProxyResourceCustomization> serviceProxyList = new ArrayList<>(); + List<ConfigurationResourceCustomization> configurationResourceList = new ArrayList<>(); ServiceProxyResourceCustomization serviceProxy = null; @@ -740,8 +739,8 @@ public class ToscaResourceInstaller { toscaResourceStruct.getSdcCsarHelper().getRequirementsOf(configNode).getAll(); for (RequirementAssignment requirement : requirementsList) { if (requirement.getNodeTemplateName().equals(spNode.getName())) { - ConfigurationResourceCustomization configurationResource = - createConfiguration(configNode, toscaResourceStruct, serviceProxy, service); + ConfigurationResourceCustomization configurationResource = createConfiguration(configNode, + toscaResourceStruct, serviceProxy, service, configurationResourceList); Optional<ConfigurationResourceCustomization> matchingObject = configurationResourceList.stream() @@ -978,8 +977,8 @@ public class ToscaResourceInstaller { VnfResourceCustomization vnfResource = createVnfResource(nodeTemplate, toscaResourceStruct, service); - Set<CvnfcCustomization> existingCvnfcSet = new HashSet<CvnfcCustomization>(); - Set<VnfcCustomization> existingVnfcSet = new HashSet<VnfcCustomization>(); + Set<CvnfcCustomization> existingCvnfcSet = new HashSet<>(); + Set<VnfcCustomization> existingVnfcSet = new HashSet<>(); for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()) { @@ -1111,7 +1110,7 @@ public class ToscaResourceInstaller { } } - if (tempGroupList.size() != 0 && tempGroupList.size() < groupList.size()) { + if (!tempGroupList.isEmpty() && tempGroupList.size() < groupList.size()) { getVNFCGroupSequenceList(strSequence, tempGroupList, nodes, iSdcCsarHelper); } } @@ -1157,7 +1156,8 @@ public class ToscaResourceInstaller { break; case ASDCConfiguration.HEAT_NET: case ASDCConfiguration.OTHER: - logger.warn("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_TYPE_NOT_SUPPORT.toString(), + case ASDCConfiguration.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT: + logger.warn(LoggingAnchor.FOUR, MessageEnum.ASDC_ARTIFACT_TYPE_NOT_SUPPORT.toString(), vfModuleArtifact.getArtifactInfo().getArtifactType() + "(Artifact Name:" + vfModuleArtifact.getArtifactInfo().getArtifactName() + ")", ErrorCode.DataError.getValue(), "Artifact type not supported"); @@ -1267,6 +1267,8 @@ public class ToscaResourceInstaller { vfModuleArtifact.getArtifactInfo().getArtifactUUID()); heatTemplate.setParameters(heatParam); vfModuleArtifact.setHeatTemplate(heatTemplate); + } else { + vfModuleArtifact.setHeatTemplate(existingHeatTemplate); } } @@ -1295,6 +1297,8 @@ public class ToscaResourceInstaller { heatEnvironment.setArtifactChecksum(MANUAL_RECORD); } vfModuleArtifact.setHeatEnvironment(heatEnvironment); + } else { + vfModuleArtifact.setHeatEnvironment(existingHeatEnvironment); } } @@ -1319,7 +1323,8 @@ public class ToscaResourceInstaller { heatFile.setArtifactChecksum(MANUAL_RECORD); } vfModuleArtifact.setHeatFiles(heatFile); - + } else { + vfModuleArtifact.setHeatFiles(existingHeatFiles); } } @@ -1350,6 +1355,13 @@ public class ToscaResourceInstaller { service.setModelInvariantUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); service.setCsar(toscaResourceStructure.getCatalogToscaCsar()); + service.setNamingPolicy(serviceMetadata.getValue("namingPolicy")); + String generateNaming = serviceMetadata.getValue("ecompGeneratedNaming"); + Boolean generateNamingValue = null; + if (generateNaming != null) { + generateNamingValue = "true".equalsIgnoreCase(generateNaming); + } + service.setOnapGeneratedNaming(generateNamingValue); } @@ -1394,24 +1406,23 @@ public class ToscaResourceInstaller { protected ConfigurationResourceCustomization createConfiguration(NodeTemplate nodeTemplate, ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization, - Service service) { + Service service, List<ConfigurationResourceCustomization> configurationResourceList) { ConfigurationResourceCustomization configCustomizationResource = getConfigurationResourceCustomization( nodeTemplate, toscaResourceStructure, spResourceCustomization, service); - ConfigurationResource configResource = getConfigurationResource(nodeTemplate); - - Set<ConfigurationResourceCustomization> configResourceCustomizationSet = new HashSet<>(); - - configCustomizationResource.setConfigurationResource(configResource); - - configResourceCustomizationSet.add(configCustomizationResource); + ConfigurationResource configResource = null; - configResource.setConfigurationResourceCustomization(configResourceCustomizationSet); + ConfigurationResource existingConfigResource = findExistingConfiguration(service, + nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID), configurationResourceList); - toscaResourceStructure.setCatalogConfigurationResource(configResource); + if (existingConfigResource == null) { + configResource = getConfigurationResource(nodeTemplate); + } else { + configResource = existingConfigResource; + } - toscaResourceStructure.setCatalogConfigurationResourceCustomization(configCustomizationResource); + configCustomizationResource.setConfigurationResource(configResource); return configCustomizationResource; } @@ -1648,7 +1659,7 @@ public class ToscaResourceInstaller { List<NetworkInstanceGroup> networkInstanceGroupList = new ArrayList<>(); List<CollectionResourceInstanceGroupCustomization> collectionResourceInstanceGroupCustomizationList = - new ArrayList<CollectionResourceInstanceGroupCustomization>(); + new ArrayList<>(); for (Group group : groupList) { @@ -1811,16 +1822,25 @@ public class ToscaResourceInstaller { VnfResourceCustomization vnfResourceCustomization, ToscaResourceStructure toscaResourceStructure) { Metadata instanceMetadata = group.getMetadata(); - // Populate InstanceGroup + + InstanceGroup existingInstanceGroup = + instanceGroupRepo.findByModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + VFCInstanceGroup vfcInstanceGroup = new VFCInstanceGroup(); - vfcInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - vfcInstanceGroup.setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); - vfcInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - vfcInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); - vfcInstanceGroup.setToscaNodeType(group.getType()); - vfcInstanceGroup.setRole("SUB-INTERFACE"); // Set Role - vfcInstanceGroup.setType(InstanceGroupType.VNFC); // Set type + if (existingInstanceGroup == null) { + // Populate InstanceGroup + vfcInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + vfcInstanceGroup + .setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + vfcInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + vfcInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + vfcInstanceGroup.setToscaNodeType(group.getType()); + vfcInstanceGroup.setRole("SUB-INTERFACE"); // Set Role + vfcInstanceGroup.setType(InstanceGroupType.VNFC); // Set type + } else { + vfcInstanceGroup = (VFCInstanceGroup) existingInstanceGroup; + } // Populate VNFCInstanceGroupCustomization VnfcInstanceGroupCustomization vfcInstanceGroupCustom = new VnfcInstanceGroupCustomization(); @@ -1934,10 +1954,9 @@ public class ToscaResourceInstaller { // * Extract VFC's and CVFC's then add them to VFModule // ****************************************************************************************************************** - Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomizations = - new HashSet<CvnfcConfigurationCustomization>(); - Set<CvnfcCustomization> cvnfcCustomizations = new HashSet<CvnfcCustomization>(); - Set<VnfcCustomization> vnfcCustomizations = new HashSet<VnfcCustomization>(); + Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomizations = new HashSet<>(); + Set<CvnfcCustomization> cvnfcCustomizations = new HashSet<>(); + Set<VnfcCustomization> vnfcCustomizations = new HashSet<>(); // Only set the CVNFC if this vfModule group is a member of it. List<NodeTemplate> groupMembers = @@ -2145,6 +2164,19 @@ public class ToscaResourceInstaller { return configResource; } + protected ConfigurationResource findExistingConfiguration(Service service, String modelUUID, + List<ConfigurationResourceCustomization> configurationResourceList) { + ConfigurationResource configResource = null; + for (ConfigurationResourceCustomization configurationResourceCustom : configurationResourceList) { + if (configurationResourceCustom.getConfigurationResource() != null + && configurationResourceCustom.getConfigurationResource().getModelUUID().equals(modelUUID)) { + configResource = configurationResourceCustom.getConfigurationResource(); + } + } + + return configResource; + } + protected VfModuleCustomization findExistingVfModuleCustomization(VnfResourceCustomization vnfResource, String vfModuleModelCustomizationUUID) { VfModuleCustomization vfModuleCustomization = null; @@ -2253,14 +2285,14 @@ public class ToscaResourceInstaller { if (matchingObject.isPresent()) { List<HeatFiles> heatFilesList = new ArrayList<>(); - List<HeatTemplate> volumeHeatChildTemplates = new ArrayList<HeatTemplate>(); - List<HeatTemplate> heatChildTemplates = new ArrayList<HeatTemplate>(); + List<HeatTemplate> volumeHeatChildTemplates = new ArrayList<>(); + List<HeatTemplate> heatChildTemplates = new ArrayList<>(); HeatTemplate parentHeatTemplate = new HeatTemplate(); String parentArtifactType = null; Set<String> artifacts = new HashSet<>(matchingObject.get().getVfModuleMetadata().getArtifacts()); for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { - List<HeatTemplate> childNestedHeatTemplates = new ArrayList<HeatTemplate>(); + List<HeatTemplate> childNestedHeatTemplates = new ArrayList<>(); if (artifacts.contains(vfModuleArtifact.getArtifactInfo().getArtifactUUID())) { checkVfModuleArtifactType(vfModule, vfModuleCustomization, heatFilesList, vfModuleArtifact, @@ -2577,7 +2609,7 @@ public class ToscaResourceInstaller { if (object == null) { return null; - } else if (object.equals("NULL")) { + } else if ("NULL".equals(object)) { return null; } else if (object instanceof Integer) { return object.toString(); @@ -2649,7 +2681,7 @@ public class ToscaResourceInstaller { // existing customization available in db. private void addVnfCustomization(Service service, VnfResourceCustomization vnfResourceCustomization) { List<Service> services = serviceRepo.findByModelUUID(service.getModelUUID()); - if (services.size() > 0) { + if (!services.isEmpty()) { // service exist in db Service existingService = services.get(0); List<VnfResourceCustomization> vnfCustomizations = existingService.getVnfCustomizations(); diff --git a/asdc-controller/src/test/java/org/onap/asdc/activity/ActivitySpecsActionsTest.java b/asdc-controller/src/test/java/org/onap/asdc/activity/ActivitySpecsActionsTest.java index 438120924a..7de35b5c13 100644 --- a/asdc-controller/src/test/java/org/onap/asdc/activity/ActivitySpecsActionsTest.java +++ b/asdc-controller/src/test/java/org/onap/asdc/activity/ActivitySpecsActionsTest.java @@ -56,6 +56,44 @@ public class ActivitySpecsActionsTest extends BaseTest { } @Test + public void CreateActivitySpecReturnsCreated_Test() throws Exception { + String HOSTNAME = createURLWithPort(""); + + ActivitySpec activitySpec = new ActivitySpec(); + activitySpec.setName("testActivitySpec"); + activitySpec.setDescription("Test Activity Spec"); + ActivitySpecCreateResponse activitySpecCreateResponse = new ActivitySpecCreateResponse(); + activitySpecCreateResponse.setId("testActivityId"); + ObjectMapper mapper = new ObjectMapper(); + String body = mapper.writeValueAsString(activitySpecCreateResponse); + wireMockServer.stubFor(post(urlPathMatching("/v1.0/activity-spec")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(org.springframework.http.HttpStatus.CREATED.value()).withBody(body))); + + String activitySpecId = activitySpecsActions.createActivitySpec(HOSTNAME, activitySpec); + assertEquals("testActivityId", activitySpecId); + } + + @Test + public void CreateActivitySpecReturnsExists_Test() throws Exception { + String HOSTNAME = createURLWithPort(""); + + ActivitySpec activitySpec = new ActivitySpec(); + activitySpec.setName("testActivitySpec"); + activitySpec.setDescription("Test Activity Spec"); + ActivitySpecCreateResponse activitySpecCreateResponse = new ActivitySpecCreateResponse(); + activitySpecCreateResponse.setId("testActivityId"); + ObjectMapper mapper = new ObjectMapper(); + String body = mapper.writeValueAsString(activitySpecCreateResponse); + wireMockServer.stubFor(post(urlPathMatching("/v1.0/activity-spec")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY.value()).withBody(body))); + + String activitySpecId = activitySpecsActions.createActivitySpec(HOSTNAME, activitySpec); + assertEquals(null, activitySpecId); + } + + @Test public void CertifyActivitySpec_Test() throws Exception { String HOSTNAME = createURLWithPort(""); @@ -70,6 +108,21 @@ public class ActivitySpecsActionsTest extends BaseTest { assertTrue(certificationResult); } + @Test + public void CertifyActivitySpecReturnsExists_Test() throws Exception { + String HOSTNAME = createURLWithPort(""); + + String activitySpecId = "testActivitySpec"; + String urlPath = "/v1.0/activity-spec/testActivitySpec/versions/latest/actions"; + + wireMockServer.stubFor( + put(urlPathMatching(urlPath)).willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY.value()))); + + boolean certificationResult = activitySpecsActions.certifyActivitySpec(HOSTNAME, activitySpecId); + assertFalse(certificationResult); + } + private String createURLWithPort(String uri) { return "http://localhost:" + wireMockPort + uri; } diff --git a/asdc-controller/src/test/java/org/onap/asdc/activity/DeployActivitySpecsITTest.java b/asdc-controller/src/test/java/org/onap/asdc/activity/DeployActivitySpecsITTest.java new file mode 100644 index 0000000000..81977da278 --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/asdc/activity/DeployActivitySpecsITTest.java @@ -0,0 +1,76 @@ +/*- + * ============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.asdc.activity; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.put; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; +import org.junit.Test; +import org.mockito.Mock; +import org.onap.so.asdc.BaseTest; +import org.onap.so.asdc.activity.DeployActivitySpecs; +import org.onap.so.asdc.activity.beans.ActivitySpecCreateResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpHeaders; +import com.fasterxml.jackson.databind.ObjectMapper; +import javax.ws.rs.core.MediaType; + +public class DeployActivitySpecsITTest extends BaseTest { + @Mock + protected Environment env; + + @Value("${wiremock.server.port}") + private String wiremockPort; + + @Autowired + private DeployActivitySpecs deployActivitySpecs; + + @Test + public void deployActivitySpecsIT_Test() throws Exception { + ActivitySpecCreateResponse activitySpecCreateResponse = new ActivitySpecCreateResponse(); + activitySpecCreateResponse.setId("testActivityId"); + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + + ObjectMapper mapper = new ObjectMapper(); + String body = mapper.writeValueAsString(activitySpecCreateResponse); + + wireMockServer.stubFor(post(urlPathMatching("/v1.0/activity-spec")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(org.springframework.http.HttpStatus.OK.value()).withBody(body))); + + when(env.getProperty("mso.asdc.config.activity.endpoint")).thenReturn("http://localhost:8090"); + + String urlPath = "/v1.0/activity-spec/testActivityId/versions/latest/actions"; + + wireMockServer.stubFor( + put(urlPathMatching(urlPath)).willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(org.springframework.http.HttpStatus.OK.value()))); + + deployActivitySpecs.deployActivities(); + assertTrue(activitySpecCreateResponse.getId().equals("testActivityId")); + } +} diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/ASDCRestInterfaceTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/ASDCRestInterfaceTest.java index ac107f6449..2c520a3bba 100644 --- a/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/ASDCRestInterfaceTest.java +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/test/rest/ASDCRestInterfaceTest.java @@ -27,11 +27,15 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; 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.assertNull; +import static org.junit.Assert.assertTrue; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashSet; +import java.util.List; +import java.util.Optional; import java.util.Set; import javax.transaction.Transactional; import javax.ws.rs.core.Response; @@ -45,11 +49,15 @@ import org.onap.so.asdc.client.test.emulators.DistributionClientEmulator; import org.onap.so.asdc.client.test.emulators.NotificationDataImpl; import org.onap.so.db.catalog.beans.AllottedResource; import org.onap.so.db.catalog.beans.AllottedResourceCustomization; +import org.onap.so.db.catalog.beans.NetworkResource; +import org.onap.so.db.catalog.beans.NetworkResourceCustomization; import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.catalog.beans.ToscaCsar; import org.onap.so.db.catalog.beans.Workflow; import org.onap.so.db.catalog.data.repository.AllottedResourceRepository; import org.onap.so.db.catalog.data.repository.NetworkResourceRepository; import org.onap.so.db.catalog.data.repository.ServiceRepository; +import org.onap.so.db.catalog.data.repository.ToscaCsarRepository; import org.onap.so.db.catalog.data.repository.WorkflowRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.web.client.TestRestTemplate; @@ -75,6 +83,9 @@ public class ASDCRestInterfaceTest extends BaseTest { private WorkflowRepository workflowRepo; @Autowired + private ToscaCsarRepository toscaCsarRepo; + + @Autowired private ASDCRestInterface asdcRestInterface; private TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); @@ -244,6 +255,41 @@ public class ASDCRestInterfaceTest extends BaseTest { } + + @Test + public void test_Vcpe_Infra_Distribution() throws Exception { + wireMockServer.stubFor(post(urlPathMatching("/aai/.*")) + .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json"))); + + wireMockServer.stubFor(post(urlPathMatching("/v1.0/activity-spec")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(org.springframework.http.HttpStatus.ACCEPTED.value()))); + + String resourceLocation = "src/test/resources/resource-examples/vcpe-infra/"; + + ObjectMapper mapper = new ObjectMapper(); + NotificationDataImpl request = mapper.readValue(new File(resourceLocation + "demovcpeinfra-notification.json"), + NotificationDataImpl.class); + headers.add("resource-location", resourceLocation); + HttpEntity<NotificationDataImpl> entity = new HttpEntity<NotificationDataImpl>(request, headers); + + ResponseEntity<String> response = restTemplate.exchange(createURLWithPort("test/treatNotification/v1"), + HttpMethod.POST, entity, String.class); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + + Optional<ToscaCsar> toscaCsar = toscaCsarRepo.findById("144606d8-a505-4ba0-90a9-6d1c6219fc6b"); + assertTrue(toscaCsar.isPresent()); + assertEquals("service-Demovcpeinfra-csar.csar", toscaCsar.get().getName()); + + Optional<Service> service = serviceRepo.findById("8a77cbbb-9850-40bb-a42f-7aec8e3e6ab7"); + assertTrue(service.isPresent()); + assertEquals("demoVCPEInfra", service.get().getModelName()); + + Optional<NetworkResource> networkResource = networkRepo.findById("89789b26-a46b-4cee-aed0-d46e21f93a5e"); + assertTrue(networkResource.isPresent()); + assertEquals("Generic NeutronNet", networkResource.get().getModelName()); + } + protected String createURLWithPort(String uri) { return "http://localhost:" + port + uri; } diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java index dd107f7775..bd8e877369 100644 --- a/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java +++ b/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java @@ -34,6 +34,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import org.hibernate.exception.LockAcquisitionException; import org.junit.Before; import org.junit.Rule; @@ -42,6 +43,7 @@ import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; import org.onap.sdc.api.notification.IResourceInstance; import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; import org.onap.sdc.tosca.parser.impl.SdcCsarHelperImpl; @@ -56,6 +58,7 @@ import org.onap.so.asdc.client.exceptions.ArtifactInstallerException; import org.onap.so.asdc.client.test.emulators.ArtifactInfoImpl; import org.onap.so.asdc.client.test.emulators.JsonStatusData; import org.onap.so.asdc.client.test.emulators.NotificationDataImpl; +import org.onap.so.asdc.installer.ResourceStructure; import org.onap.so.asdc.installer.ToscaResourceStructure; import org.onap.so.db.catalog.beans.ConfigurationResource; import org.onap.so.db.catalog.beans.ConfigurationResourceCustomization; @@ -340,7 +343,59 @@ public class ToscaResourceInstallerTest extends BaseTest { return actualWatchdogComponentDistributionStatus; } - + @Test + public void createServiceTest() { + ToscaResourceStructure toscaResourceStructure = mock(ToscaResourceStructure.class); + ResourceStructure resourceStructure = mock(ResourceStructure.class); + Metadata metadata = mock(Metadata.class); + INotificationData notification = mock(INotificationData.class); + + doReturn("e2899e5c-ae35-434c-bada-0fabb7c1b44d").when(toscaResourceStructure).getServiceVersion(); + doReturn(metadata).when(toscaResourceStructure).getServiceMetadata(); + doReturn("production").when(notification).getWorkloadContext(); + doReturn(notification).when(resourceStructure).getNotification(); + + String serviceType = "test-type"; + String serviceRole = "test-role"; + String category = "Network L4+"; + String description = "Customer Orderable service description"; + String name = "Customer Orderable Service"; + String uuid = "72db5868-4575-4804-b546-0b0d3c3b5ac6"; + String invariantUUID = "6f30bbe3-4590-4185-a7e0-4f9610926c6f"; + String namingPolicy = "naming Policy"; + String ecompGeneratedNaming = "true"; + String environmentContext = "General_Revenue-Bearing"; + + doReturn(serviceType).when(metadata).getValue("serviceType"); + doReturn(serviceRole).when(metadata).getValue("serviceRole"); + + doReturn(category).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY); + doReturn(description).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION); + + doReturn(name).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_NAME); + + doReturn(uuid).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_UUID); + + doReturn(environmentContext).when(metadata).getValue(metadata.getValue("environmentContext")); + doReturn(invariantUUID).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID); + doReturn(namingPolicy).when(metadata).getValue("namingPolicy"); + doReturn(ecompGeneratedNaming).when(metadata).getValue("ecompGeneratedNaming"); + + Service service = toscaInstaller.createService(toscaResourceStructure, resourceStructure); + + assertNotNull(service); + + verify(toscaResourceStructure, times(2)).getServiceVersion(); + assertNotNull(service.getNamingPolicy()); + assertEquals(serviceType, service.getServiceType()); + assertEquals(serviceRole, service.getServiceRole()); + assertEquals(category, service.getCategory()); + assertEquals(description, service.getDescription()); + assertEquals(uuid, service.getModelUUID()); + assertEquals(invariantUUID, service.getModelInvariantUUID()); + assertEquals(namingPolicy, service.getNamingPolicy()); + assertTrue(service.getOnapGeneratedNaming()); + } private void prepareConfigurationResource() { doReturn(metadata).when(nodeTemplate).getMetaData(); @@ -396,7 +451,7 @@ public class ToscaResourceInstallerTest extends BaseTest { assertNotNull(configurationResourceCustomization); assertNotNull(configurationResourceCustomization.getConfigurationResource()); assertEquals(MockConstants.MODEL_CUSTOMIZATIONUUID, - configurationResourceCustomization.getServiceProxyResourceCustomizationUUID()); + configurationResourceCustomization.getServiceProxyResourceCustomization().getModelCustomizationUUID()); } @Test diff --git a/asdc-controller/src/test/resources/data.sql b/asdc-controller/src/test/resources/data.sql index 47e6c4c982..bc97b1e54a 100644 --- a/asdc-controller/src/test/resources/data.sql +++ b/asdc-controller/src/test/resources/data.sql @@ -21,12 +21,14 @@ INSERT INTO temp_network_heat_template_lookup(NETWORK_RESOURCE_MODEL_NAME, HEAT_ ('TENANT_OAM_NETWORK', 'ff874603-4222-11e7-9252-005056850d2e', '3.0', NULL); INSERT INTO temp_network_heat_template_lookup(NETWORK_RESOURCE_MODEL_NAME, HEAT_TEMPLATE_ARTIFACT_UUID, AIC_VERSION_MIN, AIC_VERSION_MAX) VALUES ('SRIOV_PROVIDER_NETWORK', 'ff874603-4222-11e7-9252-005056850d2e', '3.0', NULL); +INSERT INTO temp_network_heat_template_lookup(NETWORK_RESOURCE_MODEL_NAME, HEAT_TEMPLATE_ARTIFACT_UUID, AIC_VERSION_MIN, AIC_VERSION_MAX) VALUES +('Generic NeutronNet', 'ff874603-4222-11e7-9252-005056850d2e', '3.0', NULL); insert into vnf_resource(orchestration_mode, description, creation_timestamp, model_uuid, aic_version_min, aic_version_max, model_invariant_uuid, model_version, model_name, tosca_node_type, heat_template_artifact_uuid) values ('HEAT', '1607 vSAMP10a - inherent network', '2017-04-14 21:46:28', 'ff2ae348-214a-11e7-93ae-92361f002671', '', '', '2fff5b20-214b-11e7-93ae-92361f002671', '1.0', 'vSAMP10a', 'VF', null); insert into workflow(artifact_uuid, artifact_name, name, operation_name, version, description, body, resource_target, source) values -('5b0c4322-643d-4c9f-b184-4516049e99b1', 'testingWorkflow', 'testingWorkflow', 'create', 1, 'Test Workflow', null, 'vnf', 'sdc'); +('5b0c4322-643d-4c9f-b184-4516049e99b1', 'testingWorkflow.bpmn', 'testingWorkflow', 'create', 1, 'Test Workflow', null, 'vnf', 'sdc'); insert into vnf_resource_to_workflow(vnf_resource_model_uuid, workflow_id) values ('ff2ae348-214a-11e7-93ae-92361f002671', '1'); diff --git a/asdc-controller/src/test/resources/resource-examples/vFW/service-Vfw.csar b/asdc-controller/src/test/resources/resource-examples/vFW/service-Vfw.csar Binary files differindex 260ff86916..9803d9cd2d 100644 --- a/asdc-controller/src/test/resources/resource-examples/vFW/service-Vfw.csar +++ b/asdc-controller/src/test/resources/resource-examples/vFW/service-Vfw.csar diff --git a/asdc-controller/src/test/resources/resource-examples/vcpe-infra/base_vcpe_infra.env b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/base_vcpe_infra.env new file mode 100644 index 0000000000..85d3ea19a3 --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/base_vcpe_infra.env @@ -0,0 +1,37 @@ +parameters: + cloud_env: "PUT THE CLOUD PROVIDED HERE (openstack or rackspace)" + cpe_public_net_cidr: "10.2.0.0/24" + cpe_public_net_id: "zdfw1cpe01_public" + cpe_public_subnet_id: "zdfw1cpe01_sub_public" + cpe_signal_net_cidr: "10.4.0.0/24" + cpe_signal_net_id: "zdfw1cpe01_private" + cpe_signal_subnet_id: "zdfw1cpe01_sub_private" + dcae_collector_ip: "10.0.4.1" + dcae_collector_port: "8081" + demo_artifacts_version: "1.4.0" + install_script_version: "1.4.0" + key_name: "vaaa_key" + mr_ip_addr: "10.0.11.1" + mr_ip_port: "3904" + nexus_artifact_repo: "https://nexus.onap.org" + onap_private_net_cidr: "10.0.0.0/16" + onap_private_net_id: "PUT THE ONAP PRIVATE NETWORK NAME HERE" + onap_private_subnet_id: "PUT THE ONAP PRIVATE SUBNETWORK NAME HERE" + pub_key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDQXYJYYi3/OUZXUiCYWdtc7K0m5C0dJKVxPG0eI8EWZrEHYdfYe6WoTSDJCww+1qlBSpA5ac/Ba4Wn9vh+lR1vtUKkyIC/nrYb90ReUd385Glkgzrfh5HdR5y5S2cL/Frh86lAn9r6b3iWTJD8wBwXFyoe1S2nMTOIuG4RPNvfmyCTYVh8XTCCE8HPvh3xv2r4egawG1P4Q4UDwk+hDBXThY2KS8M5/8EMyxHV0ImpLbpYCTBA6KYDIRtqmgS6iKyy8v2D1aSY5mc9J0T5t9S2Gv+VZQNWQDDKNFnxqYaAo1uEoq/i1q63XC5AD3ckXb2VT6dp23BQMdDfbHyUWfJN" + public_net_id: "PUT THE PUBLIC NETWORK ID HERE" + vaaa_name_0: "zdcpe1cpe01aaa01" + vaaa_private_ip_0: "10.4.0.4" + vaaa_private_ip_1: "10.0.101.2" + vcpe_flavor_name: "PUT THE FLAVOR NAME HERE (MEDIUM FLAVOR SUGGESTED)" + vcpe_image_name: "PUT THE IMAGE NAME HERE (Ubuntu 1604 SUGGESTED)" + vdhcp_name_0: "zdcpe1cpe01dhcp01" + vdhcp_private_ip_0: "10.4.0.1" + vdhcp_private_ip_1: "10.0.101.1" + vdns_name_0: "zdcpe1cpe01dns01" + vdns_private_ip_0: "10.2.0.1" + vdns_private_ip_1: "10.0.101.3" + vf_module_id: "vCPE_Intrastructure" + vnf_id: "vCPE_Infrastructure_demo_app" + vweb_name_0: "zdcpe1cpe01web01" + vweb_private_ip_0: "10.2.0.10" + vweb_private_ip_1: "10.0.101.40" diff --git a/asdc-controller/src/test/resources/resource-examples/vcpe-infra/base_vcpe_infra.yaml b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/base_vcpe_infra.yaml new file mode 100644 index 0000000000..9f3bf27492 --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/base_vcpe_infra.yaml @@ -0,0 +1,460 @@ +########################################################################## +# +#==================LICENSE_START========================================== +# +# +# Copyright 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============================================ +# +# ECOMP is a trademark and service mark of AT&T Intellectual Property. +# +########################################################################## + +heat_template_version: 2013-05-23 + +description: Heat template to deploy vCPE Infrastructue emlements (vAAA, vDHCP, vDNS_DHCP, webServer) + +############## +# # +# PARAMETERS # +# # +############## + +parameters: + vcpe_image_name: + type: string + label: Image name or ID + description: Image to be used for compute instance + vcpe_flavor_name: + type: string + label: Flavor + description: Type of instance (flavor) to be used + public_net_id: + type: string + label: Public network name or ID + description: Public network that enables remote connection to VNF + onap_private_net_id: + type: string + label: ONAP management network name or ID + description: Private network that connects ONAP components and the VNF + onap_private_subnet_id: + type: string + label: ONAP management sub-network name or ID + description: Private sub-network that connects ONAP components and the VNF + onap_private_net_cidr: + type: string + label: ONAP private network CIDR + description: The CIDR of the protected private network + cpe_signal_net_id: + type: string + label: vAAA private network name or ID + description: Private network that connects vAAA with vDNSs + cpe_signal_subnet_id: + type: string + label: CPE Signal subnet + description: CPE Signal subnet + cpe_signal_net_cidr: + type: string + label: vAAA private network CIDR + description: The CIDR of the vAAA private network + cpe_public_net_id: + type: string + label: vCPE Public network (emulates internet) name or ID + description: Private network that connects vGW to emulated internet + cpe_public_subnet_id: + type: string + label: CPE Public subnet + description: CPE Public subnet + cpe_public_net_cidr: + type: string + label: vCPE public network CIDR + description: The CIDR of the vCPE public + vaaa_private_ip_0: + type: string + label: vAAA private IP address towards the CPE_SIGNAL private network + description: Private IP address that is assigned to the vAAA to communicate with the vCPE components + vaaa_private_ip_1: + type: string + label: vAAA private IP address towards the ONAP management network + description: Private IP address that is assigned to the vAAA to communicate with ONAP components + vdns_private_ip_0: + type: string + label: vDNS private IP address towards the CPE_PUBLIC private network + description: Private IP address that is assigned to the vDNS to communicate with the vCPE components + vdns_private_ip_1: + type: string + label: vDNS private IP address towards the ONAP management network + description: Private IP address that is assigned to the vDNS to communicate with ONAP components + vdhcp_private_ip_0: + type: string + label: vDHCP private IP address towards the CPE_SIGNAL private network + description: Private IP address that is assigned to the vDHCP to communicate with the vCPE components + vdhcp_private_ip_1: + type: string + label: vDNS private IP address towards the ONAP management network + description: Private IP address that is assigned to the vDHCP to communicate with ONAP components + vweb_private_ip_0: + type: string + label: vWEB private IP address towards the CPE_PUBLIC private network + description: Private IP address that is assigned to the vWEB to communicate with the vGWs + vweb_private_ip_1: + type: string + label: vWEB private IP address towards the ONAP management network + description: Private IP address that is assigned to the vWEB to communicate with ONAP components + vaaa_name_0: + type: string + label: vAAA name + description: Name of the vAAA + vdns_name_0: + type: string + label: vDNS name + description: Name of the vDNS + vdhcp_name_0: + type: string + label: vDHCP name + description: Name of the vDHCP + vweb_name_0: + type: string + label: vWEB name + description: Name of the vWEB + vnf_id: + type: string + label: VNF ID + description: The VNF ID is provided by ONAP + vf_module_id: + type: string + label: vFirewall module ID + description: The vAAA Module ID is provided by ONAP + dcae_collector_ip: + type: string + label: DCAE collector IP address + description: IP address of the DCAE collector + dcae_collector_port: + type: string + label: DCAE collector port + description: Port of the DCAE collector + mr_ip_addr: + type: string + label: Message Router IP address + description: IP address of the Message Router that for vDHCP configuration + mr_ip_port: + type: string + label: Message Router Port + description: IP port of the Message Router that for vDHCP configuration + key_name: + type: string + label: Key pair name + description: Public/Private key pair name + pub_key: + type: string + label: Public key + description: Public key to be installed on the compute instance + install_script_version: + type: string + label: Installation script version number + description: Version number of the scripts that install the vFW demo app + demo_artifacts_version: + type: string + label: Artifacts version used in demo vnfs + description: Artifacts (jar, tar.gz) version used in demo vnfs + nexus_artifact_repo: + type: string + description: Root URL for the Nexus repository for Maven artifacts. + default: "https://nexus.onap.org" + cloud_env: + type: string + label: Cloud environment + description: Cloud environment (e.g., openstack, rackspace) + +############# +# # +# RESOURCES # +# # +############# + +resources: + + random-str: + type: OS::Heat::RandomString + properties: + length: 4 + + my_keypair: + type: OS::Nova::KeyPair + properties: + name: + str_replace: + template: base_rand + params: + base: { get_param: key_name } + rand: { get_resource: random-str } + public_key: { get_param: pub_key } + save_private_key: false + + + # Virtual AAA server Instantiation + vaaa_private_0_port: + type: OS::Neutron::Port + properties: + network: { get_param: cpe_signal_net_id } + fixed_ips: [{"subnet": { get_param: cpe_signal_subnet_id }, "ip_address": { get_param: vaaa_private_ip_0 }}] + + vaaa_private_1_port: + type: OS::Neutron::Port + properties: + network: { get_param: onap_private_net_id } + fixed_ips: [{"subnet": { get_param: onap_private_subnet_id }, "ip_address": { get_param: vaaa_private_ip_1 }}] + + vaaa_0: + type: OS::Nova::Server + properties: + image: { get_param: vcpe_image_name } + flavor: { get_param: vcpe_flavor_name } + name: { get_param: vaaa_name_0 } + key_name: { get_resource: my_keypair } + networks: + - network: { get_param: public_net_id } + - port: { get_resource: vaaa_private_0_port } + - port: { get_resource: vaaa_private_1_port } + metadata: {vnf_id: { get_param: vnf_id }, vf_module_id: { get_param: vf_module_id }} + user_data_format: RAW + user_data: + str_replace: + params: + __dcae_collector_ip__: { get_param: dcae_collector_ip } + __dcae_collector_port__: { get_param: dcae_collector_port } + __cpe_signal_net_ipaddr__: { get_param: vaaa_private_ip_0 } + __oam_ipaddr__: { get_param: vaaa_private_ip_1 } + __oam_cidr__: { get_param: onap_private_net_cidr } + __cpe_signal_net_cidr__: { get_param: cpe_signal_net_cidr } + __demo_artifacts_version__ : { get_param: demo_artifacts_version } + __install_script_version__ : { get_param: install_script_version } + __cloud_env__ : { get_param: cloud_env } + __nexus_artifact_repo__: { get_param: nexus_artifact_repo } + template: | + #!/bin/bash + + # Create configuration files + mkdir /opt/config + echo "__dcae_collector_ip__" > /opt/config/dcae_collector_ip.txt + echo "__dcae_collector_port__" > /opt/config/dcae_collector_port.txt + echo "__cpe_signal_net_ipaddr__" > /opt/config/cpe_signal_net_ipaddr.txt + echo "__oam_ipaddr__" > /opt/config/oam_ipaddr.txt + echo "__oam_cidr__" > /opt/config/oam_cidr.txt + echo "__cpe_signal_net_cidr__" > /opt/config/cpe_signal_net_cidr.txt + echo "__demo_artifacts_version__" > /opt/config/demo_artifacts_version.txt + echo "__install_script_version__" > /opt/config/install_script_version.txt + echo "__cloud_env__" > /opt/config/cloud_env.txt + echo "__nexus_artifact_repo__" > /opt/config/nexus_artifact_repo.txt + + # Download and run install script + apt-get update + apt-get -y install unzip + if [[ "__install_script_version__" =~ "SNAPSHOT" ]]; then REPO=snapshots; else REPO=releases; fi + curl -k -L "__nexus_artifact_repo__/service/local/artifact/maven/redirect?r=${REPO}&g=org.onap.demo.vnf.vcpe&a=vcpe-scripts&e=zip&v=__install_script_version__" -o /opt/vcpe-scripts-__install_script_version__.zip + unzip -j /opt/vcpe-scripts-__install_script_version__.zip -d /opt v_aaa_install.sh + cd /opt + chmod +x v_aaa_install.sh + ./v_aaa_install.sh + + + # Virtual DNS Instantiation + vdns_private_0_port: + type: OS::Neutron::Port + properties: + network: { get_param: cpe_public_net_id } + fixed_ips: [{"subnet": { get_param: cpe_public_subnet_id }, "ip_address": { get_param: vdns_private_ip_0 }}] + + vdns_private_1_port: + type: OS::Neutron::Port + properties: + network: { get_param: onap_private_net_id } + fixed_ips: [{"subnet": { get_param: onap_private_subnet_id }, "ip_address": { get_param: vdns_private_ip_1 }}] + + vdns_0: + type: OS::Nova::Server + properties: + image: { get_param: vcpe_image_name } + flavor: { get_param: vcpe_flavor_name } + name: { get_param: vdns_name_0 } + key_name: { get_resource: my_keypair } + networks: + - network: { get_param: public_net_id } + - port: { get_resource: vdns_private_0_port } + - port: { get_resource: vdns_private_1_port } + metadata: {vnf_id: { get_param: vnf_id }, vf_module_id: { get_param: vf_module_id }} + user_data_format: RAW + user_data: + str_replace: + params: + __oam_ipaddr__ : { get_param: vdns_private_ip_1 } + __cpe_public_net_ipaddr__: { get_param: vdns_private_ip_0 } + __oam_cidr__: { get_param: onap_private_net_cidr } + __cpe_public_net_cidr__: { get_param: cpe_public_net_cidr } + __demo_artifacts_version__ : { get_param: demo_artifacts_version } + __install_script_version__ : { get_param: install_script_version } + __cloud_env__ : { get_param: cloud_env } + __nexus_artifact_repo__: { get_param: nexus_artifact_repo } + template: | + #!/bin/bash + + # Create configuration files + mkdir /opt/config + echo "__oam_ipaddr__" > /opt/config/oam_ipaddr.txt + echo "__cpe_public_net_ipaddr__" > /opt/config/cpe_public_net_ipaddr.txt + echo "__oam_cidr__" > /opt/config/oam_cidr.txt + echo "__cpe_public_net_cidr__" > /opt/config/cpe_public_net_cidr.txt + echo "__demo_artifacts_version__" > /opt/config/demo_artifacts_version.txt + echo "__install_script_version__" > /opt/config/install_script_version.txt + echo "__cloud_env__" > /opt/config/cloud_env.txt + echo "__nexus_artifact_repo__" > /opt/config/nexus_artifact_repo.txt + + # Download and run install script + apt-get update + apt-get -y install unzip + if [[ "__install_script_version__" =~ "SNAPSHOT" ]]; then REPO=snapshots; else REPO=releases; fi + curl -k -L "__nexus_artifact_repo__/service/local/artifact/maven/redirect?r=${REPO}&g=org.onap.demo.vnf.vcpe&a=vcpe-scripts&e=zip&v=__install_script_version__" -o /opt/vcpe-scripts-__install_script_version__.zip + unzip -j /opt/vcpe-scripts-__install_script_version__.zip -d /opt v_dns_install.sh + cd /opt + chmod +x v_dns_install.sh + ./v_dns_install.sh + + + # Virtual DHCP Instantiation + vdhcp_private_0_port: + type: OS::Neutron::Port + properties: + network: { get_param: cpe_signal_net_id } + fixed_ips: [{"subnet": { get_param: cpe_signal_subnet_id }, "ip_address": { get_param: vdhcp_private_ip_0 }}] + + vdhcp_private_1_port: + type: OS::Neutron::Port + properties: + network: { get_param: onap_private_net_id } + fixed_ips: [{"subnet": { get_param: onap_private_subnet_id }, "ip_address": { get_param: vdhcp_private_ip_1 }}] + + vdhcp_0: + type: OS::Nova::Server + properties: + image: { get_param: vcpe_image_name } + flavor: { get_param: vcpe_flavor_name } + name: { get_param: vdhcp_name_0 } + key_name: { get_resource: my_keypair } + networks: + - network: { get_param: public_net_id } + - port: { get_resource: vdhcp_private_0_port } + - port: { get_resource: vdhcp_private_1_port } + metadata: {vnf_id: { get_param: vnf_id }, vf_module_id: { get_param: vf_module_id }} + user_data_format: RAW + user_data: + str_replace: + params: + __oam_ipaddr__ : { get_param: vdhcp_private_ip_1 } + __cpe_signal_ipaddr__ : { get_param: vdhcp_private_ip_0 } + __oam_cidr__ : { get_param: onap_private_net_cidr } + __cpe_signal_net_cidr__ : { get_param: cpe_signal_net_cidr } + __mr_ip_addr__ : { get_param: mr_ip_addr } + __mr_ip_port__ : { get_param: mr_ip_port } + __demo_artifacts_version__ : { get_param: demo_artifacts_version } + __install_script_version__ : { get_param: install_script_version } + __cloud_env__ : { get_param: cloud_env } + __nexus_artifact_repo__: { get_param: nexus_artifact_repo } + template: | + #!/bin/bash + + # Create configuration files + mkdir /opt/config + echo "__oam_ipaddr__" > /opt/config/oam_ipaddr.txt + echo "__cpe_signal_ipaddr__" > /opt/config/cpe_signal_ipaddr.txt + echo "__oam_cidr__" > /opt/config/oam_cidr.txt + echo "__cpe_signal_net_cidr__" > /opt/config/cpe_signal_net_cidr.txt + echo "__mr_ip_addr__" > /opt/config/mr_ip_addr.txt + echo "__mr_ip_port__" > /opt/config/mr_ip_port.txt + echo "__demo_artifacts_version__" > /opt/config/demo_artifacts_version.txt + echo "__install_script_version__" > /opt/config/install_script_version.txt + echo "__cloud_env__" > /opt/config/cloud_env.txt + echo "__nexus_artifact_repo__" > /opt/config/nexus_artifact_repo.txt + + # Download and run install script + apt-get update + apt-get -y install unzip + if [[ "__install_script_version__" =~ "SNAPSHOT" ]]; then REPO=snapshots; else REPO=releases; fi + curl -k -L "__nexus_artifact_repo__/service/local/artifact/maven/redirect?r=${REPO}&g=org.onap.demo.vnf.vcpe&a=vcpe-scripts&e=zip&v=__install_script_version__" -o /opt/vcpe-scripts-__install_script_version__.zip + unzip -j /opt/vcpe-scripts-__install_script_version__.zip -d /opt v_dhcp_install.sh + cd /opt + chmod +x v_dhcp_install.sh + ./v_dhcp_install.sh + + # vWEB instantiaion + vweb_private_0_port: + type: OS::Neutron::Port + properties: + network: { get_param: cpe_public_net_id } + fixed_ips: [{"subnet": { get_param: cpe_public_subnet_id }, "ip_address": { get_param: vweb_private_ip_0 }}] + + vweb_private_1_port: + type: OS::Neutron::Port + properties: + network: { get_param: onap_private_net_id } + fixed_ips: [{"subnet": { get_param: onap_private_subnet_id }, "ip_address": { get_param: vweb_private_ip_1 }}] + + + vweb_0: + type: OS::Nova::Server + properties: + image: { get_param: vcpe_image_name } + flavor: { get_param: vcpe_flavor_name } + name: { get_param: vweb_name_0 } + key_name: { get_resource: my_keypair } + networks: + - network: { get_param: public_net_id } + - port: { get_resource: vweb_private_0_port } + - port: { get_resource: vweb_private_1_port } + metadata: {vnf_id: { get_param: vnf_id }, vf_module_id: { get_param: vf_module_id }} + user_data_format: RAW + user_data: + str_replace: + params: + __oam_ipaddr__ : { get_param: vweb_private_ip_1 } + __cpe_public_ipaddr__: { get_param: vweb_private_ip_0 } + __oam_cidr__: { get_param: onap_private_net_cidr } + __cpe_public_net_cidr__: { get_param: cpe_public_net_cidr } + __demo_artifacts_version__ : { get_param: demo_artifacts_version } + __install_script_version__ : { get_param: install_script_version } + __cloud_env__ : { get_param: cloud_env } + __nexus_artifact_repo__: { get_param: nexus_artifact_repo } + template: | + #!/bin/bash + + # Create configuration files + mkdir /opt/config + echo "__oam_ipaddr__" > /opt/config/oam_ipaddr.txt + echo "__cpe_public_ipaddr__" > /opt/config/cpe_public_ipaddr.txt + echo "__oam_cidr__" > /opt/config/oam_cidr.txt + echo "__cpe_public_net_cidr__" > /opt/config/cpe_public_net_cidr.txt + echo "__demo_artifacts_version__" > /opt/config/demo_artifacts_version.txt + echo "__install_script_version__" > /opt/config/install_script_version.txt + echo "__cloud_env__" > /opt/config/cloud_env.txt + echo "__nexus_artifact_repo__" > /opt/config/nexus_artifact_repo.txt + + # Download and run install script + apt-get update + apt-get -y install unzip + if [[ "__install_script_version__" =~ "SNAPSHOT" ]]; then REPO=snapshots; else REPO=releases; fi + curl -k -L "__nexus_artifact_repo__/service/local/artifact/maven/redirect?r=${REPO}&g=org.onap.demo.vnf.vcpe&a=vcpe-scripts&e=zip&v=__install_script_version__" -o /opt/vcpe-scripts-__install_script_version__.zip + unzip -j /opt/vcpe-scripts-__install_script_version__.zip -d /opt v_web_install.sh + cd /opt + chmod +x v_web_install.sh + ./v_web_install.sh diff --git a/asdc-controller/src/test/resources/resource-examples/vcpe-infra/demovcpeinfra-notification.json b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/demovcpeinfra-notification.json new file mode 100644 index 0000000000..61468a74f7 --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/demovcpeinfra-notification.json @@ -0,0 +1,111 @@ +{ + "distributionID": "e61f72f2-eee9-4c46-bf76-ae24414c6396", + "serviceName": "demoVCPEInfra", + "serviceVersion": "1.0", + "serviceUUID": "8a77cbbb-9850-40bb-a42f-7aec8e3e6ab7", + "serviceDescription": "catalog service description", + "serviceInvariantUUID": "21c102b6-c3e6-49ca-8021-83c105a191fa", + "resources": [{ + "resourceInstanceName": "CPE_PUBLIC", + "resourceName": "Generic NeutronNet", + "resourceVersion": "1.0", + "resoucreType": "VL", + "resourceUUID": "67bf9c77-aa78-4fab-99f4-3939a6d42348", + "resourceInvariantUUID": "8917e73c-88cf-42ed-8b33-6ea8ad080285", + "resourceCustomizationUUID": "4b3bd88b-6351-4564-b1de-e01021cdb79b", + "category": "Generic", + "subcategory": "Network Elements", + "artifacts": [] + }, { + "resourceInstanceName": "vCPE_infra bf35304f-e92f 0", + "resourceName": "vCPE_infra bf35304f-e92f", + "resourceVersion": "1.0", + "resoucreType": "VF", + "resourceUUID": "9a91c854-86fb-4072-8d4d-94dc0e96a311", + "resourceInvariantUUID": "dcd9cb6c-1634-4424-86e6-b03baed3e10a", + "resourceCustomizationUUID": "01564fe7-0541-4d92-badc-464cc35f83ba", + "category": "Generic", + "subcategory": "Abstract", + "artifacts": [{ + "artifactName": "vf-license-model.xml", + "artifactType": "VF_LICENSE", + "artifactURL": "vf-license-model.xml", + "artifactChecksum": "ODc4YjdjY2M5MDE1NDcxN2JhYTA2MjdiNGUxODE2MTM=", + "artifactDescription": "VF license file", + "artifactTimeout": 120, + "artifactUUID": "7fbbb913-0309-4a8b-8596-a1faf84886e8", + "artifactVersion": "1" + }, { + "artifactName": "vcpe_infrabf35304fe92f0_modules.json", + "artifactType": "VF_MODULES_METADATA", + "artifactURL": "vcpe_infrabf35304fe92f0_modules.json", + "artifactChecksum": "OGQ2MTI5YjZjYTFlYzUyOTYyOTY4YWZkYTQxYzViYzg=", + "artifactDescription": "Auto-generated VF Modules information artifact", + "artifactTimeout": 120, + "artifactUUID": "518b313a-4484-4cfd-92f0-0b23e2a415fd", + "artifactVersion": "1" + }, { + "artifactName": "base_vcpe_infra.yaml", + "artifactType": "HEAT", + "artifactURL": "base_vcpe_infra.yaml", + "artifactChecksum": "ZGEyNDgwNmEzZDk3ODU3ZDg3YTg1MDc0NmU1ZTMwYmI=", + "artifactDescription": "created from csar", + "artifactTimeout": 120, + "artifactUUID": "183353d4-2b50-4dc1-aecc-f2818f666b70", + "artifactVersion": "2" + }, { + "artifactName": "vendor-license-model.xml", + "artifactType": "VENDOR_LICENSE", + "artifactURL": "vendor-license-model.xml", + "artifactChecksum": "OTJhOTQyNTczZGRiYTJlM2M0MDQxZTdlMTE3NDE5YTQ=", + "artifactDescription": " Vendor license file", + "artifactTimeout": 120, + "artifactUUID": "7f4577e5-9f89-4c8e-985e-500e58425276", + "artifactVersion": "1" + }, { + "artifactName": "base_vcpe_infra.env", + "artifactType": "HEAT_ENV", + "artifactURL": "base_vcpe_infra.env", + "artifactChecksum": "ZmQxYTM1Yjg0ODJmN2I0OWE4OWMxN2NjOGEwMTM5NTY=", + "artifactDescription": "Auto-generated HEAT Environment deployment artifact", + "artifactTimeout": 120, + "artifactUUID": "1e9e20c7-6801-4a6c-a270-c8f5cec034c0", + "artifactVersion": "2", + "generatedFromUUID": "183353d4-2b50-4dc1-aecc-f2818f666b70" + } + ] + }, { + "resourceInstanceName": "CPE_SIGNAL", + "resourceName": "Generic NeutronNet", + "resourceVersion": "1.0", + "resoucreType": "VL", + "resourceUUID": "67bf9c77-aa78-4fab-99f4-3939a6d42348", + "resourceInvariantUUID": "8917e73c-88cf-42ed-8b33-6ea8ad080285", + "resourceCustomizationUUID": "803e0da3-6c40-4a4f-918b-7f3484de61ff", + "category": "Generic", + "subcategory": "Network Elements", + "artifacts": [] + } + ], + "serviceArtifacts": [{ + "artifactName": "service-Demovcpeinfra-template.yml", + "artifactType": "TOSCA_TEMPLATE", + "artifactURL": "service-Demovcpeinfra-template.yml", + "artifactChecksum": "ZDY3ZGY4ZTM4ZDA3ZjY4M2Y2MDgxNzI0MDE3NjkzODM=", + "artifactDescription": "TOSCA representation of the asset", + "artifactTimeout": 0, + "artifactUUID": "a4180154-1279-47d5-acbc-392e87d3fc7f", + "artifactVersion": "1" + }, { + "artifactName": "service-Demovcpeinfra-csar.csar", + "artifactType": "TOSCA_CSAR", + "artifactURL": "service-Demovcpeinfra-csar.csar", + "artifactChecksum": "NjlhMDk2YzNlNTI5OTg3MzE2ZmUzYjI5MTY2M2Y5YmU=", + "artifactDescription": "TOSCA definition package of the asset", + "artifactTimeout": 0, + "artifactUUID": "144606d8-a505-4ba0-90a9-6d1c6219fc6b", + "artifactVersion": "1" + } + ], + "workloadContext": "Production" +} diff --git a/asdc-controller/src/test/resources/resource-examples/vcpe-infra/service-Demovcpeinfra-csar.csar b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/service-Demovcpeinfra-csar.csar Binary files differnew file mode 100644 index 0000000000..841c681088 --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/service-Demovcpeinfra-csar.csar diff --git a/asdc-controller/src/test/resources/resource-examples/vcpe-infra/vcpe_infrabf35304fe92f0_modules.json b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/vcpe_infrabf35304fe92f0_modules.json new file mode 100644 index 0000000000..d005a09730 --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/vcpe_infrabf35304fe92f0_modules.json @@ -0,0 +1,25 @@ +[ + { + "vfModuleModelName": "VcpeInfraBf35304fE92f..base_vcpe_infra..module-0", + "vfModuleModelInvariantUUID": "e9a09595-26cd-4929-89e6-a79a02d3ef8f", + "vfModuleModelVersion": "1", + "vfModuleModelUUID": "4555cb57-7dc6-4680-912f-84739fc8d03e", + "vfModuleModelCustomizationUUID": "354b1e83-47db-4af1-8af4-9c14b03b482d", + "isBase": true, + "artifacts": [ + "183353d4-2b50-4dc1-aecc-f2818f666b70", + "1e9e20c7-6801-4a6c-a270-c8f5cec034c0" + ], + "properties": { + "min_vf_module_instances": "1", + "vf_module_label": "base_vcpe_infra", + "max_vf_module_instances": "1", + "vfc_list": "", + "vf_module_description": "", + "vf_module_type": "Base", + "availability_zone_count": "", + "volume_group": "false", + "initial_count": "1" + } + } +]
\ No newline at end of file diff --git a/asdc-controller/src/test/resources/resource-examples/vcpe-infra/vendor-license-model.xml b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/vendor-license-model.xml new file mode 100644 index 0000000000..4c6a44d46b --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/vendor-license-model.xml @@ -0,0 +1 @@ +<vendor-license-model xmlns="http://xmlns.openecomp.org/asdc/license-model/1.0"><vendor-name>4c24f75d-4191-4447-9b61</vendor-name><entitlement-pool-list><entitlement-pool><entitlement-pool-invariant-uuid>af63f5c36c93451c99640c1b63ae5bc9</entitlement-pool-invariant-uuid><entitlement-pool-uuid>187EE1211F1A437CBCC6032B60841846</entitlement-pool-uuid><version>1.0</version><name>4e401c4f-0679-46a0-b7f1</name><description>vendor entitlement pool</description><increments/><manufacturer-reference-number>111111</manufacturer-reference-number><threshold-value><unit>Percentage</unit><value>100</value></threshold-value><sp-limits/><vendor-limits/><operational-scope><value/></operational-scope><start-date>2019-05-10T00:00:00Z</start-date><expiry-date>2020-05-09T23:59:59Z</expiry-date></entitlement-pool></entitlement-pool-list><license-key-group-list><license-key-group><version>1.0</version><name>22353211-5524-4b26-af02</name><description>vendor license key group</description><type>Universal</type><increments/><manufacturerReferenceNumber>11111</manufacturerReferenceNumber><license-key-group-invariant-uuid>4e872234ca73482da2d4efc0a7da9e06</license-key-group-invariant-uuid><license-key-group-uuid>65C063A5402146DC9CEDDB7D99F9BA1A</license-key-group-uuid><threshold-value><unit>Percentage</unit><value>100</value></threshold-value><sp-limits/><vendor-limits/><operational-scope><value/></operational-scope><start-date>2019-05-10T00:00:00Z</start-date><expiry-date>2020-05-09T23:59:59Z</expiry-date></license-key-group></license-key-group-list></vendor-license-model>
\ No newline at end of file diff --git a/asdc-controller/src/test/resources/resource-examples/vcpe-infra/vf-license-model.xml b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/vf-license-model.xml new file mode 100644 index 0000000000..cc13fa4fea --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vcpe-infra/vf-license-model.xml @@ -0,0 +1 @@ +<vf-license-model xmlns="http://xmlns.openecomp.org/asdc/license-model/1.0"><vendor-name>4c24f75d-4191-4447-9b61</vendor-name><vf-id>b9cd64d6d4dc4a93953193ac0bc09619</vf-id><feature-group-list><feature-group><entitlement-pool-list><entitlement-pool><name>4e401c4f-0679-46a0-b7f1</name><description>vendor entitlement pool</description><increments/><entitlement-pool-invariant-uuid>af63f5c36c93451c99640c1b63ae5bc9</entitlement-pool-invariant-uuid><entitlement-pool-uuid>187EE1211F1A437CBCC6032B60841846</entitlement-pool-uuid><manufacturer-reference-number>111111</manufacturer-reference-number><threshold-value><unit>Percentage</unit><value>100</value></threshold-value><version>1.0</version><sp-limits/><vendor-limits/><operational-scope><value/></operational-scope><start-date>2019-05-10T00:00:00Z</start-date><expiry-date>2020-05-09T23:59:59Z</expiry-date></entitlement-pool></entitlement-pool-list><license-key-group-list><license-key-group><name>22353211-5524-4b26-af02</name><description>vendor license key group</description><type>Universal</type><increments/><license-key-group-invariant-uuid>4e872234ca73482da2d4efc0a7da9e06</license-key-group-invariant-uuid><license-key-group-uuid>65C063A5402146DC9CEDDB7D99F9BA1A</license-key-group-uuid><manufacturer-reference-number>11111</manufacturer-reference-number><threshold-value><unit>Percentage</unit><value>100</value></threshold-value><version>1.0</version><sp-limits/><vendor-limits/><operational-scope><value/></operational-scope><start-date>2019-05-10T00:00:00Z</start-date><expiry-date>2020-05-09T23:59:59Z</expiry-date></license-key-group></license-key-group-list><name>9bc21ea0-5bcd-44d6-93f0</name><feature-group-uuid>f7fdb15660df4254b520797c59297b24</feature-group-uuid><part-number>123abc456</part-number><description>vendor feature group</description></feature-group></feature-group-list></vf-license-model>
\ No newline at end of file diff --git a/asdc-controller/src/test/resources/schema.sql b/asdc-controller/src/test/resources/schema.sql index 0e8024da0a..5e4af83e0e 100644 --- a/asdc-controller/src/test/resources/schema.sql +++ b/asdc-controller/src/test/resources/schema.sql @@ -806,7 +806,9 @@ CREATE TABLE `service` ( `WORKLOAD_CONTEXT` varchar(200) DEFAULT NULL, `SERVICE_CATEGORY` varchar(200) DEFAULT NULL, `RESOURCE_ORDER` varchar(200) default NULL, - OVERALL_DISTRIBUTION_STATUS varchar(45), + `OVERALL_DISTRIBUTION_STATUS` varchar(45), + `ONAP_GENERATED_NAMING` TINYINT(1) DEFAULT NULL, + `NAMING_POLICY` varchar(200) DEFAULT NULL, PRIMARY KEY (`MODEL_UUID`), KEY `fk_service__tosca_csar1_idx` (`TOSCA_CSAR_ARTIFACT_UUID`), CONSTRAINT `fk_service__tosca_csar1` FOREIGN KEY (`TOSCA_CSAR_ARTIFACT_UUID`) REFERENCES `tosca_csar` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE diff --git a/bpmn/MSOCommonBPMN/pom.xml b/bpmn/MSOCommonBPMN/pom.xml index 182976d69e..e233e6a7c6 100644 --- a/bpmn/MSOCommonBPMN/pom.xml +++ b/bpmn/MSOCommonBPMN/pom.xml @@ -311,7 +311,7 @@ <dependency> <groupId>org.onap.appc.client</groupId> <artifactId>client-lib</artifactId> - <version>1.6.0-SNAPSHOT</version> + <version>${appc.client.version}</version> <exclusions> <exclusion> <groupId>org.mockito</groupId> @@ -330,7 +330,7 @@ <dependency> <groupId>org.onap.appc.client</groupId> <artifactId>client-kit</artifactId> - <version>1.6.0-SNAPSHOT</version> + <version>${appc.client.version}</version> <exclusions> <exclusion> <groupId>org.mockito</groupId> @@ -364,16 +364,6 @@ <artifactId>jersey-media-json-jackson</artifactId> </dependency> <dependency> - <groupId>org.onap.sdc.sdc-tosca</groupId> - <artifactId>sdc-tosca</artifactId> - <version>1.4.4</version> - </dependency> - <dependency> - <groupId>org.onap.sdc.jtosca</groupId> - <artifactId>jtosca</artifactId> - <version>1.4.4</version> - </dependency> - <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy index b98e395228..f14e3dcc42 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.client.HttpClientFactory import org.onap.so.logger.ErrorCode @@ -134,13 +135,13 @@ class AaiUtil { } logger.debug("Cloud Region value for code='404' of " + backend + " is: " + regionId) }else{ - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Call AAI Cloud Region is NOT Successful.", "BPMN", ErrorCode.UnknownError.getValue()); throw new BpmnError("MSOWorkflowException") } }catch(Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception occured while getting the Cloud Reqion.", "BPMN", ErrorCode.UnknownError.getValue(), e.getMessage()); (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy index e0e85e9629..4df38edcc3 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.client.aai.entities.AAIResultWrapper import org.onap.so.logger.ErrorCode @@ -195,7 +196,7 @@ class AllottedResourceUtils { AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(aaiARPath).build()) getAAIClient().update(uri,allottedResource) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception in updateAR.", "BPMN", ErrorCode.UnknownError.getValue(), e.getMessage()); exceptionUtil.buildAndThrowWorkflowException(execution, 500, 'Internal Error in updateAROrchStatus.' + e.getMessage()) } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AppCClient.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AppCClient.groovy index 4a59b9789a..c843cc35fe 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AppCClient.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AppCClient.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.core.json.JsonUtils @@ -120,7 +121,7 @@ public class AppCClient extends AbstractServiceTaskProcessor{ appcMessage = client.getErrorMessage() } catch (BpmnError e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); appcMessage = e.getMessage() diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.groovy index d5b0b31a39..2bf7298584 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.apache.commons.lang3.StringUtils import org.camunda.bpm.engine.delegate.DelegateExecution import org.json.JSONArray @@ -80,7 +81,7 @@ class CatalogDbUtils { } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception in Querying Catalog DB", "BPMN", ErrorCode.UnknownError.getValue(), e.message); throw e @@ -118,7 +119,7 @@ class CatalogDbUtils { return getResponseFromCatalogDb(execution, endPoint) } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception in Querying Catalog DB", "BPMN", ErrorCode.UnknownError.getValue(), e.message); throw e @@ -142,7 +143,7 @@ class CatalogDbUtils { } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception in Querying Catalog DB", "BPMN", ErrorCode.UnknownError.getValue(), e.message); throw e @@ -168,7 +169,7 @@ class CatalogDbUtils { } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception in Querying Catalog DB", "BPMN", ErrorCode.UnknownError.getValue(), e.message); throw e @@ -218,7 +219,7 @@ class CatalogDbUtils { logger.debug("Returning networks JSON: " + modelInfosString) } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception in parsing Catalog DB Response", "BPMN", ErrorCode.UnknownError.getValue(), e.message); } @@ -297,7 +298,7 @@ class CatalogDbUtils { logger.debug("Returning vnfs JSON: " + modelInfosString) } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception in parsing Catalog DB Response", "BPMN", ErrorCode.UnknownError.getValue(), e.message); } @@ -351,7 +352,7 @@ class CatalogDbUtils { logger.debug("Returning allottedResources JSON: " + modelInfosString) } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception in parsing Catalog DB Response", "BPMN", ErrorCode.UnknownError.getValue(), e.message); } @@ -380,7 +381,7 @@ class CatalogDbUtils { logger.debug("Returning serviceResources JSON: " + serviceResourcesObject.toString()) } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception in parsing Catalog DB Response", "BPMN", ErrorCode.UnknownError.getValue(), e.message); } @@ -428,7 +429,7 @@ class CatalogDbUtils { modelJson.put("modelInfo", modelInfo) } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception while parsing model information", "BPMN", ErrorCode.UnknownError.getValue(), e.message); } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy index a9e01c7191..7e1280729c 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.logger.ErrorCode @@ -74,7 +75,7 @@ public class CompleteMsoProcess extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + ' ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) } @@ -236,7 +237,7 @@ public class CompleteMsoProcess extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) @@ -269,7 +270,7 @@ public class CompleteMsoProcess extends AbstractServiceTaskProcessor { logger.debug("Rethrowing MSOWorkflowException") throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) @@ -307,7 +308,7 @@ public class CompleteMsoProcess extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupName.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupName.groovy index 6a82512d88..b666c8d19d 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupName.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupName.groovy @@ -24,70 +24,67 @@ package org.onap.so.bpmn.common.scripts -import joptsimple.internal.Strings -import org.onap.so.bpmn.common.scripts.ExceptionUtil -import org.onap.so.logger.ErrorCode -import org.springframework.http.HttpStatus - -import javax.ws.rs.core.UriBuilder - import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.VolumeGroup import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.constants.Defaults +import org.onap.so.logger.ErrorCode +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.MessageEnum import org.slf4j.Logger import org.slf4j.LoggerFactory +import org.springframework.http.HttpStatus +import joptsimple.internal.Strings public class ConfirmVolumeGroupName extends AbstractServiceTaskProcessor{ private static final Logger logger = LoggerFactory.getLogger( ConfirmVolumeGroupName.class); - def static final Prefix = "CVGN_" - private final ExceptionUtil exceptionUtil - - ConfirmVolumeGroupName(ExceptionUtil exceptionUtil) { - this.exceptionUtil = exceptionUtil - } - - public void initProcessVariables(DelegateExecution execution) { - execution.setVariable("prefix",Prefix) - execution.setVariable("CVGN_volumeGroupId",null) - execution.setVariable("CVGN_volumeGroupName",null) - execution.setVariable("CVGN_aicCloudRegion", null) - execution.setVariable("CVGN_volumeGroupGetEndpoint",null) - - // ConfirmVolumeGroupName workflow response variable placeholders - execution.setVariable("CVGN_volumeGroupNameMatches", false) - execution.setVariable("CVGN_queryVolumeGroupResponseCode",null) - execution.setVariable("CVGN_queryVolumeGroupResponse","") - execution.setVariable("CVGN_ResponseCode",null) - execution.setVariable("RollbackData", null) - } - - // store the incoming data in the flow DelegateExecution - public void preProcessRequest(DelegateExecution execution) { - def volumeGroupId = execution.getVariable("ConfirmVolumeGroupName_volumeGroupId") - def volumeGroupName= execution.getVariable("ConfirmVolumeGroupName_volumeGroupName") - def aicCloudRegion = execution.getVariable("ConfirmVolumeGroupName_aicCloudRegion") - - initProcessVariables(execution) - execution.setVariable("CVGN_volumeGroupId", volumeGroupId) - execution.setVariable("CVGN_volumeGroupName", volumeGroupName) - execution.setVariable("CVGN_aicCloudRegion", aicCloudRegion) - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), aicCloudRegion, volumeGroupId) - execution.setVariable("CVGN_volumeGroupGetEndpoint", uri) - } - - // send a GET request to AA&I to retrieve the Volume information based on volume-group-id - // expect a 200 response with the information in the response body or a 404 if the volume group id does not exist - public void queryAAIForVolumeGroupId(DelegateExecution execution) { - AAIResourceUri resourceUri = execution.getVariable("CVGN_volumeGroupGetEndpoint") - - try { - Optional<VolumeGroup> volumeGroupOp = getAAIClient().get(VolumeGroup.class, resourceUri) + def static final Prefix = "CVGN_" + private final ExceptionUtil exceptionUtil + + ConfirmVolumeGroupName(ExceptionUtil exceptionUtil) { + this.exceptionUtil = exceptionUtil + } + + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable("prefix",Prefix) + execution.setVariable("CVGN_volumeGroupId",null) + execution.setVariable("CVGN_volumeGroupName",null) + execution.setVariable("CVGN_aicCloudRegion", null) + execution.setVariable("CVGN_volumeGroupGetEndpoint",null) + + // ConfirmVolumeGroupName workflow response variable placeholders + execution.setVariable("CVGN_volumeGroupNameMatches", false) + execution.setVariable("CVGN_queryVolumeGroupResponseCode",null) + execution.setVariable("CVGN_queryVolumeGroupResponse","") + execution.setVariable("CVGN_ResponseCode",null) + execution.setVariable("RollbackData", null) + } + + // store the incoming data in the flow DelegateExecution + public void preProcessRequest(DelegateExecution execution) { + def volumeGroupId = execution.getVariable("ConfirmVolumeGroupName_volumeGroupId") + def volumeGroupName= execution.getVariable("ConfirmVolumeGroupName_volumeGroupName") + def aicCloudRegion = execution.getVariable("ConfirmVolumeGroupName_aicCloudRegion") + + initProcessVariables(execution) + execution.setVariable("CVGN_volumeGroupId", volumeGroupId) + execution.setVariable("CVGN_volumeGroupName", volumeGroupName) + execution.setVariable("CVGN_aicCloudRegion", aicCloudRegion) + + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), aicCloudRegion, volumeGroupId) + execution.setVariable("CVGN_volumeGroupGetEndpoint", uri) + } + + // send a GET request to AA&I to retrieve the Volume information based on volume-group-id + // expect a 200 response with the information in the response body or a 404 if the volume group id does not exist + public void queryAAIForVolumeGroupId(DelegateExecution execution) { + AAIResourceUri resourceUri = execution.getVariable("CVGN_volumeGroupGetEndpoint") + + try { + Optional<VolumeGroup> volumeGroupOp = getAAIClient().get(VolumeGroup.class, resourceUri) if(volumeGroupOp.isPresent()){ execution.setVariable("CVGN_queryVolumeGroupResponseCode", HttpStatus.OK.value()) execution.setVariable("CVGN_queryVolumeGroupResponse", volumeGroupOp.get()) @@ -95,60 +92,60 @@ public class ConfirmVolumeGroupName extends AbstractServiceTaskProcessor{ execution.setVariable("CVGN_queryVolumeGroupResponseCode", HttpStatus.NOT_FOUND.value()) execution.setVariable("CVGN_queryVolumeGroupResponse", "Volume Group not Found!") } - } catch (Exception ex) { - logger.debug("Exception occurred while executing AAI GET:" + ex.getMessage()) - execution.setVariable("CVGN_queryVolumeGroupResponseCode", HttpStatus.INTERNAL_SERVER_ERROR.value()) - execution.setVariable("CVGN_queryVolumeGroupResponse", "AAI GET Failed:" + ex.getMessage()) - exceptionUtil.buildAndThrowWorkflowException(execution, HttpStatus.INTERNAL_SERVER_ERROR.value(), "AAI GET Failed") - } - } + } catch (Exception ex) { + logger.debug("Exception occurred while executing AAI GET:" + ex.getMessage()) + execution.setVariable("CVGN_queryVolumeGroupResponseCode", HttpStatus.INTERNAL_SERVER_ERROR.value()) + execution.setVariable("CVGN_queryVolumeGroupResponse", "AAI GET Failed:" + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, HttpStatus.INTERNAL_SERVER_ERROR.value(), "AAI GET Failed") + } + } - // process the result from queryAAIVolumeGroupId() + // process the result from queryAAIVolumeGroupId() - public void checkAAIQueryResult(DelegateExecution execution) { + public void checkAAIQueryResult(DelegateExecution execution) { def actualVolumeGroupName = "" if (execution.getVariable("CVGN_queryVolumeGroupResponseCode") == HttpStatus.NOT_FOUND.value()) { - logger.debug('volumeGroupId does not exist in AAI') - } - else if (execution.getVariable("CVGN_queryVolumeGroupResponseCode") == HttpStatus.OK.value()) { + logger.debug('volumeGroupId does not exist in AAI') + } + else if (execution.getVariable("CVGN_queryVolumeGroupResponseCode") == HttpStatus.OK.value()) { VolumeGroup volumeGroup = execution.getVariable("CVGN_queryVolumeGroupResponse") if (!Strings.isNullOrEmpty(volumeGroup.getVolumeGroupName())) { actualVolumeGroupName = volumeGroup.getVolumeGroupName() - logger.debug("volumeGroupId exists in AAI") - } - } - execution.setVariable("CVGN_volumeGroupNameMatches", false) - def volumeGroupName = execution.getVariable("CVGN_volumeGroupName") - - if (!actualVolumeGroupName.isEmpty() && volumeGroupName.equals(actualVolumeGroupName)) { - logger.debug('Volume Group Name Matches AAI records') - execution.setVariable("CVGN_volumeGroupNameMatches", true) - } - } - - - // generates a WorkflowException if the A&AI query returns a response code other than 200/404 - public void handleAAIQueryFailure(DelegateExecution execution) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - "Error occurred attempting to query AAI, Response Code " + execution.getVariable("CVGN_queryVolumeGroupResponseCode"), - "BPMN", ErrorCode.UnknownError.getValue(), - "ErrorResponse is:\n" + execution.getVariable("CVGN_queryVolumeGroupResponse")); - } - - // generates a WorkflowException if the volume group name does not match AAI record for this volume group - public void handleVolumeGroupNameNoMatch(DelegateExecution execution) { - def errorNotAssociated = "Error occurred - volume group id ${execution.getVariable('CVGN_volumeGroupId')} " + - "is not associated with ${execution.getVariable('CVGN_volumeGroupName')}" - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), errorNotAssociated, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, errorNotAssociated) - } - - // sends a successful WorkflowResponse - public void reportSuccess(DelegateExecution execution) { - logger.debug("Sending 200 back to the caller") - def responseXML = "" - execution.setVariable("WorkflowResponse", responseXML) - } + logger.debug("volumeGroupId exists in AAI") + } + } + execution.setVariable("CVGN_volumeGroupNameMatches", false) + def volumeGroupName = execution.getVariable("CVGN_volumeGroupName") + + if (!actualVolumeGroupName.isEmpty() && volumeGroupName.equals(actualVolumeGroupName)) { + logger.debug('Volume Group Name Matches AAI records') + execution.setVariable("CVGN_volumeGroupNameMatches", true) + } + } + + + // generates a WorkflowException if the A&AI query returns a response code other than 200/404 + public void handleAAIQueryFailure(DelegateExecution execution) { + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + "Error occurred attempting to query AAI, Response Code " + execution.getVariable("CVGN_queryVolumeGroupResponseCode"), + "BPMN", ErrorCode.UnknownError.getValue(), + "ErrorResponse is:\n" + execution.getVariable("CVGN_queryVolumeGroupResponse")); + } + + // generates a WorkflowException if the volume group name does not match AAI record for this volume group + public void handleVolumeGroupNameNoMatch(DelegateExecution execution) { + def errorNotAssociated = "Error occurred - volume group id ${execution.getVariable('CVGN_volumeGroupId')} " + + "is not associated with ${execution.getVariable('CVGN_volumeGroupName')}" + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), errorNotAssociated, "BPMN", + ErrorCode.UnknownError.getValue()); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, errorNotAssociated) + } + + // sends a successful WorkflowResponse + public void reportSuccess(DelegateExecution execution) { + logger.debug("Sending 200 back to the caller") + def responseXML = "" + execution.setVariable("WorkflowResponse", responseXML) + } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy index 7c1c0a0490..569d4b75b9 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.VolumeGroup @@ -105,7 +106,7 @@ class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{ }catch(BpmnError b){ throw b }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing queryAAIForVolumeGroup.", "BPMN", ErrorCode.UnknownError.getValue(), e.getMessage()); exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in preProcessRequest.") @@ -127,7 +128,7 @@ class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{ logger.debug("Volume Heat Stack Id is: " + heatStackId) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing assignVolumeHeatId.", "BPMN", ErrorCode.UnknownError.getValue(), e); exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in assignVolumeHeatId.") @@ -147,7 +148,7 @@ class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{ exceptionUtil.buildWorkflowException(execution, errorCode, errorMessage) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing assignWorkflowException.", "BPMN", ErrorCode.UnknownError.getValue(), e); } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy index e9e7d1ed7c..163e914238 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.apache.commons.lang.StringUtils import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.GenericVnf @@ -423,7 +424,7 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ // generates a WorkflowException when the A&AI query returns a response code other than 200 or 404 public void handleAAIQueryFailure(DelegateExecution execution) { - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Error occurred attempting to query AAI, Response Code " + execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") + ", Error Response " + execution.getVariable("CAAIVfMod_queryGenericVnfResponse"), "BPMN", ErrorCode.UnknownError.getValue()); int code = execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") @@ -475,7 +476,7 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ errorCode = 2000 } - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Error occurred during CreateAAIVfModule flow", "BPMN", ErrorCode.UnknownError.getValue(), errorResponse); exceptionUtil.buildAndThrowWorkflowException(execution, errorCode, errorResponse) diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy index 4bce23eff7..4d57b1b26f 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy @@ -21,6 +21,8 @@ */ package org.onap.so.bpmn.common.scripts + +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.GenericVnf import org.onap.so.client.aai.AAIObjectType @@ -204,7 +206,7 @@ public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ // generates a WorkflowException if the A&AI query returns a response code other than 200 public void handleAAIQueryFailure(DelegateExecution execution) { - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Error occurred attempting to query AAI, Response Code " + execution.getVariable("DAAIVfMod_queryGenericVnfResponseCode") + ", Error Response " + execution.getVariable("DAAIVfMod_queryGenericVnfResponse"), "BPMN", ErrorCode.UnknownError.getValue()); def errorCode = 5000 @@ -251,7 +253,7 @@ public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ } } - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Error occurred during DeleteAAIVfModule flow", "BPMN", ErrorCode.UnknownError.getValue(), errorResponse); exceptionUtil.buildAndThrowWorkflowException(execution, errorCode, errorResponse) @@ -261,7 +263,7 @@ public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ // generates a WorkflowException if // - the A&AI Generic Vnf DELETE returns a response code other than 200 public void handleDeleteGenericVnfFailure(DelegateExecution execution) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "AAI error occurred deleting the Generic Vnf", "BPMN", ErrorCode.UnknownError.getValue(), execution.getVariable("DAAIVfMod_deleteGenericVnfResponse")); diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExceptionUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExceptionUtil.groovy index 30dbeb09d5..d95dbe2184 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExceptionUtil.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExceptionUtil.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.ErrorCode import static org.apache.commons.lang3.StringUtils.* @@ -91,7 +92,7 @@ class ExceptionUtil extends AbstractServiceTaskProcessor { buildWorkflowException(execution, 5000, modifiedErrorMessage) wfex = execution.getVariable("WorkflowException") - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Fault", "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Fault", "BPMN", ErrorCode.UnknownError.getValue(), wfex.errorMessage); return wfex } else { @@ -104,7 +105,7 @@ class ExceptionUtil extends AbstractServiceTaskProcessor { logger.debug("mappedErrorMessage " + mappedErrorMessage) wfex = execution.getVariable("WorkflowException") - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Fault", "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Fault", "BPMN", ErrorCode.UnknownError.getValue(), wfex.errorMessage); return wfex } catch(Exception ex) { diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy index 2ceec3cb44..ed849755b7 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.logger.ErrorCode @@ -97,7 +98,7 @@ public class FalloutHandler extends AbstractServiceTaskProcessor { execution.setVariable("FH_ResponseCode", "") } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) @@ -210,7 +211,7 @@ public class FalloutHandler extends AbstractServiceTaskProcessor { execution.setVariable("FH_content_type", "text/xml") } } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in" + method) @@ -244,7 +245,7 @@ public class FalloutHandler extends AbstractServiceTaskProcessor { execution.setVariable("FH_updateRequestPayload", payload) return execution.getVariable("FH_updateRequestPayload") } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) @@ -275,7 +276,7 @@ public class FalloutHandler extends AbstractServiceTaskProcessor { logger.debug("updateRequestInfraPayload: " + payload) return execution.getVariable("FH_updateRequestInfraPayload") } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) @@ -306,7 +307,7 @@ public class FalloutHandler extends AbstractServiceTaskProcessor { logger.debug("updateRequestGammaPayload: " + payload) return execution.getVariable("FH_updateRequestGammaPayload") } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) @@ -335,7 +336,7 @@ public class FalloutHandler extends AbstractServiceTaskProcessor { logger.debug("updateResponseStatusPayload: " + payload) return execution.getVariable("FH_updateResponseStatusPayload") } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) @@ -355,7 +356,7 @@ public class FalloutHandler extends AbstractServiceTaskProcessor { def errorCode = responseCode == null ? 7000 : 7020 // exceptionUtil.buildWorkflowException(execution, errorCode, errorMessage) } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) @@ -390,7 +391,7 @@ public class FalloutHandler extends AbstractServiceTaskProcessor { logger.debug("FalloutHandlerResponse =\n" + falloutHandlerResponse) } catch (Exception e) { // Do NOT throw WorkflowException! - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.groovy index f008130c32..3008f77b62 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.client.HttpClientFactory import org.onap.so.logger.ErrorCode @@ -158,7 +159,7 @@ public class GenerateVfModuleName extends AbstractServiceTaskProcessor{ } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAI(): ' + e.getMessage()) diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ManualHandling.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ManualHandling.groovy index 27fe33f5ea..ef4291d18f 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ManualHandling.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ManualHandling.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.ErrorCode; import static org.apache.commons.lang3.StringUtils.*; @@ -289,7 +290,7 @@ public class ManualHandling extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) @@ -341,11 +342,11 @@ public class ManualHandling extends AbstractServiceTaskProcessor { } catch (BpmnError e) { msg = "BPMN error in createAOTSTicket " + ex.getMessage() - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); } catch (Exception ex){ msg = "Exception in createAOTSTicket " + ex.getMessage() - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); } logger.trace("Exit createAOTSTicket of ManualHandling ") diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy index f371ccef4d..a2f5dfbffe 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.ErrorCode import java.text.SimpleDateFormat @@ -294,10 +295,10 @@ class MsoUtils { if ("INFO"==logmode) { logger.info(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), logtxt, "BPMN"); } else if ("WARN"==logmode) { - logger.warn ("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_WARNING.toString(), logtxt, "BPMN", + logger.warn (LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_WARNING.toString(), logtxt, "BPMN", ErrorCode.UnknownError.getValue(), logtxt); } else if ("ERROR"==logmode) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), logtxt, "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), logtxt, "BPMN", ErrorCode.UnknownError.getValue(), logtxt); } else { logger.debug(logtxt); diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy index d17a3c42a6..6583ded413 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy @@ -32,15 +32,18 @@ import org.onap.so.bpmn.core.domain.ServiceDecomposition import org.onap.so.bpmn.core.domain.Subscriber import org.onap.so.bpmn.core.domain.VnfResource import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.DefaultProperties import org.onap.so.client.HttpClient import org.onap.so.client.HttpClientFactory -import org.slf4j.Logger -import org.slf4j.LoggerFactory +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.db.catalog.beans.AuthenticationType import org.onap.so.db.catalog.beans.CloudIdentity import org.onap.so.db.catalog.beans.CloudSite import org.onap.so.db.catalog.beans.HomingInstance -import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.db.catalog.beans.ServerType import org.onap.so.utils.TargetEntity +import org.slf4j.Logger +import org.slf4j.LoggerFactory import org.json.JSONArray import org.json.JSONObject @@ -106,12 +109,12 @@ class OofHoming extends AbstractServiceTaskProcessor { if (isBlank(subscriberInfo)) { subscriber = new Subscriber("", "", "") } else { - String subId = jsonUtil.getJsonValue(subscriberInfo, "globalSubscriberId") - String subName = jsonUtil.getJsonValue(subscriberInfo, "subscriberName") - String subCommonSiteId = "" - if (jsonUtil.jsonElementExist(subscriberInfo, "subscriberCommonSiteId")) { - subCommonSiteId = jsonUtil.getJsonValue(subscriberInfo, "subscriberCommonSiteId") - } + String subId = jsonUtil.getJsonValue(subscriberInfo, "globalSubscriberId") + String subName = jsonUtil.getJsonValue(subscriberInfo, "subscriberName") + String subCommonSiteId = "" + if (jsonUtil.jsonElementExist(subscriberInfo, "subscriberCommonSiteId")) { + subCommonSiteId = jsonUtil.getJsonValue(subscriberInfo, "subscriberCommonSiteId") + } subscriber = new Subscriber(subId, subName, subCommonSiteId) } @@ -161,21 +164,24 @@ class OofHoming extends AbstractServiceTaskProcessor { logger.debug( "Posting to OOF Url: " + urlString) - URL url = new URL(urlString); - HttpClient httpClient = new HttpClientFactory().newJsonClient(url, TargetEntity.SNIRO) + URL url = new URL(urlString) + HttpClient httpClient = new HttpClientFactory().newJsonClient(url, TargetEntity.OOF) httpClient.addAdditionalHeader("Authorization", authHeader) - Response httpResponse = httpClient.post(oofRequest) + Response httpResponse = httpClient.post(oofRequest) - int responseCode = httpResponse.getStatus() - logger.debug("OOF sync response code is: " + responseCode) + int responseCode = httpResponse.getStatus() + logger.debug("OOF sync response code is: " + responseCode) + if(responseCode != 202){ + exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.") + } logger.debug( "*** Completed Homing Call OOF ***") } } catch (BpmnError b) { throw b } catch (Exception e) { - logger.error(e); + logger.error(e); exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in Homing callOof: " + e.getMessage()) } @@ -358,7 +364,7 @@ class OofHoming extends AbstractServiceTaskProcessor { throw b } catch (Exception e) { logger.debug( "ProcessHomingSolution Exception: " + e) - logger.error(e); + logger.error(e); exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occurred in Homing ProcessHomingSolution") } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy index 2f46630715..4bfb29bc45 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy @@ -25,6 +25,7 @@ package org.onap.so.bpmn.common.scripts import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.util.OofInfraUtils import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.domain.HomingSolution import org.onap.so.bpmn.core.domain.ModelInfo @@ -53,6 +54,7 @@ import org.slf4j.LoggerFactory import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response +import javax.ws.rs.core.UriBuilder import javax.xml.ws.http.HTTPException import static org.onap.so.bpmn.common.scripts.GenericUtils.* @@ -62,6 +64,7 @@ class OofUtils { ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() + OofInfraUtils oofInfraUtils = new OofInfraUtils() private AbstractServiceTaskProcessor utils @@ -504,27 +507,8 @@ class OofUtils { * * @return void */ - Void createCloudSiteCatalogDb(CloudSite cloudSite, DelegateExecution execution) { - - String endpoint = UrnPropertiesReader.getVariable("mso.catalog.db.spring.endpoint", execution) - String auth = UrnPropertiesReader.getVariable("mso.db.auth", execution) - String uri = "/cloudSite" - - URL url = new URL(endpoint + uri) - HttpClient client = new HttpClientFactory().newJsonClient(url, TargetEntity.EXTERNAL) - client.addAdditionalHeader(HttpHeaders.AUTHORIZATION, auth) - client.addAdditionalHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON) - - Response response = client.post(request.getBody().toString()) - - int responseCode = response.getStatus() - logger.debug("CatalogDB response code is: " + responseCode) - String syncResponse = response.readEntity(String.class) - logger.debug("CatalogDB response is: " + syncResponse) - - if(responseCode != 202){ - exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from CatalogDB.") - } + Void createCloudSite(CloudSite cloudSite, DelegateExecution execution) { + oofInfraUtils.createCloudSite(cloudSite, execution) } /** @@ -537,11 +521,12 @@ class OofUtils { Void createHomingInstance(HomingInstance homingInstance, DelegateExecution execution) { oofInfraUtils.createHomingInstance(homingInstance, execution) } - String getMsbHost(DelegateExecution execution) { - String msbHost = UrnPropertiesReader.getVariable("mso.msb.host", execution, "msb-iag.onap") - Integer msbPort = UrnPropertiesReader.getVariable("mso.msb.port", execution, "80").toInteger() + String getMsbHost(DelegateExecution execution) { + String msbHost = UrnPropertiesReader.getVariable("mso.msb.host", execution, "msb-iag.onap") + + Integer msbPort = UrnPropertiesReader.getVariable("mso.msb.port", execution, "80").toInteger() - return UriBuilder.fromPath("").host(msbHost).port(msbPort).scheme("http").build().toString() + return UriBuilder.fromPath("").host(msbHost).port(msbPort).scheme("http").build().toString() } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ReceiveWorkflowMessage.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ReceiveWorkflowMessage.groovy index a0da6870ae..39e6db4d3f 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ReceiveWorkflowMessage.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ReceiveWorkflowMessage.groovy @@ -20,8 +20,9 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.scripts; +package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor; import groovy.json.* import org.apache.commons.lang3.* @@ -66,7 +67,7 @@ public void preProcessRequest (DelegateExecution execution) { if ((timeout == null) || (timeout.isEmpty())) { String msg = getProcessKey(execution) + ': Missing or empty input variable \'RCVWFMSG_timeout\'' logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -77,7 +78,7 @@ public void preProcessRequest (DelegateExecution execution) { if ((messageType == null) || (messageType.isEmpty())) { String msg = getProcessKey(execution) + ': Missing or empty input variable \'RCVWFMSG_messageType\'' logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -88,7 +89,7 @@ public void preProcessRequest (DelegateExecution execution) { if ((correlator == null) || (correlator.isEmpty())) { String msg = getProcessKey(execution) + ': Missing or empty input variable \'RCVWFMSG_correlator\'' logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -100,7 +101,7 @@ public void preProcessRequest (DelegateExecution execution) { } catch (Exception e) { String msg = 'Caught exception in ' + method + ": " + e logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy index a7bb707dff..f013fa8698 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy @@ -20,7 +20,9 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.scripts; +package org.onap.so.bpmn.common.scripts + +import org.onap.so.logger.LoggingAnchor; import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.logger.ErrorCode; @@ -73,7 +75,7 @@ public class SDNCAdapter extends AbstractServiceTaskProcessor { def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution)) execution.setVariable("BasicAuthHeaderValue",encodedString) } catch (IOException ex) { - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Unable to encode username password string", "BPMN", ErrorCode.UnknownError.getValue()); } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy index fdd53b2f05..449f4e3222 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.client.HttpClientFactory import org.onap.so.logger.ErrorCode @@ -86,7 +87,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { if (sdncAdapterEndpoint == null || sdncAdapterEndpoint.isEmpty()) { String msg = getProcessKey(execution) + ': mso:adapters:sdnc:rest:endpoint URN mapping is not defined' logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -107,7 +108,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { if (sdncRequestId == null || sdncRequestId.isEmpty()) { String msg = getProcessKey(execution) + ': no sdncRequestId in ' + requestType logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -122,7 +123,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { if (bpNotificationUrl == null || bpNotificationUrl.isEmpty()) { String msg = getProcessKey(execution) + ': no bpNotificationUrl in ' + requestType logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -139,7 +140,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { } else { String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -154,7 +155,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { if (basicAuthValue == null || basicAuthValue.isEmpty()) { logger.debug(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined") - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN", ErrorCode.UnknownError.getValue()); } else { @@ -163,7 +164,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString) } catch (IOException ex) { logger.debug(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter") - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter", "BPMN", ErrorCode.UnknownError.getValue(), ex); } @@ -195,7 +196,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { } catch (Exception e) { String msg = 'Caught exception in ' + method + ": " + e logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -243,7 +244,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { } else { String msg = 'Unsupported HTTP method "' + sdncAdapterMethod + '" in ' + method + ": " + e logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -257,7 +258,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { } catch (Exception e) { String msg = 'Caught exception in ' + method + ": " + e logger.debug(msg, e) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -368,7 +369,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { } catch (Exception e) { String msg = 'Caught exception in ' + method + ": " + e logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -394,7 +395,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { } catch (Exception e) { String msg = 'Caught exception in ' + method + ": " + e logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy index e56091ad65..62c7bb5adf 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.ErrorCode import java.text.SimpleDateFormat @@ -85,7 +86,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { if (sdncAdapterEndpoint == null || sdncAdapterEndpoint.isEmpty()) { String msg = getProcessKey(execution) + ': mso:adapters:sdnc:rest:endpoint URN mapping is not defined' logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -106,7 +107,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { if (sdncRequestId == null || sdncRequestId.isEmpty()) { String msg = getProcessKey(execution) + ': no sdncRequestId in ' + requestType logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -121,7 +122,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { if (bpNotificationUrl == null || bpNotificationUrl.isEmpty()) { String msg = getProcessKey(execution) + ': no bpNotificationUrl in ' + requestType logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -132,7 +133,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { } else { String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -150,7 +151,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { if (basicAuthValue == null || basicAuthValue.isEmpty()) { logger.debug(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined") - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN", ErrorCode.UnknownError.getValue()); } else { @@ -159,7 +160,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString) } catch (IOException ex) { logger.debug(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter") - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter", "BPMN", ErrorCode.UnknownError.getValue(), ex); } @@ -191,7 +192,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { } catch (Exception e) { String msg = 'Caught exception in ' + method + ": " + e logger.debug(msg) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy index eb832224db..f24eda813d 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy @@ -20,8 +20,9 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.scripts; +package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor; import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.L3Network @@ -257,7 +258,7 @@ class SDNCAdapterUtils { def callbackUrl = (String)UrnPropertiesReader.getVariable('mso.workflow.sdncadapter.callback',execution) if (callbackUrl == null || callbackUrl.trim() == "") { - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'mso:workflow:sdncadapter:callback URN is not set', "BPMN", ErrorCode.UnknownError.getValue()); workflowException(execution, 'Internal Error', 9999) // TODO: what message and error code? @@ -395,7 +396,7 @@ class SDNCAdapterUtils { def callbackUrl = (String)UrnPropertiesReader.getVariable('mso.workflow.sdncadapter.callback',execution) if (callbackUrl == null || callbackUrl.trim() == "") { - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'mso:workflow:sdncadapter:callback URN is not set', "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Internal Error - During PreProcess Request") @@ -468,7 +469,7 @@ class SDNCAdapterUtils { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error") @@ -973,7 +974,7 @@ class SDNCAdapterUtils { } }else { - logger.warn("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_WARNING, + logger.warn(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_WARNING, 'sdncAdapter did not complete successfully, sdncAdapter Success Indicator was false ', "BPMN", ErrorCode.UnknownError, 'sdncAdapter did not complete successfully, sdncAdapter Success Indicator was false ') @@ -983,7 +984,7 @@ class SDNCAdapterUtils { } if (response == null || response.trim().equals("")) { - logger.warn("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_WARNING, + logger.warn(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_WARNING, 'sdncAdapter workflow response is empty', "BPMN", ErrorCode.UnknownError, 'sdncAdapter workflow response is empty') execution.setVariable("L3HLAB_rollback", true) @@ -996,7 +997,7 @@ class SDNCAdapterUtils { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught ' + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught ' + 'exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable(prefix+"ResponseCode",400) execution.setVariable("L3HLAB_rollback", true) diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/TrinityExceptionUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/TrinityExceptionUtil.groovy index 615c977a1e..30964aa4ec 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/TrinityExceptionUtil.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/TrinityExceptionUtil.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.DelegateExecution import org.apache.commons.lang3.* import org.onap.so.logger.ErrorCode @@ -215,7 +216,7 @@ class TrinityExceptionUtil { if(message != null) { execution.setVariable(prefix+"ErrorResponse",message) - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Fault", "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Fault", "BPMN", ErrorCode.UnknownError.getValue(), execution.getVariable(prefix+"ErrorResponse")); return message @@ -311,7 +312,7 @@ class TrinityExceptionUtil { execution.setVariable(prefix+"err", myErr) execution.setVariable(prefix+"errTxt", messageTxt) execution.setVariable(prefix+"errVariables", msgVars) - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Fault", "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Fault", "BPMN", ErrorCode.UnknownError.getValue(), execution.getVariable(prefix+"ErrorResponse")); return message diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy index a40bf59097..8f409fa13e 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.GenericVnf @@ -182,7 +183,7 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { if (newPersonaModelId != null || newPersonaModelVersion != null) { if (newPersonaModelId != genericVnf.getModelInvariantId()) { def msg = 'Can\'t update Generic VNF ' + vnfId + ' since there is \'persona-model-id\' mismatch between the current and new values' - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()) throw new Exception(msg) } @@ -226,6 +227,8 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { try { getAAIClient().update(uri,payload) + execution.setVariable('UAAIGenVnf_updateGenericVnfResponseCode', 200) + execution.setVariable('UAAIGenVnf_updateGenericVnfResponse', "Success") } catch (Exception ex) { logger.debug('Exception occurred while executing AAI PATCH: {}', ex.getMessage(), ex) execution.setVariable('UAAIGenVnf_updateGenericVnfResponseCode', 500) diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VfModuleBase.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VfModuleBase.groovy index c4ef165f63..20aeb11c5f 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VfModuleBase.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VfModuleBase.groovy @@ -9,9 +9,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.ErrorCode; import javax.xml.parsers.DocumentBuilder @@ -40,839 +41,926 @@ public abstract class VfModuleBase extends AbstractServiceTaskProcessor { private static final Logger logger = LoggerFactory.getLogger( VfModuleBase.class); - protected XmlParser xmlParser = new XmlParser() - - /** - * Get the XmlParser. - * - * @return the XmlParser. - */ - protected XmlParser getXmlParser() { - return xmlParser - } - - /** - * Find the VF Module with specified ID in the specified Generic VF. If no such - * VF Module is found, null is returned. - * - * @param genericVnf The Generic VNF in which to search for the specified VF Moduel. - * @param vfModuleId The ID of the VF Module for which to search. - * @return a VFModule object for the found VF Module or null if no VF Module is found. - */ - protected VfModule findVfModule(String genericVnf, String vfModuleId) { - - def genericVnfNode = xmlParser.parseText(genericVnf) - def vfModulesNode = utils.getChildNode(genericVnfNode, 'vf-modules') - if (vfModulesNode == null) { - return null - } - def vfModuleList = utils.getIdenticalChildren(vfModulesNode, 'vf-module') - for (vfModuleNode in vfModuleList) { - def vfModuleIdNode = utils.getChildNode(vfModuleNode, 'vf-module-id') - if ((vfModuleIdNode != null) && (vfModuleIdNode.text().equals(vfModuleId))) { - return new VfModule(vfModuleNode, (vfModuleList.size() == 1)) - } - } - return null - } - - /** - * Transform all '*_network' parameter specifications from the incoming '*-params' root - * element to a corresponding list of 'vnf-networks' specifications (typically used when - * invoking the VNF Rest Adpater). Each element in '*-params' whose name attribute ends - * with '_network' is used to create an 'vnf-networks' element. - * - * @param paramsNode A Node representing a '*-params' element. - * @return a String of 'vnf-networks' elements, one for each 'param' element whose name - * attribute ends with '_network'. - */ - protected String transformNetworkParamsToVnfNetworks(String paramsRootXml) { - if ((paramsRootXml == null) || (paramsRootXml.isEmpty())) { - return '' - } - def String vnfNetworks = '' - try { - paramsRootXml = utils.removeXmlNamespaces(paramsRootXml) - def paramsNode = xmlParser.parseText(paramsRootXml) - def params = utils.getIdenticalChildren(paramsNode, 'param') - for (param in params) { - def String attrName = (String) param.attribute('name') - if (attrName.endsWith('_network')) { - def networkRole = attrName.substring(0, (attrName.length()-'_network'.length())) - def networkName = param.text() - String vnfNetwork = """ + protected XmlParser xmlParser = new XmlParser() + + /** + * Get the XmlParser. + * + * @return the XmlParser. + */ + protected XmlParser getXmlParser() { + return xmlParser + } + + /** + * Find the VF Module with specified ID in the specified Generic VF. If no such + * VF Module is found, null is returned. + * + * @param genericVnf The Generic VNF in which to search for the specified VF Moduel. + * @param vfModuleId The ID of the VF Module for which to search. + * @return a VFModule object for the found VF Module or null if no VF Module is found. + */ + protected VfModule findVfModule(String genericVnf, String vfModuleId) { + + def genericVnfNode = xmlParser.parseText(genericVnf) + def vfModulesNode = utils.getChildNode(genericVnfNode, 'vf-modules') + if (vfModulesNode == null) { + return null + } + def vfModuleList = utils.getIdenticalChildren(vfModulesNode, 'vf-module') + for (vfModuleNode in vfModuleList) { + def vfModuleIdNode = utils.getChildNode(vfModuleNode, 'vf-module-id') + if ((vfModuleIdNode != null) && (vfModuleIdNode.text().equals(vfModuleId))) { + return new VfModule(vfModuleNode, (vfModuleList.size() == 1)) + } + } + return null + } + + /** + * Transform all '*_network' parameter specifications from the incoming '*-params' root + * element to a corresponding list of 'vnf-networks' specifications (typically used when + * invoking the VNF Rest Adpater). Each element in '*-params' whose name attribute ends + * with '_network' is used to create an 'vnf-networks' element. + * + * @param paramsNode A Node representing a '*-params' element. + * @return a String of 'vnf-networks' elements, one for each 'param' element whose name + * attribute ends with '_network'. + */ + protected String transformNetworkParamsToVnfNetworks(String paramsRootXml) { + if ((paramsRootXml == null) || (paramsRootXml.isEmpty())) { + return '' + } + def String vnfNetworks = '' + try { + paramsRootXml = utils.removeXmlNamespaces(paramsRootXml) + def paramsNode = xmlParser.parseText(paramsRootXml) + def params = utils.getIdenticalChildren(paramsNode, 'param') + for (param in params) { + def String attrName = (String) param.attribute('name') + if (attrName.endsWith('_network')) { + def networkRole = attrName.substring(0, (attrName.length()-'_network'.length())) + def networkName = param.text() + String vnfNetwork = """ <vnf-networks> <network-role>${MsoUtils.xmlEscape(networkRole)}</network-role> <network-name>${MsoUtils.xmlEscape(networkName)}</network-name> </vnf-networks> """ - vnfNetworks = vnfNetworks + vnfNetwork - } - } - } catch (Exception e) { - logger.warn("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_WARNING.toString(), - 'Exception transforming network params to vnfNetworks', "BPMN", - ErrorCode.UnknownError.getValue(), 'Exception is: \n' + e); - } - return vnfNetworks - } - - /** - * Transform the parameter specifications from the incoming '*-params' root element to - * a corresponding list of 'entry's (typically used when invoking the VNF Rest Adpater). - * Each element in '*-params' is used to create an 'entry' element. - * - * @param paramsNode A Node representing a '*-params' element. - * @return a String of 'entry' elements, one for each 'param' element. - */ - protected String transformParamsToEntries(String paramsRootXml) { - if ((paramsRootXml == null) || (paramsRootXml.isEmpty())) { - return '' - } - def String entries = '' - try { - paramsRootXml = utils.removeXmlNamespaces(paramsRootXml) - def paramsNode = xmlParser.parseText(paramsRootXml) - def params = utils.getIdenticalChildren(paramsNode, 'param') - for (param in params) { - def key = (String) param.attribute('name') - if (key == null) { - key = '' - } - def value = (String) param.text() - String entry = """ + vnfNetworks = vnfNetworks + vnfNetwork + } + } + } catch (Exception e) { + logger.warn(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_WARNING.toString(), + 'Exception transforming network params to vnfNetworks', "BPMN", + ErrorCode.UnknownError.getValue(), 'Exception is: \n' + e); + } + return vnfNetworks + } + + /** + * Transform the parameter specifications from the incoming '*-params' root element to + * a corresponding list of 'entry's (typically used when invoking the VNF Rest Adpater). + * Each element in '*-params' is used to create an 'entry' element. + * + * @param paramsNode A Node representing a '*-params' element. + * @return a String of 'entry' elements, one for each 'param' element. + */ + protected String transformParamsToEntries(String paramsRootXml) { + if ((paramsRootXml == null) || (paramsRootXml.isEmpty())) { + return '' + } + def String entries = '' + try { + paramsRootXml = utils.removeXmlNamespaces(paramsRootXml) + def paramsNode = xmlParser.parseText(paramsRootXml) + def params = utils.getIdenticalChildren(paramsNode, 'param') + for (param in params) { + def key = (String) param.attribute('name') + if (key == null) { + key = '' + } + def value = (String) param.text() + String entry = """ <entry> <key>${MsoUtils.xmlEscape(key)}</key> <value>${MsoUtils.xmlEscape(value)}</value> </entry> """ - entries = entries + entry - } - } catch (Exception e) { - logger.warn("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_WARNING.toString(), - 'Exception transforming params to entries', "BPMN", - ErrorCode.UnknownError.getValue(), 'Exception transforming params to entries' + e); - } - return entries - } - - /** - * Transform the parameter specifications from the incoming '*-params' root element to - * a corresponding list of 'entry's (typically used when invoking the VNF Rest Adpater). - * Each element in '*-params' is used to create an 'entry' element. - * - * @param paramsNode A Node representing a '*-params' element. - * @return a String of 'entry' elements, one for each 'param' element. - */ - protected String transformVolumeParamsToEntries(String paramsRootXml) { - if ((paramsRootXml == null) || (paramsRootXml.isEmpty())) { - return '' - } - def String entries = '' - try { - paramsRootXml = utils.removeXmlNamespaces(paramsRootXml) - def paramsNode = xmlParser.parseText(paramsRootXml) - def params = utils.getIdenticalChildren(paramsNode, 'param') - for (param in params) { - def key = (String) param.attribute('name') - if (key == null) { - key = '' - } - if ( !(key in ['vnf_id', 'vnf_name', 'vf_module_id', 'vf_module_name'])) { - def value = (String) param.text() - String entry = """ + entries = entries + entry + } + } catch (Exception e) { + logger.warn(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_WARNING.toString(), + 'Exception transforming params to entries', "BPMN", + ErrorCode.UnknownError.getValue(), 'Exception transforming params to entries' + e); + } + return entries + } + + /** + * Transform the parameter specifications from the incoming '*-params' root element to + * a corresponding list of 'entry's (typically used when invoking the VNF Rest Adpater). + * Each element in '*-params' is used to create an 'entry' element. + * + * @param paramsNode A Node representing a '*-params' element. + * @return a String of 'entry' elements, one for each 'param' element. + */ + protected String transformVolumeParamsToEntries(String paramsRootXml) { + if ((paramsRootXml == null) || (paramsRootXml.isEmpty())) { + return '' + } + def String entries = '' + try { + paramsRootXml = utils.removeXmlNamespaces(paramsRootXml) + def paramsNode = xmlParser.parseText(paramsRootXml) + def params = utils.getIdenticalChildren(paramsNode, 'param') + for (param in params) { + def key = (String) param.attribute('name') + if (key == null) { + key = '' + } + if ( !(key in [ + 'vnf_id', + 'vnf_name', + 'vf_module_id', + 'vf_module_name' + ])) { + def value = (String) param.text() + String entry = """ <entry> <key>${MsoUtils.xmlEscape(key)}</key> <value>${MsoUtils.xmlEscape(value)}</value> </entry> """ - entries = entries + entry - } - } - } catch (Exception e) { - logger.warn("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_WARNING.toString(), - 'Exception transforming params to entries', "BPMN", - ErrorCode.UnknownError.getValue(), 'Exception transforming params to entries' + e); - } - return entries - } - - /* - * Parses VNF parameters passed in on the incoming requests and SDNC parameters returned from SDNC get response - * and puts them into the format expected by VNF adapter. - * @param vnfParamsMap - map of VNF parameters passed in the request body - * @param sdncGetResponse - response string from SDNC GET topology request - * @param vnfId - * @param vnfName - * @param vfModuleId - * @param vfModuleName - * @param vfModuleIndex - can be null - * @return a String of key/value entries for vfModuleParams - */ - - - protected String buildVfModuleParams(Map<String, String> vnfParamsMap, String sdncGetResponse, String vnfId, String vnfName, - String vfModuleId, String vfModuleName, String vfModuleIndex, String environmentContext, String workloadContext) { - - //Get SDNC Response Data - - String data = utils.getNodeXml(sdncGetResponse, "response-data") - - String serviceData = utils.getNodeXml(data, "service-data") - serviceData = utils.removeXmlPreamble(serviceData) - serviceData = utils.removeXmlNamespaces(serviceData) - String vnfRequestInfo = utils.getNodeXml(serviceData, "vnf-request-information") - String oldVnfId = utils.getNodeXml(vnfRequestInfo, "vnf-id") - oldVnfId = utils.removeXmlPreamble(oldVnfId) - oldVnfId = utils.removeXmlNamespaces(oldVnfId) - serviceData = serviceData.replace(oldVnfId, "") - def vnfId1 = utils.getNodeText(serviceData, "vnf-id") - - Map<String, String> paramsMap = new HashMap<String, String>() - - if (vfModuleIndex != null) { - paramsMap.put("vf_module_index", "${vfModuleIndex}") - } - - // Add-on data - paramsMap.put("vnf_id", "${vnfId}") - paramsMap.put("vnf_name", "${vnfName}") - paramsMap.put("vf_module_id", "${vfModuleId}") - paramsMap.put("vf_module_name", "${vfModuleName}") - paramsMap.put("environment_context", "${environmentContext}") - paramsMap.put("workload_context", "${workloadContext}") - - InputSource source = new InputSource(new StringReader(data)); - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - docFactory.setNamespaceAware(true) - DocumentBuilder docBuilder = docFactory.newDocumentBuilder() - Document responseXml = docBuilder.parse(source) - - - // Availability Zones Data - - NodeList aZonesList = responseXml.getElementsByTagNameNS("*", "availability-zones") - String aZonePosition = "0" - for (int z = 0; z < aZonesList.getLength(); z++) { - Node node = aZonesList.item(z) - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) node - String aZoneValue = utils.getElementText(eElement, "availability-zone") - aZonePosition = z.toString() - paramsMap.put("availability_zone_${aZonePosition}", "${aZoneValue}") - } - } - - // Map of network-roles and network-tags from vm-networks - - NodeList vmNetworksListGlobal = responseXml.getElementsByTagNameNS("*", "vm-networks") - Map<String, String> networkRoleMap = new HashMap<String, String>() - for(int n = 0; n < vmNetworksListGlobal.getLength(); n++){ - Node nodeNetworkKey = vmNetworksListGlobal.item(n) - if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) { - Element eElementNetworkKey = (Element) nodeNetworkKey - String networkRole = utils.getElementText(eElementNetworkKey, "network-role") - String networkRoleValue = utils.getElementText(eElementNetworkKey, "network-role-tag") - if (networkRoleValue.isEmpty()) { - networkRoleValue = networkRole - } - networkRoleMap.put(networkRole, networkRoleValue) - } - } - - // VNF Networks Data - - StringBuilder sbNet = new StringBuilder() - - NodeList vnfNetworkList = responseXml.getElementsByTagNameNS("*", "vnf-networks") - for (int x = 0; x < vnfNetworkList.getLength(); x++) { - Node node = vnfNetworkList.item(x) - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) node - String vnfNetworkKey = utils.getElementText(eElement, "network-role-tag") - String networkRole = utils.getElementText(eElement, "network-role") - if (vnfNetworkKey.isEmpty()) { - vnfNetworkKey = networkRoleMap.get(networkRole) - if (vnfNetworkKey == null || vnfNetworkKey.isEmpty()) { - vnfNetworkKey = networkRole - } - } - String vnfNetworkNeutronIdValue = utils.getElementText(eElement, "neutron-id") - String vnfNetworkNetNameValue = utils.getElementText(eElement, "network-name") - String vnfNetworkSubNetIdValue = utils.getElementText(eElement, "subnet-id") - String vnfNetworkV6SubNetIdValue = utils.getElementText(eElement, "ipv6-subnet-id") - String vnfNetworkNetFqdnValue = utils.getElementText(eElement, "contrail-network-fqdn") - paramsMap.put("${vnfNetworkKey}_net_id", "${vnfNetworkNeutronIdValue}") - paramsMap.put("${vnfNetworkKey}_net_name", "${vnfNetworkNetNameValue}") - paramsMap.put("${vnfNetworkKey}_subnet_id", "${vnfNetworkSubNetIdValue}") - paramsMap.put("${vnfNetworkKey}_v6_subnet_id", "${vnfNetworkV6SubNetIdValue}") - paramsMap.put("${vnfNetworkKey}_net_fqdn", "${vnfNetworkNetFqdnValue}") - - NodeList sriovVlanFilterList = eElement.getElementsByTagNameNS("*","sriov-vlan-filter-list") - StringBuffer sriovFilterBuf = new StringBuffer() - String values = "" - for(int i = 0; i < sriovVlanFilterList.getLength(); i++){ - Node node1 = sriovVlanFilterList.item(i) - if (node1.getNodeType() == Node.ELEMENT_NODE) { - Element eElement1 = (Element) node1 - String value = utils.getElementText(eElement1, "sriov-vlan-filter") - if (i != sriovVlanFilterList.getLength() - 1) { - values = sriovFilterBuf.append(value + ",") - } - else { - values = sriovFilterBuf.append(value); - } - } - } - if (!values.isEmpty()) { - paramsMap.put("${vnfNetworkKey}_ATT_VF_VLAN_FILTER", "${values}") - } - } - } - - // VNF-VMS Data - - def key - def value - def networkKey - def networkValue - def floatingIPKey - def floatingIPKeyValue - def floatingIPV6Key - def floatingIPV6KeyValue - StringBuilder sb = new StringBuilder() - - NodeList vmsList = responseXml.getElementsByTagNameNS("*","vnf-vms") - for (int x = 0; x < vmsList.getLength(); x++) { - Node node = vmsList.item(x) - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) node - key = utils.getElementText(eElement, "vm-type") - String values - String position = "0" - StringBuilder sb1 = new StringBuilder() - NodeList valueList = eElement.getElementsByTagNameNS("*","vm-names") - NodeList vmNetworksList = eElement.getElementsByTagNameNS("*","vm-networks") - for(int i = 0; i < valueList.getLength(); i++){ - Node node1 = valueList.item(i) - if (node1.getNodeType() == Node.ELEMENT_NODE) { - Element eElement1 = (Element) node1 - value = utils.getElementText(eElement1, "vm-name") - if (i != valueList.getLength() - 1) { - values = sb1.append(value + ",") - } - else { - values = sb1.append(value); - } - position = i.toString() - paramsMap.put("${key}_name_${position}", "${value}") - } - } - for(int n = 0; n < vmNetworksList.getLength(); n++){ - String floatingIpKeyValueStr = "" - String floatingIpV6KeyValueStr = "" - Node nodeNetworkKey = vmNetworksList.item(n) - if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) { - Element eElementNetworkKey = (Element) nodeNetworkKey - String ipAddressValues - String ipV6AddressValues - String networkPosition = "0" - StringBuilder sb2 = new StringBuilder() - StringBuilder sb3 = new StringBuilder() - StringBuilder sb4 = new StringBuilder() - networkKey = utils.getElementText(eElementNetworkKey, "network-role-tag") - if (networkKey.isEmpty()) { - networkKey = utils.getElementText(eElementNetworkKey, "network-role") - } - floatingIPKey = key + '_' + networkKey + '_floating_ip' - floatingIPKeyValue = utils.getElementText(eElementNetworkKey, "floating-ip") - if(!floatingIPKeyValue.isEmpty()){ - paramsMap.put("$floatingIPKey", "$floatingIPKeyValue") - } - floatingIPV6Key = key + '_' + networkKey + '_floating_v6_ip' - floatingIPV6KeyValue = utils.getElementText(eElementNetworkKey, "floating-ip-v6") - if(!floatingIPV6KeyValue.isEmpty()){ - paramsMap.put("$floatingIPV6Key", "$floatingIPV6KeyValue") - } - NodeList networkIpsList = eElementNetworkKey.getElementsByTagNameNS("*","network-ips") - for(int a = 0; a < networkIpsList.getLength(); a++){ - Node ipAddress = networkIpsList.item(a) - if (ipAddress.getNodeType() == Node.ELEMENT_NODE) { - Element eElementIpAddress = (Element) ipAddress - String ipAddressValue = utils.getElementText(eElementIpAddress, "ip-address") - if (a != networkIpsList.getLength() - 1) { - ipAddressValues = sb2.append(ipAddressValue + ",") - } - else { - ipAddressValues = sb2.append(ipAddressValue); - } - networkPosition = a.toString() - paramsMap.put("${key}_${networkKey}_ip_${networkPosition}", "${ipAddressValue}") - } - } - - paramsMap.put("${key}_${networkKey}_ips", "${ipAddressValues}") - - NodeList interfaceRoutePrefixesList = eElementNetworkKey.getElementsByTagNameNS("*","interface-route-prefixes") - String interfaceRoutePrefixValues = sb3.append("[") - - for(int a = 0; a < interfaceRoutePrefixesList.getLength(); a++){ - Node interfaceRoutePrefix = interfaceRoutePrefixesList.item(a) - if (interfaceRoutePrefix.getNodeType() == Node.ELEMENT_NODE) { - Element eElementInterfaceRoutePrefix = (Element) interfaceRoutePrefix - String interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix-cidr") - if (interfaceRoutePrefixValue == null || interfaceRoutePrefixValue.isEmpty()) { - interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix") - } - if (a != interfaceRoutePrefixesList.getLength() - 1) { - interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}" + ",") - } - else { - interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}") - } - } - } - interfaceRoutePrefixValues = sb3.append("]") - if (interfaceRoutePrefixesList.getLength() > 0) { - paramsMap.put("${key}_${networkKey}_route_prefixes", "${interfaceRoutePrefixValues}") - } - - NodeList networkIpsV6List = eElementNetworkKey.getElementsByTagNameNS("*","network-ips-v6") - for(int a = 0; a < networkIpsV6List.getLength(); a++){ - Node ipV6Address = networkIpsV6List.item(a) - if (ipV6Address.getNodeType() == Node.ELEMENT_NODE) { - Element eElementIpV6Address = (Element) ipV6Address - String ipV6AddressValue = utils.getElementText(eElementIpV6Address, "ip-address-ipv6") - if (a != networkIpsV6List.getLength() - 1) { - ipV6AddressValues = sb4.append(ipV6AddressValue + ",") - } - else { - ipV6AddressValues = sb4.append(ipV6AddressValue); - } - networkPosition = a.toString() - paramsMap.put("${key}_${networkKey}_v6_ip_${networkPosition}", "${ipV6AddressValue}") - } - } - paramsMap.put("${key}_${networkKey}_v6_ips", "${ipV6AddressValues}") - } - } - paramsMap.put("${key}_names", "${values}") - } - } - //SDNC Response Params - String sdncResponseParams = "" - List<String> sdncResponseParamsToSkip = ["vnf_id", "vf_module_id", "vnf_name", "vf_module_name"] - String vnfParamsChildNodes = utils.getChildNodes(data, "vnf-parameters") - if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){ - // No SDNC params - }else{ - NodeList paramsList = responseXml.getElementsByTagNameNS("*", "vnf-parameters") - for (int z = 0; z < paramsList.getLength(); z++) { - Node node = paramsList.item(z) - Element eElement = (Element) node - String vnfParameterName = utils.getElementText(eElement, "vnf-parameter-name") - if (!sdncResponseParamsToSkip.contains(vnfParameterName)) { - String vnfParameterValue = utils.getElementText(eElement, "vnf-parameter-value") - paramsMap.put("${vnfParameterName}", "${vnfParameterValue}") - } - } - } - - // Parameters received from the request should overwrite any parameters received from SDNC - if (vnfParamsMap != null) { - for (Map.Entry<String, String> entry : vnfParamsMap.entrySet()) { - String vnfKey = entry.getKey() - String vnfValue = entry.getValue() - paramsMap.put("$vnfKey", "$vnfValue") - } - } - - StringBuilder sbParams = new StringBuilder() - def vfModuleParams = "" - for (Map.Entry<String, String> entry : paramsMap.entrySet()) { - String paramsXml - String paramName = entry.getKey() - String paramValue = entry.getValue() - paramsXml = - """<entry> + entries = entries + entry + } + } + } catch (Exception e) { + logger.warn(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_WARNING.toString(), + 'Exception transforming params to entries', "BPMN", + ErrorCode.UnknownError.getValue(), 'Exception transforming params to entries' + e); + } + return entries + } + + /* + * Parses VNF parameters passed in on the incoming requests and SDNC parameters returned from SDNC get response + * and puts them into the format expected by VNF adapter. + * @param vnfParamsMap - map of VNF parameters passed in the request body + * @param sdncGetResponse - response string from SDNC GET topology request + * @param vnfId + * @param vnfName + * @param vfModuleId + * @param vfModuleName + * @param vfModuleIndex - can be null + * @return a String of key/value entries for vfModuleParams + */ + + + protected String buildVfModuleParams(Map<String, String> vnfParamsMap, String sdncGetResponse, String vnfId, String vnfName, + String vfModuleId, String vfModuleName, String vfModuleIndex, String environmentContext, String workloadContext) { + + //Get SDNC Response Data + + String data = utils.getNodeXml(sdncGetResponse, "response-data") + + String serviceData = utils.getNodeXml(data, "service-data") + serviceData = utils.removeXmlPreamble(serviceData) + serviceData = utils.removeXmlNamespaces(serviceData) + String vnfRequestInfo = utils.getNodeXml(serviceData, "vnf-request-information") + String oldVnfId = utils.getNodeXml(vnfRequestInfo, "vnf-id") + oldVnfId = utils.removeXmlPreamble(oldVnfId) + oldVnfId = utils.removeXmlNamespaces(oldVnfId) + serviceData = serviceData.replace(oldVnfId, "") + def vnfId1 = utils.getNodeText(serviceData, "vnf-id") + + Map<String, String> paramsMap = new HashMap<String, String>() + + if (vfModuleIndex != null) { + paramsMap.put("vf_module_index", "${vfModuleIndex}") + } + + // Add-on data + paramsMap.put("vnf_id", "${vnfId}") + paramsMap.put("vnf_name", "${vnfName}") + paramsMap.put("vf_module_id", "${vfModuleId}") + paramsMap.put("vf_module_name", "${vfModuleName}") + paramsMap.put("environment_context", "${environmentContext}") + paramsMap.put("workload_context", "${workloadContext}") + + InputSource source = new InputSource(new StringReader(data)); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setNamespaceAware(true) + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document responseXml = docBuilder.parse(source) + + + // Availability Zones Data + + NodeList aZonesList = responseXml.getElementsByTagNameNS("*", "availability-zones") + String aZonePosition = "0" + for (int z = 0; z < aZonesList.getLength(); z++) { + Node node = aZonesList.item(z) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + String aZoneValue = utils.getElementText(eElement, "availability-zone") + aZonePosition = z.toString() + paramsMap.put("availability_zone_${aZonePosition}", "${aZoneValue}") + } + } + + // Map of network-roles and network-tags from vm-networks + + NodeList vmNetworksListGlobal = responseXml.getElementsByTagNameNS("*", "vm-networks") + Map<String, String> networkRoleMap = new HashMap<String, String>() + for(int n = 0; n < vmNetworksListGlobal.getLength(); n++){ + Node nodeNetworkKey = vmNetworksListGlobal.item(n) + if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) { + Element eElementNetworkKey = (Element) nodeNetworkKey + String networkRole = utils.getElementText(eElementNetworkKey, "network-role") + String networkRoleValue = utils.getElementText(eElementNetworkKey, "network-role-tag") + if (networkRoleValue.isEmpty()) { + networkRoleValue = networkRole + } + networkRoleMap.put(networkRole, networkRoleValue) + } + } + + // VNF Networks Data + + StringBuilder sbNet = new StringBuilder() + + NodeList vnfNetworkList = responseXml.getElementsByTagNameNS("*", "vnf-networks") + for (int x = 0; x < vnfNetworkList.getLength(); x++) { + Node node = vnfNetworkList.item(x) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + String vnfNetworkKey = utils.getElementText(eElement, "network-role-tag") + String networkRole = utils.getElementText(eElement, "network-role") + if (vnfNetworkKey.isEmpty()) { + vnfNetworkKey = networkRoleMap.get(networkRole) + if (vnfNetworkKey == null || vnfNetworkKey.isEmpty()) { + vnfNetworkKey = networkRole + } + } + String vnfNetworkNeutronIdValue = utils.getElementText(eElement, "neutron-id") + String vnfNetworkNetNameValue = utils.getElementText(eElement, "network-name") + String vnfNetworkSubNetIdValue = utils.getElementText(eElement, "subnet-id") + String vnfNetworkV6SubNetIdValue = utils.getElementText(eElement, "ipv6-subnet-id") + String vnfNetworkNetFqdnValue = utils.getElementText(eElement, "contrail-network-fqdn") + paramsMap.put("${vnfNetworkKey}_net_id", "${vnfNetworkNeutronIdValue}") + paramsMap.put("${vnfNetworkKey}_net_name", "${vnfNetworkNetNameValue}") + paramsMap.put("${vnfNetworkKey}_subnet_id", "${vnfNetworkSubNetIdValue}") + paramsMap.put("${vnfNetworkKey}_v6_subnet_id", "${vnfNetworkV6SubNetIdValue}") + paramsMap.put("${vnfNetworkKey}_net_fqdn", "${vnfNetworkNetFqdnValue}") + + NodeList sriovVlanFilterList = eElement.getElementsByTagNameNS("*","sriov-vlan-filter-list") + StringBuffer sriovFilterBuf = new StringBuffer() + String values = "" + for(int i = 0; i < sriovVlanFilterList.getLength(); i++){ + Node node1 = sriovVlanFilterList.item(i) + if (node1.getNodeType() == Node.ELEMENT_NODE) { + Element eElement1 = (Element) node1 + String value = utils.getElementText(eElement1, "sriov-vlan-filter") + if (i != sriovVlanFilterList.getLength() - 1) { + values = sriovFilterBuf.append(value + ",") + } + else { + values = sriovFilterBuf.append(value); + } + } + } + if (!values.isEmpty()) { + paramsMap.put("${vnfNetworkKey}_ATT_VF_VLAN_FILTER", "${values}") + } + } + } + + // VNF-VMS Data + + def key + def value + def networkKey + def networkValue + def floatingIPKey + def floatingIPKeyValue + def floatingIPV6Key + def floatingIPV6KeyValue + StringBuilder sb = new StringBuilder() + + NodeList vmsList = responseXml.getElementsByTagNameNS("*","vnf-vms") + for (int x = 0; x < vmsList.getLength(); x++) { + Node node = vmsList.item(x) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + key = utils.getElementText(eElement, "vm-type") + String values + String position = "0" + StringBuilder sb1 = new StringBuilder() + NodeList valueList = eElement.getElementsByTagNameNS("*","vm-names") + NodeList vmNetworksList = eElement.getElementsByTagNameNS("*","vm-networks") + for(int i = 0; i < valueList.getLength(); i++){ + Node node1 = valueList.item(i) + if (node1.getNodeType() == Node.ELEMENT_NODE) { + Element eElement1 = (Element) node1 + value = utils.getElementText(eElement1, "vm-name") + if (i != valueList.getLength() - 1) { + values = sb1.append(value + ",") + } + else { + values = sb1.append(value); + } + position = i.toString() + paramsMap.put("${key}_name_${position}", "${value}") + } + } + for(int n = 0; n < vmNetworksList.getLength(); n++){ + String floatingIpKeyValueStr = "" + String floatingIpV6KeyValueStr = "" + Node nodeNetworkKey = vmNetworksList.item(n) + if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) { + Element eElementNetworkKey = (Element) nodeNetworkKey + String ipAddressValues + String ipV6AddressValues + String networkPosition = "0" + StringBuilder sb2 = new StringBuilder() + StringBuilder sb3 = new StringBuilder() + StringBuilder sb4 = new StringBuilder() + networkKey = utils.getElementText(eElementNetworkKey, "network-role-tag") + if (networkKey.isEmpty()) { + networkKey = utils.getElementText(eElementNetworkKey, "network-role") + } + floatingIPKey = key + '_' + networkKey + '_floating_ip' + floatingIPKeyValue = utils.getElementText(eElementNetworkKey, "floating-ip") + if(!floatingIPKeyValue.isEmpty()){ + paramsMap.put("$floatingIPKey", "$floatingIPKeyValue") + } + floatingIPV6Key = key + '_' + networkKey + '_floating_v6_ip' + floatingIPV6KeyValue = utils.getElementText(eElementNetworkKey, "floating-ip-v6") + if(!floatingIPV6KeyValue.isEmpty()){ + paramsMap.put("$floatingIPV6Key", "$floatingIPV6KeyValue") + } + NodeList networkIpsList = eElementNetworkKey.getElementsByTagNameNS("*","network-ips") + for(int a = 0; a < networkIpsList.getLength(); a++){ + Node ipAddress = networkIpsList.item(a) + if (ipAddress.getNodeType() == Node.ELEMENT_NODE) { + Element eElementIpAddress = (Element) ipAddress + String ipAddressValue = utils.getElementText(eElementIpAddress, "ip-address") + if (a != networkIpsList.getLength() - 1) { + ipAddressValues = sb2.append(ipAddressValue + ",") + } + else { + ipAddressValues = sb2.append(ipAddressValue); + } + networkPosition = a.toString() + paramsMap.put("${key}_${networkKey}_ip_${networkPosition}", "${ipAddressValue}") + } + } + + paramsMap.put("${key}_${networkKey}_ips", "${ipAddressValues}") + + NodeList interfaceRoutePrefixesList = eElementNetworkKey.getElementsByTagNameNS("*","interface-route-prefixes") + String interfaceRoutePrefixValues = sb3.append("[") + + for(int a = 0; a < interfaceRoutePrefixesList.getLength(); a++){ + Node interfaceRoutePrefix = interfaceRoutePrefixesList.item(a) + if (interfaceRoutePrefix.getNodeType() == Node.ELEMENT_NODE) { + Element eElementInterfaceRoutePrefix = (Element) interfaceRoutePrefix + String interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix-cidr") + if (interfaceRoutePrefixValue == null || interfaceRoutePrefixValue.isEmpty()) { + interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix") + } + if (a != interfaceRoutePrefixesList.getLength() - 1) { + interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}" + ",") + } + else { + interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}") + } + } + } + interfaceRoutePrefixValues = sb3.append("]") + if (interfaceRoutePrefixesList.getLength() > 0) { + paramsMap.put("${key}_${networkKey}_route_prefixes", "${interfaceRoutePrefixValues}") + } + + NodeList networkIpsV6List = eElementNetworkKey.getElementsByTagNameNS("*","network-ips-v6") + for(int a = 0; a < networkIpsV6List.getLength(); a++){ + Node ipV6Address = networkIpsV6List.item(a) + if (ipV6Address.getNodeType() == Node.ELEMENT_NODE) { + Element eElementIpV6Address = (Element) ipV6Address + String ipV6AddressValue = utils.getElementText(eElementIpV6Address, "ip-address-ipv6") + if (a != networkIpsV6List.getLength() - 1) { + ipV6AddressValues = sb4.append(ipV6AddressValue + ",") + } + else { + ipV6AddressValues = sb4.append(ipV6AddressValue); + } + networkPosition = a.toString() + paramsMap.put("${key}_${networkKey}_v6_ip_${networkPosition}", "${ipV6AddressValue}") + } + } + paramsMap.put("${key}_${networkKey}_v6_ips", "${ipV6AddressValues}") + } + } + paramsMap.put("${key}_names", "${values}") + } + } + //SDNC Response Params + String sdncResponseParams = "" + List<String> sdncResponseParamsToSkip = [ + "vnf_id", + "vf_module_id", + "vnf_name", + "vf_module_name" + ] + String vnfParamsChildNodes = utils.getChildNodes(data, "vnf-parameters") + if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){ + // No SDNC params + }else{ + NodeList paramsList = responseXml.getElementsByTagNameNS("*", "vnf-parameters") + for (int z = 0; z < paramsList.getLength(); z++) { + Node node = paramsList.item(z) + Element eElement = (Element) node + String vnfParameterName = utils.getElementText(eElement, "vnf-parameter-name") + if (!sdncResponseParamsToSkip.contains(vnfParameterName)) { + String vnfParameterValue = utils.getElementText(eElement, "vnf-parameter-value") + paramsMap.put("${vnfParameterName}", "${vnfParameterValue}") + } + } + } + + // make the sdnc_directives parameter + String sdncDirectives = "{}" + StringBuilder sdncDirectivesBuilder = new StringBuilder() + sdncDirectivesBuilder.append("{ \"attributes\": [") + int pcnt = 0 + for (Map.Entry<String, String> entry : paramsMap.entrySet()) { + String attributeName = entry.getKey() + String attributeValue = entry.getValue() + if (pcnt > 0) { + sdncDirectivesBuilder.append(",") + } + pcnt++ + sdncDirectivesBuilder.append("{\"attribute_name\":\"${attributeName}\",") + sdncDirectivesBuilder.append("\"attribute_value\":\"${attributeValue}\"}") + } + if (pcnt > 0) { + sdncDirectives = sdncDirectivesBuilder.append("]}").toString() + } + paramsMap.put("sdnc_directives", "${sdncDirectives}") + + // Parameters received from the request should overwrite any parameters received from SDNC + // Also build the user_directives parameter + String userDirectives = "{}" + if (vnfParamsMap != null) { + StringBuilder userDirectivesBuilder = new StringBuilder() + userDirectivesBuilder.append("{ \"attributes\": [") + pcnt = 0 + for (Map.Entry<String, String> entry : vnfParamsMap.entrySet()) { + String vnfKey = entry.getKey() + String vnfValue = entry.getValue() + paramsMap.put("$vnfKey", "$vnfValue") + if (!"oof_directives".equals(vnfKey)) { + if (pcnt > 0) { + userDirectivesBuilder.append(",") + } + pcnt++ + userDirectivesBuilder.append("{\"attribute_name\":\"${vnfKey}\",") + userDirectivesBuilder.append("\"attribute_value\":\"${vnfValue}\"}") + } + } + if (pcnt > 0) { + userDirectives = userDirectivesBuilder.append("]}").toString() + } + } + paramsMap.put("user_directives", "${userDirectives}") + + StringBuilder sbParams = new StringBuilder() + def vfModuleParams = "" + for (Map.Entry<String, String> entry : paramsMap.entrySet()) { + String paramsXml + String paramName = entry.getKey() + String paramValue = entry.getValue() + paramsXml = + """<entry> <key>${MsoUtils.xmlEscape(paramName)}</key> <value>${MsoUtils.xmlEscape(paramValue)}</value> </entry> """ - - vfModuleParams = sbParams.append(paramsXml) - } - - return vfModuleParams - - } - - - /* - * Parses VNF parameters passed in on the incoming requests and SDNC parameters returned from SDNC get response - * for both VNF and VF Module - * and puts them into the format expected by VNF adapter. - * @param vnfParamsMap - map of VNF parameters passed in the request body - * @param vnfSdncGetResponse - response string from SDNC GET VNF topology request - * @param vfmoduleSdncGetResponse - response string from SDNC GET VF Module topology request - * @param vnfId - * @param vnfName - * @param vfModuleId - * @param vfModuleName - * @param vfModuleIndex - can be null - * @return a String of key/value entries for vfModuleParams - */ - - protected String buildVfModuleParamsFromCombinedTopologies(Map<String, String> vnfParamsMap, String vnfSdncGetResponse, String vfmoduleSdncGetResponse, String vnfId, String vnfName, - String vfModuleId, String vfModuleName, String vfModuleIndex, String environmentContext, String workloadContext) { - - // Set up initial parameters - - Map<String, String> paramsMap = new HashMap<String, String>() - - if (vfModuleIndex != null) { - paramsMap.put("vf_module_index", "${vfModuleIndex}") - } - - // Add-on data - paramsMap.put("vnf_id", "${vnfId}") - paramsMap.put("vnf_name", "${vnfName}") - paramsMap.put("vf_module_id", "${vfModuleId}") - paramsMap.put("vf_module_name", "${vfModuleName}") - paramsMap.put("environment_context","${environmentContext}") - paramsMap.put("workload_context", "${workloadContext}") - - //Get SDNC Response Data for VNF - - String vnfData = utils.getNodeXml(vnfSdncGetResponse, "response-data") - - String vnfTopology = utils.getNodeXml(vnfData, "vnf-topology") - vnfTopology = utils.removeXmlPreamble(vnfTopology) - vnfTopology = utils.removeXmlNamespaces(vnfTopology) - - InputSource sourceVnf = new InputSource(new StringReader(vnfData)); - DocumentBuilderFactory docFactoryVnf = DocumentBuilderFactory.newInstance(); - docFactoryVnf.setNamespaceAware(true) - DocumentBuilder docBuilderVnf = docFactoryVnf.newDocumentBuilder() - Document responseXmlVnf = docBuilderVnf.parse(sourceVnf) - - // Availability Zones Data - - NodeList aZonesList = responseXmlVnf.getElementsByTagNameNS("*", "availability-zones") - String aZonePosition = "0" - for (int z = 0; z < aZonesList.getLength(); z++) { - Node node = aZonesList.item(z) - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) node - String aZoneValue = utils.getElementText(eElement, "availability-zone") - aZonePosition = z.toString() - paramsMap.put("availability_zone_${aZonePosition}", "${aZoneValue}") - } - } - - //Get SDNC Response Data for VF Module - - String vfModuleData = utils.getNodeXml(vfmoduleSdncGetResponse, "response-data") - - String vfModuleTopology = utils.getNodeXml(vfModuleData, "vf-module-topology") - vfModuleTopology = utils.removeXmlPreamble(vfModuleTopology) - vfModuleTopology = utils.removeXmlNamespaces(vfModuleTopology) - String vfModuleTopologyIdentifier = utils.getNodeXml(vfModuleTopology, "vf-module-topology-identifier") - - InputSource sourceVfModule = new InputSource(new StringReader(vfModuleData)); - DocumentBuilderFactory docFactoryVfModule = DocumentBuilderFactory.newInstance(); - docFactoryVfModule.setNamespaceAware(true) - DocumentBuilder docBuilderVfModule = docFactoryVfModule.newDocumentBuilder() - Document responseXmlVfModule = docBuilderVfModule.parse(sourceVfModule) - - // Map of network-roles and network-tags from vm-networks - - NodeList vmNetworksListGlobal = responseXmlVfModule.getElementsByTagNameNS("*", "vm-networks") - Map<String, String> networkRoleMap = new HashMap<String, String>() - for(int n = 0; n < vmNetworksListGlobal.getLength(); n++){ - Node nodeNetworkKey = vmNetworksListGlobal.item(n) - if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) { - Element eElementNetworkKey = (Element) nodeNetworkKey - String networkRole = utils.getElementText(eElementNetworkKey, "network-role") - String networkRoleValue = utils.getElementText(eElementNetworkKey, "network-role-tag") - if (networkRoleValue.isEmpty()) { - networkRoleValue = networkRole - } - networkRoleMap.put(networkRole, networkRoleValue) - } - } - - // VNF Networks Data - - StringBuilder sbNet = new StringBuilder() - - NodeList vnfNetworkList = responseXmlVnf.getElementsByTagNameNS("*", "vnf-networks") - for (int x = 0; x < vnfNetworkList.getLength(); x++) { - Node node = vnfNetworkList.item(x) - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) node - String vnfNetworkKey = utils.getElementText(eElement, "network-role-tag") - String networkRole = utils.getElementText(eElement, "network-role") - if (vnfNetworkKey.isEmpty()) { - vnfNetworkKey = networkRoleMap.get(networkRole) - if (vnfNetworkKey == null || vnfNetworkKey.isEmpty()) { - vnfNetworkKey = networkRole - } - } - String vnfNetworkNeutronIdValue = utils.getElementText(eElement, "neutron-id") - String vnfNetworkNetNameValue = utils.getElementText(eElement, "network-name") - String vnfNetworkSubNetIdValue = utils.getElementText(eElement, "subnet-id") - String vnfNetworkV6SubNetIdValue = utils.getElementText(eElement, "ipv6-subnet-id") - String vnfNetworkNetFqdnValue = utils.getElementText(eElement, "contrail-network-fqdn") - paramsMap.put("${vnfNetworkKey}_net_id", "${vnfNetworkNeutronIdValue}") - paramsMap.put("${vnfNetworkKey}_net_name", "${vnfNetworkNetNameValue}") - paramsMap.put("${vnfNetworkKey}_subnet_id", "${vnfNetworkSubNetIdValue}") - paramsMap.put("${vnfNetworkKey}_v6_subnet_id", "${vnfNetworkV6SubNetIdValue}") - paramsMap.put("${vnfNetworkKey}_net_fqdn", "${vnfNetworkNetFqdnValue}") - - NodeList sriovVlanFilterList = eElement.getElementsByTagNameNS("*","sriov-vlan-filter-list") - StringBuffer sriovFilterBuf = new StringBuffer() - String values = "" - for(int i = 0; i < sriovVlanFilterList.getLength(); i++){ - Node node1 = sriovVlanFilterList.item(i) - if (node1.getNodeType() == Node.ELEMENT_NODE) { - Element eElement1 = (Element) node1 - String value = utils.getElementText(eElement1, "sriov-vlan-filter") - if (i != sriovVlanFilterList.getLength() - 1) { - values = sriovFilterBuf.append(value + ",") - } - else { - values = sriovFilterBuf.append(value); - } - } - } - if (!values.isEmpty()) { - paramsMap.put("${vnfNetworkKey}_ATT_VF_VLAN_FILTER", "${values}") - } - } - } - - - - // VMS Data - - def key - def value - def networkKey - def networkValue - def floatingIPKey - def floatingIPKeyValue - def floatingIPV6Key - def floatingIPV6KeyValue - StringBuilder sb = new StringBuilder() - - NodeList vmsList = responseXmlVfModule.getElementsByTagNameNS("*","vm") - for (int x = 0; x < vmsList.getLength(); x++) { - Node node = vmsList.item(x) - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) node - key = utils.getElementText(eElement, "vm-type") - String values - String position = "0" - StringBuilder sb1 = new StringBuilder() - NodeList valueList = eElement.getElementsByTagNameNS("*","vm-names") - NodeList vmNetworksList = eElement.getElementsByTagNameNS("*","vm-networks") - for(int i = 0; i < valueList.getLength(); i++){ - Node node1 = valueList.item(i) - if (node1.getNodeType() == Node.ELEMENT_NODE) { - Element eElement1 = (Element) node1 - value = utils.getElementText(eElement1, "vm-name") - if (i != valueList.getLength() - 1) { - values = sb1.append(value + ",") - } - else { - values = sb1.append(value); - } - position = i.toString() - paramsMap.put("${key}_name_${position}", "${value}") - } - } - for(int n = 0; n < vmNetworksList.getLength(); n++){ - String floatingIpKeyValueStr = "" - String floatingIpV6KeyValueStr = "" - Node nodeNetworkKey = vmNetworksList.item(n) - if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) { - Element eElementNetworkKey = (Element) nodeNetworkKey - String ipAddressValues - String ipV6AddressValues - String networkPosition = "0" - StringBuilder sb2 = new StringBuilder() - StringBuilder sb3 = new StringBuilder() - StringBuilder sb4 = new StringBuilder() - networkKey = utils.getElementText(eElementNetworkKey, "network-role-tag") - if (networkKey.isEmpty()) { - networkKey = utils.getElementText(eElementNetworkKey, "network-role") - } - floatingIPKey = key + '_' + networkKey + '_floating_ip' - floatingIPKeyValue = utils.getElementText(eElementNetworkKey, "floating-ip") - if(!floatingIPKeyValue.isEmpty()){ - paramsMap.put("$floatingIPKey", "$floatingIPKeyValue") - } - floatingIPV6Key = key + '_' + networkKey + '_floating_v6_ip' - floatingIPV6KeyValue = utils.getElementText(eElementNetworkKey, "floating-ip-v6") - if(!floatingIPV6KeyValue.isEmpty()){ - paramsMap.put("$floatingIPV6Key", "$floatingIPV6KeyValue") - } - NodeList networkIpsList = eElementNetworkKey.getElementsByTagNameNS("*","network-ips") - for(int a = 0; a < networkIpsList.getLength(); a++){ - Node ipAddress = networkIpsList.item(a) - if (ipAddress.getNodeType() == Node.ELEMENT_NODE) { - Element eElementIpAddress = (Element) ipAddress - String ipAddressValue = utils.getElementText(eElementIpAddress, "ip-address") - if (a != networkIpsList.getLength() - 1) { - ipAddressValues = sb2.append(ipAddressValue + ",") - } - else { - ipAddressValues = sb2.append(ipAddressValue); - } - networkPosition = a.toString() - paramsMap.put("${key}_${networkKey}_ip_${networkPosition}", "${ipAddressValue}") - } - } - - paramsMap.put("${key}_${networkKey}_ips", "${ipAddressValues}") - - NodeList interfaceRoutePrefixesList = eElementNetworkKey.getElementsByTagNameNS("*","interface-route-prefixes") - String interfaceRoutePrefixValues = sb3.append("[") - - for(int a = 0; a < interfaceRoutePrefixesList.getLength(); a++){ - Node interfaceRoutePrefix = interfaceRoutePrefixesList.item(a) - if (interfaceRoutePrefix.getNodeType() == Node.ELEMENT_NODE) { - Element eElementInterfaceRoutePrefix = (Element) interfaceRoutePrefix - String interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix-cidr") - if (interfaceRoutePrefixValue == null || interfaceRoutePrefixValue.isEmpty()) { - interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix") - } - if (a != interfaceRoutePrefixesList.getLength() - 1) { - interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}" + ",") - } - else { - interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}") - } - } - } - interfaceRoutePrefixValues = sb3.append("]") - if (interfaceRoutePrefixesList.getLength() > 0) { - paramsMap.put("${key}_${networkKey}_route_prefixes", "${interfaceRoutePrefixValues}") - } - - NodeList networkIpsV6List = eElementNetworkKey.getElementsByTagNameNS("*","network-ips-v6") - for(int a = 0; a < networkIpsV6List.getLength(); a++){ - Node ipV6Address = networkIpsV6List.item(a) - if (ipV6Address.getNodeType() == Node.ELEMENT_NODE) { - Element eElementIpV6Address = (Element) ipV6Address - String ipV6AddressValue = utils.getElementText(eElementIpV6Address, "ip-address-ipv6") - if (a != networkIpsV6List.getLength() - 1) { - ipV6AddressValues = sb4.append(ipV6AddressValue + ",") - } - else { - ipV6AddressValues = sb4.append(ipV6AddressValue); - } - networkPosition = a.toString() - paramsMap.put("${key}_${networkKey}_v6_ip_${networkPosition}", "${ipV6AddressValue}") - } - } - paramsMap.put("${key}_${networkKey}_v6_ips", "${ipV6AddressValues}") - } - } - paramsMap.put("${key}_names", "${values}") - } - } - //SDNC Response Params - List<String> sdncResponseParamsToSkip = ["vnf_id", "vf_module_id", "vnf_name", "vf_module_name"] - - String vnfParamsChildNodes = utils.getChildNodes(vnfData, "param") - if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){ - // No SDNC params for VNF - }else{ - NodeList paramsList = responseXmlVnf.getElementsByTagNameNS("*", "param") - for (int z = 0; z < paramsList.getLength(); z++) { - Node node = paramsList.item(z) - Element eElement = (Element) node - String vnfParameterName = utils.getElementText(eElement, "name") - if (!sdncResponseParamsToSkip.contains(vnfParameterName)) { - String vnfParameterValue = utils.getElementText(eElement, "value") - paramsMap.put("${vnfParameterName}", "${vnfParameterValue}") - } - } - } - - String vfModuleParamsChildNodes = utils.getChildNodes(vfModuleData, "param") - if(vfModuleParamsChildNodes == null || vfModuleParamsChildNodes.length() < 1){ - // No SDNC params for VF Module - }else{ - NodeList paramsList = responseXmlVfModule.getElementsByTagNameNS("*", "param") - for (int z = 0; z < paramsList.getLength(); z++) { - Node node = paramsList.item(z) - Element eElement = (Element) node - String vnfParameterName = utils.getElementText(eElement, "name") - if (!sdncResponseParamsToSkip.contains(vnfParameterName)) { - String vnfParameterValue = utils.getElementText(eElement, "value") - paramsMap.put("${vnfParameterName}", "${vnfParameterValue}") - } - } - } - - // Parameters received from the request should overwrite any parameters received from SDNC - if (vnfParamsMap != null) { - for (Map.Entry<String, String> entry : vnfParamsMap.entrySet()) { - String vnfKey = entry.getKey() - String vnfValue = entry.getValue() - paramsMap.put("$vnfKey", "$vnfValue") - } - } - - StringBuilder sbParams = new StringBuilder() - def vfModuleParams = "" - for (Map.Entry<String, String> entry : paramsMap.entrySet()) { - String paramsXml - String paramName = entry.getKey() - String paramValue = entry.getValue() - paramsXml = - """<entry> + + vfModuleParams = sbParams.append(paramsXml) + } + + return vfModuleParams + + } + + + /* + * Parses VNF parameters passed in on the incoming requests and SDNC parameters returned from SDNC get response + * for both VNF and VF Module + * and puts them into the format expected by VNF adapter. + * @param vnfParamsMap - map of VNF parameters passed in the request body + * @param vnfSdncGetResponse - response string from SDNC GET VNF topology request + * @param vfmoduleSdncGetResponse - response string from SDNC GET VF Module topology request + * @param vnfId + * @param vnfName + * @param vfModuleId + * @param vfModuleName + * @param vfModuleIndex - can be null + * @return a String of key/value entries for vfModuleParams + */ + + protected String buildVfModuleParamsFromCombinedTopologies(Map<String, String> vnfParamsMap, String vnfSdncGetResponse, String vfmoduleSdncGetResponse, String vnfId, String vnfName, + String vfModuleId, String vfModuleName, String vfModuleIndex, String environmentContext, String workloadContext) { + + // Set up initial parameters + + Map<String, String> paramsMap = new HashMap<String, String>() + + if (vfModuleIndex != null) { + paramsMap.put("vf_module_index", "${vfModuleIndex}") + } + + // Add-on data + paramsMap.put("vnf_id", "${vnfId}") + paramsMap.put("vnf_name", "${vnfName}") + paramsMap.put("vf_module_id", "${vfModuleId}") + paramsMap.put("vf_module_name", "${vfModuleName}") + paramsMap.put("environment_context","${environmentContext}") + paramsMap.put("workload_context", "${workloadContext}") + + //Get SDNC Response Data for VNF + + String vnfData = utils.getNodeXml(vnfSdncGetResponse, "response-data") + + String vnfTopology = utils.getNodeXml(vnfData, "vnf-topology") + vnfTopology = utils.removeXmlPreamble(vnfTopology) + vnfTopology = utils.removeXmlNamespaces(vnfTopology) + + InputSource sourceVnf = new InputSource(new StringReader(vnfData)); + DocumentBuilderFactory docFactoryVnf = DocumentBuilderFactory.newInstance(); + docFactoryVnf.setNamespaceAware(true) + DocumentBuilder docBuilderVnf = docFactoryVnf.newDocumentBuilder() + Document responseXmlVnf = docBuilderVnf.parse(sourceVnf) + + // Availability Zones Data + + NodeList aZonesList = responseXmlVnf.getElementsByTagNameNS("*", "availability-zones") + String aZonePosition = "0" + for (int z = 0; z < aZonesList.getLength(); z++) { + Node node = aZonesList.item(z) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + String aZoneValue = utils.getElementText(eElement, "availability-zone") + aZonePosition = z.toString() + paramsMap.put("availability_zone_${aZonePosition}", "${aZoneValue}") + } + } + + //Get SDNC Response Data for VF Module + + String vfModuleData = utils.getNodeXml(vfmoduleSdncGetResponse, "response-data") + + String vfModuleTopology = utils.getNodeXml(vfModuleData, "vf-module-topology") + vfModuleTopology = utils.removeXmlPreamble(vfModuleTopology) + vfModuleTopology = utils.removeXmlNamespaces(vfModuleTopology) + String vfModuleTopologyIdentifier = utils.getNodeXml(vfModuleTopology, "vf-module-topology-identifier") + + InputSource sourceVfModule = new InputSource(new StringReader(vfModuleData)); + DocumentBuilderFactory docFactoryVfModule = DocumentBuilderFactory.newInstance(); + docFactoryVfModule.setNamespaceAware(true) + DocumentBuilder docBuilderVfModule = docFactoryVfModule.newDocumentBuilder() + Document responseXmlVfModule = docBuilderVfModule.parse(sourceVfModule) + + // Map of network-roles and network-tags from vm-networks + + NodeList vmNetworksListGlobal = responseXmlVfModule.getElementsByTagNameNS("*", "vm-networks") + Map<String, String> networkRoleMap = new HashMap<String, String>() + for(int n = 0; n < vmNetworksListGlobal.getLength(); n++){ + Node nodeNetworkKey = vmNetworksListGlobal.item(n) + if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) { + Element eElementNetworkKey = (Element) nodeNetworkKey + String networkRole = utils.getElementText(eElementNetworkKey, "network-role") + String networkRoleValue = utils.getElementText(eElementNetworkKey, "network-role-tag") + if (networkRoleValue.isEmpty()) { + networkRoleValue = networkRole + } + networkRoleMap.put(networkRole, networkRoleValue) + } + } + + // VNF Networks Data + + StringBuilder sbNet = new StringBuilder() + + NodeList vnfNetworkList = responseXmlVnf.getElementsByTagNameNS("*", "vnf-networks") + for (int x = 0; x < vnfNetworkList.getLength(); x++) { + Node node = vnfNetworkList.item(x) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + String vnfNetworkKey = utils.getElementText(eElement, "network-role-tag") + String networkRole = utils.getElementText(eElement, "network-role") + if (vnfNetworkKey.isEmpty()) { + vnfNetworkKey = networkRoleMap.get(networkRole) + if (vnfNetworkKey == null || vnfNetworkKey.isEmpty()) { + vnfNetworkKey = networkRole + } + } + String vnfNetworkNeutronIdValue = utils.getElementText(eElement, "neutron-id") + String vnfNetworkNetNameValue = utils.getElementText(eElement, "network-name") + String vnfNetworkSubNetIdValue = utils.getElementText(eElement, "subnet-id") + String vnfNetworkV6SubNetIdValue = utils.getElementText(eElement, "ipv6-subnet-id") + String vnfNetworkNetFqdnValue = utils.getElementText(eElement, "contrail-network-fqdn") + paramsMap.put("${vnfNetworkKey}_net_id", "${vnfNetworkNeutronIdValue}") + paramsMap.put("${vnfNetworkKey}_net_name", "${vnfNetworkNetNameValue}") + paramsMap.put("${vnfNetworkKey}_subnet_id", "${vnfNetworkSubNetIdValue}") + paramsMap.put("${vnfNetworkKey}_v6_subnet_id", "${vnfNetworkV6SubNetIdValue}") + paramsMap.put("${vnfNetworkKey}_net_fqdn", "${vnfNetworkNetFqdnValue}") + + NodeList sriovVlanFilterList = eElement.getElementsByTagNameNS("*","sriov-vlan-filter-list") + StringBuffer sriovFilterBuf = new StringBuffer() + String values = "" + for(int i = 0; i < sriovVlanFilterList.getLength(); i++){ + Node node1 = sriovVlanFilterList.item(i) + if (node1.getNodeType() == Node.ELEMENT_NODE) { + Element eElement1 = (Element) node1 + String value = utils.getElementText(eElement1, "sriov-vlan-filter") + if (i != sriovVlanFilterList.getLength() - 1) { + values = sriovFilterBuf.append(value + ",") + } + else { + values = sriovFilterBuf.append(value); + } + } + } + if (!values.isEmpty()) { + paramsMap.put("${vnfNetworkKey}_ATT_VF_VLAN_FILTER", "${values}") + } + } + } + + + + // VMS Data + + def key + def value + def networkKey + def networkValue + def floatingIPKey + def floatingIPKeyValue + def floatingIPV6Key + def floatingIPV6KeyValue + StringBuilder sb = new StringBuilder() + + NodeList vmsList = responseXmlVfModule.getElementsByTagNameNS("*","vm") + for (int x = 0; x < vmsList.getLength(); x++) { + Node node = vmsList.item(x) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + key = utils.getElementText(eElement, "vm-type") + String values + String position = "0" + StringBuilder sb1 = new StringBuilder() + NodeList valueList = eElement.getElementsByTagNameNS("*","vm-names") + NodeList vmNetworksList = eElement.getElementsByTagNameNS("*","vm-networks") + for(int i = 0; i < valueList.getLength(); i++){ + Node node1 = valueList.item(i) + if (node1.getNodeType() == Node.ELEMENT_NODE) { + Element eElement1 = (Element) node1 + value = utils.getElementText(eElement1, "vm-name") + if (i != valueList.getLength() - 1) { + values = sb1.append(value + ",") + } + else { + values = sb1.append(value); + } + position = i.toString() + paramsMap.put("${key}_name_${position}", "${value}") + } + } + for(int n = 0; n < vmNetworksList.getLength(); n++){ + String floatingIpKeyValueStr = "" + String floatingIpV6KeyValueStr = "" + Node nodeNetworkKey = vmNetworksList.item(n) + if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) { + Element eElementNetworkKey = (Element) nodeNetworkKey + String ipAddressValues + String ipV6AddressValues + String networkPosition = "0" + StringBuilder sb2 = new StringBuilder() + StringBuilder sb3 = new StringBuilder() + StringBuilder sb4 = new StringBuilder() + networkKey = utils.getElementText(eElementNetworkKey, "network-role-tag") + if (networkKey.isEmpty()) { + networkKey = utils.getElementText(eElementNetworkKey, "network-role") + } + floatingIPKey = key + '_' + networkKey + '_floating_ip' + floatingIPKeyValue = utils.getElementText(eElementNetworkKey, "floating-ip") + if(!floatingIPKeyValue.isEmpty()){ + paramsMap.put("$floatingIPKey", "$floatingIPKeyValue") + } + floatingIPV6Key = key + '_' + networkKey + '_floating_v6_ip' + floatingIPV6KeyValue = utils.getElementText(eElementNetworkKey, "floating-ip-v6") + if(!floatingIPV6KeyValue.isEmpty()){ + paramsMap.put("$floatingIPV6Key", "$floatingIPV6KeyValue") + } + NodeList networkIpsList = eElementNetworkKey.getElementsByTagNameNS("*","network-ips") + for(int a = 0; a < networkIpsList.getLength(); a++){ + Node ipAddress = networkIpsList.item(a) + if (ipAddress.getNodeType() == Node.ELEMENT_NODE) { + Element eElementIpAddress = (Element) ipAddress + String ipAddressValue = utils.getElementText(eElementIpAddress, "ip-address") + if (a != networkIpsList.getLength() - 1) { + ipAddressValues = sb2.append(ipAddressValue + ",") + } + else { + ipAddressValues = sb2.append(ipAddressValue); + } + networkPosition = a.toString() + paramsMap.put("${key}_${networkKey}_ip_${networkPosition}", "${ipAddressValue}") + } + } + + paramsMap.put("${key}_${networkKey}_ips", "${ipAddressValues}") + + NodeList interfaceRoutePrefixesList = eElementNetworkKey.getElementsByTagNameNS("*","interface-route-prefixes") + String interfaceRoutePrefixValues = sb3.append("[") + + for(int a = 0; a < interfaceRoutePrefixesList.getLength(); a++){ + Node interfaceRoutePrefix = interfaceRoutePrefixesList.item(a) + if (interfaceRoutePrefix.getNodeType() == Node.ELEMENT_NODE) { + Element eElementInterfaceRoutePrefix = (Element) interfaceRoutePrefix + String interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix-cidr") + if (interfaceRoutePrefixValue == null || interfaceRoutePrefixValue.isEmpty()) { + interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix") + } + if (a != interfaceRoutePrefixesList.getLength() - 1) { + interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}" + ",") + } + else { + interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}") + } + } + } + interfaceRoutePrefixValues = sb3.append("]") + if (interfaceRoutePrefixesList.getLength() > 0) { + paramsMap.put("${key}_${networkKey}_route_prefixes", "${interfaceRoutePrefixValues}") + } + + NodeList networkIpsV6List = eElementNetworkKey.getElementsByTagNameNS("*","network-ips-v6") + for(int a = 0; a < networkIpsV6List.getLength(); a++){ + Node ipV6Address = networkIpsV6List.item(a) + if (ipV6Address.getNodeType() == Node.ELEMENT_NODE) { + Element eElementIpV6Address = (Element) ipV6Address + String ipV6AddressValue = utils.getElementText(eElementIpV6Address, "ip-address-ipv6") + if (a != networkIpsV6List.getLength() - 1) { + ipV6AddressValues = sb4.append(ipV6AddressValue + ",") + } + else { + ipV6AddressValues = sb4.append(ipV6AddressValue); + } + networkPosition = a.toString() + paramsMap.put("${key}_${networkKey}_v6_ip_${networkPosition}", "${ipV6AddressValue}") + } + } + paramsMap.put("${key}_${networkKey}_v6_ips", "${ipV6AddressValues}") + } + } + paramsMap.put("${key}_names", "${values}") + } + } + //SDNC Response Params + List<String> sdncResponseParamsToSkip = [ + "vnf_id", + "vf_module_id", + "vnf_name", + "vf_module_name" + ] + + String vnfParamsChildNodes = utils.getChildNodes(vnfData, "param") + if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){ + // No SDNC params for VNF + }else{ + NodeList paramsList = responseXmlVnf.getElementsByTagNameNS("*", "param") + for (int z = 0; z < paramsList.getLength(); z++) { + Node node = paramsList.item(z) + Element eElement = (Element) node + String vnfParameterName = utils.getElementText(eElement, "name") + if (!sdncResponseParamsToSkip.contains(vnfParameterName)) { + String vnfParameterValue = utils.getElementText(eElement, "value") + paramsMap.put("${vnfParameterName}", "${vnfParameterValue}") + } + } + } + + String vfModuleParamsChildNodes = utils.getChildNodes(vfModuleData, "param") + if(vfModuleParamsChildNodes == null || vfModuleParamsChildNodes.length() < 1){ + // No SDNC params for VF Module + }else{ + NodeList paramsList = responseXmlVfModule.getElementsByTagNameNS("*", "param") + for (int z = 0; z < paramsList.getLength(); z++) { + Node node = paramsList.item(z) + Element eElement = (Element) node + String vnfParameterName = utils.getElementText(eElement, "name") + if (!sdncResponseParamsToSkip.contains(vnfParameterName)) { + String vnfParameterValue = utils.getElementText(eElement, "value") + paramsMap.put("${vnfParameterName}", "${vnfParameterValue}") + } + } + } + + // make the sdnc_directives parameter + String sdncDirectives = "{}" + StringBuilder sdncDirectivesBuilder = new StringBuilder() + sdncDirectivesBuilder.append("{ \"attributes\": [") + int pcnt = 0 + for (Map.Entry<String, String> entry : paramsMap.entrySet()) { + String attributeName = entry.getKey() + String attributeValue = entry.getValue() + if (pcnt > 0) { + sdncDirectivesBuilder.append(",") + } + pcnt++ + sdncDirectivesBuilder.append("{\"attribute_name\":\"${attributeName}\",") + sdncDirectivesBuilder.append("\"attribute_value\":\"${attributeValue}\"}") + } + if (pcnt > 0) { + sdncDirectives = sdncDirectivesBuilder.append("]}").toString() + } + paramsMap.put("sdnc_directives", "${sdncDirectives}") + + + // Parameters received from the request should overwrite any parameters received from SDNC + String userDirectives = "{}" + if (vnfParamsMap != null) { + StringBuilder userDirectivesBuilder = new StringBuilder() + userDirectivesBuilder.append("{ \"attributes\": [") + pcnt = 0 + for (Map.Entry<String, String> entry : vnfParamsMap.entrySet()) { + String vnfKey = entry.getKey() + String vnfValue = entry.getValue() + paramsMap.put("$vnfKey", "$vnfValue") + if (pcnt > 0) { + userDirectivesBuilder.append(",") + } + pcnt++ + userDirectivesBuilder.append("{\"attribute_name\":\"${vnfKey}\",") + userDirectivesBuilder.append("\"attribute_value\":\"${vnfValue}\"}") + } + if (pcnt > 0) { + userDirectives = userDirectivesBuilder.append("]}").toString() + } + } + paramsMap.put("user_directives", "${userDirectives}") + + StringBuilder sbParams = new StringBuilder() + def vfModuleParams = "" + for (Map.Entry<String, String> entry : paramsMap.entrySet()) { + String paramsXml + String paramName = entry.getKey() + String paramValue = entry.getValue() + paramsXml = + """<entry> <key>${MsoUtils.xmlEscape(paramName)}</key> <value>${MsoUtils.xmlEscape(paramValue)}</value> </entry> """ - - vfModuleParams = sbParams.append(paramsXml) - } - - return vfModuleParams - - } - - - /* - * VBNG specific method that parses VNF parameters passed in on the - * incoming requests and SDNC parameters returned from SDNC get response - * and puts them into the format expected by VNF adapter. - * @param vnfParamsMap - map of VNF parameters passed in the request body - * @param sdncGetResponse - response string from SDNC GET topology request - * @param vnfId - * @param vnfName - * @param vfModuleId - * @param vfModuleName - * @return a String of key/value entries for vfModuleParams - */ - - protected String buildVfModuleParamsVbng(String vnfParams, String sdncGetResponse, String vnfId, String vnfName, - String vfModuleId, String vfModuleName) { - - //Get SDNC Response Data - - String data = utils.getNodeXml(sdncGetResponse, "response-data") - - - - // Add-on data - String vnfInfo = - """<entry> + + vfModuleParams = sbParams.append(paramsXml) + } + + return vfModuleParams + + } + + + /* + * VBNG specific method that parses VNF parameters passed in on the + * incoming requests and SDNC parameters returned from SDNC get response + * and puts them into the format expected by VNF adapter. + * @param vnfParamsMap - map of VNF parameters passed in the request body + * @param sdncGetResponse - response string from SDNC GET topology request + * @param vnfId + * @param vnfName + * @param vfModuleId + * @param vfModuleName + * @return a String of key/value entries for vfModuleParams + */ + + protected String buildVfModuleParamsVbng(String vnfParams, String sdncGetResponse, String vnfId, String vnfName, + String vfModuleId, String vfModuleName) { + + //Get SDNC Response Data + + String data = utils.getNodeXml(sdncGetResponse, "response-data") + + + + // Add-on data + String vnfInfo = + """<entry> <key>vnf_id</key> <value>${MsoUtils.xmlEscape(vnfId)}</value> </entry> @@ -889,347 +977,352 @@ public abstract class VfModuleBase extends AbstractServiceTaskProcessor { <value>${MsoUtils.xmlEscape(vfModuleName)}</value> </entry>""" - logger.debug("vnfInfo: " + vnfInfo) - InputSource source = new InputSource(new StringReader(data)); - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - docFactory.setNamespaceAware(true) - DocumentBuilder docBuilder = docFactory.newDocumentBuilder() - Document responseXml = docBuilder.parse(source) - - - // Availability Zones Data - String aZones = "" - StringBuilder sbAZone = new StringBuilder() - NodeList aZonesList = responseXml.getElementsByTagNameNS("*", "availability-zones") - String aZonePosition = "0" - for (int z = 0; z < aZonesList.getLength(); z++) { - Node node = aZonesList.item(z) - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) node - String aZoneValue = utils.getElementText(eElement, "availability-zone") - aZonePosition = z.toString() - String aZoneXml = - """<entry> + logger.debug("vnfInfo: " + vnfInfo) + InputSource source = new InputSource(new StringReader(data)); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setNamespaceAware(true) + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document responseXml = docBuilder.parse(source) + + + // Availability Zones Data + String aZones = "" + StringBuilder sbAZone = new StringBuilder() + NodeList aZonesList = responseXml.getElementsByTagNameNS("*", "availability-zones") + String aZonePosition = "0" + for (int z = 0; z < aZonesList.getLength(); z++) { + Node node = aZonesList.item(z) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + String aZoneValue = utils.getElementText(eElement, "availability-zone") + aZonePosition = z.toString() + String aZoneXml = + """<entry> <key>availability_zone_${MsoUtils.xmlEscape(aZonePosition)}</key> <value>${MsoUtils.xmlEscape(aZoneValue)}</value> </entry>""" - aZones = sbAZone.append(aZoneXml) - } - } - - // Map of network-roles and network-tags from vm-networks - - NodeList vmNetworksListGlobal = responseXml.getElementsByTagNameNS("*", "vm-networks") - Map<String, String> networkRoleMap = new HashMap<String, String>() - for(int n = 0; n < vmNetworksListGlobal.getLength(); n++){ - Node nodeNetworkKey = vmNetworksListGlobal.item(n) - if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) { - Element eElementNetworkKey = (Element) nodeNetworkKey - String networkRole = utils.getElementText(eElementNetworkKey, "network-role") - String networkRoleValue = utils.getElementText(eElementNetworkKey, "network-role-tag") - if (networkRoleValue.isEmpty()) { - networkRoleValue = networkRole - } - networkRoleMap.put(networkRole, networkRoleValue) - } - } - - // VNF Networks Data - String vnfNetworkNetId = "" - String vnfNetworkNetName = "" - String vnfNetworkSubNetId = "" - String vnfNetworkV6SubNetId = "" - String vnfNetworkNetFqdn = "" - String vnfNetworksSriovVlanFilters = "" - StringBuilder sbNet = new StringBuilder() - StringBuilder sbNet2 = new StringBuilder() - StringBuilder sbNet3 = new StringBuilder() - StringBuilder sbNet4 = new StringBuilder() - StringBuilder sbNet5 = new StringBuilder() - StringBuilder sbNet6 = new StringBuilder() - NodeList vnfNetworkList = responseXml.getElementsByTagNameNS("*", "vnf-networks") - for (int x = 0; x < vnfNetworkList.getLength(); x++) { - Node node = vnfNetworkList.item(x) - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) node - String vnfNetworkKey = utils.getElementText(eElement, "network-role-tag") - String networkRole = utils.getElementText(eElement, "network-role") - if (vnfNetworkKey.isEmpty()) { - vnfNetworkKey = networkRoleMap.get(networkRole) - if (vnfNetworkKey == null || vnfNetworkKey.isEmpty()) { - vnfNetworkKey = networkRole - } - } - String vnfNetworkNeutronIdValue = utils.getElementText(eElement, "neutron-id") - String vnfNetworkNetNameValue = utils.getElementText(eElement, "network-name") - String vnfNetworkSubNetIdValue = utils.getElementText(eElement, "subnet-id") - String vnfNetworkV6SubNetIdValue = utils.getElementText(eElement, "ipv6-subnet-id") - String vnfNetworkNetFqdnValue = utils.getElementText(eElement, "contrail-network-fqdn") - String vnfNetworkNetIdXml = - """<entry> + aZones = sbAZone.append(aZoneXml) + } + } + + // Map of network-roles and network-tags from vm-networks + + NodeList vmNetworksListGlobal = responseXml.getElementsByTagNameNS("*", "vm-networks") + Map<String, String> networkRoleMap = new HashMap<String, String>() + for(int n = 0; n < vmNetworksListGlobal.getLength(); n++){ + Node nodeNetworkKey = vmNetworksListGlobal.item(n) + if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) { + Element eElementNetworkKey = (Element) nodeNetworkKey + String networkRole = utils.getElementText(eElementNetworkKey, "network-role") + String networkRoleValue = utils.getElementText(eElementNetworkKey, "network-role-tag") + if (networkRoleValue.isEmpty()) { + networkRoleValue = networkRole + } + networkRoleMap.put(networkRole, networkRoleValue) + } + } + + // VNF Networks Data + String vnfNetworkNetId = "" + String vnfNetworkNetName = "" + String vnfNetworkSubNetId = "" + String vnfNetworkV6SubNetId = "" + String vnfNetworkNetFqdn = "" + String vnfNetworksSriovVlanFilters = "" + StringBuilder sbNet = new StringBuilder() + StringBuilder sbNet2 = new StringBuilder() + StringBuilder sbNet3 = new StringBuilder() + StringBuilder sbNet4 = new StringBuilder() + StringBuilder sbNet5 = new StringBuilder() + StringBuilder sbNet6 = new StringBuilder() + NodeList vnfNetworkList = responseXml.getElementsByTagNameNS("*", "vnf-networks") + for (int x = 0; x < vnfNetworkList.getLength(); x++) { + Node node = vnfNetworkList.item(x) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + String vnfNetworkKey = utils.getElementText(eElement, "network-role-tag") + String networkRole = utils.getElementText(eElement, "network-role") + if (vnfNetworkKey.isEmpty()) { + vnfNetworkKey = networkRoleMap.get(networkRole) + if (vnfNetworkKey == null || vnfNetworkKey.isEmpty()) { + vnfNetworkKey = networkRole + } + } + String vnfNetworkNeutronIdValue = utils.getElementText(eElement, "neutron-id") + String vnfNetworkNetNameValue = utils.getElementText(eElement, "network-name") + String vnfNetworkSubNetIdValue = utils.getElementText(eElement, "subnet-id") + String vnfNetworkV6SubNetIdValue = utils.getElementText(eElement, "ipv6-subnet-id") + String vnfNetworkNetFqdnValue = utils.getElementText(eElement, "contrail-network-fqdn") + String vnfNetworkNetIdXml = + """<entry> <key>${MsoUtils.xmlEscape(vnfNetworkKey)}_net_id</key> <value>${MsoUtils.xmlEscape(vnfNetworkNeutronIdValue)}</value> </entry>""" - vnfNetworkNetId = sbNet.append(vnfNetworkNetIdXml) - String vnfNetworkNetNameXml = - """<entry> + vnfNetworkNetId = sbNet.append(vnfNetworkNetIdXml) + String vnfNetworkNetNameXml = + """<entry> <key>${MsoUtils.xmlEscape(vnfNetworkKey)}_net_name</key> <value>${MsoUtils.xmlEscape(vnfNetworkNetNameValue)}</value> </entry>""" - vnfNetworkNetName = sbNet2.append(vnfNetworkNetNameXml) - String vnfNetworkSubNetIdXml = - """<entry> + vnfNetworkNetName = sbNet2.append(vnfNetworkNetNameXml) + String vnfNetworkSubNetIdXml = + """<entry> <key>${MsoUtils.xmlEscape(vnfNetworkKey)}_subnet_id</key> <value>${MsoUtils.xmlEscape(vnfNetworkSubNetIdValue)}</value> </entry>""" - vnfNetworkSubNetId = sbNet3.append(vnfNetworkSubNetIdXml) - String vnfNetworkV6SubNetIdXml = - """<entry> + vnfNetworkSubNetId = sbNet3.append(vnfNetworkSubNetIdXml) + String vnfNetworkV6SubNetIdXml = + """<entry> <key>${MsoUtils.xmlEscape(vnfNetworkKey)}_v6_subnet_id</key> <value>${MsoUtils.xmlEscape(vnfNetworkV6SubNetIdValue)}</value> </entry>""" - vnfNetworkV6SubNetId = sbNet5.append(vnfNetworkV6SubNetIdXml) - String vnfNetworkNetFqdnXml = - """<entry> + vnfNetworkV6SubNetId = sbNet5.append(vnfNetworkV6SubNetIdXml) + String vnfNetworkNetFqdnXml = + """<entry> <key>${MsoUtils.xmlEscape(vnfNetworkKey)}_net_fqdn</key> <value>${MsoUtils.xmlEscape(vnfNetworkNetFqdnValue)}</value> </entry>""" - vnfNetworkNetFqdn = sbNet4.append(vnfNetworkNetFqdnXml) - - NodeList sriovVlanFilterList = eElement.getElementsByTagNameNS("*","sriov-vlan-filter-list") - StringBuffer sriovFilterBuf = new StringBuffer() - String values = "" - for(int i = 0; i < sriovVlanFilterList.getLength(); i++){ - Node node1 = sriovVlanFilterList.item(i) - if (node1.getNodeType() == Node.ELEMENT_NODE) { - Element eElement1 = (Element) node1 - String value = utils.getElementText(eElement1, "sriov-vlan-filter") - if (i != sriovVlanFilterList.getLength() - 1) { - values = sriovFilterBuf.append(value + ",") - } - else { - values = sriovFilterBuf.append(value); - } - } - } - if (!values.isEmpty()) { - String vnfNetworkSriovVlanFilterXml = - """<entry> + vnfNetworkNetFqdn = sbNet4.append(vnfNetworkNetFqdnXml) + + NodeList sriovVlanFilterList = eElement.getElementsByTagNameNS("*","sriov-vlan-filter-list") + StringBuffer sriovFilterBuf = new StringBuffer() + String values = "" + for(int i = 0; i < sriovVlanFilterList.getLength(); i++){ + Node node1 = sriovVlanFilterList.item(i) + if (node1.getNodeType() == Node.ELEMENT_NODE) { + Element eElement1 = (Element) node1 + String value = utils.getElementText(eElement1, "sriov-vlan-filter") + if (i != sriovVlanFilterList.getLength() - 1) { + values = sriovFilterBuf.append(value + ",") + } + else { + values = sriovFilterBuf.append(value); + } + } + } + if (!values.isEmpty()) { + String vnfNetworkSriovVlanFilterXml = + """<entry> <key>${MsoUtils.xmlEscape(vnfNetworkKey)}_ATT_VF_VLAN_FILTER</key> <value>${MsoUtils.xmlEscape(values)}</value> </entry>""" - vnfNetworksSriovVlanFilters = sbNet6.append(vnfNetworkSriovVlanFilterXml) - } - } - } - - // VNF-VMS Data - String vnfVMS = "" - String vnfVMSPositions = "" - String vmNetworks = "" - String vmNetworksPositions = "" - String vmNetworksPositionsV6 = "" - String interfaceRoutePrefixes = "" - def key - def value - def networkKey - def networkValue - def floatingIPKey - def floatingIPKeyValue - def floatingIPV6Key - def floatingIPV6KeyValue - StringBuilder sb = new StringBuilder() - StringBuilder sbPositions = new StringBuilder() - StringBuilder sbVmNetworks = new StringBuilder() - StringBuilder sbNetworksPositions = new StringBuilder() - StringBuilder sbInterfaceRoutePrefixes = new StringBuilder() - StringBuilder sbNetworksPositionsV6 = new StringBuilder() - - NodeList vmsList = responseXml.getElementsByTagNameNS("*","vnf-vms") - for (int x = 0; x < vmsList.getLength(); x++) { - Node node = vmsList.item(x) - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) node - key = utils.getElementText(eElement, "vm-type") - String values - String position = "0" - StringBuilder sb1 = new StringBuilder() - NodeList valueList = eElement.getElementsByTagNameNS("*","vm-names") - NodeList vmNetworksList = eElement.getElementsByTagNameNS("*","vm-networks") - for(int i = 0; i < valueList.getLength(); i++){ - Node node1 = valueList.item(i) - if (node1.getNodeType() == Node.ELEMENT_NODE) { - Element eElement1 = (Element) node1 - value = utils.getElementText(eElement1, "vm-name") - if (i != valueList.getLength() - 1) { - values = sb1.append(value + ",") - } - else { - values = sb1.append(value); - } - position = i.toString() - String vnfPositionXml = - """<entry> + vnfNetworksSriovVlanFilters = sbNet6.append(vnfNetworkSriovVlanFilterXml) + } + } + } + + // VNF-VMS Data + String vnfVMS = "" + String vnfVMSPositions = "" + String vmNetworks = "" + String vmNetworksPositions = "" + String vmNetworksPositionsV6 = "" + String interfaceRoutePrefixes = "" + def key + def value + def networkKey + def networkValue + def floatingIPKey + def floatingIPKeyValue + def floatingIPV6Key + def floatingIPV6KeyValue + StringBuilder sb = new StringBuilder() + StringBuilder sbPositions = new StringBuilder() + StringBuilder sbVmNetworks = new StringBuilder() + StringBuilder sbNetworksPositions = new StringBuilder() + StringBuilder sbInterfaceRoutePrefixes = new StringBuilder() + StringBuilder sbNetworksPositionsV6 = new StringBuilder() + + NodeList vmsList = responseXml.getElementsByTagNameNS("*","vnf-vms") + for (int x = 0; x < vmsList.getLength(); x++) { + Node node = vmsList.item(x) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + key = utils.getElementText(eElement, "vm-type") + String values + String position = "0" + StringBuilder sb1 = new StringBuilder() + NodeList valueList = eElement.getElementsByTagNameNS("*","vm-names") + NodeList vmNetworksList = eElement.getElementsByTagNameNS("*","vm-networks") + for(int i = 0; i < valueList.getLength(); i++){ + Node node1 = valueList.item(i) + if (node1.getNodeType() == Node.ELEMENT_NODE) { + Element eElement1 = (Element) node1 + value = utils.getElementText(eElement1, "vm-name") + if (i != valueList.getLength() - 1) { + values = sb1.append(value + ",") + } + else { + values = sb1.append(value); + } + position = i.toString() + String vnfPositionXml = + """<entry> <key>${MsoUtils.xmlEscape(key)}_name_${MsoUtils.xmlEscape(position)}</key> <value>${MsoUtils.xmlEscape(value)}</value> </entry>""" - nfVMSPositions = sbPositions.append(vnfPositionXml) - } - } - for(int n = 0; n < vmNetworksList.getLength(); n++){ - String floatingIpKeyValueStr = "" - String floatingIpV6KeyValueStr = "" - Node nodeNetworkKey = vmNetworksList.item(n) - if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) { - Element eElementNetworkKey = (Element) nodeNetworkKey - String ipAddressValues - String ipV6AddressValues - String networkPosition = "0" - StringBuilder sb2 = new StringBuilder() - StringBuilder sb3 = new StringBuilder() - StringBuilder sb4 = new StringBuilder() - networkKey = utils.getElementText(eElementNetworkKey, "network-role-tag") - if (networkKey.isEmpty()) { - networkKey = utils.getElementText(eElementNetworkKey, "network-role") - } - floatingIPKey = key + '_' + networkKey + '_floating_ip' - floatingIPKeyValue = utils.getElementText(eElementNetworkKey, "floating-ip") - if(!floatingIPKeyValue.isEmpty()){ - floatingIpKeyValueStr = """<entry> + nfVMSPositions = sbPositions.append(vnfPositionXml) + } + } + for(int n = 0; n < vmNetworksList.getLength(); n++){ + String floatingIpKeyValueStr = "" + String floatingIpV6KeyValueStr = "" + Node nodeNetworkKey = vmNetworksList.item(n) + if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) { + Element eElementNetworkKey = (Element) nodeNetworkKey + String ipAddressValues + String ipV6AddressValues + String networkPosition = "0" + StringBuilder sb2 = new StringBuilder() + StringBuilder sb3 = new StringBuilder() + StringBuilder sb4 = new StringBuilder() + networkKey = utils.getElementText(eElementNetworkKey, "network-role-tag") + if (networkKey.isEmpty()) { + networkKey = utils.getElementText(eElementNetworkKey, "network-role") + } + floatingIPKey = key + '_' + networkKey + '_floating_ip' + floatingIPKeyValue = utils.getElementText(eElementNetworkKey, "floating-ip") + if(!floatingIPKeyValue.isEmpty()){ + floatingIpKeyValueStr = """<entry> <key>$floatingIPKey</key> <value>$floatingIPKeyValue</value> </entry>""" - } - floatingIPV6Key = key + '_' + networkKey + '_floating_v6_ip' - floatingIPV6KeyValue = utils.getElementText(eElementNetworkKey, "floating-ip-v6") - if(!floatingIPV6KeyValue.isEmpty()){ - floatingIpV6KeyValueStr = """<entry> + } + floatingIPV6Key = key + '_' + networkKey + '_floating_v6_ip' + floatingIPV6KeyValue = utils.getElementText(eElementNetworkKey, "floating-ip-v6") + if(!floatingIPV6KeyValue.isEmpty()){ + floatingIpV6KeyValueStr = """<entry> <key>$floatingIPV6Key</key> <value>$floatingIPV6KeyValue</value> </entry>""" - } - NodeList networkIpsList = eElementNetworkKey.getElementsByTagNameNS("*","network-ips") - for(int a = 0; a < networkIpsList.getLength(); a++){ - Node ipAddress = networkIpsList.item(a) - if (ipAddress.getNodeType() == Node.ELEMENT_NODE) { - Element eElementIpAddress = (Element) ipAddress - String ipAddressValue = utils.getElementText(eElementIpAddress, "ip-address") - if (a != networkIpsList.getLength() - 1) { - ipAddressValues = sb2.append(ipAddressValue + ",") - } - else { - ipAddressValues = sb2.append(ipAddressValue); - } - networkPosition = a.toString() - String vmNetworksPositionsXml = - """<entry> + } + NodeList networkIpsList = eElementNetworkKey.getElementsByTagNameNS("*","network-ips") + for(int a = 0; a < networkIpsList.getLength(); a++){ + Node ipAddress = networkIpsList.item(a) + if (ipAddress.getNodeType() == Node.ELEMENT_NODE) { + Element eElementIpAddress = (Element) ipAddress + String ipAddressValue = utils.getElementText(eElementIpAddress, "ip-address") + if (a != networkIpsList.getLength() - 1) { + ipAddressValues = sb2.append(ipAddressValue + ",") + } + else { + ipAddressValues = sb2.append(ipAddressValue); + } + networkPosition = a.toString() + String vmNetworksPositionsXml = + """<entry> <key>${MsoUtils.xmlEscape(key)}_${MsoUtils.xmlEscape(networkKey)}_ip_${MsoUtils.xmlEscape(networkPosition)}</key> <value>${MsoUtils.xmlEscape(ipAddressValue)}</value> </entry>""" - vmNetworksPositions = sbNetworksPositions.append(vmNetworksPositionsXml) - } - } - vmNetworksPositions = sbNetworksPositions.append(floatingIpKeyValueStr).append(floatingIpV6KeyValueStr) - - String vmNetworksXml = - """<entry> + vmNetworksPositions = sbNetworksPositions.append(vmNetworksPositionsXml) + } + } + vmNetworksPositions = sbNetworksPositions.append(floatingIpKeyValueStr).append(floatingIpV6KeyValueStr) + + String vmNetworksXml = + """<entry> <key>${MsoUtils.xmlEscape(key)}_${MsoUtils.xmlEscape(networkKey)}_ips</key> <value>${MsoUtils.xmlEscape(ipAddressValues)}</value> </entry>""" - vmNetworks = sbVmNetworks.append(vmNetworksXml) - - NodeList interfaceRoutePrefixesList = eElementNetworkKey.getElementsByTagNameNS("*","interface-route-prefixes") - String interfaceRoutePrefixValues = sb3.append("[") - - for(int a = 0; a < interfaceRoutePrefixesList.getLength(); a++){ - Node interfaceRoutePrefix = interfaceRoutePrefixesList.item(a) - if (interfaceRoutePrefix.getNodeType() == Node.ELEMENT_NODE) { - Element eElementInterfaceRoutePrefix = (Element) interfaceRoutePrefix - String interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix-cidr") - if (interfaceRoutePrefixValue == null || interfaceRoutePrefixValue.isEmpty()) { - interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix") - } - if (a != interfaceRoutePrefixesList.getLength() - 1) { - interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}" + ",") - } - else { - interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}") - } - } - } - interfaceRoutePrefixValues = sb3.append("]") - if (interfaceRoutePrefixesList.getLength() > 0) { - String interfaceRoutePrefixesXml = - """<entry> + vmNetworks = sbVmNetworks.append(vmNetworksXml) + + NodeList interfaceRoutePrefixesList = eElementNetworkKey.getElementsByTagNameNS("*","interface-route-prefixes") + String interfaceRoutePrefixValues = sb3.append("[") + + for(int a = 0; a < interfaceRoutePrefixesList.getLength(); a++){ + Node interfaceRoutePrefix = interfaceRoutePrefixesList.item(a) + if (interfaceRoutePrefix.getNodeType() == Node.ELEMENT_NODE) { + Element eElementInterfaceRoutePrefix = (Element) interfaceRoutePrefix + String interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix-cidr") + if (interfaceRoutePrefixValue == null || interfaceRoutePrefixValue.isEmpty()) { + interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix") + } + if (a != interfaceRoutePrefixesList.getLength() - 1) { + interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}" + ",") + } + else { + interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}") + } + } + } + interfaceRoutePrefixValues = sb3.append("]") + if (interfaceRoutePrefixesList.getLength() > 0) { + String interfaceRoutePrefixesXml = + """<entry> <key>${MsoUtils.xmlEscape(key)}_${MsoUtils.xmlEscape(networkKey)}_route_prefixes</key> <value>${MsoUtils.xmlEscape(interfaceRoutePrefixValues)}</value> - </entry>""" - interfaceRoutePrefixes = sbInterfaceRoutePrefixes.append(interfaceRoutePrefixesXml) - } - - NodeList networkIpsV6List = eElementNetworkKey.getElementsByTagNameNS("*","network-ips-v6") - for(int a = 0; a < networkIpsV6List.getLength(); a++){ - Node ipV6Address = networkIpsV6List.item(a) - if (ipV6Address.getNodeType() == Node.ELEMENT_NODE) { - Element eElementIpV6Address = (Element) ipV6Address - String ipV6AddressValue = utils.getElementText(eElementIpV6Address, "ip-address-ipv6") - if (a != networkIpsV6List.getLength() - 1) { - ipV6AddressValues = sb4.append(ipV6AddressValue + ",") - } - else { - ipV6AddressValues = sb4.append(ipV6AddressValue); - } - networkPosition = a.toString() - String vmNetworksPositionsV6Xml = - """<entry> + </entry>""" + interfaceRoutePrefixes = sbInterfaceRoutePrefixes.append(interfaceRoutePrefixesXml) + } + + NodeList networkIpsV6List = eElementNetworkKey.getElementsByTagNameNS("*","network-ips-v6") + for(int a = 0; a < networkIpsV6List.getLength(); a++){ + Node ipV6Address = networkIpsV6List.item(a) + if (ipV6Address.getNodeType() == Node.ELEMENT_NODE) { + Element eElementIpV6Address = (Element) ipV6Address + String ipV6AddressValue = utils.getElementText(eElementIpV6Address, "ip-address-ipv6") + if (a != networkIpsV6List.getLength() - 1) { + ipV6AddressValues = sb4.append(ipV6AddressValue + ",") + } + else { + ipV6AddressValues = sb4.append(ipV6AddressValue); + } + networkPosition = a.toString() + String vmNetworksPositionsV6Xml = + """<entry> <key>${MsoUtils.xmlEscape(key)}_${MsoUtils.xmlEscape(networkKey)}_v6_ip_${MsoUtils.xmlEscape(networkPosition)}</key> <value>${MsoUtils.xmlEscape(ipV6AddressValue)}</value> </entry>""" - vmNetworksPositionsV6 = sbNetworksPositionsV6.append(vmNetworksPositionsV6Xml) - } - } - String vmNetworksV6Xml = - """<entry> + vmNetworksPositionsV6 = sbNetworksPositionsV6.append(vmNetworksPositionsV6Xml) + } + } + String vmNetworksV6Xml = + """<entry> <key>${MsoUtils.xmlEscape(key)}_${MsoUtils.xmlEscape(networkKey)}_v6_ips</key> <value>${MsoUtils.xmlEscape(ipV6AddressValues)}</value> </entry>""" - vmNetworks = sbVmNetworks.append(vmNetworksV6Xml) - } - } - String vnfXml = - """<entry> + vmNetworks = sbVmNetworks.append(vmNetworksV6Xml) + } + } + String vnfXml = + """<entry> <key>${MsoUtils.xmlEscape(key)}_names</key> <value>${MsoUtils.xmlEscape(values)}</value> </entry>""" - vnfVMS = sb.append(vnfXml) - } - } - //SDNC Response Params - String sdncResponseParams = "" - List<String> sdncResponseParamsToSkip = ["vnf_id", "vf_module_id", "vnf_name", "vf_module_name"] - String vnfParamsChildNodes = utils.getChildNodes(data, "vnf-parameters") - if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){ - // No SDNC params - }else{ - NodeList paramsList = responseXml.getElementsByTagNameNS("*", "vnf-parameters") - for (int z = 0; z < paramsList.getLength(); z++) { - Node node = paramsList.item(z) - Element eElement = (Element) node - String vnfParameterName = utils.getElementText(eElement, "vnf-parameter-name") - if (!sdncResponseParamsToSkip.contains(vnfParameterName)) { - String vnfParameterValue = utils.getElementText(eElement, "vnf-parameter-value") - String paraEntry = - """<entry> + vnfVMS = sb.append(vnfXml) + } + } + //SDNC Response Params + String sdncResponseParams = "" + List<String> sdncResponseParamsToSkip = [ + "vnf_id", + "vf_module_id", + "vnf_name", + "vf_module_name" + ] + String vnfParamsChildNodes = utils.getChildNodes(data, "vnf-parameters") + if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){ + // No SDNC params + }else{ + NodeList paramsList = responseXml.getElementsByTagNameNS("*", "vnf-parameters") + for (int z = 0; z < paramsList.getLength(); z++) { + Node node = paramsList.item(z) + Element eElement = (Element) node + String vnfParameterName = utils.getElementText(eElement, "vnf-parameter-name") + if (!sdncResponseParamsToSkip.contains(vnfParameterName)) { + String vnfParameterValue = utils.getElementText(eElement, "vnf-parameter-value") + String paraEntry = + """<entry> <key>${MsoUtils.xmlEscape(vnfParameterName)}</key> <value>${MsoUtils.xmlEscape(vnfParameterValue)}</value> </entry>""" - sdncResponseParams = sb.append(paraEntry) - } - } - } - - - def vfModuleParams = """ + sdncResponseParams = sb.append(paraEntry) + } + } + } + + + def vfModuleParams = """ ${vnfInfo} ${aZones} ${vnfNetworkNetId} @@ -1247,8 +1340,8 @@ public abstract class VfModuleBase extends AbstractServiceTaskProcessor { ${vnfParams} ${sdncResponseParams}""" - return vfModuleParams + return vfModuleParams - } + } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy index 9215eabc57..a769eca3a1 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.client.HttpClientFactory import org.onap.so.logger.ErrorCode @@ -78,7 +79,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (messageId == null || messageId.isEmpty()) { String msg = getProcessKey(execution) + ': no messageId in ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -92,7 +93,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (notificationUrl == null || notificationUrl.isEmpty()) { String msg = getProcessKey(execution) + ': no notificationUrl in ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -106,7 +107,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (vnfAdapterEndpoint == null || vnfAdapterEndpoint.isEmpty()) { String msg = getProcessKey(execution) + ': mso:adapters:vnf:rest:endpoint URN mapping is not defined' - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -124,7 +125,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (vnfId == null || vnfId.isEmpty()) { String msg = getProcessKey(execution) + ': no vnfId in ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -137,7 +138,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (vnfId == null || vnfId.isEmpty()) { String msg = getProcessKey(execution) + ': no vnfId in ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -146,7 +147,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (vfModuleId == null || vfModuleId.isEmpty()) { String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -160,7 +161,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (vnfId == null || vnfId.isEmpty()) { String msg = getProcessKey(execution) + ': no vnfId in ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -169,7 +170,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (vfModuleId == null || vfModuleId.isEmpty()) { String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -183,7 +184,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (vfModuleRollbackNode == null) { String msg = getProcessKey(execution) + ': no vfModuleRollback in ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -192,7 +193,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (vnfId == null || vnfId.isEmpty()) { String msg = getProcessKey(execution) + ': no vnfId in ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -201,7 +202,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (vfModuleId == null || vfModuleId.isEmpty()) { String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -222,7 +223,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (volumeGroupId == null || volumeGroupId.isEmpty()) { String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -238,7 +239,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (volumeGroupId == null || volumeGroupId.isEmpty()) { String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -254,7 +255,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if (volumeGroupId == null || volumeGroupId.isEmpty()) { String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -267,7 +268,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { } else { String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -284,7 +285,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { String basicAuthValue = UrnPropertiesReader.getVariable("mso.adapters.po.auth", execution) if (basicAuthValue == null || basicAuthValue.isEmpty()) { - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN", ErrorCode.UnknownError.getValue()); } else { @@ -292,7 +293,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution)) execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString) } catch (IOException ex) { - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), getProcessKey(execution) + ": Unable to encode BasicAuth credentials for VnfAdapter", "BPMN", ErrorCode.UnknownError.getValue(), ex); } @@ -303,7 +304,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { throw e } catch (Exception e) { String msg = 'Caught exception in ' + method + ": " + e - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); logger.debug(msg) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) @@ -355,7 +356,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { response = httpClient.delete(vnfAdapterRequest) } else { String msg = 'Unsupported HTTP method "' + vnfAdapterMethod + '" in ' + method + ": " + e - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -368,7 +369,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { throw e } catch (Exception e) { String msg = 'Caught exception in ' + method + ": " + e - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterUtils.groovy index c947bf2e65..6cfa2a1a64 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterUtils.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution; import org.onap.so.bpmn.core.WorkflowException @@ -86,7 +87,7 @@ class VnfAdapterUtils { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 5000, 'Internal Error- Unable to validate VNF Response ' + e.getMessage()) diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/PayloadClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/PayloadClient.java index 3b768cbc3b..9e9c4b5cfa 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/PayloadClient.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/PayloadClient.java @@ -24,11 +24,14 @@ import java.util.Optional; import org.onap.so.bpmn.appc.payload.beans.ConfigurationParametersHealthCheck; import org.onap.so.bpmn.appc.payload.beans.ConfigurationParametersQuiesce; import org.onap.so.bpmn.appc.payload.beans.ConfigurationParametersResumeTraffic; +import org.onap.so.bpmn.appc.payload.beans.ConfigurationParametersDistributeTraffic; import org.onap.so.bpmn.appc.payload.beans.ConfigurationParametersUpgrade; import org.onap.so.bpmn.appc.payload.beans.HealthCheckAction; import org.onap.so.bpmn.appc.payload.beans.QuiesceTrafficAction; import org.onap.so.bpmn.appc.payload.beans.RequestParametersHealthCheck; import org.onap.so.bpmn.appc.payload.beans.ResumeTrafficAction; +import org.onap.so.bpmn.appc.payload.beans.DistributeTrafficAction; +import org.onap.so.bpmn.appc.payload.beans.DistributeTrafficCheckAction; import org.onap.so.bpmn.appc.payload.beans.SnapshotAction; import org.onap.so.bpmn.appc.payload.beans.StartStopAction; import org.onap.so.bpmn.appc.payload.beans.UpgradeAction; @@ -56,6 +59,38 @@ public class PayloadClient { return Optional.of(mapper.writeValueAsString(payloadResult)); } + public static Optional<String> distributeTrafficFormat(Optional<String> payload, String vnfName) + throws JsonProcessingException { + DistributeTrafficAction payloadResult = new DistributeTrafficAction(); + ConfigurationParametersDistributeTraffic configParams = new ConfigurationParametersDistributeTraffic(); + String payloadString = payload.isPresent() ? payload.get() : ""; + String bookName = JsonUtils.getJsonValue(payloadString, "book_name"); + String nodeList = JsonUtils.getJsonValue(payloadString, "node_list"); + String fileParameterContent = JsonUtils.getJsonValue(payloadString, "file_parameter_content"); + configParams.setBookName(bookName); + configParams.setNodeList(nodeList); + configParams.setFileParameterContent(fileParameterContent); + configParams.setVnfName(vnfName); + payloadResult.setConfigurationParameters(configParams); + return Optional.of(mapper.writeValueAsString(payloadResult)); + } + + public static Optional<String> distributeTrafficCheckFormat(Optional<String> payload, String vnfName) + throws JsonProcessingException { + DistributeTrafficCheckAction payloadResult = new DistributeTrafficCheckAction(); + ConfigurationParametersDistributeTraffic configParams = new ConfigurationParametersDistributeTraffic(); + String payloadString = payload.isPresent() ? payload.get() : ""; + String bookName = JsonUtils.getJsonValue(payloadString, "book_name"); + String nodeList = JsonUtils.getJsonValue(payloadString, "node_list"); + String fileParameterContent = JsonUtils.getJsonValue(payloadString, "file_parameter_content"); + configParams.setBookName(bookName); + configParams.setNodeList(nodeList); + configParams.setFileParameterContent(fileParameterContent); + configParams.setVnfName(vnfName); + payloadResult.setConfigurationParameters(configParams); + return Optional.of(mapper.writeValueAsString(payloadResult)); + } + public static Optional<String> resumeTrafficFormat(String vnfName) throws JsonProcessingException { ResumeTrafficAction payloadResult = new ResumeTrafficAction(); ConfigurationParametersResumeTraffic configParams = new ConfigurationParametersResumeTraffic(); diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersDistributeTraffic.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersDistributeTraffic.java new file mode 100644 index 0000000000..a4ffdbfdba --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/ConfigurationParametersDistributeTraffic.java @@ -0,0 +1,78 @@ +/*- + * ============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.appc.payload.beans; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"vnf_name", "book_name", "node_list", "file_parameter_content"}) +public class ConfigurationParametersDistributeTraffic { + @JsonProperty("vnf_name") + private String vnfName; + @JsonProperty("book_name") + private String bookName; + @JsonProperty("node_list") + private String nodeList; + @JsonProperty("file_parameter_content") + private String fileParameterContent; + + @JsonProperty("vnf_name") + public String getVnfName() { + return vnfName; + } + + @JsonProperty("vnf_name") + public void setVnfName(String vnfName) { + this.vnfName = vnfName; + } + + @JsonProperty("book_name") + public String getBookName() { + return bookName; + } + + @JsonProperty("book_name") + public void setBookName(String bookName) { + this.bookName = bookName; + } + + @JsonProperty("node_list") + public String getNodeList() { + return nodeList; + } + + @JsonProperty("node_list") + public void setNodeList(String nodeList) { + this.nodeList = nodeList; + } + + @JsonProperty("file_parameter_content") + public String getFileParameterContent() { + return fileParameterContent; + } + + @JsonProperty("file_parameter_content") + public void setFileParameterContent(String fileParameterContent) { + this.fileParameterContent = fileParameterContent; + } +} diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/DistributeTrafficAction.java index 67d1cbff4e..9b7856e33f 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/DistributeTrafficAction.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ - * Copyright (C) 2018 Intel Corp. All rights reserved. + * Copyright (C) 2019 Orange 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. @@ -18,40 +18,27 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.openstack.utils; +package org.onap.so.bpmn.appc.payload.beans; -import java.io.Serializable; -import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang.builder.ToStringBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({"stack"}) -public class MulticloudCreateStackResponse implements Serializable { - private static final long serialVersionUID = -5215028275577848311L; +@JsonPropertyOrder({"configuration-parameters"}) +public class DistributeTrafficAction { - @JsonProperty("stack") - private MulticloudCreateHeatResponse stack; + @JsonProperty("configuration-parameters") + private ConfigurationParametersDistributeTraffic configurationParameters; - @JsonCreator - public MulticloudCreateStackResponse(@JsonProperty("stack") MulticloudCreateHeatResponse stack) { - this.stack = stack; + @JsonProperty("configuration-parameters") + public ConfigurationParametersDistributeTraffic getConfigurationParameters() { + return configurationParameters; } - @JsonProperty("stack") - public MulticloudCreateHeatResponse getStack() { - return stack; - } - - @JsonProperty("stack") - public void setStack(MulticloudCreateHeatResponse stack) { - this.stack = stack; - } - - @Override - public String toString() { - return new ToStringBuilder(this).append("stack", stack).toString(); + @JsonProperty("configuration-parameters") + public void setConfigurationParameters(ConfigurationParametersDistributeTraffic configurationParameters) { + this.configurationParameters = configurationParameters; } } + diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/DistributeTrafficCheckAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/DistributeTrafficCheckAction.java new file mode 100644 index 0000000000..b9831a90c4 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/appc/payload/beans/DistributeTrafficCheckAction.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 Orange 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.appc.payload.beans; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"configuration-parameters"}) +public class DistributeTrafficCheckAction { + + @JsonProperty("configuration-parameters") + private ConfigurationParametersDistributeTraffic configurationParameters; + + @JsonProperty("configuration-parameters") + public ConfigurationParametersDistributeTraffic getConfigurationParameters() { + return configurationParameters; + } + + @JsonProperty("configuration-parameters") + public void setConfigurationParameters(ConfigurationParametersDistributeTraffic configurationParameters) { + this.configurationParameters = configurationParameters; + } +} + diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/BBConstants.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/BBConstants.java new file mode 100644 index 0000000000..49ccc7b4a8 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/BBConstants.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.common; + +public class BBConstants { + public static final String G_ORCHESTRATION_FLOW = "gOrchestrationFlow"; + public static final String G_ACTION = "requestAction"; + public static final String G_CURRENT_SEQUENCE = "gCurrentSequence"; + public static final String G_REQUEST_ID = "mso-request-id"; + public static final String G_BPMN_REQUEST = "bpmnRequest"; + public static final String G_ALACARTE = "aLaCarte"; + public static final String G_APIVERSION = "apiVersion"; + public static final String G_URI = "requestUri"; + public static final String G_ISTOPLEVELFLOW = "isTopLevelFlow"; + public static final String G_SERVICE_TYPE = "serviceType"; + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/BuildingBlockExecution.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/BuildingBlockExecution.java index 83a44cfe8b..248f3b5f1a 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/BuildingBlockExecution.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/BuildingBlockExecution.java @@ -39,4 +39,6 @@ public interface BuildingBlockExecution { public Map<ResourceKey, String> getLookupMap(); public String getFlowToBeCalled(); + + public int getCurrentSequence(); } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DelegateExecutionImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DelegateExecutionImpl.java index 734262aa55..9aed5e9408 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DelegateExecutionImpl.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DelegateExecutionImpl.java @@ -112,6 +112,11 @@ public class DelegateExecutionImpl implements BuildingBlockExecution, Serializab return this.get("flowToBeCalled"); } + @JsonIgnore + @Override + public int getCurrentSequence() { + return this.get("gCurrentSequence"); + } public void setDelegateExecution(final DelegateExecution execution) { this.execution = execution; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/ListenerRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/ListenerRunner.java new file mode 100644 index 0000000000..3c36052dca --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/ListenerRunner.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.common.listener; + +import java.lang.annotation.Annotation; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import javax.annotation.Priority; +import org.onap.so.client.exception.ExceptionBuilder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; + +public abstract class ListenerRunner { + + @Autowired + protected ApplicationContext context; + + @Autowired + protected ExceptionBuilder exceptionBuilder; + + protected <T> List<T> filterListeners(List<T> validators, Predicate<T> predicate) { + return validators.stream().filter(item -> { + return !item.getClass().isAnnotationPresent(Skip.class) && predicate.test(item); + }).sorted(Comparator.comparing(item -> { + Priority p = Optional.ofNullable(item.getClass().getAnnotation(Priority.class)).orElse(new Priority() { + public int value() { + return 1000; + } + + @Override + public Class<? extends Annotation> annotationType() { + return Priority.class; + } + }); + return p.value(); + })).collect(Collectors.toList()); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/Skip.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/Skip.java index fe03a10795..a0543fd3cc 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/Skip.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/Skip.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulator.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulator.java new file mode 100644 index 0000000000..5e2882cb5b --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulator.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.common.listener.flowmanipulator; + +import java.util.List; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; + +public interface FlowManipulator { + + public boolean shouldRunFor(String currentBBName, boolean isFirst, BuildingBlockExecution execution); + + public void run(List<ExecuteBuildingBlock> flowsToExecute, ExecuteBuildingBlock currentBB, + BuildingBlockExecution execution); +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulatorListenerRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulatorListenerRunner.java new file mode 100644 index 0000000000..5f4dc871fb --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulatorListenerRunner.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.common.listener.flowmanipulator; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.listener.ListenerRunner; +import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class FlowManipulatorListenerRunner extends ListenerRunner { + + private static Logger logger = LoggerFactory.getLogger(FlowManipulatorListenerRunner.class); + + protected List<FlowManipulator> flowManipulators; + + @PostConstruct + protected void init() { + + flowManipulators = new ArrayList<>( + Optional.ofNullable(context.getBeansOfType(FlowManipulator.class)).orElse(new HashMap<>()).values()); + + } + + public void modifyFlows(List<ExecuteBuildingBlock> flowsToExecute, BuildingBlockExecution execution) { + + ExecuteBuildingBlock currentBB = flowsToExecute.get(execution.getCurrentSequence()); + List<FlowManipulator> filtered = filterListeners(flowManipulators, + (item -> item.shouldRunFor(currentBB.getBuildingBlock().getBpmnFlowName(), + execution.getCurrentSequence() == 0, execution))); + + logger.info("Running flow manipulators:\n{}", + filtered.stream().map(item -> item.getClass().getName()).collect(Collectors.joining("\n"))); + filtered.forEach(item -> item.run(flowsToExecute, currentBB, execution)); + + } + + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/BuildingBlockValidatorRunner.java index a8e43c51e5..78d897fd87 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunner.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/BuildingBlockValidatorRunner.java @@ -18,26 +18,13 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; -import java.lang.annotation.Annotation; import java.util.ArrayList; -import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import javax.annotation.PostConstruct; -import javax.annotation.Priority; -import org.camunda.bpm.engine.delegate.BpmnError; -import org.javatuples.Pair; -import org.onap.so.bpmn.common.BuildingBlockExecution; -import org.onap.so.client.exception.ExceptionBuilder; -import org.reflections.Reflections; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; @@ -45,9 +32,9 @@ import org.springframework.stereotype.Component; * Controls running all pre and post validation for building blocks. * * To define a validation you must make it a spring bean and implement either - * {@link org.onap.so.bpmn.common.validation.PreBuildingBlockValidator} or - * {@link org.onap.so.bpmn.common.validation.PostBuildingBlockValidator} your validation will automatically be run by - * this class. + * {@link org.onap.so.bpmn.common.listener.validation.PreBuildingBlockValidator} or + * {@link org.onap.so.bpmn.common.listener.validation.PostBuildingBlockValidator} your validation will automatically be + * run by this class. * */ @Component diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidator.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/FlowValidator.java index 66a8de9f8b..657e1d9539 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidator.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/FlowValidator.java @@ -18,10 +18,9 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; import java.util.Optional; -import java.util.Set; import org.onap.so.bpmn.common.BuildingBlockExecution; public interface FlowValidator { @@ -30,6 +29,7 @@ public interface FlowValidator { * Should this validator run for given bb * * @return + * */ public boolean shouldRunFor(String bbName); diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidatorRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/FlowValidatorRunner.java index 0bdf4e35a2..040522b576 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/FlowValidatorRunner.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/FlowValidatorRunner.java @@ -18,25 +18,19 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; -import java.lang.annotation.Annotation; import java.util.ArrayList; -import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; -import javax.annotation.Priority; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.javatuples.Pair; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.common.DelegateExecutionImpl; -import org.onap.so.client.exception.ExceptionBuilder; -import org.reflections.Reflections; +import org.onap.so.bpmn.common.listener.ListenerRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; @@ -49,14 +43,9 @@ import org.springframework.stereotype.Component; * */ @Component -public abstract class FlowValidatorRunner<S extends FlowValidator, E extends FlowValidator> { +public abstract class FlowValidatorRunner<S extends FlowValidator, E extends FlowValidator> extends ListenerRunner { private static Logger logger = LoggerFactory.getLogger(FlowValidatorRunner.class); - @Autowired - protected ApplicationContext context; - - @Autowired - protected ExceptionBuilder exceptionBuilder; protected List<S> preFlowValidators; protected List<E> postFlowValidators; @@ -114,7 +103,7 @@ public abstract class FlowValidatorRunner<S extends FlowValidator, E extends Flo protected List<Pair<String, Optional<String>>> runValidations(List<? extends FlowValidator> validators, String bbName, BuildingBlockExecution execution) { - List<FlowValidator> filtered = filterValidators(validators, bbName); + List<? extends FlowValidator> filtered = filterListeners(validators, (item -> item.shouldRunFor(bbName))); List<Pair<String, Optional<String>>> results = new ArrayList<>(); filtered.forEach(item -> results.add(new Pair<>(item.getClass().getName(), item.validate(execution)))); @@ -122,38 +111,6 @@ public abstract class FlowValidatorRunner<S extends FlowValidator, E extends Flo return results.stream().filter(item -> item.getValue1().isPresent()).collect(Collectors.toList()); } - protected List<FlowValidator> filterValidators(List<? extends FlowValidator> validators, String bbName) { - return validators.stream().filter(item -> { - return !item.getClass().isAnnotationPresent(Skip.class) && item.shouldRunFor(bbName); - }).sorted(Comparator.comparing(item -> { - Priority p = Optional.ofNullable(item.getClass().getAnnotation(Priority.class)).orElse(new Priority() { - public int value() { - return 1000; - } - - @Override - public Class<? extends Annotation> annotationType() { - return Priority.class; - } - }); - return p.value(); - })).collect(Collectors.toList()); - } - - protected <T> List<T> buildalidatorList(Reflections reflections, Class<T> clazz) { - List<T> result = new ArrayList<>(); - try { - for (Class<? extends T> klass : reflections.getSubTypesOf(clazz)) { - result.add(klass.newInstance()); - } - } catch (InstantiationException | IllegalAccessException e) { - logger.error("failed to build validator list for {}", clazz.getName(), e); - throw new RuntimeException(e); - } - - return result; - } - protected abstract List<S> getPreFlowValidators(); protected abstract List<E> getPostFlowValidators(); diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PostBuildingBlockValidator.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/PostBuildingBlockValidator.java index f26a2ee479..75dc75de43 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PostBuildingBlockValidator.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/PostBuildingBlockValidator.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; public interface PostBuildingBlockValidator extends FlowValidator { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PostWorkflowValidator.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/PostWorkflowValidator.java index 9070615a7a..7d5f68a482 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PostWorkflowValidator.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/PostWorkflowValidator.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; public interface PostWorkflowValidator extends FlowValidator { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PreBuildingBlockValidator.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/PreBuildingBlockValidator.java index fda687e072..fda2d264d8 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PreBuildingBlockValidator.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/PreBuildingBlockValidator.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; public interface PreBuildingBlockValidator extends FlowValidator { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PreWorkflowValidator.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/PreWorkflowValidator.java index 0bfbf5602f..a8e8642058 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PreWorkflowValidator.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/PreWorkflowValidator.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; public interface PreWorkflowValidator extends FlowValidator { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/WorkflowValidatorRunner.java index 6950618953..c6afa16ec2 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunner.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/WorkflowValidatorRunner.java @@ -18,25 +18,13 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; -import java.lang.annotation.Annotation; import java.util.ArrayList; -import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import javax.annotation.PostConstruct; -import javax.annotation.Priority; -import org.camunda.bpm.engine.delegate.DelegateExecution; -import org.javatuples.Pair; -import org.onap.so.client.exception.ExceptionBuilder; -import org.reflections.Reflections; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; @@ -44,9 +32,9 @@ import org.springframework.stereotype.Component; * Controls running all pre and post validation for workflows. * * To define a validation you must make it a spring bean and implement either - * {@link org.onap.so.bpmn.common.validation.PreWorkflowValidator} or - * {@link org.onap.so.bpmn.common.validation.PostWorkflowValidator} your validation will automatically be run by this - * class. + * {@link org.onap.so.bpmn.common.listener.validation.PreWorkflowValidator} or + * {@link org.onap.so.bpmn.common.listener.validation.PostWorkflowValidator} your validation will automatically be run + * by this class. * */ @Component diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnRestClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnRestClient.java index b9200e0640..c98c9ad5da 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnRestClient.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnRestClient.java @@ -25,6 +25,7 @@ package org.onap.so.bpmn.common.recipe; import java.io.IOException; import java.security.GeneralSecurityException; import javax.xml.bind.DatatypeConverter; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; @@ -62,16 +63,12 @@ public class BpmnRestClient { public static final String CAMUNDA_AUTH = "mso.camundaAuth"; - private static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA"; @Autowired private UrnPropertiesReader urnPropertiesReader; private static boolean noProperties = true; - // because for NS it will take a long time the time out of the resouce will be 2 hours. - private static final String DEFAULT_TIME_OUT = "7200"; - - public synchronized final boolean getNoPropertiesState() { + public final synchronized boolean getNoPropertiesState() { return noProperties; } @@ -93,7 +90,7 @@ public class BpmnRestClient { */ public HttpResponse post(String recipeUri, String requestId, int recipeTimeout, String requestAction, String serviceInstanceId, String serviceType, String requestDetails, String recipeParamXsd) - throws ClientProtocolException, IOException { + throws IOException { HttpClient client = HttpClientBuilder.create().build(); @@ -163,7 +160,7 @@ public class BpmnRestClient { BpmnParam recipeParamsInput = new BpmnParam(); BpmnIntegerParam recipeTimeoutInput = new BpmnIntegerParam(); recipeTimeoutInput.setValue(recipeTimeout); - // host.setValue(parseURL()); + requestIdInput.setValue(requestId); requestActionInput.setValue(requestAction); serviceInstanceIdInput.setValue(serviceInstanceId); @@ -181,7 +178,7 @@ public class BpmnRestClient { jsonReq = recipeRequest.toString(); logger.trace("request body is {}", jsonReq); } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", "wrapVIDRequest", + logger.error(LoggingAnchor.FIVE, MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", "wrapVIDRequest", ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e); } return jsonReq; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceInput.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceInput.java index 33c48fbe44..91049a8d0c 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceInput.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/ResourceInput.java @@ -21,6 +21,7 @@ */ package org.onap.so.bpmn.common.recipe; +import java.io.Serializable; import org.onap.so.bpmn.core.domain.ModelInfo; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -43,7 +44,7 @@ import org.slf4j.LoggerFactory; "operationId", "serviceModelInfo", "resourceModelInfo", "resourceInstancenUuid", "resourceParameters", "operationType"}) @JsonRootName("variables") -public class ResourceInput { +public class ResourceInput implements Serializable { private static Logger logger = LoggerFactory.getLogger(ResourceInput.class); diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/InstanceResourceList.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/InstanceResourceList.java index cc628657db..2b650e1eed 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/InstanceResourceList.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/InstanceResourceList.java @@ -31,13 +31,16 @@ import org.onap.so.bpmn.core.domain.VnfResource; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; public class InstanceResourceList { + private InstanceResourceList() { + throw new IllegalStateException("Utility class"); + } + private static Map<String, List<List<GroupResource>>> convertUUIReqTOStd(final JsonObject reqInputJsonObj, List<Resource> seqResourceList) { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilder.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilder.java index 9d0b9e42cc..faa3d74dba 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilder.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilder.java @@ -41,7 +41,6 @@ import org.onap.so.bpmn.core.domain.GroupResource; import org.onap.so.bpmn.core.domain.Resource; import org.onap.so.bpmn.core.domain.ResourceType; import org.onap.so.bpmn.core.domain.VnfResource; -import org.onap.so.bpmn.core.domain.VnfcResource; import org.onap.so.bpmn.core.json.JsonUtils; import org.onap.so.client.HttpClient; import org.onap.so.client.HttpClientFactory; @@ -56,14 +55,16 @@ import org.slf4j.LoggerFactory; public class ResourceRequestBuilder { - private static String CUSTOMIZATION_UUID = "cuserviceResourcesstomizationUUID"; - private static String SERVICE_URL_SERVICE_INSTANCE = "/v2/serviceResources"; private static Logger logger = LoggerFactory.getLogger(ResourceRequestBuilder.class); static JsonUtils jsonUtil = new JsonUtils(); + private ResourceRequestBuilder() { + throw new IllegalStateException("Utility class"); + } + public static List<String> getResourceSequence(String serviceUuid) { List<String> resourceSequence = new ArrayList(); @@ -111,7 +112,7 @@ public class ResourceRequestBuilder { String locationConstraints = "[]"; if (resource.getResourceType() == ResourceType.VNF) { for (String eachResource : resourceList) { - String resCusUuid = (String) JsonUtils.getJsonValue(eachResource, "resourceCustomizationUuid"); + String resCusUuid = JsonUtils.getJsonValue(eachResource, "resourceCustomizationUuid"); if ((null != resCusUuid) && resCusUuid.equals(resource.getModelInfo().getModelCustomizationUuid())) { String resourceParameters = JsonUtils.getJsonValue(eachResource, "parameters"); locationConstraints = JsonUtils.getJsonValue(resourceParameters, "locationConstraints"); @@ -156,7 +157,6 @@ public class ResourceRequestBuilder { break; } - Map<String, Object> resourceInputsAfterMerge = new HashMap<>(); if (StringUtils.isNotEmpty(resourceInputStr)) { return getResourceInput(resourceInputStr, uuiRequestInputs, resourceLevel, currentVFData); } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContextHolder.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContextHolder.java index 33fb78b306..047b1f3930 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContextHolder.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContextHolder.java @@ -25,6 +25,7 @@ package org.onap.so.bpmn.common.workflow.context; import java.util.concurrent.DelayQueue; import java.util.concurrent.TimeUnit; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; @@ -130,7 +131,7 @@ public class WorkflowContextHolder { Thread.currentThread().interrupt(); } catch (Exception e) { logger.debug("WorkflowContextHolder timeout thread caught exception: ", e); - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", ErrorCode.UnknownError.getValue(), "Error in WorkflowContextHolder timeout thread"); } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Configuration.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Configuration.java index dff5a57040..36262ec800 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Configuration.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Configuration.java @@ -78,6 +78,9 @@ public class Configuration implements Serializable, ShallowCopy<Configuration> { @JsonProperty("l-interface") private LInterface lInterface; + @JsonProperty("vpn-binding") + private VpnBinding vpnBinding; + public ModelInfoConfiguration getModelInfoConfiguration() { return modelInfoConfiguration; } @@ -222,6 +225,14 @@ public class Configuration implements Serializable, ShallowCopy<Configuration> { this.lInterface = lInterface; } + public VpnBinding getVpnBinding() { + return vpnBinding; + } + + public void setVpnBinding(VpnBinding vpnBinding) { + this.vpnBinding = vpnBinding; + } + @Override public boolean equals(final Object other) { if (!(other instanceof Configuration)) { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceInstance.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceInstance.java index b9f5a6af8e..0803bed574 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceInstance.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceInstance.java @@ -81,6 +81,10 @@ public class ServiceInstance implements Serializable, ShallowCopy<ServiceInstanc @JsonProperty("service-proxies") private List<ServiceProxy> serviceProxies = new ArrayList<ServiceProxy>(); + public void setServiceProxies(List<ServiceProxy> serviceProxies) { + this.serviceProxies = serviceProxies; + } + public List<GenericVnf> getVnfs() { return vnfs; } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vnfc.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vnfc.java index 087edff7c0..08b1124726 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vnfc.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vnfc.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.servicedecomposition.bbobjects; import java.io.Serializable; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/wrappers/ServiceInstanceWrapper.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/wrappers/ServiceInstanceWrapper.java new file mode 100644 index 0000000000..1f7f970058 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/wrappers/ServiceInstanceWrapper.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.servicedecomposition.bbobjects.wrappers; + +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceProxy; +import org.onap.so.bpmn.servicedecomposition.bbobjects.wrappers.exceptions.ServiceProxyNotFoundException; + +public class ServiceInstanceWrapper { + + private final ServiceInstance serviceInstance; + private static final String SERVICE_PROXY_TRANSPORT = "TRANSPORT"; + + public ServiceInstanceWrapper(ServiceInstance serviceInstance) { + this.serviceInstance = serviceInstance; + } + + public ServiceProxy getTransportServiceProxy() throws ServiceProxyNotFoundException { + ServiceProxy serviceProxy = null; + for (ServiceProxy sp : serviceInstance.getServiceProxies()) { + if (SERVICE_PROXY_TRANSPORT.equalsIgnoreCase(sp.getType())) { + serviceProxy = sp; + break; + } + } + if (serviceProxy == null) { + throw new ServiceProxyNotFoundException("Transport Service Proxy not found for service instance: " + + serviceInstance.getServiceInstanceId()); + } + return serviceProxy; + } + + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/wrappers/exceptions/ServiceProxyNotFoundException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/wrappers/exceptions/ServiceProxyNotFoundException.java new file mode 100644 index 0000000000..046299bb13 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/wrappers/exceptions/ServiceProxyNotFoundException.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.servicedecomposition.bbobjects.wrappers.exceptions; + +public class ServiceProxyNotFoundException extends Exception { + + private static final long serialVersionUID = 717577158109655720L; + + public ServiceProxyNotFoundException() { + super(); + } + + public ServiceProxyNotFoundException(String message) { + super(message); + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ExecuteBuildingBlock.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ExecuteBuildingBlock.java index af9eb525aa..f1de0cc6f6 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ExecuteBuildingBlock.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ExecuteBuildingBlock.java @@ -35,7 +35,7 @@ public class ExecuteBuildingBlock implements Serializable { private String requestAction; private String vnfType; private Boolean aLaCarte; - private Boolean homing; + private Boolean homing = false; private WorkflowResourceIds workflowResourceIds; private RequestDetails requestDetails; private ConfigurationResourceKeys configurationResourceKeys; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ResourceKey.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ResourceKey.java index 9e95e79b70..8608fee244 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ResourceKey.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ResourceKey.java @@ -21,5 +21,15 @@ package org.onap.so.bpmn.servicedecomposition.entities; public enum ResourceKey { - SERVICE_INSTANCE_ID, GENERIC_VNF_ID, NETWORK_ID, VOLUME_GROUP_ID, VF_MODULE_ID, ALLOTTED_RESOURCE_ID, CONFIGURATION_ID, NETWORK_COLLECTION_ID, VPN_ID, VPN_BONDING_LINK_ID, INSTANCE_GROUP_ID; + SERVICE_INSTANCE_ID, + GENERIC_VNF_ID, + NETWORK_ID, + VOLUME_GROUP_ID, + VF_MODULE_ID, + ALLOTTED_RESOURCE_ID, + CONFIGURATION_ID, + NETWORK_COLLECTION_ID, + VPN_ID, + VPN_BONDING_LINK_ID, + INSTANCE_GROUP_ID; } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionCandidates.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionCandidates.java index 4c91ad38a0..068fa876ce 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionCandidates.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/homingobjects/SolutionCandidates.java @@ -36,6 +36,8 @@ public class SolutionCandidates implements Serializable { private List<Candidate> excludedCandidates = new ArrayList<Candidate>(); @JsonProperty("existingCandidates") private List<Candidate> existingCandidates = new ArrayList<Candidate>(); + @JsonProperty("filteringAttributes") + private List<Candidate> filteringAttributes = new ArrayList<Candidate>(); public List<Candidate> getRequiredCandidates() { @@ -58,6 +60,8 @@ public class SolutionCandidates implements Serializable { return existingCandidates; } - + public List<Candidate> getFilteringAttributes() { + return filteringAttributes; + } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoGenericVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoGenericVnf.java index 14327a3583..a558057979 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoGenericVnf.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoGenericVnf.java @@ -55,7 +55,26 @@ public class ModelInfoGenericVnf extends ModelInfoMetadata implements Serializab private String MultiStageDesign; @JsonProperty("created") private String Created; + @JsonProperty("blueprintName") + private String blueprintName; + @JsonProperty("blueprintVersion") + private String blueprintVersion; + public String getBlueprintName() { + return blueprintName; + } + + public void setBlueprintName(String blueprintName) { + this.blueprintName = blueprintName; + } + + public String getBlueprintVersion() { + return blueprintVersion; + } + + public void setBlueprintVersion(String blueprintVersion) { + this.blueprintVersion = blueprintVersion; + } public String getToscaNodeType() { return ToscaNodeType; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoServiceInstance.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoServiceInstance.java index 05cad456d0..bc330eeafd 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoServiceInstance.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoServiceInstance.java @@ -39,6 +39,10 @@ public class ModelInfoServiceInstance extends ModelInfoMetadata implements Seria private String environmentContext; @JsonProperty("workload-context") private String workloadContext; + @JsonProperty("naming-policy") + private String namingPolicy; + @JsonProperty("onap-generated-naming") + private Boolean onapGeneratedNaming; public String getDescription() { @@ -88,4 +92,21 @@ public class ModelInfoServiceInstance extends ModelInfoMetadata implements Seria public void setWorkloadContext(String workloadContext) { this.workloadContext = workloadContext; } + + + public String getNamingPolicy() { + return namingPolicy; + } + + public void setNamingPolicy(String namingPolicy) { + this.namingPolicy = namingPolicy; + } + + public Boolean getOnapGeneratedNaming() { + return onapGeneratedNaming; + } + + public void setOnapGeneratedNaming(Boolean onapGeneratedNaming) { + this.onapGeneratedNaming = onapGeneratedNaming; + } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoServiceProxy.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoServiceProxy.java index b2494384f4..91ff3d623d 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoServiceProxy.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/modelinfo/ModelInfoServiceProxy.java @@ -22,11 +22,31 @@ package org.onap.so.bpmn.servicedecomposition.modelinfo; import java.io.Serializable; +import com.fasterxml.jackson.annotation.JsonProperty; public class ModelInfoServiceProxy extends ModelInfoMetadata implements Serializable { private static final long serialVersionUID = -6256897576261215926L; + @JsonProperty("tosca-node-type") + private String toscaNodeType; + @JsonProperty("description") + private String description; + public String getToscaNodeType() { + return toscaNodeType; + } + + public void setToscaNodeType(String toscaNodeType) { + this.toscaNodeType = toscaNodeType; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/AssignFlows.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/AssignFlows.java index 7ca6076b21..f23f62d763 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/AssignFlows.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/AssignFlows.java @@ -22,10 +22,15 @@ package org.onap.so.bpmn.servicedecomposition.tasks; public enum AssignFlows { - SERVICE_INSTANCE("AssignServiceInstanceBB"), VNF("AssignVnfBB"), VF_MODULE("AssignVfModuleBB"), NETWORK_A_LA_CARTE( - "AssignNetwork1802BB"), NETWORK_MACRO("AssignNetworkBB"), VOLUME_GROUP( - "AssignVolumeGroupBB"), NETWORK_COLLECTION( - "CreateNetworkCollectionBB"), FABRIC_CONFIGURATION("AssignFabricConfigurationBB"); + SERVICE_INSTANCE("AssignServiceInstanceBB"), + VNF("AssignVnfBB"), + VF_MODULE("AssignVfModuleBB"), + NETWORK_A_LA_CARTE("AssignNetwork1802BB"), + NETWORK_MACRO("AssignNetworkBB"), + VOLUME_GROUP("AssignVolumeGroupBB"), + NETWORK_COLLECTION("CreateNetworkCollectionBB"), + FABRIC_CONFIGURATION("AssignFabricConfigurationBB"), + VRF_CONFIGURATION("AssignVrfConfigurationBBV2"); private final String flowName; 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 2d066285a4..c7665acc68 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 @@ -47,11 +47,13 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform; import org.onap.so.bpmn.servicedecomposition.bbobjects.Project; import org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTableReference; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceProxy; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceSubscription; import org.onap.so.bpmn.servicedecomposition.bbobjects.Tenant; import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; import org.onap.so.bpmn.servicedecomposition.bbobjects.Vnfc; import org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup; +import org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBinding; import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys; import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; @@ -76,6 +78,7 @@ import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization; import org.onap.so.db.catalog.beans.NetworkResourceCustomization; import org.onap.so.db.catalog.beans.OrchestrationStatus; import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.catalog.beans.ServiceProxyResourceCustomization; import org.onap.so.db.catalog.beans.VfModuleCustomization; import org.onap.so.db.catalog.beans.VnfResourceCustomization; import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization; @@ -342,7 +345,7 @@ public class BBInputSetup implements JavaDelegate { ModelInfo configurationModelInfo = new ModelInfo(); configurationModelInfo.setModelCustomizationUuid(configurationKey); populateConfiguration(configurationModelInfo, service, bbName, serviceInstance, lookupKeyMap, - configurationId, instanceName, configurationResourceKeys); + configurationId, instanceName, configurationResourceKeys, requestDetails); } else { lookupKeyMap.put(ResourceKey.VF_MODULE_ID, resourceId); this.populateVfModule(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId, @@ -372,7 +375,7 @@ public class BBInputSetup implements JavaDelegate { protected void populateConfiguration(ModelInfo modelInfo, Service service, String bbName, ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, String resourceId, - String instanceName, ConfigurationResourceKeys configurationResourceKeys) { + String instanceName, ConfigurationResourceKeys configurationResourceKeys, RequestDetails requestDetails) { Configuration configuration = null; for (Configuration configurationTemp : serviceInstance.getConfigurations()) { if (lookupKeyMap.get(ResourceKey.CONFIGURATION_ID) != null && configurationTemp.getConfigurationId() @@ -385,14 +388,20 @@ public class BBInputSetup implements JavaDelegate { } } } - if (configuration == null && bbName.equalsIgnoreCase(AssignFlows.FABRIC_CONFIGURATION.toString())) { + if (configuration == null && (bbName.equalsIgnoreCase(AssignFlows.FABRIC_CONFIGURATION.toString()) + || bbName.equalsIgnoreCase(AssignFlows.VRF_CONFIGURATION.toString()))) { configuration = this.createConfiguration(lookupKeyMap, instanceName, resourceId); serviceInstance.getConfigurations().add(configuration); } - if (configuration != null) { + if (configuration != null && bbName.contains("Fabric")) { Vnfc vnfc = getVnfcToConfiguration(configurationResourceKeys.getVnfcName()); configuration.setVnfc(vnfc); this.mapCatalogConfiguration(configuration, modelInfo, service, configurationResourceKeys); + } else if (configuration != null && bbName.contains("Vrf")) { + configuration.setModelInfoConfiguration(mapperLayer.mapCatalogConfigurationToConfiguration( + findConfigurationResourceCustomization(modelInfo, service), null)); + configuration.setConfigurationType(configuration.getModelInfoConfiguration().getConfigurationType()); + configuration.setConfigurationSubType(configuration.getModelInfoConfiguration().getConfigurationRole()); } } @@ -1115,15 +1124,67 @@ public class BBInputSetup implements JavaDelegate { ModelInfo configurationModelInfo = new ModelInfo(); configurationModelInfo.setModelCustomizationUuid(key); this.populateConfiguration(configurationModelInfo, service, bbName, serviceInstance, lookupKeyMap, - configurationId, null, executeBB.getConfigurationResourceKeys()); + configurationId, null, executeBB.getConfigurationResourceKeys(), executeBB.getRequestDetails()); } if (executeBB.getWorkflowResourceIds() != null) { this.populateNetworkCollectionAndInstanceGroupAssign(service, bbName, serviceInstance, executeBB.getWorkflowResourceIds().getNetworkCollectionId(), key); } + RelatedInstance relatedVpnBinding = + bbInputSetupUtils.getRelatedInstanceByType(executeBB.getRequestDetails(), ModelType.vpnBinding); + RelatedInstance relatedLocalNetwork = + bbInputSetupUtils.getRelatedInstanceByType(executeBB.getRequestDetails(), ModelType.network); + if (relatedVpnBinding != null && relatedLocalNetwork != null) { + org.onap.aai.domain.yang.VpnBinding aaiVpnBinding = + bbInputSetupUtils.getAAIVpnBinding(relatedVpnBinding.getInstanceId()); + org.onap.aai.domain.yang.L3Network aaiLocalNetwork = + bbInputSetupUtils.getAAIL3Network(relatedLocalNetwork.getInstanceId()); + VpnBinding vpnBinding = mapperLayer.mapAAIVpnBinding(aaiVpnBinding); + L3Network localNetwork = mapperLayer.mapAAIL3Network(aaiLocalNetwork); + Optional<org.onap.aai.domain.yang.VpnBinding> aaiAICVpnBindingOp = + bbInputSetupUtils.getAICVpnBindingFromNetwork(aaiLocalNetwork); + if (aaiAICVpnBindingOp.isPresent()) { + localNetwork.getVpnBindings().add(mapperLayer.mapAAIVpnBinding(aaiAICVpnBindingOp.get())); + } + ServiceProxy serviceProxy = getServiceProxy(service); + gBB.getServiceInstance().getServiceProxies().add(serviceProxy); + gBB.getCustomer().getVpnBindings().add(vpnBinding); + lookupKeyMap.put(ResourceKey.VPN_ID, vpnBinding.getVpnId()); + gBB.getServiceInstance().getNetworks().add(localNetwork); + lookupKeyMap.put(ResourceKey.NETWORK_ID, localNetwork.getNetworkId()); + } return gBB; } + protected ServiceProxy getServiceProxy(Service service) { + if (!service.getServiceProxyCustomizations().isEmpty()) { + ServiceProxyResourceCustomization serviceProxyCatalog = getServiceProxyResourceCustomization(service); + ServiceProxy serviceProxy = new ServiceProxy(); + serviceProxy.setModelInfoServiceProxy( + mapperLayer.mapServiceProxyCustomizationToServiceProxy(serviceProxyCatalog)); + Service sourceService = serviceProxyCatalog.getSourceService(); + ServiceInstance sourceServiceShell = new ServiceInstance(); + sourceServiceShell + .setModelInfoServiceInstance(mapperLayer.mapCatalogServiceIntoServiceInstance(sourceService)); + serviceProxy.setServiceInstance(sourceServiceShell); + serviceProxy.setType(sourceService.getServiceType()); + return serviceProxy; + } else { + return null; + } + } + + protected ServiceProxyResourceCustomization getServiceProxyResourceCustomization(Service service) { + ServiceProxyResourceCustomization serviceProxyCatalog = null; + for (ServiceProxyResourceCustomization serviceProxyTemp : service.getServiceProxyCustomizations()) { + if (serviceProxyTemp.getSourceService() != null + && serviceProxyTemp.getSourceService().getServiceType().equalsIgnoreCase("TRANSPORT")) { + serviceProxyCatalog = serviceProxyTemp; + } + } + return serviceProxyCatalog; + } + protected L3Network getVirtualLinkL3Network(Map<ResourceKey, String> lookupKeyMap, String bbName, String key, String networkId, CollectionNetworkResourceCustomization collectionNetworkResourceCust, ServiceInstance serviceInstance) { @@ -1348,7 +1409,7 @@ public class BBInputSetup implements JavaDelegate { findConfigurationResourceCustomization(configurationModelInfo, service); if (configurationCust != null) { this.populateConfiguration(configurationModelInfo, service, bbName, serviceInstance, lookupKeyMap, - configurationId, null, executeBB.getConfigurationResourceKeys()); + configurationId, null, executeBB.getConfigurationResourceKeys(), executeBB.getRequestDetails()); } else { logger.debug("Could not find a configuration customization with key: {}", key); } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java index 86f7eeb2cd..63dd72566b 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java @@ -49,6 +49,7 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.OwningEntity; import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform; import org.onap.so.bpmn.servicedecomposition.bbobjects.Project; import org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTableReference; +import org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTarget; import org.onap.so.bpmn.servicedecomposition.bbobjects.SegmentationAssignment; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceSubscription; @@ -57,6 +58,7 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.Tenant; import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; import org.onap.so.bpmn.servicedecomposition.bbobjects.Vnfc; import org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup; +import org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBinding; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; import org.onap.so.bpmn.servicedecomposition.generalobjects.License; import org.onap.so.bpmn.servicedecomposition.generalobjects.OrchestrationContext; @@ -68,6 +70,7 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoGenericVnf; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoInstanceGroup; 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.db.catalog.beans.CollectionNetworkResourceCustomization; import org.onap.so.db.catalog.beans.CollectionResource; @@ -80,6 +83,7 @@ import org.onap.so.db.catalog.beans.InstanceGroupType; import org.onap.so.db.catalog.beans.NetworkResourceCustomization; import org.onap.so.db.catalog.beans.OrchestrationStatus; import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.catalog.beans.ServiceProxyResourceCustomization; import org.onap.so.db.catalog.beans.VfModuleCustomization; import org.onap.so.db.catalog.beans.VnfResourceCustomization; import org.onap.so.serviceinstancebeans.CloudConfiguration; @@ -350,7 +354,9 @@ public class BBInputSetupMapperLayer { public RequestContext mapRequestContext(RequestDetails requestDetails) { RequestContext context = new RequestContext(); - modelMapper.map(requestDetails.getRequestInfo(), context); + if (null != requestDetails.getRequestInfo()) { + modelMapper.map(requestDetails.getRequestInfo(), context); + } org.onap.so.serviceinstancebeans.RequestParameters requestParameters = requestDetails.getRequestParameters(); if (null != requestParameters) { context.setSubscriptionServiceType(requestParameters.getSubscriptionServiceType()); @@ -393,7 +399,11 @@ public class BBInputSetupMapperLayer { protected OrchestrationContext mapOrchestrationContext(RequestDetails requestDetails) { OrchestrationContext context = new OrchestrationContext(); - context.setIsRollbackEnabled(!(requestDetails.getRequestInfo().getSuppressRollback())); + if (requestDetails.getRequestInfo() != null) { + context.setIsRollbackEnabled(!(requestDetails.getRequestInfo().getSuppressRollback())); + } else { + context.setIsRollbackEnabled(false); + } return context; } @@ -511,13 +521,18 @@ public class BBInputSetupMapperLayer { protected ModelInfoConfiguration mapCatalogConfigurationToConfiguration( ConfigurationResourceCustomization configurationResourceCustomization, CvnfcConfigurationCustomization cvnfcConfigurationCustomization) { + ModelInfoConfiguration modelInfoConfiguration = new ModelInfoConfiguration(); modelInfoConfiguration .setModelVersionId(configurationResourceCustomization.getConfigurationResource().getModelUUID()); modelInfoConfiguration.setModelCustomizationId(configurationResourceCustomization.getModelCustomizationUUID()); modelInfoConfiguration.setModelInvariantId( configurationResourceCustomization.getConfigurationResource().getModelInvariantUUID()); - modelInfoConfiguration.setPolicyName(cvnfcConfigurationCustomization.getPolicyName()); + modelInfoConfiguration.setConfigurationRole(configurationResourceCustomization.getRole()); + modelInfoConfiguration.setConfigurationType(configurationResourceCustomization.getType()); + if (cvnfcConfigurationCustomization != null) { + modelInfoConfiguration.setPolicyName(cvnfcConfigurationCustomization.getPolicyName()); + } return modelInfoConfiguration; } @@ -543,4 +558,29 @@ public class BBInputSetupMapperLayer { public Vnfc mapAAIVnfc(org.onap.aai.domain.yang.Vnfc vnfcAAI) { return modelMapper.map(vnfcAAI, Vnfc.class); } + + public VpnBinding mapAAIVpnBinding(org.onap.aai.domain.yang.VpnBinding aaiVpnBinding) { + VpnBinding vpnBinding = modelMapper.map(aaiVpnBinding, VpnBinding.class); + mapAllRouteTargetsToAAIVpnBinding(aaiVpnBinding, vpnBinding); + return vpnBinding; + } + + protected void mapAllRouteTargetsToAAIVpnBinding(org.onap.aai.domain.yang.VpnBinding aaiVpnBinding, + VpnBinding vpnBinding) { + if (aaiVpnBinding.getRouteTargets() != null) { + for (org.onap.aai.domain.yang.RouteTarget aaiRouteTarget : aaiVpnBinding.getRouteTargets() + .getRouteTarget()) { + vpnBinding.getRouteTargets().add(mapAAIRouteTarget(aaiRouteTarget)); + } + } + } + + public RouteTarget mapAAIRouteTarget(org.onap.aai.domain.yang.RouteTarget aaiRouteTarget) { + return modelMapper.map(aaiRouteTarget, RouteTarget.class); + } + + protected ModelInfoServiceProxy mapServiceProxyCustomizationToServiceProxy( + ServiceProxyResourceCustomization serviceProxyCustomization) { + return modelMapper.map(serviceProxyCustomization, ModelInfoServiceProxy.class); + } } 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 5cf2bd7b39..8ac5f6e69b 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 @@ -39,6 +39,7 @@ import org.onap.aai.domain.yang.ServiceSubscription; import org.onap.aai.domain.yang.VfModule; import org.onap.aai.domain.yang.VolumeGroup; import org.onap.aai.domain.yang.VolumeGroups; +import org.onap.aai.domain.yang.VpnBinding; import org.onap.so.bpmn.common.InjectionHelper; import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer; import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.MultipleObjectsFoundException; @@ -60,6 +61,9 @@ import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.serviceinstancebeans.CloudConfiguration; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RelatedInstance; +import org.onap.so.serviceinstancebeans.RelatedInstanceList; import org.onap.so.serviceinstancebeans.RequestDetails; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -85,6 +89,20 @@ public class BBInputSetupUtils { @Autowired protected InjectionHelper injectionHelper; + public RelatedInstance getRelatedInstanceByType(RequestDetails requestDetails, ModelType modelType) { + if (requestDetails.getRelatedInstanceList() != null) { + for (RelatedInstanceList relatedInstanceList : requestDetails.getRelatedInstanceList()) { + RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); + if (relatedInstance != null && relatedInstance.getModelInfo() != null + && relatedInstance.getModelInfo().getModelType() != null + && relatedInstance.getModelInfo().getModelType().equals(modelType)) { + return relatedInstance; + } + } + } + return null; + } + public void updateInfraActiveRequestVnfId(InfraActiveRequests request, String vnfId) { if (request != null) { request.setVnfId(vnfId); @@ -334,6 +352,17 @@ public class BBInputSetupUtils { }); } + public VpnBinding getAAIVpnBinding(String vpnBindingId) { + + return this.injectionHelper.getAaiClient() + .get(VpnBinding.class, + AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING, vpnBindingId).depth(Depth.ONE)) + .orElseGet(() -> { + logger.debug("No VpnBinding matched by id"); + return null; + }); + } + public VolumeGroup getAAIVolumeGroup(String cloudOwnerId, String cloudRegionId, String volumeGroupId) { return this.injectionHelper.getAaiClient() .get(VolumeGroup.class, AAIUriFactory @@ -463,4 +492,16 @@ public class BBInputSetupUtils { return Optional.of(volumeGroup); } } + + public Optional<org.onap.aai.domain.yang.VpnBinding> getAICVpnBindingFromNetwork( + org.onap.aai.domain.yang.L3Network aaiLocalNetwork) { + AAIResultWrapper networkWrapper = new AAIResultWrapper(aaiLocalNetwork); + if (networkWrapper.getRelationships().isPresent() + && !networkWrapper.getRelationships().get().getRelatedUris(AAIObjectType.VPN_BINDING).isEmpty()) { + return getAAIResourceDepthOne( + networkWrapper.getRelationships().get().getRelatedUris(AAIObjectType.VPN_BINDING).get(0)) + .asBean(org.onap.aai.domain.yang.VpnBinding.class); + } + return Optional.empty(); + } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java index 86bbead9a4..b76316bf0e 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java @@ -57,8 +57,13 @@ public class ExtractPojosForBB { GenericVnf vnf; switch (key) { case SERVICE_INSTANCE_ID: - result = lookupObjectInList(gBBInput.getCustomer().getServiceSubscription().getServiceInstances(), - value); + if (gBBInput.getCustomer().getServiceSubscription() == null + && gBBInput.getServiceInstance() != null) { + result = Optional.of((T) gBBInput.getServiceInstance()); + } else { + result = lookupObjectInList( + gBBInput.getCustomer().getServiceSubscription().getServiceInstances(), value); + } break; case GENERIC_VNF_ID: serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/DuplicateNameException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/DuplicateNameException.java new file mode 100644 index 0000000000..2f2a116526 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/DuplicateNameException.java @@ -0,0 +1,18 @@ +package org.onap.so.bpmn.servicedecomposition.tasks.exceptions; + +public class DuplicateNameException extends Exception { + + private static final long serialVersionUID = -2850043981787600326L; + + public DuplicateNameException() { + super(); + } + + public DuplicateNameException(String message) { + super(message); + } + + public DuplicateNameException(String objectType, String name) { + super(objectType + " with name " + name + " already exists. The name must be unique."); + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerAction.java index eccd81217f..b97b9ac1ca 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerAction.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/appc/ApplicationControllerAction.java @@ -68,6 +68,12 @@ public class ApplicationControllerAction { case QuiesceTraffic: appCStatus = quiesceTrafficAction(msoRequestId, vnfId, payload, vnfName, controllerType); break; + case DistributeTraffic: + appCStatus = distributeTrafficAction(msoRequestId, vnfId, payload, vnfName, controllerType); + break; + case DistributeTrafficCheck: + appCStatus = distributeTrafficCheckAction(msoRequestId, vnfId, payload, vnfName, controllerType); + break; case HealthCheck: appCStatus = healthCheckAction(msoRequestId, vnfId, vnfName, vnfHostIpAddress, controllerType); break; @@ -91,8 +97,6 @@ public class ApplicationControllerAction { break; case ConfigModify: case ConfigScaleOut: - case DistributeTraffic: - case DistributeTrafficCheck: appCStatus = payloadAction(action, msoRequestId, vnfId, payload, controllerType); break; case UpgradePreCheck: @@ -158,6 +162,29 @@ public class ApplicationControllerAction { return client.vnfCommand(action, msoRequestId, vnfId, Optional.empty(), payload, controllerType); } + private Status distributeTrafficAction(String msoRequestId, String vnfId, Optional<String> payload, String vnfName, + String controllerType) + throws JsonProcessingException, IllegalArgumentException, ApplicationControllerOrchestratorException { + if (!(payload.isPresent())) { + throw new IllegalArgumentException("Payload is not present for " + Action.DistributeTraffic.toString()); + } + payload = PayloadClient.distributeTrafficFormat(payload, vnfName); + return client.vnfCommand(Action.DistributeTraffic, msoRequestId, vnfId, Optional.empty(), payload, + controllerType); + } + + private Status distributeTrafficCheckAction(String msoRequestId, String vnfId, Optional<String> payload, + String vnfName, String controllerType) + throws JsonProcessingException, IllegalArgumentException, ApplicationControllerOrchestratorException { + if (!(payload.isPresent())) { + throw new IllegalArgumentException( + "Payload is not present for " + Action.DistributeTrafficCheck.toString()); + } + payload = PayloadClient.distributeTrafficCheckFormat(payload, vnfName); + return client.vnfCommand(Action.DistributeTrafficCheck, msoRequestId, vnfId, Optional.empty(), payload, + controllerType); + } + private Status resumeTrafficAction(String msoRequestId, String vnfId, String vnfName, String controllerType) throws JsonProcessingException, ApplicationControllerOrchestratorException { Optional<String> payload = PayloadClient.resumeTrafficFormat(vnfName); diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtils.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtils.java index 6bfa67502d..5498b5be31 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtils.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtils.java @@ -34,6 +34,7 @@ import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOu import org.onap.so.client.PreconditionFailedException; import org.onap.so.client.RestPropertiesLoader; import org.onap.so.client.cds.beans.AbstractCDSPropertiesBean; +import org.onap.so.client.exception.BadResponseException; import org.onap.so.client.exception.ExceptionBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,6 +59,12 @@ public class AbstractCDSProcessingBBUtils implements CDSProcessingListener { private static final String FAILED = "Failed"; private static final String PROCESSING = "Processing"; + /** + * indicate exception thrown. + */ + private static final String EXCEPTION = "Exception"; + + private final AtomicReference<String> cdsResponse = new AtomicReference<>(); @Autowired @@ -132,7 +139,15 @@ public class AbstractCDSProcessingBBUtils implements CDSProcessingListener { } if (cdsResponse != null) { - execution.setVariable("CDSStatus", cdsResponse.get()); + String cdsResponseStatus = cdsResponse.get(); + execution.setVariable("CDSStatus", cdsResponseStatus); + + /** + * throw CDS failed exception. + */ + if (cdsResponseStatus != SUCCESS) { + throw new BadResponseException("CDS call failed with status: " + cdsResponseStatus); + } } } catch (Exception ex) { @@ -177,6 +192,7 @@ public class AbstractCDSProcessingBBUtils implements CDSProcessingListener { public void onError(Throwable t) { Status status = Status.fromThrowable(t); logger.error("Failed processing blueprint {}", status, t); + cdsResponse.set(EXCEPTION); } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExceptionBuilder.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExceptionBuilder.java index dabfc81e1f..d656314fd1 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExceptionBuilder.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExceptionBuilder.java @@ -26,6 +26,7 @@ import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.onap.so.logger.LoggingAnchor; import org.camunda.bpm.engine.delegate.BpmnError; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.onap.aai.domain.yang.LInterface; @@ -75,7 +76,7 @@ public class ExceptionBuilder { } } - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue(), msg.toString()); execution.setVariable(errorVariable, exception.getMessage()); } catch (Exception ex) { @@ -106,7 +107,7 @@ public class ExceptionBuilder { break; } } - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue(), msg.toString()); execution.setVariable(errorVariable, exception.getMessage()); } catch (Exception ex) { @@ -153,65 +154,67 @@ public class ExceptionBuilder { } public void processAuditException(DelegateExecutionImpl execution, boolean flowShouldContinue) { - logger.info("Building a WorkflowException for Subflow"); + logger.debug("Processing Audit Results"); + String auditListString = (String) execution.getVariable("auditInventoryResult"); + if (auditListString != null) { + StringBuilder errorMessage = new StringBuilder(); + String processKey = getProcessKey(execution.getDelegateExecution()); + try { + ExtractPojosForBB extractPojosForBB = getExtractPojosForBB(); + VfModule module = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); + String cloudRegionId = execution.getGeneralBuildingBlock().getCloudRegion().getLcpCloudRegionId(); + + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + AAIObjectAuditList auditList = + objectMapper.getMapper().readValue(auditListString, AAIObjectAuditList.class); + + errorMessage = errorMessage.append(auditList.getAuditType() + " VF-Module " + module.getVfModuleId() + + " failed due to incomplete AAI vserver inventory population after stack " + + auditList.getHeatStackName() + " was successfully " + auditList.getAuditType() + + "d in cloud region " + cloudRegionId + ". MSO Audit indicates that the following was not " + + auditList.getAuditType() + "d in AAI: "); + + Stream<AAIObjectAudit> vServerLInterfaceAuditStream = auditList.getAuditList().stream() + .filter(auditObject -> auditObject.getAaiObjectType().equals(AAIObjectType.VSERVER.typeName()) + || auditObject.getAaiObjectType().equals(AAIObjectType.L_INTERFACE.typeName())); + List<AAIObjectAudit> filteredAuditStream = + vServerLInterfaceAuditStream.filter(a -> !a.isDoesObjectExist()).collect(Collectors.toList()); + + for (AAIObjectAudit object : filteredAuditStream) { + if (object.getAaiObjectType().equals(AAIObjectType.L_INTERFACE.typeName())) { + LInterface li = objectMapper.getMapper().convertValue(object.getAaiObject(), LInterface.class); + errorMessage = errorMessage + .append(AAIObjectType.L_INTERFACE.typeName() + " " + li.getInterfaceId() + ", "); + } else { + Vserver vs = objectMapper.getMapper().convertValue(object.getAaiObject(), Vserver.class); + errorMessage = + errorMessage.append(AAIObjectType.VSERVER.typeName() + " " + vs.getVserverId() + ", "); + } + } - StringBuilder errorMessage = new StringBuilder(); - String processKey = getProcessKey(execution.getDelegateExecution()); - try { - ExtractPojosForBB extractPojosForBB = getExtractPojosForBB(); - VfModule module = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); - String cloudRegionId = execution.getGeneralBuildingBlock().getCloudRegion().getLcpCloudRegionId(); - - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - String auditListString = (String) execution.getVariable("auditInventoryResult"); - AAIObjectAuditList auditList = - objectMapper.getMapper().readValue(auditListString, AAIObjectAuditList.class); - - errorMessage = errorMessage.append(auditList.getAuditType() + " VF-Module " + module.getVfModuleId() - + " failed due to incomplete A&AI vserver inventory population after stack " - + auditList.getHeatStackName() + " was successfully " + auditList.getAuditType() - + "d in cloud region " + cloudRegionId + ". MSO Audit indicates that AIC RO did not " - + auditList.getAuditType() + " "); - - Stream<AAIObjectAudit> vServerLInterfaceAuditStream = auditList.getAuditList().stream() - .filter(auditObject -> auditObject.getAaiObjectType().equals(AAIObjectType.VSERVER.typeName()) - || auditObject.getAaiObjectType().equals(AAIObjectType.L_INTERFACE.typeName())); - List<AAIObjectAudit> filteredAuditStream = - vServerLInterfaceAuditStream.filter(a -> !a.isDoesObjectExist()).collect(Collectors.toList()); - - for (AAIObjectAudit object : filteredAuditStream) { - if (object.getAaiObjectType().equals(AAIObjectType.L_INTERFACE.typeName())) { - LInterface li = objectMapper.getMapper().convertValue(object.getAaiObject(), LInterface.class); - errorMessage = errorMessage - .append(AAIObjectType.L_INTERFACE.typeName() + " " + li.getInterfaceId() + ", "); - } else { - Vserver vs = objectMapper.getMapper().convertValue(object.getAaiObject(), Vserver.class); - errorMessage = - errorMessage.append(AAIObjectType.VSERVER.typeName() + " " + vs.getVserverId() + ", "); + if (errorMessage.length() > 0) { + errorMessage.setLength(errorMessage.length() - 2); + errorMessage = errorMessage.append("."); } - } - if (errorMessage.length() > 0) { - errorMessage.setLength(errorMessage.length() - 2); - errorMessage = errorMessage.append(" in AAI. "); + } catch (IOException | BBObjectNotFoundException e) { + errorMessage = errorMessage.append("process objects in AAI. "); } - } catch (IOException | BBObjectNotFoundException e) { - errorMessage = errorMessage.append("process objects in AAI. "); - } - - errorMessage.append( - "Recommendation - Wait for nightly RO Audit to run and fix the data issue and resume vf-module creation in VID. If problem persists then report problem to AIC/RO Ops."); + if (flowShouldContinue) { + execution.setVariable("StatusMessage", errorMessage.toString()); + } else { + WorkflowException exception = new WorkflowException(processKey, 400, errorMessage.toString()); + execution.setVariable("WorkflowException", exception); + execution.setVariable("WorkflowExceptionErrorMessage", errorMessage.toString()); + logger.info("Outgoing WorkflowException is {}", exception); + logger.info("Throwing MSOWorkflowException"); + throw new BpmnError("AAIInventoryFailure"); + } - if (flowShouldContinue) { - execution.setVariable("StatusMessage", errorMessage.toString()); } else { - WorkflowException exception = new WorkflowException(processKey, 400, errorMessage.toString()); - execution.setVariable("WorkflowException", exception); - execution.setVariable("WorkflowExceptionErrorMessage", errorMessage.toString()); - logger.info("Outgoing WorkflowException is {}", exception); - logger.info("Throwing MSOWorkflowException"); - throw new BpmnError("AAIInventoryFailure"); + logger.debug("Unable to process audit results due to auditInventoryResult being null"); } } + } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExpectedDataException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExpectedDataException.java index 12ab165c3a..9ead1576cb 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExpectedDataException.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExpectedDataException.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.client.exception; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/UnexpectedDataException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/UnexpectedDataException.java index 84cf491355..9ae14a0162 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/UnexpectedDataException.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/UnexpectedDataException.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.client.exception; diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java index 3bb417741f..9e10058ec8 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java @@ -247,6 +247,7 @@ public class BuildingBlockTestDataSetup { modelInfoConfiguration.setModelCustomizationId("testModelCustomizationId" + configurationCounter); configuration.setModelInfoConfiguration(modelInfoConfiguration); + configuration.setVpnBinding(buildVpnBinding()); return configuration; } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunnerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/BuildingBlockValidatorRunnerTest.java index f13bcb8a93..2c0377d11c 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunnerTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/BuildingBlockValidatorRunnerTest.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -34,6 +34,12 @@ import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.common.DelegateExecutionImpl; +import org.onap.so.bpmn.common.listener.validation.BuildingBlockValidatorRunner; +import org.onap.so.bpmn.common.listener.validation.FlowValidator; +import org.onap.so.bpmn.common.listener.validation.MyPreValidatorOne; +import org.onap.so.bpmn.common.listener.validation.MyPreValidatorThree; +import org.onap.so.bpmn.common.listener.validation.MyPreValidatorTwo; +import org.onap.so.bpmn.common.listener.validation.ValidationConfig; import org.onap.so.bpmn.core.WorkflowException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; @@ -57,7 +63,7 @@ public class BuildingBlockValidatorRunnerTest { MyPreValidatorThree three = new MyPreValidatorThree(); List<FlowValidator> validators = Arrays.asList(one, two, three); - List<FlowValidator> result = runner.filterValidators(validators, "test"); + List<FlowValidator> result = runner.filterListeners(validators, (item -> item.shouldRunFor("test"))); List<FlowValidator> expected = Arrays.asList(two, one); @@ -75,7 +81,7 @@ public class BuildingBlockValidatorRunnerTest { } catch (BpmnError e) { WorkflowException workflowException = (WorkflowException) execution.getVariable("WorkflowException"); assertEquals( - "Failed Validations:\norg.onap.so.bpmn.common.validation.MyPreValidatorTwo: my-error-two\norg.onap.so.bpmn.common.validation.MyPreValidatorOne: my-error-one", + "Failed Validations:\norg.onap.so.bpmn.common.listener.validation.MyPreValidatorTwo: my-error-two\norg.onap.so.bpmn.common.listener.validation.MyPreValidatorOne: my-error-one", workflowException.getErrorMessage()); } runner.preValidate("test2", mock(BuildingBlockExecution.class)); diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunnerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/WorkflowValidatorRunnerTest.java index 07cd790ed1..0143e567af 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowValidatorRunnerTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/WorkflowValidatorRunnerTest.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -33,7 +33,11 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; -import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.listener.validation.FlowValidator; +import org.onap.so.bpmn.common.listener.validation.ValidationConfig; +import org.onap.so.bpmn.common.listener.validation.WorkflowPreValidatorOne; +import org.onap.so.bpmn.common.listener.validation.WorkflowPreValidatorTwo; +import org.onap.so.bpmn.common.listener.validation.WorkflowValidatorRunner; import org.onap.so.bpmn.core.WorkflowException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; @@ -56,7 +60,7 @@ public class WorkflowValidatorRunnerTest { WorkflowPreValidatorTwo two = new WorkflowPreValidatorTwo(); List<FlowValidator> validators = Arrays.asList(one, two); - List<FlowValidator> result = runner.filterValidators(validators, "test"); + List<FlowValidator> result = runner.filterListeners(validators, (item -> item.shouldRunFor("test"))); List<FlowValidator> expected = Arrays.asList(two, one); @@ -74,7 +78,7 @@ public class WorkflowValidatorRunnerTest { } catch (BpmnError e) { WorkflowException workflowException = (WorkflowException) execution.getVariable("WorkflowException"); assertEquals( - "Failed Validations:\norg.onap.so.bpmn.common.validation.WorkflowPreValidatorTwo: my-error-two\norg.onap.so.bpmn.common.validation.WorkflowPreValidatorOne: my-error-one", + "Failed Validations:\norg.onap.so.bpmn.common.listener.validation.WorkflowPreValidatorTwo: my-error-two\norg.onap.so.bpmn.common.listener.validation.WorkflowPreValidatorOne: my-error-one", workflowException.getErrorMessage()); } runner.preValidate("test2", mock(DelegateExecution.class)); diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyDisabledValidator.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyDisabledValidator.java index 7572e930cd..af64ed2de6 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyDisabledValidator.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyDisabledValidator.java @@ -18,11 +18,13 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; import java.util.Collections; import java.util.Optional; import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.listener.Skip; +import org.onap.so.bpmn.common.listener.validation.PreBuildingBlockValidator; import org.springframework.stereotype.Component; @Component diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorFour.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyPreValidatorFour.java index 85531719d5..f0f27172a5 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorFour.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyPreValidatorFour.java @@ -18,12 +18,13 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; import java.util.Collections; import java.util.Optional; import java.util.Set; import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.listener.validation.PreBuildingBlockValidator; import org.springframework.stereotype.Component; @Component diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorOne.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyPreValidatorOne.java index 989a65fe47..e705bafafe 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorOne.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyPreValidatorOne.java @@ -18,12 +18,13 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; import java.util.Collections; import java.util.Optional; import java.util.Set; import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.listener.validation.PreBuildingBlockValidator; import org.springframework.stereotype.Component; @Component diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorThree.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyPreValidatorThree.java index a51d3836da..3c747dd20f 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorThree.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyPreValidatorThree.java @@ -18,12 +18,13 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; import java.util.Collections; import java.util.Optional; import java.util.Set; import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.listener.validation.PreBuildingBlockValidator; import org.springframework.stereotype.Component; @Component diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorTwo.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyPreValidatorTwo.java index 1276d8f1d2..3fb3485c39 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorTwo.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyPreValidatorTwo.java @@ -18,13 +18,14 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; import java.util.Collections; import java.util.Optional; import java.util.Set; import javax.annotation.Priority; import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.listener.validation.PreBuildingBlockValidator; import org.springframework.stereotype.Component; @Priority(1) diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/ValidationConfig.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/ValidationConfig.java index 90d094ce41..068f433dd5 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/ValidationConfig.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/ValidationConfig.java @@ -18,16 +18,16 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; import org.onap.so.bpmn.common.DefaultToShortClassNameBeanNameGenerator; +import org.onap.so.bpmn.common.listener.ListenerRunner; import org.onap.so.client.exception.ExceptionBuilder; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; @Configuration -@ComponentScan(basePackages = {"org.onap.so.bpmn.common.validation"}, basePackageClasses = {ExceptionBuilder.class}, +@ComponentScan(basePackageClasses = {ExceptionBuilder.class, ListenerRunner.class}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class) public class ValidationConfig { diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorOne.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/WorkflowPreValidatorOne.java index 485aae2fcc..f7aedcfd6f 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorOne.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/WorkflowPreValidatorOne.java @@ -18,12 +18,13 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; import java.util.Collections; import java.util.Optional; import java.util.Set; import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.listener.validation.PreWorkflowValidator; import org.springframework.stereotype.Component; @Component diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorTwo.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/WorkflowPreValidatorTwo.java index 9596524a56..99a7e161a9 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/WorkflowPreValidatorTwo.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/WorkflowPreValidatorTwo.java @@ -18,13 +18,14 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.validation; +package org.onap.so.bpmn.common.listener.validation; import java.util.Collections; import java.util.Optional; import java.util.Set; import javax.annotation.Priority; import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.listener.validation.PreWorkflowValidator; import org.springframework.stereotype.Component; @Priority(1) diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/ExtractPojosForBBTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/ExtractPojosForBBTest.java index 8ab2c8e155..7bd2beeb92 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/ExtractPojosForBBTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/ExtractPojosForBBTest.java @@ -227,4 +227,16 @@ public class ExtractPojosForBBTest extends BaseTest { gBBInput.setCustomer(customer); extractPojos.extractByKey(execution, ResourceKey.VPN_BONDING_LINK_ID); } + + @Test + public void getServiceInstanceWithNoCustomer() throws BBObjectNotFoundException { + ServiceInstance serviceInstancePend = new ServiceInstance(); + serviceInstancePend.setServiceInstanceId("abc"); + lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstancePend.getServiceInstanceId()); + Customer customer = new Customer(); + gBBInput.setCustomer(customer); + gBBInput.setServiceInstance(serviceInstancePend); + ServiceInstance extractServPend = extractPojos.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + assertEquals(extractServPend.getServiceInstanceId(), serviceInstancePend.getServiceInstanceId()); + } } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/bbobjects/wrappers/ServiceInstanceWrapperTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/bbobjects/wrappers/ServiceInstanceWrapperTest.java new file mode 100644 index 0000000000..fa8de7ff23 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/bbobjects/wrappers/ServiceInstanceWrapperTest.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.servicedecomposition.bbobjects.wrappers; + +import static org.junit.Assert.assertEquals; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceProxy; +import org.onap.so.bpmn.servicedecomposition.bbobjects.wrappers.exceptions.ServiceProxyNotFoundException; + +public class ServiceInstanceWrapperTest { + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void getTransportServiceProxyTest() throws ServiceProxyNotFoundException { + ServiceInstance si = buildServiceInstance(); + si.getServiceProxies().add(buildServiceProxy()); + ServiceInstanceWrapper sw = new ServiceInstanceWrapper(si); + ServiceProxy sp = sw.getTransportServiceProxy(); + assertEquals("sp-001", sp.getId()); + assertEquals("transport", sp.getType()); + } + + @Test + public void getTransportServiceProxyExceptionTest() throws ServiceProxyNotFoundException { + expectedException.expect(ServiceProxyNotFoundException.class); + ServiceInstanceWrapper sw = new ServiceInstanceWrapper(buildServiceInstance()); + sw.getTransportServiceProxy(); + } + + private ServiceInstance buildServiceInstance() { + ServiceInstance si = new ServiceInstance(); + si.setServiceInstanceId("si-001"); + si.setServiceInstanceName("Test SI"); + return si; + } + + private ServiceProxy buildServiceProxy() { + ServiceProxy sp = new ServiceProxy(); + sp.setId("sp-001"); + sp.setType("transport"); + return sp; + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayerTest.java index 37f8b8b2fd..13d2b7d3d3 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayerTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayerTest.java @@ -573,6 +573,19 @@ public class BBInputSetupMapperLayerTest { } @Test + public void testMapOrchestrationContextNoRequestInfo() throws IOException { + OrchestrationContext expected = new OrchestrationContext(); + expected.setIsRollbackEnabled(false); + + RequestDetails requestDetails = mapper.readValue( + new File(RESOURCE_PATH + "RequestDetailsInput_mapReqContextNoRequestInfo.json"), RequestDetails.class); + + OrchestrationContext actual = bbInputSetupMapperLayer.mapOrchestrationContext(requestDetails); + + assertThat(actual, sameBeanAs(expected)); + } + + @Test public void testMapLocationContext() { CloudRegion expected = new CloudRegion(); expected.setCloudOwner("test-owner-name"); 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 ad1918e6da..787957dc38 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 @@ -65,6 +65,7 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform; import org.onap.so.bpmn.servicedecomposition.bbobjects.Project; import org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTableReference; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceProxy; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceSubscription; import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; import org.onap.so.bpmn.servicedecomposition.bbobjects.Vnfc; @@ -82,6 +83,7 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoGenericVnf; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoInstanceGroup; 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.client.aai.AAICommonObjectMapperProvider; import org.onap.so.client.aai.AAIObjectType; @@ -94,14 +96,15 @@ import org.onap.so.db.catalog.beans.CollectionResourceCustomization; import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization; import org.onap.so.db.catalog.beans.ConfigurationResource; import org.onap.so.db.catalog.beans.ConfigurationResourceCustomization; +import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization; import org.onap.so.db.catalog.beans.InstanceGroupType; import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization; import org.onap.so.db.catalog.beans.NetworkResourceCustomization; import org.onap.so.db.catalog.beans.OrchestrationStatus; import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.catalog.beans.ServiceProxyResourceCustomization; import org.onap.so.db.catalog.beans.VfModuleCustomization; import org.onap.so.db.catalog.beans.VnfResourceCustomization; -import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization; import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.serviceinstancebeans.CloudConfiguration; @@ -1231,19 +1234,19 @@ public class BBInputSetupTest { configResourceKeys.setVnfcName(vnfcName); Vnfc vnfc = new Vnfc(); vnfc.setVnfcName(vnfcName); - + RequestDetails requestDetails = new RequestDetails(); doNothing().when(SPY_bbInputSetup).mapCatalogConfiguration(configuration, modelInfo, service, configResourceKeys); doReturn(vnfc).when(SPY_bbInputSetup).getVnfcToConfiguration(vnfcName); SPY_bbInputSetup.populateConfiguration(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId, - instanceName, configResourceKeys); + instanceName, configResourceKeys, requestDetails); verify(SPY_bbInputSetup, times(1)).mapCatalogConfiguration(configuration, modelInfo, service, configResourceKeys); lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, null); SPY_bbInputSetup.populateConfiguration(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId, - instanceName, configResourceKeys); + instanceName, configResourceKeys, requestDetails); verify(SPY_bbInputSetup, times(2)).mapCatalogConfiguration(configuration, modelInfo, service, configResourceKeys); @@ -1255,7 +1258,7 @@ public class BBInputSetupTest { doNothing().when(SPY_bbInputSetup).mapCatalogConfiguration(configuration2, modelInfo, service, configResourceKeys); SPY_bbInputSetup.populateConfiguration(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId, - instanceName, configResourceKeys); + instanceName, configResourceKeys, requestDetails); verify(SPY_bbInputSetup, times(1)).mapCatalogConfiguration(configuration2, modelInfo, service, configResourceKeys); } @@ -1307,6 +1310,7 @@ public class BBInputSetupTest { configResourceKeys.setVnfcName(vnfcName); Vnfc vnfc = new Vnfc(); vnfc.setVnfcName(vnfcName); + RequestDetails requestDetails = new RequestDetails(); CvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization = new CvnfcConfigurationCustomization(); @@ -1319,7 +1323,7 @@ public class BBInputSetupTest { doReturn(vnfc).when(SPY_bbInputSetup).getVnfcToConfiguration(vnfcName); SPY_bbInputSetup.populateConfiguration(modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId, - instanceName, configResourceKeys); + instanceName, configResourceKeys, requestDetails); verify(SPY_bbInputSetup, times(1)).mapCatalogConfiguration(configuration, modelInfo, service, configResourceKeys); } @@ -1972,14 +1976,117 @@ public class BBInputSetupTest { configurationCustList.add(configurationCust); doNothing().when(SPY_bbInputSetup).populateConfiguration(isA(ModelInfo.class), isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(), - isA(ConfigurationResourceKeys.class)); + isA(ConfigurationResourceKeys.class), isA(RequestDetails.class)); executeBB.getBuildingBlock().setBpmnFlowName("AssignFabricConfigurationBB"); executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa9"); SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); verify(SPY_bbInputSetup, times(1)).populateConfiguration(isA(ModelInfo.class), isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(), - isA(ConfigurationResourceKeys.class)); + isA(ConfigurationResourceKeys.class), isA(RequestDetails.class)); + + + } + + @Test + public void testGBBMacroNoUserParamsVrfConfiguration() throws Exception { + GeneralBuildingBlock gBB = mapper.readValue(new File(RESOURCE_PATH + "GeneralBuildingBlockExpected.json"), + GeneralBuildingBlock.class); + ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"), + ExecuteBuildingBlock.class); + RequestDetails requestDetails = mapper + .readValue(new File(RESOURCE_PATH + "RequestDetailsInput_serviceMacroVrf.json"), RequestDetails.class); + InfraActiveRequests request = Mockito.mock(InfraActiveRequests.class); + Map<ResourceKey, String> lookupKeyMap = new HashMap<>(); + lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "serviceInstanceId"); + lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, "configurationId"); + String resourceId = "123"; + String vnfType = "vnfType"; + Service service = Mockito.mock(Service.class); + String requestAction = "createInstance"; + + ConfigurationResourceKeys configResourceKeys = new ConfigurationResourceKeys(); + configResourceKeys.setCvnfcCustomizationUUID("cvnfcCustomizationUUID"); + 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)); + doReturn(service).when(SPY_bbInputSetupUtils) + .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid()); + + RelatedInstance relatedVpnBinding = new RelatedInstance(); + relatedVpnBinding.setInstanceId("vpnBindingInstanceId"); + RelatedInstance relatedLocalNetwork = new RelatedInstance(); + relatedLocalNetwork.setInstanceId("localNetworkInstanceId"); + org.onap.aai.domain.yang.VpnBinding aaiVpnBinding = new org.onap.aai.domain.yang.VpnBinding(); + aaiVpnBinding.setVpnId("vpnBindingId"); + org.onap.aai.domain.yang.L3Network aaiLocalNetwork = new org.onap.aai.domain.yang.L3Network(); + aaiLocalNetwork.setNetworkId("localNetworkId"); + Optional<org.onap.aai.domain.yang.VpnBinding> aaiAICVpnBindingOp = + Optional.of(new org.onap.aai.domain.yang.VpnBinding()); + aaiAICVpnBindingOp.get().setVpnId("AICVpnBindingId"); + ServiceProxy proxy = new ServiceProxy(); + proxy.setType("transport"); + proxy.setServiceInstance(new ServiceInstance()); + proxy.getServiceInstance().setModelInfoServiceInstance(new ModelInfoServiceInstance()); + proxy.getServiceInstance().getModelInfoServiceInstance().setModelUuid("sourceServiceModelUUID"); + doReturn(relatedVpnBinding).when(SPY_bbInputSetupUtils).getRelatedInstanceByType(requestDetails, + ModelType.vpnBinding); + doReturn(relatedLocalNetwork).when(SPY_bbInputSetupUtils).getRelatedInstanceByType(requestDetails, + ModelType.network); + doReturn(aaiVpnBinding).when(SPY_bbInputSetupUtils).getAAIVpnBinding(relatedVpnBinding.getInstanceId()); + doReturn(aaiLocalNetwork).when(SPY_bbInputSetupUtils).getAAIL3Network(relatedLocalNetwork.getInstanceId()); + doReturn(aaiAICVpnBindingOp).when(SPY_bbInputSetupUtils).getAICVpnBindingFromNetwork(aaiLocalNetwork); + doReturn(proxy).when(SPY_bbInputSetup).getServiceProxy(service); + + Configuration configuration = new Configuration(); + configuration.setConfigurationId("configurationId"); + gBB.getServiceInstance().getConfigurations().add(configuration); + List<ConfigurationResourceCustomization> configurationCustList = new ArrayList<>(); + ConfigurationResourceCustomization configurationCust = new ConfigurationResourceCustomization(); + configurationCust.setModelCustomizationUUID("72d9d1cd-f46d-447a-abdb-451d6fb05fa9"); + configurationCustList.add(configurationCust); + doNothing().when(SPY_bbInputSetup).populateConfiguration(isA(ModelInfo.class), isA(Service.class), + any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(), + isA(ConfigurationResourceKeys.class), isA(RequestDetails.class)); + + executeBB.getBuildingBlock().setBpmnFlowName("AssignVrfConfigurationBB"); + executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa9"); + gBB = SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); + verify(SPY_bbInputSetup, times(1)).populateConfiguration(isA(ModelInfo.class), isA(Service.class), + any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(), + isA(ConfigurationResourceKeys.class), isA(RequestDetails.class)); + assertEquals(gBB.getCustomer().getVpnBindings().get(0).getVpnId(), "vpnBindingId"); + assertEquals(gBB.getServiceInstance().getNetworks().get(0).getNetworkId(), "localNetworkId"); + assertEquals(gBB.getServiceInstance().getNetworks().get(0).getVpnBindings().get(0).getVpnId(), + "AICVpnBindingId"); + assertEquals(gBB.getServiceInstance().getServiceProxies().get(0).getType(), "transport"); + } + + @Test + public void testGetServiceProxy() { + ServiceProxy expected = new ServiceProxy(); + expected.setType("TRANSPORT"); + expected.setModelInfoServiceProxy(new ModelInfoServiceProxy()); + expected.getModelInfoServiceProxy().setModelCustomizationUuid("modelCustomizationUUID"); + expected.setServiceInstance(new ServiceInstance()); + expected.getServiceInstance().setModelInfoServiceInstance(new ModelInfoServiceInstance()); + expected.getServiceInstance().getModelInfoServiceInstance().setModelUuid("modelUUID"); + expected.getServiceInstance().getModelInfoServiceInstance().setServiceType("TRANSPORT"); + Service service = new Service(); + ServiceProxyResourceCustomization serviceProxyCatalog = new ServiceProxyResourceCustomization(); + serviceProxyCatalog.setModelCustomizationUUID("modelCustomizationUUID"); + Service sourceService = new Service(); + sourceService.setModelUUID("modelUUID"); + sourceService.setServiceType("TRANSPORT"); + serviceProxyCatalog.setSourceService(sourceService); + service.setServiceProxyCustomizations(new ArrayList<ServiceProxyResourceCustomization>()); + service.getServiceProxyCustomizations().add(serviceProxyCatalog); + ServiceProxy actual = SPY_bbInputSetup.getServiceProxy(service); + assertThat(actual, sameBeanAs(expected)); } @Test diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/exception/ExceptionBuilderTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/exception/ExceptionBuilderTest.java index 549f16b6f6..5f9aef67e6 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/exception/ExceptionBuilderTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/exception/ExceptionBuilderTest.java @@ -138,7 +138,7 @@ public class ExceptionBuilderTest extends BaseTest { WorkflowException we = execution.getVariable("WorkflowException"); assertNotNull(we); assertEquals( - "create VF-Module testVfModuleId1 failed due to incomplete A&AI vserver inventory population after stack testStackName was successfully created in cloud region testLcpCloudRegionId. MSO Audit indicates that AIC RO did not create vserver testVServerId in AAI. Recommendation - Wait for nightly RO Audit to run and fix the data issue and resume vf-module creation in VID. If problem persists then report problem to AIC/RO Ops.", + "create VF-Module testVfModuleId1 failed due to incomplete AAI vserver inventory population after stack testStackName was successfully created in cloud region testLcpCloudRegionId. MSO Audit indicates that the following was not created in AAI: vserver testVServerId.", we.getErrorMessage()); } } @@ -151,7 +151,7 @@ public class ExceptionBuilderTest extends BaseTest { String sm = execution.getVariable("StatusMessage"); assertNotNull(sm); assertEquals( - "create VF-Module testVfModuleId1 failed due to incomplete A&AI vserver inventory population after stack testStackName was successfully created in cloud region testLcpCloudRegionId. MSO Audit indicates that AIC RO did not create vserver testVServerId in AAI. Recommendation - Wait for nightly RO Audit to run and fix the data issue and resume vf-module creation in VID. If problem persists then report problem to AIC/RO Ops.", + "create VF-Module testVfModuleId1 failed due to incomplete AAI vserver inventory population after stack testStackName was successfully created in cloud region testLcpCloudRegionId. MSO Audit indicates that the following was not created in AAI: vserver testVServerId.", sm); } catch (BpmnError bpmnException) { fail(); diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ModelInfoGenericVnfExpected.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ModelInfoGenericVnfExpected.json index 98f966e753..9703b9c105 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ModelInfoGenericVnfExpected.json +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ModelInfoGenericVnfExpected.json @@ -17,5 +17,7 @@ "model-version" : "modelVersion", "model-invariant-uuid" : "modelInvariantUUID", "model-name" : "modelName", - "model-uuid" : "modelUUID" + "model-uuid" : "modelUUID", + "blueprintName" : "testBlueprintName", + "blueprintVersion" : "testBlueprintVersion" }
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/RequestDetailsInput_mapReqContextNoRequestInfo.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/RequestDetailsInput_mapReqContextNoRequestInfo.json new file mode 100644 index 0000000000..41f0fde834 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/RequestDetailsInput_mapReqContextNoRequestInfo.json @@ -0,0 +1,29 @@ +{ + "requestParameters": { + "subscriptionServiceType": "subscriptionServiceType", + "userParams": [ + { + "name" : "mns_vfw_protected_route_prefixes", + "value" : [ { + "interface_route_table_routes_route" : "1.1.1.1/32" + }, { + "interface_route_table_routes_route" : "0::1/128" + } ] + }, + { + "name": "name1", + "value": "value1" + }, + { + "ignore": "false", + "skip": "ignore" + }] + }, + "configurationParameters": [ + { + "availability-zone":"$.vnf-topology.vnf-resource-assignments.availability-zones.availability-zone[0]", + "xtz-123":"$.vnf-topology.vnf-resource-assignments.availability-zones.availability-zone[0]" + } + ] +} + diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/RequestDetailsInput_serviceMacro.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/RequestDetailsInput_serviceMacro.json index 1cc387aaa0..97a230a1db 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/RequestDetailsInput_serviceMacro.json +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/RequestDetailsInput_serviceMacro.json @@ -3,7 +3,7 @@ "modelType": "service", "modelInvariantId": "5d48acb5-097d-4982-aeb2-f4a3bd87d31b", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersion": "10.0" }, "owningEntity": { @@ -31,7 +31,7 @@ "service": { "modelInfo": { "modelType": "service", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a" }, "instanceName": "vPE_Service", diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/RequestDetailsInput_serviceMacroVrf.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/RequestDetailsInput_serviceMacroVrf.json new file mode 100644 index 0000000000..32745e19f3 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/RequestDetailsInput_serviceMacroVrf.json @@ -0,0 +1,48 @@ +{ + "modelInfo": { + "modelType": "service", + "modelInvariantId": "5d48acb5-097d-4982-aeb2-f4a3bd87d31b", + "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a", + "modelName": "Sample Service Model", + "modelVersion": "10.0" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "subscriberId" + }, + "requestInfo": { + "instanceName": "vPE_Service", + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "source": "VID", + "suppressRollback": true, + "requestorId": "xxxxxx" + }, + "requestParameters": { + "subscriptionServiceType": "VMX", + "aLaCarte": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "vpnBindingId", + "modelInfo": { + "modelType": "vpnBinding" + } + } + }, + { + "relatedInstance": { + "instanceId": "localNetworkId", + "modelInfo": { + "modelType": "network" + } + } + } + ] +} diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroNetworks.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroNetworks.json index f458d732d2..8d03005a9e 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroNetworks.json +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroNetworks.json @@ -1,7 +1,7 @@ { "modelInfo": { "modelType": "service", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a" }, "instanceName": "vPE_Service", diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroNoCloudConfig.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroNoCloudConfig.json index 0c3d8e709e..3201ec1bc0 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroNoCloudConfig.json +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroNoCloudConfig.json @@ -1,7 +1,7 @@ { "modelInfo": { "modelType": "service", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a" }, "instanceName": "vPE_Service", diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroVfModules.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroVfModules.json index de20a5a963..fd6f8fad6a 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroVfModules.json +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroVfModules.json @@ -1,7 +1,7 @@ { "modelInfo": { "modelType": "service", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a" }, "instanceName": "vPE_Service", diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroVnfs.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroVnfs.json index c4ad0ac047..80ea6b34ec 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroVnfs.json +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/ServiceMacroVnfs.json @@ -1,7 +1,7 @@ { "modelInfo": { "modelType": "service", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a" }, "instanceName": "vPE_Service", diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/VnfResourceCustomizationInput.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/VnfResourceCustomizationInput.json index 26516ce907..95b116cec8 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/VnfResourceCustomizationInput.json +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/VnfResourceCustomizationInput.json @@ -9,6 +9,8 @@ "nfRole" : "nfRole", "nfNamingCode" : "nfNamingCode", "multiStageDesign" : "multiStageDesign", + "blueprintName" : "testBlueprintName", + "blueprintVersion" : "testBlueprintVersion", "vnfResources" : { "modelUUID" : "modelUUID", "modelInvariantUUID" : "modelInvariantUUID", diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/License.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/License.java index 1db360f391..4d70d0f14b 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/License.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/License.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -22,7 +24,6 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.json.JSONArray; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -40,9 +41,9 @@ public class License extends JsonWrapper implements Serializable { private static final long serialVersionUID = 1L; @JsonInclude(JsonInclude.Include.NON_EMPTY) - private List<String> entitlementPoolList = new ArrayList<String>(); + private List<String> entitlementPoolList = new ArrayList(); @JsonInclude(JsonInclude.Include.NON_EMPTY) - private List<String> licenseKeyGroupList = new ArrayList<String>(); + private List<String> licenseKeyGroupList = new ArrayList<>(); public List<String> getEntitlementPoolList() { diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Request.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Request.java index 6c33d37cfe..eb24c96bca 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Request.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/Request.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -21,7 +23,6 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; -import com.fasterxml.jackson.annotation.JsonRootName; /** * This class is used to store instance data of services aka ServiceDecomposition diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceDecomposition.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceDecomposition.java index b291765252..7dbf97d223 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceDecomposition.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceDecomposition.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -27,7 +29,6 @@ import com.fasterxml.jackson.annotation.JsonIgnore; * Abstract superclass for all individual decomposition resources * */ -// @JsonIgnoreProperties public abstract class ResourceDecomposition extends JsonWrapper implements Serializable { private static final long serialVersionUID = 1L; @@ -74,9 +75,6 @@ public abstract class ResourceDecomposition extends JsonWrapper implements Seria public String getResourceInstanceName() { return this.getInstanceData().getInstanceName(); } - // @JsonIgnore - // public String getResourceHomingSolution() { - // } public void setResourceInstanceId(String newInstanceId) { this.getInstanceData().setInstanceId(newInstanceId); @@ -85,7 +83,4 @@ public abstract class ResourceDecomposition extends JsonWrapper implements Seria public void setResourceInstanceName(String newInstanceName) { this.getInstanceData().setInstanceName(newInstanceName); } - // @JsonIgnore - // public String setResourceHomingSolution() { - // } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceDecomposition.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceDecomposition.java index b3439d58e3..3632d187c9 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceDecomposition.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceDecomposition.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -24,7 +26,6 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; -import java.util.Iterator; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; @@ -32,6 +33,8 @@ import com.fasterxml.jackson.annotation.JsonRootName; import org.json.JSONObject; import org.onap.so.bpmn.core.json.DecomposeJsonUtil; import org.onap.so.bpmn.core.json.JsonDecomposingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @@ -41,10 +44,10 @@ import org.onap.so.bpmn.core.json.JsonDecomposingException; * resource's decompositon */ @JsonRootName(value = "serviceResources") -// @JsonTypeInfo(include=As.WRAPPER_OBJECT, use=Id.NAME) public class ServiceDecomposition extends JsonWrapper implements Serializable { private static final long serialVersionUID = 1L; + private static final Logger logger = LoggerFactory.getLogger(ServiceDecomposition.class); @JsonProperty("modelInfo") private ModelInfo modelInfo; @@ -315,8 +318,6 @@ public class ServiceDecomposition extends JsonWrapper implements Serializable { public String getVnfResource(String resourceObjectId) { for (Resource resource : getServiceResources()) { - // resource.getModelInfo().getModelInvariantId(); - if ("extracted information".equals(resourceObjectId)) { return resource.toJsonString(); } @@ -457,11 +458,11 @@ public class ServiceDecomposition extends JsonWrapper implements Serializable { boolean result = false; for (Resource resource : (Iterable<Resource>) resources) { - System.out.println("resource found"); + logger.debug("resource found"); if (resource.resourceType == newResource.resourceType) { - System.out.println("resource type matches"); + logger.debug("resource type matches"); if (resource.getResourceId().equalsIgnoreCase(newResource.getResourceId())) { - System.out.println("resource id matches"); + logger.debug("resource id matches"); // returns TRUE if replacement is a success result = Collections.replaceAll(resources, resource, newResource); } @@ -491,14 +492,12 @@ public class ServiceDecomposition extends JsonWrapper implements Serializable { public boolean deleteResource(Resource resource) { List serviceResourceList = getResourceList(resource); for (Resource item : (Iterable<Resource>) serviceResourceList) { - if (item.resourceType == resource.resourceType) { - if (item.getResourceId().equalsIgnoreCase(resource.getResourceId())) { - // returns TRUE if replacement is a success - return serviceResourceList.remove(resource); - } + if (item.resourceType == resource.resourceType + && item.getResourceId().equalsIgnoreCase(resource.getResourceId())) { + // returns TRUE if replacement is a success + return serviceResourceList.remove(resource); } } - return false; } diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerService.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerService.java index 7c0c2f20b3..13ba46a852 100644 --- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerService.java +++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/CallbackHandlerService.java @@ -26,6 +26,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.onap.so.logger.LoggingAnchor; import org.camunda.bpm.engine.MismatchingMessageCorrelationException; import org.camunda.bpm.engine.OptimisticLockingException; import org.camunda.bpm.engine.RuntimeService; @@ -207,7 +208,7 @@ public class CallbackHandlerService { + messageEventName + " with " + correlationVariable + " = '" + correlationValue + "'; last exception was:" + queryException; logger.debug(msg); - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", ErrorCode.UnknownError.getValue(), msg, queryException); } @@ -245,8 +246,8 @@ public class CallbackHandlerService { String msg = "Caught " + ole.getClass().getSimpleName() + " after receiving " + messageEventName + " with " + correlationVariable + " = '" + correlationValue + "': " + ole; logger.debug(msg); - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN CORRELATION ERROR -", - ErrorCode.UnknownError.getValue(), msg, ole); + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), + "BPMN CORRELATION ERROR -", ErrorCode.UnknownError.getValue(), msg, ole); // Retry for OptimisticLocking Exceptions int retryCount = 0; @@ -279,7 +280,7 @@ public class CallbackHandlerService { String strMsg = "Received exception, OptimisticLockingException retry failed, retryCount:" + retryCount + " | exception returned: " + olex; logger.debug(strMsg); - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", ErrorCode.UnknownError.getValue(), strMsg, olex); } catch (Exception excep) { retryCount = 0; @@ -287,7 +288,7 @@ public class CallbackHandlerService { String strMsg = "Received exception, OptimisticLockingException retry failed, retryCount:" + retryCount + " | exception returned: " + excep; logger.debug(strMsg); - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", ErrorCode.UnknownError.getValue(), strMsg, excep); } @@ -300,7 +301,7 @@ public class CallbackHandlerService { + " after receiving " + messageEventName + " with " + correlationVariable + " = '" + correlationValue + "': " + e; logger.debug(msg); - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", ErrorCode.UnknownError.getValue(), msg, e); } } catch (Exception e) { @@ -309,7 +310,7 @@ public class CallbackHandlerService { String msg = "Caught " + e.getClass().getSimpleName() + " after receiving " + messageEventName + " with " + correlationVariable + " = '" + correlationValue + "': " + e; logger.debug(msg); - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN CORRELATION ERROR -", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN CORRELATION ERROR -", ErrorCode.UnknownError.getValue(), msg, e); } @@ -345,10 +346,10 @@ public class CallbackHandlerService { */ protected void logCallbackError(String method, long startTime, String msg, Exception e) { if (e == null) { - logger.error("{} {} {} {}", MessageEnum.BPMN_CALLBACK_EXCEPTION.toString(), "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_CALLBACK_EXCEPTION.toString(), "BPMN", ErrorCode.UnknownError.getValue(), msg); } else { - logger.error("{} {} {} {}", MessageEnum.BPMN_CALLBACK_EXCEPTION.toString(), "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_CALLBACK_EXCEPTION.toString(), "BPMN", ErrorCode.UnknownError.getValue(), msg, e); } } diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowMessageResource.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowMessageResource.java index 1e9ebdf0b2..f76fde9ef1 100644 --- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowMessageResource.java +++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowMessageResource.java @@ -32,6 +32,7 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.bpmn.common.workflow.service.CallbackHandlerService.CallbackError; import org.onap.so.bpmn.common.workflow.service.CallbackHandlerService.CallbackResult; import org.onap.so.logger.ErrorCode; @@ -78,7 +79,7 @@ public class WorkflowMessageResource { if (messageType == null || messageType.isEmpty()) { String msg = "Missing message type"; logger.debug(LOGMARKER + " " + msg); - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", ErrorCode.DataError.getValue(), LOGMARKER + ":" + msg); return Response.status(400).entity(msg).build(); } @@ -86,7 +87,7 @@ public class WorkflowMessageResource { if (correlator == null || correlator.isEmpty()) { String msg = "Missing correlator"; logger.debug(LOGMARKER + " " + msg); - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "BPMN", ErrorCode.DataError.getValue(), LOGMARKER + ":" + msg); return Response.status(400).entity(msg).build(); } diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowResource.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowResource.java index 9d63e8eaf1..20f3eb4fee 100644 --- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowResource.java +++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/workflow/service/WorkflowResource.java @@ -36,6 +36,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; +import org.onap.so.logger.LoggingAnchor; import org.camunda.bpm.engine.HistoryService; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.ProcessEngineServices; @@ -195,7 +196,7 @@ public class WorkflowResource extends ProcessEngineAwareService { if (processInstance != null) workflowResponse.setProcessInstanceID(processInstance.getId()); - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "BPMN", MDC.get(processKey), ErrorCode.UnknownError.getValue(), LOGMARKER + workflowResponse.getMessage() + " for processKey: " + processKey + " with response: " + workflowResponse.getResponse()); @@ -581,7 +582,7 @@ public class WorkflowResource extends ProcessEngineAwareService { response.setResponse("Failed to retrieve the variables," + ex.getMessage()); response.setProcessInstanceID(processInstanceId); - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "BPMN", MDC.get(processKey), ErrorCode.UnknownError.getValue(), LOGMARKER + response.getMessage() + " for processKey: " + processKey + " with response: " + response.getResponse()); logger.debug("Exception :", ex); diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/LoggingAndURNMappingPlugin.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/LoggingAndURNMappingPlugin.java index 296ab64df3..251464a34d 100644 --- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/LoggingAndURNMappingPlugin.java +++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/LoggingAndURNMappingPlugin.java @@ -22,16 +22,8 @@ package org.onap.so.bpmn.core.plugins; -import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; import org.camunda.bpm.engine.RepositoryService; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.ExecutionListener; @@ -39,26 +31,15 @@ import org.camunda.bpm.engine.impl.bpmn.parser.AbstractBpmnParseListener; import org.camunda.bpm.engine.impl.bpmn.parser.BpmnParseListener; import org.camunda.bpm.engine.impl.cfg.AbstractProcessEnginePlugin; import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; -import org.camunda.bpm.engine.impl.context.Context; -import org.camunda.bpm.engine.impl.interceptor.Command; -import org.camunda.bpm.engine.impl.interceptor.CommandContext; import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity; import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl; import org.camunda.bpm.engine.impl.pvm.process.ScopeImpl; import org.camunda.bpm.engine.impl.pvm.process.TransitionImpl; import org.camunda.bpm.engine.impl.util.xml.Element; import org.camunda.bpm.engine.impl.variable.VariableDeclaration; -import org.camunda.bpm.model.bpmn.impl.instance.FlowNodeImpl; -import org.camunda.bpm.model.bpmn.instance.EndEvent; -import org.camunda.bpm.model.bpmn.instance.FlowNode; -import org.camunda.bpm.model.bpmn.instance.StartEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.AbstractEnvironment; -import org.springframework.core.env.Environment; -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.env.PropertySource; import org.springframework.stereotype.Component; diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/WorkflowExceptionPlugin.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/WorkflowExceptionPlugin.java index ab21c0807e..42c6ef059f 100644 --- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/WorkflowExceptionPlugin.java +++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/WorkflowExceptionPlugin.java @@ -32,7 +32,6 @@ import org.camunda.bpm.engine.delegate.JavaDelegate; import org.camunda.bpm.engine.impl.bpmn.behavior.ClassDelegateActivityBehavior; import org.camunda.bpm.engine.impl.bpmn.parser.AbstractBpmnParseListener; import org.camunda.bpm.engine.impl.bpmn.parser.BpmnParseListener; -import org.camunda.bpm.engine.impl.bpmn.parser.FieldDeclaration; import org.camunda.bpm.engine.impl.cfg.AbstractProcessEnginePlugin; import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity; @@ -58,6 +57,8 @@ import org.slf4j.LoggerFactory; public class WorkflowExceptionPlugin extends AbstractProcessEnginePlugin { private static final Logger logger = LoggerFactory.getLogger(WorkflowExceptionPlugin.class); + private static final String WORKFLOW_EXCEPTION = "WorkflowException"; + @Override public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) { List<BpmnParseListener> preParseListeners = processEngineConfiguration.getCustomPreBPMNParseListeners(); @@ -131,7 +132,7 @@ public class WorkflowExceptionPlugin extends AbstractProcessEnginePlugin { */ public static class WorkflowExceptionResetListener implements ExecutionListener { public void notify(DelegateExecution execution) throws Exception { - Object workflowException = execution.getVariable("WorkflowException"); + Object workflowException = execution.getVariable(WORKFLOW_EXCEPTION); if (workflowException instanceof WorkflowException) { int index = 1; @@ -140,10 +141,10 @@ public class WorkflowExceptionPlugin extends AbstractProcessEnginePlugin { saveName = "SavedWorkflowException" + (++index); } - logger.debug("WorkflowExceptionResetTask is moving WorkflowException to " + saveName); + logger.debug("WorkflowExceptionResetTask is moving WorkflowException to {}", saveName); execution.setVariable(saveName, workflowException); - execution.setVariable("WorkflowException", null); + execution.setVariable(WORKFLOW_EXCEPTION, null); } } } @@ -153,7 +154,7 @@ public class WorkflowExceptionPlugin extends AbstractProcessEnginePlugin { */ public static class WorkflowExceptionTriggerTask implements JavaDelegate { public void execute(DelegateExecution execution) throws Exception { - if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + if (execution.getVariable(WORKFLOW_EXCEPTION) instanceof WorkflowException) { logger.debug("WorkflowExceptionTriggerTask is generating a MSOWorkflowException event"); throw new BpmnError("MSOWorkflowException"); } diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java index c61808ebb1..093fba089d 100644 --- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java +++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java @@ -24,14 +24,15 @@ package org.onap.so.bpmn.infrastructure; import java.util.List; import java.util.concurrent.Executor; -import org.camunda.bpm.application.PostDeploy; +import org.onap.so.logger.LoggingAnchor; +import javax.annotation.PostConstruct; import org.camunda.bpm.application.PreUndeploy; import org.camunda.bpm.application.ProcessApplicationInfo; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.repository.DeploymentBuilder; import org.onap.so.bpmn.common.DefaultToShortClassNameBeanNameGenerator; import org.onap.so.db.catalog.beans.Workflow; -import org.onap.so.db.catalog.data.repository.WorkflowRepository; +import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.logging.jaxrs.filter.MDCTaskDecorator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,13 +40,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.Primary; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @@ -56,17 +55,17 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @SpringBootApplication @EnableAsync -@EnableJpaRepositories("org.onap.so.db.catalog.data.repository") -@EntityScan({"org.onap.so.db.catalog.beans"}) @ComponentScan(basePackages = {"org.onap"}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class, excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)}) public class MSOInfrastructureApplication { private static final Logger logger = LoggerFactory.getLogger(MSOInfrastructureApplication.class); + @Autowired + private ProcessEngine processEngine; @Autowired - private WorkflowRepository workflowRepository; + private CatalogDbClient catalogDbClient; @Value("${mso.async.core-pool-size}") private int corePoolSize; @@ -79,6 +78,7 @@ public class MSOInfrastructureApplication { private static final String LOGS_DIR = "logs_dir"; private static final String BPMN_SUFFIX = ".bpmn"; + private static final String SDC_SOURCE = "sdc"; private static void setLogsDir() { @@ -93,10 +93,14 @@ public class MSOInfrastructureApplication { setLogsDir(); } - @PostDeploy - public void postDeploy(ProcessEngine processEngineInstance) { - DeploymentBuilder deploymentBuilder = processEngineInstance.getRepositoryService().createDeployment(); - deployCustomWorkflows(deploymentBuilder); + @PostConstruct + public void postConstruct() { + try { + DeploymentBuilder deploymentBuilder = processEngine.getRepositoryService().createDeployment(); + deployCustomWorkflows(deploymentBuilder); + } catch (Exception e) { + logger.warn("Unable to invoke deploymentBuilder: " + e.getMessage()); + } } @PreUndeploy @@ -117,23 +121,26 @@ public class MSOInfrastructureApplication { } public void deployCustomWorkflows(DeploymentBuilder deploymentBuilder) { - if (workflowRepository == null) { - return; - } - List<Workflow> workflows = workflowRepository.findAll(); - if (workflows != null && workflows.size() != 0) { - for (Workflow workflow : workflows) { - String workflowName = workflow.getName(); - String workflowBody = workflow.getBody(); - if (!workflowName.endsWith(BPMN_SUFFIX)) { - workflowName += BPMN_SUFFIX; - } - if (workflowBody != null) { - logger.info("{} {}", "Deploying custom workflow", workflowName); - deploymentBuilder.addString(workflowName, workflowBody); + logger.debug("Attempting to deploy custom workflows"); + try { + List<Workflow> workflows = catalogDbClient.findWorkflowBySource(SDC_SOURCE); + if (workflows != null && !workflows.isEmpty()) { + for (Workflow workflow : workflows) { + String workflowName = workflow.getName(); + String workflowBody = workflow.getBody(); + if (!workflowName.endsWith(BPMN_SUFFIX)) { + workflowName += BPMN_SUFFIX; + } + if (workflowBody != null) { + logger.info(LoggingAnchor.TWO, "Deploying custom workflow", workflowName); + deploymentBuilder.addString(workflowName, workflowBody); + } + deploymentBuilder.enableDuplicateFiltering(true); + deploymentBuilder.deploy(); } } - deploymentBuilder.deploy(); + } catch (Exception e) { + logger.warn("Unable to deploy custom workflows, " + e.getMessage()); } } } diff --git a/bpmn/mso-infrastructure-bpmn/src/main/resources/application.yaml b/bpmn/mso-infrastructure-bpmn/src/main/resources/application.yaml index a91cb9d88d..e364981a66 100644 --- a/bpmn/mso-infrastructure-bpmn/src/main/resources/application.yaml +++ b/bpmn/mso-infrastructure-bpmn/src/main/resources/application.yaml @@ -4,7 +4,7 @@ server: max-threads: 50 mso: infra: - auditInventory: true + auditInventory: false spring: datasource: driver-class-name: org.mariadb.jdbc.Driver @@ -36,4 +36,4 @@ management: export: prometheus: enabled: true # Whether exporting of metrics to Prometheus is enabled. - step: 1m # Step size (i.e. reporting frequency) to use.
\ No newline at end of file + step: 1m # Step size (i.e. reporting frequency) to use. diff --git a/bpmn/pom.xml b/bpmn/pom.xml index b8c572fe19..65af2fd8d5 100644 --- a/bpmn/pom.xml +++ b/bpmn/pom.xml @@ -24,7 +24,8 @@ <xmlunit.version>2.4.0</xmlunit.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> - <sdnc.northbound.version>1.5.2-SNAPSHOT</sdnc.northbound.version> + <sdnc.northbound.version>1.5.2</sdnc.northbound.version> + <appc.client.version>1.6.0-SNAPSHOT</appc.client.version> </properties> <modules> diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AssignVnfBB.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AssignVnfBB.bpmn index 7bb97939dd..d522f3445e 100644 --- a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AssignVnfBB.bpmn +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AssignVnfBB.bpmn @@ -24,7 +24,7 @@ <bpmn:sequenceFlow id="SequenceFlow_1nle8kc" sourceRef="Task_createInstanceGroups" targetRef="ExclusiveGateway_02tchpp" /> <bpmn:sequenceFlow id="SequenceFlow_11jum90" name="no" sourceRef="ExclusiveGateway_02tchpp" targetRef="ExclusiveGateway_1blf52g" /> <bpmn:sequenceFlow id="SequenceFlow_1uiok7v" name="yes" sourceRef="ExclusiveGateway_02tchpp" targetRef="Task_callHoming"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("homing")}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("homing") == true}]]></bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:sequenceFlow id="SequenceFlow_0v8d14a" sourceRef="Task_callHoming" targetRef="ExclusiveGateway_1blf52g" /> <bpmn:callActivity id="Task_callHoming" name="Call Homing" calledElement="HomingBB"> diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ConfigAssignVnfBB.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ConfigAssignVnfBB.bpmn index 9892fbdd91..11d77bf97a 100644 --- a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ConfigAssignVnfBB.bpmn +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ConfigAssignVnfBB.bpmn @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_1ahlzqg" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="2.0.1"> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_1ahlzqg" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="1.9.0"> <bpmn:process id="ConfigAssignVnfBB" name="ConfigAssignVnfBB" isExecutable="true"> <bpmn:startEvent id="StartEvent_1"> <bpmn:outgoing>SequenceFlow_0gmfit3</bpmn:outgoing> @@ -23,7 +23,7 @@ <bpmn:outgoing>SequenceFlow_1mkhog2</bpmn:outgoing> </bpmn:serviceTask> <bpmn:sequenceFlow id="SequenceFlow_05qembo" sourceRef="Task_0bhf6tp" targetRef="CallActivity_1gfzi2g" /> - <bpmn:serviceTask id="Task_0bhf6tp" name="PreProcess Abstract CDS Processing" camunda:expression="${ConfigAssignVnf.PreProcessAbstractCDSProcessing(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:serviceTask id="Task_0bhf6tp" name="PreProcess Abstract CDS Processing" camunda:expression="${ConfigAssignVnf.preProcessAbstractCDSProcessing(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> <bpmn:incoming>SequenceFlow_0gmfit3</bpmn:incoming> <bpmn:outgoing>SequenceFlow_05qembo</bpmn:outgoing> </bpmn:serviceTask> @@ -34,7 +34,7 @@ </bpmn:exclusiveGateway> <bpmn:sequenceFlow id="SequenceFlow_0cvsnuu" sourceRef="CallActivity_1gfzi2g" targetRef="ExclusiveGateway_13q340y" /> <bpmn:sequenceFlow id="SequenceFlow_07tqu82" name="success" sourceRef="ExclusiveGateway_13q340y" targetRef="Task_1hs1mn0"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{execution.getVariable("CDSStatus").equals("Success")}</bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[#{execution.getVariable("CDSStatus").equals("Success")}]]></bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:endEvent id="EndEvent_0mnaj50"> <bpmn:incoming>SequenceFlow_15gxql1</bpmn:incoming> @@ -49,15 +49,15 @@ <dc:Bounds x="507" y="187" width="36" height="36" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0gmfit3_di" bpmnElement="SequenceFlow_0gmfit3"> - <di:waypoint x="543" y="205" /> - <di:waypoint x="614" y="205" /> + <di:waypoint xsi:type="dc:Point" x="543" y="205" /> + <di:waypoint xsi:type="dc:Point" x="614" y="205" /> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="EndEvent_0lgvk82_di" bpmnElement="EndEvent_0lgvk82"> <dc:Bounds x="1307" y="187" width="36" height="36" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1mkhog2_di" bpmnElement="SequenceFlow_1mkhog2"> - <di:waypoint x="1218" y="205" /> - <di:waypoint x="1307" y="205" /> + <di:waypoint xsi:type="dc:Point" x="1218" y="205" /> + <di:waypoint xsi:type="dc:Point" x="1307" y="205" /> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="CallActivity_1gfzi2g_di" bpmnElement="CallActivity_1gfzi2g"> <dc:Bounds x="788" y="165" width="100" height="80" /> @@ -66,8 +66,8 @@ <dc:Bounds x="1118" y="165" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_05qembo_di" bpmnElement="SequenceFlow_05qembo"> - <di:waypoint x="714" y="205" /> - <di:waypoint x="788" y="205" /> + <di:waypoint xsi:type="dc:Point" x="714" y="205" /> + <di:waypoint xsi:type="dc:Point" x="788" y="205" /> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_01mv1si_di" bpmnElement="Task_0bhf6tp"> <dc:Bounds x="614" y="165" width="100" height="80" /> @@ -76,12 +76,12 @@ <dc:Bounds x="978" y="180" width="50" height="50" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0cvsnuu_di" bpmnElement="SequenceFlow_0cvsnuu"> - <di:waypoint x="888" y="205" /> - <di:waypoint x="978" y="205" /> + <di:waypoint xsi:type="dc:Point" x="888" y="205" /> + <di:waypoint xsi:type="dc:Point" x="978" y="205" /> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_07tqu82_di" bpmnElement="SequenceFlow_07tqu82"> - <di:waypoint x="1028" y="205" /> - <di:waypoint x="1118" y="205" /> + <di:waypoint xsi:type="dc:Point" x="1028" y="205" /> + <di:waypoint xsi:type="dc:Point" x="1118" y="205" /> <bpmndi:BPMNLabel> <dc:Bounds x="1053" y="187" width="41" height="14" /> </bpmndi:BPMNLabel> @@ -90,8 +90,8 @@ <dc:Bounds x="985" y="327" width="36" height="36" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_15gxql1_di" bpmnElement="SequenceFlow_15gxql1"> - <di:waypoint x="1003" y="230" /> - <di:waypoint x="1003" y="327" /> + <di:waypoint xsi:type="dc:Point" x="1003" y="230" /> + <di:waypoint xsi:type="dc:Point" x="1003" y="327" /> </bpmndi:BPMNEdge> </bpmndi:BPMNPlane> </bpmndi:BPMNDiagram> diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/DeleteVfModuleBB.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/DeleteVfModuleBB.bpmn index b774c052cc..33335ab2c4 100644 --- a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/DeleteVfModuleBB.bpmn +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/DeleteVfModuleBB.bpmn @@ -82,7 +82,7 @@ <bpmn:sequenceFlow id="SequenceFlow_0qfmmgt" sourceRef="Audit_Inventory" targetRef="auditSuccessfulCheck" /> <bpmn:sequenceFlow id="SequenceFlow_14bu4ys" sourceRef="ExclusiveGateway_1yvh16a" targetRef="aaiThrow" /> <bpmn:sequenceFlow id="SequenceFlow_1mgunf3" name="No" sourceRef="ExclusiveGateway_1h2ystu" targetRef="ExclusiveGateway_1pydilb" /> - <bpmn:serviceTask id="Check_Audit" name="Check Audit Variable" camunda:expression="${AuditTasks.isAuditNeeded(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:serviceTask id="Check_Audit" name="Check Audit Variable" camunda:expression="${AuditTasks.isDeleteAuditNeeded(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> <bpmn:incoming>SequenceFlow_1v3jgqe</bpmn:incoming> <bpmn:outgoing>SequenceFlow_1odt2wt</bpmn:outgoing> </bpmn:serviceTask> diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/EtsiVnfInstantiateBB.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/EtsiVnfInstantiateBB.bpmn index 13bd107fdb..38bbdc1134 100644 --- a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/EtsiVnfInstantiateBB.bpmn +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/EtsiVnfInstantiateBB.bpmn @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_0x13ohc" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="2.2.4"> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_0x13ohc" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="2.0.3"> <bpmn:process id="EtsiVnfInstantiateBB" name=" EtsiVnfInstantiateBB" isExecutable="true"> <bpmn:serviceTask id="ServiceTask_02e82t2" name="Create CreateVnfRequest " camunda:expression="${VnfmAdapterCreateVnfTask.buildCreateVnfRequest(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> <bpmn:incoming>SequenceFlow_18fsqzd</bpmn:incoming> @@ -25,16 +25,22 @@ <bpmn:sequenceFlow id="SequenceFlow_0hp0ka1" sourceRef="ServiceTask_06ao4xu" targetRef="CallActivity_0fuqfru" /> <bpmn:callActivity id="CallActivity_0fuqfru" name="Monitor Instantiation Job" calledElement="MonitorVnfmCreateJob"> <bpmn:extensionElements> - <camunda:in source="SDNCRequest" target="SDNCRequest" /> - <camunda:out source="SDNCResponse" target="SDNCResponse" /> <camunda:out source="WorkflowException" target="WorkflowException" /> <camunda:in source="mso-request-id" target="mso-request-id" /> + <camunda:in source="gBuildingBlockExecution" target="gBuildingBlockExecution" /> + <camunda:out source="gBuildingBlockExecution" target="gBuildingBlockExecution" /> + <camunda:in source="createVnfResponse" target="createVnfResponse" /> + <camunda:out source="WorkflowExceptionErrorMessage" target="WorkflowExceptionErrorMessage" /> </bpmn:extensionElements> <bpmn:incoming>SequenceFlow_0hp0ka1</bpmn:incoming> <bpmn:outgoing>SequenceFlow_1owx4yu</bpmn:outgoing> </bpmn:callActivity> <bpmn:sequenceFlow id="SequenceFlow_1owx4yu" sourceRef="CallActivity_0fuqfru" targetRef="CallActivity_0agszsb" /> <bpmn:callActivity id="CallActivity_0agszsb" name="Monitor Create Node Status" calledElement="MonitorVnfmCreateNodeStatus"> + <bpmn:extensionElements> + <camunda:in source="gBuildingBlockExecution" target="gBuildingBlockExecution" /> + <camunda:out source="gBuildingBlockExecution" target="gBuildingBlockExecution" /> + </bpmn:extensionElements> <bpmn:incoming>SequenceFlow_1owx4yu</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0n57z81</bpmn:outgoing> </bpmn:callActivity> diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/MonitorVnfmCreateNodeStatus.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/MonitorVnfmCreateNodeStatus.bpmn index 6d54262dc5..9712ca8ab7 100644 --- a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/MonitorVnfmCreateNodeStatus.bpmn +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/MonitorVnfmCreateNodeStatus.bpmn @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_1ko0frn" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="2.2.4"> - <bpmn:process id="Process_1" isExecutable="true"> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_1ko0frn" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="2.0.3"> + <bpmn:process id="MonitorVnfmCreateNodeStatus" name="MonitorVnfmCreateNodeStatus" isExecutable="true"> <bpmn:startEvent id="StartEvent_0k0qfjb"> <bpmn:outgoing>SequenceFlow_1miob62</bpmn:outgoing> </bpmn:startEvent> @@ -24,7 +24,7 @@ <bpmn:endEvent id="EndEvent_0tei3i9"> <bpmn:incoming>SequenceFlow_1rxbeqi</bpmn:incoming> </bpmn:endEvent> - <bpmn:serviceTask id="ServiceTask_0y71su8" name=" Get node status " camunda:asyncAfter="true" camunda:expression="${MonitorVnfmNodeTask.getNodeStatus(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:serviceTask id="ServiceTask_0y71su8" name=" Get node status " camunda:asyncAfter="true" camunda:expression="${MonitorInstantiateVnfmNodeTask.getNodeStatus(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> <bpmn:incoming>SequenceFlow_1moaz0q</bpmn:incoming> <bpmn:incoming>SequenceFlow_09t51ao</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0qvy3sn</bpmn:outgoing> @@ -56,7 +56,7 @@ <bpmn:sequenceFlow id="SequenceFlow_0qcc5x4" sourceRef="BoundaryEvent_1f5o5i9" targetRef="ServiceTask_12qp0ty" /> </bpmn:process> <bpmndi:BPMNDiagram id="BPMNDiagram_1"> - <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1"> + <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="MonitorVnfmCreateNodeStatus"> <bpmndi:BPMNShape id="StartEvent_0k0qfjb_di" bpmnElement="StartEvent_0k0qfjb"> <dc:Bounds x="155" y="219" width="36" height="36" /> </bpmndi:BPMNShape> diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/MonitorVnfmDeleteNodeStatus.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/MonitorVnfmDeleteNodeStatus.bpmn index 8fababaffe..668cfaa44a 100644 --- a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/MonitorVnfmDeleteNodeStatus.bpmn +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/MonitorVnfmDeleteNodeStatus.bpmn @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_15jp7td" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="2.2.4"> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_15jp7td" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="2.0.3"> <bpmn:process id="MonitorVnfmDeleteNodeStatus" name="MonitorVnfmDeleteNodeStatus" isExecutable="true"> <bpmn:startEvent id="StartEvent_0f7nbs2"> <bpmn:outgoing>SequenceFlow_0spr34x</bpmn:outgoing> @@ -28,7 +28,7 @@ <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">${execution.getVariable("deleteVnfNodeStatus")}</bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:sequenceFlow id="SequenceFlow_0zlblru" sourceRef="ExclusiveGateway_1j9jbtk" targetRef="IntermediateCatchEvent_15yl23y" /> - <bpmn:serviceTask id="ServiceTask_1ksqjjf" name=" Get node status " camunda:asyncAfter="true" camunda:expression="${MonitorVnfmNodeTask.getNodeStatus(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:serviceTask id="ServiceTask_1ksqjjf" name=" Get node status " camunda:asyncAfter="true" camunda:expression="${MonitorTerminateVnfmNodeTask.getNodeStatus(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> <bpmn:incoming>SequenceFlow_17vvpzi</bpmn:incoming> <bpmn:incoming>SequenceFlow_11rfobu</bpmn:incoming> <bpmn:outgoing>SequenceFlow_1unicf9</bpmn:outgoing> diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/BaseBPMNTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/BaseBPMNTest.java index 5ef4d7ea98..ff987b75d4 100644 --- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/BaseBPMNTest.java +++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/BaseBPMNTest.java @@ -36,7 +36,7 @@ import org.junit.runner.RunWith; import org.onap.so.TestApplication; import org.onap.so.bpmn.buildingblock.HomingV2; import org.onap.so.bpmn.common.DelegateExecutionImpl; -import org.onap.so.bpmn.common.validation.BuildingBlockValidatorRunner; +import org.onap.so.bpmn.common.listener.validation.BuildingBlockValidatorRunner; import org.onap.so.bpmn.infrastructure.aai.tasks.AAICommonTasks; import org.onap.so.bpmn.infrastructure.aai.tasks.AAICreateTasks; import org.onap.so.bpmn.infrastructure.aai.tasks.AAIDeleteTasks; diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSDNCNetworkResource.groovy index 5ed815b0ab..0338647ce7 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSDNCNetworkResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSDNCNetworkResource.groovy @@ -317,6 +317,7 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor { </vnf-information> <vf-module-information> <from-preload>false</from-preload> + <vf-module-id>${msoUtils.xmlEscape(resourceInstanceId)}</vf-module-id> <onap-model-information> <model-invariant-uuid>${msoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> <model-customization-uuid>${msoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy index bd465eb9a8..2abee7caaa 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy @@ -23,23 +23,28 @@ package org.onap.so.bpmn.infrastructure.scripts -import org.onap.so.logger.ErrorCode; - import static org.apache.commons.lang3.StringUtils.* - import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.ServiceInstance import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.VnfResource import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.MessageEnum import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.web.util.UriUtils - import groovy.json.* /** @@ -325,12 +330,48 @@ public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor logger.debug("CreateVfModuleInfra Outgoing updateServiceOperStatusRequest Request: " + payload) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing prepareInitServiceOperationStatus.", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage()) } logger.trace("finished prepareInitServiceOperationStatus") } + + public void updateAAIOrchStatus (DelegateExecution execution){ + logger.debug(" ***** start updateAAIOrchStatus ***** ") + String msg = "" + String serviceInstanceId = execution.getVariable("serviceInstanceId") + logger.debug("serviceInstanceId: "+serviceInstanceId) + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + + try { + ServiceInstance si = execution.getVariable("serviceInstanceData") + boolean allActive = true + for (VnfResource resource : serviceDecomposition.vnfResources) { + logger.debug("resource.modelInfo.getModelName: " + resource.modelInfo.getModelName() +" | resource.getOrchestrationStatus: "+resource.getOrchestrationStatus()) + if (resource.getOrchestrationStatus() != "Active") { + allActive = false + } + } + + if (allActive){ + si.setOrchestrationStatus("Assigned") + }else { + si.setOrchestrationStatus("Pending") + } + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId) + client.update(uri, si) + } catch (BpmnError e) { + throw e + } catch (Exception ex) { + msg = "Exception in org.onap.so.bpmn.common.scripts.CompleteMsoProcess.updateAAIOrchStatus " + ex.getMessage() + logger.info( msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + + logger.debug(" ***** end updateAAIOrchStatus ***** ") + } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy index 421fd062fe..d431bdc3b4 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy @@ -201,10 +201,9 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { String uResourceInput = jsonUtil.addJsonValue(resourceInput, "requestInputs.CVLAN", cvlan) uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.SVLAN", svlan) - uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.accessID", remoteId) + uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.remote_id", remoteId) uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.manufacturer", manufacturer) uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ONTSN", ontsn) - logger.debug("old resource input:" + resourceInputObj.toString()) resourceInputObj.setResourceParameters(uResourceInput) execution.setVariable(Prefix + "resourceInput", resourceInputObj.toString()) @@ -397,7 +396,6 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { <subscriber-name>${msoUtils.xmlEscape(globalCustomerId)}</subscriber-name> </service-information> <vnf-information> - <vnf-id>${msoUtils.xmlEscape(vnfid)}</vnf-id> <vnf-type></vnf-type> <onap-model-information> <model-invariant-uuid>${msoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> @@ -883,4 +881,4 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { } logger.debug(" ***** Exit sendSyncResponse *****") } -}
\ No newline at end of file +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy index fa9fe62df4..c9dadf57cb 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.v12.GenericVnf; @@ -251,7 +252,7 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { String restFaultMessage = e.getMessage() //execution.setVariable("CVFMODVOL2_RESTFault", restFaultMessage) //execution.setVariable("CVFMODVOL2_isDataOk", false) - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Internal Error - During PreProcessRequest") @@ -301,7 +302,7 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Encountered ", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) @@ -402,7 +403,7 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { logger.debug("Outgoing MsoCompletionRequest: \n" + payload) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing PostProcessResponse - " + "\n", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("CVFMI_ErrorResponse", "Error Occured during PostProcessResponse Method:\n" + e.getMessage()) @@ -479,7 +480,7 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Caught exception in " + method , "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message") @@ -528,7 +529,7 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { logger.debug("CreateVfModuleInfra Outgoing UpdateInfra Request: " + payload) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing prepareUpdateInfraRequest.", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareUpdateInfraRequest Method:\n" + e.getMessage()) @@ -584,7 +585,7 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Caught exception in " + method , "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error') diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy index 5ba90eb989..1fba23d3c8 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; @@ -306,7 +307,7 @@ class CreateVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { String xmlHandlerRequest = utils.formatXml(falloutHandlerRequest) execution.setVariable(prefix+'FalloutHandlerRequest', xmlHandlerRequest) - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Overall Error Response " + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Overall Error Response " + "going to FalloutHandler", "BPMN", ErrorCode.UnknownError.getValue(), "\n" + xmlHandlerRequest); } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVnfInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVnfInfra.groovy index e941d50155..3eb15558d2 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVnfInfra.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVnfInfra.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory import org.onap.so.logger.ErrorCode @@ -168,7 +169,7 @@ class CreateVnfInfra extends AbstractServiceTaskProcessor { String sdncCallbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing' - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) @@ -194,7 +195,7 @@ class CreateVnfInfra extends AbstractServiceTaskProcessor { logger.debug("Rethrowing MSOWorkflowException") throw b }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), " Error Occurred in " + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), " Error Occurred in " + "CreateVnfInfra PreProcessRequest method", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occurred in CreateVnfInfra PreProcessRequest") @@ -220,7 +221,7 @@ class CreateVnfInfra extends AbstractServiceTaskProcessor { execution.setVariable("CREVI_sentSyncResponse", true) } catch (Exception ex) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), " Error Occurred in CreateVnfInfra SendSyncResponse Process", "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), " Error Occurred in CreateVnfInfra SendSyncResponse Process", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateVnfInfra SendSyncResponse Process") @@ -246,7 +247,7 @@ class CreateVnfInfra extends AbstractServiceTaskProcessor { logger.debug("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occurred Processing preProcessSDNCAssignRequest", "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occurred Processing preProcessSDNCAssignRequest", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareProvision Method:\n" + e.getMessage()) } @@ -270,7 +271,7 @@ class CreateVnfInfra extends AbstractServiceTaskProcessor { logger.debug("Outgoing CommitSDNCRequest is: \n" + activateSDNCRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured " + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured " + "Processing preProcessSDNCActivateRequest", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCActivateRequest Method:\n" + e.getMessage()) } @@ -461,7 +462,7 @@ class CreateVnfInfra extends AbstractServiceTaskProcessor { logger.debug("obtained VNF list: " + vnfs) if (vnfs == null) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "No matching " + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "No matching " + "VNFs in Catalog DB for vnfModelCustomizationUuid=" + vnfModelCustomizationUuid, "BPMN", ErrorCode.UnknownError.getValue(), ""); exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "No matching VNFs in Catalog DB for vnfModelCustomizationUuid=" + vnfModelCustomizationUuid) } @@ -470,7 +471,7 @@ class CreateVnfInfra extends AbstractServiceTaskProcessor { JSONObject vnf = vnfs.get(0) if (vnf == null) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "No matching VNF" + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "No matching VNF" + " in Catalog DB for vnfModelCustomizationUuid=" + vnfModelCustomizationUuid, "BPMN", ErrorCode.UnknownError.getValue(), ""); exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "No matching VNF in Catalog DB for vnfModelCustomizationUuid=" + vnfModelCustomizationUuid) } @@ -543,7 +544,7 @@ class CreateVnfInfra extends AbstractServiceTaskProcessor { aaiCR.createAAILineOfBusiness(lineOfBusiness, vnfId) }catch(Exception ex){ String msg = "Exception in LineOfBusiness. " + ex.getMessage(); - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + ex) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeActivateSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeActivateSDNCNetworkResource.groovy index 4233147f83..3d62a6ca90 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeActivateSDNCNetworkResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeActivateSDNCNetworkResource.groovy @@ -31,6 +31,7 @@ import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.core.domain.ModelInfo import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.bpmn.core.UrnPropertiesReader import org.slf4j.Logger @@ -80,45 +81,14 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor //the operationType from worflow(first node) is highest priority. operationType = jsonUtil.getJsonValue(recipeParamsFromWf, "operationType") } - - - // TODO: based on the resource type decide action and operation type - String sdnc_svcAction = "deactivate" - switch (resourceInputObj.getResourceModelInfo().getModelName()) { - case ~/[\w\s\W]*SOTNConnectivity[\w\s\W]*/ : - operationType = "SOTNConnectivity" - break - - case ~/[\w\s\W]*sotnvpnattachment[\w\s\W]*/ : - operationType = "SOTNAttachment" - break - - case ~/[\w\s\W]*SiteVF[\w\s\W]*/ : - operationType = "Site" - break - - case ~/[\w\s\W]*deviceVF[\w\s\W]*/ : - operationType = "SDWANDevice" - execution.setVariable("isActivateRequired", "true") - break - - case ~/[\w\s\W]*SDWANConnectivity[\w\s\W]*/ : - operationType = "SDWANConnectivity" - break - - case ~/[\w\s\W]*sdwanvpnattachment[\w\s\W]*/ : - operationType = "SDWANAttachment" - break - - case ~/[\w\s\W]*SiteWANVF[\w\s\W]*/ : - operationType = "SDWANPort" - execution.setVariable("isActivateRequired", "true") - break - - default: - break + String operationTypeFromConfig = UrnPropertiesReader.getVariable("resource-config." + resourceInputObj.resourceModelInfo.getModelName() + ".operation-type") + if (StringUtils.isNotEmpty(operationTypeFromConfig)) { + // highest priority if operation type configured + operationType = operationTypeFromConfig } + // based on the resource type decide action and operation type + String sdnc_svcAction = "deactivate" String sdnc_requestAction = StringUtils.capitalize(sdnc_svcAction) + operationType +"Instance" execution.setVariable(Prefix + "svcAction", sdnc_svcAction) execution.setVariable(Prefix + "requestAction", sdnc_requestAction) @@ -161,13 +131,12 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor String modelName = resourceInputObj.getResourceModelInfo().getModelName() String modelVersion = resourceInputObj.getResourceModelInfo().getModelVersion() String resourceInstnaceId = resourceInputObj.getResourceInstancenUuid() + String modelType = resourceInputObj.getResourceModelInfo().getModelType() // 1. prepare assign topology via SDNC Adapter SUBFLOW call String sdncTopologyDeleteRequest = "" - switch (modelName) { - case ~/[\w\s\W]*deviceVF[\w\s\W]*/ : - case ~/[\w\s\W]*SiteWANVF[\w\s\W]*/ : - case ~/[\w\s\W]*SiteVF[\w\s\W]*/: + switch (modelType) { + case "VNF" : sdncTopologyDeleteRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> @@ -224,8 +193,17 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor </aetgt:SDNCAdapterWorkflowRequest>""".trim() break - case ~/[\w\s\W]*sdwanvpnattachment[\w\s\W]*/ : - case ~/[\w\s\W]*sotnvpnattachment[\w\s\W]*/ : + case "GROUP" : + //When a new resource creation request reaches SO, the parent resources information needs to be provided + //while creating the child resource. + String vnfid = resourceInputObj.getVnfId() + ModelInfo vfModelInfo = resourceInputObj.getVfModelInfo() + String vnfmodelInvariantUuid = vfModelInfo.getModelInvariantUuid() + String vnfmodelCustomizationUuid = vfModelInfo.getModelCustomizationUuid() + String vnfmodelUuid = vfModelInfo.getModelUuid() + String vnfmodelVersion = vfModelInfo.getModelVersion() + String vnfmodelName = vfModelInfo.getModelName() + sdncTopologyDeleteRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> @@ -233,7 +211,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor <sdncadapter:RequestId>${msoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> <sdncadapter:SvcInstanceId>${msoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> <sdncadapter:SvcAction>${msoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> - <sdncadapter:SvcOperation>connection-attachment-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:SvcOperation>vf-module-topology-operation</sdncadapter:SvcOperation> <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> </sdncadapter:RequestHeader> @@ -257,26 +235,40 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor </onap-model-information> <service-instance-id>${msoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> <global-customer-id>${msoUtils.xmlEscape(globalCustomerId)}</global-customer-id> - <subscriber-name></subscriber-name> + <subscriber-name>${msoUtils.xmlEscape(globalCustomerId)}</subscriber-name> </service-information> - <allotted-resource-information> - <allotted-resource-id>$resourceInstnaceId</allotted-resource-id> - <allotted-resource-type></allotted-resource-type> - <parent-service-instance-id></parent-service-instance-id> - <onap-model-information> - <model-invariant-uuid>${msoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> - <model-customization-uuid>${msoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> - <model-uuid>${msoUtils.xmlEscape(modelUuid)}</model-uuid> - <model-version>${msoUtils.xmlEscape(modelVersion)}</model-version> - <model-name>${msoUtils.xmlEscape(modelName)}</model-name> - </onap-model-information> - </allotted-resource-information> - <connection-attachment-request-input> - </connection-attachment-request-input> + <vnf-information> + <vnf-id>$vnfid</vnf-id> + <vnf-type></vnf-type> + <onap-model-information> + <model-invariant-uuid>${msoUtils.xmlEscape(vnfmodelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${msoUtils.xmlEscape(vnfmodelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${msoUtils.xmlEscape(vnfmodelUuid)}</model-uuid> + <model-version>${msoUtils.xmlEscape(vnfmodelVersion)}</model-version> + <model-name>${msoUtils.xmlEscape(vnfmodelName)}</model-name> + </onap-model-information> + </vnf-information> + <vf-module-information> + <vf-module-id>$resourceInstnaceId</vf-module-id> + <vf-module-type></vf-module-type> + <from-preload>false</from-preload> + <onap-model-information> + <model-invariant-uuid>${msoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${msoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${msoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${msoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${msoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </vf-module-information> + <vf-module-request-input> + <vf-module-input-parameters> + </vf-module-input-parameters> + </vf-module-request-input> </sdncadapterworkflow:SDNCRequestData> </aetgt:SDNCAdapterWorkflowRequest>""".trim() break + // for SDWANConnectivity and SOTNConnectivity: default: sdncTopologyDeleteRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" @@ -325,6 +317,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor </network-request-input> </sdncadapterworkflow:SDNCRequestData> </aetgt:SDNCAdapterWorkflowRequest>""".trim() + } String sdncTopologyDeleteRequesAsString = utils.formatXml(sdncTopologyDeleteRequest) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteNetworkInstance.groovy index 1e2f50148c..5c7127f36e 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteNetworkInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteNetworkInstance.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil @@ -354,7 +355,7 @@ public class DeleteNetworkInstance extends AbstractServiceTaskProcessor { logger.debug(falloutHandlerRequest) execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, "BPMN", ErrorCode.UnknownError.getValue()) @@ -377,7 +378,7 @@ public class DeleteNetworkInstance extends AbstractServiceTaskProcessor { </aetgt:WorkflowException> </aetgt:FalloutHandlerRequest>""" execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest,"BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + ex) } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy index 20134a77a9..49f0e14d17 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy @@ -31,6 +31,8 @@ import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.ResourceType import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.bpmn.core.UrnPropertiesReader import org.slf4j.Logger @@ -52,7 +54,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { JsonUtils jsonUtil = new JsonUtils() SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() - + MsoUtils msoUtils = new MsoUtils() public void preProcessRequest(DelegateExecution execution){ @@ -84,62 +86,18 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { //the operationType from worflow(first node) is highest priority. operationType = jsonUtil.getJsonValue(recipeParamsFromWf, "operationType") } + String operationTypeFromConfig = UrnPropertiesReader.getVariable("resource-config." + resourceInputObj.resourceModelInfo.getModelName() + ".operation-type") + if (StringUtils.isNotEmpty(operationTypeFromConfig)) { + // highest priority if operation type configured + operationType = operationTypeFromConfig + } //For sdnc, generate svc_action and request_action String sdnc_svcAction = "delete" - switch (resourceInputObj.getResourceModelInfo().getModelName()) { - - case ~/[\w\s\W]*overlay[\w\s\W]*/ : - ///This will be resolved in R3. - sdnc_svcAction ="deactivate" - operationType = "NCINetwork" - break - - case ~/[\w\s\W]*underlay[\w\s\W]*/ : - //This will be resolved in R3. - operationType ="Network" - break - - case ~/[\w\s\W]*SOTNConnectivity[\w\s\W]*/ : - operationType = "SOTNConnectivity" - execution.setVariable("isActivateRequired", "true") - break - - case ~/[\w\s\W]*sotnvpnattachment[\w\s\W]*/ : - operationType = "SOTNAttachment" - execution.setVariable("isActivateRequired", "true") - break - - case ~/[\w\s\W]*SiteVF[\w\s\W]*/ : - operationType = "Site" - execution.setVariable("isActivateRequired", "true") - break - - case ~/[\w\s\W]*deviceVF[\w\s\W]*/ : - operationType = "SDWANDevice" - execution.setVariable("isActivateRequired", "true") - break - - case ~/[\w\s\W]*SDWANConnectivity[\w\s\W]*/ : - operationType = "SDWANConnectivity" - execution.setVariable("isActivateRequired", "true") - break - - case ~/[\w\s\W]*sdwanvpnattachment[\w\s\W]*/ : - operationType = "SDWANAttachment" - execution.setVariable("isActivateRequired", "true") - break - - case ~/[\w\s\W]*SiteWANVF[\w\s\W]*/ : - operationType = "SDWANPort" - execution.setVariable("isActivateRequired", "true") - break - - default: - break - } - String sdnc_requestAction = StringUtils.capitalize(sdnc_svcAction) + operationType +"Instance" + String sdnc_requestAction = StringUtils.capitalize(sdnc_svcAction) + operationType + "Instance" + String isActivateRequired = UrnPropertiesReader.getVariable("resource-config." + resourceInputObj.resourceModelInfo.getModelName() + ".activation-required") + execution.setVariable("isActivateRequired", isActivateRequired) execution.setVariable(Prefix + "svcAction", sdnc_svcAction) execution.setVariable(Prefix + "requestAction", sdnc_requestAction) execution.setVariable(Prefix + "serviceInstanceId", resourceInputObj.getServiceInstanceId()) @@ -152,6 +110,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { logger.debug( msg) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) } + logger.info(" ***** Exit preProcessRequest *****") } /** @@ -174,6 +133,8 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId") String source = execution.getVariable("source") String sdnc_service_id = execution.getVariable(Prefix + "sdncServiceId") + String resourceInput = execution.getVariable(Prefix + "resourceInput") + logger.info("The resourceInput is: " + resourceInput) ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) String serviceType = resourceInputObj.getServiceType() String serviceModelInvariantUuid = resourceInputObj.getServiceModelInfo().getModelInvariantUuid() @@ -187,13 +148,13 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { String modelName = resourceInputObj.getResourceModelInfo().getModelName() String modelVersion = resourceInputObj.getResourceModelInfo().getModelVersion() String resourceInstnaceId = resourceInputObj.getResourceInstancenUuid() + String modelType = resourceInputObj.getResourceModelInfo().getModelType() + // 1. prepare assign topology via SDNC Adapter SUBFLOW call String sdncTopologyDeleteRequest = "" - switch (modelName) { - case ~/[\w\s\W]*deviceVF[\w\s\W]*/ : - case ~/[\w\s\W]*SiteWANVF[\w\s\W]*/ : - case ~/[\w\s\W]*SiteVF[\w\s\W]*/: + switch (modelType) { + case "VNF": sdncTopologyDeleteRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> @@ -249,60 +210,82 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { </sdncadapterworkflow:SDNCRequestData> </aetgt:SDNCAdapterWorkflowRequest>""".trim() break - - case ~/[\w\s\W]*sdwanvpnattachment[\w\s\W]*/ : - case ~/[\w\s\W]*sotnvpnattachment[\w\s\W]*/ : - sdncTopologyDeleteRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" - xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" - xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> - <sdncadapter:RequestHeader> + case "GROUP" : + //When a new resource creation request reaches SO, the parent resources information needs to be provided + //while creating the child resource. + String vnfid = resourceInputObj.getVnfId() + ModelInfo vfModelInfo = resourceInputObj.getVfModelInfo() + String vnfmodelInvariantUuid = vfModelInfo.getModelInvariantUuid() + String vnfmodelCustomizationUuid = vfModelInfo.getModelCustomizationUuid() + String vnfmodelUuid = vfModelInfo.getModelUuid() + String vnfmodelVersion = vfModelInfo.getModelVersion() + String vnfmodelName = vfModelInfo.getModelName() + + sdncTopologyDeleteRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> <sdncadapter:RequestId>${msoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> <sdncadapter:SvcInstanceId>${msoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> <sdncadapter:SvcAction>${msoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> - <sdncadapter:SvcOperation>connection-attachment-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:SvcOperation>vf-module-topology-operation</sdncadapter:SvcOperation> <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> - </sdncadapter:RequestHeader> - <sdncadapterworkflow:SDNCRequestData> - <request-information> - <request-id>${msoUtils.xmlEscape(hdrRequestId)}</request-id> - <request-action>${msoUtils.xmlEscape(sdnc_requestAction)}</request-action> - <source>${msoUtils.xmlEscape(source)}</source> - <notification-url></notification-url> - <order-number></order-number> - <order-version></order-version> - </request-information> - <service-information> - <service-id>${msoUtils.xmlEscape(serviceInstanceId)}</service-id> - <subscription-service-type>${msoUtils.xmlEscape(serviceType)}</subscription-service-type> - <onap-model-information> - <model-invariant-uuid>${msoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> - <model-uuid>${msoUtils.xmlEscape(serviceModelUuid)}</model-uuid> - <model-version>${msoUtils.xmlEscape(serviceModelVersion)}</model-version> - <model-name>${msoUtils.xmlEscape(serviceModelName)}</model-name> - </onap-model-information> - <service-instance-id>${msoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> - <global-customer-id>${msoUtils.xmlEscape(globalCustomerId)}</global-customer-id> - <subscriber-name></subscriber-name> - </service-information> - <allotted-resource-information> - <allotted-resource-id>$resourceInstnaceId</allotted-resource-id> - <allotted-resource-type></allotted-resource-type> - <parent-service-instance-id></parent-service-instance-id> - <onap-model-information> - <model-invariant-uuid>${msoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> - <model-customization-uuid>${msoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> - <model-uuid>${msoUtils.xmlEscape(modelUuid)}</model-uuid> - <model-version>${msoUtils.xmlEscape(modelVersion)}</model-version> - <model-name>${msoUtils.xmlEscape(modelName)}</model-name> - </onap-model-information> - </allotted-resource-information> - <connection-attachment-request-input> - </connection-attachment-request-input> - </sdncadapterworkflow:SDNCRequestData> - </aetgt:SDNCAdapterWorkflowRequest>""".trim() + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${msoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>${msoUtils.xmlEscape(sdnc_requestAction)}</request-action> + <source>${msoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${msoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${msoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${msoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${msoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${msoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${msoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${msoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${msoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + <subscriber-name>${msoUtils.xmlEscape(globalCustomerId)}</subscriber-name> + </service-information> + <vnf-information> + <vnf-id>$vnfid</vnf-id> + <vnf-type></vnf-type> + <onap-model-information> + <model-invariant-uuid>${msoUtils.xmlEscape(vnfmodelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${msoUtils.xmlEscape(vnfmodelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${msoUtils.xmlEscape(vnfmodelUuid)}</model-uuid> + <model-version>${msoUtils.xmlEscape(vnfmodelVersion)}</model-version> + <model-name>${msoUtils.xmlEscape(vnfmodelName)}</model-name> + </onap-model-information> + </vnf-information> + <vf-module-information> + <vf-module-id>$resourceInstnaceId</vf-module-id> + <vf-module-type></vf-module-type> + <from-preload>false</from-preload> + <onap-model-information> + <model-invariant-uuid>${msoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${msoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${msoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${msoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${msoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </vf-module-information> + <vf-module-request-input> + <vf-module-input-parameters> + </vf-module-input-parameters> + </vf-module-request-input> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() break + // for SDWANConnectivity and SOTNConnectivity: default: sdncTopologyDeleteRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" @@ -373,6 +356,8 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { } public void prepareUpdateBeforeDeleteSDNCResource(DelegateExecution execution) { + logger.debug(" *** prepareUpdateBeforeDeleteSDNCResource *** ") + String resourceInput = execution.getVariable(Prefix + "resourceInput"); ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) String operType = resourceInputObj.getOperationType() String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() @@ -402,10 +387,13 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { </soapenv:Envelope>"""; setProgressUpdateVariables(execution, body) + logger.debug(" ***** Exit prepareUpdateBeforeDeleteSDNCResource *****") } public void prepareUpdateAfterDeleteSDNCResource(DelegateExecution execution) { + logger.debug(" *** prepareUpdateAfterDeleteSDNCResource *** ") + String resourceInput = execution.getVariable(Prefix + "resourceInput"); ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) String operType = resourceInputObj.getOperationType() String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() @@ -435,15 +423,16 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { </soapenv:Envelope>"""; setProgressUpdateVariables(execution, body) + logger.debug(" ***** Exit prepareUpdateAfterDeleteSDNCResource *****") } public void postDeleteSDNCCall(DelegateExecution execution){ - logger.info(" ***** Started prepareSDNCRequest *****") + logger.info(" ***** Started postDeleteSDNCCall *****") String responseCode = execution.getVariable(Prefix + "sdncDeleteReturnCode") String responseObj = execution.getVariable(Prefix + "SuccessIndicator") logger.info("response from sdnc, response code :" + responseCode + " response object :" + responseObj) - logger.info(" ***** Exit prepareSDNCRequest *****") + logger.info(" ***** Exit postDeleteSDNCCall *****") } public void sendSyncResponse (DelegateExecution execution) { diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleInfra.groovy index 3a1815cfe6..79aa745792 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleInfra.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleInfra.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; @@ -126,7 +127,7 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { } catch(Exception e) { String restFaultMessage = e.getMessage() - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Caught exception", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Caught exception", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Internal Error - During PreProcess Request") @@ -159,7 +160,7 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Caught exception in " + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) @@ -202,7 +203,7 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Caught exception in " + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) @@ -229,7 +230,7 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoDeleteVfModule(): ' + e.getMessage()) } @@ -277,7 +278,7 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepInfraRequest(): ' + e.getMessage()) @@ -322,7 +323,7 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error') @@ -375,7 +376,7 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error') diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy index cf53aff878..9fa488f8a7 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.VolumeGroup @@ -463,7 +464,7 @@ public class DeleteVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { logger.debug(xmlHandlerRequest) execution.setVariable("DELVfModVol_FalloutHandlerRequest", xmlHandlerRequest) - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Overall Error Response going to FalloutHandler", "BPMN", ErrorCode.UnknownError.getValue(), "\n" + xmlHandlerRequest); } @@ -484,7 +485,7 @@ public class DeleteVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { def String errorMessage = 'TenantId ' + tenantId + ' in incoming request does not match Tenant Id ' + volumeGroupTenantId + ' retrieved from AAI for Volume Group Id ' + volumeGroupId - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Error in DeleteVfModuleVolume: " + "\n" + errorMessage, "BPMN", ErrorCode.UnknownError.getValue()); diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy index 125c3e4504..a5a92b6b06 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy @@ -22,6 +22,7 @@ */ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.ErrorCode; import static org.apache.commons.lang3.StringUtils.*; @@ -443,7 +444,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { logger.debug("CreateVfModuleInfra Outgoing initResourceOperationStatus Request: " + payload) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preInitResourcesOperStatus.", "BPMN", ErrorCode.UnknownError.getValue(), e); execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy index a303da9a8f..587337b647 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy @@ -352,5 +352,10 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ public void postConfigRequest(DelegateExecution execution){ //now do noting + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + for (VnfResource resource : serviceDecomposition.vnfResources) { + resource.setOrchestrationStatus("Active") + } + execution.setVariable("serviceDecomposition", serviceDecomposition) } }
\ No newline at end of file diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy index 468f603ef6..eab99df9b2 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.client.HttpClientFactory import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.uri.AAIResourceUri @@ -234,7 +235,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces getAAIClient().connect(nsUri,relatedServiceUri) logger.info("NS relationship to Service added successfully") }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception occured while executing AAI Put Call", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); throw new BpmnError("MSOWorkflowException") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy index 6b4fc840f7..731c5b8dc5 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory import org.onap.so.client.HttpClientFactory import org.onap.so.logger.ErrorCode @@ -270,11 +271,11 @@ public class DoCreateVfModule extends VfModuleBase { Map<String,String> vfModuleInputParams = execution.getVariable("vfModuleInputParams") if (oofDirectives != null && vfModuleInputParams != null) { vfModuleInputParams.put("oof_directives", oofDirectives) - vfModuleInputParams.put("sdnc_directives", "{}") + //vfModuleInputParams.put("sdnc_directives", "{}") logger.debug("OofDirectives are: " + oofDirectives) } else if (vfModuleInputParams != null) { vfModuleInputParams.put("oof_directives", "{}") - vfModuleInputParams.put("sdnc_directives", "{}") + //vfModuleInputParams.put("sdnc_directives", "{}") } if (vfModuleInputParams != null) { execution.setVariable("DCVFM_vnfParamsMap", vfModuleInputParams) @@ -568,7 +569,7 @@ public class DoCreateVfModule extends VfModuleBase { String sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing' - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue(), msg); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) @@ -620,7 +621,7 @@ public class DoCreateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); @@ -747,7 +748,7 @@ public class DoCreateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage()) @@ -827,7 +828,7 @@ public class DoCreateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.SIX, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e, e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModuleForStatus(): ' + e.getMessage()) @@ -863,7 +864,7 @@ public class DoCreateVfModule extends VfModuleBase { logger.debug("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occurred Processing preProcessSDNCAssignRequest", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareProvision Method:\n" + e.getMessage()) @@ -957,7 +958,7 @@ public class DoCreateVfModule extends VfModuleBase { logger.debug("Outgoing GetSDNCRequest is: \n" + SDNCGetRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occurred Processing preProcessSDNCGetRequest", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage()) @@ -1165,7 +1166,7 @@ public class DoCreateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message") @@ -1556,7 +1557,7 @@ public class DoCreateVfModule extends VfModuleBase { logger.debug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessUpdateAAIVfModuleRequestOrch", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestOrch Method:\n" + e.getMessage()) @@ -1586,7 +1587,7 @@ public class DoCreateVfModule extends VfModuleBase { logger.debug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessUpdateAAIVfModuleStatus", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleStatus Method:\n" + e.getMessage()) @@ -1616,7 +1617,7 @@ public class DoCreateVfModule extends VfModuleBase { logger.debug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessUpdateAAIVfModuleRequestGroup", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestGroup Method:\n" + e.getMessage()) @@ -1696,7 +1697,7 @@ public class DoCreateVfModule extends VfModuleBase { logger.debug("Outgoing GetSDNCRequest is: \n" + SDNCGetRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessSDNCGetRequest", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage()) @@ -1818,14 +1819,14 @@ public class DoCreateVfModule extends VfModuleBase { logger.debug(" is Cloud Region Good: " + execution.getVariable("DCVFM_isCloudRegionGood")) } catch(BpmnError b){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Rethrowing MSOWorkflowException", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + b.getMessage()); throw b }catch (Exception ex) { // try error String errorMessage = "Bpmn error encountered in CreateVfModule flow. Unexpected Response from AAI - " + ex.getMessage() - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "AAI Query Cloud Region Failed " + errorMessage, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + ex); exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during queryCloudRegion method") @@ -1888,7 +1889,7 @@ public class DoCreateVfModule extends VfModuleBase { logger.debug("Outgoing CreateAAIVfModuleVolumeGroupRequest is: \n" + createAAIVfModuleVolumeGroupRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Exception Occured Processing prepareCreateAAIVfModuleVolumeGroupRequest', "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareCreateAAIVfModuleVolumeGroupRequest Method:\n" + e.getMessage()) @@ -2021,7 +2022,7 @@ public class DoCreateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Encountered in " + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); @@ -2066,7 +2067,7 @@ public class DoCreateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in postProcessUpdateAAIGenericVnf(): ' + e.getMessage()) @@ -2119,7 +2120,7 @@ public class DoCreateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in queryCatalogDB', "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryCatalogDB(): ' + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy index 65f6f76a21..4bab2b390d 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy @@ -21,6 +21,8 @@ */ package org.onap.so.bpmn.infrastructure.scripts + +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.NetworkPolicies @@ -263,7 +265,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ logger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessSDNCDeactivateRequest.", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage()) @@ -448,7 +450,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ // - public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "AAI error occurred deleting the Generic Vnf" + execution.getVariable("DoDVfMod_deleteGenericVnfResponse"), "BPMN", ErrorCode.UnknownError.getValue()); String processKey = getProcessKey(execution); @@ -609,7 +611,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessUpdateAAIGenericVnf((): ' + e.getMessage()) @@ -627,7 +629,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ execution.setVariable("rollbackError", null) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing setSuccessfulRollbackStatus.", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setSuccessfulRollbackStatus Method:\n" + e.getMessage()) @@ -647,7 +649,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ execution.setVariable("rollbackData", null) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing setFailedRollbackStatus.", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setFailedRollbackStatus Method:\n" + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnf.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnf.groovy index fb5c0fa0aa..e9b748b14b 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnf.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnf.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.db.catalog.beans.HomingInstance import org.onap.so.logger.ErrorCode @@ -215,7 +216,7 @@ class DoCreateVnf extends AbstractServiceTaskProcessor { String sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing' - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -406,7 +407,7 @@ class DoCreateVnf extends AbstractServiceTaskProcessor { logger.debug("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessSDNCAssignRequest", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCAssignRequest Method:\n" + e.getMessage()) @@ -624,7 +625,7 @@ class DoCreateVnf extends AbstractServiceTaskProcessor { logger.debug("Outgoing GetSDNCRequest is: \n" + SDNCGetRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occurred Processing preProcessSDNCGetRequest. ", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage()) @@ -663,7 +664,7 @@ class DoCreateVnf extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Caught exception in " + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy index 725a139b59..180032c8f0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.json.JSONObject; import org.json.JSONArray; import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor @@ -308,7 +309,7 @@ class DoCreateVnfAndModules extends AbstractServiceTaskProcessor { }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessAddOnModule ", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) @@ -326,7 +327,7 @@ class DoCreateVnfAndModules extends AbstractServiceTaskProcessor { execution.setVariable("addOnModulesDeployed", addOnModulesDeployed + 1) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing postProcessAddOnModule ", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during postProcessAddOnModule Method:\n" + e.getMessage()) @@ -356,7 +357,7 @@ class DoCreateVnfAndModules extends AbstractServiceTaskProcessor { } }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing validateBaseModule ", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during validateBaseModule Method:\n" + e.getMessage()) @@ -387,7 +388,7 @@ class DoCreateVnfAndModules extends AbstractServiceTaskProcessor { rollbackData.put("VNFANDMODULES", "numOfCreatedAddOnModules", "${numOfCreatedAddOnModules}") execution.setVariable("rollbackData", rollbackData) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessAddOnModule ", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModulesRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModulesRollback.groovy index 7ea32d2a60..a6cb5cf4cc 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModulesRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModulesRollback.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.ErrorCode import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution; @@ -163,7 +164,7 @@ class DoCreateVnfAndModulesRollback extends AbstractServiceTaskProcessor { execution.setVariable("DCVAMR_RollbackData", vfModuleRollbackData) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessCreateVfModuleRollback ", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessCreateVfModuleRollback Method:\n" + e.getMessage()) @@ -183,14 +184,14 @@ class DoCreateVnfAndModulesRollback extends AbstractServiceTaskProcessor { def numOfModulesToDelete = execution.getVariable("DCVAMR_numOfModulesToDelete") execution.setVariable("DCVAMR_numOfModulesToDelete", numOfModulesToDelete - 1) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing postProcessCreateVfModuleRollback ", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during postProcessCreateVfModuleRollback Method:\n" + e.getMessage()) } if (rolledBack == false) { logger.debug("Failure on DoCreateVfModuleRollback") - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Unsuccessful rollback of DoCreateVfModule ", "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during rollback of DoCreateVfModule") @@ -216,7 +217,7 @@ class DoCreateVnfAndModulesRollback extends AbstractServiceTaskProcessor { logger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessSDNCDeactivateRequest ", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage()) @@ -339,7 +340,7 @@ class DoCreateVnfAndModulesRollback extends AbstractServiceTaskProcessor { execution.setVariable("rollbackError", null) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured " + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured " + "Processing setSuccessfulRollbackStatus ", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setSuccessfulRollbackStatus Method:\n" + e.getMessage()) } @@ -361,7 +362,7 @@ class DoCreateVnfAndModulesRollback extends AbstractServiceTaskProcessor { execution.setVariable("rollbackData", null) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured " + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured " + "Processing setFailedRollbackStatus. ", "BPMN",ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setFailedRollbackStatus Method:\n" + e.getMessage()) } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy index f1b7328bcc..cf3a0ef56f 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy @@ -22,6 +22,7 @@ */ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.ErrorCode import static org.apache.commons.lang3.StringUtils.*; @@ -532,7 +533,7 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess logger.debug("CreateVfModuleInfra Outgoing initResourceOperationStatus Request: " + payload) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preInitResourcesOperStatus.", "BPMN", ErrorCode.UnknownError.getValue(), e); execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy index 1912d65ce3..48e4fdf2ff 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy @@ -22,6 +22,7 @@ */ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.aai.domain.yang.AllottedResource import org.onap.so.logger.ErrorCode @@ -944,7 +945,7 @@ public class DoCustomDeleteE2EServiceInstanceV2 extends AbstractServiceTaskProce }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preUpdateServiceOperationStatus.", "BPMN", ErrorCode.UnknownError.getValue(), e); execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preUpdateServiceOperationStatus Method:\n" + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy index f2af481f66..e24597aab3 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy @@ -21,34 +21,45 @@ */ package org.onap.so.bpmn.infrastructure.scripts + import groovy.json.JsonOutput import groovy.json.JsonSlurper import org.apache.commons.lang3.StringUtils +import org.apache.commons.lang3.tuple.ImmutablePair import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.json.JSONArray import org.json.JSONObject +import org.onap.aai.domain.yang.RelatedToProperty +import org.onap.aai.domain.yang.Relationship +import org.onap.aai.domain.yang.RelationshipData +import org.onap.aai.domain.yang.ServiceInstance import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.core.UrnPropertiesReader -import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.GroupResource import org.onap.so.bpmn.core.domain.Resource +import org.onap.so.bpmn.core.domain.ResourceType import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.domain.VnfcResource import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.client.HttpClient import org.onap.so.client.HttpClientFactory +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.slf4j.Logger import org.slf4j.LoggerFactory import org.onap.so.utils.TargetEntity import org.springframework.web.util.UriUtils -import org.w3c.dom.Document -import org.w3c.dom.Node -import org.xml.sax.InputSource +import javax.ws.rs.NotFoundException import javax.ws.rs.core.Response -import javax.xml.parsers.DocumentBuilder -import javax.xml.parsers.DocumentBuilderFactory + import static org.apache.commons.lang3.StringUtils.isBlank @@ -113,7 +124,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) } - String sdncCallbackUrl = UrnPropertiesReader.getVariable('URN_mso_workflow_sdncadapter_callback', execution) + String sdncCallbackUrl = UrnPropertiesReader.getVariable('mso.workflow.sdncadapter.callback', execution) if (isBlank(sdncCallbackUrl)) { msg = "URN_mso_workflow_sdncadapter_callback is null" logger.info(msg) @@ -161,80 +172,48 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { String msg = "" try { - String serviceInstanceId = execution.getVariable("serviceInstanceId") - boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator") - String serviceType = "" - - if(foundInAAI){ + String serviceInstanceId = execution.getVariable('serviceInstanceId') + String globalSubscriberId = execution.getVariable('globalSubscriberId') + String serviceType = execution.getVariable('serviceType') + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceInstanceId) + if (!resourceClient.exists(serviceInstanceUri)) { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai") + } + AAIResultWrapper wrapper = resourceClient.get(serviceInstanceUri, NotFoundException.class) + Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class) + // found in AAI + if (si.isPresent() && StringUtils.isNotEmpty(si.get().getServiceInstanceName())) { logger.debug("Found Service-instance in AAI") - - String siData = execution.getVariable("GENGS_service") - logger.debug("SI Data") - if (isBlank(siData)) - { - msg = "Could not retrive ServiceInstance data from AAI to delete id:" + serviceInstanceId - logger.error(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } - else - { - InputSource source = new InputSource(new StringReader(siData)); - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder() - Document serviceXml = docBuilder.parse(source) - serviceXml.getDocumentElement().normalize() - // get model invariant id - // Get Template uuid and version - if (utils.nodeExists(siData, "model-invariant-id") && utils.nodeExists(siData, "model-version-id") ) { - logger.debug("SI Data model-invariant-id and model-version-id exist") - def modelInvariantId = serviceXml.getElementsByTagName("model-invariant-id").item(0).getTextContent() - def modelVersionId = serviceXml.getElementsByTagName("model-version-id").item(0).getTextContent() - - // Set Original Template info - execution.setVariable("model-invariant-id-original", modelInvariantId) - execution.setVariable("model-version-id-original", modelVersionId) - } - - logger.debug("SI Data" + siData) - //Confirm there are no related service instances (vnf/network or volume) - if (utils.nodeExists(siData, "relationship-list")) { - logger.debug("SI Data relationship-list exists") - JSONArray jArray = new JSONArray() - - XmlParser xmlParser = new XmlParser() - Node root = xmlParser.parseText(siData) - def relation_list = utils.getChildNode(root, 'relationship-list') - def relationships = utils.getIdenticalChildren(relation_list, 'relationship') - - for (def relation: relationships) { - def jObj = getRelationShipData(relation, isDebugEnabled) - jArray.put(jObj) - } - - execution.setVariable("serviceRelationShip", jArray.toString()) - execution.setVariable("serviceRelationShip", jArray.toString()) - } + execution.setVariable("serviceInstanceName", si.get().getServiceInstanceName()) + // get model invariant id + // Get Template uuid and version + if ((null != si.get().getModelInvariantId()) && (null != si.get().getModelVersionId())) { + logger.debug("SI Data model-invariant-id and model-version-id exist") + // Set Original Template info + execution.setVariable("model-invariant-id-original", si.get().getModelInvariantId()) + execution.setVariable("model-version-id-original", si.get().getModelVersionId()) } - }else{ - boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator") - if(!succInAAI){ - logger.debug("Error getting Service-instance from AAI :" + serviceInstanceId) - WorkflowException workflowException = execution.getVariable("WorkflowException") - if(workflowException != null){ - logger.error("workflowException: " + workflowException) - exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) - } - else { - msg = "Failure in postProcessAAIGET GENGS_SuccessIndicator:" + succInAAI - logger.error(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + if ((null != si.get().getRelationshipList()) && (null != si.get().getRelationshipList().getRelationship())) { + logger.debug("SI Data relationship-list exists") + List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship() + JSONArray jArray = new JSONArray() + for (Relationship relationship : relationshipList) { + def jObj = getRelationShipData(relationship) + jArray.put(jObj) } + execution.setVariable("serviceRelationShip", jArray.toString()) } - - logger.debug("Service-instance NOT found in AAI. Silent Success") + } else { + msg = "Service-instance: " + serviceInstanceId + " NOT found in AAI." + logger.error(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) } - }catch (BpmnError e) { + } catch (BpmnError e) { throw e + } catch (NotFoundException e) { + logger.debug("Service Instance does not exist AAI") + exceptionUtil.buildAndThrowWorkflowException(execution, 404, "Service Instance was not found in aai") } catch (Exception ex) { msg = "Exception in DoDeleteE2EServiceInstance.postProcessAAIGET. " + ex.getMessage() logger.debug(msg) @@ -243,50 +222,98 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { logger.debug(" *** Exit postProcessAAIGET *** ") } - private JSONObject getRelationShipData(node, isDebugEnabled){ - JSONObject jObj = new JSONObject() - - def relation = utils.nodeToString(node) - def rt = utils.getNodeText(relation, "related-to") - - def rl = utils.getNodeText(relation, "related-link") - logger.debug("ServiceInstance Related NS/Configuration :" + rl) - - def rl_datas = utils.getIdenticalChildren(node, "relationship-data") - for(def rl_data : rl_datas) { - def eKey = utils.getChildNodeText(rl_data, "relationship-key") - def eValue = utils.getChildNodeText(rl_data, "relationship-value") + private JSONObject getRelationShipData(Relationship relationship) { + JSONObject jObj = new JSONObject() + def rt = relationship.getRelatedTo() + def rl = relationship.getRelatedLink() + logger.debug("ServiceInstance Related NS/Configuration :" + rl) + List<RelationshipData> rl_datas = relationship.getRelationshipData() + for (RelationshipData rl_data : rl_datas) { + def eKey = rl_data.getRelationshipKey() + def eValue = rl_data.getRelationshipValue() + if ((rt.equals("service-instance") && eKey.equals("service-instance.service-instance-id")) + //for overlay/underlay + || (rt.equals("configuration") && eKey.equals("configuration.configuration-id") + )) { + jObj.put("resourceInstanceId", eValue) + } + // for sp-partner and others + else if (eKey.endsWith("-id")) { + jObj.put("resourceInstanceId", eValue) + String resourceName = rt + eValue; + jObj.put("resourceType", resourceName) + } + jObj.put("resourceLinkUrl", rl) + } + List<RelatedToProperty> rl_props = relationship.getRelatedToProperty() + for (RelatedToProperty rl_prop : rl_props) { + def eKey = rl_prop.getPropertyKey() + def eValue = rl_prop.getPropertyValue() + if ((rt.equals("service-instance") && eKey.equals("service-instance.service-instance-name")) + //for overlay/underlay + || (rt.equals("configuration") && eKey.equals("configuration.configuration-type"))) { + jObj.put("resourceType", eValue) + } + } + logger.debug("Relationship related to Resource:" + jObj.toString()) + return jObj + } - if ((rt == "service-instance" && eKey.equals("service-instance.service-instance-id")) - //for overlay/underlay - || (rt == "configuration" && eKey.equals("configuration.configuration-id") - )){ - jObj.put("resourceInstanceId", eValue) - } - // for sp-partner and others - else if(eKey.endsWith("-id")){ - jObj.put("resourceInstanceId", eValue) - String resourceName = rt + eValue; - jObj.put("resourceType", resourceName) - } + private Relationship getRelationShipFromNode(groovy.util.slurpersupport.Node relationshipNode) { + Relationship relationship = new Relationship() + def rtn = relationshipNode.childNodes() + List<RelationshipData> relationshipDatas = new ArrayList<>() + List<RelatedToProperty> relationshipProperties = new ArrayList<>() + while (rtn.hasNext()) { + groovy.util.slurpersupport.Node node = rtn.next() + def key = node.name() + + if(key.equals("related-to")){ + def rt = node.text() + relationship.setRelatedTo(rt) + } else if (key.equals("related-link")){ + def rl = node.text() + relationship.setRelatedLink(rl) + } else if (key.equals("relationship-label")){ + def label = node.text() + relationship.setRelationshipLabel(label) + } else if (key.equals("relationship-data")){ + def rData = node.childNodes() + RelationshipData relationshipData = new RelationshipData() + while(rData.hasNext()){ + groovy.util.slurpersupport.Node datanode = rData.next() + def dataKey = datanode.name() + if(dataKey.equals("relationship-key")) { + relationshipData.setRelationshipKey(datanode.text()) + } else if(dataKey.equals("relationship-value")) { + relationshipData.setRelationshipValue(datanode.text()) + } + } + relationshipDatas.add(relationshipData) + } else if (key.equals("related-to-property")){ + def rProperty = node.childNodes() + RelatedToProperty relationshipProperty = new RelatedToProperty() + while(rProperty.hasNext()){ + groovy.util.slurpersupport.Node propnode = rProperty.next() + + def dataKey = propnode.name() + if(dataKey.equals("property-key")) { + relationshipProperty.setPropertyKey(propnode.text()) + } else if(dataKey.equals("property-value")) { + relationshipProperty.setPropertyValue(propnode.text()) + } - jObj.put("resourceLinkUrl", rl) - } + } + relationshipProperties.add(relationshipProperty) + } - def rl_props = utils.getIdenticalChildren(node, "related-to-property") - for(def rl_prop : rl_props) { - def eKey = utils.getChildNodeText(rl_prop, "property-key") - def eValue = utils.getChildNodeText(rl_prop, "property-value") - if((rt == "service-instance" && eKey.equals("service-instance.service-instance-name")) - //for overlay/underlay - || (rt == "configuration" && eKey.equals("configuration.configuration-type"))){ - jObj.put("resourceType", eValue) - } - } + } + relationship.getRelationshipData().addAll(relationshipDatas) + relationship.getRelatedToProperty().addAll(relationshipProperties) - logger.debug("Relationship related to Resource:" + jObj.toString()) - return jObj - } + logger.debug("Relationship related to Resource:" + relationship.toString()) + return relationship + } public void getCurrentNS(DelegateExecution execution){ logger.info( "======== Start getCurrentNS Process ======== ") @@ -325,19 +352,31 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { } } - private void generateRelatedResourceInfo(String response, JSONObject jObj){ + private void generateRelatedResourceInfo(String response, JSONObject jObj, boolean processRelationship){ def xml = new XmlSlurper().parseText(response) def rtn = xml.childNodes() while (rtn.hasNext()) { groovy.util.slurpersupport.Node node = rtn.next() def key = node.name() - def value = node.text() - jObj.put(key, value) + if (key.equals("relationship-list") && processRelationship) { + def relns = node.childNodes() + JSONArray jArray = new JSONArray() + while (relns.hasNext()) { + groovy.util.slurpersupport.Node relNode = relns.next() + Relationship relationship = getRelationShipFromNode(relNode) + def relationObj = getRelationShipData(relationship) + jArray.put(relationObj) + } + jObj.put(key, jArray) + } else { + def value = node.text() + jObj.put(key, value) + } } } - private JSONObject getRelatedResourceInAAI (DelegateExecution execution, JSONObject jObj) + private JSONObject getRelatedResourceInAAI (DelegateExecution execution, JSONObject jObj, boolean processRelationship) { logger.debug(" ***** Started getRelatedResourceInAAI *****") @@ -365,7 +404,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { execution.setVariable(Prefix + "SuccessIndicator", true) execution.setVariable(Prefix + "FoundIndicator", true) - generateRelatedResourceInfo(aaiResponse, jObj) + generateRelatedResourceInfo(aaiResponse, jObj, processRelationship) //get model-invariant-uuid and model-uuid String modelInvariantId = "" @@ -392,7 +431,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { } public void postDecomposeService(DelegateExecution execution) { - logger.debug(" ***** Inside processDecomposition() of delete generic e2e service flow ***** ") + logger.debug(" ***** Inside postDecomposeService() of delete generic e2e service flow ***** ") try { ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") @@ -409,7 +448,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { relationShipList = jsonSlurper.parseText(serviceRelationShip) } - List<Resource> deleteRealResourceList = new ArrayList<Resource>() + List<ImmutablePair<Resource, List<Resource>>> deleteRealResourceList = new ArrayList<ImmutablePair<Resource, List<Resource>>>() //Set the real resource instance id to the decomosed resource list //reset the resource instance id , because in the decompose flow ,its a random one. @@ -417,21 +456,27 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { if (relationShipList != null) { relationShipList.each { - JSONObject obj = getRelatedResourceInAAI(execution, (JSONObject)it) + JSONObject obj = getRelatedResourceInAAI(execution, (JSONObject)it, true) for (Resource resource : deleteResourceList) { - String modelName = resource.getModelInfo().getModelName() - - String modelCustomizationUuid = resource.getModelInfo().getModelCustomizationUuid() - if (StringUtils.containsIgnoreCase(obj.get("resourceType"), modelName)) { - resource.setResourceId(obj.get("resourceInstanceId")) - deleteRealResourceList.add(resource) - } - else if (modelCustomizationUuid.equals(obj.get("modelCustomizationId"))) { - resource.setResourceId(obj.get("resourceInstanceId")) - resource.setResourceInstanceName(obj.get("resourceType")) - deleteRealResourceList.add(resource) + boolean matches = processMatchingResource(resource, obj) + if((matches) && resource.getResourceType().equals(ResourceType.VNF)) { + List<Resource> delGroupList = new ArrayList<Resource>() + JSONArray vfRelationship = obj.getJSONArray("relationship-list") + for (int idx = 0; idx < vfRelationship.length(); idx++) { + JSONObject vfItem = vfRelationship.getJSONObject(idx) + JSONObject groupObject = getRelatedResourceInAAI(execution, vfItem, false) + List<GroupResource> groups = ((VnfResource)resource).getGroups() + for (GroupResource group : groups){ + if(processMatchingResource(group, groupObject)){ + delGroupList.add(group) + } + } + } + def delMap = new ImmutablePair(resource, delGroupList) + + deleteRealResourceList.add(delMap) } } } @@ -452,7 +497,25 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { logger.error(exceptionMessage) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) } - logger.debug( " ***** exit processDecomposition() of delete generic e2e service flow ***** ") + logger.debug(" ***** exit postDecomposeService() of delete generic e2e service flow ***** ") + } + + private boolean processMatchingResource(Resource resource, JSONObject obj) { + boolean matches = false + String modelName = resource.getModelInfo().getModelName() + + String modelCustomizationUuid = resource.getModelInfo().getModelCustomizationUuid() + if (StringUtils.containsIgnoreCase(obj.get("resourceType"), modelName)) { + resource.setResourceId(obj.get("resourceInstanceId")) + //deleteRealResourceList.add(resource) + matches = true; + } else if (modelCustomizationUuid.equals(obj.get("modelCustomizationId"))) { + resource.setResourceId(obj.get("resourceInstanceId")) + resource.setResourceInstanceName(obj.get("resourceType")) + //deleteRealResourceList.add(resource) + matches = true; + } + return matches } public void preInitResourcesOperStatus(DelegateExecution execution){ @@ -471,11 +534,12 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { execution.setVariable("serviceInstanceId", serviceId) execution.setVariable("operationId", operationId) execution.setVariable("operationType", operationType) - List<Resource> deleteResourceList = execution.getVariable("deleteResourceList") + List<ImmutablePair<Resource, List<Resource>>> deleteResourceList = execution.getVariable("deleteResourceList") String serviceRelationShip = execution.getVariable("serviceRelationShip") - for(Resource resource : deleteResourceList){ - resourceTemplateUUIDs = resourceTemplateUUIDs + resource.getModelInfo().getModelCustomizationUuid() + ":" + for (ImmutablePair rc : deleteResourceList) { + Resource resource = rc.getKey() + resourceTemplateUUIDs = resourceTemplateUUIDs + resource.getModelInfo().getModelCustomizationUuid() + ":" } def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy index 2558f7eff5..21f9484cbc 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.L3Network @@ -465,7 +466,7 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { } catch (Exception ex) { // caught exception String exceptionMessage = "Bpmn error encountered in DoDeleteNetworkInstance, sendRequestToVnfAdapter() - " + ex.getMessage() - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), exceptionMessage, + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), exceptionMessage, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + ex); logger.debug(exceptionMessage) @@ -517,7 +518,7 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { } catch (Exception ex) { // caught exception String exceptionMessage = "Bpmn error encountered in DoDeleteNetworkInstance, prepareSDNCRequest() - " + ex.getMessage() - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), exceptionMessage, + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), exceptionMessage, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + ex); logger.debug(exceptionMessage) @@ -558,7 +559,7 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { } catch (Exception ex) { // caught exception String exceptionMessage = "Bpmn error encountered in DoDeleteNetworkInstance, prepareSDNCRequest() - " + ex.getMessage() - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), exceptionMessage, + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), exceptionMessage, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + ex); logger.debug(exceptionMessage) @@ -998,7 +999,7 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { } catch (Exception ex) { // caught exception String exceptionMessage = "Bpmn error encountered in DoDeleteNetworkInstance, prepareSDNCRollback() - " + ex.getMessage() - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), exceptionMessage, + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), exceptionMessage, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + ex); logger.debug(exceptionMessage) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResourcesV1.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResourcesV1.groovy index 7e194657fb..2dcfcaa4f4 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResourcesV1.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResourcesV1.groovy @@ -22,7 +22,12 @@ */ package org.onap.so.bpmn.infrastructure.scripts +import org.apache.commons.lang3.tuple.ImmutablePair +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory +import org.onap.so.bpmn.core.domain.GroupResource +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.ResourceType import static org.apache.commons.lang3.StringUtils.isBlank @@ -102,7 +107,7 @@ public class DoDeleteResourcesV1 extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) } - String sdncCallbackUrl = UrnPropertiesReader.getVariable('URN_mso_workflow_sdncadapter_callback', execution) + String sdncCallbackUrl = UrnPropertiesReader.getVariable('mso.workflow.sdncadapter.callback', execution) if (isBlank(sdncCallbackUrl)) { msg = "URN_mso_workflow_sdncadapter_callback is null" logger.error(msg) @@ -151,17 +156,61 @@ public class DoDeleteResourcesV1 extends AbstractServiceTaskProcessor { List<Resource> wanResources = new ArrayList<Resource>() // get delete resource list and order list - List<Resource> delResourceList = execution.getVariable("deleteResourceList") + List<ImmutablePair<Resource, List<Resource>>> delResourceList = execution.getVariable("deleteResourceList") ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") String serviceModelName = serviceDecomposition.getModelInfo().getModelName(); - + String serviceModelUuid = serviceDecomposition.getModelInfo().getModelUuid(); + + Map<String, Map<String, Object>> parentVNF = new HashMap<>() + + // get Sequence from properties def resourceSequence = BPMNProperties.getResourceSequenceProp(serviceModelName) + // get Sequence from catalog db csar(model) + if(resourceSequence == null) { + resourceSequence = ResourceRequestBuilder.getResourceSequence(serviceModelUuid) + logger.info("Get Sequence from catalog db csar : " + resourceSequence) + } + if(resourceSequence != null) { for (resourceType in resourceSequence.reverse()) { - for (resource in delResourceList) { + + boolean vfFound = false + + for (ImmutablePair resourceTuple : delResourceList) { + Resource resource = resourceTuple.getKey() + List<Resource> groupResources = resourceTuple.getValue() + if (StringUtils.containsIgnoreCase(resource.getModelInfo().getModelName(), resourceType)) { + + + + // if resource type is vnfResource then check for groups also + // Did not use continue because if same model type is used twice + // then we would like to add it twice for processing + // e.g. S{ V1{G1, G2, G1}} --> S{ {G2, G1, G1}V1} + // we will add in reverse order for deletion + if (resource instanceof VnfResource) { + if (resource.getGroupOrder() != null && !StringUtils.isEmpty(resource.getGroupOrder())) { + String[] grpSequence = resource.getGroupOrder().split(",") + + Map<String, Object> parentVNFData = new HashMap<>() + parentVNFData.put("vfModelInfo", resource.getModelInfo()) + parentVNFData.put("vnf-id", resource.getResourceId()) + + for (String grpType in grpSequence.reverse()) { + for (GroupResource gResource in groupResources) { + if (StringUtils.containsIgnoreCase(gResource.getModelInfo().getModelName(), grpType)) { + sequencedResourceList.add(gResource) + // Store parent VNF info for the group resource id + parentVNF.put(gResource.getResourceId(), parentVNFData) + } + } + } + } + } + sequencedResourceList.add(resource) if (resource instanceof NetworkResource) { @@ -173,11 +222,32 @@ public class DoDeleteResourcesV1 extends AbstractServiceTaskProcessor { }else { //define sequenced resource list, we deploy vf first and then network and then ar //this is defaule sequence + // While deleting we will delete in resource order group resource, ar, network, then VF. List<VnfResource> vnfResourceList = new ArrayList<VnfResource>() List<AllottedResource> arResourceList = new ArrayList<AllottedResource>() - for (Resource rc : delResourceList) { + for (ImmutablePair resourceTuple : delResourceList) { + Resource rc = resourceTuple.getKey() + List<Resource> groupResources = resourceTuple.getValue() + if (rc instanceof VnfResource) { vnfResourceList.add(rc) + if (rc.getGroupOrder() != null && !StringUtils.isEmpty(rc.getGroupOrder())) { + String[] grpSequence = rc.getGroupOrder().split(",") + + Map<String, Object> parentVNFData = new HashMap<>() + parentVNFData.put("vfModelInfo", rc.getModelInfo()) + parentVNFData.put("vnf-id", rc.getResourceId()) + + for (String grpType in grpSequence.reverse()) { + for (GroupResource gResource in groupResources) { + if (StringUtils.containsIgnoreCase(gResource.getModelInfo().getModelName(), grpType)) { + sequencedResourceList.add(gResource) + // Store parent VNF info for the group resource id + parentVNF.put(gResource.getResourceId(), parentVNFData) + } + } + } + } } else if (rc instanceof NetworkResource) { wanResources.add(rc) } else if (rc instanceof AllottedResource) { @@ -199,6 +269,7 @@ public class DoDeleteResourcesV1 extends AbstractServiceTaskProcessor { execution.setVariable("isContainsWanResource", isContainsWanResource) execution.setVariable("currentResourceIndex", 0) execution.setVariable("sequencedResourceList", sequencedResourceList) + execution.setVariable("parentVNF", parentVNF) logger.debug("resourceSequence: " + resourceSequence) logger.debug(" ======== END sequenceResource Process ======== ") } @@ -235,45 +306,58 @@ public class DoDeleteResourcesV1 extends AbstractServiceTaskProcessor { */ public void executeResourceDelete(DelegateExecution execution) { logger.debug("======== Start executeResourceDelete Process ======== ") - try { - String requestId = execution.getVariable("msoRequestId") - String serviceInstanceId = execution.getVariable("serviceInstanceId") - String serviceType = execution.getVariable("serviceType") - - String resourceInstanceId = execution.getVariable("resourceInstanceId") - - Resource currentResource = execution.getVariable("currentResource") - String action = "deleteInstance" - JSONObject resourceRecipe = catalogDbUtils.getResourceRecipe(execution, currentResource.getModelInfo().getModelUuid(), action) - String recipeUri = resourceRecipe.getString("orchestrationUri") - int recipeTimeout = resourceRecipe.getInt("recipeTimeout") - String recipeParamXsd = resourceRecipe.get("paramXSD") - - - ResourceInput resourceInput = new ResourceInput(); - resourceInput.setServiceInstanceId(serviceInstanceId) - resourceInput.setResourceInstanceName(currentResource.getResourceInstanceName()) - resourceInput.setResourceInstancenUuid(currentResource.getResourceId()) - resourceInput.setOperationId(execution.getVariable("operationId")) - resourceInput.setOperationType(execution.getVariable("operationType")) - String globalSubscriberId = execution.getVariable("globalSubscriberId") - resourceInput.setGlobalSubscriberId(globalSubscriberId) - resourceInput.setResourceModelInfo(currentResource.getModelInfo()); - ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") - resourceInput.setServiceModelInfo(serviceDecomposition.getModelInfo()); - resourceInput.setServiceType(serviceType) - - String recipeURL = BPMNProperties.getProperty("bpelURL", "http://mso:8080") + recipeUri - - HttpResponse resp = BpmnRestClient.post(recipeURL, requestId, recipeTimeout, action, serviceInstanceId, serviceType, resourceInput.toString(), recipeParamXsd) - logger.debug(" ======== END executeResourceDelete Process ======== ") - }catch(BpmnError b){ - logger.error("Rethrowing MSOWorkflowException") - throw b - }catch(Exception e){ - logger.error("Error occured within DoDeleteResourcesV1 executeResourceDelete method: " + e) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured during DoDeleteResourcesV1 executeResourceDelete Catalog") - } + try { + String requestId = execution.getVariable("msoRequestId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String serviceType = execution.getVariable("serviceType") + + String resourceInstanceId = execution.getVariable("resourceInstanceId") + + Resource currentResource = execution.getVariable("currentResource") + String action = "deleteInstance" + JSONObject resourceRecipe = catalogDbUtils.getResourceRecipe(execution, currentResource.getModelInfo().getModelUuid(), action) + String recipeUri = resourceRecipe.getString("orchestrationUri") + int recipeTimeout = resourceRecipe.getInt("recipeTimeout") + String recipeParamXsd = resourceRecipe.get("paramXSD") + + + ResourceInput resourceInput = new ResourceInput(); + resourceInput.setServiceInstanceId(serviceInstanceId) + resourceInput.setResourceInstanceName(currentResource.getResourceInstanceName()) + resourceInput.setResourceInstancenUuid(currentResource.getResourceId()) + resourceInput.setOperationId(execution.getVariable("operationId")) + resourceInput.setOperationType(execution.getVariable("operationType")) + String globalSubscriberId = execution.getVariable("globalSubscriberId") + resourceInput.setGlobalSubscriberId(globalSubscriberId) + resourceInput.setResourceModelInfo(currentResource.getModelInfo()); + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + resourceInput.setServiceModelInfo(serviceDecomposition.getModelInfo()); + resourceInput.setServiceType(serviceType) + resourceInput.getResourceModelInfo().setModelType(currentResource.getResourceType().toString()) + if (currentResource.getResourceType() == ResourceType.GROUP) { + Map<String, Map<String, Object>> parentVNF = execution.getVariable("parentVNF") + if((null != parentVNF) && (null!=parentVNF.get(currentResource.getResourceId()))){ + Map<String, Object> parentVNFData = parentVNF.get(currentResource.getResourceId()) + ModelInfo parentVNFModel = parentVNFData.get("vfModelInfo") + String parentResourceId = parentVNFData.get("vnf-id") + resourceInput.setVfModelInfo(parentVNFModel) + resourceInput.setVnfId(parentResourceId) + } + } + + String recipeURL = BPMNProperties.getProperty("bpelURL", "http://so-bpmn-infra.onap:8081") + recipeUri + + BpmnRestClient bpmnRestClient = new BpmnRestClient() + + HttpResponse resp = bpmnRestClient.post(recipeURL, requestId, recipeTimeout, action, serviceInstanceId, serviceType, resourceInput.toString(), recipeParamXsd) + logger.debug(" ======== END executeResourceDelete Process ======== ") + } catch (BpmnError b) { + logger.error("Rethrowing MSOWorkflowException") + throw b + } catch (Exception e) { + logger.error("Error occured within DoDeleteResourcesV1 executeResourceDelete method: " + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured during DoDeleteResourcesV1 executeResourceDelete Catalog") + } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy index 0c676b5589..1acadbdad8 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy @@ -290,7 +290,8 @@ public class DoDeleteServiceInstance extends AbstractServiceTaskProcessor { AAIResourcesClient resourceClient = new AAIResourcesClient() AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId) - if(resourceClient.exists(uri)){ + if(resourceClient.exists(uri)){ + execution.setVariable("GENGS_FoundIndicator", true) execution.setVariable("GENGS_siResourceLink", uri.build().toString()) Map<String, String> keys = uri.getURIKeys() String globalSubscriberId = execution.getVariable("globalSubscriberId") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy index b21dcf3433..4c8247a309 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.aai.domain.yang.NetworkPolicies import org.onap.aai.domain.yang.NetworkPolicy import org.onap.so.logger.ErrorCode @@ -359,7 +360,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ // generates a WorkflowException if // - public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "AAI error occurred deleting the Generic Vnf: " + execution.getVariable("DoDVfMod_deleteGenericVnfResponse"), "BPMN", ErrorCode.UnknownError.getValue(), "Exception"); String processKey = getProcessKey(execution); @@ -580,7 +581,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) @@ -628,7 +629,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModuleForStatus(): ' + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy index e5306c40de..eba43632a7 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.aai.domain.yang.GenericVnf import org.onap.aai.domain.yang.NetworkPolicies import org.onap.aai.domain.yang.NetworkPolicy @@ -114,7 +115,7 @@ public class DoDeleteVfModuleFromVnf extends VfModuleBase { String sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing' - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue(), "Exception"); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -160,7 +161,7 @@ public class DoDeleteVfModuleFromVnf extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIForVfModule(): ' + e.getMessage()) @@ -213,7 +214,7 @@ public class DoDeleteVfModuleFromVnf extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in validateVfModule(): ' + e.getMessage()) @@ -239,7 +240,7 @@ public class DoDeleteVfModuleFromVnf extends VfModuleBase { }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessSDNCDeactivateRequest. Exception is:\n" + e, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage()) @@ -403,7 +404,7 @@ public class DoDeleteVfModuleFromVnf extends VfModuleBase { // generates a WorkflowException if // - public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "AAI error occurred deleting the Generic Vnf: " + execution.getVariable("DDVFMV_deleteGenericVnfResponse"), "BPMN", ErrorCode.UnknownError.getValue(), "Exception"); String processKey = getProcessKey(execution); diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy index 9bd3388b79..20d250d89f 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.aai.domain.yang.GenericVnf import org.onap.aai.domain.yang.VfModule import org.camunda.bpm.engine.delegate.BpmnError @@ -110,7 +111,7 @@ class DoDeleteVnfAndModules extends AbstractServiceTaskProcessor { String sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback", execution) if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing' - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue(), "Exception"); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -238,7 +239,7 @@ class DoDeleteVnfAndModules extends AbstractServiceTaskProcessor { }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessAddOnModule." + e, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) @@ -338,7 +339,7 @@ class DoDeleteVnfAndModules extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage()) @@ -366,7 +367,7 @@ class DoDeleteVnfAndModules extends AbstractServiceTaskProcessor { execution.setVariable("DDVAM_vfModuleModelInfo", vfModuleModelInfo) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessAddOnModule." + e, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareNextModuleToDelete Method:\n" + e.getMessage()) @@ -392,7 +393,7 @@ class DoDeleteVnfAndModules extends AbstractServiceTaskProcessor { logger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessSDNCDeactivateRequest." + e, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleE2EServiceInstance.groovy index ce3b243533..231fe6e252 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleE2EServiceInstance.groovy @@ -21,6 +21,7 @@ */ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.ErrorCode import static org.apache.commons.lang3.StringUtils.*; @@ -138,7 +139,7 @@ public class DoScaleE2EServiceInstance extends AbstractServiceTaskProcessor { logger.debug("CreateVfModuleInfra Outgoing initResourceOperationStatus Request: " + payload) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preInitResourcesOperStatus.", "BPMN", ErrorCode.UnknownError.getValue(), e); execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleVFCNetworkServiceInstance.groovy index 1b089d2a2b..2a8cc08cdf 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleVFCNetworkServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleVFCNetworkServiceInstance.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.DelegateExecution import org.json.JSONArray import org.json.JSONObject; @@ -182,7 +183,7 @@ public class DoScaleVFCNetworkServiceInstance extends AbstractServiceTaskProcess try { Thread.sleep(5000) } catch (InterruptedException e) { - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Time Delay exception" + e, "BPMN", ErrorCode.UnknownError.getValue()); } @@ -216,7 +217,7 @@ public class DoScaleVFCNetworkServiceInstance extends AbstractServiceTaskProcess logger.info("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class)) logger.trace("Completed Execute VF-C adapter Post Process ") }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception occured " + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception occured " + "while executing VFC Post Call.", "BPMN", ErrorCode.UnknownError.getValue(), e); throw new BpmnError("MSOWorkflowException") } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy index abbcf66323..f7852431e5 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.GenericVnf @@ -333,7 +334,7 @@ public class DoUpdateVfModule extends VfModuleBase { def sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing' - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -342,7 +343,7 @@ public class DoUpdateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) @@ -383,7 +384,7 @@ public class DoUpdateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preparePrepareUpdateAAIVfModule(): ' + e.getMessage()) @@ -434,14 +435,14 @@ public class DoUpdateVfModule extends VfModuleBase { logger.debug(" is Cloud Region Good: " + execution.getVariable(prefix + "isCloudRegionGood")) } catch(BpmnError b){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Rethrowing MSOWorkflowException", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + b); throw b }catch (Exception e) { // try error String errorMessage = "Bpmn error encountered in CreateVfModule flow. Unexpected Response from AAI - " + e.getMessage() - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "AAI Query Cloud Region Failed. Exception - " + "\n" + errorMessage, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during prepConfirmVolumeGroupTenant(): " + e.getMessage()) @@ -548,7 +549,7 @@ public class DoUpdateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepSDNCTopologyChg(): ' + e.getMessage()) @@ -612,7 +613,7 @@ public class DoUpdateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepSDNCTopologyQuery(): ' + e.getMessage()) @@ -716,7 +717,7 @@ public class DoUpdateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepVnfAdapterRest(): ' + e.getMessage()) @@ -764,7 +765,7 @@ public class DoUpdateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) @@ -838,7 +839,7 @@ public class DoUpdateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIVfModule(): ' + e.getMessage()) @@ -941,7 +942,7 @@ public class DoUpdateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepSDNCTopologyAct(): ' + e.getMessage()) @@ -962,7 +963,7 @@ public class DoUpdateVfModule extends VfModuleBase { try { def WorkflowException workflowException = (WorkflowException) execution.getVariable('WorkflowException') - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), method + ' caught WorkflowException: ' + workflowException.getErrorMessage(), "BPMN", ErrorCode.UnknownError.getValue()); @@ -970,7 +971,7 @@ public class DoUpdateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildWorkflowException(execution, 1002, 'Error in handleWorkflowException(): ' + e.getMessage()) @@ -1048,7 +1049,7 @@ public class DoUpdateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e, e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy index eb788a85b7..75ac6900fa 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.client.HttpClientFactory import org.onap.so.logger.ErrorCode @@ -272,7 +273,7 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage()) @@ -328,7 +329,7 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { } }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preProcessAddOnModule. Exception is:\n" + e, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareNextModuleToUpdate Method:\n" + e.getMessage()) @@ -404,7 +405,7 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/HandlePNF.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/HandlePNF.groovy index 90c2b923b0..cbeb1d3d69 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/HandlePNF.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/HandlePNF.groovy @@ -22,9 +22,12 @@ package org.onap.so.bpmn.infrastructure.scripts import org.apache.commons.lang3.StringUtils import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.recipe.ResourceInput +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.onap.so.bpmn.common.scripts.CatalogDbUtils import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames import org.slf4j.Logger @@ -35,50 +38,91 @@ public class HandlePNF extends AbstractServiceTaskProcessor{ ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() - CatalogDbUtils cutils = new CatalogDbUtils() + MsoUtils msoUtils = new MsoUtils() + String Prefix="CRESI_" @Override void preProcessRequest(DelegateExecution execution) { - msoLogger.debug("Start preProcess for HandlePNF") - + logger.debug("Start preProcess for HandlePNF") // set correlation ID def resourceInput = execution.getVariable("resourceInput") String serInput = jsonUtil.getJsonValue(resourceInput, "requestsInputs") String correlationId = jsonUtil.getJsonValue(serInput, "service.parameters.requestInputs.ont_ont_pnf_name") if (!StringUtils.isEmpty(correlationId)) { - execution.setVariable(ExecutionVariableNames.CORRELATION_ID, correlationId) - msoLogger.debug("Found correlation id : " + correlationId) + execution.setVariable(ExecutionVariableNames.PNF_CORRELATION_ID, correlationId) + logger.debug("Found correlation id : " + correlationId) } else { - msoLogger.error("== correlation id is empty ==") + logger.error("== correlation id is empty ==") exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "correlation id is not provided") } + + String serviceInstanceID = jsonUtil.getJsonValue(resourceInput, ExecutionVariableNames.SERVICE_INSTANCE_ID) + if (!StringUtils.isEmpty(serviceInstanceID)) { + execution.setVariable(ExecutionVariableNames.SERVICE_INSTANCE_ID, serviceInstanceID) + logger.debug("found serviceInstanceID: "+serviceInstanceID) + } else { + logger.error("== serviceInstance ID is empty ==") + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "serviceInstance ID is not provided") + } // next task will set the uuid - msoLogger.debug("exit preProcess for HandlePNF") + logger.debug("exit preProcess for HandlePNF") } void postProcessRequest(DelegateExecution execution) { - msoLogger.debug("start postProcess for HandlePNF") + logger.debug("start postProcess for HandlePNF") + ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(execution.getVariable("resourceInput"), ResourceInput.class) + String operType = resourceInputObj.getOperationType() + String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + String serviceInstanceId = resourceInputObj.getServiceInstanceId() + String operationId = resourceInputObj.getOperationId() + String progress = "100" + String status = "finished" + String statusDescription = "SDCN resource creation and activation completed" - msoLogger.debug("exit postProcess for HandlePNF") + String body = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateResourceOperationStatus> + <operType>${msoUtils.xmlEscape(operType)}</operType> + <operationId>${msoUtils.xmlEscape(operationId)}</operationId> + <progress>${msoUtils.xmlEscape(progress)}</progress> + <resourceTemplateUUID>${msoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID> + <serviceId>${msoUtils.xmlEscape(serviceInstanceId)}</serviceId> + <status>${msoUtils.xmlEscape(status)}</status> + <statusDescription>${msoUtils.xmlEscape(statusDescription)}</statusDescription> + </ns:updateResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>"""; + logger.debug("body: "+body) + setProgressUpdateVariables(execution, body) + logger.debug("exit postProcess for HandlePNF") } public void sendSyncResponse (DelegateExecution execution) { - msoLogger.debug(" *** sendSyncResponse *** ") + logger.debug(" *** sendSyncResponse *** ") try { String operationStatus = "finished" // RESTResponse for main flow String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim() - msoLogger.debug(" sendSyncResponse to APIH:" + "\n" + resourceOperationResp) + logger.debug(" sendSyncResponse to APIH:" + "\n" + resourceOperationResp) sendWorkflowResponse(execution, 202, resourceOperationResp) execution.setVariable("sentSyncResponse", true) } catch (Exception ex) { String msg = "Exception in sendSyncResponse:" + ex.getMessage() - msoLogger.debug(msg) + logger.debug(msg) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) } - msoLogger.debug(" ***** Exit sendSyncResponse *****") + logger.debug(" ***** Exit sendSyncResponse *****") + } + + private void setProgressUpdateVariables(DelegateExecution execution, String body) { + def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution) + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + execution.setVariable("CVFMI_updateResOperStatusRequest", body) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ReplaceVnfInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ReplaceVnfInfra.groovy index 4321dbadd5..e36f32578d 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ReplaceVnfInfra.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ReplaceVnfInfra.groovy @@ -21,6 +21,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.appc.client.lcm.model.Action; @@ -233,7 +234,7 @@ public class ReplaceVnfInfra extends VnfCmBase { } catch(Exception e) { String restFaultMessage = e.getMessage() - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Encountered - " + "\n" + restFaultMessage, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage) @@ -276,7 +277,7 @@ public class ReplaceVnfInfra extends VnfCmBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) @@ -327,7 +328,7 @@ public class ReplaceVnfInfra extends VnfCmBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getVnfResourceDecomposition(): ' + e.getMessage()) @@ -369,7 +370,7 @@ public class ReplaceVnfInfra extends VnfCmBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("errorCode", "1002") @@ -413,7 +414,7 @@ public class ReplaceVnfInfra extends VnfCmBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("errorCode", "1002") @@ -461,7 +462,7 @@ public class ReplaceVnfInfra extends VnfCmBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("errorCode", "1002") @@ -531,19 +532,19 @@ public class ReplaceVnfInfra extends VnfCmBase { logger.trace('Exited ' + method) } catch (BpmnError e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("errorCode", "1002") execution.setVariable("errorText", e.getMessage()) } catch (java.lang.NoSuchMethodError e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("errorCode", "1002") execution.setVariable("errorText", e.getMessage()) } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("errorCode", "1002") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy index ef4a78ffde..ed65616d89 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy @@ -21,6 +21,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.ErrorCode import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.camunda.bpm.engine.delegate.DelegateExecution @@ -87,7 +88,7 @@ public class RollbackVnf extends VnfCmBase { } catch(Exception e) { String restFaultMessage = e.getMessage() - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Encountered - " + "\n" + restFaultMessage, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("rollbackErrorCode", "1") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ScaleCustomE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ScaleCustomE2EServiceInstance.groovy index 0afa34bdec..b21efdd563 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ScaleCustomE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ScaleCustomE2EServiceInstance.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.ErrorCode import static org.apache.commons.lang3.StringUtils.* @@ -294,7 +295,7 @@ public class ScaleCustomE2EServiceInstance extends AbstractServiceTaskProcessor logger.debug("Scale network service updateServiceOperStatusRequest Request: " + payload) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing prepareInitServiceOperationStatus.", "BPMN", ErrorCode.UnknownError.getValue(), e); execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModule.groovy index 9db5b7366a..6946eebc56 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModule.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModule.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor @@ -96,7 +97,7 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) @@ -151,7 +152,7 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendSynchResponse(): ' + e.getMessage()) @@ -181,7 +182,7 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage()) @@ -237,7 +238,7 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateInfraRequest(): ' + e.getMessage()) @@ -278,7 +279,7 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error') @@ -333,7 +334,7 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error') diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy index 0344206145..7f2bbebc8d 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import groovy.json.JsonException import groovy.json.JsonSlurper import org.camunda.bpm.engine.delegate.BpmnError @@ -482,7 +483,7 @@ class UpdateVfModuleVolumeInfraV1 extends VfModuleBase { " retrieved from AAI for Volume Group Id " + volumeGroupId + ", AIC Cloud Region " + aicCloudRegion ExceptionUtil exceptionUtil = new ExceptionUtil() - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Error in ' + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Error in ' + 'UpdateVfModuleVol: ' + errorMessage, "BPMN", ErrorCode.UnknownError.getValue(), "Exception") exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) } @@ -501,7 +502,7 @@ class UpdateVfModuleVolumeInfraV1 extends VfModuleBase { " retrieved from AAI for Volume Group Id " ExceptionUtil exceptionUtil = new ExceptionUtil() - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Error in ' + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Error in ' + 'UpdateVfModuleVol: ' + errorMessage, "BPMN", ErrorCode.UnknownError.getValue(), "Exception") exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfInPlaceUpdate.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfInPlaceUpdate.groovy index 05aff713bc..3cb40115ba 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfInPlaceUpdate.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfInPlaceUpdate.groovy @@ -21,6 +21,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.logger.LoggingAnchor import groovy.json.JsonOutput import groovy.json.JsonSlurper import org.camunda.bpm.engine.delegate.BpmnError @@ -351,7 +352,7 @@ public class VnfInPlaceUpdate extends VnfCmBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + ' ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("errorCode", "1002") execution.setVariable("errorText", e.getMessage()) @@ -396,7 +397,7 @@ public class VnfInPlaceUpdate extends VnfCmBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + ' ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("errorCode", "1002") execution.setVariable("errorText", e.getMessage()) @@ -441,7 +442,7 @@ public class VnfInPlaceUpdate extends VnfCmBase { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + ' ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("errorCode", "1002") execution.setVariable("errorText", e.getMessage()) @@ -520,17 +521,17 @@ public class VnfInPlaceUpdate extends VnfCmBase { logger.trace('Exited ' + method) } catch (BpmnError e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + ' ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("errorCode", "1002") execution.setVariable("errorText", e.getMessage()) } catch (java.lang.NoSuchMethodError e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + ' ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("errorCode", "1002") execution.setVariable("errorText", e.getMessage()) } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + ' ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); execution.setVariable("errorCode", "1002") execution.setVariable("errorText", e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustService.groovy index 9829419128..d57011f61f 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustService.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustService.groovy @@ -21,6 +21,7 @@ */ package org.onap.so.bpmn.vcpe.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.ErrorCode; import static org.apache.commons.lang3.StringUtils.* @@ -420,7 +421,7 @@ public class CreateVcpeResCustService extends AbstractServiceTaskProcessor { } catch (BpmnError e) { throw e; } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) @@ -847,7 +848,7 @@ public class CreateVcpeResCustService extends AbstractServiceTaskProcessor { // Adding this line temporarily until this flows error handling gets updated exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception") } catch (BpmnError b) { - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Rethrowing MSOWorkflowException", "BPMN", ErrorCode.UnknownError.getValue()); throw b diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy index a1cdacaf08..553ec2397c 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy @@ -21,6 +21,7 @@ */ package org.onap.so.bpmn.vcpe.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor @@ -419,7 +420,7 @@ public class DeleteVcpeResCustService extends AbstractServiceTaskProcessor { execution.setVariable(Prefix+"unexpectedError", "Caught a Java Lang Exception") // Adding this line temporarily until this flows error handling gets updated exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception") }catch(BpmnError b){ - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Rethrowing MSOWorkflowException", "BPMN", ErrorCode.UnknownError.getValue()); throw b diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy index 2c5b6430e6..0681e54bba 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.vcpe.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.AllottedResource @@ -585,7 +586,7 @@ public class DoCreateAllottedResourceBRG extends AbstractServiceTaskProcessor{ execution.setVariable("sdncGetRequest", SDNCGetRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occurred Processing preProcessSDNCGetRequest.", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during SDNC GET Method:\n" + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollback.groovy index 58c0ef2dcf..f24bb46981 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollback.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.vcpe.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.AllottedResource @@ -205,7 +206,7 @@ public class DoCreateAllottedResourceBRGRollback extends AbstractServiceTaskProc } catch (BpmnError e) { throw e; }catch(Exception ex){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occurred Processing preProcessSDNCGetRequest.", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + ex); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during SDNC GET Method:\n" + ex.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXC.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXC.groovy index 61dd13b4e2..51d04dd092 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXC.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXC.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.vcpe.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.AllottedResource @@ -520,7 +521,7 @@ public class DoCreateAllottedResourceTXC extends AbstractServiceTaskProcessor{ execution.setVariable("sdncGetRequest", SDNCGetRequest) }catch(Exception e){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occurred Processing preProcessSDNCGetRequest.", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during SDNC GET Method:\n" + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy index 44e27d99cf..1427730187 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.vcpe.scripts +import org.onap.so.logger.LoggingAnchor import org.onap.aai.domain.yang.AllottedResource; import org.onap.so.bpmn.common.scripts.*; import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor @@ -206,7 +207,7 @@ public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProc } catch (BpmnError e) { throw e; }catch(Exception ex){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occurred Processing preProcessSDNCGetRequest.", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + ex); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during SDNC GET Method:\n" + ex.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRG.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRG.groovy index 9dcee3dfb2..29ee1a648e 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRG.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRG.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.vcpe.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AllottedResourceUtils @@ -351,7 +352,7 @@ public class DoDeleteAllottedResourceBRG extends AbstractServiceTaskProcessor{ } catch (BpmnError e) { throw e; }catch(Exception ex){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occurred Processing preProcessSDNCGetRequest." + ex, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:" + ex); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during SDNC GET Method:\n" + ex.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXC.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXC.groovy index 43e095859e..404f19eca9 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXC.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXC.groovy @@ -22,6 +22,7 @@ package org.onap.so.bpmn.vcpe.scripts +import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AllottedResourceUtils @@ -355,7 +356,7 @@ public class DoDeleteAllottedResourceTXC extends AbstractServiceTaskProcessor{ } catch (BpmnError e) { throw e; }catch(Exception ex){ - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occurred Processing preProcessSDNCGetRequest.", "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + ex); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during SDNC GET Method:\n" + ex.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationId.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationId.java index 7cb78a10e5..8010ce62ab 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationId.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/JsonUtilForPnfCorrelationId.java @@ -5,6 +5,7 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Copyright (C) 2018 Nokia. + * Modifications Copyright (c) 2019 Samsung * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,15 +36,18 @@ public final class JsonUtilForPnfCorrelationId { private static final String JSON_PNF_CORRELATION_ID_FIELD_NAME = "correlationId"; + private JsonUtilForPnfCorrelationId() { + throw new IllegalStateException("Utility class"); + } + static List<String> parseJsonToGelAllPnfCorrelationId(String json) { JsonElement je = new JsonParser().parse(json); JsonArray array = je.getAsJsonArray(); List<String> list = new ArrayList<>(); Spliterator<JsonElement> spliterator = array.spliterator(); - spliterator.forEachRemaining(jsonElement -> { - handleEscapedCharacters(jsonElement).ifPresent(jsonObject -> getPnfCorrelationId(jsonObject) - .ifPresent(pnfCorrelationId -> list.add(pnfCorrelationId))); - }); + spliterator.forEachRemaining(jsonElement -> handleEscapedCharacters(jsonElement) + .ifPresent(jsonObject -> getPnfCorrelationId(jsonObject) + .ifPresent(pnfCorrelationId -> list.add(pnfCorrelationId)))); return list; } 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 5451f9ff57..f7708b69d3 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.onap.so.logger.LoggingAnchor; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -282,7 +283,7 @@ public abstract class AbstractSdncOperationTask extends BaseTask { } catch (Exception exception) { logger.info("exception: AbstractSdncOperationTask.updateProgress fail!"); logger.error("exception: AbstractSdncOperationTask.updateProgress fail:", exception); - logger.error("{} {} {} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.GENERAL_EXCEPTION.toString(), " updateProgress catch exception: ", this.getTaskName(), ErrorCode.UnknownError.getValue(), exception.getClass().toString()); } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncNetworkTopologyOperationTask.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncNetworkTopologyOperationTask.java index 4d58439fda..8775b39f97 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncNetworkTopologyOperationTask.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncNetworkTopologyOperationTask.java @@ -23,6 +23,7 @@ package org.onap.so.bpmn.infrastructure.workflow.serviceTask; import java.util.Map; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; @@ -78,7 +79,7 @@ public class SdncNetworkTopologyOperationTask extends AbstractSdncOperationTask httpPost.addHeader("Authorization", defaulAuth); httpPost.addHeader("Content-type", "application/json"); String postBody = getPostbody(inputEntity); - logger.info("{} {} {}", MessageEnum.RA_SEND_REQUEST_SDNC, postBody, "SDNC"); + logger.info(LoggingAnchor.THREE, MessageEnum.RA_SEND_REQUEST_SDNC, postBody, "SDNC"); httpPost.setEntity(new StringEntity(postBody, ContentType.APPLICATION_XML)); httpPost(url, httpPost); logger.info("SdncNetworkTopologyOperationTask.send2SdncDirectly end!"); diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncServiceTopologyOperationTask.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncServiceTopologyOperationTask.java index 4fb6817a39..ab0bb718ab 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncServiceTopologyOperationTask.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncServiceTopologyOperationTask.java @@ -24,6 +24,7 @@ package org.onap.so.bpmn.infrastructure.workflow.serviceTask; import java.util.Map; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; @@ -77,7 +78,7 @@ public class SdncServiceTopologyOperationTask extends AbstractSdncOperationTask httpPost.addHeader("Authorization", defaulAuth); httpPost.addHeader("Content-type", "application/json"); String postBody = getPostbody(inputEntity); - logger.info("{} {} {}", MessageEnum.RA_SEND_REQUEST_SDNC, postBody, "SDNC"); + logger.info(LoggingAnchor.THREE, MessageEnum.RA_SEND_REQUEST_SDNC, postBody, "SDNC"); httpPost.setEntity(new StringEntity(postBody, ContentType.APPLICATION_XML)); httpPost(url, httpPost); logger.info("SdncServiceTopologyOperationTask.send2SdncDirectly end!"); diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilder.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilder.java index 21b14c35f9..2418479da6 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilder.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/client/builder/AbstractBuilder.java @@ -38,31 +38,23 @@ public abstract class AbstractBuilder<I, O> { public static final String RESOURCE_TYPE = "resourceType"; public enum RequestAction { - CREATE_NETWORK_INSTANCE(0, "CreateNetworkInstance"), ACTIVATE_NETWORK_INSTANCE(1, - "ActivateNetworkInstance"), CREATE_SERVICE_INSTANCE(2, - "CreateServiceInstance"), DELETE_SERVICE_INSTANCE(3, - "DeleteServiceInstance"), DELETE_NETWORK_INSTANCE(4, - "DeleteNetworkInstance"), CREATE_VNF_INSTANCE(5, - "CreateVnfInstance"), ACTIVATE_VNF_INSTANCE(6, - "ActivateVnfInstance"), DELETE_VNF_INSTANCE(7, - "DeleteVnfInstance"), CREATE_VF_MODULE_INSTANCE(8, - "CreateVfModuleInstance"), ACTIVATE_VF_MODULE_INSTANCE( - 9, - "ActivateVfModuleInstance"), DELETE_VF_MODULE_INSTANCE( - 10, - "DeleteVfModuleInstance"), CREATE_CONTRAIL_ROUTE_INSTANCE( - 11, - "CreateContrailRouteInstance"), DELETE_CONTRAIL_ROUTE_INSTANCE( - 12, - "DeleteContrailRouteInstance"), CREATE_SECURITY_ZONE_INSTANCE( - 13, - "CreateSecurityZoneInstance"), DELETE_SECURITY_ZONE_INSTANCE( - 14, - "DeleteSecurityZoneInstance"), ACTIVATE_DCI_NETWORK_INSTANCE( - 15, - "ActivateDCINetworkInstance"), DEACTIVATE_DCI_NETWORK_INSTANCE( - 16, - "DeActivateDCINetworkInstance"); + CREATE_NETWORK_INSTANCE(0, "CreateNetworkInstance"), + ACTIVATE_NETWORK_INSTANCE(1, "ActivateNetworkInstance"), + CREATE_SERVICE_INSTANCE(2, "CreateServiceInstance"), + DELETE_SERVICE_INSTANCE(3, "DeleteServiceInstance"), + DELETE_NETWORK_INSTANCE(4, "DeleteNetworkInstance"), + CREATE_VNF_INSTANCE(5, "CreateVnfInstance"), + ACTIVATE_VNF_INSTANCE(6, "ActivateVnfInstance"), + DELETE_VNF_INSTANCE(7, "DeleteVnfInstance"), + CREATE_VF_MODULE_INSTANCE(8, "CreateVfModuleInstance"), + ACTIVATE_VF_MODULE_INSTANCE(9, "ActivateVfModuleInstance"), + DELETE_VF_MODULE_INSTANCE(10, "DeleteVfModuleInstance"), + CREATE_CONTRAIL_ROUTE_INSTANCE(11, "CreateContrailRouteInstance"), + DELETE_CONTRAIL_ROUTE_INSTANCE(12, "DeleteContrailRouteInstance"), + CREATE_SECURITY_ZONE_INSTANCE(13, "CreateSecurityZoneInstance"), + DELETE_SECURITY_ZONE_INSTANCE(14, "DeleteSecurityZoneInstance"), + ACTIVATE_DCI_NETWORK_INSTANCE(15, "ActivateDCINetworkInstance"), + DEACTIVATE_DCI_NETWORK_INSTANCE(16, "DeActivateDCINetworkInstance"); String name; int value; @@ -82,9 +74,16 @@ public abstract class AbstractBuilder<I, O> { } public enum SvcAction { - RESERVE(0, "reserve"), ASSIGN(1, "assign"), ACTIVATE(2, "activate"), DELETE(3, "delete"), CHANGEASSIGN(4, - "changeassign"), CHANGEDELETE(5, "changedelete"), ROLLBACK(6, - "rollback"), DEACTIVATE(7, "deactivate"), UNASSIGN(8, "unassign"), CREATE(9, "create"); + RESERVE(0, "reserve"), + ASSIGN(1, "assign"), + ACTIVATE(2, "activate"), + DELETE(3, "delete"), + CHANGEASSIGN(4, "changeassign"), + CHANGEDELETE(5, "changedelete"), + ROLLBACK(6, "rollback"), + DEACTIVATE(7, "deactivate"), + UNASSIGN(8, "unassign"), + CREATE(9, "create"); String name; int value; diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleTest.groovy index faa6a0e395..5a6ad4291e 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleTest.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -47,6 +47,9 @@ import static org.mockito.Mockito.* class DoCreateVfModuleTest { def prefix = "DCVFM_" + @Rule + public WireMockRule wireMockRule = new WireMockRule(8090); + @Captor static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) @@ -54,7 +57,7 @@ class DoCreateVfModuleTest { void init() throws IOException { MockitoAnnotations.initMocks(this); } - + @Test void testQueryAAIVfModule() { ExecutionEntity mockExecution = setupMock() @@ -90,7 +93,7 @@ class DoCreateVfModuleTest { Mockito.verify(mockExecution).setVariable("DCVFM_queryAAIVfModuleForStatusResponseCode", 200) } - + @Test void testPreProcessVNFAdapterRequest() { @@ -122,7 +125,7 @@ class DoCreateVfModuleTest { map.put("vrr_image_name", "MDT17"); map.put("availability_zone_0", "nova"); map.put("vrr_flavor_name", "ns.c16r32d128.v1"); - when(mockExecution.getVariable("vnfParamsMap")).thenReturn(map) + when(mockExecution.getVariable(prefix + "vnfParamsMap")).thenReturn(map) when(mockExecution.getVariable("mso-request-id")).thenReturn("testRequestId-1503410089303") when(mockExecution.getVariable("mso.use.qualified.host")).thenReturn("true") when(mockExecution.getVariable("mso.workflow.message.endpoint")).thenReturn("http://localhost:28080/mso/WorkflowMesssage") @@ -155,7 +158,7 @@ class DoCreateVfModuleTest { Mockito.verify(mockExecution).setVariable(prefix + "queryCloudRegionReturnCode", "200") } - + @Test void testCreateNetworkPoliciesInAAI() { @@ -181,7 +184,7 @@ class DoCreateVfModuleTest { Mockito.verify(mockExecution).setVariable(prefix + "aaiQqueryNetworkPolicyByFqdnReturnCode", 200) } - + private static ExecutionEntity setupMock() { ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/DoCreateVfModule/createVnfARequest.xml b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/DoCreateVfModule/createVnfARequest.xml index f78d38f802..782936c382 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/DoCreateVfModule/createVnfARequest.xml +++ b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/DoCreateVfModule/createVnfARequest.xml @@ -1,5 +1,6 @@ <createVfModuleRequest> <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <cloudOwner>null</cloudOwner> <tenantId>fba1bd1e195a404cacb9ce17a9b2b421</tenantId> <vnfId>skask</vnfId> <vnfName>skask-test</vnfName> @@ -47,6 +48,10 @@ <value>null</value> </entry> <entry> + <key>user_directives</key> + <value>{ "attributes": [{"attribute_name":"vrr_image_name","attribute_value":"MDT17"},{"attribute_name":"availability_zone_0","attribute_value":"nova"},{"attribute_name":"vrr_flavor_name","attribute_value":"ns.c16r32d128.v1"}]}</value> + </entry> + <entry> <key>vf_module_name</key> <value>PCRF::module-0-2</value> </entry> @@ -71,6 +76,10 @@ <value></value> </entry> <entry> + <key>vrr_flavor_name</key> + <value>ns.c16r32d128.v1</value> + </entry> + <entry> <key>ADIG_SRIOV_2_net_name</key> <value>ADIG_SRIOV_2</value> </entry> @@ -103,6 +112,10 @@ <value>null</value> </entry> <entry> + <key>sdnc_directives</key> + <value>{ "attributes": [{"attribute_name":"vf_module_id","attribute_value":"cb510af0-5b21-4bc7-86d9-323cb396ce32"},{"attribute_name":"vrra_Internal-Network1_ips","attribute_value":"null"},{"attribute_name":"ADIG_SRIOV_2_subnet_id","attribute_value":""},{"attribute_name":"vrra_ADIGOam.OAM_v6_ips","attribute_value":"null"},{"attribute_name":"vnf_name","attribute_value":"skask-test"},{"attribute_name":"ADIGOam.OAM_v6_subnet_id","attribute_value":""},{"attribute_name":"workload_context","attribute_value":"null"},{"attribute_name":"vf_module_name","attribute_value":"PCRF::module-0-2"},{"attribute_name":"vnf_id","attribute_value":"skask"},{"attribute_name":"ADIG_SRIOV_2_v6_subnet_id","attribute_value":""},{"attribute_name":"vrra_ADIG_SRIOV_1_ips","attribute_value":"null"},{"attribute_name":"ADIG_SRIOV_1_v6_subnet_id","attribute_value":""},{"attribute_name":"ADIG_SRIOV_1_subnet_id","attribute_value":""},{"attribute_name":"ADIG_SRIOV_2_net_name","attribute_value":"ADIG_SRIOV_2"},{"attribute_name":"ADIGOam.OAM_subnet_id","attribute_value":""},{"attribute_name":"ADIGOam.OAM_net_id","attribute_value":"491c7cef-a3f4-4990-883e-b0af397466d0"},{"attribute_name":"environment_context","attribute_value":"null"},{"attribute_name":"ADIG_SRIOV_1_net_fqdn","attribute_value":""},{"attribute_name":"ADIGOam.OAM_net_name","attribute_value":"ADIGOAM.OAM"},{"attribute_name":"vrra_name_0","attribute_value":"frkdevRvrra24"},{"attribute_name":"vrra_ADIG_SRIOV_2_ips","attribute_value":"null"},{"attribute_name":"ADIG_SRIOV_2_net_fqdn","attribute_value":""},{"attribute_name":"vrra_Internal-Network2_ips","attribute_value":"null"},{"attribute_name":"ADIG_SRIOV_1_net_name","attribute_value":"ADIG_SRIOV_1"},{"attribute_name":"vrra_ADIG_SRIOV_1_v6_ips","attribute_value":"null"},{"attribute_name":"vrra_ADIGOam.OAM_ips","attribute_value":"null"},{"attribute_name":"vrra_Internal-Network1_v6_ips","attribute_value":"null"},{"attribute_name":"ADIGOam.OAM_net_fqdn","attribute_value":""},{"attribute_name":"vrra_names","attribute_value":"frkdevRvrra24"},{"attribute_name":"ADIG_SRIOV_1_net_id","attribute_value":"491c7cef-a3f4-4990-883e-b0af397466d0"},{"attribute_name":"vrra_Internal-Network2_v6_ips","attribute_value":"null"},{"attribute_name":"vrra_ADIG_SRIOV_2_v6_ips","attribute_value":"null"},{"attribute_name":"ADIG_SRIOV_2_net_id","attribute_value":"491c7cef-a3f4-4990-883e-b0af397466d0"},{"attribute_name":"vf_module_index","attribute_value":"index"},{"attribute_name":"availability_zone_0","attribute_value":"frkde-esx-az01"}]}</value> + </entry> + <entry> <key>ADIG_SRIOV_2_net_fqdn</key> <value></value> </entry> @@ -127,6 +140,10 @@ <value>null</value> </entry> <entry> + <key>vrr_image_name</key> + <value>MDT17</value> + </entry> + <entry> <key>ADIGOam.OAM_net_fqdn</key> <value></value> </entry> @@ -156,9 +173,10 @@ </entry> <entry> <key>availability_zone_0</key> - <value>frkde-esx-az01</value> + <value>nova</value> </entry> + </vfModuleParams> <msoRequest> <requestId>testRequestId</requestId> @@ -166,4 +184,4 @@ </msoRequest> <messageId>testRequestId-1503410089303-1513204371234</messageId> <notificationUrl>http://localhost:28080/mso/WorkflowMesssage/VNFAResponse/testRequestId-1503410089303-1513204371234</notificationUrl> -</createVfModuleRequest>
\ No newline at end of file +</createVfModuleRequest> diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/Macro/CreateNetworkCollection.json b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/Macro/CreateNetworkCollection.json index 7b369ab97e..ce0e5aa643 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/Macro/CreateNetworkCollection.json +++ b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/Macro/CreateNetworkCollection.json @@ -4,7 +4,7 @@ "modelType": "service", "modelInvariantId": "5d48acb5-097d-4982-aeb2-f4a3bd87d31b", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersion": "10" }, "cloudConfiguration": { @@ -34,7 +34,7 @@ { "service": { "modelInfo": { - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a" }, "instanceParams": [], diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/Macro/ServiceMacroAssign.json b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/Macro/ServiceMacroAssign.json index 51caddd48a..b86a2a28f6 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/Macro/ServiceMacroAssign.json +++ b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/Macro/ServiceMacroAssign.json @@ -4,7 +4,7 @@ "modelType": "service", "modelInvariantId": "5d48acb5-097d-4982-aeb2-f4a3bd87d31b", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersion": "10.0" }, "owningEntity": { @@ -31,7 +31,7 @@ "service": { "modelInfo": { "modelType": "service", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a" }, "instanceParams": [], diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/ConfigurePnfResource.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/ConfigurePnfResource.bpmn index f489a27052..9a1a7ed628 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/ConfigurePnfResource.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/ConfigurePnfResource.bpmn @@ -30,7 +30,7 @@ <bpmn:incoming>SequenceFlow_17llfxw</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0p0aqtx</bpmn:outgoing> </bpmn:callActivity> - <bpmn:exclusiveGateway id="ExclusiveGateway_0vtv1wi"> + <bpmn:exclusiveGateway id="ExclusiveGateway_0vtv1wi" default="SequenceFlow_1w4p9f7"> <bpmn:incoming>SequenceFlow_0p0aqtx</bpmn:incoming> <bpmn:outgoing>SequenceFlow_1owbpsy</bpmn:outgoing> <bpmn:outgoing>SequenceFlow_1w4p9f7</bpmn:outgoing> @@ -49,7 +49,7 @@ <bpmn:incoming>SequenceFlow_0jfgn7n</bpmn:incoming> <bpmn:outgoing>SequenceFlow_08voj55</bpmn:outgoing> </bpmn:callActivity> - <bpmn:exclusiveGateway id="ExclusiveGateway_01jwwmc"> + <bpmn:exclusiveGateway id="ExclusiveGateway_01jwwmc" default="SequenceFlow_0d24h26"> <bpmn:incoming>SequenceFlow_08voj55</bpmn:incoming> <bpmn:outgoing>SequenceFlow_1n080up</bpmn:outgoing> <bpmn:outgoing>SequenceFlow_0d24h26</bpmn:outgoing> diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/CreateCustomE2EServiceInstance.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/CreateCustomE2EServiceInstance.bpmn index 04ff48d4ed..c1b5ef82de 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/CreateCustomE2EServiceInstance.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/CreateCustomE2EServiceInstance.bpmn @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="1.16.2"> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="2.2.4"> <bpmn:process id="CreateCustomE2EServiceInstance" name="CreateCustomE2EServiceInstance" isExecutable="true"> <bpmn:startEvent id="StartEvent_00qj6ro" name="Create SI Start Flow"> <bpmn:outgoing>SequenceFlow_0s2spoq</bpmn:outgoing> @@ -44,6 +44,8 @@ ex.processJavaException(execution)</bpmn:script> <camunda:in source="uuiRequest" target="uuiRequest" /> <camunda:in source="requestAction" target="operationType" /> <camunda:in source="operationId" target="operationId" /> + <camunda:out source="serviceDecomposition" target="serviceDecomposition" /> + <camunda:out source="serviceInstanceData" target="serviceInstanceData" /> </bpmn:extensionElements> <bpmn:incoming>SequenceFlow_19eilro</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0klbpxx</bpmn:outgoing> @@ -74,7 +76,7 @@ csi.prepareCompletionRequest(execution)</bpmn:script> <camunda:out source="CompleteMsoProcessResponse" target="CompleteMsoProcessResponse" /> <camunda:out source="CMSO_ErrorResponse" target="CMSO_ErrorResponse" /> </bpmn:extensionElements> - <bpmn:incoming>SequenceFlow_0je30si</bpmn:incoming> + <bpmn:incoming>SequenceFlow_0kaz8ac</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0yayvrf</bpmn:outgoing> </bpmn:callActivity> <bpmn:subProcess id="SubProcess_0vaws86" name="Sub-process for FalloutHandler and Rollback" triggeredByEvent="true"> @@ -140,7 +142,7 @@ csi.sendSyncResponse(execution)</bpmn:script> <bpmn:sequenceFlow id="SequenceFlow_14zu6wr" name="yes" sourceRef="ExclusiveGateway_0aqn64l" targetRef="ScriptTask_0ttvn8r"> <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{execution.getVariable("WorkflowException") == null}</bpmn:conditionExpression> </bpmn:sequenceFlow> - <bpmn:sequenceFlow id="SequenceFlow_0je30si" sourceRef="ScriptTask_0ttvn8r" targetRef="CallActivity_02fyxz0" /> + <bpmn:sequenceFlow id="SequenceFlow_0je30si" sourceRef="ScriptTask_0ttvn8r" targetRef="Task_1bgdtc9" /> <bpmn:sequenceFlow id="SequenceFlow_1fueo69" name="no" sourceRef="ExclusiveGateway_0aqn64l" targetRef="EndEvent_07uk5iy"> <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{execution.getVariable("WorkflowException") != null}</bpmn:conditionExpression> </bpmn:sequenceFlow> @@ -175,6 +177,14 @@ csi.prepareInitServiceOperationStatus(execution)</bpmn:script> <bpmn:outgoing>SequenceFlow_081z8l2</bpmn:outgoing> </bpmn:serviceTask> <bpmn:sequenceFlow id="SequenceFlow_081z8l2" sourceRef="Task_19mxcw3" targetRef="ScriptTask_0xupxj9" /> + <bpmn:sequenceFlow id="SequenceFlow_0kaz8ac" sourceRef="Task_1bgdtc9" targetRef="CallActivity_02fyxz0" /> + <bpmn:scriptTask id="Task_1bgdtc9" name="Update AAI Status" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_0je30si</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0kaz8ac</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def csi = new CreateCustomE2EServiceInstance() +csi.updateAAIOrchStatus(execution)</bpmn:script> + </bpmn:scriptTask> </bpmn:process> <bpmn:error id="Error_0nbdy47" name="MSOWorkflowException" errorCode="MSOWorkflowException" /> <bpmndi:BPMNDiagram id="BPMNDiagram_1"> @@ -192,9 +202,9 @@ csi.prepareInitServiceOperationStatus(execution)</bpmn:script> <dc:Bounds x="751" y="158" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="EndEvent_0bpd6c0_di" bpmnElement="EndEvent_0bpd6c0"> - <dc:Bounds x="1258" y="286" width="36" height="36" /> + <dc:Bounds x="1387" y="286" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1268" y="322" width="22" height="12" /> + <dc:Bounds x="1398" y="322" width="20" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ScriptTask_1s09c7d_di" bpmnElement="ScriptTask_1s09c7d"> @@ -204,7 +214,7 @@ csi.prepareInitServiceOperationStatus(execution)</bpmn:script> <dc:Bounds x="1038" y="158" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="CallActivity_02fyxz0_di" bpmnElement="CallActivity_02fyxz0"> - <dc:Bounds x="1226" y="158" width="100" height="80" /> + <dc:Bounds x="1355" y="158" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="SubProcess_0vaws86_di" bpmnElement="SubProcess_0vaws86" isExpanded="true"> <dc:Bounds x="348" y="370" width="679" height="194" /> @@ -246,8 +256,8 @@ csi.prepareInitServiceOperationStatus(execution)</bpmn:script> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0yayvrf_di" bpmnElement="SequenceFlow_0yayvrf"> - <di:waypoint x="1276" y="238" /> - <di:waypoint x="1276" y="286" /> + <di:waypoint x="1405" y="238" /> + <di:waypoint x="1405" y="286" /> <bpmndi:BPMNLabel> <dc:Bounds x="1246" y="262" width="0" height="12" /> </bpmndi:BPMNLabel> @@ -270,7 +280,7 @@ csi.prepareInitServiceOperationStatus(execution)</bpmn:script> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0je30si_di" bpmnElement="SequenceFlow_0je30si"> <di:waypoint x="1138" y="198" /> - <di:waypoint x="1226" y="198" /> + <di:waypoint x="1189" y="198" /> <bpmndi:BPMNLabel> <dc:Bounds x="1137" y="183" width="0" height="12" /> </bpmndi:BPMNLabel> @@ -386,6 +396,13 @@ csi.prepareInitServiceOperationStatus(execution)</bpmn:script> <dc:Bounds x="533" y="177" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0kaz8ac_di" bpmnElement="SequenceFlow_0kaz8ac"> + <di:waypoint x="1289" y="198" /> + <di:waypoint x="1355" y="198" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_0novdpr_di" bpmnElement="Task_1bgdtc9"> + <dc:Bounds x="1189" y="158" width="100" height="80" /> + </bpmndi:BPMNShape> </bpmndi:BPMNPlane> </bpmndi:BPMNDiagram> </bpmn:definitions> diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/HandlePNF.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/HandlePNF.bpmn index c81b289737..43ebf9810e 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/HandlePNF.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/HandlePNF.bpmn @@ -1,57 +1,76 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="1.16.2"> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="2.2.4"> <bpmn:process id="HandlePNF" name="HandlePNF" isExecutable="true"> <bpmn:startEvent id="createNS_StartEvent_pnf_disc" name="start PNF handling"> <bpmn:outgoing>SequenceFlow_1c92ks3_activate</bpmn:outgoing> </bpmn:startEvent> <bpmn:scriptTask id="Task_13sx2bp_activate" name="Pre Process Request" scriptFormat="groovy"> <bpmn:incoming>SequenceFlow_1c92ks3_activate</bpmn:incoming> - <bpmn:outgoing>SequenceFlow_17xr584</bpmn:outgoing> <bpmn:outgoing>SequenceFlow_12q67gd</bpmn:outgoing> <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* def handlePNF = new HandlePNF() handlePNF.preProcessRequest(execution)</bpmn:script> </bpmn:scriptTask> <bpmn:sequenceFlow id="SequenceFlow_1c92ks3_activate" sourceRef="createNS_StartEvent_pnf_disc" targetRef="Task_13sx2bp_activate" /> - <bpmn:sequenceFlow id="SequenceFlow_17xr584" sourceRef="Task_13sx2bp_activate" targetRef="Task_0kv28gm" /> <bpmn:sequenceFlow id="SequenceFlow_0pujwl4" sourceRef="Task_0657l04" targetRef="PostProcessPNFDiscovery" /> <bpmn:endEvent id="EndEvent_0pigsdfk3" name="end PNF hadler"> <bpmn:incoming>SequenceFlow_02fi1yn</bpmn:incoming> </bpmn:endEvent> - <bpmn:sequenceFlow id="SequenceFlow_1la8oih" sourceRef="PostProcessPNFDiscovery" targetRef="Task_1r8h7of" /> + <bpmn:sequenceFlow id="SequenceFlow_1la8oih" sourceRef="PostProcessPNFDiscovery" targetRef="Task_1kxmpj3" /> <bpmn:callActivity id="Task_0657l04" name="invoke pnf handler" calledElement="CreateAndActivatePnfResource"> <bpmn:extensionElements> - <camunda:in source="correlationId" target="correlationId" /> + <camunda:in source="pnfCorrelationId" target="pnfCorrelationId" /> <camunda:in source="pnfUuid" target="pnfUuid" /> + <camunda:in source="serviceInstanceId" target="serviceInstanceId" /> + <camunda:in businessKey="#{execution.processBusinessKey}" /> </bpmn:extensionElements> <bpmn:incoming>SequenceFlow_1apj1fn</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0pujwl4</bpmn:outgoing> </bpmn:callActivity> - <bpmn:scriptTask id="PostProcessPNFDiscovery" name="Post Process Request" scriptFormat="groovy"> - <bpmn:incoming>SequenceFlow_0pujwl4</bpmn:incoming> - <bpmn:outgoing>SequenceFlow_1la8oih</bpmn:outgoing> - <bpmn:outgoing>SequenceFlow_1ezf4gu</bpmn:outgoing> - <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* -def handlePNF = new HandlePNF() -handlePNF.postProcessRequest(execution)</bpmn:script> - </bpmn:scriptTask> <bpmn:sequenceFlow id="SequenceFlow_12q67gd" sourceRef="Task_13sx2bp_activate" targetRef="Task_0kv28gm" /> <bpmn:sequenceFlow id="SequenceFlow_1apj1fn" sourceRef="Task_0kv28gm" targetRef="Task_0657l04" /> <bpmn:serviceTask id="Task_0kv28gm" name="Generate PNF uuid" camunda:delegateExpression="${GeneratePnfUuidDelegate}"> <bpmn:incoming>SequenceFlow_12q67gd</bpmn:incoming> - <bpmn:incoming>SequenceFlow_17xr584</bpmn:incoming> <bpmn:outgoing>SequenceFlow_1apj1fn</bpmn:outgoing> </bpmn:serviceTask> - <bpmn:sequenceFlow id="SequenceFlow_1ezf4gu" sourceRef="PostProcessPNFDiscovery" targetRef="Task_1r8h7of" /> <bpmn:sequenceFlow id="SequenceFlow_02fi1yn" sourceRef="Task_1r8h7of" targetRef="EndEvent_0pigsdfk3" /> <bpmn:scriptTask id="Task_1r8h7of" name="Send Sync Response" scriptFormat="groovy"> - <bpmn:incoming>SequenceFlow_1ezf4gu</bpmn:incoming> - <bpmn:incoming>SequenceFlow_1la8oih</bpmn:incoming> + <bpmn:incoming>SequenceFlow_1ud44f8</bpmn:incoming> <bpmn:outgoing>SequenceFlow_02fi1yn</bpmn:outgoing> <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* def handlePNF = new HandlePNF() handlePNF.sendSyncResponse(execution)</bpmn:script> </bpmn:scriptTask> + <bpmn:scriptTask id="PostProcessPNFDiscovery" name="Post Process Request" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_0pujwl4</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1la8oih</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def handlePNF = new HandlePNF() +handlePNF.postProcessRequest(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:sequenceFlow id="SequenceFlow_1ud44f8" sourceRef="Task_1kxmpj3" targetRef="Task_1r8h7of" /> + <bpmn:serviceTask id="Task_1kxmpj3" name="update progress update"> + <bpmn:extensionElements> + <camunda:connector> + <camunda:inputOutput> + <camunda:inputParameter name="url">${CVFMI_dbAdapterEndpoint}</camunda:inputParameter> + <camunda:inputParameter name="headers"> + <camunda:map> + <camunda:entry key="content-type">application/soap+xml</camunda:entry> + <camunda:entry key="Authorization">Basic YnBlbDpwYXNzd29yZDEk</camunda:entry> + </camunda:map> + </camunda:inputParameter> + <camunda:inputParameter name="payload">${CVFMI_updateResOperStatusRequest}</camunda:inputParameter> + <camunda:inputParameter name="method">POST</camunda:inputParameter> + <camunda:outputParameter name="CVFMI_dbResponseCode">${statusCode}</camunda:outputParameter> + <camunda:outputParameter name="CVFMI_dbResponse">${response}</camunda:outputParameter> + </camunda:inputOutput> + <camunda:connectorId>http-connector</camunda:connectorId> + </camunda:connector> + </bpmn:extensionElements> + <bpmn:incoming>SequenceFlow_1la8oih</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1ud44f8</bpmn:outgoing> + </bpmn:serviceTask> </bpmn:process> <bpmndi:BPMNDiagram id="BPMNDiagram_1"> <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="HandlePNF"> @@ -68,51 +87,50 @@ handlePNF.sendSyncResponse(execution)</bpmn:script> <di:waypoint x="-428" y="324" /> <di:waypoint x="-341" y="324" /> </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="SequenceFlow_17xr584_di" bpmnElement="SequenceFlow_17xr584"> - <di:waypoint x="-241" y="324" /> - <di:waypoint x="-180" y="324" /> - </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0pujwl4_di" bpmnElement="SequenceFlow_0pujwl4"> <di:waypoint x="81" y="324" /> <di:waypoint x="156" y="324" /> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="EndEvent_0pigdk3_di" bpmnElement="EndEvent_0pigsdfk3"> - <dc:Bounds x="543" y="306" width="36" height="36" /> + <dc:Bounds x="626" y="306" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="524" y="349" width="78" height="14" /> + <dc:Bounds x="607" y="349" width="78" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1la8oih_di" bpmnElement="SequenceFlow_1la8oih"> <di:waypoint x="256" y="324" /> - <di:waypoint x="353" y="324" /> + <di:waypoint x="303" y="324" /> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="CallActivity_1sxp6qj_di" bpmnElement="Task_0657l04"> <dc:Bounds x="-19" y="284" width="100" height="80" /> </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="ScriptTask_0qqb00i_di" bpmnElement="PostProcessPNFDiscovery"> - <dc:Bounds x="156" y="284" width="100" height="80" /> - </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_12q67gd_di" bpmnElement="SequenceFlow_12q67gd"> <di:waypoint x="-241" y="324" /> - <di:waypoint x="-180" y="324" /> + <di:waypoint x="-176" y="324" /> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1apj1fn_di" bpmnElement="SequenceFlow_1apj1fn"> - <di:waypoint x="-80" y="324" /> + <di:waypoint x="-76" y="324" /> <di:waypoint x="-19" y="324" /> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_1y3h50n_di" bpmnElement="Task_0kv28gm"> - <dc:Bounds x="-180" y="284" width="100" height="80" /> + <dc:Bounds x="-176" y="284" width="100" height="80" /> </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="SequenceFlow_1ezf4gu_di" bpmnElement="SequenceFlow_1ezf4gu"> - <di:waypoint x="256" y="324" /> - <di:waypoint x="353" y="324" /> - </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_02fi1yn_di" bpmnElement="SequenceFlow_02fi1yn"> - <di:waypoint x="453" y="324" /> - <di:waypoint x="543" y="324" /> + <di:waypoint x="536" y="324" /> + <di:waypoint x="626" y="324" /> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ScriptTask_1yqlrg7_di" bpmnElement="Task_1r8h7of"> - <dc:Bounds x="353" y="284" width="100" height="80" /> + <dc:Bounds x="436" y="284" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ScriptTask_0qqb00i_di" bpmnElement="PostProcessPNFDiscovery"> + <dc:Bounds x="156" y="284" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1ud44f8_di" bpmnElement="SequenceFlow_1ud44f8"> + <di:waypoint x="403" y="324" /> + <di:waypoint x="436" y="324" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ServiceTask_0fkkgnl_di" bpmnElement="Task_1kxmpj3"> + <dc:Bounds x="303" y="284" width="100" height="80" /> </bpmndi:BPMNShape> </bpmndi:BPMNPlane> </bpmndi:BPMNDiagram> diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateE2EServiceInstance.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateE2EServiceInstance.bpmn index eccb9486dd..76dd6facd6 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateE2EServiceInstance.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateE2EServiceInstance.bpmn @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="_MagIIMOUEeW8asg-vCEgWQ" targetNamespace="http://camunda.org/schema/1.0/bpmn" exporter="Camunda Modeler" exporterVersion="1.10.0" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"> +<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="_MagIIMOUEeW8asg-vCEgWQ" targetNamespace="http://camunda.org/schema/1.0/bpmn" exporter="Camunda Modeler" exporterVersion="2.2.4" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"> <bpmn2:process id="DoCreateE2EServiceInstanceV3" name="DoCreateE2EServiceInstanceV3" isExecutable="true"> <bpmn2:startEvent id="createSI_startEvent" name="Start Flow"> <bpmn2:outgoing>SequenceFlow_1qiiycn</bpmn2:outgoing> @@ -7,10 +7,10 @@ <bpmn2:scriptTask id="preProcessRequest_ScriptTask" name="PreProcess Incoming Request" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_1qiiycn</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_0w9t6tc</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def dcsi = new DoCreateE2EServiceInstance() dcsi.preProcessRequest(execution) -]]></bpmn2:script> +</bpmn2:script> </bpmn2:scriptTask> <bpmn2:subProcess id="SubProcess_06d8lk8" name="Sub-process for Application Errors" triggeredByEvent="true"> <bpmn2:startEvent id="StartEvent_0yljq9y"> @@ -36,28 +36,28 @@ dcsi.preProcessRequest(execution) <bpmn2:scriptTask id="ScriptTask_0ocetux" name="Pre Process Rollback" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_0tgrn11</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_1lqktwf</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def dcsi = new DoCreateE2EServiceInstance() dcsi.preProcessRollback(execution) -]]></bpmn2:script> +</bpmn2:script> </bpmn2:scriptTask> <bpmn2:sequenceFlow id="SequenceFlow_1lqktwf" sourceRef="ScriptTask_0ocetux" targetRef="CallActivity_1srx6p6" /> <bpmn2:scriptTask id="ScriptTask_1p0vyip" name="Post Process Rollback" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_0eumzpf</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_1xzgv5k</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def dcsi = new DoCreateE2EServiceInstance() dcsi.postProcessRollback(execution) -]]></bpmn2:script> +</bpmn2:script> </bpmn2:scriptTask> <bpmn2:sequenceFlow id="SequenceFlow_1xzgv5k" sourceRef="ScriptTask_1p0vyip" targetRef="EndEvent_117lkk3" /> </bpmn2:subProcess> <bpmn2:scriptTask id="ScriptTask_0q37vn9" name=" AAI Create (srv instance) " scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_012h7yx</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_1tkgqu3</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def ddsi = new DoCreateE2EServiceInstance() -ddsi.createServiceInstance(execution)]]></bpmn2:script> +ddsi.createServiceInstance(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:intermediateThrowEvent id="IntermediateThrowEvent_0bq4fxs" name="Go to Decompose_Service"> <bpmn2:incoming>SequenceFlow_0w9t6tc</bpmn2:incoming> @@ -66,9 +66,9 @@ ddsi.createServiceInstance(execution)]]></bpmn2:script> <bpmn2:scriptTask id="ScriptTask_1o01d7d" name="PostProcess Decompose Service " scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_0xjwb45</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_012h7yx</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def dcsi= new DoCreateE2EServiceInstance() -dcsi.processDecomposition(execution)]]></bpmn2:script> +dcsi.processDecomposition(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:callActivity id="CallActivity_0biblpc" name="Call Decompose Service" calledElement="DecomposeService"> <bpmn2:extensionElements> @@ -85,9 +85,9 @@ dcsi.processDecomposition(execution)]]></bpmn2:script> <bpmn2:scriptTask id="ScriptTask_1cllqk3" name="Prepare Decompose Service " scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_166w91p</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_0qxzgvq</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def dcsi= new DoCreateE2EServiceInstance() -dcsi.prepareDecomposeService(execution)]]></bpmn2:script> +dcsi.prepareDecomposeService(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:intermediateCatchEvent id="IntermediateCatchEvent_0tv85pg" name="Decompose_Service"> <bpmn2:outgoing>SequenceFlow_166w91p</bpmn2:outgoing> @@ -111,9 +111,9 @@ dcsi.prepareDecomposeService(execution)]]></bpmn2:script> <bpmn2:scriptTask id="ScriptTask_1rzf8a1" name="Prepare Resource Oper Status" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_1y9rkfr</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_0n7nbx3</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def ddsi = new DoCreateE2EServiceInstance() -ddsi.preInitResourcesOperStatus(execution)]]></bpmn2:script> +ddsi.preInitResourcesOperStatus(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:serviceTask id="ServiceTask_1asgesv" name="Init Resource Oper Status"> <bpmn2:extensionElements> @@ -154,6 +154,7 @@ ddsi.preInitResourcesOperStatus(execution)]]></bpmn2:script> <camunda:in source="serviceDecomposition" target="serviceDecomposition" /> <camunda:in source="uuiRequest" target="uuiRequest" /> <camunda:in source="msoRequestId" target="msoRequestId" /> + <camunda:out source="serviceDecomposition" target="serviceDecomposition" /> </bpmn2:extensionElements> <bpmn2:incoming>SequenceFlow_0b1dsaj</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_0sphcy5</bpmn2:outgoing> @@ -161,16 +162,16 @@ ddsi.preInitResourcesOperStatus(execution)]]></bpmn2:script> <bpmn2:scriptTask id="ScriptTask_0ns08tn" name="PreProcess for Add Resources" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_022onug</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_0b1dsaj</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def csi = new DoCreateE2EServiceInstance() -csi.preProcessForAddResource(execution)]]></bpmn2:script> +csi.preProcessForAddResource(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:scriptTask id="ScriptTask_19t13rd" name="PostProcess for Add Resource" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_0sphcy5</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_18gnns6</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def csi = new DoCreateE2EServiceInstance() -csi.postProcessForAddResource(execution)]]></bpmn2:script> +csi.postProcessForAddResource(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:endEvent id="EndEvent_1x4kvfh"> <bpmn2:incoming>SequenceFlow_18gnns6</bpmn2:incoming> @@ -178,16 +179,16 @@ csi.postProcessForAddResource(execution)]]></bpmn2:script> <bpmn2:scriptTask id="ScriptTask_0jxdler" name="Process Site Location" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_0yuzaen</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_1y9rkfr</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def dcsi= new DoCreateE2EServiceInstance() -dcsi.doProcessSiteLocation(execution)]]></bpmn2:script> +dcsi.doProcessSiteLocation(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:scriptTask id="ScriptTask_0ts3c3b" name="Process Link TP Resource Allocation" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_0ckto7v</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_022onug</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def dcsi= new DoCreateE2EServiceInstance() -dcsi.doTPResourcesAllocation(execution)]]></bpmn2:script> +dcsi.doTPResourcesAllocation(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:sequenceFlow id="SequenceFlow_1y9rkfr" sourceRef="ScriptTask_0jxdler" targetRef="ScriptTask_1rzf8a1" /> <bpmn2:sequenceFlow id="SequenceFlow_0n7nbx3" sourceRef="ScriptTask_1rzf8a1" targetRef="ServiceTask_1asgesv" /> @@ -230,15 +231,15 @@ dcsi.doTPResourcesAllocation(execution)]]></bpmn2:script> <dc:Bounds x="409" y="920" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0eumzpf_di" bpmnElement="SequenceFlow_0eumzpf"> - <di:waypoint xsi:type="dc:Point" x="509" y="960" /> - <di:waypoint xsi:type="dc:Point" x="577" y="960" /> + <di:waypoint x="509" y="960" /> + <di:waypoint x="577" y="960" /> <bpmndi:BPMNLabel> <dc:Bounds x="498" y="945" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0tgrn11_di" bpmnElement="SequenceFlow_0tgrn11"> - <di:waypoint xsi:type="dc:Point" x="147" y="960" /> - <di:waypoint xsi:type="dc:Point" x="246" y="960" /> + <di:waypoint x="147" y="960" /> + <di:waypoint x="246" y="960" /> <bpmndi:BPMNLabel> <dc:Bounds x="152" y="945" width="90" height="0" /> </bpmndi:BPMNLabel> @@ -250,8 +251,8 @@ dcsi.doTPResourcesAllocation(execution)]]></bpmn2:script> <dc:Bounds x="246" y="920" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1lqktwf_di" bpmnElement="SequenceFlow_1lqktwf"> - <di:waypoint xsi:type="dc:Point" x="346" y="960" /> - <di:waypoint xsi:type="dc:Point" x="409" y="960" /> + <di:waypoint x="346" y="960" /> + <di:waypoint x="409" y="960" /> <bpmndi:BPMNLabel> <dc:Bounds x="333" y="945" width="90" height="0" /> </bpmndi:BPMNLabel> @@ -260,10 +261,10 @@ dcsi.doTPResourcesAllocation(execution)]]></bpmn2:script> <dc:Bounds x="577" y="920" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1xzgv5k_di" bpmnElement="SequenceFlow_1xzgv5k"> - <di:waypoint xsi:type="dc:Point" x="677" y="960" /> - <di:waypoint xsi:type="dc:Point" x="709" y="960" /> - <di:waypoint xsi:type="dc:Point" x="709" y="960" /> - <di:waypoint xsi:type="dc:Point" x="744" y="960" /> + <di:waypoint x="677" y="960" /> + <di:waypoint x="709" y="960" /> + <di:waypoint x="709" y="960" /> + <di:waypoint x="744" y="960" /> <bpmndi:BPMNLabel> <dc:Bounds x="679" y="960" width="90" height="0" /> </bpmndi:BPMNLabel> @@ -290,29 +291,29 @@ dcsi.doTPResourcesAllocation(execution)]]></bpmn2:script> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0xjwb45_di" bpmnElement="SequenceFlow_0xjwb45"> - <di:waypoint xsi:type="dc:Point" x="569" y="146" /> - <di:waypoint xsi:type="dc:Point" x="704" y="146" /> + <di:waypoint x="569" y="146" /> + <di:waypoint x="704" y="146" /> <bpmndi:BPMNLabel> <dc:Bounds x="592" y="125" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0qxzgvq_di" bpmnElement="SequenceFlow_0qxzgvq"> - <di:waypoint xsi:type="dc:Point" x="287" y="146" /> - <di:waypoint xsi:type="dc:Point" x="469" y="146" /> + <di:waypoint x="287" y="146" /> + <di:waypoint x="469" y="146" /> <bpmndi:BPMNLabel> <dc:Bounds x="333" y="125" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1qiiycn_di" bpmnElement="SequenceFlow_1qiiycn"> - <di:waypoint xsi:type="dc:Point" x="45" y="-4" /> - <di:waypoint xsi:type="dc:Point" x="117" y="-4" /> + <di:waypoint x="45" y="-4" /> + <di:waypoint x="117" y="-4" /> <bpmndi:BPMNLabel> <dc:Bounds x="36" y="-25" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_166w91p_di" bpmnElement="SequenceFlow_166w91p"> - <di:waypoint xsi:type="dc:Point" x="53" y="146" /> - <di:waypoint xsi:type="dc:Point" x="187" y="146" /> + <di:waypoint x="53" y="146" /> + <di:waypoint x="187" y="146" /> <bpmndi:BPMNLabel> <dc:Bounds x="75" y="125" width="90" height="12" /> </bpmndi:BPMNLabel> @@ -324,19 +325,19 @@ dcsi.doTPResourcesAllocation(execution)]]></bpmn2:script> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1tkgqu3_di" bpmnElement="SequenceFlow_1tkgqu3"> - <di:waypoint xsi:type="dc:Point" x="1112" y="146" /> - <di:waypoint xsi:type="dc:Point" x="1222" y="146" /> - <di:waypoint xsi:type="dc:Point" x="1222" y="146" /> - <di:waypoint xsi:type="dc:Point" x="1306" y="146" /> + <di:waypoint x="1112" y="146" /> + <di:waypoint x="1222" y="146" /> + <di:waypoint x="1222" y="146" /> + <di:waypoint x="1306" y="146" /> <bpmndi:BPMNLabel> <dc:Bounds x="1192" y="140" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0w9t6tc_di" bpmnElement="SequenceFlow_0w9t6tc"> - <di:waypoint xsi:type="dc:Point" x="217" y="-4" /> - <di:waypoint xsi:type="dc:Point" x="762" y="-4" /> - <di:waypoint xsi:type="dc:Point" x="762" y="-4" /> - <di:waypoint xsi:type="dc:Point" x="1306" y="-4" /> + <di:waypoint x="217" y="-4" /> + <di:waypoint x="762" y="-4" /> + <di:waypoint x="762" y="-4" /> + <di:waypoint x="1306" y="-4" /> <bpmndi:BPMNLabel> <dc:Bounds x="732" y="-10" width="90" height="12" /> </bpmndi:BPMNLabel> @@ -348,10 +349,10 @@ dcsi.doTPResourcesAllocation(execution)]]></bpmn2:script> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_012h7yx_di" bpmnElement="SequenceFlow_012h7yx"> - <di:waypoint xsi:type="dc:Point" x="804" y="146" /> - <di:waypoint xsi:type="dc:Point" x="917" y="146" /> - <di:waypoint xsi:type="dc:Point" x="917" y="146" /> - <di:waypoint xsi:type="dc:Point" x="1012" y="146" /> + <di:waypoint x="804" y="146" /> + <di:waypoint x="917" y="146" /> + <di:waypoint x="917" y="146" /> + <di:waypoint x="1012" y="146" /> <bpmndi:BPMNLabel> <dc:Bounds x="887" y="139" width="90" height="14" /> </bpmndi:BPMNLabel> @@ -384,61 +385,61 @@ dcsi.doTPResourcesAllocation(execution)]]></bpmn2:script> <dc:Bounds x="599" y="260" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1y9rkfr_di" bpmnElement="SequenceFlow_1y9rkfr"> - <di:waypoint xsi:type="dc:Point" x="188" y="300" /> - <di:waypoint xsi:type="dc:Point" x="262" y="300" /> + <di:waypoint x="188" y="300" /> + <di:waypoint x="262" y="300" /> <bpmndi:BPMNLabel> <dc:Bounds x="180" y="279" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0n7nbx3_di" bpmnElement="SequenceFlow_0n7nbx3"> - <di:waypoint xsi:type="dc:Point" x="362" y="300" /> - <di:waypoint xsi:type="dc:Point" x="433" y="300" /> + <di:waypoint x="362" y="300" /> + <di:waypoint x="433" y="300" /> <bpmndi:BPMNLabel> <dc:Bounds x="353.5" y="279" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0ckto7v_di" bpmnElement="SequenceFlow_0ckto7v"> - <di:waypoint xsi:type="dc:Point" x="533" y="300" /> - <di:waypoint xsi:type="dc:Point" x="599" y="300" /> + <di:waypoint x="533" y="300" /> + <di:waypoint x="599" y="300" /> <bpmndi:BPMNLabel> <dc:Bounds x="521" y="279" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0b1dsaj_di" bpmnElement="SequenceFlow_0b1dsaj"> - <di:waypoint xsi:type="dc:Point" x="885" y="300" /> - <di:waypoint xsi:type="dc:Point" x="957" y="300" /> + <di:waypoint x="885" y="300" /> + <di:waypoint x="957" y="300" /> <bpmndi:BPMNLabel> <dc:Bounds x="876" y="279" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0sphcy5_di" bpmnElement="SequenceFlow_0sphcy5"> - <di:waypoint xsi:type="dc:Point" x="1057" y="300" /> - <di:waypoint xsi:type="dc:Point" x="1131" y="300" /> + <di:waypoint x="1057" y="300" /> + <di:waypoint x="1131" y="300" /> <bpmndi:BPMNLabel> <dc:Bounds x="1049" y="279" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_022onug_di" bpmnElement="SequenceFlow_022onug"> - <di:waypoint xsi:type="dc:Point" x="699" y="300" /> - <di:waypoint xsi:type="dc:Point" x="785" y="300" /> + <di:waypoint x="699" y="300" /> + <di:waypoint x="785" y="300" /> <bpmndi:BPMNLabel> <dc:Bounds x="697" y="279" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_18gnns6_di" bpmnElement="SequenceFlow_18gnns6"> - <di:waypoint xsi:type="dc:Point" x="1231" y="300" /> - <di:waypoint xsi:type="dc:Point" x="1301" y="300" /> + <di:waypoint x="1231" y="300" /> + <di:waypoint x="1301" y="300" /> <bpmndi:BPMNLabel> <dc:Bounds x="1221" y="279" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0yuzaen_di" bpmnElement="SequenceFlow_0yuzaen"> - <di:waypoint xsi:type="dc:Point" x="54" y="300" /> - <di:waypoint xsi:type="dc:Point" x="88" y="300" /> + <di:waypoint x="54" y="300" /> + <di:waypoint x="88" y="300" /> <bpmndi:BPMNLabel> <dc:Bounds x="71" y="279" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> </bpmndi:BPMNPlane> </bpmndi:BPMNDiagram> -</bpmn2:definitions>
\ No newline at end of file +</bpmn2:definitions> diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVnf.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVnf.bpmn index 50436352ea..df95cf0210 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVnf.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVnf.bpmn @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="_DkzPAHB4EeaJwpcpVN5gXw" targetNamespace="http://camunda.org/schema/1.0/bpmn" exporter="Camunda Modeler" exporterVersion="1.10.0" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"> +<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="_DkzPAHB4EeaJwpcpVN5gXw" targetNamespace="http://camunda.org/schema/1.0/bpmn" exporter="Camunda Modeler" exporterVersion="1.11.3" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"> <bpmn2:process id="DoCreateVnf" name="DoCreateVnf" isExecutable="true"> <bpmn2:startEvent id="StartEvent_1"> <bpmn2:outgoing>SequenceFlow_1</bpmn2:outgoing> @@ -90,7 +90,7 @@ createVnf.preProcessSDNCActivateRequest(execution)]]></bpmn2:script> <bpmn2:extensionElements> <camunda:in source="DoCVNF_activateSDNCRequest" target="sdncAdapterWorkflowRequest" /> <camunda:in source="isDebugLogEnabled" target="isDebugLogEnabled" /> - <camunda:in source="mso-reqeuest-id" target="mso-request-id" /> + <camunda:in source="mso-request-id" target="mso-request-id" /> <camunda:in source="mso-service-instance-id" target="mso-service-instance-id" /> <camunda:out source="WorkflowException" target="WorkflowException" /> <camunda:out source="sdncAdapterResponse" target="DoCVNF_activateSDNCAdapterResponse" /> diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteE2EServiceInstance.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteE2EServiceInstance.bpmn index 9f9d58fa19..4d0324e478 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteE2EServiceInstance.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteE2EServiceInstance.bpmn @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="1.11.3"> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="3.1.0"> <bpmn:process id="DoDeleteE2EServiceInstance" name="All Resources Deleted" isExecutable="true"> <bpmn:startEvent id="StartEvent_0212h2r" name="Start Flow"> <bpmn:outgoing>SequenceFlow_0vz7cd9</bpmn:outgoing> @@ -7,28 +7,28 @@ <bpmn:scriptTask id="ScriptTask_06phzgv" name="PreProcess Incoming Request" scriptFormat="groovy"> <bpmn:incoming>SequenceFlow_0vz7cd9</bpmn:incoming> <bpmn:outgoing>SequenceFlow_11e6bfy</bpmn:outgoing> - <bpmn:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* def ddsi = new DoDeleteE2EServiceInstance() ddsi.preProcessRequest(execution) -]]></bpmn:script> +</bpmn:script> </bpmn:scriptTask> <bpmn:endEvent id="EndEvent_1uqzt26"> <bpmn:incoming>SequenceFlow_0e7inkl</bpmn:incoming> </bpmn:endEvent> <bpmn:scriptTask id="ScriptTask_1rtnsh8" name="Post Process AAI GET" scriptFormat="groovy"> - <bpmn:incoming>SequenceFlow_188ejvu</bpmn:incoming> + <bpmn:incoming>SequenceFlow_11e6bfy</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0vi0sv6</bpmn:outgoing> - <bpmn:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* def ddsi = new DoDeleteE2EServiceInstance() -ddsi.postProcessAAIGET(execution)]]></bpmn:script> +ddsi.postProcessAAIGET(execution)</bpmn:script> </bpmn:scriptTask> <bpmn:scriptTask id="ScriptTask_01erufg" name=" AAI Delete (svc instance) " scriptFormat="groovy"> <bpmn:incoming>SequenceFlow_1cevtpy</bpmn:incoming> <bpmn:incoming>SequenceFlow_12rr1yy</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0e7inkl</bpmn:outgoing> - <bpmn:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* def ddsi = new DoCustomDeleteE2EServiceInstance() -ddsi.deleteServiceInstance(execution)]]></bpmn:script> +ddsi.deleteServiceInstance(execution)</bpmn:script> </bpmn:scriptTask> <bpmn:subProcess id="SubProcess_1u8zt9i" name="Sub-process for UnexpectedErrors" triggeredByEvent="true"> <bpmn:startEvent id="StartEvent_0sf5lpt"> @@ -41,22 +41,22 @@ ddsi.deleteServiceInstance(execution)]]></bpmn:script> <bpmn:scriptTask id="ScriptTask_0nha3pr" name="Log / Print Unexpected Error" scriptFormat="groovy"> <bpmn:incoming>SequenceFlow_1921mo3</bpmn:incoming> <bpmn:outgoing>SequenceFlow_18vlzfo</bpmn:outgoing> - <bpmn:script><![CDATA[import org.onap.so.bpmn.common.scripts.* + <bpmn:script>import org.onap.so.bpmn.common.scripts.* ExceptionUtil ex = new ExceptionUtil() -ex.processJavaException(execution)]]></bpmn:script> +ex.processJavaException(execution)</bpmn:script> </bpmn:scriptTask> <bpmn:sequenceFlow id="SequenceFlow_1921mo3" name="" sourceRef="StartEvent_0sf5lpt" targetRef="ScriptTask_0nha3pr" /> <bpmn:sequenceFlow id="SequenceFlow_18vlzfo" name="" sourceRef="ScriptTask_0nha3pr" targetRef="EndEvent_06utmg4" /> </bpmn:subProcess> <bpmn:sequenceFlow id="SequenceFlow_0vz7cd9" sourceRef="StartEvent_0212h2r" targetRef="ScriptTask_06phzgv" /> - <bpmn:sequenceFlow id="SequenceFlow_11e6bfy" sourceRef="ScriptTask_06phzgv" targetRef="CallActivity_076pc2z" /> + <bpmn:sequenceFlow id="SequenceFlow_11e6bfy" sourceRef="ScriptTask_06phzgv" targetRef="ScriptTask_1rtnsh8" /> <bpmn:sequenceFlow id="SequenceFlow_0e7inkl" sourceRef="ScriptTask_01erufg" targetRef="EndEvent_1uqzt26" /> <bpmn:scriptTask id="ScriptTask_146jt8v" name="Prepare Resource Oper Status" scriptFormat="groovy"> <bpmn:incoming>SequenceFlow_1961633</bpmn:incoming> <bpmn:outgoing>SequenceFlow_1ym9otf</bpmn:outgoing> - <bpmn:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* def ddsi = new DoDeleteE2EServiceInstance() -ddsi.preInitResourcesOperStatus(execution)]]></bpmn:script> +ddsi.preInitResourcesOperStatus(execution)</bpmn:script> </bpmn:scriptTask> <bpmn:serviceTask id="ServiceTask_00tg69u" name="Init Resource Oper Status"> <bpmn:extensionElements> @@ -81,22 +81,6 @@ ddsi.preInitResourcesOperStatus(execution)]]></bpmn:script> <bpmn:outgoing>SequenceFlow_1j08ko3</bpmn:outgoing> </bpmn:serviceTask> <bpmn:sequenceFlow id="SequenceFlow_1ym9otf" sourceRef="ScriptTask_146jt8v" targetRef="ServiceTask_00tg69u" /> - <bpmn:callActivity id="CallActivity_076pc2z" name="Call AAI Generic GetService" calledElement="GenericGetService"> - <bpmn:extensionElements> - <camunda:in source="serviceInstanceId" target="GENGS_serviceInstanceId" /> - <camunda:in sourceExpression="service-instance" target="GENGS_type" /> - <camunda:out source="GENGS_FoundIndicator" target="GENGS_FoundIndicator" /> - <camunda:out source="GENGS_SuccessIndicator" target="GENGS_SuccessIndicator" /> - <camunda:out source="WorkflowException" target="WorkflowException" /> - <camunda:out source="GENGS_siResourceLink" target="GENGS_siResourceLink" /> - <camunda:out source="GENGS_service" target="GENGS_service" /> - <camunda:in source="globalSubscriberId" target="GENGS_globalCustomerId" /> - <camunda:in source="serviceType" target="GENGS_serviceType" /> - </bpmn:extensionElements> - <bpmn:incoming>SequenceFlow_11e6bfy</bpmn:incoming> - <bpmn:outgoing>SequenceFlow_188ejvu</bpmn:outgoing> - </bpmn:callActivity> - <bpmn:sequenceFlow id="SequenceFlow_188ejvu" sourceRef="CallActivity_076pc2z" targetRef="ScriptTask_1rtnsh8" /> <bpmn:sequenceFlow id="SequenceFlow_1j08ko3" sourceRef="ServiceTask_00tg69u" targetRef="Task_1f5dlsv" /> <bpmn:sequenceFlow id="SequenceFlow_0fo5vw5" sourceRef="Task_1ldvug1" targetRef="Task_0mhdfuu" /> <bpmn:sequenceFlow id="SequenceFlow_0orw2f8" sourceRef="Task_0mhdfuu" targetRef="Task_1yx1n05" /> @@ -108,9 +92,9 @@ ddsi.preInitResourcesOperStatus(execution)]]></bpmn:script> <bpmn:scriptTask id="Task_1ldvug1" name="Prepare Decompose Service" scriptFormat="groovy"> <bpmn:incoming>SequenceFlow_1q2mqnm</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0fo5vw5</bpmn:outgoing> - <bpmn:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* def dcsi= new DoDeleteE2EServiceInstance() -dcsi.prepareDecomposeService(execution)]]></bpmn:script> +dcsi.prepareDecomposeService(execution)</bpmn:script> </bpmn:scriptTask> <bpmn:callActivity id="Task_0mhdfuu" name="Call Decompose Service" calledElement="DecomposeService"> <bpmn:extensionElements> @@ -130,9 +114,9 @@ dcsi.prepareDecomposeService(execution)]]></bpmn:script> <bpmn:scriptTask id="Task_1yx1n05" name="Post Decompose Service" scriptFormat="groovy"> <bpmn:incoming>SequenceFlow_0orw2f8</bpmn:incoming> <bpmn:outgoing>SequenceFlow_013rime</bpmn:outgoing> - <bpmn:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* def dcsi= new DoDeleteE2EServiceInstance() -dcsi.postDecomposeService(execution)]]></bpmn:script> +dcsi.postDecomposeService(execution)</bpmn:script> </bpmn:scriptTask> <bpmn:callActivity id="Task_1f5dlsv" name="Delete Resources" calledElement="DoDeleteResourcesV1"> <bpmn:extensionElements> @@ -177,7 +161,7 @@ dcsi.postDecomposeService(execution)]]></bpmn:script> <bpmn:linkEventDefinition name="EndDeleteProcess" /> </bpmn:intermediateThrowEvent> <bpmn:sequenceFlow id="SequenceFlow_1fozgqz" name="Yes" sourceRef="ExclusiveGateway_156mc3h" targetRef="IntermediateThrowEvent_00pyc0n"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[#{(execution.getVariable("isDeleteResourceListValid" ) == true)}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{(execution.getVariable("isDeleteResourceListValid" ) == true)}</bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:sequenceFlow id="SequenceFlow_1ncja2b" sourceRef="ExclusiveGateway_156mc3h" targetRef="IntermediateThrowEvent_1g4uc66" /> <bpmn:sequenceFlow id="SequenceFlow_013rime" sourceRef="Task_1yx1n05" targetRef="ExclusiveGateway_156mc3h" /> @@ -206,12 +190,12 @@ dcsi.postDecomposeService(execution)]]></bpmn:script> <bpmn:scriptTask id="ScriptTask_0f3tjbn" name="prepare update service operation status" scriptFormat="groovy"> <bpmn:incoming>SequenceFlow_0h5c1bd</bpmn:incoming> <bpmn:outgoing>SequenceFlow_1ab3vex</bpmn:outgoing> - <bpmn:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* execution.setVariable("progress", "100") execution.setVariable("result", "finished") execution.setVariable("operationContent", "No actual resoure in service instance") def csi= new DoDeleteE2EServiceInstance() -csi.prepareUpdateServiceOperationStatus(execution)]]></bpmn:script> +csi.prepareUpdateServiceOperationStatus(execution)</bpmn:script> </bpmn:scriptTask> <bpmn:intermediateCatchEvent id="IntermediateCatchEvent_0hrkmxb" name="End Delete Process"> <bpmn:outgoing>SequenceFlow_0h5c1bd</bpmn:outgoing> @@ -224,263 +208,249 @@ csi.prepareUpdateServiceOperationStatus(execution)]]></bpmn:script> <bpmndi:BPMNDiagram id="BPMNDiagram_1"> <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="DoDeleteE2EServiceInstance"> <bpmndi:BPMNShape id="StartEvent_0212h2r_di" bpmnElement="StartEvent_0212h2r"> - <dc:Bounds x="-537" y="-51" width="36" height="36" /> + <dc:Bounds x="168" y="103" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="-544" y="-10" width="52" height="12" /> + <dc:Bounds x="162" y="144" width="50" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ScriptTask_06phzgv_di" bpmnElement="ScriptTask_06phzgv"> - <dc:Bounds x="-449" y="-73" width="100" height="80" /> + <dc:Bounds x="256" y="81" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="EndEvent_1uqzt26_di" bpmnElement="EndEvent_1uqzt26"> - <dc:Bounds x="543" y="472" width="36" height="36" /> + <dc:Bounds x="1248" y="626" width="36" height="36" /> <bpmndi:BPMNLabel> <dc:Bounds x="471" y="513" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ScriptTask_1rtnsh8_di" bpmnElement="ScriptTask_1rtnsh8"> - <dc:Bounds x="-109" y="-73" width="100" height="80" /> + <dc:Bounds x="596" y="81" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ScriptTask_01erufg_di" bpmnElement="ScriptTask_01erufg"> - <dc:Bounds x="254" y="450" width="100" height="80" /> + <dc:Bounds x="959" y="604" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="SubProcess_1u8zt9i_di" bpmnElement="SubProcess_1u8zt9i" isExpanded="true"> - <dc:Bounds x="-161" y="980" width="467" height="193" /> + <dc:Bounds x="544" y="1134" width="467" height="193" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0vz7cd9_di" bpmnElement="SequenceFlow_0vz7cd9"> - <di:waypoint xsi:type="dc:Point" x="-501" y="-33" /> - <di:waypoint xsi:type="dc:Point" x="-475" y="-33" /> - <di:waypoint xsi:type="dc:Point" x="-475" y="-33" /> - <di:waypoint xsi:type="dc:Point" x="-449" y="-33" /> + <di:waypoint x="204" y="121" /> + <di:waypoint x="230" y="121" /> + <di:waypoint x="230" y="121" /> + <di:waypoint x="256" y="121" /> <bpmndi:BPMNLabel> <dc:Bounds x="-505" y="-39" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_11e6bfy_di" bpmnElement="SequenceFlow_11e6bfy"> - <di:waypoint xsi:type="dc:Point" x="-349" y="-33" /> - <di:waypoint xsi:type="dc:Point" x="-318" y="-33" /> - <di:waypoint xsi:type="dc:Point" x="-318" y="-33" /> - <di:waypoint xsi:type="dc:Point" x="-286" y="-33" /> + <di:waypoint x="356" y="121" /> + <di:waypoint x="596" y="121" /> <bpmndi:BPMNLabel> <dc:Bounds x="-348" y="-39" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0e7inkl_di" bpmnElement="SequenceFlow_0e7inkl"> - <di:waypoint xsi:type="dc:Point" x="354" y="490" /> - <di:waypoint xsi:type="dc:Point" x="543" y="490" /> + <di:waypoint x="1059" y="644" /> + <di:waypoint x="1248" y="644" /> <bpmndi:BPMNLabel> <dc:Bounds x="403.5" y="469" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="StartEvent_0sf5lpt_di" bpmnElement="StartEvent_0sf5lpt"> - <dc:Bounds x="-93" y="1047" width="36" height="36" /> + <dc:Bounds x="612" y="1201" width="36" height="36" /> <bpmndi:BPMNLabel> <dc:Bounds x="-165" y="1088" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="EndEvent_06utmg4_di" bpmnElement="EndEvent_06utmg4"> - <dc:Bounds x="200" y="1047" width="36" height="36" /> + <dc:Bounds x="905" y="1201" width="36" height="36" /> <bpmndi:BPMNLabel> <dc:Bounds x="128" y="1088" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ScriptTask_0nha3pr_di" bpmnElement="ScriptTask_0nha3pr"> - <dc:Bounds x="11" y="1025" width="100" height="80" /> + <dc:Bounds x="716" y="1179" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1921mo3_di" bpmnElement="SequenceFlow_1921mo3"> - <di:waypoint xsi:type="dc:Point" x="-57" y="1065" /> - <di:waypoint xsi:type="dc:Point" x="11" y="1065" /> + <di:waypoint x="648" y="1219" /> + <di:waypoint x="716" y="1219" /> <bpmndi:BPMNLabel> <dc:Bounds x="-113" y="1050" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_18vlzfo_di" bpmnElement="SequenceFlow_18vlzfo"> - <di:waypoint xsi:type="dc:Point" x="111" y="1065" /> - <di:waypoint xsi:type="dc:Point" x="200" y="1065" /> + <di:waypoint x="816" y="1219" /> + <di:waypoint x="905" y="1219" /> <bpmndi:BPMNLabel> <dc:Bounds x="67" y="1050" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ScriptTask_146jt8v_di" bpmnElement="ScriptTask_146jt8v"> - <dc:Bounds x="-422" y="450" width="100" height="80" /> + <dc:Bounds x="283" y="604" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ServiceTask_00tg69u_di" bpmnElement="ServiceTask_00tg69u"> - <dc:Bounds x="-229" y="450" width="100" height="80" /> + <dc:Bounds x="476" y="604" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1ym9otf_di" bpmnElement="SequenceFlow_1ym9otf"> - <di:waypoint xsi:type="dc:Point" x="-322" y="490" /> - <di:waypoint xsi:type="dc:Point" x="-229" y="490" /> + <di:waypoint x="383" y="644" /> + <di:waypoint x="476" y="644" /> <bpmndi:BPMNLabel> <dc:Bounds x="-320.5" y="469" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="CallActivity_076pc2z_di" bpmnElement="CallActivity_076pc2z"> - <dc:Bounds x="-286" y="-73" width="100" height="80" /> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="SequenceFlow_188ejvu_di" bpmnElement="SequenceFlow_188ejvu"> - <di:waypoint xsi:type="dc:Point" x="-186" y="-33" /> - <di:waypoint xsi:type="dc:Point" x="-154" y="-33" /> - <di:waypoint xsi:type="dc:Point" x="-154" y="-33" /> - <di:waypoint xsi:type="dc:Point" x="-109" y="-33" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="-184" y="-39" width="90" height="12" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1j08ko3_di" bpmnElement="SequenceFlow_1j08ko3"> - <di:waypoint xsi:type="dc:Point" x="-129" y="490" /> - <di:waypoint xsi:type="dc:Point" x="-1" y="490" /> + <di:waypoint x="576" y="644" /> + <di:waypoint x="704" y="644" /> <bpmndi:BPMNLabel> <dc:Bounds x="-110" y="469" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0fo5vw5_di" bpmnElement="SequenceFlow_0fo5vw5"> - <di:waypoint xsi:type="dc:Point" x="-278" y="198" /> - <di:waypoint xsi:type="dc:Point" x="-254" y="198" /> - <di:waypoint xsi:type="dc:Point" x="-254" y="198" /> - <di:waypoint xsi:type="dc:Point" x="-178" y="198" /> + <di:waypoint x="427" y="352" /> + <di:waypoint x="451" y="352" /> + <di:waypoint x="451" y="352" /> + <di:waypoint x="527" y="352" /> <bpmndi:BPMNLabel> <dc:Bounds x="-284" y="192" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0orw2f8_di" bpmnElement="SequenceFlow_0orw2f8"> - <di:waypoint xsi:type="dc:Point" x="-78" y="198" /> - <di:waypoint xsi:type="dc:Point" x="-49" y="198" /> - <di:waypoint xsi:type="dc:Point" x="-49" y="198" /> - <di:waypoint xsi:type="dc:Point" x="47" y="198" /> + <di:waypoint x="627" y="352" /> + <di:waypoint x="656" y="352" /> + <di:waypoint x="656" y="352" /> + <di:waypoint x="752" y="352" /> <bpmndi:BPMNLabel> <dc:Bounds x="-79" y="192" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="IntermediateCatchEvent_1jcfnjr_di" bpmnElement="startDeleteResources"> - <dc:Bounds x="-537" y="472" width="36" height="36" /> + <dc:Bounds x="168" y="626" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="-549" y="512" width="60" height="24" /> + <dc:Bounds x="157" y="666" width="58" height="27" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1961633_di" bpmnElement="SequenceFlow_1961633"> - <di:waypoint xsi:type="dc:Point" x="-501" y="490" /> - <di:waypoint xsi:type="dc:Point" x="-422" y="490" /> + <di:waypoint x="204" y="644" /> + <di:waypoint x="283" y="644" /> <bpmndi:BPMNLabel> <dc:Bounds x="-461.5" y="469" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ScriptTask_079nac8_di" bpmnElement="Task_1ldvug1"> - <dc:Bounds x="-378" y="158" width="100" height="80" /> + <dc:Bounds x="327" y="312" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="CallActivity_01b12fk_di" bpmnElement="Task_0mhdfuu"> - <dc:Bounds x="-178" y="158" width="100" height="80" /> + <dc:Bounds x="527" y="312" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ScriptTask_0msjtc4_di" bpmnElement="Task_1yx1n05"> - <dc:Bounds x="47" y="158" width="100" height="80" /> + <dc:Bounds x="752" y="312" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="CallActivity_16sm2op_di" bpmnElement="Task_1f5dlsv"> - <dc:Bounds x="-1" y="450" width="100" height="80" /> + <dc:Bounds x="704" y="604" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1cevtpy_di" bpmnElement="SequenceFlow_1cevtpy"> - <di:waypoint xsi:type="dc:Point" x="99" y="490" /> - <di:waypoint xsi:type="dc:Point" x="254" y="490" /> + <di:waypoint x="804" y="644" /> + <di:waypoint x="959" y="644" /> <bpmndi:BPMNLabel> <dc:Bounds x="131.5" y="469" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="IntermediateCatchEvent_0s6bb2d_di" bpmnElement="DecomposeService"> - <dc:Bounds x="-537" y="180" width="36" height="36" /> + <dc:Bounds x="168" y="334" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="-550" y="220" width="61" height="24" /> + <dc:Bounds x="156" y="374" width="59" height="27" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1q2mqnm_di" bpmnElement="SequenceFlow_1q2mqnm"> - <di:waypoint xsi:type="dc:Point" x="-501" y="198" /> - <di:waypoint xsi:type="dc:Point" x="-378" y="198" /> + <di:waypoint x="204" y="352" /> + <di:waypoint x="327" y="352" /> <bpmndi:BPMNLabel> <dc:Bounds x="-484" y="177" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="IntermediateThrowEvent_1j1awcj_di" bpmnElement="StartEvent_1qh5a34"> - <dc:Bounds x="71" y="-51" width="36" height="36" /> + <dc:Bounds x="776" y="103" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="46" y="-11" width="85" height="24" /> + <dc:Bounds x="752" y="143" width="83" height="27" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0vi0sv6_di" bpmnElement="SequenceFlow_0vi0sv6"> - <di:waypoint xsi:type="dc:Point" x="-9" y="-33" /> - <di:waypoint xsi:type="dc:Point" x="14" y="-33" /> - <di:waypoint xsi:type="dc:Point" x="14" y="-33" /> - <di:waypoint xsi:type="dc:Point" x="71" y="-33" /> + <di:waypoint x="696" y="121" /> + <di:waypoint x="719" y="121" /> + <di:waypoint x="719" y="121" /> + <di:waypoint x="776" y="121" /> <bpmndi:BPMNLabel> <dc:Bounds x="-16" y="-39" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="IntermediateThrowEvent_00pyc0n_di" bpmnElement="IntermediateThrowEvent_00pyc0n"> - <dc:Bounds x="398" y="180" width="36" height="36" /> + <dc:Bounds x="1103" y="334" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="389" y="220" width="57" height="24" /> + <dc:Bounds x="1094" y="374" width="58" height="27" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ExclusiveGateway_156mc3h_di" bpmnElement="ExclusiveGateway_156mc3h" isMarkerVisible="true"> - <dc:Bounds x="279" y="173" width="50" height="50" /> + <dc:Bounds x="984" y="327" width="50" height="50" /> <bpmndi:BPMNLabel> - <dc:Bounds x="266" y="145" width="75" height="24" /> + <dc:Bounds x="972" y="299" width="74" height="27" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="IntermediateThrowEvent_1g4uc66_di" bpmnElement="IntermediateThrowEvent_1g4uc66"> - <dc:Bounds x="286" y="270" width="36" height="36" /> + <dc:Bounds x="991" y="424" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="279" y="308" width="53" height="24" /> + <dc:Bounds x="983" y="462" width="55" height="27" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1fozgqz_di" bpmnElement="SequenceFlow_1fozgqz"> - <di:waypoint xsi:type="dc:Point" x="329" y="198" /> - <di:waypoint xsi:type="dc:Point" x="398" y="198" /> + <di:waypoint x="1034" y="352" /> + <di:waypoint x="1103" y="352" /> <bpmndi:BPMNLabel> - <dc:Bounds x="356.5" y="176" width="19" height="12" /> + <dc:Bounds x="1062" y="330" width="19" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1ncja2b_di" bpmnElement="SequenceFlow_1ncja2b"> - <di:waypoint xsi:type="dc:Point" x="304" y="223" /> - <di:waypoint xsi:type="dc:Point" x="304" y="270" /> + <di:waypoint x="1009" y="377" /> + <di:waypoint x="1009" y="424" /> <bpmndi:BPMNLabel> <dc:Bounds x="274" y="240.5" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_013rime_di" bpmnElement="SequenceFlow_013rime"> - <di:waypoint xsi:type="dc:Point" x="147" y="198" /> - <di:waypoint xsi:type="dc:Point" x="279" y="198" /> + <di:waypoint x="852" y="352" /> + <di:waypoint x="984" y="352" /> <bpmndi:BPMNLabel> <dc:Bounds x="213" y="177" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_1lsic7i_di" bpmnElement="ServiceTask_1lsic7i"> - <dc:Bounds x="-121" y="697" width="100" height="80" /> + <dc:Bounds x="584" y="851" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ScriptTask_0f3tjbn_di" bpmnElement="ScriptTask_0f3tjbn"> - <dc:Bounds x="-399" y="697" width="100" height="80" /> + <dc:Bounds x="306" y="851" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="IntermediateCatchEvent_0hrkmxb_di" bpmnElement="IntermediateCatchEvent_0hrkmxb"> - <dc:Bounds x="-531" y="719" width="36" height="36" /> + <dc:Bounds x="174" y="873" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="-539" y="759" width="53" height="24" /> + <dc:Bounds x="165" y="913" width="55" height="27" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1ab3vex_di" bpmnElement="SequenceFlow_1ab3vex"> - <di:waypoint xsi:type="dc:Point" x="-299" y="737" /> - <di:waypoint xsi:type="dc:Point" x="-121" y="737" /> + <di:waypoint x="406" y="891" /> + <di:waypoint x="584" y="891" /> <bpmndi:BPMNLabel> <dc:Bounds x="-255" y="715" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0h5c1bd_di" bpmnElement="SequenceFlow_0h5c1bd"> - <di:waypoint xsi:type="dc:Point" x="-495" y="737" /> - <di:waypoint xsi:type="dc:Point" x="-399" y="737" /> + <di:waypoint x="210" y="891" /> + <di:waypoint x="306" y="891" /> <bpmndi:BPMNLabel> <dc:Bounds x="-492" y="715" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_12rr1yy_di" bpmnElement="SequenceFlow_12rr1yy"> - <di:waypoint xsi:type="dc:Point" x="-21" y="737" /> - <di:waypoint xsi:type="dc:Point" x="117" y="737" /> - <di:waypoint xsi:type="dc:Point" x="117" y="490" /> - <di:waypoint xsi:type="dc:Point" x="254" y="490" /> + <di:waypoint x="684" y="891" /> + <di:waypoint x="822" y="891" /> + <di:waypoint x="822" y="644" /> + <di:waypoint x="959" y="644" /> <bpmndi:BPMNLabel> <dc:Bounds x="132" y="607.5" width="0" height="12" /> </bpmndi:BPMNLabel> diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/CreateVcpeResCustServiceSimplifiedTest.java b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/CreateVcpeResCustServiceSimplifiedTest.java index f51ea006d2..5b095a9983 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/CreateVcpeResCustServiceSimplifiedTest.java +++ b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/CreateVcpeResCustServiceSimplifiedTest.java @@ -27,13 +27,12 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat; -import com.google.protobuf.Struct; import java.io.IOException; import java.util.List; import java.util.UUID; -import org.camunda.bpm.engine.runtime.Execution; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.junit.Before; import org.junit.Ignore; @@ -47,17 +46,19 @@ import org.onap.so.bpmn.mock.FileUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import com.google.protobuf.Struct; /** * Basic Integration test for createVcpeResCustService_Simplified.bpmn workflow. */ -@Ignore public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest { - private static final long WORKFLOW_WAIT_TIME = 1000L; private Logger logger = LoggerFactory.getLogger(getClass()); + private static final long WORKFLOW_WAIT_TIME = 1000L; + private static final int DMAAP_DELAY_TIME_MS = 2000; + private static final String TEST_PROCESSINSTANCE_KEY = "CreateVcpeResCustService_simplified"; private String testBusinessKey; @@ -103,6 +104,7 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest { } + @Ignore @Test public void workflow_validInput_expectedOuput() throws InterruptedException { @@ -113,17 +115,9 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest { ProcessInstance pi = runtimeService.startProcessInstanceByKey(TEST_PROCESSINSTANCE_KEY, testBusinessKey, variables); - assertThat(pi).isNotNull(); - - Thread.sleep(WORKFLOW_WAIT_TIME); - - Execution execution = runtimeService.createExecutionQuery().processInstanceBusinessKey(testBusinessKey) - .messageEventSubscriptionName("WorkflowMessage").singleResult(); - - assertThat(execution).isNotNull(); int waitCount = 10; - while (!pi.isEnded() && waitCount >= 0) { + while (!isProcessInstanceEnded() && waitCount >= 0) { Thread.sleep(WORKFLOW_WAIT_TIME); waitCount--; } @@ -145,6 +139,11 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest { } } + private boolean isProcessInstanceEnded() { + return runtimeService.createProcessInstanceQuery().processDefinitionKey(TEST_PROCESSINSTANCE_KEY) + .singleResult() == null; + } + private void checkConfigAssign(ExecutionServiceInput executionServiceInput) { logger.info("Checking the configAssign request"); @@ -154,26 +153,26 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest { * the fields of actionIdentifiers should match the one in the * response/createVcpeResCustServiceSimplifiedTest_catalogdb.json. */ - assertThat(actionIdentifiers.getBlueprintName()).matches("test_configuration_restconf"); - assertThat(actionIdentifiers.getBlueprintVersion()).matches("1.0.0"); - assertThat(actionIdentifiers.getActionName()).matches("config-assign"); - assertThat(actionIdentifiers.getMode()).matches("sync"); + assertThat(actionIdentifiers.getBlueprintName()).isEqualTo("test_configuration_restconf"); + assertThat(actionIdentifiers.getBlueprintVersion()).isEqualTo("1.0.0"); + assertThat(actionIdentifiers.getActionName()).isEqualTo("config-assign"); + assertThat(actionIdentifiers.getMode()).isEqualTo("sync"); CommonHeader commonHeader = executionServiceInput.getCommonHeader(); - assertThat(commonHeader.getOriginatorId()).matches("SO"); - assertThat(commonHeader.getRequestId()).matches(msoRequestId); + assertThat(commonHeader.getOriginatorId()).isEqualTo("SO"); + assertThat(commonHeader.getRequestId()).isEqualTo(msoRequestId); Struct payload = executionServiceInput.getPayload(); Struct requeststruct = payload.getFieldsOrThrow("config-assign-request").getStructValue(); - assertThat(requeststruct.getFieldsOrThrow("resolution-key").getStringValue()).matches("PNFDemo"); + assertThat(requeststruct.getFieldsOrThrow("resolution-key").getStringValue()).isEqualTo("PNFDemo"); Struct propertiesStruct = requeststruct.getFieldsOrThrow("config-assign-properties").getStructValue(); - assertThat(propertiesStruct.getFieldsOrThrow("pnf-name").getStringValue()).matches("PNFDemo"); + assertThat(propertiesStruct.getFieldsOrThrow("pnf-name").getStringValue()).isEqualTo("PNFDemo"); assertThat(propertiesStruct.getFieldsOrThrow("service-model-uuid").getStringValue()) - .matches("f2daaac6-5017-4e1e-96c8-6a27dfbe1421"); + .isEqualTo("f2daaac6-5017-4e1e-96c8-6a27dfbe1421"); assertThat(propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue()) - .matches("68dc9a92-214c-11e7-93ae-92361f002680"); + .isEqualTo("68dc9a92-214c-11e7-93ae-92361f002680"); } private void checkConfigDeploy(ExecutionServiceInput executionServiceInput) { @@ -185,32 +184,32 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest { * the fields of actionIdentifiers should match the one in the * response/createVcpeResCustServiceSimplifiedTest_catalogdb.json. */ - assertThat(actionIdentifiers.getBlueprintName()).matches("test_configuration_restconf"); - assertThat(actionIdentifiers.getBlueprintVersion()).matches("1.0.0"); - assertThat(actionIdentifiers.getActionName()).matches("config-deploy"); - assertThat(actionIdentifiers.getMode()).matches("async"); + assertThat(actionIdentifiers.getBlueprintName()).isEqualTo("test_configuration_restconf"); + assertThat(actionIdentifiers.getBlueprintVersion()).isEqualTo("1.0.0"); + assertThat(actionIdentifiers.getActionName()).isEqualTo("config-deploy"); + assertThat(actionIdentifiers.getMode()).isEqualTo("async"); CommonHeader commonHeader = executionServiceInput.getCommonHeader(); - assertThat(commonHeader.getOriginatorId()).matches("SO"); - assertThat(commonHeader.getRequestId()).matches(msoRequestId); + assertThat(commonHeader.getOriginatorId()).isEqualTo("SO"); + assertThat(commonHeader.getRequestId()).isEqualTo(msoRequestId); Struct payload = executionServiceInput.getPayload(); Struct requeststruct = payload.getFieldsOrThrow("config-deploy-request").getStructValue(); - assertThat(requeststruct.getFieldsOrThrow("resolution-key").getStringValue()).matches("PNFDemo"); + assertThat(requeststruct.getFieldsOrThrow("resolution-key").getStringValue()).isEqualTo("PNFDemo"); Struct propertiesStruct = requeststruct.getFieldsOrThrow("config-deploy-properties").getStructValue(); - assertThat(propertiesStruct.getFieldsOrThrow("pnf-name").getStringValue()).matches("PNFDemo"); + assertThat(propertiesStruct.getFieldsOrThrow("pnf-name").getStringValue()).isEqualTo("PNFDemo"); assertThat(propertiesStruct.getFieldsOrThrow("service-model-uuid").getStringValue()) - .matches("f2daaac6-5017-4e1e-96c8-6a27dfbe1421"); + .isEqualTo("f2daaac6-5017-4e1e-96c8-6a27dfbe1421"); assertThat(propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue()) - .matches("68dc9a92-214c-11e7-93ae-92361f002680"); + .isEqualTo("68dc9a92-214c-11e7-93ae-92361f002680"); /** * IP addresses match the OAM ip addresses from AAI. */ - assertThat(propertiesStruct.getFieldsOrThrow("pnf-ipv4-address").getStringValue()).matches("1.1.1.1"); - assertThat(propertiesStruct.getFieldsOrThrow("pnf-ipv6-address").getStringValue()).matches("::/128"); + assertThat(propertiesStruct.getFieldsOrThrow("pnf-ipv4-address").getStringValue()).isEqualTo("1.1.1.1"); + assertThat(propertiesStruct.getFieldsOrThrow("pnf-ipv6-address").getStringValue()).isEqualTo("::/128"); } /** @@ -223,8 +222,8 @@ public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest { /** * Get the events from PNF topic */ - wireMockServer - .stubFor(get(urlPathMatching("/events/pnfReady/consumerGroup.*")).willReturn(okJson(pnfResponse))); + wireMockServer.stubFor(get(urlPathMatching("/events/pnfReady/consumerGroup.*")) + .willReturn(okJson(pnfResponse).withFixedDelay(DMAAP_DELAY_TIME_MS))); } private void mockAai() { diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/resources/__files/Macro/CreateNetworkCollection.json b/bpmn/so-bpmn-infrastructure-flows/src/test/resources/__files/Macro/CreateNetworkCollection.json index 7b369ab97e..ce0e5aa643 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/test/resources/__files/Macro/CreateNetworkCollection.json +++ b/bpmn/so-bpmn-infrastructure-flows/src/test/resources/__files/Macro/CreateNetworkCollection.json @@ -4,7 +4,7 @@ "modelType": "service", "modelInvariantId": "5d48acb5-097d-4982-aeb2-f4a3bd87d31b", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersion": "10" }, "cloudConfiguration": { @@ -34,7 +34,7 @@ { "service": { "modelInfo": { - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a" }, "instanceParams": [], diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/resources/__files/Macro/ServiceMacroAssign.json b/bpmn/so-bpmn-infrastructure-flows/src/test/resources/__files/Macro/ServiceMacroAssign.json index 51caddd48a..b86a2a28f6 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/test/resources/__files/Macro/ServiceMacroAssign.json +++ b/bpmn/so-bpmn-infrastructure-flows/src/test/resources/__files/Macro/ServiceMacroAssign.json @@ -4,7 +4,7 @@ "modelType": "service", "modelInvariantId": "5d48acb5-097d-4982-aeb2-f4a3bd87d31b", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersion": "10.0" }, "owningEntity": { @@ -31,7 +31,7 @@ "service": { "modelInfo": { "modelType": "service", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a" }, "instanceParams": [], diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/SniroHomingV2.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/SniroHomingV2.java index 2b9729f7c7..e5df3d3f35 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/SniroHomingV2.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/SniroHomingV2.java @@ -90,19 +90,17 @@ public class SniroHomingV2 { private SniroClient client; @Autowired private ExceptionBuilder exceptionUtil; - private static final String MODEL_NAME = "modelName"; private static final String MODEL_INVARIANT_ID = "modelInvariantId"; private static final String MODEL_VERSION_ID = "modelVersionId"; - private static final String MODEL_VERSION = "modelVersion"; private static final String SERVICE_RESOURCE_ID = "serviceResourceId"; - private static final String RESOURCE_MODULE_NAME = "resourceModuleName"; - private static final String RESOURCE_MODEL_INFO = "resourceModelInfo"; private static final String IDENTIFIER_TYPE = "identifierType"; private static final String SOLUTIONS = "solutions"; private static final String RESOURCE_MISSING_DATA = "Resource does not contain: "; private static final String SERVICE_MISSING_DATA = "Service Instance does not contain: "; private static final String UNPROCESSABLE = "422"; private static final int INTERNAL = 500; + private static final String EXCEPTION_OCCURRED = "Exception occurred"; + private static final String VNF_HOST_NAME = "vnfHostName"; /** * Generates the request payload then sends to sniro manager to perform homing and licensing for the provided @@ -147,7 +145,7 @@ public class SniroHomingV2 { licenseInfo.setDemands(licenseDemands); request.setLicenseInformation(licenseInfo); - if (placementDemands.size() > 0 || licenseDemands.size() > 0) { + if (!placementDemands.isEmpty() || !licenseDemands.isEmpty()) { client.postDemands(request); } else { logger.debug(SERVICE_MISSING_DATA + "resources eligible for homing or licensing"); @@ -161,13 +159,13 @@ public class SniroHomingV2 { logger.trace("Completed Sniro Homing Call Sniro"); } catch (BpmnError e) { - logger.error("Exception occurred", e); + logger.error(EXCEPTION_OCCURRED, e); exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(e.getErrorCode()), e.getMessage()); } catch (BadResponseException e) { - logger.error("Exception occurred", e); + logger.error(EXCEPTION_OCCURRED, e); exceptionUtil.buildAndThrowWorkflowException(execution, 400, e.getMessage()); } catch (Exception e) { - logger.error("Exception occurred", e); + logger.error(EXCEPTION_OCCURRED, e); exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL, "Internal Error - occurred while preparing sniro request: " + e.getMessage()); } @@ -183,7 +181,6 @@ public class SniroHomingV2 { logger.trace("Started Sniro Homing Process Solution"); try { // TODO improve handling multiple solutions but is dependent on sniro enhancing api + work with sniro - // conductor to improve "inventoryType" representation validateSolution(asyncResponse); ServiceInstance serviceInstance = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription() .getServiceInstances().get(0); @@ -213,13 +210,13 @@ public class SniroHomingV2 { logger.trace("Completed Sniro Homing Process Solution"); } catch (BpmnError e) { - logger.error("Exception occurred", e); + logger.error(EXCEPTION_OCCURRED, e); exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(e.getErrorCode()), e.getMessage()); } catch (BadResponseException e) { - logger.error("Exception occurred", e); + logger.error(EXCEPTION_OCCURRED, e); exceptionUtil.buildAndThrowWorkflowException(execution, 400, e.getMessage()); } catch (Exception e) { - logger.error("Exception occurred", e); + logger.error(EXCEPTION_OCCURRED, e); exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL, "Internal Error - occurred while processing sniro asynchronous response: " + e.getMessage()); } @@ -230,7 +227,7 @@ public class SniroHomingV2 { * * @throws Exception */ - private RequestInfo buildRequestInfo(String requestId, String timeout) throws Exception { + private RequestInfo buildRequestInfo(String requestId, String timeout) { logger.trace("Building request information"); RequestInfo requestInfo = new RequestInfo(); if (requestId != null) { @@ -305,7 +302,7 @@ public class SniroHomingV2 { */ private List<Demand> buildPlacementDemands(ServiceInstance serviceInstance) { logger.trace("Building placement information demands"); - List<Demand> placementDemands = new ArrayList<Demand>(); + List<Demand> placementDemands = new ArrayList<>(); List<AllottedResource> allottedResourceList = serviceInstance.getAllottedResources(); if (!allottedResourceList.isEmpty()) { @@ -355,7 +352,7 @@ public class SniroHomingV2 { */ private List<Demand> buildLicenseDemands(ServiceInstance serviceInstance) { logger.trace("Building license information"); - List<Demand> licenseDemands = new ArrayList<Demand>(); + List<Demand> licenseDemands = new ArrayList<>(); List<GenericVnf> vnfList = serviceInstance.getVnfs(); if (!vnfList.isEmpty()) { logger.debug("Adding vnfs to license demands list"); @@ -406,49 +403,46 @@ public class SniroHomingV2 { } /** - * Adds required, excluded, and existing candidates to a demand + * Adds required, excluded, and existing candidates as well as filtering attributes to a demand * */ private void addCandidates(SolutionCandidates candidates, Demand demand) { List<Candidate> required = candidates.getRequiredCandidates(); List<Candidate> excluded = candidates.getExcludedCandidates(); List<Candidate> existing = candidates.getExistingCandidates(); - if (!required.isEmpty()) { - List<org.onap.so.client.sniro.beans.Candidate> cans = - new ArrayList<org.onap.so.client.sniro.beans.Candidate>(); - for (Candidate c : required) { - org.onap.so.client.sniro.beans.Candidate can = new org.onap.so.client.sniro.beans.Candidate(); - can.setIdentifierType(c.getIdentifierType()); - can.setIdentifiers(c.getIdentifiers()); - can.setCloudOwner(c.getCloudOwner()); - cans.add(can); - } - demand.setRequiredCandidates(cans); + List<Candidate> filtering = candidates.getFilteringAttributes(); + + List<org.onap.so.client.sniro.beans.Candidate> candidateList = getCandidates(required); + if (!candidateList.isEmpty()) { + demand.setRequiredCandidates(candidateList); } - if (!excluded.isEmpty()) { - List<org.onap.so.client.sniro.beans.Candidate> cans = - new ArrayList<org.onap.so.client.sniro.beans.Candidate>(); - for (Candidate c : excluded) { - org.onap.so.client.sniro.beans.Candidate can = new org.onap.so.client.sniro.beans.Candidate(); - can.setIdentifierType(c.getIdentifierType()); - can.setIdentifiers(c.getIdentifiers()); - can.setCloudOwner(c.getCloudOwner()); - cans.add(can); - } - demand.setExcludedCandidates(cans); + candidateList = getCandidates(excluded); + if (!candidateList.isEmpty()) { + demand.setExcludedCandidates(candidateList); + } + candidateList = getCandidates(existing); + if (!candidateList.isEmpty()) { + demand.setExistingCandidates(candidateList); } - if (!existing.isEmpty()) { - List<org.onap.so.client.sniro.beans.Candidate> cans = - new ArrayList<org.onap.so.client.sniro.beans.Candidate>(); - for (Candidate c : existing) { + + candidateList = getCandidates(filtering); + if (!candidateList.isEmpty()) { + demand.setFilteringAttributes(candidateList); + } + } + + private List<org.onap.so.client.sniro.beans.Candidate> getCandidates(List<Candidate> candidates) { + List<org.onap.so.client.sniro.beans.Candidate> candidateList = new ArrayList<>(); + if (!candidates.isEmpty()) { + for (Candidate c : candidates) { org.onap.so.client.sniro.beans.Candidate can = new org.onap.so.client.sniro.beans.Candidate(); can.setIdentifierType(c.getIdentifierType()); can.setIdentifiers(c.getIdentifiers()); can.setCloudOwner(c.getCloudOwner()); - cans.add(can); + candidateList.add(can); } - demand.setExistingCandidates(cans); } + return candidateList; } /** @@ -562,7 +556,7 @@ public class SniroHomingV2 { si.setServiceInstanceId(identifierValue); si.setOrchestrationStatus(OrchestrationStatus.CREATED); cloud.setLcpCloudRegionId(assignmentsMap.get("cloudRegionId")); - if (assignmentsMap.containsKey("vnfHostName") && !assignmentsMap.get("vnfHostName").isEmpty()) { + if (assignmentsMap.containsKey(VNF_HOST_NAME) && !assignmentsMap.get(VNF_HOST_NAME).isEmpty()) { logger.debug("Resources has been homed to a vnf"); GenericVnf vnf = setVnf(assignmentsMap); vnf.setCloudRegion(cloud); @@ -612,7 +606,7 @@ public class SniroHomingV2 { private GenericVnf setVnf(Map<String, String> assignmentsMap) { GenericVnf vnf = new GenericVnf(); vnf.setOrchestrationStatus(OrchestrationStatus.CREATED); - vnf.setVnfName(assignmentsMap.get("vnfHostName")); + vnf.setVnfName(assignmentsMap.get(VNF_HOST_NAME)); vnf.setVnfId(assignmentsMap.get("vnfId")); return vnf; } 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 4d4b7c9ad2..e3540ecc58 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 @@ -29,6 +29,7 @@ import java.util.TreeSet; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.onap.so.logger.LoggingAnchor; import org.camunda.bpm.engine.delegate.BpmnError; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; @@ -49,6 +50,7 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup; import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; +import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.DuplicateNameException; import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; @@ -75,6 +77,7 @@ public class AAICreateTasks { private static final Logger logger = LoggerFactory.getLogger(AAICreateTasks.class); private static final String networkTypeProvider = "PROVIDER"; + private static final String A_LA_CARTE = "aLaCarte"; private static String NETWORK_COLLECTION_NAME = "networkCollectionName"; private static String CONTRAIL_NETWORK_POLICY_FQDN_LIST = "contrailNetworkPolicyFqdnList"; private static String HEAT_STACK_ID = "heatStackId"; @@ -104,8 +107,12 @@ public class AAICreateTasks { public void createServiceInstance(BuildingBlockExecution execution) { try { + Boolean alaCarte = execution.getVariable(A_LA_CARTE); ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + if (Boolean.TRUE.equals(alaCarte) && aaiSIResources.checkInstanceServiceNameInUse(serviceInstance)) { + throw new DuplicateNameException("service-instance", serviceInstance.getServiceInstanceName()); + } Customer customer = execution.getGeneralBuildingBlock().getCustomer(); aaiSIResources.createServiceInstance(serviceInstance, customer); } catch (Exception ex) { @@ -122,8 +129,8 @@ public class AAICreateTasks { String errorMessage = "Exception in creating ServiceSubscription. Customer not present for ServiceInstanceID: " + serviceInstance.getServiceInstanceId(); - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), errorMessage, "BPMN", - ErrorCode.UnknownError.getValue(), errorMessage); + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), errorMessage, + "BPMN", ErrorCode.UnknownError.getValue(), errorMessage); exceptionUtil.buildAndThrowWorkflowException(execution, 7000, errorMessage); } aaiSIResources.createServiceSubscription(customer); @@ -169,14 +176,14 @@ public class AAICreateTasks { if (owningEntityName == null || "".equals(owningEntityName)) { String msg = "Exception in AAICreateOwningEntity. Can't create an owningEntity with no owningEntityName."; - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue(), msg); exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg); } else { if (aaiSIResources.existsOwningEntityName(owningEntityName)) { String msg = "Exception in AAICreateOwningEntity. Can't create OwningEntity as name already exists in AAI associated with a different owning-entity-id (name must be unique)"; - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue(), msg); exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg); } else { @@ -192,10 +199,14 @@ public class AAICreateTasks { public void createVnf(BuildingBlockExecution execution) { try { + Boolean alaCarte = execution.getVariable(A_LA_CARTE); GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + if (Boolean.TRUE.equals(alaCarte) && aaiVnfResources.checkNameInUse(vnf.getVnfName())) { + throw new DuplicateNameException("generic-vnf", vnf.getVnfName()); + } ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); - execution.setVariable("callHoming", Boolean.TRUE.equals(vnf.isCallHoming())); + execution.setVariable("homing", Boolean.TRUE.equals(vnf.isCallHoming())); aaiVnfResources.createVnfandConnectServiceInstance(vnf, serviceInstance); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -251,6 +262,10 @@ public class AAICreateTasks { GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); CloudRegion cloudRegion = gBBInput.getCloudRegion(); + Boolean alaCarte = execution.getVariable(A_LA_CARTE); + if (Boolean.TRUE.equals(alaCarte) && aaiVolumeGroupResources.checkNameInUse(volumeGroup)) { + throw new DuplicateNameException("volume-group", volumeGroup.getVolumeGroupName()); + } aaiVolumeGroupResources.createVolumeGroup(volumeGroup, cloudRegion); aaiVolumeGroupResources.connectVolumeGroupToVnf(genericVnf, volumeGroup, cloudRegion); aaiVolumeGroupResources.connectVolumeGroupToTenant(volumeGroup, cloudRegion); @@ -263,6 +278,10 @@ public class AAICreateTasks { try { GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); + Boolean alaCarte = execution.getVariable(A_LA_CARTE); + if (Boolean.TRUE.equals(alaCarte) && aaiVfModuleResources.checkNameInUse(vfModule)) { + throw new DuplicateNameException("vf-module", vfModule.getVfModuleName()); + } int moduleIndex = 0; if (vfModule.getModelInfoVfModule() != null && !Boolean.TRUE.equals(vfModule.getModelInfoVfModule().getIsBaseBoolean())) { @@ -308,9 +327,14 @@ public class AAICreateTasks { */ public void createNetwork(BuildingBlockExecution execution) { try { + Boolean alaCarte = execution.getVariable(A_LA_CARTE); ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); + if (Boolean.TRUE.equals(alaCarte) + && aaiNetworkResources.checkNetworkNameInUse(l3network.getNetworkName())) { + throw new DuplicateNameException("l3Network", l3network.getNetworkName()); + } // set default to false. ToBe updated by SDNC l3network.setIsBoundToVpn(false); // define is bound to vpn flag as true if NEUTRON_NETWORK_TYPE is PROVIDER @@ -361,11 +385,16 @@ public class AAICreateTasks { */ public void createNetworkCollectionInstanceGroup(BuildingBlockExecution execution) { try { + Boolean alaCarte = execution.getVariable(A_LA_CARTE); ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); InstanceGroup instanceGroup = serviceInstance.getCollection().getInstanceGroup(); // set name generated for NetworkCollection/NetworkCollectionInstanceGroup in previous step of the BB flow instanceGroup.setInstanceGroupName(execution.getVariable(NETWORK_COLLECTION_NAME)); + if (Boolean.TRUE.equals(alaCarte) + && aaiInstanceGroupResources.checkInstanceGroupNameInUse(instanceGroup.getInstanceGroupName())) { + throw new DuplicateNameException("instance-group", instanceGroup.getInstanceGroupName()); + } // put shell in AAI aaiNetworkResources.createNetworkInstanceGroup(instanceGroup); } catch (Exception ex) { @@ -482,7 +511,12 @@ public class AAICreateTasks { public void createConfiguration(BuildingBlockExecution execution) { try { + Boolean alaCarte = execution.getVariable(A_LA_CARTE); Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID); + if (Boolean.TRUE.equals(alaCarte) + && aaiConfigurationResources.checkConfigurationNameInUse(configuration.getConfigurationName())) { + throw new DuplicateNameException("configuration", configuration.getConfigurationName()); + } aaiConfigurationResources.createConfiguration(configuration); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -491,9 +525,14 @@ public class AAICreateTasks { public void createInstanceGroupVnf(BuildingBlockExecution execution) { try { + Boolean alaCarte = execution.getVariable(A_LA_CARTE); ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID); + if (Boolean.TRUE.equals(alaCarte) + && aaiInstanceGroupResources.checkInstanceGroupNameInUse(instanceGroup.getInstanceGroupName())) { + throw new DuplicateNameException("instance-group", instanceGroup.getInstanceGroupName()); + } aaiInstanceGroupResources.createInstanceGroupandConnectServiceInstance(instanceGroup, serviceInstance); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); 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 a37f43727e..775e3213d4 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 @@ -25,12 +25,14 @@ package org.onap.so.bpmn.infrastructure.activity; import java.util.HashMap; import java.util.Map; import java.util.UUID; +import org.onap.so.logger.LoggingAnchor; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.camunda.bpm.engine.runtime.ProcessInstanceWithVariables; import org.camunda.bpm.engine.variable.VariableMap; import org.onap.so.bpmn.core.WorkflowException; +import org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionBBTasks; import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds; @@ -55,6 +57,7 @@ public class ExecuteActivity implements JavaDelegate { private static final String G_REQUEST_ID = "mso-request-id"; 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 SERVICE_TASK_IMPLEMENTATION_ATTRIBUTE = "implementation"; private static final String ACTIVITY_PREFIX = "activity:"; @@ -65,12 +68,19 @@ public class ExecuteActivity implements JavaDelegate { private RuntimeService runtimeService; @Autowired private ExceptionBuilder exceptionBuilder; + @Autowired + private WorkflowActionBBTasks workflowActionBBTasks; @Override public void execute(DelegateExecution execution) throws Exception { final String requestId = (String) execution.getVariable(G_REQUEST_ID); try { + Boolean workflowSyncAckSent = (Boolean) execution.getVariable(WORKFLOW_SYNC_ACK_SENT); + if (workflowSyncAckSent == null || workflowSyncAckSent == false) { + workflowActionBBTasks.sendSyncAck(execution); + execution.setVariable(WORKFLOW_SYNC_ACK_SENT, Boolean.TRUE); + } final String implementationString = execution.getBpmnModelElementInstance().getAttributeValue(SERVICE_TASK_IMPLEMENTATION_ATTRIBUTE); logger.debug("activity implementation String: {}", implementationString); @@ -135,7 +145,7 @@ public class ExecuteActivity implements JavaDelegate { } protected void buildAndThrowException(DelegateExecution execution, String msg, Exception ex) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue(), msg, ex); execution.setVariable("ExecuteActivityErrorMessage", msg); exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java index 48426fa725..e5f28aa4c3 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.adapter.vnf.tasks; +import org.onap.so.logger.LoggingAnchor; import org.apache.commons.lang3.StringUtils; import org.onap.so.adapters.vnfrest.CreateVfModuleResponse; import org.onap.so.adapters.vnfrest.CreateVolumeGroupResponse; @@ -171,8 +172,8 @@ public class VnfAdapterImpl { SAXSource source = new SAXSource(xmlReader, inputSource); return jaxbUnmarshaller.unmarshal(source); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(), ErrorCode.SchemaError.getValue(), - e.getMessage(), e); + logger.error(LoggingAnchor.THREE, MessageEnum.GENERAL_EXCEPTION.toString(), + ErrorCode.SchemaError.getValue(), e.getMessage(), e); throw new MarshallerException("Error parsing VNF Adapter response. " + e.getMessage(), ErrorCode.SchemaError.getValue(), e); } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorInstantiateVnfmNodeTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorInstantiateVnfmNodeTask.java new file mode 100644 index 0000000000..b885cc2ee5 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorInstantiateVnfmNodeTask.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; + +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.CREATE_VNF_NODE_STATUS; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.VNF_CREATED; +import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; +import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.client.orchestration.AAIVnfResources; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * @author waqas.ikram@est.tech + * + */ +@Component +public class MonitorInstantiateVnfmNodeTask extends MonitorVnfmNodeTask { + + @Autowired + public MonitorInstantiateVnfmNodeTask(final ExtractPojosForBB extractPojosForBB, + final ExceptionBuilder exceptionUtil, final AAIVnfResources aaiVnfResources) { + super(extractPojosForBB, exceptionUtil, aaiVnfResources); + } + + @Override + public String getNodeStatusVariableName() { + return CREATE_VNF_NODE_STATUS; + } + + @Override + public boolean isOrchestrationStatusValid(final String orchestrationStatus) { + return VNF_CREATED.equalsIgnoreCase(orchestrationStatus); + } + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorTerminateVnfmNodeTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorTerminateVnfmNodeTask.java new file mode 100644 index 0000000000..34296c20d6 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorTerminateVnfmNodeTask.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; + +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.DELETE_VNF_NODE_STATUS; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.VNF_ASSIGNED; +import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; +import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.client.orchestration.AAIVnfResources; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * @author waqas.ikram@est.tech + * + */ +@Component +public class MonitorTerminateVnfmNodeTask extends MonitorVnfmNodeTask { + + @Autowired + public MonitorTerminateVnfmNodeTask(final ExtractPojosForBB extractPojosForBB, final ExceptionBuilder exceptionUtil, + final AAIVnfResources aaiVnfResources) { + super(extractPojosForBB, exceptionUtil, aaiVnfResources); + } + + @Override + public String getNodeStatusVariableName() { + return DELETE_VNF_NODE_STATUS; + } + + @Override + public boolean isOrchestrationStatusValid(final String orchestrationStatus) { + return VNF_ASSIGNED.equalsIgnoreCase(orchestrationStatus); + } + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTask.java index 4645680fc2..30f0d38754 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTask.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmCreateJobTask.java @@ -1,8 +1,8 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Ericsson. All rights reserved. + * Copyright (C) 2019 Ericsson. All rights reserved. * ================================================================================ - * Modifications Copyright (c) 2019 Samsung + * Copyright (C) 2019 Samsung * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,6 @@ * 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.bpmn.infrastructure.adapter.vnfm.tasks; @@ -55,11 +53,18 @@ public class MonitorVnfmCreateJobTask extends MonitorVnfmJobTask { * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl} */ public void getCurrentOperationStatus(final BuildingBlockExecution execution) { - LOGGER.debug("Executing getCurrentOperationStatus ..."); - final CreateVnfResponse vnfInstantiateResponse = execution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME); - execution.setVariable(OPERATION_STATUS_PARAM_NAME, - getOperationStatus(execution, vnfInstantiateResponse.getJobId())); - LOGGER.debug("Finished executing getCurrentOperationStatus ..."); + try { + LOGGER.debug("Executing getCurrentOperationStatus ..."); + final CreateVnfResponse vnfInstantiateResponse = execution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME); + execution.setVariable(OPERATION_STATUS_PARAM_NAME, + getOperationStatus(execution, vnfInstantiateResponse.getJobId())); + LOGGER.debug("Finished executing getCurrentOperationStatus ..."); + } catch (final Exception exception) { + final String message = "Unable to invoke get current Operation status"; + LOGGER.error(message); + exceptionUtil.buildAndThrowWorkflowException(execution, 1209, message); + + } } /** diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTask.java index e91f362d53..8fecb81d75 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTask.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmDeleteJobTask.java @@ -1,8 +1,8 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Ericsson. All rights reserved. + * Copyright (C) 2019 Ericsson. All rights reserved. * ================================================================================ - * Modifications Copyright (c) 2019 Samsung + * Copyright (C) 2019 Samsung * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,8 +15,6 @@ * 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.bpmn.infrastructure.adapter.vnfm.tasks; @@ -56,10 +54,18 @@ public class MonitorVnfmDeleteJobTask extends MonitorVnfmJobTask { * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl} */ public void getCurrentOperationStatus(final BuildingBlockExecution execution) { - LOGGER.debug("Executing getCurrentOperationStatus ..."); - final DeleteVnfResponse deleteVnfResponse = execution.getVariable(Constants.DELETE_VNF_RESPONSE_PARAM_NAME); - execution.setVariable(OPERATION_STATUS_PARAM_NAME, getOperationStatus(execution, deleteVnfResponse.getJobId())); - LOGGER.debug("Finished executing getCurrentOperationStatus ..."); + try { + LOGGER.debug("Executing getCurrentOperationStatus ..."); + final DeleteVnfResponse deleteVnfResponse = execution.getVariable(Constants.DELETE_VNF_RESPONSE_PARAM_NAME); + execution.setVariable(OPERATION_STATUS_PARAM_NAME, + getOperationStatus(execution, deleteVnfResponse.getJobId())); + LOGGER.debug("Finished executing getCurrentOperationStatus ..."); + } catch (final Exception exception) { + final String message = "Unable to invoke get current Operation status"; + LOGGER.error(message); + exceptionUtil.buildAndThrowWorkflowException(execution, 1216, message); + + } } /** diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeTask.java index 65b05e21f5..a7a4eadb33 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeTask.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeTask.java @@ -19,38 +19,39 @@ */ package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; -import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.CREATE_VNF_NODE_STATUS; -import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.DELETE_VNF_NODE_STATUS; -import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.VNF_ASSIGNED; -import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.VNF_CREATED; import static org.onap.so.bpmn.servicedecomposition.entities.ResourceKey.GENERIC_VNF_ID; +import java.util.Optional; import org.onap.aai.domain.yang.GenericVnf; import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.exception.GenericVnfNotFoundException; import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.client.orchestration.AAIVnfResources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; /** * * @author Lathishbabu Ganesan (lathishbabu.ganesan@est.tech) + * @author Waqas Ikram (waqas.ikram@est.tech) * */ -@Component -public class MonitorVnfmNodeTask { +public abstract class MonitorVnfmNodeTask { private static final Logger LOGGER = LoggerFactory.getLogger(MonitorVnfmNodeTask.class); private final ExtractPojosForBB extractPojosForBB; private final ExceptionBuilder exceptionUtil; + private final AAIVnfResources aaiVnfResources; @Autowired - public MonitorVnfmNodeTask(final ExtractPojosForBB extractPojosForBB, final ExceptionBuilder exceptionUtil) { + public MonitorVnfmNodeTask(final ExtractPojosForBB extractPojosForBB, final ExceptionBuilder exceptionUtil, + final AAIVnfResources aaiVnfResources) { this.exceptionUtil = exceptionUtil; this.extractPojosForBB = extractPojosForBB; + this.aaiVnfResources = aaiVnfResources; } /** @@ -61,11 +62,23 @@ public class MonitorVnfmNodeTask { public void getNodeStatus(final BuildingBlockExecution execution) { try { LOGGER.debug("Executing getNodeStatus ..."); - final GenericVnf vnf = extractPojosForBB.extractByKey(execution, GENERIC_VNF_ID); - String orchestrationStatus = vnf.getOrchestrationStatus(); - LOGGER.debug("Orchestration Status in AAI {}", orchestrationStatus); - execution.setVariable(CREATE_VNF_NODE_STATUS, VNF_CREATED.equalsIgnoreCase(orchestrationStatus)); - execution.setVariable(DELETE_VNF_NODE_STATUS, VNF_ASSIGNED.equalsIgnoreCase(orchestrationStatus)); + + final org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf = + extractPojosForBB.extractByKey(execution, GENERIC_VNF_ID); + + final String vnfId = vnf.getVnfId(); + LOGGER.debug("Query A&AI for generic VNF using vnfID: {}", vnfId); + final Optional<GenericVnf> aaiGenericVnfOptional = aaiVnfResources.getGenericVnf(vnfId); + + if (!aaiGenericVnfOptional.isPresent()) { + throw new GenericVnfNotFoundException("Unable to find generic vnf in A&AI using vnfID: " + vnfId); + } + final GenericVnf genericVnf = aaiGenericVnfOptional.get(); + final String orchestrationStatus = genericVnf.getOrchestrationStatus(); + LOGGER.debug("Found generic vnf with orchestration status : {}", orchestrationStatus); + + execution.setVariable(getNodeStatusVariableName(), isOrchestrationStatusValid(orchestrationStatus)); + } catch (final Exception exception) { LOGGER.error("Unable to get vnf from AAI", exception); exceptionUtil.buildAndThrowWorkflowException(execution, 1220, exception); @@ -73,6 +86,20 @@ public class MonitorVnfmNodeTask { } /** + * Get variable to store in execution context + * + * @return the variable name + */ + public abstract String getNodeStatusVariableName(); + + /** + * @param orchestrationStatus the orchestration status from A&AI + * @return true if valid + */ + public abstract boolean isOrchestrationStatusValid(final String orchestrationStatus); + + + /** * Log and throw exception on timeout for job status * * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImpl.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImpl.java index e0176eb802..32516c1dcb 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImpl.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImpl.java @@ -146,7 +146,7 @@ public class VnfmAdapterServiceProviderImpl implements VnfmAdapterServiceProvide return Optional.of(response.getBody()); } catch (final RestProcessingException | InvalidRestRequestException httpInvocationException) { LOGGER.error("Unexpected error while processing job request", httpInvocationException); - return Optional.absent(); + throw httpInvocationException; } } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/exception/GenericVnfNotFoundException.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/exception/GenericVnfNotFoundException.java new file mode 100644 index 0000000000..d33d0bc895 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/exception/GenericVnfNotFoundException.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.exception; + +/** + * @author waqas.ikram@est.tech + * + */ +public class GenericVnfNotFoundException extends Exception { + private static final long serialVersionUID = -2049370314818025597L; + + public GenericVnfNotFoundException(final String message) { + super(message); + } + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java index f9bd8c546f..eddcc94e71 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java @@ -24,6 +24,7 @@ package org.onap.so.bpmn.infrastructure.appc.tasks; import java.util.HashMap; import java.util.Optional; +import org.onap.so.logger.LoggingAnchor; import org.onap.appc.client.lcm.model.Action; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; @@ -140,7 +141,7 @@ public class AppcRunTasks { appcMessage = appCClient.getErrorMessage(); mapRollbackVariables(execution, action, appcCode); } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "Caught exception in runAppcCommand", "BPMN", ErrorCode.UnknownError.getValue(), "APPC Error", e); appcMessage = e.getMessage(); } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java index a223259d4d..62878fd4f7 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java @@ -60,6 +60,16 @@ public class AuditTasks { } } + public void isDeleteAuditNeeded(BuildingBlockExecution execution) { + try { + logger.debug("deleteAuditInventoryNeeded Value: {}", env.getProperty("mso.infra.deleteAuditInventory")); + execution.setVariable("auditInventoryNeeded", + Boolean.parseBoolean(env.getProperty("mso.infra.deleteAuditInventory"))); + } catch (Exception ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + } + public void setupAuditVariable(BuildingBlockExecution execution) { try { execution.setVariable("auditInventory", createAuditInventory(execution)); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnf.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnf.java index 8a24330093..bc71fc6f67 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnf.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnf.java @@ -20,6 +20,7 @@ package org.onap.so.bpmn.infrastructure.flowspecific.tasks; +import java.util.List; import java.util.Map; import java.util.UUID; import org.onap.so.bpmn.common.BuildingBlockExecution; @@ -68,7 +69,8 @@ public class ConfigAssignVnf { ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); - Map<String, Object> userParams = execution.getGeneralBuildingBlock().getRequestContext().getUserParams(); + List<Map<String, Object>> userParams = + execution.getGeneralBuildingBlock().getRequestContext().getRequestParameters().getUserParams(); ConfigAssignPropertiesForVnf configAssignPropertiesForVnf = new ConfigAssignPropertiesForVnf(); configAssignPropertiesForVnf.setServiceInstanceId(serviceInstance.getServiceInstanceId()); @@ -79,16 +81,19 @@ public class ConfigAssignVnf { configAssignPropertiesForVnf.setVnfId(vnf.getVnfId()); configAssignPropertiesForVnf.setVnfName(vnf.getVnfName()); - for (Map.Entry<String, Object> entry : userParams.entrySet()) { - configAssignPropertiesForVnf.setUserParam(entry.getKey(), entry.getValue()); + for (Map<String, Object> params : userParams) { + for (Map.Entry<String, Object> entry : params.entrySet()) { + configAssignPropertiesForVnf.setUserParam(entry.getKey(), entry.getValue()); + } } ConfigAssignRequestVnf configAssignRequestVnf = new ConfigAssignRequestVnf(); configAssignRequestVnf.setResolutionKey(vnf.getVnfName()); configAssignRequestVnf.setConfigAssignPropertiesForVnf(configAssignPropertiesForVnf); - String blueprintName = vnf.getBlueprintName(); - String blueprintVersion = vnf.getBlueprintVersion(); + String blueprintName = vnf.getModelInfoGenericVnf().getBlueprintName(); + String blueprintVersion = vnf.getModelInfoGenericVnf().getBlueprintVersion(); + logger.debug(" BlueprintName : " + blueprintName + " BlueprintVersion : " + blueprintVersion); AbstractCDSPropertiesBean abstractCDSPropertiesBean = new AbstractCDSPropertiesBean(); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnf.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnf.java index 4ec8b932c0..cdbe0db57c 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnf.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnf.java @@ -1,15 +1,20 @@ -/* - * ============LICENSE_START======================================================= ONAP : SO - * ================================================================================ Copyright 2019 TechMahindra - * ================================================================================= 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_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 TechMahindra + * ================================================================================ + * 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========================================================= */ @@ -92,8 +97,10 @@ public class ConfigDeployVnf { configDeployRequestVnf.setResolutionKey(vnf.getVnfName()); configDeployRequestVnf.setConfigDeployPropertiesForVnf(configDeployPropertiesForVnf); - String blueprintName = vnf.getBlueprintName(); - String blueprintVersion = vnf.getBlueprintVersion(); + String blueprintName = vnf.getModelInfoGenericVnf().getBlueprintName(); + String blueprintVersion = vnf.getModelInfoGenericVnf().getBlueprintVersion(); + logger.debug(" BlueprintName : " + blueprintName + " BlueprintVersion : " + blueprintVersion); + AbstractCDSPropertiesBean abstractCDSPropertiesBean = new AbstractCDSPropertiesBean(); abstractCDSPropertiesBean.setBlueprintName(blueprintName); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOut.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOut.java index 0ad88d0676..ff9d7376de 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOut.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOut.java @@ -25,6 +25,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import org.onap.so.logger.LoggingAnchor; import org.onap.appc.client.lcm.model.Action; import org.onap.so.bpmn.appc.payload.beans.ConfigScaleOutPayload; import org.onap.so.bpmn.appc.payload.beans.RequestParametersConfigScaleOut; @@ -152,7 +153,7 @@ public class ConfigurationScaleOut { appcMessage = appCClient.getErrorMessage(); } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "Caught exception in runAppcCommand in ConfigurationScaleOut", "BPMN", ErrorCode.UnknownError.getValue(), "APPC Error", e); appcMessage = e.getMessage(); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheck.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheck.java index 8f0c809e1f..1a7d22c0dd 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheck.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheck.java @@ -23,6 +23,7 @@ package org.onap.so.bpmn.infrastructure.flowspecific.tasks; import java.util.HashMap; import java.util.Optional; +import org.onap.so.logger.LoggingAnchor; import org.camunda.bpm.engine.delegate.BpmnError; import org.onap.appc.client.lcm.model.Action; import org.onap.so.bpmn.common.BuildingBlockExecution; @@ -114,19 +115,19 @@ public class GenericVnfHealthCheck { appcCode = appCClient.getErrorCode(); appcMessage = appCClient.getErrorMessage(); } catch (BpmnError ex) { - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Caught exception in GenericVnfHealthCheck", "BPMN", ErrorCode.UnknownError.getValue(), ex); appcMessage = ex.getMessage(); exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage); } catch (Exception e) { if (e instanceof java.util.concurrent.TimeoutException) { appcMessage = "Request to APPC timed out. "; - logger.error("{} {} {} {} {}", MessageEnum.RA_CONNECTION_EXCEPTION.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_CONNECTION_EXCEPTION.toString(), "Caught timedOut exception in runAppcCommand in GenericVnfHealthCheck", "BPMN", ErrorCode.UnknownError.getValue(), "APPC Error", e); throw e; } else { - logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(), "Caught exception in runAppcCommand in GenericVnfHealthCheck", "BPMN", ErrorCode.UnknownError.getValue(), "APPC Error", e); appcMessage = e.getMessage(); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasks.java index 61fc8ffc48..17089be571 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasks.java @@ -1,7 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.infrastructure.manualhandling.tasks; import java.util.Map; import java.util.HashMap; +import org.onap.so.logger.LoggingAnchor; import org.camunda.bpm.engine.TaskService; import org.camunda.bpm.engine.delegate.BpmnError; import org.camunda.bpm.engine.delegate.DelegateTask; @@ -187,11 +208,11 @@ public class ManualHandlingTasks { ticket.createTicket(); } catch (BpmnError e) { String msg = "BPMN error in createAOTSTicket " + e.getMessage(); - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", ErrorCode.UnknownError.getValue()); } catch (Exception ex) { String msg = "Exception in createExternalTicket " + ex.getMessage(); - logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", ErrorCode.UnknownError.getValue()); } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasks.java index d248ad5443..155455e654 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasks.java @@ -20,12 +20,28 @@ package org.onap.so.bpmn.infrastructure.namingservice.tasks; - +import java.util.List; +import java.util.Optional; +import org.onap.aai.domain.yang.Zone; import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.InjectionHelper; +import org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration; import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup; +import org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; +import org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBinding; +import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; +import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils; import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; +import org.onap.so.client.aai.AAIObjectType; +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.exception.ExceptionBuilder; +import org.onap.so.client.namingservice.NamingRequestObject; +import org.onap.so.client.namingservice.NamingServiceConstants; import org.onap.so.client.orchestration.NamingServiceResources; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -40,6 +56,14 @@ public class NamingServiceCreateTasks { @Autowired private NamingServiceResources namingServiceResources; + @Autowired + protected InjectionHelper injectionHelper; + @Autowired + protected BBInputSetupUtils bbInputSetupUtils; + + public void setBbInputSetupUtils(BBInputSetupUtils bbInputSetupUtils) { + this.bbInputSetupUtils = bbInputSetupUtils; + } public void createInstanceGroupName(BuildingBlockExecution execution) throws Exception { InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID); @@ -54,4 +78,46 @@ public class NamingServiceCreateTasks { } instanceGroup.setInstanceGroupName(generatedInstanceGroupName); } + + public void createWanTransportServiceName(BuildingBlockExecution execution) throws Exception { + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + NamingRequestObject namingRequestObject = new NamingRequestObject(); + namingRequestObject.setExternalKeyValue(serviceInstance.getServiceInstanceId()); + namingRequestObject.setNamingTypeValue(NamingServiceConstants.NAMING_TYPE_SERVICE); + namingRequestObject.setResourceNameValue(NamingServiceConstants.RESOURCE_NAME_SERVICE_INSTANCE_NAME); + namingRequestObject.setPolicyInstanceNameValue(serviceInstance.getModelInfoServiceInstance().getNamingPolicy()); + namingRequestObject.setServiceModelNameValue(serviceInstance.getModelInfoServiceInstance().getModelName()); + namingRequestObject.setModelVersionValue(serviceInstance.getModelInfoServiceInstance().getModelVersion()); + + String generatedWanTransportServiceName = ""; + try { + generatedWanTransportServiceName = namingServiceResources.generateServiceInstanceName(namingRequestObject); + } catch (Exception ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + serviceInstance.setServiceInstanceName(generatedWanTransportServiceName); + } + + public void createVpnBondingServiceName(BuildingBlockExecution execution) throws Exception { + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + L3Network network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); + VpnBinding vpnBinding = extractPojosForBB.extractByKey(execution, ResourceKey.VPN_ID); + NamingRequestObject namingRequestObject = new NamingRequestObject(); + namingRequestObject.setExternalKeyValue(serviceInstance.getServiceInstanceId()); + namingRequestObject.setPolicyInstanceNameValue(serviceInstance.getModelInfoServiceInstance().getNamingPolicy()); + namingRequestObject.setNamingTypeValue(NamingServiceConstants.NAMING_TYPE_SERVICE); + namingRequestObject.setServiceModelNameValue(serviceInstance.getModelInfoServiceInstance().getModelName()); + namingRequestObject.setModelVersionValue(serviceInstance.getModelInfoServiceInstance().getModelVersion()); + namingRequestObject.setNetworkNameValue(execution.getVariable(network.getNetworkName())); + namingRequestObject.setVpnNameValue(vpnBinding.getVpnName()); + namingRequestObject.setResourceNameValue(NamingServiceConstants.RESOURCE_NAME_SERVICE_INSTANCE_NAME); + + String generatedVpnBondingServiceName = ""; + try { + generatedVpnBondingServiceName = namingServiceResources.generateServiceInstanceName(namingRequestObject); + } catch (Exception ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + serviceInstance.setServiceInstanceName(generatedVpnBondingServiceName); + } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasks.java index 9a8c9df8b5..507e14e42a 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasks.java @@ -23,9 +23,11 @@ package org.onap.so.bpmn.infrastructure.namingservice.tasks; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.client.namingservice.NamingRequestObject; import org.onap.so.client.orchestration.NamingServiceResources; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -50,4 +52,16 @@ public class NamingServiceDeleteTasks { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } } + + public void deleteServiceInstanceName(BuildingBlockExecution execution) throws Exception { + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + NamingRequestObject namingRequestObject = new NamingRequestObject(); + namingRequestObject.setExternalKeyValue(serviceInstance.getServiceInstanceId()); + try { + namingServiceResources.deleteServiceInstanceName(namingRequestObject); + } catch (Exception ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + } + } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/exceptions/SDNCErrorResponseException.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/exceptions/SDNCErrorResponseException.java index d76d860b3b..b8f025aaa6 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/exceptions/SDNCErrorResponseException.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/exceptions/SDNCErrorResponseException.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.infrastructure.sdnc.exceptions; public class SDNCErrorResponseException extends Exception { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTasks.java index 32276891c7..e4dd35503e 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTasks.java @@ -22,6 +22,8 @@ package org.onap.so.bpmn.infrastructure.sdnc.tasks; +import java.net.URI; +import javax.ws.rs.core.UriBuilder; import org.onap.sdnc.northbound.client.model.GenericResourceApiNetworkOperationInformation; import org.onap.sdnc.northbound.client.model.GenericResourceApiVfModuleOperationInformation; import org.onap.sdnc.northbound.client.model.GenericResourceApiVnfOperationInformation; @@ -46,6 +48,7 @@ import org.onap.so.client.sdnc.endpoint.SDNCTopology; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component @@ -62,7 +65,8 @@ public class SDNCActivateTasks { private SDNCNetworkResources sdncNetworkResources; @Autowired private SDNCVfModuleResources sdncVfModuleResources; - + @Autowired + private Environment env; public void activateVnf(BuildingBlockExecution execution) { try { @@ -122,9 +126,12 @@ public class SDNCActivateTasks { vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); Customer customer = gBBInput.getCustomer(); CloudRegion cloudRegion = gBBInput.getCloudRegion(); - GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.activateVfModule(vfModule, vnf, - serviceInstance, customer, cloudRegion, requestContext); SDNCRequest sdncRequest = new SDNCRequest(); + UriBuilder builder = UriBuilder.fromPath(env.getRequiredProperty("mso.workflow.message.endpoint")) + .path(sdncRequest.getCorrelationName()).path(sdncRequest.getCorrelationValue()); + URI uri = builder.build(); + GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.activateVfModule(vfModule, vnf, + serviceInstance, customer, cloudRegion, requestContext, uri); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VFMODULE); execution.setVariable(SDNC_REQUEST, sdncRequest); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasks.java index 111f008159..c100cd6cee 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasks.java @@ -22,6 +22,8 @@ package org.onap.so.bpmn.infrastructure.sdnc.tasks; +import java.net.URI; +import javax.ws.rs.core.UriBuilder; import org.onap.sdnc.northbound.client.model.GenericResourceApiNetworkOperationInformation; import org.onap.sdnc.northbound.client.model.GenericResourceApiServiceOperationInformation; import org.onap.sdnc.northbound.client.model.GenericResourceApiVfModuleOperationInformation; @@ -49,6 +51,7 @@ import org.onap.so.client.sdnc.endpoint.SDNCTopology; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component @@ -67,6 +70,8 @@ public class SDNCAssignTasks { private ExtractPojosForBB extractPojosForBB; @Autowired private SDNCNetworkResources sdncNetworkResources; + @Autowired + private Environment env; public void assignServiceInstance(BuildingBlockExecution execution) { try { @@ -122,9 +127,12 @@ public class SDNCAssignTasks { } Customer customer = gBBInput.getCustomer(); CloudRegion cloudRegion = gBBInput.getCloudRegion(); - GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.assignVfModule(vfModule, - volumeGroup, vnf, serviceInstance, customer, cloudRegion, requestContext); SDNCRequest sdncRequest = new SDNCRequest(); + UriBuilder builder = UriBuilder.fromPath(env.getRequiredProperty("mso.workflow.message.endpoint")) + .path(sdncRequest.getCorrelationName()).path(sdncRequest.getCorrelationValue()); + URI uri = builder.build(); + GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.assignVfModule(vfModule, + volumeGroup, vnf, serviceInstance, customer, cloudRegion, requestContext, uri); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VFMODULE); execution.setVariable(SDNC_REQUEST, sdncRequest); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasks.java index 4ffb397707..acf48acdda 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasks.java @@ -20,6 +20,8 @@ package org.onap.so.bpmn.infrastructure.sdnc.tasks; +import java.net.URI; +import javax.ws.rs.core.UriBuilder; import org.onap.sdnc.northbound.client.model.GenericResourceApiNetworkOperationInformation; import org.onap.sdnc.northbound.client.model.GenericResourceApiServiceOperationInformation; import org.onap.sdnc.northbound.client.model.GenericResourceApiVfModuleOperationInformation; @@ -43,6 +45,7 @@ import org.onap.so.client.orchestration.SDNCVnfResources; import org.onap.so.client.sdnc.beans.SDNCRequest; import org.onap.so.client.sdnc.endpoint.SDNCTopology; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component @@ -60,6 +63,8 @@ public class SDNCChangeAssignTasks { private ExceptionBuilder exceptionUtil; @Autowired private SDNCVfModuleResources sdncVfModuleResources; + @Autowired + private Environment env; public void changeModelServiceInstance(BuildingBlockExecution execution) { try { @@ -121,9 +126,12 @@ public class SDNCChangeAssignTasks { GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); Customer customer = gBBInput.getCustomer(); - GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.changeAssignVfModule(vfModule, - vnf, serviceInstance, customer, cloudRegion, requestContext); SDNCRequest sdncRequest = new SDNCRequest(); + UriBuilder builder = UriBuilder.fromPath(env.getRequiredProperty("mso.workflow.message.endpoint")) + .path(sdncRequest.getCorrelationName()).path(sdncRequest.getCorrelationValue()); + URI uri = builder.build(); + GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.changeAssignVfModule(vfModule, + vnf, serviceInstance, customer, cloudRegion, requestContext, uri); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VFMODULE); execution.setVariable(SDNC_REQUEST, sdncRequest); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTasks.java index e587830c74..3fc25196e1 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTasks.java @@ -22,6 +22,8 @@ package org.onap.so.bpmn.infrastructure.sdnc.tasks; +import java.net.URI; +import javax.ws.rs.core.UriBuilder; import org.onap.sdnc.northbound.client.model.GenericResourceApiNetworkOperationInformation; import org.onap.sdnc.northbound.client.model.GenericResourceApiServiceOperationInformation; import org.onap.sdnc.northbound.client.model.GenericResourceApiVfModuleOperationInformation; @@ -47,6 +49,7 @@ import org.onap.so.client.sdnc.endpoint.SDNCTopology; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component @@ -65,6 +68,8 @@ public class SDNCDeactivateTasks { private ExceptionBuilder exceptionUtil; @Autowired private ExtractPojosForBB extractPojosForBB; + @Autowired + private Environment env; public void deactivateVfModule(BuildingBlockExecution execution) { try { @@ -76,9 +81,12 @@ public class SDNCDeactivateTasks { VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); Customer customer = gBBInput.getCustomer(); CloudRegion cloudRegion = gBBInput.getCloudRegion(); - GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.deactivateVfModule(vfModule, vnf, - serviceInstance, customer, cloudRegion, requestContext); SDNCRequest sdncRequest = new SDNCRequest(); + UriBuilder builder = UriBuilder.fromPath(env.getRequiredProperty("mso.workflow.message.endpoint")) + .path(sdncRequest.getCorrelationName()).path(sdncRequest.getCorrelationValue()); + URI uri = builder.build(); + GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.deactivateVfModule(vfModule, vnf, + serviceInstance, customer, cloudRegion, requestContext, uri); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VFMODULE); execution.setVariable(SDNC_REQUEST, sdncRequest); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasks.java index f32ffd72c3..cb761f4110 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasks.java @@ -21,8 +21,13 @@ package org.onap.so.bpmn.infrastructure.sdnc.tasks; import java.io.StringReader; +import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; import org.camunda.bpm.engine.delegate.DelegateExecution; @@ -98,12 +103,18 @@ public class SDNCRequestTasks { Document doc = db.parse(new InputSource(new StringReader(asyncRequest))); String finalMessageIndicator = getXmlElement(doc, "/input/ack-final-indicator"); + boolean isCallbackCompleted = convertIndicatorToBoolean(finalMessageIndicator); execution.setVariable(IS_CALLBACK_COMPLETED, isCallbackCompleted); if (isCallbackCompleted) { String responseCode = getXmlElement(doc, "/input/response-code"); - String responseMessage = getXmlElement(doc, "/input/response-message"); if (!SDNC_SUCCESS.equalsIgnoreCase(responseCode)) { + String responseMessage; + try { + responseMessage = getXmlElement(doc, "/input/response-message"); + } catch (Exception e) { + responseMessage = "Unknown Error in SDNC"; + } throw new SDNCErrorResponseException(responseMessage); } } @@ -126,8 +137,17 @@ public class SDNCRequestTasks { } protected String getXmlElement(Document doc, String exp) throws Exception { + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer transformer = tf.newTransformer(); + StringWriter writer = new StringWriter(); + transformer.transform(new DOMSource(doc), new StreamResult(writer)); + logger.debug(writer.getBuffer().toString()); XPath xPath = XPathFactory.newInstance().newXPath(); - return xPath.evaluate(exp, doc); + String result = xPath.evaluate(exp, doc); + if (result == null || result.isEmpty()) { + throw new Exception("XPath Failed to find element expression: " + exp); + } + return result; } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasks.java index fba189fcfc..7d5591af0f 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasks.java @@ -22,6 +22,8 @@ package org.onap.so.bpmn.infrastructure.sdnc.tasks; +import java.net.URI; +import javax.ws.rs.core.UriBuilder; import org.onap.sdnc.northbound.client.model.GenericResourceApiNetworkOperationInformation; import org.onap.sdnc.northbound.client.model.GenericResourceApiServiceOperationInformation; import org.onap.sdnc.northbound.client.model.GenericResourceApiVfModuleOperationInformation; @@ -47,6 +49,7 @@ import org.onap.so.client.sdnc.endpoint.SDNCTopology; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component @@ -65,6 +68,8 @@ public class SDNCUnassignTasks { private ExtractPojosForBB extractPojosForBB; @Autowired private SDNCNetworkResources sdncNetworkResources; + @Autowired + private Environment env; public void unassignServiceInstance(BuildingBlockExecution execution) { try { @@ -90,9 +95,12 @@ public class SDNCUnassignTasks { extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); - GenericResourceApiVfModuleOperationInformation req = - sdncVfModuleResources.unassignVfModule(vfModule, vnf, serviceInstance); SDNCRequest sdncRequest = new SDNCRequest(); + UriBuilder builder = UriBuilder.fromPath(env.getRequiredProperty("mso.workflow.message.endpoint")) + .path(sdncRequest.getCorrelationName()).path(sdncRequest.getCorrelationValue()); + URI uri = builder.build(); + GenericResourceApiVfModuleOperationInformation req = + sdncVfModuleResources.unassignVfModule(vfModule, vnf, serviceInstance, uri); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VFMODULE); execution.setVariable(SDNC_REQUEST, sdncRequest); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java index 47855eaa6e..fc3f2aec7a 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java @@ -23,8 +23,8 @@ package org.onap.so.bpmn.infrastructure.validations; import java.util.Optional; import java.util.regex.Pattern; import org.onap.so.bpmn.common.BuildingBlockExecution; -import org.onap.so.bpmn.common.validation.PreBuildingBlockValidator; -import org.onap.so.bpmn.common.validation.Skip; +import org.onap.so.bpmn.common.listener.Skip; +import org.onap.so.bpmn.common.listener.validation.PreBuildingBlockValidator; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.client.exception.ExceptionBuilder; import org.slf4j.Logger; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/VrfBondingServiceException.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/VrfBondingServiceException.java new file mode 100644 index 0000000000..0584472e14 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/VrfBondingServiceException.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.infrastructure.workflow.tasks; + +public class VrfBondingServiceException extends Exception { + /** + * + */ + private static final long serialVersionUID = -4277883464681291740L; + + public VrfBondingServiceException(String errorMessage) { + super(errorMessage); + } +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/VrfValidation.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/VrfValidation.java new file mode 100644 index 0000000000..1e0208b6ec --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/VrfValidation.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.infrastructure.workflow.tasks; + +import java.util.List; +import java.util.Optional; +import org.onap.aai.domain.yang.L3Network; +import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.db.catalog.beans.ConfigurationResourceCustomization; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class VrfValidation { + + @Autowired + protected BBInputSetupUtils bbInputSetupUtils; + + public void setBbInputSetupUtils(BBInputSetupUtils bbInputSetupUtils) { + this.bbInputSetupUtils = bbInputSetupUtils; + } + + protected void vrfServiceValidation(org.onap.so.db.catalog.beans.Service service) + throws VrfBondingServiceException { + if (!"BONDING".equalsIgnoreCase(service.getServiceType()) + || !"INFRASTRUCTURE-VPN".equalsIgnoreCase(service.getServiceRole())) { + throw new VrfBondingServiceException("Service: " + service.getModelName() + + " does not have service type of BONDING and does not have service role of INFRASTRUCTURE-VPN"); + } + } + + protected void vrfCatalogDbChecks(org.onap.so.db.catalog.beans.Service service) throws VrfBondingServiceException { + ConfigurationResourceCustomization configuration = getVrfConfiguration(service); + if (configuration == null || configuration.getServiceProxyResourceCustomization() == null + || configuration.getServiceProxyResourceCustomization().getSourceService() == null + || !configuration.getServiceProxyResourceCustomization().getSourceService().getServiceType() + .equalsIgnoreCase("TRANSPORT")) { + throw new VrfBondingServiceException("Service: " + service.getModelName() + + " does not have a configuration of type VRF-ENTRY and role INFRASTRUCTURE-CLOUD-VPN" + + ", and serviceProxy that does not have source service that has a serviceType of TRANSPORT)"); + } + } + + protected ConfigurationResourceCustomization getVrfConfiguration(org.onap.so.db.catalog.beans.Service service) { + for (ConfigurationResourceCustomization configuration : service.getConfigurationCustomizations()) { + if (configuration.getType() != null && configuration.getType().equalsIgnoreCase("VRF-ENTRY") + && configuration.getRole() != null + && configuration.getRole().equalsIgnoreCase("INFRASTRUCTURE-CLOUD-VPN")) { + return configuration; + } + } + return null; + } + + protected void aaiVpnBindingValidation(String relatedVpnId, org.onap.aai.domain.yang.VpnBinding aaiVpnBinding) + throws VrfBondingServiceException { + if (aaiVpnBinding == null) { + throw new VrfBondingServiceException("The infrastructure vpn " + relatedVpnId + " does not exist in A&AI."); + } else if (aaiVpnBinding.getVpnType() != null + && !aaiVpnBinding.getVpnType().equalsIgnoreCase("SERVICE-INFRASTRUCTURE")) { + throw new VrfBondingServiceException( + "VpnBinding: " + relatedVpnId + " does not have a vpn type of SERVICE-INFRASTRUCTURE."); + } + } + + protected void aaiAggregateRouteValidation(org.onap.aai.domain.yang.L3Network aaiLocalNetwork) + throws VrfBondingServiceException { + if (aaiLocalNetwork.getAggregateRoutes() == null + || aaiLocalNetwork.getAggregateRoutes().getAggregateRoute() == null) { + return; + } + if (aaiLocalNetwork.getAggregateRoutes().getAggregateRoute().size() == 1 && !aaiLocalNetwork + .getAggregateRoutes().getAggregateRoute().get(0).getIpVersion().equalsIgnoreCase("4")) { + throw new VrfBondingServiceException("LocalNetwork: " + aaiLocalNetwork.getNetworkId() + + " has 1 aggregate route but the Ip version of aggregate route is : " + + aaiLocalNetwork.getAggregateRoutes().getAggregateRoute().get(0).getIpVersion() + " and is not 4"); + } else if (aaiLocalNetwork.getAggregateRoutes().getAggregateRoute().size() == 2 + && !ipVersionValidation(aaiLocalNetwork.getAggregateRoutes().getAggregateRoute().get(0).getIpVersion(), + aaiLocalNetwork.getAggregateRoutes().getAggregateRoute().get(1).getIpVersion())) { + throw new VrfBondingServiceException("LocalNetwork: " + aaiLocalNetwork.getNetworkId() + + " has 2 aggregate routes but the combination of the Ip versions for the aggregate routes did not match the ip version of one of them to be 4 and one to be 6"); + } else if (aaiLocalNetwork.getAggregateRoutes().getAggregateRoute().size() > 2) { + throw new VrfBondingServiceException( + "LocalNetwork: " + aaiLocalNetwork.getNetworkId() + " either has more than 2 aggregate routes"); + } + } + + protected void aaiNetworkValidation(String relatedNetworkid, org.onap.aai.domain.yang.L3Network aaiLocalNetwork) + throws VrfBondingServiceException { + if (aaiLocalNetwork == null) { + throw new VrfBondingServiceException("The local network " + relatedNetworkid + " does not exist in A&AI."); + } + } + + protected void aaiSubnetValidation(org.onap.aai.domain.yang.L3Network aaiLocalNetwork) + throws VrfBondingServiceException { + if (aaiLocalNetwork.getSubnets() == null || aaiLocalNetwork.getSubnets().getSubnet() == null) { + throw new VrfBondingServiceException("LocalNetwork: " + aaiLocalNetwork.getNetworkId() + " has no subnets"); + } else if (aaiLocalNetwork.getSubnets().getSubnet().size() == 1 + && !aaiLocalNetwork.getSubnets().getSubnet().get(0).getIpVersion().equalsIgnoreCase("4")) { + throw new VrfBondingServiceException("LocalNetwork: " + aaiLocalNetwork.getNetworkId() + + " has 1 subnet but the Ip version of subnet is : " + + aaiLocalNetwork.getSubnets().getSubnet().get(0).getIpVersion() + " and is not 4"); + } else if (aaiLocalNetwork.getSubnets().getSubnet().size() == 2 + && !ipVersionValidation(aaiLocalNetwork.getSubnets().getSubnet().get(0).getIpVersion(), + aaiLocalNetwork.getSubnets().getSubnet().get(1).getIpVersion())) { + throw new VrfBondingServiceException("LocalNetwork: " + aaiLocalNetwork.getNetworkId() + + " has 2 subnets but the combination of the Ip versions for the subnets did not match the ip version of one of them to be 4 and one to be 6"); + } else if (aaiLocalNetwork.getSubnets().getSubnet().isEmpty() + || aaiLocalNetwork.getSubnets().getSubnet().size() > 2) { + throw new VrfBondingServiceException("LocalNetwork: " + aaiLocalNetwork.getNetworkId() + + " either has no subnets or more than 2 subnets"); + } + } + + protected boolean ipVersionValidation(String ipVersion1, String ipVersion2) { + return (ipVersion1.equalsIgnoreCase("4") && ipVersion2.equalsIgnoreCase("6")) + || (ipVersion1.equalsIgnoreCase("6") && ipVersion2.equalsIgnoreCase("4")); + } + + protected void aaiRouteTargetValidation(L3Network aaiLocalNetwork) throws VrfBondingServiceException { + AAIResultWrapper networkWrapper = new AAIResultWrapper(aaiLocalNetwork); + if (networkWrapper.getRelationships().isPresent()) { + List<AAIResourceUri> vpnBindingUris = + networkWrapper.getRelationships().get().getRelatedUris(AAIObjectType.VPN_BINDING); + if (!vpnBindingUris.isEmpty()) { + Optional<org.onap.aai.domain.yang.VpnBinding> vpnBindingOp = + bbInputSetupUtils.getAAIResourceDepthOne(vpnBindingUris.get(0)) + .asBean(org.onap.aai.domain.yang.VpnBinding.class); + if (vpnBindingOp.isPresent()) { + org.onap.aai.domain.yang.VpnBinding vpnBinding = vpnBindingOp.get(); + if (vpnBinding.getRouteTargets() != null + && !vpnBinding.getRouteTargets().getRouteTarget().isEmpty()) { + return; + } + } + } + } + throw new VrfBondingServiceException("The Local Network: " + aaiLocalNetwork.getNetworkId() + + " does not have vpn binding and/or RT information"); + } +} 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 2fc301f9d7..2e9e215ee0 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 @@ -35,13 +35,14 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.javatuples.Pair; -import org.slf4j.LoggerFactory; import org.onap.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.L3Network; import org.onap.aai.domain.yang.Relationship; import org.onap.aai.domain.yang.ServiceInstance; import org.onap.aai.domain.yang.Vnfc; import org.onap.aai.domain.yang.VolumeGroup; +import org.onap.aai.domain.yang.VpnBinding; +import org.onap.so.bpmn.common.BBConstants; import org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration; import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock; @@ -61,9 +62,11 @@ import org.onap.so.client.orchestration.AAIConfigurationResources; import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization; import org.onap.so.db.catalog.beans.CollectionResourceCustomization; import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization; +import org.onap.so.db.catalog.beans.ConfigurationResourceCustomization; +import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization; import org.onap.so.db.catalog.beans.CvnfcCustomization; +import org.onap.so.db.catalog.beans.ServiceProxyResourceCustomization; import org.onap.so.db.catalog.beans.VfModuleCustomization; -import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization; import org.onap.so.db.catalog.beans.macro.NorthBoundRequest; import org.onap.so.db.catalog.beans.macro.OrchestrationFlow; import org.onap.so.db.catalog.client.CatalogDbClient; @@ -78,9 +81,11 @@ import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.onap.so.serviceinstancebeans.VfModules; import org.onap.so.serviceinstancebeans.Vnfs; import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @Component @@ -91,15 +96,6 @@ public class WorkflowAction { private static final String VF_MODULES = "vfModules"; private static final String WORKFLOW_ACTION_WAS_UNABLE_TO_VERIFY_IF_THE_INSTANCE_NAME_ALREADY_EXIST_IN_AAI = "WorkflowAction was unable to verify if the instance name already exist in AAI."; - private static final String G_ORCHESTRATION_FLOW = "gOrchestrationFlow"; - private static final String G_ACTION = "requestAction"; - private static final String G_CURRENT_SEQUENCE = "gCurrentSequence"; - private static final String G_REQUEST_ID = "mso-request-id"; - private static final String G_BPMN_REQUEST = "bpmnRequest"; - private static final String G_ALACARTE = "aLaCarte"; - private static final String G_APIVERSION = "apiVersion"; - private static final String G_URI = "requestUri"; - private static final String G_ISTOPLEVELFLOW = "isTopLevelFlow"; private static final String VNF_TYPE = "vnfType"; private static final String SERVICE = "Service"; private static final String VNF = "Vnf"; @@ -115,8 +111,8 @@ public class WorkflowAction { "vnfs|vfModules|networks|networkCollections|volumeGroups|serviceInstances|instanceGroups"; private static final String HOMINGSOLUTION = "Homing_Solution"; private static final String FABRIC_CONFIGURATION = "FabricConfiguration"; - private static final String G_SERVICE_TYPE = "serviceType"; private static final String SERVICE_TYPE_TRANSPORT = "TRANSPORT"; + private static final String SERVICE_TYPE_BONDING = "BONDING"; private static final Logger logger = LoggerFactory.getLogger(WorkflowAction.class); @Autowired @@ -131,6 +127,8 @@ public class WorkflowAction { private AAIConfigurationResources aaiConfigurationResources; @Autowired private WorkflowActionExtractResourcesAAI workflowActionUtils; + @Autowired + private VrfValidation vrfValidation; @Autowired private Environment environment; @@ -145,17 +143,19 @@ public class WorkflowAction { } public void selectExecutionList(DelegateExecution execution) throws Exception { - final String requestAction = (String) execution.getVariable(G_ACTION); - final String requestId = (String) execution.getVariable(G_REQUEST_ID); - final String bpmnRequest = (String) execution.getVariable(G_BPMN_REQUEST); - final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE); - final String apiVersion = (String) execution.getVariable(G_APIVERSION); - final String uri = (String) execution.getVariable(G_URI); + final String requestAction = (String) execution.getVariable(BBConstants.G_ACTION); + final String requestId = (String) execution.getVariable(BBConstants.G_REQUEST_ID); + final String bpmnRequest = (String) execution.getVariable(BBConstants.G_BPMN_REQUEST); + final boolean aLaCarte = (boolean) execution.getVariable(BBConstants.G_ALACARTE); + final String apiVersion = (String) execution.getVariable(BBConstants.G_APIVERSION); + final String uri = (String) execution.getVariable(BBConstants.G_URI); final String vnfType = (String) execution.getVariable(VNF_TYPE); String serviceInstanceId = (String) execution.getVariable("serviceInstanceId"); - final String serviceType = Optional.ofNullable((String) execution.getVariable(G_SERVICE_TYPE)).orElse(""); + final String serviceType = + Optional.ofNullable((String) execution.getVariable(BBConstants.G_SERVICE_TYPE)).orElse(""); - List<OrchestrationFlow> orchFlows = (List<OrchestrationFlow>) execution.getVariable(G_ORCHESTRATION_FLOW); + List<OrchestrationFlow> orchFlows = + (List<OrchestrationFlow>) execution.getVariable(BBConstants.G_ORCHESTRATION_FLOW); List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>(); WorkflowResourceIds workflowResourceIds = populateResourceIdsFromApiHandler(execution); List<Pair<WorkflowType, String>> aaiResourceIds = new ArrayList<>(); @@ -166,7 +166,7 @@ public class WorkflowAction { try { ObjectMapper mapper = new ObjectMapper(); - execution.setVariable(G_ISTOPLEVELFLOW, true); + execution.setVariable(BBConstants.G_ISTOPLEVELFLOW, true); ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class); RequestDetails requestDetails = sIRequest.getRequestDetails(); String cloudOwner = ""; @@ -270,7 +270,7 @@ public class WorkflowAction { foundRelated = traverseUserParamsService(execution, resourceCounter, sIRequest, requestAction); } if (!foundRelated) { - traverseCatalogDbService(execution, sIRequest, resourceCounter); + traverseCatalogDbService(execution, sIRequest, resourceCounter, aaiResourceIds); } } else if (resourceType == WorkflowType.SERVICE && (requestAction.equalsIgnoreCase("activateInstance") || requestAction.equalsIgnoreCase("unassignInstance") @@ -354,14 +354,14 @@ public class WorkflowAction { flowNames.add(ebb.getBuildingBlock().getBpmnFlowName()); } execution.setVariable("flowNames", flowNames); - execution.setVariable(G_CURRENT_SEQUENCE, 0); + execution.setVariable(BBConstants.G_CURRENT_SEQUENCE, 0); execution.setVariable("retryCount", 0); execution.setVariable("isRollback", false); execution.setVariable("flowsToExecute", flowsToExecute); execution.setVariable("isRollbackComplete", false); } catch (Exception ex) { - buildAndThrowException(execution, "Exception in create execution list " + ex.getMessage(), ex); + buildAndThrowException(execution, "Exception in create execution list. " + ex.getMessage(), ex); } } @@ -415,7 +415,7 @@ public class WorkflowAction { protected boolean isConfiguration(List<OrchestrationFlow> orchFlows) { for (OrchestrationFlow flow : orchFlows) { - if (flow.getFlowName().contains("Configuration")) { + if (flow.getFlowName().contains("Configuration") && !flow.getFlowName().equals("ConfigurationScaleOutBB")) { return true; } } @@ -616,97 +616,179 @@ public class WorkflowAction { } protected void traverseCatalogDbService(DelegateExecution execution, ServiceInstancesRequest sIRequest, - List<Resource> resourceCounter) { + List<Resource> resourceCounter, List<Pair<WorkflowType, String>> aaiResourceIds) + throws JsonProcessingException, VrfBondingServiceException { String modelUUID = sIRequest.getRequestDetails().getModelInfo().getModelVersionId(); org.onap.so.db.catalog.beans.Service service = catalogDbClient.getServiceByID(modelUUID); if (service == null) { buildAndThrowException(execution, "Could not find the service model in catalog db."); } else { resourceCounter.add(new Resource(WorkflowType.SERVICE, service.getModelUUID(), false)); - if (service.getVnfCustomizations() == null || service.getVnfCustomizations().isEmpty()) { - List<CollectionResourceCustomization> customizations = service.getCollectionResourceCustomizations(); - if (customizations.isEmpty()) { - logger.debug("No Collections found. CollectionResourceCustomization list is empty."); - } else { - CollectionResourceCustomization collectionResourceCustomization = - findCatalogNetworkCollection(execution, service); - if (collectionResourceCustomization != null) { - resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION, - collectionResourceCustomization.getModelCustomizationUUID(), false)); - logger.debug("Found a network collection"); - if (collectionResourceCustomization.getCollectionResource() != null) { - if (collectionResourceCustomization.getCollectionResource().getInstanceGroup() != null) { - String toscaNodeType = collectionResourceCustomization.getCollectionResource() - .getInstanceGroup().getToscaNodeType(); - if (toscaNodeType != null && toscaNodeType.contains("NetworkCollection")) { - int minNetworks = 0; - org.onap.so.db.catalog.beans.InstanceGroup instanceGroup = - collectionResourceCustomization.getCollectionResource().getInstanceGroup(); - CollectionResourceInstanceGroupCustomization collectionInstCust = null; - if (!instanceGroup.getCollectionInstanceGroupCustomizations().isEmpty()) { - for (CollectionResourceInstanceGroupCustomization collectionInstanceGroupTemp : instanceGroup - .getCollectionInstanceGroupCustomizations()) { - if (collectionInstanceGroupTemp.getModelCustomizationUUID() - .equalsIgnoreCase(collectionResourceCustomization - .getModelCustomizationUUID())) { - collectionInstCust = collectionInstanceGroupTemp; - break; - } - } - if (collectionInstCust != null - && collectionInstCust.getSubInterfaceNetworkQuantity() != null) { - minNetworks = collectionInstCust.getSubInterfaceNetworkQuantity(); - } - } - logger.debug("minNetworks: {}", minNetworks); - CollectionNetworkResourceCustomization collectionNetworkResourceCust = null; - for (CollectionNetworkResourceCustomization collectionNetworkTemp : instanceGroup - .getCollectionNetworkResourceCustomizations()) { - if (collectionNetworkTemp.getNetworkResourceCustomization() - .getModelCustomizationUUID().equalsIgnoreCase( - collectionResourceCustomization.getModelCustomizationUUID())) { - collectionNetworkResourceCust = collectionNetworkTemp; + RelatedInstance relatedVpnBinding = + bbInputSetupUtils.getRelatedInstanceByType(sIRequest.getRequestDetails(), ModelType.vpnBinding); + RelatedInstance relatedLocalNetwork = + bbInputSetupUtils.getRelatedInstanceByType(sIRequest.getRequestDetails(), ModelType.network); + if (relatedVpnBinding != null && relatedLocalNetwork != null) { + traverseVrfConfiguration(execution, aaiResourceIds, resourceCounter, service, relatedVpnBinding, + relatedLocalNetwork); + } else { + traverseNetworkCollection(execution, resourceCounter, service); + } + } + } + + protected void traverseVrfConfiguration(DelegateExecution execution, + List<Pair<WorkflowType, String>> aaiResourceIds, List<Resource> resourceCounter, + org.onap.so.db.catalog.beans.Service service, RelatedInstance relatedVpnBinding, + RelatedInstance relatedLocalNetwork) throws VrfBondingServiceException, JsonProcessingException { + org.onap.aai.domain.yang.L3Network aaiLocalNetwork = + bbInputSetupUtils.getAAIL3Network(relatedLocalNetwork.getInstanceId()); + vrfValidation.vrfServiceValidation(service); + vrfValidation.vrfCatalogDbChecks(service); + vrfValidation.aaiVpnBindingValidation(relatedVpnBinding.getInstanceId(), + bbInputSetupUtils.getAAIVpnBinding(relatedVpnBinding.getInstanceId())); + vrfValidation.aaiNetworkValidation(relatedLocalNetwork.getInstanceId(), aaiLocalNetwork); + vrfValidation.aaiSubnetValidation(aaiLocalNetwork); + vrfValidation.aaiAggregateRouteValidation(aaiLocalNetwork); + vrfValidation.aaiRouteTargetValidation(aaiLocalNetwork); + String existingAAIVrfConfiguration = getExistingAAIVrfConfiguration(relatedVpnBinding, aaiLocalNetwork); + if (existingAAIVrfConfiguration != null) { + aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION, existingAAIVrfConfiguration)); + } + resourceCounter.add(new Resource(WorkflowType.CONFIGURATION, + service.getConfigurationCustomizations().get(0).getModelCustomizationUUID(), false)); + + } + + protected String getExistingAAIVrfConfiguration(RelatedInstance relatedVpnBinding, + org.onap.aai.domain.yang.L3Network aaiLocalNetwork) + throws JsonProcessingException, VrfBondingServiceException { + Optional<Relationships> relationshipsOp = new AAIResultWrapper( + new AAICommonObjectMapperProvider().getMapper().writeValueAsString(aaiLocalNetwork)).getRelationships(); + if (relationshipsOp.isPresent()) { + List<AAIResultWrapper> configurationsRelatedToLocalNetwork = + relationshipsOp.get().getByType(AAIObjectType.CONFIGURATION); + if (configurationsRelatedToLocalNetwork.size() > 1) { + throw new VrfBondingServiceException( + "Network: " + aaiLocalNetwork.getNetworkId() + " has more than 1 configuration related to it"); + } + if (configurationsRelatedToLocalNetwork.size() == 1) { + AAIResultWrapper configWrapper = configurationsRelatedToLocalNetwork.get(0); + Optional<Configuration> relatedConfiguration = configWrapper.asBean(Configuration.class); + if (relatedConfiguration.isPresent() && vrfConfigurationAlreadyExists(relatedVpnBinding, + relatedConfiguration.get(), configWrapper)) { + return relatedConfiguration.get().getConfigurationId(); + } + } + } + return null; + } + + protected boolean vrfConfigurationAlreadyExists(RelatedInstance relatedVpnBinding, Configuration vrfConfiguration, + AAIResultWrapper configWrapper) throws VrfBondingServiceException { + if (vrfConfiguration.getConfigurationType().equalsIgnoreCase("VRF-ENTRY")) { + Optional<Relationships> relationshipsConfigOp = configWrapper.getRelationships(); + if (relationshipsConfigOp.isPresent()) { + Optional<VpnBinding> relatedInfraVpnBindingOp = + workflowActionUtils.extractRelationshipsVpnBinding(relationshipsConfigOp.get()); + if (relatedInfraVpnBindingOp.isPresent()) { + VpnBinding relatedInfraVpnBinding = relatedInfraVpnBindingOp.get(); + if (!relatedInfraVpnBinding.getVpnId().equalsIgnoreCase(relatedVpnBinding.getInstanceId())) { + throw new VrfBondingServiceException("Configuration: " + vrfConfiguration.getConfigurationId() + + " is not connected to the same vpn binding id provided in request: " + + relatedVpnBinding.getInstanceId()); + } else { + return true; + } + } + } + } + return false; + } + + protected void traverseNetworkCollection(DelegateExecution execution, List<Resource> resourceCounter, + org.onap.so.db.catalog.beans.Service service) { + if (service.getVnfCustomizations() == null || service.getVnfCustomizations().isEmpty()) { + List<CollectionResourceCustomization> customizations = service.getCollectionResourceCustomizations(); + if (customizations.isEmpty()) { + logger.debug("No Collections found. CollectionResourceCustomization list is empty."); + } else { + CollectionResourceCustomization collectionResourceCustomization = + findCatalogNetworkCollection(execution, service); + if (collectionResourceCustomization != null) { + resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION, + collectionResourceCustomization.getModelCustomizationUUID(), false)); + logger.debug("Found a network collection"); + if (collectionResourceCustomization.getCollectionResource() != null) { + if (collectionResourceCustomization.getCollectionResource().getInstanceGroup() != null) { + String toscaNodeType = collectionResourceCustomization.getCollectionResource() + .getInstanceGroup().getToscaNodeType(); + if (toscaNodeType != null && toscaNodeType.contains("NetworkCollection")) { + int minNetworks = 0; + org.onap.so.db.catalog.beans.InstanceGroup instanceGroup = + collectionResourceCustomization.getCollectionResource().getInstanceGroup(); + CollectionResourceInstanceGroupCustomization collectionInstCust = null; + if (!instanceGroup.getCollectionInstanceGroupCustomizations().isEmpty()) { + for (CollectionResourceInstanceGroupCustomization collectionInstanceGroupTemp : instanceGroup + .getCollectionInstanceGroupCustomizations()) { + if (collectionInstanceGroupTemp.getModelCustomizationUUID().equalsIgnoreCase( + collectionResourceCustomization.getModelCustomizationUUID())) { + collectionInstCust = collectionInstanceGroupTemp; break; } } - for (int i = 0; i < minNetworks; i++) { - if (collectionNetworkResourceCust != null && collectionInstCust != null) { - Resource resource = new Resource(WorkflowType.VIRTUAL_LINK, - collectionNetworkResourceCust.getModelCustomizationUUID(), false); - resource.setVirtualLinkKey(Integer.toString(i)); - resourceCounter.add(resource); - } + if (collectionInstCust != null + && collectionInstCust.getSubInterfaceNetworkQuantity() != null) { + minNetworks = collectionInstCust.getSubInterfaceNetworkQuantity(); + } + } + logger.debug("minNetworks: {}", minNetworks); + CollectionNetworkResourceCustomization collectionNetworkResourceCust = null; + for (CollectionNetworkResourceCustomization collectionNetworkTemp : instanceGroup + .getCollectionNetworkResourceCustomizations()) { + if (collectionNetworkTemp.getNetworkResourceCustomization() + .getModelCustomizationUUID().equalsIgnoreCase( + collectionResourceCustomization.getModelCustomizationUUID())) { + collectionNetworkResourceCust = collectionNetworkTemp; + break; + } + } + for (int i = 0; i < minNetworks; i++) { + if (collectionNetworkResourceCust != null && collectionInstCust != null) { + Resource resource = new Resource(WorkflowType.VIRTUAL_LINK, + collectionNetworkResourceCust.getModelCustomizationUUID(), false); + resource.setVirtualLinkKey(Integer.toString(i)); + resourceCounter.add(resource); } - } else { - logger.debug( - "Instance Group tosca node type does not contain NetworkCollection: {}", - toscaNodeType); } } else { - logger.debug("No Instance Group found for network collection."); + logger.debug("Instance Group tosca node type does not contain NetworkCollection: {}", + toscaNodeType); } } else { - logger.debug("No Network Collection found. collectionResource is null"); + logger.debug("No Instance Group found for network collection."); } } else { - logger.debug("No Network Collection Customization found"); + logger.debug("No Network Collection found. collectionResource is null"); } + } else { + logger.debug("No Network Collection Customization found"); } - if (resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()) - .collect(Collectors.toList()).isEmpty()) { - if (service.getNetworkCustomizations() == null) { - logger.debug("No networks were found on this service model"); - } else { - for (int i = 0; i < service.getNetworkCustomizations().size(); i++) { - resourceCounter.add(new Resource(WorkflowType.NETWORK, - service.getNetworkCustomizations().get(i).getModelCustomizationUUID(), false)); - } + } + if (resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()) + .collect(Collectors.toList()).isEmpty()) { + if (service.getNetworkCustomizations() == null) { + logger.debug("No networks were found on this service model"); + } else { + for (int i = 0; i < service.getNetworkCustomizations().size(); i++) { + resourceCounter.add(new Resource(WorkflowType.NETWORK, + service.getNetworkCustomizations().get(i).getModelCustomizationUUID(), false)); } } - } else { - buildAndThrowException(execution, - "Cannot orchestrate Service-Macro-Create without user params with a vnf. Please update ASDC model for new macro orchestration support or add service_recipe records to route to old macro flows"); } + } else { + buildAndThrowException(execution, + "Cannot orchestrate Service-Macro-Create without user params with a vnf. Please update ASDC model for new macro orchestration support or add service_recipe records to route to old macro flows"); } } @@ -759,7 +841,8 @@ public class WorkflowAction { aaiConfigurationResources.getConfiguration(config.getConfigurationId()); if (aaiConfig.isPresent() && aaiConfig.get().getRelationshipList() != null) { for (Relationship relationship : aaiConfig.get().getRelationshipList().getRelationship()) { - if (relationship.getRelatedTo().contains("vnfc")) { + if (relationship.getRelatedTo().contains("vnfc") + || relationship.getRelatedTo().contains("vpn-binding")) { aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION, config.getConfigurationId())); resourceCounter.add( @@ -1315,7 +1398,8 @@ public class WorkflowAction { WorkflowType resourceName, boolean aLaCarte, String cloudOwner, String serviceType) { List<OrchestrationFlow> listToExecute = new ArrayList<>(); NorthBoundRequest northBoundRequest = null; - if (serviceType.equalsIgnoreCase(SERVICE_TYPE_TRANSPORT)) { + if (serviceType.equalsIgnoreCase(SERVICE_TYPE_TRANSPORT) + || serviceType.equalsIgnoreCase(SERVICE_TYPE_BONDING)) { northBoundRequest = catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwnerAndServiceType( requestAction, resourceName.toString(), aLaCarte, cloudOwner, serviceType); @@ -1324,6 +1408,10 @@ public class WorkflowAction { requestAction, resourceName.toString(), aLaCarte, cloudOwner); } if (northBoundRequest == null) { + northBoundRequest = catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScope(requestAction, + resourceName.toString(), aLaCarte); + } + if (northBoundRequest == null) { if (aLaCarte) { buildAndThrowException(execution, "The request: ALaCarte " + resourceName + " " + requestAction + " is not supported by GR_API."); @@ -1333,7 +1421,7 @@ public class WorkflowAction { } } else { if (northBoundRequest.getIsToplevelflow() != null) { - execution.setVariable(G_ISTOPLEVELFLOW, northBoundRequest.getIsToplevelflow()); + execution.setVariable(BBConstants.G_ISTOPLEVELFLOW, northBoundRequest.getIsToplevelflow()); } List<OrchestrationFlow> flows = northBoundRequest.getOrchestrationFlowList(); if (flows == null) diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailure.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailure.java index 5f357f5478..35ceef0473 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailure.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailure.java @@ -55,7 +55,6 @@ public class WorkflowActionBBFailure { } request.setStatusMessage(errorMsg); request.setProgress(Long.valueOf(100)); - request.setRequestStatus("FAILED"); request.setLastModifiedBy("CamundaBPMN"); request.setEndTime(new Timestamp(System.currentTimeMillis())); requestDbclient.updateInfraActiveRequests(request); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasks.java index 753a050c03..44152fcaf4 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasks.java @@ -27,6 +27,8 @@ import java.util.UUID; import javax.persistence.EntityNotFoundException; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.onap.aai.domain.yang.Vnfc; +import org.onap.so.bpmn.common.DelegateExecutionImpl; +import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulatorListenerRunner; import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse; import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder; import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock; @@ -77,42 +79,19 @@ public class WorkflowActionBBTasks { private BBInputSetupUtils bbInputSetupUtils; @Autowired private CatalogDbClient catalogDbClient; + @Autowired + private FlowManipulatorListenerRunner flowManipulatorListenerRunner; public void selectBB(DelegateExecution execution) { List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); execution.setVariable("MacroRollback", false); - int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE); - ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence); - if (ebb.getBuildingBlock().getBpmnFlowName().equals("ConfigAssignVnfBB") - || ebb.getBuildingBlock().getBpmnFlowName().equals("ConfigDeployVnfBB")) { - String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId(); - String vnfCustomizationUUID = ebb.getBuildingBlock().getKey(); + flowManipulatorListenerRunner.modifyFlows(flowsToExecute, new DelegateExecutionImpl(execution)); + int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE); - List<VnfResourceCustomization> vnfResourceCustomizations = - catalogDbClient.getVnfResourceCustomizationByModelUuid(serviceInstanceId); - if (vnfResourceCustomizations != null && vnfResourceCustomizations.size() >= 1) { - VnfResourceCustomization vrc = catalogDbClient.findVnfResourceCustomizationInList(vnfCustomizationUUID, - vnfResourceCustomizations); - boolean skipConfigVNF = vrc.isSkipPostInstConf(); - if (skipConfigVNF) { - currentSequence++; - ebb = flowsToExecute.get(currentSequence); - } - } - } + ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence); - boolean homing = (boolean) execution.getVariable("homing"); - boolean calledHoming = (boolean) execution.getVariable("calledHoming"); - if (homing && !calledHoming) { - if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) { - ebb.setHoming(true); - execution.setVariable("calledHoming", true); - } - } else { - ebb.setHoming(false); - } execution.setVariable("buildingBlock", ebb); currentSequence++; if (currentSequence >= flowsToExecute.size()) { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionExtractResourcesAAI.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionExtractResourcesAAI.java index 99ae2e7495..f672aa4b59 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionExtractResourcesAAI.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionExtractResourcesAAI.java @@ -22,18 +22,25 @@ package org.onap.so.bpmn.infrastructure.workflow.tasks; import java.util.List; import java.util.Optional; +import org.onap.aai.domain.yang.VpnBinding; import org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration; +import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils; import org.onap.so.client.aai.AAIObjectType; 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.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class WorkflowActionExtractResourcesAAI { private static final Logger logger = LoggerFactory.getLogger(WorkflowActionExtractResourcesAAI.class); + @Autowired + protected BBInputSetupUtils bbInputSetupUtils; + public Optional<Configuration> extractRelationshipsConfiguration(Relationships relationships) { List<AAIResultWrapper> configurations = relationships.getByType(AAIObjectType.CONFIGURATION); for (AAIResultWrapper configWrapper : configurations) { @@ -45,6 +52,18 @@ public class WorkflowActionExtractResourcesAAI { return Optional.empty(); } + public Optional<VpnBinding> extractRelationshipsVpnBinding(Relationships relationships) { + List<AAIResourceUri> configurations = relationships.getRelatedUris(AAIObjectType.VPN_BINDING); + for (AAIResourceUri vpnBindingUri : configurations) { + AAIResultWrapper vpnBindingWrapper = bbInputSetupUtils.getAAIResourceDepthOne(vpnBindingUri); + Optional<VpnBinding> vpnBinding = vpnBindingWrapper.asBean(VpnBinding.class); + if (vpnBinding.isPresent()) { + return vpnBinding; + } + } + return Optional.empty(); + } + public Optional<Relationships> extractRelationshipsVnfc(Relationships relationships) { List<AAIResultWrapper> vnfcs = relationships.getByType(AAIObjectType.VNFC); for (AAIResultWrapper vnfcWrapper : vnfcs) { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowType.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowType.java index af8f93b92b..05a51797dd 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowType.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowType.java @@ -22,9 +22,15 @@ package org.onap.so.bpmn.infrastructure.workflow.tasks; public enum WorkflowType { - SERVICE("Service"), VNF("Vnf"), VFMODULE("VfModule"), VOLUMEGROUP("VolumeGroup"), NETWORK("Network"), VIRTUAL_LINK( - "VirtualLink"), NETWORKCOLLECTION( - "NetworkCollection"), CONFIGURATION("Configuration"), INSTANCE_GROUP("InstanceGroup"); + SERVICE("Service"), + VNF("Vnf"), + VFMODULE("VfModule"), + VOLUMEGROUP("VolumeGroup"), + NETWORK("Network"), + VIRTUAL_LINK("VirtualLink"), + NETWORKCOLLECTION("NetworkCollection"), + CONFIGURATION("Configuration"), + INSTANCE_GROUP("InstanceGroup"); private final String type; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/HomingListener.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/HomingListener.java new file mode 100644 index 0000000000..6254aae029 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/HomingListener.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.infrastructure.workflow.tasks.listeners; + +import java.util.List; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulator; +import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; +import org.springframework.stereotype.Component; + +@Component +public class HomingListener implements FlowManipulator { + + + @Override + public boolean shouldRunFor(String currentBBName, boolean isFirst, BuildingBlockExecution execution) { + return "AssignVnfBB".equals(currentBBName); + } + + @Override + public void run(List<ExecuteBuildingBlock> flowsToExecute, ExecuteBuildingBlock currentBB, + BuildingBlockExecution execution) { + + boolean homing = (boolean) execution.getVariable("homing"); + boolean calledHoming = (boolean) execution.getVariable("calledHoming"); + if (homing && !calledHoming) { + currentBB.setHoming(true); + execution.setVariable("calledHoming", true); + } + } + + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/MultiStageSkipListener.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/MultiStageSkipListener.java new file mode 100644 index 0000000000..fd0de086ad --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/MultiStageSkipListener.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.infrastructure.workflow.tasks.listeners; + +import java.util.Collections; +import java.util.List; +import org.onap.so.bpmn.common.BBConstants; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulator; +import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; +import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class MultiStageSkipListener implements FlowManipulator { + + @Autowired + protected BBInputSetupUtils bbInputSetupUtils; + + @Autowired + private CatalogDbClient catalogDbClient; + + @Override + public boolean shouldRunFor(String currentBBName, boolean isFirst, BuildingBlockExecution execution) { + return ((boolean) execution.getVariable(BBConstants.G_ALACARTE)) && "AssignVfModuleBB".equals(currentBBName) + && isFirst; + } + + @Override + public void run(List<ExecuteBuildingBlock> flowsToExecute, ExecuteBuildingBlock currentBB, + BuildingBlockExecution execution) { + String vfModuleId = currentBB.getResourceId(); + String vnfId = currentBB.getWorkflowResourceIds().getVnfId(); + org.onap.aai.domain.yang.VfModule vfModule = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId); + if (vfModule == null) { + org.onap.aai.domain.yang.GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(vnfId); + if (vnf != null) { + VnfResourceCustomization vnfCust = catalogDbClient + .getVnfResourceCustomizationByModelCustomizationUUID(vnf.getModelCustomizationId()); + if (vnfCust != null && vnfCust.getMultiStageDesign() != null + && vnfCust.getMultiStageDesign().equalsIgnoreCase("true")) { + flowsToExecute.retainAll(Collections.singletonList(currentBB)); + } + } + } + + } + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/SkipConfigVnfListener.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/SkipConfigVnfListener.java new file mode 100644 index 0000000000..772fca0841 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/SkipConfigVnfListener.java @@ -0,0 +1,44 @@ +package org.onap.so.bpmn.infrastructure.workflow.tasks.listeners; + +import java.util.List; +import org.onap.so.bpmn.common.BBConstants; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulator; +import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class SkipConfigVnfListener implements FlowManipulator { + + @Autowired + private CatalogDbClient catalogDbClient; + + @Override + public boolean shouldRunFor(String currentBBName, boolean isFirst, BuildingBlockExecution execution) { + return "ConfigAssignVnfBB".equals(currentBBName) || "ConfigDeployVnfBB".equals(currentBBName); + } + + @Override + public void run(List<ExecuteBuildingBlock> flowsToExecute, ExecuteBuildingBlock currentBB, + BuildingBlockExecution execution) { + String vnfCustomizationUUID = currentBB.getBuildingBlock().getKey(); + + List<VnfResourceCustomization> vnfResourceCustomizations = catalogDbClient + .getVnfResourceCustomizationByModelUuid(currentBB.getRequestDetails().getModelInfo().getModelUuid()); + if (vnfResourceCustomizations != null && !vnfResourceCustomizations.isEmpty()) { + VnfResourceCustomization vrc = + catalogDbClient.findVnfResourceCustomizationInList(vnfCustomizationUUID, vnfResourceCustomizations); + boolean skipConfigVNF = vrc.isSkipPostInstConf(); + if (skipConfigVNF) { + execution.setVariable(BBConstants.G_CURRENT_SEQUENCE, + ((int) execution.getVariable(BBConstants.G_CURRENT_SEQUENCE)) + 1); + } + } + } + + + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapper.java index 4fee1f909b..173e776af9 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapper.java @@ -34,7 +34,6 @@ import org.onap.so.adapters.nwrest.ContrailNetwork; import org.onap.so.adapters.nwrest.CreateNetworkRequest; import org.onap.so.adapters.nwrest.CreateNetworkResponse; import org.onap.so.adapters.nwrest.DeleteNetworkRequest; -import org.onap.so.adapters.nwrest.NetworkTechnology; import org.onap.so.adapters.nwrest.ProviderVlanNetwork; import org.onap.so.adapters.nwrest.RollbackNetworkRequest; import org.onap.so.adapters.nwrest.UpdateNetworkRequest; @@ -261,7 +260,7 @@ public class NetworkAdapterObjectMapper { * @param L3Network * @return List<org.onap.so.openstack.beans.Subnet> */ - private List<Subnet> buildOpenstackSubnetList(L3Network l3Network) { + protected List<Subnet> buildOpenstackSubnetList(L3Network l3Network) { List<org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet> subnets = l3Network.getSubnets(); List<org.onap.so.openstack.beans.Subnet> subnetList = new ArrayList<org.onap.so.openstack.beans.Subnet>(); @@ -292,9 +291,10 @@ public class NetworkAdapterObjectMapper { .setCidr(subnet.getNetworkStartAddress().concat(FORWARD_SLASH).concat(subnet.getCidrMask())); List<org.onap.so.bpmn.servicedecomposition.bbobjects.HostRoute> hostRouteList = subnet.getHostRoutes(); List<org.onap.so.openstack.beans.HostRoute> openstackHostRouteList = new ArrayList<>(); - org.onap.so.openstack.beans.HostRoute openstackHostRoute = new org.onap.so.openstack.beans.HostRoute(); + org.onap.so.openstack.beans.HostRoute openstackHostRoute = null; // TODO only 2 fields available on openstack object. Confirm it is sufficient or add as needed for (org.onap.so.bpmn.servicedecomposition.bbobjects.HostRoute hostRoute : hostRouteList) { + openstackHostRoute = new org.onap.so.openstack.beans.HostRoute(); openstackHostRoute.setNextHop(hostRoute.getNextHop()); openstackHostRoute.setPrefix(hostRoute.getRoutePrefix()); // add host route to the list diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java index 94e95687db..b0ba0595d5 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java @@ -205,14 +205,22 @@ public class VnfAdapterVfModuleObjectMapper { private void buildDirectivesParamFromMap(Map<String, Object> paramsMap, String directive, Map<String, Object> srcMap) { StringBuilder directives = new StringBuilder(); - if (srcMap.size() > 0) { + int no_directives_size = 0; + if (directives.equals(MsoMulticloudUtils.USER_DIRECTIVES) + && srcMap.containsKey(MsoMulticloudUtils.OOF_DIRECTIVES)) { + no_directives_size = 1; + } + if (srcMap.size() > no_directives_size) { directives.append("{ \"attributes\": [ "); int i = 0; for (String attributeName : srcMap.keySet()) { - directives.append(new AttributeNameValue(attributeName, srcMap.get(attributeName).toString())); - if (i < (srcMap.size() - 1)) - directives.append(", "); - i++; + if (!(MsoMulticloudUtils.USER_DIRECTIVES.equals(directives) + && attributeName.equals(MsoMulticloudUtils.OOF_DIRECTIVES))) { + directives.append(new AttributeNameValue(attributeName, srcMap.get(attributeName).toString())); + if (i < (srcMap.size() - 1 + no_directives_size)) + directives.append(", "); + i++; + } } directives.append("] }"); } else { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClientResponseValidator.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClientResponseValidator.java index 717bb04099..088ce1ac38 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClientResponseValidator.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingClientResponseValidator.java @@ -24,6 +24,7 @@ package org.onap.so.client.namingservice; import java.io.IOException; import java.util.List; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpStatus; import org.onap.namingservice.model.NameGenDeleteResponse; import org.onap.namingservice.model.NameGenResponse; @@ -43,6 +44,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class NamingClientResponseValidator { private static final Logger logger = LoggerFactory.getLogger(NamingClientResponseValidator.class); private static final String INSTANCE_GROUP_NAME = "instance-group-name"; + private static final String SERVICE_INSTANCE_NAME = "Service-Instance-Name"; private static final String NO_RESPONSE_FROM_NAMING_SERVICE = "Error did not receive a response from Naming Service."; private static final String NULL_RESPONSE_FROM_NAMING_SERVICE = @@ -51,8 +53,9 @@ public class NamingClientResponseValidator { public String validateNameGenResponse(ResponseEntity<NameGenResponse> response) throws BadResponseException { if (response == null) { - logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), NO_RESPONSE_FROM_NAMING_SERVICE, - "BPMN", ErrorCode.UnknownError.getValue(), NO_RESPONSE_FROM_NAMING_SERVICE); + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_GENERAL_EXCEPTION.toString(), + NO_RESPONSE_FROM_NAMING_SERVICE, "BPMN", ErrorCode.UnknownError.getValue(), + NO_RESPONSE_FROM_NAMING_SERVICE); throw new BadResponseException(NO_RESPONSE_FROM_NAMING_SERVICE); } @@ -60,7 +63,7 @@ public class NamingClientResponseValidator { String generatedName = ""; NameGenResponse responseBody = response.getBody(); if (responseBody == null) { - logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_GENERAL_EXCEPTION.toString(), NULL_RESPONSE_FROM_NAMING_SERVICE, "BPMN", ErrorCode.UnknownError.getValue(), NULL_RESPONSE_FROM_NAMING_SERVICE); throw new BadResponseException(NULL_RESPONSE_FROM_NAMING_SERVICE); @@ -78,6 +81,9 @@ public class NamingClientResponseValidator { if (INSTANCE_GROUP_NAME.equals(resourceName)) { generatedName = respElement.getResourceValue(); break; + } else if (SERVICE_INSTANCE_NAME.equals(resourceName)) { + generatedName = respElement.getResourceValue(); + break; } } } @@ -90,7 +96,7 @@ public class NamingClientResponseValidator { errorMessageString = error.getMessage(); } String errorMessage = String.format(NAMING_SERVICE_ERROR, errorMessageString); - logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), errorMessage, "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_GENERAL_EXCEPTION.toString(), errorMessage, "BPMN", ErrorCode.DataError.getValue(), errorMessage); throw new BadResponseException(errorMessage); } @@ -99,8 +105,9 @@ public class NamingClientResponseValidator { public String validateNameGenDeleteResponse(ResponseEntity<NameGenDeleteResponse> response) throws BadResponseException { if (response == null) { - logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), NO_RESPONSE_FROM_NAMING_SERVICE, - "BPMN", ErrorCode.UnknownError.getValue(), NO_RESPONSE_FROM_NAMING_SERVICE); + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_GENERAL_EXCEPTION.toString(), + NO_RESPONSE_FROM_NAMING_SERVICE, "BPMN", ErrorCode.UnknownError.getValue(), + NO_RESPONSE_FROM_NAMING_SERVICE); throw new BadResponseException(NO_RESPONSE_FROM_NAMING_SERVICE); } @@ -108,7 +115,7 @@ public class NamingClientResponseValidator { String responseMessage = ""; NameGenDeleteResponse responseBody = response.getBody(); if (responseBody == null) { - logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_GENERAL_EXCEPTION.toString(), NULL_RESPONSE_FROM_NAMING_SERVICE, "BPMN", ErrorCode.UnknownError.getValue(), NULL_RESPONSE_FROM_NAMING_SERVICE); throw new BadResponseException(NULL_RESPONSE_FROM_NAMING_SERVICE); @@ -121,7 +128,7 @@ public class NamingClientResponseValidator { String errorMessageString = NAMING_SERVICE_ERROR; String errorMessage = String.format(NAMING_SERVICE_ERROR, errorMessageString); - logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), errorMessage, "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_GENERAL_EXCEPTION.toString(), errorMessage, "BPMN", ErrorCode.DataError.getValue(), errorMessage); throw new BadResponseException(errorMessage); } @@ -141,7 +148,7 @@ public class NamingClientResponseValidator { errorMessageString = error.getMessage(); } String errorMessage = String.format(NAMING_SERVICE_ERROR, errorMessageString); - logger.error("{} {} {} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), errorMessage, "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_GENERAL_EXCEPTION.toString(), errorMessage, "BPMN", ErrorCode.DataError.getValue(), errorMessage); return errorMessage; } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingRequestObject.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingRequestObject.java new file mode 100644 index 0000000000..3d3058da0b --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingRequestObject.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.client.namingservice; + +import java.util.HashMap; + +public class NamingRequestObject { + + private HashMap<String, String> namingRequestMap = new HashMap<String, String>(); + + public HashMap<String, String> getNamingRequestObjectMap() { + return this.namingRequestMap; + } + + public String getExternalKeyValue() { + return namingRequestMap.get(NamingServiceConstants.NS_EXTERNAL_KEY); + } + + public void setExternalKeyValue(String externalKey) { + this.namingRequestMap.put(NamingServiceConstants.NS_EXTERNAL_KEY, externalKey); + } + + public String getPolicyInstanceNameValue() { + return this.namingRequestMap.get(NamingServiceConstants.NS_POLICY_INSTANCE_NAME); + } + + public void setPolicyInstanceNameValue(String policyInstanceName) { + this.namingRequestMap.put(NamingServiceConstants.NS_POLICY_INSTANCE_NAME, policyInstanceName); + } + + public String getNamingTypeValue() { + return namingRequestMap.get(NamingServiceConstants.NS_NAMING_TYPE); + } + + public void setNamingTypeValue(String namingType) { + this.namingRequestMap.put(NamingServiceConstants.NS_NAMING_TYPE, namingType); + } + + public String getResourceNameValue() { + return this.namingRequestMap.get(NamingServiceConstants.NS_RESOURCE_NAME); + } + + public void setResourceNameValue(String resourceName) { + namingRequestMap.put(NamingServiceConstants.NS_RESOURCE_NAME, resourceName); + } + + public String getNfNamingCodeValue() { + return this.namingRequestMap.get(NamingServiceConstants.NS_NF_NAMING_CODE); + } + + public void setNfNamingCodeValue(String nfNamingCode) { + this.namingRequestMap.put(NamingServiceConstants.NS_NF_NAMING_CODE, nfNamingCode); + } + + public String getServiceModelNameValue() { + return this.namingRequestMap.get(NamingServiceConstants.NS_SERVICE_MODEL_NAME); + } + + public void setServiceModelNameValue(String serviceModelName) { + this.namingRequestMap.put(NamingServiceConstants.NS_SERVICE_MODEL_NAME, serviceModelName); + } + + public String getModelVersionValue() { + return this.namingRequestMap.get(NamingServiceConstants.NS_MODEL_VERSION); + } + + public void setModelVersionValue(String modelVersion) { + this.namingRequestMap.put(NamingServiceConstants.NS_MODEL_VERSION, modelVersion); + } + + public String getNetworkNameValue() { + return this.namingRequestMap.get(NamingServiceConstants.NS_NETWORK_NAME); + } + + public void setNetworkNameValue(String networkName) { + this.namingRequestMap.put(NamingServiceConstants.NS_NETWORK_NAME, networkName); + } + + public String getVpnNameValue() { + return this.namingRequestMap.get(NamingServiceConstants.NS_VPN_NAME); + } + + public void setVpnNameValue(String vpnName) { + this.namingRequestMap.put(NamingServiceConstants.NS_VPN_NAME, vpnName); + } + + public String getZoneIdValue() { + return this.namingRequestMap.get(NamingServiceConstants.NS_ZONE_ID); + } + + public void setZoneIdValue(String zoneId) { + this.namingRequestMap.put(NamingServiceConstants.NS_ZONE_ID, zoneId); + } + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingServiceConstants.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingServiceConstants.java new file mode 100644 index 0000000000..5637410af0 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingServiceConstants.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.client.namingservice; + +public class NamingServiceConstants { + public static final String NS_EXTERNAL_KEY = "external-key"; + public static final String NS_POLICY_INSTANCE_NAME = "policy-instance-name"; + public static final String NS_NAMING_TYPE = "naming-type"; + public static final String NS_RESOURCE_NAME = "resource-name"; + public static final String NS_NF_NAMING_CODE = "nf-naming-code"; + public static final String NS_SERVICE_MODEL_NAME = "service-model-name"; + public static final String NS_MODEL_VERSION = "model-version"; + public static final String NS_NETWORK_NAME = "network-name"; + public static final String NS_VPN_NAME = "vpn-name"; + public static final String NS_ZONE_ID = "zone-id"; + public static final String NS_RESOURCE_VALUE = "resource-value"; + + public static final String NAMING_TYPE_SERVICE = "SERVICE"; + public static final String RESOURCE_NAME_SERVICE_INSTANCE_NAME = "Service-Instance-Name"; + public static final String RESOURCE_NAME_SERVICEINSTANCE = "ServiceInstance"; + + private NamingServiceConstants() {} +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingServiceUtils.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingServiceUtils.java new file mode 100644 index 0000000000..16c8e5549c --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingServiceUtils.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.client.namingservice; + +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; +import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; +import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; +import org.onap.so.client.exception.ExceptionBuilder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class NamingServiceUtils { + + private static String errorMessages = "Policy name is not present, or Onap name was not generated! "; + + @Autowired + private ExceptionBuilder exceptionUtil; + @Autowired + private ExtractPojosForBB extractPojosForBB; + + public void checkVpnBondingService(BuildingBlockExecution execution) { + execution.setVariable("isVpnBondingService", false); + boolean isNamingPolicyAndOnapGeneratedNaming = false; + checkBondingAndInfrastureVpn(execution); + boolean isBondingAndInsfrastructureVpn = execution.getVariable("isBondingAndInsfrastructureVpn"); + if (isBondingAndInsfrastructureVpn) { + checkNamingPolicyAndOnapGeneratedNaming(execution); + isNamingPolicyAndOnapGeneratedNaming = execution.getVariable("isNamingPolicyAndOnapGeneratedNaming"); + } + if (isBondingAndInsfrastructureVpn && isNamingPolicyAndOnapGeneratedNaming) { + execution.setVariable("isVpnBondingService", true); + } + } + + public void checkBondingAndInfrastureVpn(BuildingBlockExecution execution) { + execution.setVariable("isBondingAndInsfrastructureVpn", false); + try { + ServiceInstance serviceInstance = + extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + if ("bonding".equalsIgnoreCase(serviceInstance.getModelInfoServiceInstance().getServiceType()) + && "infrastructure-vpn" + .equalsIgnoreCase(serviceInstance.getModelInfoServiceInstance().getServiceRole())) { + execution.setVariable("isBondingAndInsfrastructureVpn", true); + } + } catch (Exception ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + } + + public void checkNamingPolicyAndOnapGeneratedNaming(BuildingBlockExecution execution) { + execution.setVariable("isNamingPolicyAndOnapGeneratedNaming", false); + try { + ServiceInstance serviceInstance = + extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + if (serviceInstance.getModelInfoServiceInstance().getNamingPolicy() != null + && !serviceInstance.getModelInfoServiceInstance().getNamingPolicy().isEmpty() + && serviceInstance.getModelInfoServiceInstance().getOnapGeneratedNaming() != null + && serviceInstance.getModelInfoServiceInstance().getOnapGeneratedNaming() == true) { + execution.setVariable("isNamingPolicyAndOnapGeneratedNaming", true); + } else { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, errorMessages); + } + } catch (Exception ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + } +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIConfigurationResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIConfigurationResources.java index 1453e40653..867d80a4ea 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIConfigurationResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIConfigurationResources.java @@ -24,6 +24,7 @@ import java.util.Optional; import javax.ws.rs.core.UriBuilder; import org.onap.so.bpmn.common.InjectionHelper; import org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.entities.AAIEdgeLabel; import org.onap.so.client.aai.entities.uri.AAIResourceUri; @@ -79,7 +80,7 @@ public class AAIConfigurationResources { /** * A&AI call to disconnect configuration relation with service instance - * + * * @param configurationId * @param serviceInstanceId */ @@ -211,7 +212,7 @@ public class AAIConfigurationResources { /** * Get Configuration from AAI using related Link - * + * * @param relatedLink related link - URI * @return AAI Configuration object */ @@ -228,4 +229,20 @@ public class AAIConfigurationResources { org.onap.aai.domain.yang.Configuration aaiConfiguration = aaiObjectMapper.mapConfiguration(configuration); injectionHelper.getAaiClient().update(aaiResourceUri, aaiConfiguration); } + + public void updateConfigurationOrchestrationStatus(Configuration configuration, + OrchestrationStatus orchestrationStatus) { + AAIResourceUri aaiResourceUri = + AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configuration.getConfigurationId()); + org.onap.aai.domain.yang.Configuration aaiConfiguration = new org.onap.aai.domain.yang.Configuration(); + aaiConfiguration.setOrchestrationStatus(orchestrationStatus.name()); + injectionHelper.getAaiClient().update(aaiResourceUri, aaiConfiguration); + } + + public boolean checkConfigurationNameInUse(String configurationName) { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.CONFIGURATION) + .queryParam("configuration-name", configurationName); + return injectionHelper.getAaiClient().exists(uri); + } + } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIInstanceGroupResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIInstanceGroupResources.java index c48593037a..296d052315 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIInstanceGroupResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIInstanceGroupResources.java @@ -25,6 +25,7 @@ import org.onap.so.bpmn.common.InjectionHelper; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.entities.AAIEdgeLabel; import org.onap.so.client.aai.entities.uri.AAIResourceUri; @@ -84,4 +85,11 @@ public class AAIInstanceGroupResources { injectionHelper.getAaiClient().createIfNotExists(instanceGroupUri, Optional.of(aaiInstanceGroup)) .connect(instanceGroupUri, serviceInstanceURI); } + + public boolean checkInstanceGroupNameInUse(String instanceGroupName) { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.INSTANCE_GROUP) + .queryParam("instance-group-name", instanceGroupName); + return injectionHelper.getAaiClient().exists(uri); + } + } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAINetworkResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAINetworkResources.java index b936551549..bc702c9fb4 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAINetworkResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAINetworkResources.java @@ -32,6 +32,7 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup; import org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; import org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.entities.AAIEdgeLabel; import org.onap.so.client.aai.entities.AAIResultWrapper; @@ -206,4 +207,11 @@ public class AAINetworkResources { AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId); injectionHelper.getAaiClient().delete(networkPolicyURI); } + + public boolean checkNetworkNameInUse(String networkName) { + AAIResourceUri uri = + AAIUriFactory.createResourceUri(AAIObjectPlurals.L3_NETWORK).queryParam("network-name", networkName); + return injectionHelper.getAaiClient().exists(uri); + } + } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java index f84afbe4a2..c41f3fa56c 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java @@ -157,5 +157,10 @@ public class AAIServiceInstanceResources { injectionHelper.getAaiClient().update(serviceInstanceURI, aaiServiceInstance); } + public boolean checkInstanceServiceNameInUse(ServiceInstance serviceInstance) { + AAIResourceUri uriSI = AAIUriFactory.createNodesUri(AAIObjectPlurals.SERVICE_INSTANCE) + .queryParam("service-instance-name", serviceInstance.getServiceInstanceName()); + return injectionHelper.getAaiClient().exists(uriSI); + } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVfModuleResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVfModuleResources.java index 514f48ffc8..4d1a6dce38 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVfModuleResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVfModuleResources.java @@ -23,12 +23,15 @@ package org.onap.so.client.orchestration; import java.util.Optional; +import org.onap.aai.domain.yang.VfModules; import org.onap.so.bpmn.common.InjectionHelper; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; import org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.aai.mapper.AAIObjectMapper; @@ -108,4 +111,19 @@ public class AAIVfModuleResources { cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId()); injectionHelper.getAaiClient().connect(vfModuleURI, volumeGroupURI); } + + public boolean checkNameInUse(VfModule vfModule) { + boolean nameInUse = false; + AAIResourceUri vfModuleUri = AAIUriFactory.createNodesUri(AAIObjectPlurals.VF_MODULE) + .queryParam("vf-module-name", vfModule.getVfModuleName()); + AAIResourceUri vfModuleUriWithCustomization = vfModuleUri.clone().queryParam("model-customization-id", + vfModule.getModelInfoVfModule().getModelCustomizationUUID()); + if (injectionHelper.getAaiClient().exists(vfModuleUriWithCustomization)) { + // assume it's a resume case and return false + nameInUse = false; + } else { + nameInUse = injectionHelper.getAaiClient().exists(vfModuleUri); + } + return nameInUse; + } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java index eb66f6bef5..a9635d1e34 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java @@ -30,8 +30,10 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; import org.onap.so.bpmn.servicedecomposition.bbobjects.LineOfBusiness; import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIValidatorImpl; +import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.aai.mapper.AAIObjectMapper; @@ -152,4 +154,10 @@ public class AAIVnfResources { return aaiValidatorImpl.isPhysicalServerLocked(vnf.getVnfId()); } + + public boolean checkNameInUse(String vnfName) { + AAIResourceUri vnfUri = + AAIUriFactory.createResourceUri(AAIObjectPlurals.GENERIC_VNF).queryParam("vnf-name", vnfName); + return injectionHelper.getAaiClient().exists(vnfUri); + } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVolumeGroupResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVolumeGroupResources.java index f4c285fdb3..b9e4aeb888 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVolumeGroupResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVolumeGroupResources.java @@ -26,6 +26,7 @@ import org.onap.so.bpmn.common.InjectionHelper; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; import org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; @@ -93,4 +94,10 @@ public class AAIVolumeGroupResources { copiedVolumeGroup.setHeatStackId(volumeGroup.getHeatStackId()); injectionHelper.getAaiClient().update(uri, aaiObjectMapper.mapVolumeGroup(copiedVolumeGroup)); } + + public boolean checkNameInUse(VolumeGroup volumeGroup) { + AAIResourceUri volumeGroupUri = AAIUriFactory.createNodesUri(AAIObjectPlurals.VOLUME_GROUP) + .queryParam("volume-group-name", volumeGroup.getVolumeGroupName()); + return injectionHelper.getAaiClient().exists(volumeGroupUri); + } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NamingServiceResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NamingServiceResources.java index 06535bb765..5513122560 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NamingServiceResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NamingServiceResources.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ @@ -24,12 +24,14 @@ package org.onap.so.client.orchestration; import java.io.IOException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import org.onap.namingservice.model.Element; import org.onap.namingservice.model.Deleteelement; import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup; import org.onap.so.client.exception.BadResponseException; import org.onap.so.client.namingservice.NamingClient; +import org.onap.so.client.namingservice.NamingRequestObject; import org.onap.so.client.namingservice.NamingRequestObjectBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -63,4 +65,25 @@ public class NamingServiceResources { return (namingClient .deleteNameGenRequest(namingRequestObjectBuilder.nameGenDeleteRequestMapper(deleteElements))); } + + public String generateServiceInstanceName(NamingRequestObject namingRequestObject) + throws BadResponseException, IOException { + HashMap<String, String> nsRequestObject = namingRequestObject.getNamingRequestObjectMap(); + Element element = new Element(); + nsRequestObject.forEach((k, v) -> element.put(k, v)); + List<Element> elements = new ArrayList<Element>(); + elements.add(element); + return (namingClient.postNameGenRequest(namingRequestObjectBuilder.nameGenRequestMapper(elements))); + } + + public String deleteServiceInstanceName(NamingRequestObject namingRequestObject) + throws BadResponseException, IOException { + HashMap<String, String> nsRequestObject = namingRequestObject.getNamingRequestObjectMap(); + Deleteelement delElement = new Deleteelement(); + nsRequestObject.forEach((k, v) -> delElement.setExternalKey(v)); + List<Deleteelement> delElements = new ArrayList<Deleteelement>(); + delElements.add(delElement); + return (namingClient.deleteNameGenRequest(namingRequestObjectBuilder.nameGenDeleteRequestMapper(delElements))); + } + } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVfModuleResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVfModuleResources.java index 60cad78f5d..b83a4d5628 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVfModuleResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVfModuleResources.java @@ -22,6 +22,7 @@ package org.onap.so.client.orchestration; +import java.net.URI; import org.onap.sdnc.northbound.client.model.GenericResourceApiVfModuleOperationInformation; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer; @@ -53,22 +54,22 @@ public class SDNCVfModuleResources { public GenericResourceApiVfModuleOperationInformation assignVfModule(VfModule vfModule, VolumeGroup volumeGroup, GenericVnf vnf, ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, - RequestContext requestContext) throws MapperException { + RequestContext requestContext, URI callbackURI) throws MapperException { return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule, - volumeGroup, vnf, serviceInstance, customer, cloudRegion, requestContext, null); + volumeGroup, vnf, serviceInstance, customer, cloudRegion, requestContext, null, callbackURI); } public GenericResourceApiVfModuleOperationInformation unassignVfModule(VfModule vfModule, GenericVnf vnf, - ServiceInstance serviceInstance) throws MapperException { + ServiceInstance serviceInstance, URI callbackURI) throws MapperException { return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, vfModule, null, - vnf, serviceInstance, null, null, null, null); + vnf, serviceInstance, null, null, null, null, callbackURI); } public GenericResourceApiVfModuleOperationInformation deactivateVfModule(VfModule vfModule, GenericVnf vnf, - ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext) - throws MapperException { + ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext, + URI callbackURI) throws MapperException { return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE, vfModule, null, - vnf, serviceInstance, customer, cloudRegion, requestContext, null); + vnf, serviceInstance, customer, cloudRegion, requestContext, null, callbackURI); } public String queryVfModule(VfModule vfModule) throws MapperException, BadResponseException { @@ -77,16 +78,16 @@ public class SDNCVfModuleResources { } public GenericResourceApiVfModuleOperationInformation activateVfModule(VfModule vfModule, GenericVnf vnf, - ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext) - throws MapperException { + ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext, + URI callbackURI) throws MapperException { return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE, vfModule, null, - vnf, serviceInstance, customer, cloudRegion, requestContext, null); + vnf, serviceInstance, customer, cloudRegion, requestContext, null, callbackURI); } public GenericResourceApiVfModuleOperationInformation changeAssignVfModule(VfModule vfModule, GenericVnf vnf, - ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext) - throws MapperException { + ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext, + URI callbackURI) throws MapperException { return sdncRM.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN, vfModule, - null, vnf, serviceInstance, customer, cloudRegion, requestContext, null); + null, vnf, serviceInstance, customer, cloudRegion, requestContext, null, callbackURI); } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SdnCommonTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SdnCommonTasks.java index fe1f3f4308..1144648517 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SdnCommonTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SdnCommonTasks.java @@ -25,6 +25,7 @@ package org.onap.so.client.sdnc; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; +import org.onap.so.logger.LoggingAnchor; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpStatus; import org.onap.so.client.exception.BadResponseException; @@ -52,7 +53,7 @@ public class SdnCommonTasks { private static final String SDNC_CODE_NOT_0_OR_IN_200_299 = "Error from SDNC: %s"; private static final String COULD_NOT_CONVERT_SDNC_POJO_TO_JSON = "ERROR: Could not convert SDNC pojo to json string."; - private static final String BRACKETS = "{} {} {} {} {}"; + private static final String BRACKETS = LoggingAnchor.FIVE; /*** * diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcAction.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcAction.java index 1718de9fe0..d6216c509d 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcAction.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcAction.java @@ -23,22 +23,17 @@ package org.onap.so.client.sdnc.beans; import org.onap.sdnc.northbound.client.model.GenericResourceApiSvcActionEnumeration; public enum SDNCSvcAction { - ACTIVATE("activate", GenericResourceApiSvcActionEnumeration.ACTIVATE), DELETE("delete", - GenericResourceApiSvcActionEnumeration.DELETE), ASSIGN("assign", - GenericResourceApiSvcActionEnumeration.ASSIGN), ROLLBACK("rollback", - GenericResourceApiSvcActionEnumeration.ROLLBACK), UNASSIGN("unassign", - GenericResourceApiSvcActionEnumeration.UNASSIGN), DEACTIVATE("deactivate", - GenericResourceApiSvcActionEnumeration.DEACTIVATE), CHANGE_DELETE( - "changedelete", - GenericResourceApiSvcActionEnumeration.CHANGEDELETE), CHANGE_ASSIGN( - "changeassign", - GenericResourceApiSvcActionEnumeration.CHANGEASSIGN), CREATE( - "create", - GenericResourceApiSvcActionEnumeration.CREATE), ENABLE( - "enable", - GenericResourceApiSvcActionEnumeration.ENABLE), DISABLE( - "disable", - GenericResourceApiSvcActionEnumeration.DISABLE); + ACTIVATE("activate", GenericResourceApiSvcActionEnumeration.ACTIVATE), + DELETE("delete", GenericResourceApiSvcActionEnumeration.DELETE), + ASSIGN("assign", GenericResourceApiSvcActionEnumeration.ASSIGN), + ROLLBACK("rollback", GenericResourceApiSvcActionEnumeration.ROLLBACK), + UNASSIGN("unassign", GenericResourceApiSvcActionEnumeration.UNASSIGN), + DEACTIVATE("deactivate", GenericResourceApiSvcActionEnumeration.DEACTIVATE), + CHANGE_DELETE("changedelete", GenericResourceApiSvcActionEnumeration.CHANGEDELETE), + CHANGE_ASSIGN("changeassign", GenericResourceApiSvcActionEnumeration.CHANGEASSIGN), + CREATE("create", GenericResourceApiSvcActionEnumeration.CREATE), + ENABLE("enable", GenericResourceApiSvcActionEnumeration.ENABLE), + DISABLE("disable", GenericResourceApiSvcActionEnumeration.DISABLE); private final String name; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcOperation.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcOperation.java index b9b04bc7b7..4edbf37bad 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcOperation.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCSvcOperation.java @@ -22,14 +22,14 @@ package org.onap.so.client.sdnc.beans; public enum SDNCSvcOperation { - VF_MODULE_TOPOLOGY_OPERATION("vf-module-topology-operation"), NETWORK_TOPOLOGY_OPERATION( - "network-topology-operation"), VNF_TOPOLOGY_OPERATION( - "vnf-topology-operation"), CONTRAIL_ROUTE_TOPOLOGY_OPERATION( - "contrail-route-topology-operation"), SECURITY_ZONE_TOPOLOGY_OPERATION( - "security-zone-topology-operation"), PORT_MIRROR_TOPOLOGY_OPERATION( - "port-mirror-topology-operation"), SERVICE_TOPOLOGY_OPERATION( - "service-topology-operation"), GENERIC_CONFIGURATION_TOPOLOGY_OPERATION( - "generic-configuration-topology-operation"); + VF_MODULE_TOPOLOGY_OPERATION("vf-module-topology-operation"), + NETWORK_TOPOLOGY_OPERATION("network-topology-operation"), + VNF_TOPOLOGY_OPERATION("vnf-topology-operation"), + CONTRAIL_ROUTE_TOPOLOGY_OPERATION("contrail-route-topology-operation"), + SECURITY_ZONE_TOPOLOGY_OPERATION("security-zone-topology-operation"), + PORT_MIRROR_TOPOLOGY_OPERATION("port-mirror-topology-operation"), + SERVICE_TOPOLOGY_OPERATION("service-topology-operation"), + GENERIC_CONFIGURATION_TOPOLOGY_OPERATION("generic-configuration-topology-operation"); private final String name; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/endpoint/SDNCTopology.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/endpoint/SDNCTopology.java index fb5f24694b..ae9fe6ad70 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/endpoint/SDNCTopology.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/endpoint/SDNCTopology.java @@ -22,11 +22,14 @@ package org.onap.so.client.sdnc.endpoint; public enum SDNCTopology { - SERVICE("service-topology-operation"), VNF("vnf-topology-operation"), VFMODULE( - "vf-module-topology-operation"), CONTRAILROUTE("contrail-route-topology-operation"), PORTMIRROR( - "port-mirror-topology-operation"), NETWORK("network-topology-operation"), SECURITYZONE( - "security-zone-topology-operation"), CONFIGURATION( - "generic-configuration-topology-operation"); + SERVICE("service-topology-operation"), + VNF("vnf-topology-operation"), + VFMODULE("vf-module-topology-operation"), + CONTRAILROUTE("contrail-route-topology-operation"), + PORTMIRROR("port-mirror-topology-operation"), + NETWORK("network-topology-operation"), + SECURITYZONE("security-zone-topology-operation"), + CONFIGURATION("generic-configuration-topology-operation"); private final String topology; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapper.java index 6627625d62..6ddb292a6c 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapper.java @@ -22,8 +22,10 @@ package org.onap.so.client.sdnc.mapper; +import java.net.URI; import java.util.Map; import java.util.UUID; +import org.onap.so.logger.LoggingAnchor; import org.onap.sdnc.northbound.client.model.GenericResourceApiParam; import org.onap.sdnc.northbound.client.model.GenericResourceApiParamParam; import org.onap.sdnc.northbound.client.model.GenericResourceApiRequestActionEnumeration; @@ -64,7 +66,7 @@ public class VfModuleTopologyOperationRequestMapper { public GenericResourceApiVfModuleOperationInformation reqMapper(SDNCSvcOperation svcOperation, SDNCSvcAction svcAction, VfModule vfModule, VolumeGroup volumeGroup, GenericVnf vnf, ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext, - String sdncAssignResponse) throws MapperException { + String sdncAssignResponse, URI callbackURL) throws MapperException { GenericResourceApiVfModuleOperationInformation req = new GenericResourceApiVfModuleOperationInformation(); boolean includeModelInformation = false; @@ -113,7 +115,7 @@ public class VfModuleTopologyOperationRequestMapper { GenericResourceApiVfmodulerequestinputVfModuleRequestInput vfModuleRequestInput = buildVfModuleRequestInput(vfModule, volumeGroup, cloudRegion, requestContext); GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = - buildVfModuleSdncRequestHeader(sdncReqId, genericResourceApiSvcAction); + buildVfModuleSdncRequestHeader(sdncReqId, genericResourceApiSvcAction, callbackURL); req.setRequestInformation(requestInformation); req.setSdncRequestHeader(sdncRequestHeader); @@ -169,13 +171,12 @@ public class VfModuleTopologyOperationRequestMapper { } private GenericResourceApiSdncrequestheaderSdncRequestHeader buildVfModuleSdncRequestHeader(String sdncReqId, - GenericResourceApiSvcActionEnumeration svcAction) { + GenericResourceApiSvcActionEnumeration svcAction, URI callbackUrl) { GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = new GenericResourceApiSdncrequestheaderSdncRequestHeader(); - sdncRequestHeader.setSvcRequestId(sdncReqId); sdncRequestHeader.setSvcAction(svcAction); - + sdncRequestHeader.setSvcNotificationUrl(callbackUrl.toString()); return sdncRequestHeader; } @@ -188,7 +189,7 @@ public class VfModuleTopologyOperationRequestMapper { mapper.readValue(sdncAssignResponse, GenericResourceApiVfModuleResponseInformation.class); objectPath = assignResponseInfo.getVfModuleResponseInformation().getObjectPath(); } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), e.getMessage(), "BPMN", + logger.error(LoggingAnchor.FIVE, MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), e.getMessage(), "BPMN", ErrorCode.UnknownError.getValue(), e.getMessage()); } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Candidate.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Candidate.java index cded23aad2..3127275b24 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Candidate.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Candidate.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -36,6 +36,13 @@ public class Candidate implements Serializable { @JsonProperty("cloudOwner") private String cloudOwner; + public Candidate() {} + + public Candidate(CandidateType identifierType, List<String> identifiers, String cloudOwner) { + this.identifierType = identifierType; + this.identifiers = identifiers; + this.cloudOwner = cloudOwner; + } public CandidateType getIdentifierType() { return identifierType; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Demand.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Demand.java index fe2b63ff92..0cc993560d 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Demand.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/Demand.java @@ -40,6 +40,8 @@ public class Demand implements Serializable { private List<Candidate> excludedCandidates; @JsonProperty("existingCandidates") private List<Candidate> existingCandidates; + @JsonProperty("filteringAttributes") + private List<Candidate> filteringAttributes; public List<Candidate> getRequiredCandidates() { @@ -90,4 +92,12 @@ public class Demand implements Serializable { this.existingCandidates = existingCandidates; } + public List<Candidate> getFilteringAttributes() { + return filteringAttributes; + } + + public void setFilteringAttributes(List<Candidate> filteringAttributes) { + this.filteringAttributes = filteringAttributes; + } + } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/ticket/ExternalTicket.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/ticket/ExternalTicket.java index a78dffb4e0..12adec9e24 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/ticket/ExternalTicket.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/ticket/ExternalTicket.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.client.ticket; public class ExternalTicket { diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/BaseTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/BaseTaskTest.java index b40e43b959..39efa6dc76 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/BaseTaskTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/BaseTaskTest.java @@ -35,6 +35,7 @@ import org.onap.so.client.aai.mapper.AAIObjectMapper; import org.onap.so.client.adapter.network.mapper.NetworkAdapterObjectMapper; import org.onap.so.client.appc.ApplicationControllerAction; import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.client.namingservice.NamingRequestObject; import org.onap.so.client.orchestration.AAICollectionResources; import org.onap.so.client.orchestration.AAIConfigurationResources; import org.onap.so.client.orchestration.AAIInstanceGroupResources; @@ -150,4 +151,8 @@ public abstract class BaseTaskTest extends TestDataSetup { @Mock protected Environment env; + + @Mock + protected NamingRequestObject namingRequestObject; + } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java index b054cc17bb..b889493d2e 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java @@ -60,6 +60,7 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoGenericVnf; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule; +import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.DuplicateNameException; import org.onap.so.client.exception.BBObjectNotFoundException; import org.onap.so.db.catalog.beans.OrchestrationStatus; import org.onap.so.client.aai.entities.uri.AAIResourceUri; @@ -122,12 +123,21 @@ public class AAICreateTasksTest extends BaseTaskTest { @Test public void createServiceInstanceTest() throws Exception { + doReturn(false).when(aaiServiceInstanceResources).checkInstanceServiceNameInUse(serviceInstance); doNothing().when(aaiServiceInstanceResources).createServiceInstance(serviceInstance, customer); aaiCreateTasks.createServiceInstance(execution); verify(aaiServiceInstanceResources, times(1)).createServiceInstance(serviceInstance, customer); } @Test + public void createServiceInstanceNameInUseExceptionTest() throws Exception { + expectedException.expect(BpmnError.class); + doReturn(true).when(aaiServiceInstanceResources).checkInstanceServiceNameInUse(serviceInstance); + execution.setVariable("aLaCarte", Boolean.TRUE); + aaiCreateTasks.createServiceInstance(execution); + } + + @Test public void createServiceInstanceExceptionTest() throws Exception { expectedException.expect(BpmnError.class); @@ -140,7 +150,7 @@ public class AAICreateTasksTest extends BaseTaskTest { @Test public void createVolumeGroupTest() throws Exception { volumeGroup.setOrchestrationStatus(OrchestrationStatus.PRECREATED); - + execution.setVariable("aLaCarte", Boolean.FALSE); doNothing().when(aaiVolumeGroupResources).createVolumeGroup(volumeGroup, cloudRegion); doNothing().when(aaiVolumeGroupResources).connectVolumeGroupToVnf(genericVnf, volumeGroup, cloudRegion); @@ -152,6 +162,14 @@ public class AAICreateTasksTest extends BaseTaskTest { } @Test + public void createVolumeGroupDuplicateNameTest() throws Exception { + expectedException.expect(BpmnError.class); + execution.setVariable("aLaCarte", Boolean.TRUE); + doReturn(true).when(aaiVolumeGroupResources).checkNameInUse(volumeGroup); + aaiCreateTasks.createVolumeGroup(execution); + } + + @Test public void createVolumeGroupExceptionTest() throws Exception { expectedException.expect(BpmnError.class); @@ -325,11 +343,20 @@ public class AAICreateTasksTest extends BaseTaskTest { @Test public void createVnfTest() throws Exception { doNothing().when(aaiVnfResources).createVnfandConnectServiceInstance(genericVnf, serviceInstance); + execution.setVariable("aLaCarte", Boolean.FALSE); aaiCreateTasks.createVnf(execution); verify(aaiVnfResources, times(1)).createVnfandConnectServiceInstance(genericVnf, serviceInstance); } @Test + public void createVnfDuplicateNameTest() throws Exception { + expectedException.expect(BpmnError.class); + doReturn(true).when(aaiVnfResources).checkNameInUse(genericVnf.getVnfName()); + execution.setVariable("aLaCarte", Boolean.TRUE); + aaiCreateTasks.createVnf(execution); + } + + @Test public void createVnfExceptionTest() throws Exception { expectedException.expect(BpmnError.class); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "notfound"); @@ -352,12 +379,21 @@ public class AAICreateTasksTest extends BaseTaskTest { .thenReturn(newVfModule); assertEquals(null, newVfModule.getModuleIndex()); + execution.setVariable("aLaCarte", Boolean.FALSE); aaiCreateTasks.createVfModule(execution); assertEquals(1, newVfModule.getModuleIndex().intValue()); verify(aaiVfModuleResources, times(1)).createVfModule(newVfModule, genericVnf); } @Test + public void createVfModuleDuplicateNameTest() throws Exception { + expectedException.expect(BpmnError.class); + execution.setVariable("aLaCarte", Boolean.TRUE); + doReturn(true).when(aaiVfModuleResources).checkNameInUse(vfModule); + aaiCreateTasks.createVfModule(execution); + } + + @Test public void createServiceSubscriptionTest() { doNothing().when(aaiServiceInstanceResources).createServiceSubscription(customer); aaiCreateTasks.createServiceSubscription(execution); @@ -398,13 +434,21 @@ public class AAICreateTasksTest extends BaseTaskTest { @Test public void createNetworkTest() throws Exception { network.getModelInfoNetwork().setNeutronNetworkType("PROVIDER"); - + execution.setVariable("aLaCarte", Boolean.FALSE); doNothing().when(aaiNetworkResources).createNetworkConnectToServiceInstance(network, serviceInstance); aaiCreateTasks.createNetwork(execution); verify(aaiNetworkResources, times(1)).createNetworkConnectToServiceInstance(network, serviceInstance); } @Test + public void createNetworkNameInUseExceptionTest() throws Exception { + expectedException.expect(BpmnError.class); + execution.setVariable("aLaCarte", Boolean.TRUE); + doReturn(true).when(aaiNetworkResources).checkNetworkNameInUse(network.getNetworkName()); + aaiCreateTasks.createNetwork(execution); + } + + @Test public void createNetworkExceptionTest() throws Exception { expectedException.expect(BpmnError.class); @@ -444,6 +488,7 @@ public class AAICreateTasksTest extends BaseTaskTest { public void createNetworkCollectionInstanceGroupTest() throws Exception { doNothing().when(aaiNetworkResources) .createNetworkInstanceGroup(serviceInstance.getCollection().getInstanceGroup()); + execution.setVariable("aLaCarte", Boolean.FALSE); aaiCreateTasks.createNetworkCollectionInstanceGroup(execution); verify(aaiNetworkResources, times(1)) .createNetworkInstanceGroup(serviceInstance.getCollection().getInstanceGroup()); @@ -509,11 +554,21 @@ public class AAICreateTasksTest extends BaseTaskTest { public void createConfigurationTest() throws Exception { gBBInput = execution.getGeneralBuildingBlock(); doNothing().when(aaiConfigurationResources).createConfiguration(configuration); + execution.setVariable("aLaCarte", Boolean.FALSE); aaiCreateTasks.createConfiguration(execution); verify(aaiConfigurationResources, times(1)).createConfiguration(configuration); } @Test + public void createConfigurationNameInUseExceptionTest() throws Exception { + expectedException.expect(BpmnError.class); + doReturn(true).when(aaiConfigurationResources) + .checkConfigurationNameInUse(configuration.getConfigurationName()); + execution.setVariable("aLaCarte", Boolean.TRUE); + aaiCreateTasks.createConfiguration(execution); + } + + @Test public void connectVnfToCloudRegionTest() throws Exception { gBBInput = execution.getGeneralBuildingBlock(); doNothing().when(aaiVnfResources).connectVnfToCloudRegion(genericVnf, gBBInput.getCloudRegion()); @@ -543,14 +598,26 @@ public class AAICreateTasksTest extends BaseTaskTest { @Test public void createInstanceGroupVnfTest() throws Exception { + doReturn(false).when(aaiInstanceGroupResources) + .checkInstanceGroupNameInUse(instanceGroup.getInstanceGroupName()); doNothing().when(aaiInstanceGroupResources).createInstanceGroupandConnectServiceInstance(instanceGroup, serviceInstance); + execution.setVariable("aLaCarte", Boolean.FALSE); aaiCreateTasks.createInstanceGroupVnf(execution); verify(aaiInstanceGroupResources, times(1)).createInstanceGroupandConnectServiceInstance(instanceGroup, serviceInstance); } @Test + public void createInstanceGroupVnfNameInUseExceptionTest() throws Exception { + expectedException.expect(BpmnError.class); + doReturn(true).when(aaiInstanceGroupResources) + .checkInstanceGroupNameInUse(instanceGroup.getInstanceGroupName()); + execution.setVariable("aLaCarte", Boolean.TRUE); + aaiCreateTasks.createInstanceGroupVnf(execution); + } + + @Test public void createInstanceGroupVnfExceptionTest() throws Exception { expectedException.expect(BpmnError.class); doThrow(RuntimeException.class).when(aaiInstanceGroupResources) diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTaskTest.java index 5805ea5ec1..caae90bfff 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTaskTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTaskTest.java @@ -119,5 +119,10 @@ public class InputParameterRetrieverTaskTest extends BaseTaskTest { return null; } + @Override + public int getCurrentSequence() { + return 0; + } + } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorInstantiateVnfmNodeTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorInstantiateVnfmNodeTaskTest.java new file mode 100644 index 0000000000..effcf24a8d --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorInstantiateVnfmNodeTaskTest.java @@ -0,0 +1,129 @@ +/*- + * ============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.bpmn.infrastructure.adapter.vnfm.tasks; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.CREATE_VNF_NODE_STATUS; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.VNF_CREATED; +import java.util.Optional; +import java.util.UUID; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.so.bpmn.BaseTaskTest; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; +import org.onap.so.client.orchestration.AAIVnfResources; + +/** + * + * @author Lathishbabu Ganesan (lathishbabu.ganesan@est.tech) + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class MonitorInstantiateVnfmNodeTaskTest extends BaseTaskTest { + + private static final String VNF_ID = UUID.randomUUID().toString(); + + private static final String VNF_NAME = "VNF_NAME"; + + private MonitorVnfmNodeTask objUnderTest; + + @Mock + private VnfmAdapterServiceProvider mockedVnfmAdapterServiceProvider; + + @Mock + private AAIVnfResources mockedAaiVnfResources; + + private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution(); + + @Before + public void setUp() { + objUnderTest = getEtsiVnfMonitorNodeJobTask(); + } + + @Test + public void testGetNodeStatus_genericVnfWithOrchStatusCreated_executionVariableSetToCreate() throws Exception { + final org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf = getGenericVnf(); + final GenericVnf aaiGenericVnf = getAAIGenericVnf(); + aaiGenericVnf.setOrchestrationStatus(VNF_CREATED); + + when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(vnf); + when(mockedAaiVnfResources.getGenericVnf(eq(VNF_ID))).thenReturn(Optional.of(aaiGenericVnf)); + objUnderTest.getNodeStatus(stubbedxecution); + assertTrue(stubbedxecution.getVariable(CREATE_VNF_NODE_STATUS)); + } + + @Test + public void testGetNodeStatus_noGenericVnfFoundInAAI_throwException() throws Exception { + final org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf = getGenericVnf(); + + when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(vnf); + when(mockedAaiVnfResources.getGenericVnf(eq(VNF_ID))).thenReturn(Optional.empty()); + objUnderTest.getNodeStatus(stubbedxecution); + verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1220), + any(Exception.class)); + assertNull(stubbedxecution.getVariable(CREATE_VNF_NODE_STATUS)); + + } + + @Test + public void testGetNodeStatusException() throws Exception { + when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenThrow(RuntimeException.class); + objUnderTest.getNodeStatus(stubbedxecution); + assertNull(stubbedxecution.getVariable(CREATE_VNF_NODE_STATUS)); + verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1220), + any(Exception.class)); + } + + @Test + public void testTimeOutLogFailue() throws Exception { + objUnderTest.timeOutLogFailue(stubbedxecution); + verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1221), + eq("Node operation time out")); + } + + private GenericVnf getAAIGenericVnf() { + final GenericVnf genericVnf = new GenericVnf(); + genericVnf.setVnfId(VNF_ID); + genericVnf.setVnfName(VNF_NAME); + return genericVnf; + } + + private org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf getGenericVnf() { + final org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf genericVnf = + new org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf(); + genericVnf.setVnfId(VNF_ID); + return genericVnf; + + } + + private MonitorInstantiateVnfmNodeTask getEtsiVnfMonitorNodeJobTask() { + return new MonitorInstantiateVnfmNodeTask(extractPojosForBB, exceptionUtil, mockedAaiVnfResources); + } + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeJobTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorTerminateVnfmNodeTaskTest.java index 6b84f6a918..04831733e1 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorVnfmNodeJobTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/MonitorTerminateVnfmNodeTaskTest.java @@ -20,16 +20,15 @@ package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; -import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.CREATE_VNF_NODE_STATUS; -import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.DELETE_VNF_NODE_STATUS; -import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.VNF_CREATED; -import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.VNF_ASSIGNED; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.DELETE_VNF_NODE_STATUS; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.VNF_ASSIGNED; +import java.util.Optional; import java.util.UUID; import org.junit.Before; import org.junit.Test; @@ -38,13 +37,14 @@ import org.onap.aai.domain.yang.GenericVnf; import org.onap.so.bpmn.BaseTaskTest; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; +import org.onap.so.client.orchestration.AAIVnfResources; /** * - * @author Lathishbabu Ganesan (lathishbabu.ganesan@est.tech) + * @author Waqas Ikram (waqas.ikram@est.tech) * */ -public class MonitorVnfmNodeJobTest extends BaseTaskTest { +public class MonitorTerminateVnfmNodeTaskTest extends BaseTaskTest { private static final String VNF_ID = UUID.randomUUID().toString(); @@ -55,6 +55,9 @@ public class MonitorVnfmNodeJobTest extends BaseTaskTest { @Mock private VnfmAdapterServiceProvider mockedVnfmAdapterServiceProvider; + @Mock + private AAIVnfResources mockedAaiVnfResources; + private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution(); @Before @@ -63,49 +66,48 @@ public class MonitorVnfmNodeJobTest extends BaseTaskTest { } @Test - public void testGetNodeStatusCreate() throws Exception { - GenericVnf vnf = getGenericVnf(); - vnf.setOrchestrationStatus(VNF_CREATED); - when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(vnf); - objUnderTest.getNodeStatus(stubbedxecution); - assertTrue(stubbedxecution.getVariable(CREATE_VNF_NODE_STATUS)); - } - - @Test public void testGetNodeStatusDelete() throws Exception { - GenericVnf vnf = getGenericVnf(); - vnf.setOrchestrationStatus(VNF_ASSIGNED); + final org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf = getGenericVnf(); + final GenericVnf aaiGenericVnf = getAAIGenericVnf(); + aaiGenericVnf.setOrchestrationStatus(VNF_ASSIGNED); + when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(vnf); + when(mockedAaiVnfResources.getGenericVnf(eq(VNF_ID))).thenReturn(Optional.of(aaiGenericVnf)); + objUnderTest.getNodeStatus(stubbedxecution); assertTrue(stubbedxecution.getVariable(DELETE_VNF_NODE_STATUS)); } @Test - public void testGetNodeStatusException() throws Exception { - when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenThrow(RuntimeException.class); + public void testGetNodeStatus_noGenericVnfFoundInAAI_throwException() throws Exception { + final org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf = getGenericVnf(); + + when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(vnf); + when(mockedAaiVnfResources.getGenericVnf(eq(VNF_ID))).thenReturn(Optional.empty()); objUnderTest.getNodeStatus(stubbedxecution); - assertNull(stubbedxecution.getVariable(CREATE_VNF_NODE_STATUS)); - assertNull(stubbedxecution.getVariable(DELETE_VNF_NODE_STATUS)); verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1220), any(Exception.class)); - } + assertNull(stubbedxecution.getVariable(DELETE_VNF_NODE_STATUS)); - @Test - public void testTimeOutLogFailue() throws Exception { - objUnderTest.timeOutLogFailue(stubbedxecution); - verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1221), - eq("Node operation time out")); } - private GenericVnf getGenericVnf() { + private GenericVnf getAAIGenericVnf() { final GenericVnf genericVnf = new GenericVnf(); genericVnf.setVnfId(VNF_ID); genericVnf.setVnfName(VNF_NAME); return genericVnf; } - private MonitorVnfmNodeTask getEtsiVnfMonitorNodeJobTask() { - return new MonitorVnfmNodeTask(extractPojosForBB, exceptionUtil); + private org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf getGenericVnf() { + final org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf genericVnf = + new org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf(); + genericVnf.setVnfId(VNF_ID); + return genericVnf; + + } + + private MonitorTerminateVnfmNodeTask getEtsiVnfMonitorNodeJobTask() { + return new MonitorTerminateVnfmNodeTask(extractPojosForBB, exceptionUtil, mockedAaiVnfResources); } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/StubbedBuildingBlockExecution.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/StubbedBuildingBlockExecution.java index 84012e8b8d..a4d8aa85a2 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/StubbedBuildingBlockExecution.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/StubbedBuildingBlockExecution.java @@ -79,6 +79,11 @@ public class StubbedBuildingBlockExecution implements BuildingBlockExecution { return null; } + @Override + public int getCurrentSequence() { + return 0; + } + public static String getTenantId() { return TENANT_ID; } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImplTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImplTest.java index 7bd6435b60..e94d7c2923 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImplTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImplTest.java @@ -228,7 +228,7 @@ public class VnfmAdapterServiceProviderImplTest { assertFalse(actual.isPresent()); } - @Test + @Test(expected = RestProcessingException.class) public void testGetInstantiateOperationJobStatus_Exception() { when(mockedHttpServiceProvider.getHttpResponse(eq(TestConstants.JOB_STATUS_EXPECTED_URL), @@ -237,8 +237,7 @@ public class VnfmAdapterServiceProviderImplTest { final VnfmAdapterServiceProvider objUnderTest = new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider); - final Optional<QueryJobResponse> actual = objUnderTest.getInstantiateOperationJobStatus(DUMMY_JOB_ID); - assertFalse(actual.isPresent()); + objUnderTest.getInstantiateOperationJobStatus(DUMMY_JOB_ID); } private QueryJobResponse getQueryJobResponse() { diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnfTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnfTest.java index 6f76c83c6f..982b75ae8e 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnfTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigDeployVnfTest.java @@ -1,16 +1,20 @@ - -/* - * ============LICENSE_START======================================================= ONAP : SO - * ================================================================================ Copyright 2019 TechMahindra - * ================================================================================= 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_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 TechMahindra + * ================================================================================ + * 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========================================================= */ diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2IT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2IT.java index b5a8318ce9..7b6ba6b8fd 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2IT.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2IT.java @@ -110,13 +110,13 @@ public class SniroHomingV2IT extends BaseIntegrationTest { public void beforeServiceProxy() { ServiceProxy sp = setServiceProxy("1", "infrastructure"); - Candidate requiredCandidate = new Candidate(); - requiredCandidate.setIdentifierType(CandidateType.CLOUD_REGION_ID); + Candidate filteringAttributes = new Candidate(); + filteringAttributes.setIdentifierType(CandidateType.CLOUD_REGION_ID); List<String> c = new ArrayList<String>(); c.add("testCloudRegionId"); - requiredCandidate.setCloudOwner("att"); - requiredCandidate.setIdentifiers(c); - sp.addRequiredCandidates(requiredCandidate); + filteringAttributes.setCloudOwner("att"); + filteringAttributes.setIdentifiers(c); + sp.getFilteringAttributes().add(filteringAttributes); serviceInstance.getServiceProxies().add(sp); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasksTest.java index f9ad473e5a..9677f8e8f3 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/manualhandling/tasks/ManualHandlingTasksTest.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.infrastructure.manualhandling.tasks; import static org.junit.Assert.assertEquals; diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasksTest.java index f5785f94fd..44e5e0e707 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasksTest.java @@ -22,31 +22,50 @@ package org.onap.so.bpmn.infrastructure.namingservice.tasks; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.aai.domain.yang.Zone; import org.onap.so.bpmn.BaseTaskTest; +import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; +import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; +import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils; +import org.onap.so.client.aai.AAICommonObjectMapperProvider; +import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.so.client.aai.entities.Relationships; import org.onap.so.client.exception.BBObjectNotFoundException; public class NamingServiceCreateTasksTest extends BaseTaskTest { @InjectMocks - private NamingServiceCreateTasks namingServiceCreateTasks = new NamingServiceCreateTasks(); + private NamingServiceCreateTasks namingServiceCreateTasks; + + @Mock + private BBInputSetupUtils MOCK_bbInputSetupUtils; private InstanceGroup instanceGroup; + private ServiceInstance serviceInstance; @Before public void before() throws BBObjectNotFoundException { instanceGroup = setInstanceGroup(); when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID))) .thenReturn(instanceGroup); + serviceInstance = setServiceInstance(); + when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))) + .thenReturn(serviceInstance); } @Test @@ -80,7 +99,29 @@ public class NamingServiceCreateTasksTest extends BaseTaskTest { namingServiceCreateTasks.createInstanceGroupName(execution); verify(namingServiceResources, times(1)).generateInstanceGroupName(instanceGroup, policyInstanceName, nfNamingCode); + } + + @Test + public void createWanTransportServiceNameTest() throws Exception { + String generatedName = "generatedWanTransportServiceName"; + doReturn(generatedName).when(namingServiceResources).generateServiceInstanceName(any()); + NamingServiceCreateTasks spy = Mockito.spy(namingServiceCreateTasks); + spy.createWanTransportServiceName(execution); + verify(namingServiceResources, times(1)).generateServiceInstanceName(any()); + assertEquals(generatedName, serviceInstance.getServiceInstanceName()); } + @Test + public void createVpnBondingServiceNameTest() throws Exception { + when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))) + .thenReturn(buildL3Network()); + when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VPN_ID))) + .thenReturn(buildVpnBinding()); + String generatedName = "generatedWanTransportServiceName"; + doReturn(generatedName).when(namingServiceResources).generateServiceInstanceName(any()); + namingServiceCreateTasks.createVpnBondingServiceName(execution); + verify(namingServiceResources, times(1)).generateServiceInstanceName(any()); + assertEquals(generatedName, serviceInstance.getServiceInstanceName()); + } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasksTest.java index 758b8f4ffd..32550a5467 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasksTest.java @@ -21,6 +21,7 @@ package org.onap.so.bpmn.infrastructure.namingservice.tasks; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; @@ -32,14 +33,17 @@ import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.onap.so.bpmn.BaseTaskTest; import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; import org.onap.so.client.exception.BBObjectNotFoundException; +import org.onap.so.client.namingservice.NamingRequestObject; public class NamingServiceDeleteTasksTest extends BaseTaskTest { @InjectMocks private NamingServiceDeleteTasks namingServiceDeleteTasks = new NamingServiceDeleteTasks(); private InstanceGroup instanceGroup; + private ServiceInstance serviceInstance; @Before public void before() throws BBObjectNotFoundException { @@ -68,4 +72,15 @@ public class NamingServiceDeleteTasksTest extends BaseTaskTest { verify(namingServiceResources, times(1)).deleteInstanceGroupName(instanceGroup); } + @Test + public void deleteServiceInstanceNameTest() throws Exception { + serviceInstance = setServiceInstance(); + when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))) + .thenReturn(serviceInstance); + doNothing().when(namingRequestObject).setExternalKeyValue(serviceInstance.getServiceInstanceId()); + doReturn("").when(namingServiceResources).deleteServiceInstanceName(namingRequestObject); + namingServiceDeleteTasks.deleteServiceInstanceName(execution); + verify(namingServiceResources, times(1)).deleteServiceInstanceName(any(NamingRequestObject.class)); + } + } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTaskTest.java index 4eb1432bbf..ffd4f74b63 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTaskTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTaskTest.java @@ -29,6 +29,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.net.URI; import org.camunda.bpm.engine.delegate.BpmnError; import org.junit.Before; import org.junit.Test; @@ -85,7 +86,10 @@ public class SDNCActivateTaskTest extends BaseTaskTest { when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network); when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))) .thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))) + .thenReturn(serviceInstance); + when(env.getRequiredProperty("mso.workflow.message.endpoint")).thenReturn("http://localhost:9090"); } @Test @@ -129,11 +133,12 @@ public class SDNCActivateTaskTest extends BaseTaskTest { @Test public void activateVfModuleTest() throws Exception { - doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources) - .activateVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext); + doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources).activateVfModule( + eq(vfModule), eq(genericVnf), eq(serviceInstance), eq(customer), eq(cloudRegion), eq(requestContext), + any(URI.class)); sdncActivateTasks.activateVfModule(execution); - verify(sdncVfModuleResources, times(1)).activateVfModule(vfModule, genericVnf, serviceInstance, customer, - cloudRegion, requestContext); + verify(sdncVfModuleResources, times(1)).activateVfModule(eq(vfModule), eq(genericVnf), eq(serviceInstance), + eq(customer), eq(cloudRegion), eq(requestContext), any(URI.class)); SDNCRequest sdncRequest = execution.getVariable("SDNCRequest"); assertEquals(SDNCTopology.VFMODULE, sdncRequest.getTopology()); } @@ -141,8 +146,8 @@ public class SDNCActivateTaskTest extends BaseTaskTest { @Test public void activateVfModuleTestException() throws Exception { expectedException.expect(BpmnError.class); - doThrow(RuntimeException.class).when(sdncVfModuleResources).activateVfModule(vfModule, genericVnf, - serviceInstance, customer, cloudRegion, requestContext); + doThrow(RuntimeException.class).when(sdncVfModuleResources).activateVfModule(eq(vfModule), eq(genericVnf), + eq(serviceInstance), eq(customer), eq(cloudRegion), eq(requestContext), any(URI.class)); sdncActivateTasks.activateVfModule(execution); } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasksTest.java index 7d8e94d1e9..982868dcbc 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasksTest.java @@ -28,6 +28,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.net.URI; import org.camunda.bpm.engine.delegate.BpmnError; import org.junit.Before; import org.junit.Test; @@ -89,6 +90,7 @@ public class SDNCAssignTasksTest extends BaseTaskTest { .thenReturn(serviceInstance); when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))) .thenReturn(volumeGroup); + when(env.getRequiredProperty("mso.workflow.message.endpoint")).thenReturn("http://localhost:9090"); } @Test @@ -132,10 +134,11 @@ public class SDNCAssignTasksTest extends BaseTaskTest { @Test public void assignVfModuleTest() throws Exception { doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources).assignVfModule( - vfModule, volumeGroup, genericVnf, serviceInstance, customer, cloudRegion, requestContext); + eq(vfModule), eq(volumeGroup), eq(genericVnf), eq(serviceInstance), eq(customer), eq(cloudRegion), + eq(requestContext), any(URI.class)); sdncAssignTasks.assignVfModule(execution); - verify(sdncVfModuleResources, times(1)).assignVfModule(vfModule, volumeGroup, genericVnf, serviceInstance, - customer, cloudRegion, requestContext); + verify(sdncVfModuleResources, times(1)).assignVfModule(eq(vfModule), eq(volumeGroup), eq(genericVnf), + eq(serviceInstance), eq(customer), eq(cloudRegion), eq(requestContext), any(URI.class)); SDNCRequest sdncRequest = execution.getVariable("SDNCRequest"); assertEquals(SDNCTopology.VFMODULE, sdncRequest.getTopology()); } @@ -143,8 +146,8 @@ public class SDNCAssignTasksTest extends BaseTaskTest { @Test public void assignVfModuleExceptionTest() throws Exception { expectedException.expect(BpmnError.class); - doThrow(RuntimeException.class).when(sdncVfModuleResources).assignVfModule(vfModule, volumeGroup, genericVnf, - serviceInstance, customer, cloudRegion, requestContext); + doThrow(RuntimeException.class).when(sdncVfModuleResources).assignVfModule(eq(vfModule), eq(volumeGroup), + eq(genericVnf), eq(serviceInstance), eq(customer), eq(cloudRegion), eq(requestContext), any(URI.class)); sdncAssignTasks.assignVfModule(execution); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasksTest.java index 1c1616a472..8c25bea801 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasksTest.java @@ -27,6 +27,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.net.URI; import org.camunda.bpm.engine.delegate.BpmnError; import org.junit.Before; import org.junit.Test; @@ -74,6 +75,7 @@ public class SDNCChangeAssignTasksTest extends BaseTaskTest { when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))) .thenReturn(serviceInstance); + when(env.getRequiredProperty("mso.workflow.message.endpoint")).thenReturn("http://localhost:9090"); } @Test @@ -97,11 +99,12 @@ public class SDNCChangeAssignTasksTest extends BaseTaskTest { @Test public void changeAssignModelVfModuleTest() throws Exception { - doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources) - .changeAssignVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext); + doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources).changeAssignVfModule( + eq(vfModule), eq(genericVnf), eq(serviceInstance), eq(customer), eq(cloudRegion), eq(requestContext), + any(URI.class)); sdncChangeAssignTasks.changeAssignModelVfModule(execution); - verify(sdncVfModuleResources, times(1)).changeAssignVfModule(vfModule, genericVnf, serviceInstance, customer, - cloudRegion, requestContext); + verify(sdncVfModuleResources, times(1)).changeAssignVfModule(eq(vfModule), eq(genericVnf), eq(serviceInstance), + eq(customer), eq(cloudRegion), eq(requestContext), any(URI.class)); SDNCRequest sdncRequest = execution.getVariable("SDNCRequest"); assertEquals(SDNCTopology.VFMODULE, sdncRequest.getTopology()); } @@ -109,8 +112,8 @@ public class SDNCChangeAssignTasksTest extends BaseTaskTest { @Test public void changeAssignModelVfModuleExceptionTest() throws Exception { expectedException.expect(BpmnError.class); - doThrow(RuntimeException.class).when(sdncVfModuleResources).changeAssignVfModule(vfModule, genericVnf, - serviceInstance, customer, cloudRegion, requestContext); + doThrow(RuntimeException.class).when(sdncVfModuleResources).changeAssignVfModule(eq(vfModule), eq(genericVnf), + eq(serviceInstance), eq(customer), eq(cloudRegion), eq(requestContext), any(URI.class)); sdncChangeAssignTasks.changeAssignModelVfModule(execution); } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTaskTest.java index 08d4d196da..d8a1b0182e 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTaskTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTaskTest.java @@ -28,6 +28,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.net.URI; import org.camunda.bpm.engine.delegate.BpmnError; import org.junit.Before; import org.junit.Test; @@ -81,16 +82,17 @@ public class SDNCDeactivateTaskTest extends BaseTaskTest { when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))) .thenReturn(serviceInstance); - + when(env.getRequiredProperty("mso.workflow.message.endpoint")).thenReturn("http://localhost:9090"); } @Test public void deactivateVfModuleTest() throws Exception { - doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources) - .deactivateVfModule(vfModule, genericVnf, serviceInstance, customer, cloudRegion, requestContext); + doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources).deactivateVfModule( + eq(vfModule), eq(genericVnf), eq(serviceInstance), eq(customer), eq(cloudRegion), eq(requestContext), + any(URI.class)); sdncDeactivateTasks.deactivateVfModule(execution); - verify(sdncVfModuleResources, times(1)).deactivateVfModule(vfModule, genericVnf, serviceInstance, customer, - cloudRegion, requestContext); + verify(sdncVfModuleResources, times(1)).deactivateVfModule(eq(vfModule), eq(genericVnf), eq(serviceInstance), + eq(customer), eq(cloudRegion), eq(requestContext), any(URI.class)); SDNCRequest sdncRequest = execution.getVariable("SDNCRequest"); assertEquals(SDNCTopology.VFMODULE, sdncRequest.getTopology()); } @@ -98,8 +100,8 @@ public class SDNCDeactivateTaskTest extends BaseTaskTest { @Test public void deactivateVfModuleExceptionTest() throws Exception { expectedException.expect(BpmnError.class); - doThrow(RuntimeException.class).when(sdncVfModuleResources).deactivateVfModule(vfModule, genericVnf, - serviceInstance, customer, cloudRegion, requestContext); + doThrow(RuntimeException.class).when(sdncVfModuleResources).deactivateVfModule(eq(vfModule), eq(genericVnf), + eq(serviceInstance), eq(customer), eq(cloudRegion), eq(requestContext), any(URI.class)); sdncDeactivateTasks.deactivateVfModule(execution); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasksTest.java index b5d34ea4c9..6a94b357e0 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasksTest.java @@ -23,8 +23,6 @@ package org.onap.so.bpmn.infrastructure.sdnc.tasks; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; import java.io.IOException; import java.io.StringReader; import java.nio.file.Files; @@ -39,7 +37,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; @@ -69,6 +66,7 @@ public class SDNCRequestTasksTest extends SDNCRequestTasks { @Mock SDNCClient sdncClient; + @Spy private ExceptionBuilder exceptionBuilder; @@ -151,7 +149,7 @@ public class SDNCRequestTasksTest extends SDNCRequestTasks { db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader(sdncResponse))); - String finalMessageIndicator = getXmlElement(doc, "/input/ack-final-indicator"); + String finalMessageIndicator = getXmlElement(doc, "//*:ack-final-indicator"); String responseCode = getXmlElement(doc, "/input/response-code"); String responseMessage = getXmlElement(doc, "/input/response-message"); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasksTest.java index 968723c628..10c034dc36 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasksTest.java @@ -29,6 +29,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.net.URI; import org.camunda.bpm.engine.delegate.BpmnError; import org.junit.Before; import org.junit.Test; @@ -81,6 +82,7 @@ public class SDNCUnassignTasksTest extends BaseTaskTest { when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))) .thenReturn(serviceInstance); + when(env.getRequiredProperty("mso.workflow.message.endpoint")).thenReturn("http://localhost:9090"); } @Test @@ -105,9 +107,10 @@ public class SDNCUnassignTasksTest extends BaseTaskTest { @Test public void unassignVfModuleTest() throws Exception { doReturn(new GenericResourceApiVfModuleOperationInformation()).when(sdncVfModuleResources) - .unassignVfModule(vfModule, genericVnf, serviceInstance); + .unassignVfModule(eq(vfModule), eq(genericVnf), eq(serviceInstance), any(URI.class)); sdncUnassignTasks.unassignVfModule(execution); - verify(sdncVfModuleResources, times(1)).unassignVfModule(vfModule, genericVnf, serviceInstance); + verify(sdncVfModuleResources, times(1)).unassignVfModule(eq(vfModule), eq(genericVnf), eq(serviceInstance), + any(URI.class)); SDNCRequest sdncRequest = execution.getVariable("SDNCRequest"); assertEquals(SDNCTopology.VFMODULE, sdncRequest.getTopology()); } @@ -115,8 +118,8 @@ public class SDNCUnassignTasksTest extends BaseTaskTest { @Test public void unassignVfModuleExceptionTest() throws Exception { expectedException.expect(BpmnError.class); - doThrow(RuntimeException.class).when(sdncVfModuleResources).unassignVfModule(vfModule, genericVnf, - serviceInstance); + doThrow(RuntimeException.class).when(sdncVfModuleResources).unassignVfModule(eq(vfModule), eq(genericVnf), + eq(serviceInstance), any(URI.class)); sdncUnassignTasks.unassignVfModule(execution); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/VrfValidationTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/VrfValidationTest.java new file mode 100644 index 0000000000..c05fd879ac --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/VrfValidationTest.java @@ -0,0 +1,219 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.infrastructure.workflow.tasks; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.onap.aai.domain.yang.AggregateRoute; +import org.onap.aai.domain.yang.AggregateRoutes; +import org.onap.aai.domain.yang.L3Network; +import org.onap.aai.domain.yang.RouteTarget; +import org.onap.aai.domain.yang.RouteTargets; +import org.onap.aai.domain.yang.Subnet; +import org.onap.aai.domain.yang.Subnets; +import org.onap.aai.domain.yang.VpnBinding; +import org.onap.so.bpmn.BaseTaskTest; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.db.catalog.beans.ConfigurationResourceCustomization; +import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.catalog.beans.ServiceProxyResourceCustomization; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class VrfValidationTest extends BaseTaskTest { + + protected ObjectMapper mapper = new ObjectMapper(); + + @InjectMocks + protected VrfValidation vrfValidation; + + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + + @Before + public void before() throws Exception { + vrfValidation.setBbInputSetupUtils(bbSetupUtils); + } + + @Test + public void testVrfServiceValidation() throws VrfBondingServiceException { + Service service = new Service(); + service.setModelName("modelName"); + service.setServiceType("BONDING"); + service.setServiceRole("VPN"); + exceptionRule.expect(VrfBondingServiceException.class); + exceptionRule.expectMessage( + "Service: modelName does not have service type of BONDING and does not have service role of INFRASTRUCTURE-VPN"); + vrfValidation.vrfServiceValidation(service); + + service.setServiceType("BOND"); + service.setServiceRole("INFRASTRUCTURE-VPN"); + exceptionRule.expect(VrfBondingServiceException.class); + exceptionRule.expectMessage( + "Service: modelName does not have service type of BONDING and does not have service role of INFRASTRUCTURE-VPN"); + vrfValidation.vrfServiceValidation(service); + + service.setServiceType("BONDING"); + service.setServiceRole("INFRASTRUCTURE-VPN"); + ExpectedException.none(); + vrfValidation.vrfServiceValidation(service); + } + + @Test + public void testVrfCatalogDbChecks() throws VrfBondingServiceException { + Service service = new Service(); + service.setModelName("modelName"); + ConfigurationResourceCustomization configuration = new ConfigurationResourceCustomization(); + service.setConfigurationCustomizations(new ArrayList<>()); + service.getConfigurationCustomizations().add(configuration); + ServiceProxyResourceCustomization serviceProxy = new ServiceProxyResourceCustomization(); + configuration.setServiceProxyResourceCustomization(serviceProxy); + service.setServiceProxyCustomizations(new ArrayList<>()); + service.getServiceProxyCustomizations().add(serviceProxy); + Service sourceService = new Service(); + sourceService.setServiceType("TRANSPORT"); + serviceProxy.setSourceService(sourceService); + configuration.setType("VRF-ENTRY"); + configuration.setRole("INFRASTRUCTURE-CLOUD-VPN"); + ExpectedException.none(); + vrfValidation.vrfCatalogDbChecks(service); + } + + @Test + public void testAaiVpnBindingValidation() throws VrfBondingServiceException { + org.onap.aai.domain.yang.VpnBinding aaiVpnBinding = new org.onap.aai.domain.yang.VpnBinding(); + aaiVpnBinding.setVpnType("SERVICE-INFRASTRUCTURE"); + ExpectedException.none(); + vrfValidation.aaiVpnBindingValidation("test-vpn", aaiVpnBinding); + } + + @Test + public void testAaiVpnBindingValidationVpnBindingIsNull() throws VrfBondingServiceException { + exceptionRule.expect(VrfBondingServiceException.class); + exceptionRule.expectMessage("The infrastructure vpn test-vpn does not exist in A&AI."); + vrfValidation.aaiVpnBindingValidation("test-vpn", null); + } + + @Test + public void testAaiNetworkValidation() throws VrfBondingServiceException { + org.onap.aai.domain.yang.L3Network aaiLocalNetwork = new org.onap.aai.domain.yang.L3Network(); + aaiLocalNetwork.setNetworkId("test-network"); + ExpectedException.none(); + vrfValidation.aaiNetworkValidation("test-network", aaiLocalNetwork); + } + + @Test + public void testAaiNetworkValidationNetworkIsNull() throws VrfBondingServiceException { + exceptionRule.expect(VrfBondingServiceException.class); + exceptionRule.expectMessage("The local network test-network does not exist in A&AI."); + vrfValidation.aaiNetworkValidation("test-network", null); + } + + @Test + public void testAaiAggregateRouteValidation() throws VrfBondingServiceException { + org.onap.aai.domain.yang.L3Network aaiLocalNetwork = new org.onap.aai.domain.yang.L3Network(); + aaiLocalNetwork.setAggregateRoutes(new AggregateRoutes()); + aaiLocalNetwork.getAggregateRoutes().getAggregateRoute().add(new AggregateRoute()); + aaiLocalNetwork.getAggregateRoutes().getAggregateRoute().get(0).setIpVersion("4"); + ExpectedException.none(); + vrfValidation.aaiAggregateRouteValidation(aaiLocalNetwork); + + aaiLocalNetwork.getAggregateRoutes().getAggregateRoute().add(new AggregateRoute()); + aaiLocalNetwork.getAggregateRoutes().getAggregateRoute().get(1).setIpVersion("6"); + ExpectedException.none(); + vrfValidation.aaiAggregateRouteValidation(aaiLocalNetwork); + + aaiLocalNetwork.setAggregateRoutes(null); + ExpectedException.none(); + vrfValidation.aaiAggregateRouteValidation(aaiLocalNetwork); + } + + @Test + public void testAaiSubnetValidation() throws VrfBondingServiceException { + org.onap.aai.domain.yang.L3Network aaiLocalNetwork = new org.onap.aai.domain.yang.L3Network(); + aaiLocalNetwork.setNetworkId("myNetworkID"); + aaiLocalNetwork.setSubnets(new Subnets()); + aaiLocalNetwork.getSubnets().getSubnet().add(new Subnet()); + aaiLocalNetwork.getSubnets().getSubnet().get(0).setIpVersion("4"); + ExpectedException.none(); + vrfValidation.aaiSubnetValidation(aaiLocalNetwork); + + aaiLocalNetwork.getSubnets().getSubnet().add(new Subnet()); + aaiLocalNetwork.getSubnets().getSubnet().get(1).setIpVersion("6"); + ExpectedException.none(); + vrfValidation.aaiSubnetValidation(aaiLocalNetwork); + + aaiLocalNetwork.setSubnets(null); + exceptionRule.expect(VrfBondingServiceException.class); + exceptionRule.expectMessage("LocalNetwork: myNetworkID has no subnets"); + vrfValidation.aaiSubnetValidation(aaiLocalNetwork); + } + + @Test + public void testIpVersionValidation() { + String ipVersion1 = "4"; + String ipVersion2 = "6"; + boolean validation = vrfValidation.ipVersionValidation(ipVersion1, ipVersion2); + assertEquals("Validation is correct", true, validation); + + + validation = vrfValidation.ipVersionValidation(ipVersion2, ipVersion1); + assertEquals("Validation is correct", true, validation); + + ipVersion1 = "6"; + validation = vrfValidation.ipVersionValidation(ipVersion1, ipVersion2); + assertEquals("Validation is correct", false, validation); + } + + @Test + public void testAaiRouteTargetValidation() + throws VrfBondingServiceException, JsonParseException, JsonMappingException, IOException { + L3Network l3Network = mapper.readValue( + new File("src/test/resources/__files/BuildingBlocks/aaiNetworkWrapper.json"), L3Network.class); + AAIResultWrapper networkWrapper = new AAIResultWrapper(l3Network); + if (networkWrapper.getRelationships().isPresent()) { + List<AAIResourceUri> vpnBindingUris = + networkWrapper.getRelationships().get().getRelatedUris(AAIObjectType.VPN_BINDING); + VpnBinding vpnBinding = new VpnBinding(); + vpnBinding.setRouteTargets(new RouteTargets()); + vpnBinding.getRouteTargets().getRouteTarget().add(new RouteTarget()); + AAIResultWrapper wrapper = Mockito.mock(AAIResultWrapper.class); + doReturn(wrapper).when(bbSetupUtils).getAAIResourceDepthOne(vpnBindingUris.get(0)); + doReturn(Optional.of(vpnBinding)).when(wrapper).asBean(VpnBinding.class); + ExpectedException.none(); + vrfValidation.aaiRouteTargetValidation(l3Network); + } + } +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailureTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailureTest.java index 52a2cf7223..c683303a41 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailureTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBFailureTest.java @@ -21,16 +21,15 @@ package org.onap.so.bpmn.infrastructure.workflow.tasks; import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; import java.sql.Timestamp; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake; -import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -157,7 +156,6 @@ public class WorkflowActionBBFailureTest extends BaseTaskTest { doReturn(reqMock).when(requestsDbClient).getInfraActiveRequestbyRequestId(reqId); workflowActionBBFailure.updateRequestErrorStatusMessage(execution); Mockito.verify(reqMock, Mockito.times(1)).setStatusMessage("Error Case"); - Mockito.verify(reqMock, Mockito.times(1)).setRequestStatus("FAILED"); Mockito.verify(reqMock, Mockito.times(1)).setProgress(Long.valueOf(100)); Mockito.verify(reqMock, Mockito.times(1)).setLastModifiedBy("CamundaBPMN"); Mockito.verify(reqMock, Mockito.times(1)).setEndTime(any(Timestamp.class)); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksTest.java index a60927d694..aac09b4475 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksTest.java @@ -42,12 +42,15 @@ import org.mockito.Mockito; import org.mockito.Spy; import org.onap.aai.domain.yang.GenericVnf; import org.onap.so.bpmn.BaseTaskTest; +import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulatorListenerRunner; import org.onap.so.bpmn.core.WorkflowException; import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds; import org.onap.so.db.catalog.beans.VnfResourceCustomization; import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.RequestDetails; import org.springframework.core.env.Environment; public class WorkflowActionBBTasksTest extends BaseTaskTest { @@ -70,6 +73,9 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { @Mock protected Environment environment; + @Mock + private FlowManipulatorListenerRunner flowManipulatorListenerRunner; + @Rule public ExpectedException thrown = ExpectedException.none(); @@ -95,14 +101,16 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { ExecuteBuildingBlock ebb = new ExecuteBuildingBlock(); String vnfCustomizationUUID = "1234567"; - String serviceInstanceId = "1234567"; + String modelUuid = "1234567"; BuildingBlock buildingBlock = new BuildingBlock(); buildingBlock.setBpmnFlowName("ConfigAssignVnfBB"); buildingBlock.setKey(vnfCustomizationUUID); ebb.setBuildingBlock(buildingBlock); - WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); - workflowResourceIds.setServiceInstanceId(serviceInstanceId); - ebb.setWorkflowResourceIds(workflowResourceIds); + RequestDetails rd = new RequestDetails(); + ModelInfo mi = new ModelInfo(); + mi.setModelUuid(modelUuid); + rd.setModelInfo(mi); + ebb.setRequestDetails(rd); flowsToExecute.add(ebb); List<VnfResourceCustomization> vnfResourceCustomizations = new ArrayList(); @@ -112,8 +120,7 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { vnfResourceCustomizations.add(vrc); GenericVnf genericVnf = new GenericVnf(); genericVnf.setModelCustomizationId(vnfCustomizationUUID); - doReturn(vnfResourceCustomizations).when(catalogDbClient) - .getVnfResourceCustomizationByModelUuid(serviceInstanceId); + doReturn(vnfResourceCustomizations).when(catalogDbClient).getVnfResourceCustomizationByModelUuid(modelUuid); doReturn(vrc).when(catalogDbClient).findVnfResourceCustomizationInList(vnfCustomizationUUID, vnfResourceCustomizations); @@ -138,14 +145,16 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock(); String vnfCustomizationUUID = "1234567"; - String serviceInstanceId = "1234567"; + String modelUuid = "1234567"; BuildingBlock buildingBlock = new BuildingBlock(); buildingBlock.setBpmnFlowName("ConfigDeployVnfBB"); buildingBlock.setKey(vnfCustomizationUUID); ebb.setBuildingBlock(buildingBlock); - WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); - workflowResourceIds.setServiceInstanceId(serviceInstanceId); - ebb.setWorkflowResourceIds(workflowResourceIds); + RequestDetails rd = new RequestDetails(); + ModelInfo mi = new ModelInfo(); + mi.setModelUuid(modelUuid); + rd.setModelInfo(mi); + ebb.setRequestDetails(rd); flowsToExecute.add(ebb); List<VnfResourceCustomization> vnfResourceCustomizations = new ArrayList(); @@ -155,8 +164,7 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { vnfResourceCustomizations.add(vrc); GenericVnf genericVnf = new GenericVnf(); genericVnf.setModelCustomizationId(vnfCustomizationUUID); - doReturn(vnfResourceCustomizations).when(catalogDbClient) - .getVnfResourceCustomizationByModelUuid(serviceInstanceId); + doReturn(vnfResourceCustomizations).when(catalogDbClient).getVnfResourceCustomizationByModelUuid(modelUuid); doReturn(vrc).when(catalogDbClient).findVnfResourceCustomizationInList(vnfCustomizationUUID, vnfResourceCustomizations); 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 ad1238b86f..09ba55aac0 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 @@ -22,12 +22,17 @@ package org.onap.so.bpmn.infrastructure.workflow.tasks; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyObject; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Matchers.isA; +import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; import com.fasterxml.jackson.databind.ObjectMapper; @@ -45,6 +50,7 @@ import java.util.UUID; import org.camunda.bpm.engine.delegate.BpmnError; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake; +import org.javatuples.Pair; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; @@ -60,7 +66,6 @@ import org.onap.aai.domain.yang.RelationshipList; import org.onap.aai.domain.yang.ServiceInstance; import org.onap.aai.domain.yang.VfModule; import org.onap.aai.domain.yang.VfModules; -import org.onap.aai.domain.yang.Vnfc; import org.onap.aai.domain.yang.VolumeGroup; import org.onap.so.bpmn.BaseTaskTest; import org.onap.so.bpmn.servicedecomposition.bbobjects.Collection; @@ -78,6 +83,7 @@ import org.onap.so.db.catalog.beans.CollectionResource; import org.onap.so.db.catalog.beans.CollectionResourceCustomization; import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization; import org.onap.so.db.catalog.beans.ConfigurationResource; +import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization; import org.onap.so.db.catalog.beans.CvnfcCustomization; import org.onap.so.db.catalog.beans.HeatEnvironment; import org.onap.so.db.catalog.beans.HeatTemplate; @@ -86,7 +92,6 @@ import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization; import org.onap.so.db.catalog.beans.NetworkResourceCustomization; import org.onap.so.db.catalog.beans.Service; import org.onap.so.db.catalog.beans.VfModuleCustomization; -import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization; import org.onap.so.db.catalog.beans.macro.NorthBoundRequest; import org.onap.so.db.catalog.beans.macro.OrchestrationFlow; import org.onap.so.serviceinstancebeans.RequestDetails; @@ -1550,7 +1555,7 @@ public class WorkflowActionTest extends BaseTaskTest { @Ignore @Test - public void traverseCatalogDbServiceMultipleNetworkTest() throws IOException { + public void traverseCatalogDbServiceMultipleNetworkTest() throws IOException, VrfBondingServiceException { execution.setVariable("testProcessKey", "testProcessKeyValue"); Service service = new Service(); List<NetworkResourceCustomization> networkCustomizations = new ArrayList<>(); @@ -1584,7 +1589,8 @@ public class WorkflowActionTest extends BaseTaskTest { ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class); List<Resource> resourceCounter = new ArrayList<>(); thrown.expect(BpmnError.class); - workflowAction.traverseCatalogDbService(execution, sIRequest, resourceCounter); + List<Pair<WorkflowType, String>> aaiResourceIds = new ArrayList<>(); + workflowAction.traverseCatalogDbService(execution, sIRequest, resourceCounter, aaiResourceIds); } @Test @@ -1672,6 +1678,72 @@ public class WorkflowActionTest extends BaseTaskTest { assertNotNull(result); } + @Test + public void traverseAAIServiceTest() { + List<Resource> resourceCounter = new ArrayList<>(); + String resourceId = "si0"; + List<Pair<WorkflowType, String>> aaiResourceIds = new ArrayList<>(); + + ServiceInstance serviceInstanceAAI = new ServiceInstance(); + serviceInstanceAAI.setServiceInstanceId(resourceId); + + org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstance = setServiceInstance(); + setGenericVnf(); + setVfModule(true); + setVolumeGroup(); + setL3Network(); + setCollection(); + setConfiguration(); + + Configuration config = new Configuration(); + config.setConfigurationId("testConfigurationId2"); + serviceInstance.getConfigurations().add(config); + + Relationship relationship1 = new Relationship(); + relationship1.setRelatedTo("vnfc"); + RelationshipList relationshipList1 = new RelationshipList(); + relationshipList1.getRelationship().add(relationship1); + + Relationship relationship2 = new Relationship(); + relationship2.setRelatedTo("vpn-binding"); + RelationshipList relationshipList2 = new RelationshipList(); + relationshipList2.getRelationship().add(relationship2); + + org.onap.aai.domain.yang.Configuration aaiConfiguration1 = new org.onap.aai.domain.yang.Configuration(); + aaiConfiguration1.setConfigurationId("testConfigurationId"); + aaiConfiguration1.setRelationshipList(relationshipList1); + + org.onap.aai.domain.yang.Configuration aaiConfiguration2 = new org.onap.aai.domain.yang.Configuration(); + aaiConfiguration2.setConfigurationId("testConfigurationId2"); + aaiConfiguration2.setRelationshipList(relationshipList1); + + try { + doReturn(serviceInstanceAAI).when(bbSetupUtils).getAAIServiceInstanceById(resourceId); + doReturn(serviceInstance).when(bbInputSetup).getExistingServiceInstance(serviceInstanceAAI); + doReturn(Optional.of(aaiConfiguration1)).when(aaiConfigurationResources) + .getConfiguration("testConfigurationId"); + doReturn(Optional.of(aaiConfiguration2)).when(aaiConfigurationResources) + .getConfiguration("testConfigurationId2"); + workflowAction.traverseAAIService(execution, resourceCounter, resourceId, aaiResourceIds); + assertEquals(8, resourceCounter.size()); + assertThat(aaiResourceIds, sameBeanAs(getExpectedResourceIds())); + } catch (Exception e) { + fail("Unexpected exception was thrown."); + } + } + + private List<Pair<WorkflowType, String>> getExpectedResourceIds() { + List<Pair<WorkflowType, String>> resourceIds = new ArrayList<>(); + resourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VNF, "testVnfId1")); + resourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VFMODULE, "testVfModuleId1")); + resourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VOLUMEGROUP, "testVolumeGroupId1")); + resourceIds.add(new Pair<WorkflowType, String>(WorkflowType.NETWORK, "testNetworkId1")); + resourceIds.add(new Pair<WorkflowType, String>(WorkflowType.NETWORKCOLLECTION, "testId")); + resourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION, "testConfigurationId")); + resourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION, "testConfigurationId2")); + return resourceIds; + } + private List<OrchestrationFlow> createFlowList(String... flowNames) { List<OrchestrationFlow> result = new ArrayList<>(); for (String flowName : flowNames) { diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/MultiStageSkipTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/MultiStageSkipTest.java new file mode 100644 index 0000000000..b6f8aafa55 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/listeners/MultiStageSkipTest.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.infrastructure.workflow.tasks.listeners; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; +import java.util.ArrayList; +import java.util.List; +import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.bpmn.common.BBConstants; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.DelegateExecutionImpl; +import org.onap.so.bpmn.infrastructure.workflow.tasks.listeners.MultiStageSkipListener; +import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock; +import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; +import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds; +import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.db.catalog.client.CatalogDbClient; + +@RunWith(MockitoJUnitRunner.class) +public class MultiStageSkipTest { + + @Mock + private CatalogDbClient catalogDbClient; + + @Mock + private BBInputSetupUtils bbInputSetupUtils; + + @InjectMocks + private MultiStageSkipListener multiStageSkipListener; + + @Test + public void testTrigger() { + BuildingBlockExecution execution = new DelegateExecutionImpl(new DelegateExecutionFake()); + execution.setVariable(BBConstants.G_ALACARTE, true); + + assertTrue("should be triggered", multiStageSkipListener.shouldRunFor("AssignVfModuleBB", true, execution)); + + execution.setVariable(BBConstants.G_ALACARTE, false); + assertFalse("should not be triggered", + multiStageSkipListener.shouldRunFor("AssignVfModuleBB", true, execution)); + + execution.setVariable(BBConstants.G_ALACARTE, true); + assertFalse("should not be triggered", + multiStageSkipListener.shouldRunFor("AssignVfModuleBB2", true, execution)); + + + } + + @Test + public void testProcessMultiStageSkip() { + String vfModuleId = "vfModuleId"; + String vnfId = "vnfId"; + List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>(); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("serviceInstanceId"); + workflowResourceIds.setVnfId(vnfId); + flowsToExecute.add(new ExecuteBuildingBlock()); + flowsToExecute.add(new ExecuteBuildingBlock()); + flowsToExecute.add(new ExecuteBuildingBlock()); + flowsToExecute.get(0).setResourceId(vfModuleId); + flowsToExecute.get(0).setBuildingBlock(new BuildingBlock()); + flowsToExecute.get(0).getBuildingBlock().setBpmnFlowName("AssignVfModuleBB"); + flowsToExecute.get(0).setWorkflowResourceIds(workflowResourceIds); + BuildingBlockExecution execution = new DelegateExecutionImpl(new DelegateExecutionFake()); + + org.onap.aai.domain.yang.VfModule vfModule = new org.onap.aai.domain.yang.VfModule(); + vfModule.setVfModuleId(vfModuleId); + org.onap.aai.domain.yang.GenericVnf vnf = new org.onap.aai.domain.yang.GenericVnf(); + vnf.setModelCustomizationId("modelCustomizationUUID"); + VnfResourceCustomization vnfCust = new VnfResourceCustomization(); + vnfCust.setModelCustomizationUUID("modelCustomizationUUID"); + vnfCust.setMultiStageDesign("true"); + when(catalogDbClient.getVnfResourceCustomizationByModelCustomizationUUID(vnf.getModelCustomizationId())) + .thenReturn(vnfCust); + when(bbInputSetupUtils.getAAIVfModule(eq(vnfId), eq(vfModuleId))).thenReturn(null); + when(bbInputSetupUtils.getAAIGenericVnf(eq(vnfId))).thenReturn(vnf); + + multiStageSkipListener.run(flowsToExecute, flowsToExecute.get(0), execution); + assertEquals("Flows should only have Assign", flowsToExecute.size(), 1); + assertEquals("Flows should only have Assign", flowsToExecute.get(0).getBuildingBlock().getBpmnFlowName(), + "AssignVfModuleBB"); + + } +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapperTest.java index ccd677c80e..d6485bd57f 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapperTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapperTest.java @@ -21,8 +21,7 @@ package org.onap.so.client.adapter.network.mapper; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.isA; +import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doReturn; import java.io.UnsupportedEncodingException; import java.nio.file.Files; @@ -39,7 +38,6 @@ import org.onap.so.adapters.nwrest.ContrailNetwork; import org.onap.so.adapters.nwrest.CreateNetworkRequest; import org.onap.so.adapters.nwrest.CreateNetworkResponse; import org.onap.so.adapters.nwrest.DeleteNetworkRequest; -import org.onap.so.adapters.nwrest.NetworkTechnology; import org.onap.so.adapters.nwrest.ProviderVlanNetwork; import org.onap.so.adapters.nwrest.RollbackNetworkRequest; import org.onap.so.adapters.nwrest.UpdateNetworkRequest; @@ -385,4 +383,19 @@ public class NetworkAdapterObjectMapperTest extends TestDataSetup { assertThat(createNetworkRequest, sameBeanAs(expectedCreateNetworkRequest).ignoring("messageId") .ignoring("msoRequest.requestId").ignoring("networkParams")); } + + @Test + public void buildOpenstackSubnetListMultipleHostRoutesTest() throws Exception { + + ObjectMapper omapper = new ObjectMapper(); + String l3NetworkJson = + new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "l3-network-multiple-subnets.json"))); + L3Network l3Network = omapper.readValue(l3NetworkJson, L3Network.class); + + List<org.onap.so.openstack.beans.Subnet> subnets = + SPY_networkAdapterObjectMapper.buildOpenstackSubnetList(l3Network); + assertEquals("192.168.0.0/16", subnets.get(0).getHostRoutes().get(0).getPrefix()); + assertEquals("192.168.1.5/16", subnets.get(0).getHostRoutes().get(1).getPrefix()); + + } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientResponseValidatorTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientResponseValidatorTest.java index f50916c0be..f7fd00a673 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientResponseValidatorTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingClientResponseValidatorTest.java @@ -36,6 +36,7 @@ public class NamingClientResponseValidatorTest extends TestDataSetup { private NamingClientResponseValidator responseValidator = new NamingClientResponseValidator(); private String instanceGroupName = "generatedInstanceGroupName"; + private String serviceInstanceName = "generatedServiceInstanceName"; @Test public void validateNameGenResponseSuccessTest() throws BadResponseException { @@ -54,6 +55,22 @@ public class NamingClientResponseValidatorTest extends TestDataSetup { } @Test + public void validateServiceInstanceNameGenResponseSuccessTest() throws BadResponseException { + NameGenResponse name = new NameGenResponse(); + Respelement respElement = new Respelement(); + respElement.setResourceName("Service-Instance-Name"); + respElement.setResourceValue(serviceInstanceName); + List<Respelement> respList = new ArrayList<Respelement>(); + respList.add(respElement); + name.setElements(respList); + ResponseEntity<NameGenResponse> resp = new ResponseEntity<>(name, null, HttpStatus.OK); + + String actual = responseValidator.validateNameGenResponse(resp); + + assertEquals(actual, "generatedServiceInstanceName"); + } + + @Test public void validateNameGenResponseNoNameGeneratedTest() throws BadResponseException { NameGenResponse name = new NameGenResponse(); Respelement respElement = new Respelement(); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingRequestObjectTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingRequestObjectTest.java new file mode 100644 index 0000000000..7c50b2031d --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingRequestObjectTest.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.client.namingservice; + +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertThat; +import java.util.HashMap; +import org.junit.Test; +import org.onap.namingservice.model.Element; + +public class NamingRequestObjectTest { + + private String externalKey = "95cbbe59-1017-4c13-b4e8-d824e54def3e"; + private String policyInstanceName = "MSO_Policy.Config_MS_VNFInstanceGroup"; + private String namingType = "Service"; + private String nfNamingCode = "NamingCode"; + private String resourceName = "resourceName"; + private String serviceModelName = "serviceModelName"; + private String modelVersion = "modelVersion"; + + @Test + public void namingRequestObjectTest() { + + Element expected = new Element(); + expected.put(NamingServiceConstants.NS_EXTERNAL_KEY, externalKey); + expected.put(NamingServiceConstants.NS_POLICY_INSTANCE_NAME, policyInstanceName); + expected.put(NamingServiceConstants.NS_NAMING_TYPE, namingType); + expected.put(NamingServiceConstants.NS_RESOURCE_NAME, resourceName); + expected.put(NamingServiceConstants.NS_NF_NAMING_CODE, nfNamingCode); + + NamingRequestObject namingRequestObject = new NamingRequestObject(); + namingRequestObject.setExternalKeyValue(externalKey); + namingRequestObject.setPolicyInstanceNameValue(policyInstanceName); + namingRequestObject.setNamingTypeValue(namingType); + namingRequestObject.setNfNamingCodeValue(nfNamingCode); + namingRequestObject.setResourceNameValue(resourceName); + + HashMap<String, String> actual = namingRequestObject.getNamingRequestObjectMap(); + assertThat(actual, sameBeanAs(expected)); + } + + @Test + public void namingWanTransportRequestObjectTest() { + + Element expected = new Element(); + expected.put(NamingServiceConstants.NS_EXTERNAL_KEY, externalKey); + expected.put(NamingServiceConstants.NS_POLICY_INSTANCE_NAME, policyInstanceName); + expected.put(NamingServiceConstants.NS_NAMING_TYPE, namingType); + expected.put(NamingServiceConstants.NS_RESOURCE_NAME, resourceName); + expected.put(NamingServiceConstants.NS_SERVICE_MODEL_NAME, serviceModelName); + expected.put(NamingServiceConstants.NS_MODEL_VERSION, modelVersion); + + NamingRequestObject namingRequestObject = new NamingRequestObject(); + namingRequestObject.setExternalKeyValue(externalKey); + namingRequestObject.setPolicyInstanceNameValue(policyInstanceName); + namingRequestObject.setNamingTypeValue(namingType); + namingRequestObject.setResourceNameValue(resourceName); + namingRequestObject.setModelVersionValue(modelVersion); + namingRequestObject.setServiceModelNameValue(serviceModelName); + + HashMap<String, String> actual = namingRequestObject.getNamingRequestObjectMap(); + assertThat(actual, sameBeanAs(expected)); + } +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingRequestUtilsTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingRequestUtilsTest.java new file mode 100644 index 0000000000..5fdb790405 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/namingservice/NamingRequestUtilsTest.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.client.namingservice; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.so.bpmn.BaseTaskTest; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; +import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; +import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceInstance; +import org.onap.so.client.exception.BBObjectNotFoundException; + +public class NamingRequestUtilsTest extends BaseTaskTest { + + @Mock + private ServiceInstance serviceInstanceMock; + + @Mock + ModelInfoServiceInstance modelInfoServiceInstanceMock; + + @InjectMocks + private NamingServiceUtils namingServiceUtils = new NamingServiceUtils(); + + @Before + public void before() throws BBObjectNotFoundException { + when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))) + .thenReturn(serviceInstanceMock); + doReturn(modelInfoServiceInstanceMock).when(serviceInstanceMock).getModelInfoServiceInstance(); + } + + @Test + public void checkVpnBondingServiceTest() { + doReturn("bonding").when(modelInfoServiceInstanceMock).getServiceType(); + doReturn("infrastructure-vpn").when(modelInfoServiceInstanceMock).getServiceRole(); + doReturn("testNaminPolicy").when(modelInfoServiceInstanceMock).getNamingPolicy(); + doReturn(true).when(modelInfoServiceInstanceMock).getOnapGeneratedNaming(); + namingServiceUtils.checkVpnBondingService(execution); + assertTrue(execution.getVariable("isVpnBondingService")); + + doReturn("bonding-false").when(modelInfoServiceInstanceMock).getServiceType(); + doReturn("infrastructure-vpn").when(modelInfoServiceInstanceMock).getServiceRole(); + namingServiceUtils.checkVpnBondingService(execution); + assertFalse(execution.getVariable("isVpnBondingService")); + } + + @Test + public void checkBondingAndInfrastureVpnTrueTest() { + doReturn("bonding").when(modelInfoServiceInstanceMock).getServiceType(); + doReturn("infrastructure-vpn").when(modelInfoServiceInstanceMock).getServiceRole(); + namingServiceUtils.checkBondingAndInfrastureVpn(execution); + assertTrue(execution.getVariable("isBondingAndInsfrastructureVpn")); + } + + @Test + public void checkBondingAndInfrastureVpnFalse1Test() { + doReturn("falseBonding").when(modelInfoServiceInstanceMock).getServiceType(); + doReturn("infrastructure-vpn").when(modelInfoServiceInstanceMock).getServiceRole(); + namingServiceUtils.checkBondingAndInfrastureVpn(execution); + assertFalse(execution.getVariable("isBondingAndInsfrastructureVpn")); + } + + @Test + public void checkBondingAndInfrastureVpnFalse2Test() { + doReturn("bonding").when(modelInfoServiceInstanceMock).getServiceType(); + doReturn("false-infrastructure-vpn").when(modelInfoServiceInstanceMock).getServiceRole(); + namingServiceUtils.checkBondingAndInfrastureVpn(execution); + assertFalse(execution.getVariable("isBondingAndInsfrastructureVpn")); + } + + @Test + public void checkNamingPolicyAndAndEcompGeneratedNaming_TrueTest() { + doReturn("testNaminPolicy").when(modelInfoServiceInstanceMock).getNamingPolicy(); + doReturn(true).when(modelInfoServiceInstanceMock).getOnapGeneratedNaming(); + namingServiceUtils.checkNamingPolicyAndOnapGeneratedNaming(execution); + assertTrue(execution.getVariable("isNamingPolicyAndOnapGeneratedNaming")); + } + + @Test + public void checkNamingPolicyAndAndEcompGeneratedNamingFalse1Test() throws BBObjectNotFoundException { + doReturn(null).when(modelInfoServiceInstanceMock).getNamingPolicy(); + doReturn(true).when(modelInfoServiceInstanceMock).getOnapGeneratedNaming(); + namingServiceUtils.checkNamingPolicyAndOnapGeneratedNaming(execution); + assertFalse(execution.getVariable("isNamingPolicyAndOnapGeneratedNaming")); + } + + @Test + public void checkNamingPolicyAndAndEcompGeneratedNamingFalse2Test() throws BBObjectNotFoundException { + doReturn("testNaminPolicy").when(modelInfoServiceInstanceMock).getNamingPolicy(); + doReturn(false).when(modelInfoServiceInstanceMock).getOnapGeneratedNaming(); + namingServiceUtils.checkNamingPolicyAndOnapGeneratedNaming(execution); + assertFalse(execution.getVariable("isNamingPolicyAndOnapGeneratedNaming")); + } + + @Test + public void checkNamingPolicyAndAndEcompGeneratedNamingFalse3Test() throws BBObjectNotFoundException { + doReturn("").when(modelInfoServiceInstanceMock).getNamingPolicy(); + doReturn(false).when(modelInfoServiceInstanceMock).getOnapGeneratedNaming(); + namingServiceUtils.checkNamingPolicyAndOnapGeneratedNaming(execution); + assertFalse(execution.getVariable("isNamingPolicyAndOnapGeneratedNaming")); + } + + @Test + public void checkNamingPolicyAndAndEcompGeneratedNamingFalse4Test() throws BBObjectNotFoundException { + doReturn("bonding").when(modelInfoServiceInstanceMock).getNamingPolicy(); + doReturn(null).when(modelInfoServiceInstanceMock).getOnapGeneratedNaming(); + namingServiceUtils.checkNamingPolicyAndOnapGeneratedNaming(execution); + assertFalse(execution.getVariable("isNamingPolicyAndOnapGeneratedNaming")); + } + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIConfigurationResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIConfigurationResourcesTest.java index be58ccb046..68f3d20c82 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIConfigurationResourcesTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIConfigurationResourcesTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,6 +20,8 @@ package org.onap.so.client.orchestration; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; @@ -44,6 +46,7 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceProxy; import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; import org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBinding; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.client.aai.entities.AAIEdgeLabel; @@ -231,4 +234,32 @@ public class AAIConfigurationResourcesTest extends TestDataSetup { verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), ArgumentMatchers.isNull()); assertEquals(OrchestrationStatus.ACTIVE, configuration.getOrchestrationStatus()); } + + @Test + public void updateConfigurationOrchestrationStatusTest() throws Exception { + doNothing().when(MOCK_aaiResourcesClient).update(isA(AAIResourceUri.class), + isA(org.onap.aai.domain.yang.Configuration.class)); + aaiConfigurationResources.updateConfigurationOrchestrationStatus(configuration, OrchestrationStatus.ACTIVE); + verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), + any(org.onap.aai.domain.yang.Configuration.class)); + } + + @Test + public void checkConfigurationNameInUseTrueTest() throws Exception { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.CONFIGURATION) + .queryParam("configuration-name", "configurationName"); + doReturn(true).when(MOCK_aaiResourcesClient).exists(eq(uri)); + boolean nameInUse = aaiConfigurationResources.checkConfigurationNameInUse("configurationName"); + assertTrue(nameInUse); + } + + @Test + public void checkConfigurationNameInUseFalseTest() throws Exception { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.CONFIGURATION) + .queryParam("configuration-name", "configurationName"); + doReturn(false).when(MOCK_aaiResourcesClient).exists(eq(uri)); + boolean nameInUse = aaiConfigurationResources.checkConfigurationNameInUse("configurationName"); + assertFalse(nameInUse); + } + } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIInstanceGroupResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIInstanceGroupResourcesTest.java index 8c0d27f799..cb5683d9d8 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIInstanceGroupResourcesTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIInstanceGroupResourcesTest.java @@ -22,6 +22,8 @@ package org.onap.so.client.orchestration; import static org.mockito.ArgumentMatchers.eq; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doNothing; @@ -40,6 +42,7 @@ import org.onap.so.bpmn.common.InjectionHelper; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.client.aai.entities.AAIEdgeLabel; @@ -131,4 +134,22 @@ public class AAIInstanceGroupResourcesTest extends TestDataSetup { verify(MOCK_aaiResourcesClient, times(1)).connect(any(AAIResourceUri.class), any(AAIResourceUri.class)); } + @Test + public void checkInstanceGroupNameInUseTrueTest() throws Exception { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.INSTANCE_GROUP) + .queryParam("instance-group-name", "instanceGroupName"); + doReturn(true).when(MOCK_aaiResourcesClient).exists(eq(uri)); + boolean nameInUse = aaiInstanceGroupResources.checkInstanceGroupNameInUse("instanceGroupName"); + assertTrue(nameInUse); + } + + @Test + public void checkInstanceGroupNameInUseFalseTest() throws Exception { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.INSTANCE_GROUP) + .queryParam("instance-group-name", "instanceGroupName"); + doReturn(false).when(MOCK_aaiResourcesClient).exists(eq(uri)); + boolean nameInUse = aaiInstanceGroupResources.checkInstanceGroupNameInUse("instanceGroupName"); + assertFalse(nameInUse); + } + } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAINetworkResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAINetworkResourcesTest.java index d41148d784..b6161d7669 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAINetworkResourcesTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAINetworkResourcesTest.java @@ -23,6 +23,7 @@ package org.onap.so.client.orchestration; 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.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -425,4 +426,22 @@ public class AAINetworkResourcesTest extends TestDataSetup { verify(MOCK_aaiResourcesClient, times(1)).delete(any(AAIResourceUri.class)); } + @Test + public void checkInstanceGroupNameInUseTrueTest() throws Exception { + AAIResourceUri uri = + AAIUriFactory.createResourceUri(AAIObjectPlurals.L3_NETWORK).queryParam("network-name", "networkName"); + doReturn(true).when(MOCK_aaiResourcesClient).exists(eq(uri)); + boolean nameInUse = aaiNetworkResources.checkNetworkNameInUse("networkName"); + assertTrue(nameInUse); + } + + @Test + public void checkInstanceGroupNameInUseFalseTest() throws Exception { + AAIResourceUri uri = + AAIUriFactory.createResourceUri(AAIObjectPlurals.L3_NETWORK).queryParam("network-name", "networkName"); + doReturn(false).when(MOCK_aaiResourcesClient).exists(eq(uri)); + boolean nameInUse = aaiNetworkResources.checkNetworkNameInUse("networkName"); + assertFalse(nameInUse); + } + } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIServiceInstanceResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIServiceInstanceResourcesTest.java index 14df832754..ea98ee0169 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIServiceInstanceResourcesTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIServiceInstanceResourcesTest.java @@ -21,8 +21,11 @@ package org.onap.so.client.orchestration; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; @@ -43,8 +46,10 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.OwningEntity; import org.onap.so.bpmn.servicedecomposition.bbobjects.Project; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceSubscription; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.aai.mapper.AAIObjectMapper; import org.onap.so.db.catalog.beans.OrchestrationStatus; @@ -186,4 +191,23 @@ public class AAIServiceInstanceResourcesTest extends TestDataSetup { verify(MOCK_aaiResourcesClient, times(1)).update(any(AAIResourceUri.class), any(org.onap.aai.domain.yang.ServiceInstance.class)); } + + @Test + public void checkInstanceServiceNameInUseTrueTest() throws Exception { + AAIResourceUri uri = AAIUriFactory.createNodesUri(AAIObjectPlurals.SERVICE_INSTANCE) + .queryParam("service-instance-name", serviceInstance.getServiceInstanceName()); + doReturn(true).when(MOCK_aaiResourcesClient).exists(eq(uri)); + boolean nameInUse = aaiServiceInstanceResources.checkInstanceServiceNameInUse(serviceInstance); + assertTrue(nameInUse); + } + + @Test + public void checkInstanceServiceNameInUseFalseTest() throws Exception { + AAIResourceUri uri = AAIUriFactory.createNodesUri(AAIObjectPlurals.SERVICE_INSTANCE) + .queryParam("service-instance-name", serviceInstance.getServiceInstanceName()); + doReturn(false).when(MOCK_aaiResourcesClient).exists(eq(uri)); + boolean nameInUse = aaiServiceInstanceResources.checkInstanceServiceNameInUse(serviceInstance); + assertFalse(nameInUse); + } + } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVfModuleResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVfModuleResourcesTest.java index ae3ebeddbd..9e3bc4f552 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVfModuleResourcesTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVfModuleResourcesTest.java @@ -21,7 +21,10 @@ package org.onap.so.client.orchestration; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; @@ -41,8 +44,10 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; import org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.aai.mapper.AAIObjectMapper; import org.onap.so.db.catalog.beans.OrchestrationStatus; @@ -154,4 +159,39 @@ public class AAIVfModuleResourcesTest extends TestDataSetup { assertEquals("testContrailServiceInstanceFqdn", vfModule.getContrailServiceInstanceFqdn()); } + + @Test + public void checkNameInUseTrueTest() throws Exception { + AAIResourceUri vfModuleUri = AAIUriFactory.createNodesUri(AAIObjectPlurals.VF_MODULE) + .queryParam("vf-module-name", vfModule.getVfModuleName()); + AAIResourceUri vfModuleUriWithCustomization = vfModuleUri.clone().queryParam("model-customization-id", + vfModule.getModelInfoVfModule().getModelCustomizationUUID()); + doReturn(false).when(MOCK_aaiResourcesClient).exists(eq(vfModuleUriWithCustomization)); + doReturn(true).when(MOCK_aaiResourcesClient).exists(eq(vfModuleUri)); + boolean nameInUse = aaiVfModuleResources.checkNameInUse(vfModule); + assertTrue(nameInUse); + } + + @Test + public void checkNameInUseFalseIsResumeTest() throws Exception { + AAIResourceUri vfModuleUri = AAIUriFactory.createNodesUri(AAIObjectPlurals.VF_MODULE) + .queryParam("vf-module-name", vfModule.getVfModuleName()); + AAIResourceUri vfModuleUriWithCustomization = vfModuleUri.clone().queryParam("model-customization-id", + vfModule.getModelInfoVfModule().getModelCustomizationUUID()); + doReturn(true).when(MOCK_aaiResourcesClient).exists(eq(vfModuleUriWithCustomization)); + boolean nameInUse = aaiVfModuleResources.checkNameInUse(vfModule); + assertFalse(nameInUse); + } + + @Test + public void checkNameInUseFalseTest() throws Exception { + AAIResourceUri vfModuleUri = AAIUriFactory.createNodesUri(AAIObjectPlurals.VF_MODULE) + .queryParam("vf-module-name", vfModule.getVfModuleName()); + AAIResourceUri vfModuleUriWithCustomization = vfModuleUri.clone().queryParam("model-customization-id", + vfModule.getModelInfoVfModule().getModelCustomizationUUID()); + doReturn(false).when(MOCK_aaiResourcesClient).exists(eq(vfModuleUriWithCustomization)); + doReturn(false).when(MOCK_aaiResourcesClient).exists(eq(vfModuleUri)); + boolean nameInUse = aaiVfModuleResources.checkNameInUse(vfModule); + assertFalse(nameInUse); + } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java index cdc601c1e4..0d48a29ca9 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java @@ -21,6 +21,7 @@ package org.onap.so.client.orchestration; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -45,9 +46,11 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; import org.onap.so.bpmn.servicedecomposition.bbobjects.LineOfBusiness; import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.client.aai.AAIValidatorImpl; +import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.aai.mapper.AAIObjectMapper; @@ -227,4 +230,23 @@ public class AAIVnfResourcesTest extends TestDataSetup { verify(MOCK_aaiValidatorImpl, times(1)).isPhysicalServerLocked(isA(String.class)); assertTrue(isVnfPserversLockedFlag); } + + + @Test + public void checkNameInUseTrueTest() { + AAIResourceUri vnfUri = + AAIUriFactory.createResourceUri(AAIObjectPlurals.GENERIC_VNF).queryParam("vnf-name", "vnfName"); + doReturn(true).when(MOCK_aaiResourcesClient).exists(eq(vnfUri)); + boolean nameInUse = aaiVnfResources.checkNameInUse("vnfName"); + assertTrue(nameInUse); + } + + @Test + public void checkNameInUseFalseTest() { + AAIResourceUri vnfUri = + AAIUriFactory.createResourceUri(AAIObjectPlurals.GENERIC_VNF).queryParam("vnf-name", "vnfName"); + doReturn(false).when(MOCK_aaiResourcesClient).exists(eq(vnfUri)); + boolean nameInUse = aaiVnfResources.checkNameInUse("vnfName"); + assertFalse(nameInUse); + } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVolumeGroupResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVolumeGroupResourcesTest.java index 2bdcf30a4c..5772cab995 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVolumeGroupResourcesTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVolumeGroupResourcesTest.java @@ -21,7 +21,10 @@ package org.onap.so.client.orchestration; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; @@ -39,8 +42,11 @@ import org.onap.so.bpmn.common.InjectionHelper; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; import org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.aai.mapper.AAIObjectMapper; import org.onap.so.db.catalog.beans.OrchestrationStatus; @@ -146,4 +152,22 @@ public class AAIVolumeGroupResourcesTest extends TestDataSetup { assertEquals("testVolumeHeatStackId", volumeGroup.getHeatStackId()); } + + @Test + public void checkNameInUseTrueTest() { + AAIResourceUri volumeGroupUri = AAIUriFactory.createNodesUri(AAIObjectPlurals.VOLUME_GROUP) + .queryParam("volume-group-name", "testVolumeGroupName1"); + doReturn(true).when(MOCK_aaiResourcesClient).exists(eq(volumeGroupUri)); + boolean nameInUse = aaiVolumeGroupResources.checkNameInUse(volumeGroup); + assertTrue(nameInUse); + } + + @Test + public void checkNameInUseFalseTest() { + AAIResourceUri volumeGroupUri = AAIUriFactory.createNodesUri(AAIObjectPlurals.VOLUME_GROUP) + .queryParam("volume-group-name", "testVolumeGroupName1"); + doReturn(false).when(MOCK_aaiResourcesClient).exists(eq(volumeGroupUri)); + boolean nameInUse = aaiVolumeGroupResources.checkNameInUse(volumeGroup); + assertFalse(nameInUse); + } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NamingServiceResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NamingServiceResourcesTest.java index 195c89a651..c60e749a29 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NamingServiceResourcesTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/NamingServiceResourcesTest.java @@ -42,7 +42,9 @@ import org.onap.namingservice.model.NameGenRequest; import org.onap.namingservice.model.NameGenResponse; import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup; import org.onap.so.client.namingservice.NamingClient; +import org.onap.so.client.namingservice.NamingRequestObject; import org.onap.so.client.namingservice.NamingRequestObjectBuilder; +import org.onap.so.client.namingservice.NamingServiceConstants; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -100,5 +102,37 @@ public class NamingServiceResourcesTest extends TestDataSetup { } + @Test + public void generateServiceInstanceNameTest() throws Exception { + + NameGenRequest req = new NameGenRequest(); + doReturn("generatedServiceInstanceName").when(MOCK_namingClient).postNameGenRequest(isA(NameGenRequest.class)); + doReturn(req).when(MOCK_namingRequestObjectBuilder).nameGenRequestMapper(isA(List.class)); + NamingRequestObject nrObject = new NamingRequestObject(); + nrObject.setExternalKeyValue("testExternalKey"); + nrObject.setNamingTypeValue(NamingServiceConstants.NAMING_TYPE_SERVICE); + nrObject.setResourceNameValue(NamingServiceConstants.RESOURCE_NAME_SERVICE_INSTANCE_NAME); + nrObject.setPolicyInstanceNameValue(execution.getVariable("policyInstanceName")); + nrObject.setServiceModelNameValue("testServiceInstanceModelName"); + nrObject.setModelVersionValue("testServiceInstanceModelVersion"); + nrObject.setZoneIdValue(execution.getVariable("zoneId")); + + String generatedName = namingServiceResources.generateServiceInstanceName(nrObject); + + verify(MOCK_namingClient, times(1)).postNameGenRequest(any(NameGenRequest.class)); + assertEquals("generatedServiceInstanceName", generatedName); + } + + @Test + public void deleteServiceInstanceNameTest() throws Exception { + NameGenDeleteRequest req = new NameGenDeleteRequest(); + doReturn(req).when(MOCK_namingRequestObjectBuilder).nameGenDeleteRequestMapper(isA(List.class)); + + NamingRequestObject nrObject = new NamingRequestObject(); + nrObject.setExternalKeyValue("testExternalKey"); + nrObject.setNamingTypeValue(NamingServiceConstants.NAMING_TYPE_SERVICE); + namingServiceResources.deleteServiceInstanceName(nrObject); + verify(MOCK_namingClient, times(1)).deleteNameGenRequest(any(NameGenDeleteRequest.class)); + } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVfModuleResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVfModuleResourcesTest.java index 2b45a3302c..57d6496a4f 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVfModuleResourcesTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCVfModuleResourcesTest.java @@ -23,6 +23,8 @@ package org.onap.so.client.orchestration; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import java.net.URI; +import java.net.URISyntaxException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -62,6 +64,8 @@ public class SDNCVfModuleResourcesTest extends TestDataSetup { private RequestContext requestContext; private GenericResourceApiVfModuleOperationInformation sdncReq; + private URI testURI; + @Before public void before() { vfModule = buildVfModule(); @@ -72,60 +76,67 @@ public class SDNCVfModuleResourcesTest extends TestDataSetup { cloudRegion = buildCloudRegion(); requestContext = buildRequestContext(); sdncReq = new GenericResourceApiVfModuleOperationInformation(); + try { + testURI = new URI("http://localhost:9800"); + } catch (URISyntaxException e) { + + } } @Test public void assignVfModuleTest() throws MapperException { doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule, volumeGroup, vnf, serviceInstance, customer, cloudRegion, - requestContext, null); + requestContext, null, testURI); sdncVfModuleResources.assignVfModule(vfModule, volumeGroup, vnf, serviceInstance, customer, cloudRegion, - requestContext); + requestContext, testURI); verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule, volumeGroup, vnf, serviceInstance, customer, cloudRegion, - requestContext, null); + requestContext, null, testURI); } @Test public void unassignVfModuleTest() throws MapperException { doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, - SDNCSvcAction.UNASSIGN, vfModule, null, vnf, serviceInstance, null, null, null, null); - sdncVfModuleResources.unassignVfModule(vfModule, vnf, serviceInstance); + SDNCSvcAction.UNASSIGN, vfModule, null, vnf, serviceInstance, null, null, null, null, testURI); + sdncVfModuleResources.unassignVfModule(vfModule, vnf, serviceInstance, testURI); verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, - SDNCSvcAction.UNASSIGN, vfModule, null, vnf, serviceInstance, null, null, null, null); + SDNCSvcAction.UNASSIGN, vfModule, null, vnf, serviceInstance, null, null, null, null, testURI); } @Test public void activateVfModuleTest() throws MapperException { doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE, vfModule, null, vnf, serviceInstance, customer, cloudRegion, requestContext, - null); - sdncVfModuleResources.activateVfModule(vfModule, vnf, serviceInstance, customer, cloudRegion, requestContext); + null, testURI); + sdncVfModuleResources.activateVfModule(vfModule, vnf, serviceInstance, customer, cloudRegion, requestContext, + testURI); verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ACTIVATE, vfModule, null, vnf, serviceInstance, customer, cloudRegion, requestContext, - null); + null, testURI); } @Test public void deactivateVfModuleTest() throws MapperException { doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE, vfModule, null, vnf, serviceInstance, customer, cloudRegion, requestContext, - null); - sdncVfModuleResources.deactivateVfModule(vfModule, vnf, serviceInstance, customer, cloudRegion, requestContext); + null, testURI); + sdncVfModuleResources.deactivateVfModule(vfModule, vnf, serviceInstance, customer, cloudRegion, requestContext, + testURI); verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.DEACTIVATE, vfModule, null, vnf, serviceInstance, customer, cloudRegion, requestContext, - null); + null, testURI); } @Test public void changeAssignVfModuleTest() throws MapperException, BadResponseException { doReturn(sdncReq).when(vfModuleTopologyMapper).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN, vfModule, null, vnf, serviceInstance, customer, cloudRegion, - requestContext, null); + requestContext, null, testURI); sdncVfModuleResources.changeAssignVfModule(vfModule, vnf, serviceInstance, customer, cloudRegion, - requestContext); + requestContext, testURI); verify(vfModuleTopologyMapper, times(1)).reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.CHANGE_ASSIGN, vfModule, null, vnf, serviceInstance, customer, cloudRegion, - requestContext, null); + requestContext, null, testURI); } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapperTest.java index 275e9f7dbb..b71ddba63b 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapperTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapperTest.java @@ -25,6 +25,7 @@ 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.assertNull; +import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; @@ -38,6 +39,7 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdnc.northbound.client.model.GenericResourceApiVfModuleOperationInformation; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; @@ -53,7 +55,6 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule; import org.onap.so.client.exception.MapperException; import org.onap.so.client.sdnc.beans.SDNCSvcAction; import org.onap.so.client.sdnc.beans.SDNCSvcOperation; -import org.onap.sdnc.northbound.client.model.GenericResourceApiVfModuleOperationInformation; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(MockitoJUnitRunner.class) @@ -134,9 +135,9 @@ public class VfModuleTopologyOperationRequestMapperTest { CloudRegion cloudRegion = new CloudRegion(); - GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest = - mapper.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule, - volumeGroup, vnf, serviceInstance, customer, cloudRegion, requestContext, null); + GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest = mapper.reqMapper( + SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule, volumeGroup, vnf, + serviceInstance, customer, cloudRegion, requestContext, null, new URI("http://localhost:8080")); String jsonToCompare = new String(Files.readAllBytes( Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleOperationInformationAssign.json"))); @@ -145,7 +146,7 @@ public class VfModuleTopologyOperationRequestMapperTest { GenericResourceApiVfModuleOperationInformation reqMapper1 = omapper.readValue(jsonToCompare, GenericResourceApiVfModuleOperationInformation.class); - assertThat(reqMapper1, sameBeanAs(vfModuleSDNCrequest).ignoring("sdncRequestHeader.svcRequestId") + assertThat(vfModuleSDNCrequest, sameBeanAs(reqMapper1).ignoring("sdncRequestHeader.svcRequestId") .ignoring("requestInformation.requestId")); assertEquals("MsoRequestId", vfModuleSDNCrequest.getRequestInformation().getRequestId()); } @@ -174,7 +175,7 @@ public class VfModuleTopologyOperationRequestMapperTest { GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest = mapper.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, vfModule, null, - vnf, serviceInstance, null, null, requestContext, null); + vnf, serviceInstance, null, null, requestContext, null, new URI("http://localhost:8080")); String jsonToCompare = new String(Files.readAllBytes( Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleOperationInformationUnassign.json"))); @@ -183,7 +184,7 @@ public class VfModuleTopologyOperationRequestMapperTest { GenericResourceApiVfModuleOperationInformation reqMapper1 = omapper.readValue(jsonToCompare, GenericResourceApiVfModuleOperationInformation.class); - assertThat(reqMapper1, sameBeanAs(vfModuleSDNCrequest).ignoring("sdncRequestHeader.svcRequestId") + assertThat(vfModuleSDNCrequest, sameBeanAs(reqMapper1).ignoring("sdncRequestHeader.svcRequestId") .ignoring("requestInformation.requestId")); assertEquals("MsoRequestId", vfModuleSDNCrequest.getRequestInformation().getRequestId()); } @@ -211,7 +212,7 @@ public class VfModuleTopologyOperationRequestMapperTest { GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest = mapper.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, vfModule, null, - vnf, serviceInstance, null, null, requestContext, null); + vnf, serviceInstance, null, null, requestContext, null, new URI("http://localhost:8080")); assertNotNull(vfModuleSDNCrequest.getRequestInformation().getRequestId()); } @@ -271,9 +272,9 @@ public class VfModuleTopologyOperationRequestMapperTest { CloudRegion cloudRegion = new CloudRegion(); - GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest = - mapper.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule, null, - vnf, serviceInstance, customer, cloudRegion, requestContext, null); + GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest = mapper.reqMapper( + SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule, null, vnf, + serviceInstance, customer, cloudRegion, requestContext, null, new URI("http://localhost:8080")); assertNull(vfModuleSDNCrequest.getServiceInformation().getOnapModelInformation().getModelCustomizationUuid()); assertEquals("vnfModelCustomizationUuid", @@ -330,7 +331,7 @@ public class VfModuleTopologyOperationRequestMapperTest { expectedException.expectMessage(ERRORMESSAGE); mapper.reqMapper(SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, vfModule, null, vnf, - serviceInstance, customer, cloudRegion, requestContext, null); + serviceInstance, customer, cloudRegion, requestContext, null, new URI("http://localhost:8080")); } } diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/NetworkMapper/l3-network-multiple-subnets.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/NetworkMapper/l3-network-multiple-subnets.json new file mode 100644 index 0000000000..e9b25ff266 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/NetworkMapper/l3-network-multiple-subnets.json @@ -0,0 +1,53 @@ +{ + "network-id" : "aNetworkId", + "cascaded" : false, + "cloud-params" : { }, + "network-name" : "aNetworkName", + "neutron-network-id" : null, + "network-type" : "aNetworkType", + "network-technology" : "aNetworkTechnology", + "network-role" : "", + "is-bound-to-vpn" : false, + "service-id" : "aServiceId", + "network-role-instance" : 0, + "orchestration-status" : "ACTIVE", + "heat-stack-id" : null, + "contrail-network-fqdn" : null, + "network-policies" : [ ], + "contrail-network-route-table-references" : [ ], + "widget-model-id" : null, + "widget-model-version" : null, + "physical-network-name" : "pNetworkName", + "is-provider-network" : false, + "is-shared-network" : false, + "is-external-network" : false, + "self-link" : "/", + "operational-status" : null, + "subnets" : [ { + "subnet-id" : "subnetId1", + "subnet-name" : "aSubnetName1", + "neutron-subnet-id" : null, + "gateway-address" : "192.168.1.1", + "network-start-address" : "192.168.1.2", + "cidr-mask" : "10", + "ip-version" : "4", + "orchestration-status" : "ACTIVE", + "dhcp-enabled" : true, + "dhcp-start" : "192.168.1.2", + "dhcp-end" : "192.168.1.16", + "subnet-role" : "", + "ip-assignment-direction" : "true", + "subnet-sequence" : null, + "host-routes": [{ + "host-route-id": "hrId1", + "route-prefix": "192.168.0.0/16", + "next-hop": "192.168.1.1", + "next-hop-type": null + }, { + "host-route-id": "hrId2", + "route-prefix": "192.168.1.5/16", + "next-hop": "192.168.1.1", + "next-hop-type": null + }] + }] +}
\ No newline at end of file diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest1SP.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest1SP.json index 27463350ab..31e6fd5f53 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest1SP.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest1SP.json @@ -32,7 +32,7 @@ "modelVersion" : "testProxyModelVersion1", "modelInvariantId" : "testProxyModelInvariantUuid1" }, - "requiredCandidates" : [ { + "filteringAttributes" : [ { "identifierType" : "cloudRegionId", "identifiers" : [ "testCloudRegionId" ], "cloudOwner" : "att" diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiNetworkWrapper.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiNetworkWrapper.json new file mode 100644 index 0000000000..aaa2c4ba35 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiNetworkWrapper.json @@ -0,0 +1,42 @@ +{ + "networkId": "0384d743-f69b-4cc8-9aa8-c3ae66662c44", + "networkName": "Dev_Bindings_1802_020118", + "networkType": "CONTRAIL30_BASIC", + "networkRole": "GN_EVPN_direct", + "networkTechnology": "contrail", + "neutronNetworkId": "1112b912-0e00-4d6d-9392-014e106399ee", + "isBoundToVpn": true, + "serviceId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "networkRoleInstance": 0, + "resourceVersion": "1517496965485", + "orchestrationStatus": "Active", + "heatStackId": "Dev_Bindings_1802_020118/06c2445f-1ca1-4ad8-be08-454c4de443bb", + "contrailNetworkFqdn": "default-domain:ECOMP_MSO_DND:Dev_Bindings_1802_020118", + "physicalNetworkName": "tbd", + "isProviderNetwork": false, + "isSharedNetwork": true, + "isExternalNetwork": false, + "relationshipList": { + "relationship": [ + { + "relatedTo": "vpn-binding", + "relatedLink": "/aai/v11/network/vpn-bindings/vpn-binding/9a7b327d9-287aa00-82c4b0-100001", + "relationshipData": [ + { + "relationshipKey": "vpn-binding.vpn-id", + "relationshipValue": "9a7b327d9-287aa00-82c4b0-100001" + } + ], + "relatedToProperty": [ + { + "propertyKey": "vpn-binding.vpn-name", + "propertyValue": "MSO_VPN_TEST" + }, + { + "propertyKey": "vpn-binding.vpn-type" + } + ] + } + ] + } +}
\ No newline at end of file diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/genericResourceApiVfModuleOperationInformationAssign.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/genericResourceApiVfModuleOperationInformationAssign.json index 777f3444d2..53c1997126 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/genericResourceApiVfModuleOperationInformationAssign.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/genericResourceApiVfModuleOperationInformationAssign.json @@ -43,7 +43,7 @@ }, "sdnc-request-header" : { "svc-request-id" : "svcRequestId", - "svc-notification-url" : null, + "svc-notification-url" : "http://localhost:8080", "svc-action" : "assign" }, "vf-module-information" : { diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/genericResourceApiVfModuleOperationInformationUnassign.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/genericResourceApiVfModuleOperationInformationUnassign.json index c28b0fa689..9f93c0df1f 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/genericResourceApiVfModuleOperationInformationUnassign.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/genericResourceApiVfModuleOperationInformationUnassign.json @@ -17,7 +17,7 @@ }, "sdnc-request-header" : { "svc-request-id" : "svcRequestId", - "svc-notification-url" : null, + "svc-notification-url" : "http://localhost:8080", "svc-action" : "unassign" }, "vf-module-information" : { diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/CreateNetworkCollection.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/CreateNetworkCollection.json index 579075f502..692ecfdf75 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/CreateNetworkCollection.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/CreateNetworkCollection.json @@ -4,7 +4,7 @@ "modelType": "service", "modelInvariantId": "5d48acb5-097d-4982-aeb2-f4a3bd87d31b", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersion": "10" }, "cloudConfiguration": { @@ -35,7 +35,7 @@ { "service": { "modelInfo": { - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a" }, "instanceParams": [], diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json index 26838024da..5753f69d3f 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/ServiceMacroActivateDeleteUnassign.json @@ -4,7 +4,7 @@ "modelType": "service", "modelInvariantId": "5d48acb5-097d-4982-aeb2-f4a3bd87d31b", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersion": "10.0" }, "cloudConfiguration": { diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/ServiceMacroAssign.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/ServiceMacroAssign.json index ddb118ea49..39e87f19f1 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/ServiceMacroAssign.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/ServiceMacroAssign.json @@ -4,7 +4,7 @@ "modelType": "service", "modelInvariantId": "5d48acb5-097d-4982-aeb2-f4a3bd87d31b", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersion": "10.0" }, "cloudConfiguration": { @@ -34,7 +34,7 @@ "service": { "modelInfo": { "modelType": "service", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a" }, "instanceParams": [], diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/ServiceMacroAssignNoCloud.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/ServiceMacroAssignNoCloud.json index 51caddd48a..b86a2a28f6 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/ServiceMacroAssignNoCloud.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/Macro/ServiceMacroAssignNoCloud.json @@ -4,7 +4,7 @@ "modelType": "service", "modelInvariantId": "5d48acb5-097d-4982-aeb2-f4a3bd87d31b", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersion": "10.0" }, "owningEntity": { @@ -31,7 +31,7 @@ "service": { "modelInfo": { "modelType": "service", - "modelName": "MOW AVPN vMX BV vPE 1 Service", + "modelName": "Sample Service Model", "modelVersionId": "3c40d244-808e-42ca-b09a-256d83d19d0a" }, "instanceParams": [], diff --git a/common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java b/common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java index d02b482008..e42a2a2383 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java @@ -70,6 +70,8 @@ public class AAIObjectPlurals implements GraphInventoryObjectPlurals, Serializab new AAIObjectPlurals(AAIObjectType.VSERVER.uriTemplate(), "/l-interfaces", "l-interface"); public static final AAIObjectPlurals SUB_L_INTERFACE = new AAIObjectPlurals(AAIObjectType.L_INTERFACE.uriTemplate(), "/l-interfaces", "l-interface"); + public static final AAIObjectPlurals INSTANCE_GROUP = + new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/instance-groups", "instance-group"); public static final AAIObjectPlurals PNF = new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/pnfs", "pnfs"); private final String uriTemplate; diff --git a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java index 6b2b6f2b3e..c2c8e933b1 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java @@ -72,6 +72,7 @@ import org.onap.aai.domain.yang.Vnfc; import org.onap.aai.domain.yang.VolumeGroup; import org.onap.aai.domain.yang.VpnBinding; import org.onap.aai.domain.yang.Vserver; +import org.onap.aai.domain.yang.Zone; import org.onap.so.client.graphinventory.GraphInventoryObjectType; import org.onap.so.constants.Defaults; import org.reflections.Reflections; @@ -186,7 +187,7 @@ public class AAIObjectType implements GraphInventoryObjectType, Serializable { "/esr-vnfm/{vnfm-id}/esr-system-info-list", "vnfm-esr-system-info-list"); public static final AAIObjectType CLOUD_ESR_SYSTEM_INFO_LIST = new AAIObjectType( AAIObjectType.CLOUD_REGION.uriTemplate(), "/esr-system-info-list", "cloud-esr-system-info-list"); - + public static final AAIObjectType ZONE = new AAIObjectType(AAINamespaceConstants.NETWORK, Zone.class); private final String uriTemplate; private final String parentUri; diff --git a/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java b/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java index 2e70c4925a..456f14e5ee 100644 --- a/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java +++ b/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java @@ -24,8 +24,9 @@ import org.onap.so.client.graphinventory.entities.GraphInventoryEdgeLabel; public enum AAIEdgeLabel implements GraphInventoryEdgeLabel { - BELONGS_TO("org.onap.relationships.inventory.BelongsTo"), USES( - "org.onap.relationships.inventory.Uses"), COMPOSED_OF("org.onap.relationships.inventory.ComposedOf"); + BELONGS_TO("org.onap.relationships.inventory.BelongsTo"), + USES("org.onap.relationships.inventory.Uses"), + COMPOSED_OF("org.onap.relationships.inventory.ComposedOf"); private final String label; diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java index f086a6abcf..37d21b375e 100644 --- a/common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java +++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java @@ -21,6 +21,8 @@ package org.onap.so.client.aai.entities.uri; import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.net.URI; import java.util.Map; import java.util.Optional; @@ -42,7 +44,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; public abstract class HttpLookupUri extends AAISimpleUri implements HttpAwareUri { - private Optional<String> cachedValue = Optional.empty(); + private transient Optional<String> cachedValue = Optional.empty(); private final AAIObjectType aaiType; protected HttpLookupUri(AAIObjectType type, Object... values) { @@ -78,8 +80,7 @@ public abstract class HttpLookupUri extends AAISimpleUri implements HttpAwareUri throw new GraphInventoryPayloadException("could not map payload: " + resultJson, e); } } - Optional<String> cachedValueOpt = this.getCachedValue(); - return cachedValueOpt.isPresent() ? cachedValueOpt.get() : ""; + return cachedValue.get(); } protected Optional<String> extractRelatedLink(String jsonString) throws IOException { @@ -139,6 +140,22 @@ public abstract class HttpLookupUri extends AAISimpleUri implements HttpAwareUri return new AAIResourcesClient(); } + private void writeObject(ObjectOutputStream oos) throws IOException { + + oos.writeUTF(this.cachedValue.orElse("")); + } + + private void readObject(ObjectInputStream ois) throws IOException { + + String value = ois.readUTF(); + if ("".equals(value)) { + this.cachedValue = Optional.empty(); + } else { + this.cachedValue = Optional.ofNullable(value); + } + + } + @Override public abstract URI buildNoNetwork(); } diff --git a/common/src/main/java/org/onap/so/client/dmaap/DmaapClient.java b/common/src/main/java/org/onap/so/client/dmaap/DmaapClient.java index 86d4aa7413..48c2d1495d 100644 --- a/common/src/main/java/org/onap/so/client/dmaap/DmaapClient.java +++ b/common/src/main/java/org/onap/so/client/dmaap/DmaapClient.java @@ -49,12 +49,12 @@ public abstract class DmaapClient { this.msoProperties = dmaapProperties.getProperties(); this.properties = new Properties(); this.properties.load(resource.getInputStream()); - try { - this.properties.put("auth", CryptoUtils.decrypt(this.getAuth(), this.getKey()).getBytes()); - } catch (GeneralSecurityException e) { - logger.error(e.getMessage(), e); + if (this.getAuth() != null && this.getKey() != null) { + this.properties.put("auth", this.getAuth()); + this.properties.put("key", this.getKey()); + } else { + logger.error("Dmaap auth or key is null"); } - this.properties.put("key", this.getKey()); this.properties.put("topic", this.getTopic()); Optional<String> host = this.getHost(); if (host.isPresent()) { diff --git a/common/src/main/java/org/onap/so/client/graphinventory/Format.java b/common/src/main/java/org/onap/so/client/graphinventory/Format.java index b422516e63..078b35aaf4 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/Format.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/Format.java @@ -22,8 +22,15 @@ package org.onap.so.client.graphinventory; public enum Format { - RESOURCE("resource"), RESOURCE_AND_URL("resource_and_url"), SIMPLE("simple"), RAW("raw"), CONSOLE( - "console"), PATHED("pathed"), GRAPHSON("graphson"), ID("id"); + RESOURCE("resource"), + RESOURCE_AND_URL("resource_and_url"), + SIMPLE("simple"), + RAW("raw"), + CONSOLE("console"), + PATHED("pathed"), + GRAPHSON("graphson"), + ID("id"), + COUNT("count"); private final String name; diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryResourcesClient.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryResourcesClient.java index 2a76dab107..c7cdb2ff58 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryResourcesClient.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryResourcesClient.java @@ -32,9 +32,7 @@ import org.onap.so.client.RestClient; import org.onap.so.client.RestProperties; import org.onap.so.client.graphinventory.entities.GraphInventoryEdgeLabel; import org.onap.so.client.graphinventory.entities.GraphInventoryResultWrapper; -import org.onap.so.client.graphinventory.entities.uri.Depth; import org.onap.so.client.graphinventory.entities.uri.GraphInventoryResourceUri; -import org.onap.so.client.graphinventory.entities.uri.GraphInventoryUri; public abstract class GraphInventoryResourcesClient<Self, Uri extends GraphInventoryResourceUri, EdgeLabel extends GraphInventoryEdgeLabel, Wrapper extends GraphInventoryResultWrapper, TransactionalClient, SingleTransactionClient> { @@ -74,7 +72,9 @@ public abstract class GraphInventoryResourcesClient<Self, Uri extends GraphInven * @return */ public boolean exists(Uri uri) { - GraphInventoryUri forceMinimal = this.addParams(Optional.of(Depth.ZERO), true, uri); + GraphInventoryResourceUri forceMinimal = uri.clone(); + forceMinimal.format(Format.COUNT); + forceMinimal.limit(1); try { RestClient giRC = client.createClient(forceMinimal); @@ -314,18 +314,6 @@ public abstract class GraphInventoryResourcesClient<Self, Uri extends GraphInven */ public abstract SingleTransactionClient beginSingleTransaction(); - private GraphInventoryUri addParams(Optional<Depth> depth, boolean nodesOnly, GraphInventoryUri uri) { - GraphInventoryUri clone = uri.clone(); - if (depth.isPresent()) { - clone.depth(depth.get()); - } - if (nodesOnly) { - clone.nodesOnly(nodesOnly); - } - - return clone; - } - public <T extends RestProperties> T getRestProperties() { return client.getRestProperties(); } diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryUri.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryUri.java index d6d3e5eaa2..6b48ad44ef 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryUri.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/GraphInventoryUri.java @@ -22,7 +22,6 @@ package org.onap.so.client.graphinventory.entities.uri; import java.net.URI; import java.util.Map; -import org.onap.so.client.graphinventory.entities.uri.Depth; import org.onap.so.client.graphinventory.GraphInventoryObjectType; public interface GraphInventoryUri { diff --git a/common/src/main/java/org/onap/so/client/policy/entities/PolicyServiceType.java b/common/src/main/java/org/onap/so/client/policy/entities/PolicyServiceType.java index b00d22dbad..eb95b75593 100644 --- a/common/src/main/java/org/onap/so/client/policy/entities/PolicyServiceType.java +++ b/common/src/main/java/org/onap/so/client/policy/entities/PolicyServiceType.java @@ -21,11 +21,18 @@ package org.onap.so.client.policy.entities; public enum PolicyServiceType { - GET_CONFIG("getConfig"), SEND_EVENT("sendEvent"), PUSH_POLICY("pushPolicy"), CREATE_POLICY( - "createPolicy"), UPDATE_POLICY("updatePolicy"), GET_DECISION("getDecision"), GET_METRICS( - "getMetrics"), DELETE_POLICY("deletePolicy"), LIST_CONFIG("listConfig"), CREATE_DICTIONARY_ITEM( - "createDictionaryItem"), UPDATE_DICTIONARY_ITEM( - "updateDictionaryItem"), GET_DICTIONARY_ITEMS("getDictionaryItems"); + GET_CONFIG("getConfig"), + SEND_EVENT("sendEvent"), + PUSH_POLICY("pushPolicy"), + CREATE_POLICY("createPolicy"), + UPDATE_POLICY("updatePolicy"), + GET_DECISION("getDecision"), + GET_METRICS("getMetrics"), + DELETE_POLICY("deletePolicy"), + LIST_CONFIG("listConfig"), + CREATE_DICTIONARY_ITEM("createDictionaryItem"), + UPDATE_DICTIONARY_ITEM("updateDictionaryItem"), + GET_DICTIONARY_ITEMS("getDictionaryItems"); private final String name; diff --git a/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java b/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java index b1adc53f3a..b85b7c3bde 100644 --- a/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java +++ b/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -38,7 +38,7 @@ public class SDNOHealthCheckDmaapPublisher extends DmaapPublisher { @Override public String getKey() { - return msoProperties.get("sdno.health-check.dmaap.msoKey"); + return msoProperties.get("mso.msoKey"); } @Override diff --git a/common/src/main/java/org/onap/so/logger/ErrorCode.java b/common/src/main/java/org/onap/so/logger/ErrorCode.java index 2d6fb791d5..7fb9522b7c 100644 --- a/common/src/main/java/org/onap/so/logger/ErrorCode.java +++ b/common/src/main/java/org/onap/so/logger/ErrorCode.java @@ -1,8 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.logger; public enum ErrorCode { - PermissionError(100), AvailabilityError(200), DataError(300), SchemaError(400), BusinessProcesssError( - 500), UnknownError(900); + PermissionError(100), + AvailabilityError(200), + DataError(300), + SchemaError(400), + BusinessProcesssError(500), + UnknownError(900); private int value; diff --git a/common/src/main/java/org/onap/so/logger/HttpHeadersConstants.java b/common/src/main/java/org/onap/so/logger/HttpHeadersConstants.java index f34b4b5a9a..83b860ff01 100644 --- a/common/src/main/java/org/onap/so/logger/HttpHeadersConstants.java +++ b/common/src/main/java/org/onap/so/logger/HttpHeadersConstants.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.logger; public class HttpHeadersConstants { diff --git a/common/src/main/java/org/onap/so/logger/LoggingAnchor.java b/common/src/main/java/org/onap/so/logger/LoggingAnchor.java new file mode 100644 index 0000000000..119ae4c43c --- /dev/null +++ b/common/src/main/java/org/onap/so/logger/LoggingAnchor.java @@ -0,0 +1,29 @@ +package org.onap.so.logger; + +import java.util.Collections; +import java.util.stream.Collectors; + +public class LoggingAnchor { + public static final String ONE = Collections.nCopies(1, "{}").stream().collect(Collectors.joining(" ")); + + public static final String TWO = Collections.nCopies(2, "{}").stream().collect(Collectors.joining(" ")); + + public static final String THREE = Collections.nCopies(3, "{}").stream().collect(Collectors.joining(" ")); + + public static final String FOUR = Collections.nCopies(4, "{}").stream().collect(Collectors.joining(" ")); + + public static final String FIVE = Collections.nCopies(5, "{}").stream().collect(Collectors.joining(" ")); + + public static final String SIX = Collections.nCopies(6, "{}").stream().collect(Collectors.joining(" ")); + + public static final String SEVEN = Collections.nCopies(7, "{}").stream().collect(Collectors.joining(" ")); + + public static final String EIGHT = Collections.nCopies(8, "{}").stream().collect(Collectors.joining(" ")); + + public static final String NINE = Collections.nCopies(9, "{}").stream().collect(Collectors.joining(" ")); + + public static final String TEN = Collections.nCopies(10, "{}").stream().collect(Collectors.joining(" ")); + + private LoggingAnchor() {} + +} diff --git a/common/src/main/java/org/onap/so/logger/MdcConstants.java b/common/src/main/java/org/onap/so/logger/MdcConstants.java index e3212733c8..33fceb2f0f 100644 --- a/common/src/main/java/org/onap/so/logger/MdcConstants.java +++ b/common/src/main/java/org/onap/so/logger/MdcConstants.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.logger; public class MdcConstants { diff --git a/common/src/main/java/org/onap/so/logger/MessageEnum.java b/common/src/main/java/org/onap/so/logger/MessageEnum.java index e92d50a685..bcf699beaf 100644 --- a/common/src/main/java/org/onap/so/logger/MessageEnum.java +++ b/common/src/main/java/org/onap/so/logger/MessageEnum.java @@ -24,13 +24,200 @@ package org.onap.so.logger; public enum MessageEnum { // Api Handler Messages - APIH_REQUEST_NULL, APIH_QUERY_FOUND, APIH_QUERY_NOT_FOUND, APIH_QUERY_PARAM_WRONG, APIH_DB_ACCESS_EXC, APIH_DB_ACCESS_EXC_REASON, APIH_VALIDATION_ERROR, APIH_REQUEST_VALIDATION_ERROR, APIH_SERVICE_VALIDATION_ERROR, APIH_GENERAL_EXCEPTION_ARG, APIH_GENERAL_EXCEPTION, APIH_GENERAL_WARNING, APIH_AUDIT_EXEC, APIH_GENERAL_METRICS, APIH_DUPLICATE_CHECK_EXC, APIH_DUPLICATE_FOUND, APIH_BAD_ORDER, APIH_DB_ATTRIBUTE_NOT_FOUND, APIH_BPEL_COMMUNICATE_ERROR, APIH_BPEL_RESPONSE_ERROR, APIH_WARP_REQUEST, APIH_ERROR_FROM_BPEL_SERVER, APIH_DB_INSERT_EXC, APIH_DB_UPDATE_EXC, APIH_NO_PROPERTIES, APIH_PROPERTY_LOAD_SUC, APIH_LOAD_PROPERTIES_FAIL, APIH_SDNC_COMMUNICATE_ERROR, APIH_SDNC_RESPONSE_ERROR, APIH_CANNOT_READ_SCHEMA, APIH_HEALTH_CHECK_EXCEPTION, APIH_REQUEST_VALIDATION_ERROR_REASON, APIH_JAXB_MARSH_ERROR, APIH_JAXB_UNMARSH_ERROR, APIH_VNFREQUEST_VALIDATION_ERROR, APIH_DOM2STR_ERROR, APIH_READ_VNFOUTPUT_CLOB_EXCEPTION, APIH_DUPLICATE_CHECK_EXC_ATT, APIH_GENERATED_REQUEST_ID, APIH_GENERATED_SERVICE_INSTANCE_ID, APIH_REPLACE_REQUEST_ID, + APIH_REQUEST_NULL, + APIH_QUERY_FOUND, + APIH_QUERY_NOT_FOUND, + APIH_QUERY_PARAM_WRONG, + APIH_DB_ACCESS_EXC, + APIH_DB_ACCESS_EXC_REASON, + APIH_VALIDATION_ERROR, + APIH_REQUEST_VALIDATION_ERROR, + APIH_SERVICE_VALIDATION_ERROR, + APIH_GENERAL_EXCEPTION_ARG, + APIH_GENERAL_EXCEPTION, + APIH_GENERAL_WARNING, + APIH_AUDIT_EXEC, + APIH_GENERAL_METRICS, + APIH_DUPLICATE_CHECK_EXC, + APIH_DUPLICATE_FOUND, + APIH_BAD_ORDER, + APIH_DB_ATTRIBUTE_NOT_FOUND, + APIH_BPEL_COMMUNICATE_ERROR, + APIH_BPEL_RESPONSE_ERROR, + APIH_WARP_REQUEST, + APIH_ERROR_FROM_BPEL_SERVER, + APIH_DB_INSERT_EXC, + APIH_DB_UPDATE_EXC, + APIH_NO_PROPERTIES, + APIH_PROPERTY_LOAD_SUC, + APIH_LOAD_PROPERTIES_FAIL, + APIH_SDNC_COMMUNICATE_ERROR, + APIH_SDNC_RESPONSE_ERROR, + APIH_CANNOT_READ_SCHEMA, + APIH_HEALTH_CHECK_EXCEPTION, + APIH_REQUEST_VALIDATION_ERROR_REASON, + APIH_JAXB_MARSH_ERROR, + APIH_JAXB_UNMARSH_ERROR, + APIH_VNFREQUEST_VALIDATION_ERROR, + APIH_DOM2STR_ERROR, + APIH_READ_VNFOUTPUT_CLOB_EXCEPTION, + APIH_DUPLICATE_CHECK_EXC_ATT, + APIH_GENERATED_REQUEST_ID, + APIH_GENERATED_SERVICE_INSTANCE_ID, + APIH_REPLACE_REQUEST_ID, // Resource Adapter Messages - RA_GENERAL_EXCEPTION_ARG, RA_GENERAL_EXCEPTION, RA_GENERAL_WARNING, RA_MISSING_PARAM, RA_AUDIT_EXEC, RA_GENERAL_METRICS, RA_CREATE_STACK_TIMEOUT, RA_DELETE_STACK_TIMEOUT, RA_UPDATE_STACK_TIMEOUT, RA_CONNECTION_EXCEPTION, RA_PARSING_ERROR, RA_PROPERTIES_NOT_FOUND, RA_LOAD_PROPERTIES_SUC, RA_NETWORK_ALREADY_EXIST, RA_UPDATE_NETWORK_ERR, RA_CREATE_STACK_ERR, RA_UPDATE_STACK_ERR, RA_CREATE_TENANT_ERR, RA_NETWORK_NOT_FOUND, RA_NETWORK_ORCHE_MODE_NOT_SUPPORT, RA_CREATE_NETWORK_EXC, RA_NS_EXC, RA_PARAM_NOT_FOUND, RA_CONFIG_EXC, RA_UNKOWN_PARAM, RA_VLAN_PARSE, RA_DELETE_NETWORK_EXC, RA_ROLLBACK_NULL, RA_TENANT_NOT_FOUND, RA_QUERY_NETWORK_EXC, RA_CREATE_NETWORK_NOTIF_EXC, RA_ASYNC_ROLLBACK, RA_WSDL_NOT_FOUND, RA_WSDL_URL_CONVENTION_EXC, RA_INIT_NOTIF_EXC, RA_SET_CALLBACK_AUTH_EXC, RA_FAULT_INFO_EXC, RA_MARSHING_ERROR, RA_PARSING_REQUEST_ERROR, RA_SEND_REQUEST_SDNC, RA_RESPONSE_FROM_SDNC, RA_EXCEPTION_COMMUNICATE_SDNC, RA_EVALUATE_XPATH_ERROR, RA_ANALYZE_ERROR_EXC, RA_ERROR_GET_RESPONSE_SDNC, RA_CALLBACK_BPEL, RA_INIT_CALLBACK_WSDL_ERR, RA_CALLBACK_BPEL_EXC, RA_CALLBACK_BPEL_COMPLETE, RA_SDNC_MISS_CONFIG_PARAM, RA_SDNC_INVALID_CONFIG, RA_PRINT_URL, RA_ERROR_CREATE_SDNC_REQUEST, RA_ERROR_CREATE_SDNC_RESPONSE, RA_ERROR_CONVERT_XML2STR, RA_RECEIVE_SDNC_NOTIF, RA_INIT_SDNC_ADAPTER, RA_SEND_REQUEST_APPC_ERR, RA_SEND_REQUEST_SDNC_ERR, RA_RECEIVE_BPEL_REQUEST, RA_TENANT_ALREADY_EXIST, RA_UPDATE_TENANT_ERR, RA_DELETE_TEMAMT_ERR, RA_ROLLBACK_TENANT_ERR, RA_QUERY_VNF_ERR, RA_VNF_ALREADY_EXIST, RA_VNF_UNKNOWN_PARAM, RA_VNF_EXTRA_PARAM, RA_CREATE_VNF_ERR, RA_VNF_NOT_EXIST, RA_UPDATE_VNF_ERR, RA_DELETE_VNF_ERR, RA_ASYNC_CREATE_VNF, RA_SEND_VNF_NOTIF_ERR, RA_ASYNC_CREATE_VNF_COMPLETE, RA_ASYNC_UPDATE_VNF, RA_ASYNC_UPDATE_VNF_COMPLETE, RA_ASYNC_QUERY_VNF, RA_ASYNC_QUERY_VNF_COMPLETE, RA_ASYNC_DELETE_VNF, RA_ASYNC_DELETE_VNF_COMPLETE, RA_ASYNC_ROLLBACK_VNF, RA_ASYNC_ROLLBACK_VNF_COMPLETE, RA_ROLLBACK_VNF_ERR, RA_DB_INVALID_STATUS, RA_CANT_UPDATE_REQUEST, RA_DB_REQUEST_NOT_EXIST, RA_CONFIG_NOT_FOUND, RA_CONFIG_LOAD, RA_RECEIVE_WORKFLOW_MESSAGE, + RA_GENERAL_EXCEPTION_ARG, + RA_GENERAL_EXCEPTION, + RA_GENERAL_WARNING, + RA_MISSING_PARAM, + RA_AUDIT_EXEC, + RA_GENERAL_METRICS, + RA_CREATE_STACK_TIMEOUT, + RA_DELETE_STACK_TIMEOUT, + RA_UPDATE_STACK_TIMEOUT, + RA_CONNECTION_EXCEPTION, + RA_PARSING_ERROR, + RA_PROPERTIES_NOT_FOUND, + RA_LOAD_PROPERTIES_SUC, + RA_NETWORK_ALREADY_EXIST, + RA_UPDATE_NETWORK_ERR, + RA_CREATE_STACK_ERR, + RA_UPDATE_STACK_ERR, + RA_CREATE_TENANT_ERR, + RA_NETWORK_NOT_FOUND, + RA_NETWORK_ORCHE_MODE_NOT_SUPPORT, + RA_CREATE_NETWORK_EXC, + RA_NS_EXC, + RA_PARAM_NOT_FOUND, + RA_CONFIG_EXC, + RA_UNKOWN_PARAM, + RA_VLAN_PARSE, + RA_DELETE_NETWORK_EXC, + RA_ROLLBACK_NULL, + RA_TENANT_NOT_FOUND, + RA_QUERY_NETWORK_EXC, + RA_CREATE_NETWORK_NOTIF_EXC, + RA_ASYNC_ROLLBACK, + RA_WSDL_NOT_FOUND, + RA_WSDL_URL_CONVENTION_EXC, + RA_INIT_NOTIF_EXC, + RA_SET_CALLBACK_AUTH_EXC, + RA_FAULT_INFO_EXC, + RA_MARSHING_ERROR, + RA_PARSING_REQUEST_ERROR, + RA_SEND_REQUEST_SDNC, + RA_RESPONSE_FROM_SDNC, + RA_EXCEPTION_COMMUNICATE_SDNC, + RA_EVALUATE_XPATH_ERROR, + RA_ANALYZE_ERROR_EXC, + RA_ERROR_GET_RESPONSE_SDNC, + RA_CALLBACK_BPEL, + RA_INIT_CALLBACK_WSDL_ERR, + RA_CALLBACK_BPEL_EXC, + RA_CALLBACK_BPEL_COMPLETE, + RA_SDNC_MISS_CONFIG_PARAM, + RA_SDNC_INVALID_CONFIG, + RA_PRINT_URL, + RA_ERROR_CREATE_SDNC_REQUEST, + RA_ERROR_CREATE_SDNC_RESPONSE, + RA_ERROR_CONVERT_XML2STR, + RA_RECEIVE_SDNC_NOTIF, + RA_INIT_SDNC_ADAPTER, + RA_SEND_REQUEST_APPC_ERR, + RA_SEND_REQUEST_SDNC_ERR, + RA_RECEIVE_BPEL_REQUEST, + RA_TENANT_ALREADY_EXIST, + RA_UPDATE_TENANT_ERR, + RA_DELETE_TEMAMT_ERR, + RA_ROLLBACK_TENANT_ERR, + RA_QUERY_VNF_ERR, + RA_VNF_ALREADY_EXIST, + RA_VNF_UNKNOWN_PARAM, + RA_VNF_EXTRA_PARAM, + RA_CREATE_VNF_ERR, + RA_VNF_NOT_EXIST, + RA_UPDATE_VNF_ERR, + RA_DELETE_VNF_ERR, + RA_ASYNC_CREATE_VNF, + RA_SEND_VNF_NOTIF_ERR, + RA_ASYNC_CREATE_VNF_COMPLETE, + RA_ASYNC_UPDATE_VNF, + RA_ASYNC_UPDATE_VNF_COMPLETE, + RA_ASYNC_QUERY_VNF, + RA_ASYNC_QUERY_VNF_COMPLETE, + RA_ASYNC_DELETE_VNF, + RA_ASYNC_DELETE_VNF_COMPLETE, + RA_ASYNC_ROLLBACK_VNF, + RA_ASYNC_ROLLBACK_VNF_COMPLETE, + RA_ROLLBACK_VNF_ERR, + RA_DB_INVALID_STATUS, + RA_CANT_UPDATE_REQUEST, + RA_DB_REQUEST_NOT_EXIST, + RA_CONFIG_NOT_FOUND, + RA_CONFIG_LOAD, + RA_RECEIVE_WORKFLOW_MESSAGE, // BPEL engine Messages - BPMN_GENERAL_INFO, BPMN_GENERAL_EXCEPTION_ARG, BPMN_GENERAL_EXCEPTION, BPMN_GENERAL_WARNING, BPMN_AUDIT_EXEC, BPMN_GENERAL_METRICS, BPMN_URN_MAPPING_FAIL, BPMN_VARIABLE_NULL, BPMN_CALLBACK_EXCEPTION, + BPMN_GENERAL_INFO, + BPMN_GENERAL_EXCEPTION_ARG, + BPMN_GENERAL_EXCEPTION, + BPMN_GENERAL_WARNING, + BPMN_AUDIT_EXEC, + BPMN_GENERAL_METRICS, + BPMN_URN_MAPPING_FAIL, + BPMN_VARIABLE_NULL, + BPMN_CALLBACK_EXCEPTION, // ASDC Messages - ASDC_GENERAL_EXCEPTION_ARG, ASDC_GENERAL_EXCEPTION, ASDC_GENERAL_WARNING, ASDC_GENERAL_INFO, ASDC_AUDIT_EXEC, ASDC_GENERAL_METRICS, ASDC_CREATE_SERVICE, ASDC_ARTIFACT_ALREADY_DEPLOYED, ASDC_CREATE_ARTIFACT, ASDC_ARTIFACT_INSTALL_EXC, ASDC_ARTIFACT_ALREADY_DEPLOYED_DETAIL, ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL, ASDC_ARTIFACT_CHECK_EXC, ASDC_INIT_ASDC_CLIENT_EXC, ASDC_INIT_ASDC_CLIENT_SUC, ASDC_LOAD_ASDC_CLIENT_EXC, ASDC_SINGLETON_CHECKT_EXC, ASDC_SHUTDOWN_ASDC_CLIENT_EXC, ASDC_CHECK_HEAT_TEMPLATE, ASDC_START_INSTALL_ARTIFACT, ASDC_ARTIFACT_TYPE_NOT_SUPPORT, ASDC_ARTIFACT_ALREADY_EXIST, ASDC_ARTIFACT_DOWNLOAD_SUC, ASDC_ARTIFACT_DOWNLOAD_FAIL, ASDC_START_DEPLOY_ARTIFACT, ASDC_SEND_NOTIF_ASDC, ASDC_SEND_NOTIF_ASDC_EXEC, ASDC_RECEIVE_CALLBACK_NOTIF, ASDC_RECEIVE_SERVICE_NOTIF, ASDC_ARTIFACT_NULL, ASDC_SERVICE_NOT_SUPPORT, ASDC_ARTIFACT_DEPLOY_SUC, ASDC_PROPERTIES_NOT_FOUND, ASDC_PROPERTIES_LOAD_SUCCESS, + ASDC_GENERAL_EXCEPTION_ARG, + ASDC_GENERAL_EXCEPTION, + ASDC_GENERAL_WARNING, + ASDC_GENERAL_INFO, + ASDC_AUDIT_EXEC, + ASDC_GENERAL_METRICS, + ASDC_CREATE_SERVICE, + ASDC_ARTIFACT_ALREADY_DEPLOYED, + ASDC_CREATE_ARTIFACT, + ASDC_ARTIFACT_INSTALL_EXC, + ASDC_ARTIFACT_ALREADY_DEPLOYED_DETAIL, + ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL, + ASDC_ARTIFACT_CHECK_EXC, + ASDC_INIT_ASDC_CLIENT_EXC, + ASDC_INIT_ASDC_CLIENT_SUC, + ASDC_LOAD_ASDC_CLIENT_EXC, + ASDC_SINGLETON_CHECKT_EXC, + ASDC_SHUTDOWN_ASDC_CLIENT_EXC, + ASDC_CHECK_HEAT_TEMPLATE, + ASDC_START_INSTALL_ARTIFACT, + ASDC_ARTIFACT_TYPE_NOT_SUPPORT, + ASDC_ARTIFACT_ALREADY_EXIST, + ASDC_ARTIFACT_DOWNLOAD_SUC, + ASDC_ARTIFACT_DOWNLOAD_FAIL, + ASDC_START_DEPLOY_ARTIFACT, + ASDC_SEND_NOTIF_ASDC, + ASDC_SEND_NOTIF_ASDC_EXEC, + ASDC_RECEIVE_CALLBACK_NOTIF, + ASDC_RECEIVE_SERVICE_NOTIF, + ASDC_ARTIFACT_NULL, + ASDC_SERVICE_NOT_SUPPORT, + ASDC_ARTIFACT_DEPLOY_SUC, + ASDC_PROPERTIES_NOT_FOUND, + ASDC_PROPERTIES_LOAD_SUCCESS, // Default Messages, in case Log catalog is not defined - GENERAL_EXCEPTION_ARG, GENERAL_EXCEPTION, GENERAL_WARNING, AUDIT_EXEC, GENERAL_METRICS, LOGGER_SETUP, LOGGER_NOT_FOUND, LOGGER_UPDATE_SUC, LOGGER_UPDATE_DEBUG, LOGGER_UPDATE_DEBUG_SUC, LOAD_PROPERTIES_SUC, NO_PROPERTIES, MADATORY_PARAM_MISSING, LOAD_PROPERTIES_FAIL, INIT_LOGGER, INIT_LOGGER_FAIL, JAXB_EXCEPTION, IDENTITY_SERVICE_NOT_FOUND; + GENERAL_EXCEPTION_ARG, + GENERAL_EXCEPTION, + GENERAL_WARNING, + AUDIT_EXEC, + GENERAL_METRICS, + LOGGER_SETUP, + LOGGER_NOT_FOUND, + LOGGER_UPDATE_SUC, + LOGGER_UPDATE_DEBUG, + LOGGER_UPDATE_DEBUG_SUC, + LOAD_PROPERTIES_SUC, + NO_PROPERTIES, + MADATORY_PARAM_MISSING, + LOAD_PROPERTIES_FAIL, + INIT_LOGGER, + INIT_LOGGER_FAIL, + JAXB_EXCEPTION, + IDENTITY_SERVICE_NOT_FOUND; } diff --git a/common/src/main/java/org/onap/so/objects/audit/AAIObjectAudit.java b/common/src/main/java/org/onap/so/objects/audit/AAIObjectAudit.java index a27e8fbbd1..d45cc00b85 100644 --- a/common/src/main/java/org/onap/so/objects/audit/AAIObjectAudit.java +++ b/common/src/main/java/org/onap/so/objects/audit/AAIObjectAudit.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.objects.audit; import java.io.Serializable; diff --git a/common/src/main/java/org/onap/so/objects/audit/AAIObjectAuditList.java b/common/src/main/java/org/onap/so/objects/audit/AAIObjectAuditList.java index 675701d598..2a4b90eef7 100644 --- a/common/src/main/java/org/onap/so/objects/audit/AAIObjectAuditList.java +++ b/common/src/main/java/org/onap/so/objects/audit/AAIObjectAuditList.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.objects.audit; import java.io.Serializable; diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/ModelType.java b/common/src/main/java/org/onap/so/serviceinstancebeans/ModelType.java index 9a184b0a51..6b9b39e5a9 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/ModelType.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/ModelType.java @@ -20,9 +20,76 @@ package org.onap.so.serviceinstancebeans; +import java.lang.reflect.InvocationTargetException; +import com.google.common.base.CaseFormat; + /* * Enum for Model Type values returned by API Handler to BPMN */ public enum ModelType { - service, vnf, vfModule, volumeGroup, network, configuration, connectionPoint, pnf, networkInstanceGroup, instanceGroup + service("serviceInstance"), + vnf("vnf"), + vfModule("vfModule"), + volumeGroup("volumeGroup"), + network("network"), + configuration("configuration"), + connectionPoint("connectionPoint"), + pnf("pnf"), + networkInstanceGroup("networkInstanceGroup"), + instanceGroup("instanceGroup"), + vpnBinding("vpnBinding"); + + final String name; + + private ModelType(String name) { + this.name = name; + } + + + public <T> T getId(Object obj) { + return this.get(obj, "Id"); + } + + public <T> T getName(Object obj) { + return this.get(obj, "Name"); + } + + public void setId(Object obj, Object value) { + this.set(obj, "Id", value); + } + + public void setName(Object obj, Object value) { + this.set(obj, "Name", value); + } + + protected <T> T get(Object obj, String field) { + T result = null; + if (obj != null) { + try { + result = (T) obj.getClass().getMethod(String.format("%s%s%s", "get", + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, this.name), field)).invoke(obj); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException + | NoSuchMethodException | SecurityException e) { + // silent fail + } + } + + return result; + } + + protected void set(Object obj, String field, Object value) { + if (obj != null) { + try { + obj.getClass() + .getMethod( + String.format("%s%s%s", "set", + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, this.name), field), + value.getClass()) + .invoke(obj, value); + } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException e) { + // silent fail + } + } + } } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java index fbdb27c0ec..75a6ba8280 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java @@ -22,7 +22,6 @@ package org.onap.so.serviceinstancebeans; import java.util.ArrayList; import java.util.List; -import java.util.Map; import org.apache.commons.lang3.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @@ -36,6 +35,7 @@ public class Request { protected String finishTime; protected String requestScope; protected String requestType; + protected String originalRequestId; protected RequestDetails requestDetails; protected InstanceReferences instanceReferences; protected RequestStatus requestStatus; @@ -124,6 +124,14 @@ public class Request { this.cloudRequestData = cloudRequestData; } + public String getOriginalRequestId() { + return originalRequestId; + } + + public void setOriginalRequestId(String originalRequestId) { + this.originalRequestId = originalRequestId; + } + @Override public String toString() { return new ToStringBuilder(this).append("requestId", requestId).append("startTime", startTime) @@ -131,6 +139,6 @@ public class Request { .append("requestType", requestType).append("requestDetails", requestDetails) .append("instanceReferences", instanceReferences).append("requestStatus", requestStatus) .append("requestProcessingData", requestProcessingData).append("cloudRequestData", cloudRequestData) - .toString(); + .append("originalRequestId", originalRequestId).toString(); } } diff --git a/common/src/main/java/org/onap/so/utils/CryptoUtils.java b/common/src/main/java/org/onap/so/utils/CryptoUtils.java index 09b48d266f..640660e97c 100644 --- a/common/src/main/java/org/onap/so/utils/CryptoUtils.java +++ b/common/src/main/java/org/onap/so/utils/CryptoUtils.java @@ -23,6 +23,7 @@ package org.onap.so.utils; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; @@ -89,7 +90,7 @@ public final class CryptoUtils { try { return CryptoUtils.encrypt(message, CLOUD_KEY); } catch (GeneralSecurityException e) { - logger.error("{} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), + logger.error(LoggingAnchor.THREE, MessageEnum.RA_GENERAL_EXCEPTION.toString(), ErrorCode.BusinessProcesssError.getValue(), "Exception in encryptPassword ", e); return null; } @@ -99,7 +100,7 @@ public final class CryptoUtils { try { return CryptoUtils.decrypt(message, CLOUD_KEY); } catch (GeneralSecurityException e) { - logger.error("{} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), + logger.error(LoggingAnchor.THREE, MessageEnum.RA_GENERAL_EXCEPTION.toString(), ErrorCode.BusinessProcesssError.getValue(), "Exception in encryptPassword ", e); return null; } diff --git a/common/src/main/java/org/onap/so/utils/TargetEntity.java b/common/src/main/java/org/onap/so/utils/TargetEntity.java index 5f87378b79..0f1fe51114 100644 --- a/common/src/main/java/org/onap/so/utils/TargetEntity.java +++ b/common/src/main/java/org/onap/so/utils/TargetEntity.java @@ -23,7 +23,21 @@ package org.onap.so.utils; import java.util.EnumSet; public enum TargetEntity { - OPENSTACK_ADAPTER, BPMN, GRM, AAI, DMAAP, POLICY, CATALOG_DB, REQUEST_DB, VNF_ADAPTER, SDNC_ADAPTER, SNIRO, SDC, EXTERNAL, MULTICLOUD; + OPENSTACK_ADAPTER, + BPMN, + GRM, + AAI, + DMAAP, + POLICY, + CATALOG_DB, + REQUEST_DB, + VNF_ADAPTER, + SDNC_ADAPTER, + SNIRO, + SDC, + EXTERNAL, + MULTICLOUD, + OOF; private static final String PREFIX = "SO"; diff --git a/common/src/main/java/org/onap/so/utils/UUIDChecker.java b/common/src/main/java/org/onap/so/utils/UUIDChecker.java index 585ffcc7c4..30fc92bf49 100644 --- a/common/src/main/java/org/onap/so/utils/UUIDChecker.java +++ b/common/src/main/java/org/onap/so/utils/UUIDChecker.java @@ -24,6 +24,7 @@ package org.onap.so.utils; import java.util.UUID; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -51,7 +52,7 @@ public class UUIDChecker { public static String getUUID() { String result = UUID.randomUUID().toString(); - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID, result); + logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID, result); return result; } } diff --git a/common/src/main/java/org/onap/so/utils/XmlMarshaller.java b/common/src/main/java/org/onap/so/utils/XmlMarshaller.java index 0022ecbb96..0ff3ccfa9c 100644 --- a/common/src/main/java/org/onap/so/utils/XmlMarshaller.java +++ b/common/src/main/java/org/onap/so/utils/XmlMarshaller.java @@ -32,6 +32,7 @@ import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXSource; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.exceptions.MarshallerException; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; @@ -52,8 +53,8 @@ public class XmlMarshaller { Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.marshal(object, stringWriter); } catch (JAXBException e) { - logger.error("{} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(), ErrorCode.SchemaError.getValue(), - e.getMessage(), e); + logger.error(LoggingAnchor.THREE, MessageEnum.GENERAL_EXCEPTION.toString(), + ErrorCode.SchemaError.getValue(), e.getMessage(), e); throw new MarshallerException(e.getMessage(), ErrorCode.SchemaError.getValue(), e); } @@ -77,8 +78,8 @@ public class XmlMarshaller { SAXSource source = new SAXSource(xmlReader, inputSource); object = jaxbUnmarshaller.unmarshal(source, object.getClass()).getValue(); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(), ErrorCode.SchemaError.getValue(), - e.getMessage(), e); + logger.error(LoggingAnchor.THREE, MessageEnum.GENERAL_EXCEPTION.toString(), + ErrorCode.SchemaError.getValue(), e.getMessage(), e); throw new MarshallerException(e.getMessage(), ErrorCode.SchemaError.getValue(), e); } diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java index e829666577..9bef35e3b5 100644 --- a/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java +++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java @@ -31,8 +31,14 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; @@ -50,9 +56,11 @@ import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.onap.so.client.aai.AAIClient; +import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.defaultproperties.DefaultAAIPropertiesImpl; +import org.onap.so.client.graphinventory.entities.uri.Depth; import org.onap.so.client.graphinventory.exceptions.GraphInventoryPayloadException; import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriComputationException; import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriNotFoundException; @@ -227,4 +235,42 @@ public class ServiceInstanceUriTest { exception.expect(NotFoundException.class); spy.build(); } + + @Test + public void serializeTest() throws IOException, ClassNotFoundException, GraphInventoryUriNotFoundException, + GraphInventoryPayloadException { + ServiceInstanceUri instance = new ServiceInstanceUri("key3"); + final String content = new String( + Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + "service-instance-pathed-query.json"))); + + ServiceInstanceUri spy = spy(instance); + AAIResourcesClient mockResourcesClient = mock(AAIResourcesClient.class); + AAIResultWrapper wrapper = mock(AAIResultWrapper.class); + when(mockResourcesClient.get(ArgumentMatchers.<AAIResourceUri>any(AAIResourceUri.class), + ArgumentMatchers.<Class<NotFoundException>>any())).thenReturn(wrapper); + when(wrapper.getJson()).thenReturn(content); + when(spy.getResourcesClient()).thenReturn(mockResourcesClient); + spy.build(); + instance = spy.clone(); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + ObjectOutputStream objectOutputStream = new ObjectOutputStream(bos); + objectOutputStream.writeObject(instance); + objectOutputStream.flush(); + objectOutputStream.close(); + + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + + ObjectInputStream objectInputStream = new ObjectInputStream(bis); + ServiceInstanceUri e2 = (ServiceInstanceUri) objectInputStream.readObject(); + objectInputStream.close(); + + ServiceInstanceUri spy2 = spy(e2); + + assertEquals(spy2.build().toString(), instance.build().toString()); + + // use the cached value do not call out to external system + verify(spy2, times(0)).getResourcesClient(); + + } } diff --git a/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java b/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java deleted file mode 100644 index 4bfac38151..0000000000 --- a/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2018 Huawei 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.client.dmaap; - -import org.junit.Test; -import javax.ws.rs.ProcessingException; -import java.io.IOException; -import java.util.Optional; - -public class DmaapPublisherTest { - - DmaapPublisher dmaapPublisher = new DmaapPublisher(120) { - @Override - public String getAuth() { - return "8F73A1691F6271E769329C176EE3EA48F52786AF12A3E16259007EED2A0F0CC3CB965F4AB5318483015723CCE1C0B48AB6C4DED6E251869393B01E4EC532FC88D4A128B92F4CDB34719B171923"; - } - - @Override - public String getKey() { - return "07a7159d3bf51a0e53be7a8f89699be7"; - } - - @Override - public String getTopic() { - return "test"; - } - - @Override - public Optional<String> getHost() { - return Optional.of("http://test"); - } - }; - - public DmaapPublisherTest() throws IOException {} - - @Test(expected = ProcessingException.class) - public void sendTest() throws Exception { - dmaapPublisher.send("{'key': 'value'}"); - } - -} diff --git a/common/src/test/java/org/onap/so/serviceinstancebeans/ModelTypeTest.java b/common/src/test/java/org/onap/so/serviceinstancebeans/ModelTypeTest.java new file mode 100644 index 0000000000..fd1977225f --- /dev/null +++ b/common/src/test/java/org/onap/so/serviceinstancebeans/ModelTypeTest.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.serviceinstancebeans; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import org.junit.Test; + +public class ModelTypeTest { + + + + @Test + public void reflectionTest() { + TestServiceInstanceBean a = new TestServiceInstanceBean(); + TestServiceInstanceBean b = new TestServiceInstanceBean(); + + a.setServiceInstanceId("my-id-a"); + a.setServiceInstanceName("my-name-a"); + + b.setServiceInstanceId("my-id-b"); + b.setServiceInstanceName("my-name-b"); + + assertEquals("my-id-a", ModelType.service.getId(a)); + assertEquals("my-name-a", ModelType.service.getName(a)); + ModelType.service.setName(a, ModelType.service.getName(b)); + ModelType.service.setId(a, ModelType.service.getId(b)); + assertEquals("my-name-b", ModelType.service.getName(a)); + assertEquals("my-id-b", ModelType.service.getId(a)); + } + + @Test + public void testSilentFail() { + TestServiceInstanceBean a = new TestServiceInstanceBean(); + + a.setServiceInstanceId("my-id-a"); + a.setServiceInstanceName("my-name-a"); + assertNull(ModelType.service.get(a, "NoField")); + } +} diff --git a/common/src/test/java/org/onap/so/serviceinstancebeans/TestServiceInstanceBean.java b/common/src/test/java/org/onap/so/serviceinstancebeans/TestServiceInstanceBean.java new file mode 100644 index 0000000000..a14f3bace4 --- /dev/null +++ b/common/src/test/java/org/onap/so/serviceinstancebeans/TestServiceInstanceBean.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.serviceinstancebeans; + +public class TestServiceInstanceBean { + + private String serviceInstanceId; + private String serviceInstanceName; + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getServiceInstanceName() { + return serviceInstanceName; + } + + public void setServiceInstanceName(String serviceInstanceName) { + this.serviceInstanceName = serviceInstanceName; + } + +} diff --git a/docs/release-notes.rst b/docs/release-notes.rst index 89e12e35c2..8d5f5727b6 100644 --- a/docs/release-notes.rst +++ b/docs/release-notes.rst @@ -8,6 +8,240 @@ Service Orchestrator Release Notes The SO provides the highest level of service orchestration in the ONAP architecture. +Version: 1.4.3 +============== + +:Release Date: 2019-06-06 + +Docker Images +------------- + +**Dockers released for SO:** + + - onap/so/api-handler-infra,1.4.3 + - onap/so/bpmn-infra,1.4.3 + - onap/so/catalog-db-adapter,1.4.3 + - onap/so/openstack-adapter,1.4.3 + - onap/so/request-db-adapter,1.4.3 + - onap/so/sdc-controller,1.4.3 + - onap/so/sdnc-adapter,1.4.3 + - onap/so/so-monitoring,1.4.3 + - onap/so/vfc-adapter,1.4.3 + +Release Purpose +---------------- + +**New Features** + +The main goal of the Dublin release was to: + - Support CCVPN extension + - Support BroadBand Service Usecase + - SO SOL003 plugin support + - Improve PNF PnP + + +**Epics** + +- [`SO-1508 <https://jira.onap.org/browse/SO-1508>`__\ ] - ETSI Alignment - SO SOL003 plugin support to connect to external VNFMs +- [`SO-1468 <https://jira.onap.org/browse/SO-1468>`__\ ] - Hardening of HPA in SO and extension of HPA capabilities to existing use-cases +- [`SO-1394 <https://jira.onap.org/browse/SO-1394>`__\ ] - Extended and enhance the SO generic building block to support pre and post instantiation. +- [`SO-1393 <https://jira.onap.org/browse/SO-1393>`__\ ] - Support the CCVPN Extension +- [`SO-1392 <https://jira.onap.org/browse/SO-1392>`__\ ] - Support the BroadBand Service Usecase +- [`SO-1353 <https://jira.onap.org/browse/SO-1353>`__\ ] - SO to be made independent of Cloud technologies +- [`SO-1273 <https://jira.onap.org/browse/SO-1273>`__\ ] - PNF PnP Dublin updates & improvements +- [`SO-1271 <https://jira.onap.org/browse/SO-1271>`__\ ] - PNF PnP Casablanca MR updates +- [`SO-677 <https://jira.onap.org/browse/SO-677>`__\ ] - Improve the issues and findings of the SO Casablanca Release +- [`SO-166 <https://jira.onap.org/browse/SO-166>`__\ ] - Non-stop operations required. + +**Stories** + +- [`SO-1974 <https://jira.onap.org/browse/SO-1974`__ ] - Turn off OpenStack heat stack audit +- [`SO-1924 <https://jira.onap.org/browse/SO-1924`__ ] - Add VnfConfigUpdate to the list of native CM workflows returned to VID +- [`SO-1820 <https://jira.onap.org/browse/SO-1820`__ ] - Add Model Version Query +- [`SO-1806 <https://jira.onap.org/browse/SO-1806`__ ] - Fix issue where null variable causes task to not +- [`SO-1793 <https://jira.onap.org/browse/SO-1793`__ ] - add status for delete +- [`SO-1792 <https://jira.onap.org/browse/SO-1792`__ ] - add status message requirement for create vf module event audit +- [`SO-1791 <https://jira.onap.org/browse/SO-1791`__ ] - Moved base client to new location +- [`SO-1790 <https://jira.onap.org/browse/SO-1790`__ ] - Enhanced sniro BB to account for sole service proxies to support 1908. +- [`SO-1765 <https://jira.onap.org/browse/SO-1765`__ ] - Convert Tabs to Spaces +- [`SO-1760 <https://jira.onap.org/browse/SO-1760`__ ] - Add Query param to pull back nested stack information +- [`SO-1758 <https://jira.onap.org/browse/SO-1758`__ ] - Fix POM to allow HTTP long polling to work on camunda +- [`SO-1749 <https://jira.onap.org/browse/SO-1749`__ ] - re add openstack audit of delete functions after refactor +- [`SO-1748 <https://jira.onap.org/browse/SO-1748`__ ] - Add support to parse cdl inside LOB and platform +- [`SO-1737 <https://jira.onap.org/browse/SO-1737`__ ] - if audit fails write sub interface data to a ai +- [`SO-1729 <https://jira.onap.org/browse/SO-1729`__ ] - Monitor Job Status-Delete +- [`SO-1687 <https://jira.onap.org/browse/SO-1687`__ ] - removed unused test classes and methods +- [`SO-1678 <https://jira.onap.org/browse/SO-1678`__ ] - removed extra argument from extractByKey method +- [`SO-1676 <https://jira.onap.org/browse/SO-1676`__ ] - replace all fixed wiremock ports +- [`SO-1671 <https://jira.onap.org/browse/SO-1671`__ ] - skip_post_instantiation_configuration schema and tosca ingestion +- [`SO-1657 <https://jira.onap.org/browse/SO-1657`__ ] - Automated testing for the SO Monitoring component +- [`SO-1648 <https://jira.onap.org/browse/SO-1648`__ ] - Increasing the test coverage of SO-Monitoring UI +- [`SO-1634 <https://jira.onap.org/browse/SO-1634`__ ] - Notification Handling - Terminate +- [`SO-1633 <https://jira.onap.org/browse/SO-1633`__ ] - Terminate VNF (with SVNFM interaction) +- [`SO-1632 <https://jira.onap.org/browse/SO-1632`__ ] - Handle VNF delete and termination (without SVNFM integration) +- [`SO-1630 <https://jira.onap.org/browse/SO-1630`__ ] - Monitor Job Status-Create +- [`SO-1629 <https://jira.onap.org/browse/SO-1629`__ ] - Notification Handling - Instantiate +- [`SO-1628 <https://jira.onap.org/browse/SO-1628`__ ] - Handle Notification Subscription +- [`SO-1627 <https://jira.onap.org/browse/SO-1627`__ ] - Create relationship between esr-vnfm and generic-vnf in AAI +- [`SO-1626 <https://jira.onap.org/browse/SO-1626`__ ] - Monitor Node Status +- [`SO-1625 <https://jira.onap.org/browse/SO-1625`__ ] - Handle Grant Request (Without Homing/OOF) +- [`SO-1624 <https://jira.onap.org/browse/SO-1624`__ ] - Instantiate VNF (with SVNFM Interaction) +- [`SO-1623 <https://jira.onap.org/browse/SO-1623`__ ] - Handle Create VNF request in VNFM adapter +- [`SO-1622 <https://jira.onap.org/browse/SO-1622`__ ] - Check for existing VNF (with SVNFM Interaction) +- [`SO-1621 <https://jira.onap.org/browse/SO-1621`__ ] - Create placeholder implementation for create VNF (without SVNFM interaction) +- [`SO-1620 <https://jira.onap.org/browse/SO-1620`__ ] - Create Shell Adapter +- [`SO-1619 <https://jira.onap.org/browse/SO-1619`__ ] - Create SO VNFM Adapter Northbound Interface using Swagger +- [`SO-1618 <https://jira.onap.org/browse/SO-1618`__ ] - SVNFM Simulator +- [`SO-1616 <https://jira.onap.org/browse/SO-1616`__ ] - Add instance group support to SO +- [`SO-1604 <https://jira.onap.org/browse/SO-1604`__ ] - SO Catalog Enhancement to support CDS Meta Data for VNF/PNF and PNF Tosca Ingestion +- [`SO-1598 <https://jira.onap.org/browse/SO-1598`__ ] - add equals and hashcode support to dslquerybuilder +- [`SO-1597 <https://jira.onap.org/browse/SO-1597`__ ] - improvements to audit inventory feature +- [`SO-1596 <https://jira.onap.org/browse/SO-1596`__ ] - query clients now have more useable result methods +- [`SO-1590 <https://jira.onap.org/browse/SO-1590`__ ] - skip cloud region validation for 1906 +- [`SO-1589 <https://jira.onap.org/browse/SO-1589`__ ] - flow validators can now be skipped via an annotation +- [`SO-1582 <https://jira.onap.org/browse/SO-1582`__ ] - vnf spin up gr api vnf s base module fails +- [`SO-1573 <https://jira.onap.org/browse/SO-1573`__ ] - Abstract for CDS Implementation +- [`SO-1569 <https://jira.onap.org/browse/SO-1569`__ ] - do not attempt to commit empty transactions +- [`SO-1538 <https://jira.onap.org/browse/SO-1538`__ ] - Integration Test for SO VNFM Adapter - Perform the functional test to validate VNFM Adapter NBI and SOL003-based SBI +- [`SO-1534 <https://jira.onap.org/browse/SO-1534`__ ] - Create Pre Building Block validator to check if cloud-region orchestration-disabled is true +- [`SO-1533 <https://jira.onap.org/browse/SO-1533`__ ] - flowvaldiator will allow more flexible filtering +- [`SO-1512 <https://jira.onap.org/browse/SO-1512`__ ] - Added Camunda migration scripts and updated camunda springboot version +- [`SO-1506 <https://jira.onap.org/browse/SO-1506`__ ] - E2E Automation - Extend PNF workflow with post-instantiation configuration +- [`SO-1501 <https://jira.onap.org/browse/SO-1501`__ ] - add new functionality to aai client +- [`SO-1495 <https://jira.onap.org/browse/SO-1495`__ ] - made max retries configurable via mso config repo +- [`SO-1493 <https://jira.onap.org/browse/SO-1493`__ ] - restructure a&ai client +- [`SO-1487 <https://jira.onap.org/browse/SO-1487`__ ] - added license headers to various java files +- [`SO-1485 <https://jira.onap.org/browse/SO-1485`__ ] - add DSL endpoint support to A&AI Client +- [`SO-1483 <https://jira.onap.org/browse/SO-1483`__ ] - SO to support a new GRPC client for container to container communication +- [`SO-1482 <https://jira.onap.org/browse/SO-1482`__ ] - SO Generic Building Block to support config deploy action for CONFIGURE Step +- [`SO-1481 <https://jira.onap.org/browse/SO-1481`__ ] - Generic Bulding block for assign shall trigger controller for config assign action +- [`SO-1477 <https://jira.onap.org/browse/SO-1477`__ ] - AAF support for SO +- [`SO-1476 <https://jira.onap.org/browse/SO-1476`__ ] - Do not process vf module being created when building an index +- [`SO-1475 <https://jira.onap.org/browse/SO-1475`__ ] - store raw distribution notification in db +- [`SO-1474 <https://jira.onap.org/browse/SO-1474`__ ] - Test Issue +- [`SO-1469 <https://jira.onap.org/browse/SO-1469`__ ] - Refactor OOF Homing to Java +- [`SO-1462 <https://jira.onap.org/browse/SO-1462`__ ] - Clean up AT&T Acronyms from Unit tests for audit +- [`SO-1459 <https://jira.onap.org/browse/SO-1459`__ ] - add maven build properties to spring actuator +- [`SO-1456 <https://jira.onap.org/browse/SO-1456`__ ] - prototype fetching resources from openstack and compare to a ai +- [`SO-1452 <https://jira.onap.org/browse/SO-1452`__ ] - added list of flows to execution for cockpit +- [`SO-1451 <https://jira.onap.org/browse/SO-1451`__ ] - Updated the SDC API call with the ECOMP OE from AAI +- [`SO-1450 <https://jira.onap.org/browse/SO-1450`__ ] - support for secure communications between SO and Multicloud +- [`SO-1447 <https://jira.onap.org/browse/SO-1447`__ ] - Refine multicloud use of SO cloudsites and identify DB +- [`SO-1446 <https://jira.onap.org/browse/SO-1446`__ ] - Multicloud API updates for generic clouds +- [`SO-1445 <https://jira.onap.org/browse/SO-1445`__ ] - Multicloud support for volume groups and networks +- [`SO-1444 <https://jira.onap.org/browse/SO-1444`__ ] - AAI update after vfmodule creation +- [`SO-1443 <https://jira.onap.org/browse/SO-1443`__ ] - Prepare user_directives for multicloud API +- [`SO-1442 <https://jira.onap.org/browse/SO-1442`__ ] - Prepare sdnc_directives for multicloud API +- [`SO-1441 <https://jira.onap.org/browse/SO-1441`__ ] - Handle distribution of service with generic cloud artifacts +- [`SO-1436 <https://jira.onap.org/browse/SO-1436`__ ] - removed unnecessary repository from pom.xml +- [`SO-1432 <https://jira.onap.org/browse/SO-1432`__ ] - duplicate add custom object support to a ai client +- [`SO-1431 <https://jira.onap.org/browse/SO-1431`__ ] - Test issue 1 +- [`SO-1429 <https://jira.onap.org/browse/SO-1429`__ ] - add custom object support to a ai client +- [`SO-1427 <https://jira.onap.org/browse/SO-1427`__ ] - Fix to include alloc pool from dhcpStart/end on reqs +- [`SO-1426 <https://jira.onap.org/browse/SO-1426`__ ] - Upgraded tosca parser to version 1.4.8 and updated imports +- [`SO-1425 <https://jira.onap.org/browse/SO-1425`__ ] - Re-Factor DMAAP Credentials to use encrypted auth +- [`SO-1421 <https://jira.onap.org/browse/SO-1421`__ ] - Support for SO->ExtAPI interface/API +- [`SO-1414 <https://jira.onap.org/browse/SO-1414`__ ] - update all inprogress checks in apih handler +- [`SO-1413 <https://jira.onap.org/browse/SO-1413`__ ] - replaced org.mockito.Matchers with ArgumentMatchers +- [`SO-1411 <https://jira.onap.org/browse/SO-1411`__ ] - Test Issue +- [`SO-1409 <https://jira.onap.org/browse/SO-1409`__ ] - added in validation for number of keys provided +- [`SO-1405 <https://jira.onap.org/browse/SO-1405`__ ] - apih infra shall ensure data for si matches on macro requests +- [`SO-1404 <https://jira.onap.org/browse/SO-1404`__ ] - covert sync calls for create and delete network to async +- [`SO-1395 <https://jira.onap.org/browse/SO-1395`__ ] - E2E Automation - PreInstatition and PostInstatition use cases +- [`SO-1389 <https://jira.onap.org/browse/SO-1389`__ ] - added mso-request-id when calling SDNCHandler subflow +- [`SO-1388 <https://jira.onap.org/browse/SO-1388`__ ] - descriptive messages now returned by validator +- [`SO-1387 <https://jira.onap.org/browse/SO-1387`__ ] - naming ms client fixes +- [`SO-1385 <https://jira.onap.org/browse/SO-1385`__ ] - removed retired A&AI versions from codebase +- [`SO-1384 <https://jira.onap.org/browse/SO-1384`__ ] - sdnc handler was not sending workflow exception upwards +- [`SO-1383 <https://jira.onap.org/browse/SO-1383`__ ] - refactored validator to be more generic +- [`SO-1381 <https://jira.onap.org/browse/SO-1381`__ ] - Quality of Life logging improvements +- [`SO-1380 <https://jira.onap.org/browse/SO-1380`__ ] - Service Proxy Consolidation +- [`SO-1379 <https://jira.onap.org/browse/SO-1379`__ ] - Add validation for vnfs before WorkflowAction starts +- [`SO-1378 <https://jira.onap.org/browse/SO-1378`__ ] - get subnet sequence number from A&AI +- [`SO-1377 <https://jira.onap.org/browse/SO-1377`__ ] - Re-enable Actuator for Springboot 2.0 +- [`SO-1376 <https://jira.onap.org/browse/SO-1376`__ ] - Created sniro request pojos for homingV2 flow +- [`SO-1370 <https://jira.onap.org/browse/SO-1370`__ ] - Preparation for next scale-out after successful instantiation of the current scale-out operation +- [`SO-1369 <https://jira.onap.org/browse/SO-1369`__ ] - Processing of configuration parameters during instantiation and scale-out +- [`SO-1368 <https://jira.onap.org/browse/SO-1368`__ ] - VNF Health check during scale-out to be made as a separate workflow +- [`SO-1367 <https://jira.onap.org/browse/SO-1367`__ ] - Invoke the APP-C service configuration API after E2E Service instantiation +- [`SO-1366 <https://jira.onap.org/browse/SO-1366`__ ] - SO Workflow need to call configure API during instantiation +- [`SO-1362 <https://jira.onap.org/browse/SO-1362`__ ] - Changed the MDC sourcing from LoggingInterceptor to JaxRsFilterLogging. +- [`SO-1346 <https://jira.onap.org/browse/SO-1346`__ ] - Use SLF4J/Logback, instead of Log4J +- [`SO-1307 <https://jira.onap.org/browse/SO-1307`__ ] - Add Headers +- [`SO-1295 <https://jira.onap.org/browse/SO-1295`__ ] - Update SDNC client Version in POM +- [`SO-1293 <https://jira.onap.org/browse/SO-1293`__ ] - Vnf Recreate +- [`SO-1290 <https://jira.onap.org/browse/SO-1290`__ ] - Update orchestrationrequest response +- [`SO-1288 <https://jira.onap.org/browse/SO-1288`__ ] - Enhance GRM Clients to use encrypted auth loading +- [`SO-1287 <https://jira.onap.org/browse/SO-1287`__ ] - Change all SDNC Calls in GR_API +- [`SO-1284 <https://jira.onap.org/browse/SO-1284`__ ] - Create Relationship between Vnf and Tenant +- [`SO-1283 <https://jira.onap.org/browse/SO-1283`__ ] - Fix GR_API cloud info retrieval +- [`SO-1282 <https://jira.onap.org/browse/SO-1282`__ ] - Update Alacarte Logic for Recreate Flow +- [`SO-1279 <https://jira.onap.org/browse/SO-1279`__ ] - Replaced the VNFC hardcoded Function +- [`SO-1278 <https://jira.onap.org/browse/SO-1278`__ ] - Move all ecomp.mso properties to org.onap.so +- [`SO-1276 <https://jira.onap.org/browse/SO-1276`__ ] - Add Cloud_Owner to northbound request table +- [`SO-1275 <https://jira.onap.org/browse/SO-1275`__ ] - Resolve path issues +- [`SO-1274 <https://jira.onap.org/browse/SO-1274`__ ] - CreateAndUpdatePNFResource workflow:: Associate PNF instance +- [`SO-1272 <https://jira.onap.org/browse/SO-1272`__ ] - Use UUID to fill pnf-id in PNF PnP sub-flow +- [`SO-1270 <https://jira.onap.org/browse/SO-1270`__ ] - Add New A&AI objects +- [`SO-1269 <https://jira.onap.org/browse/SO-1269`__ ] - Add serviceRole to MSO SNIRO Interface +- [`SO-1260 <https://jira.onap.org/browse/SO-1260`__ ] - Add support for naming service +- [`SO-1233 <https://jira.onap.org/browse/SO-1233`__ ] - Added service role to sniro request when not null +- [`SO-1232 <https://jira.onap.org/browse/SO-1232`__ ] - Switch to SpringAutoDeployment rather than processes.xml +- [`SO-1229 <https://jira.onap.org/browse/SO-1229`__ ] - Remove all usage of AlarmLogger +- [`SO-1228 <https://jira.onap.org/browse/SO-1228`__ ] - Limit Number of Occurs for security reasons +- [`SO-1227 <https://jira.onap.org/browse/SO-1227`__ ] - Remove Swagger UI due to security scan concerns +- [`SO-1226 <https://jira.onap.org/browse/SO-1226`__ ] - changed assign vnf sdnc to use the async subflow +- [`SO-1225 <https://jira.onap.org/browse/SO-1225`__ ] - Add Keystone V3 Support +- [`SO-1207 <https://jira.onap.org/browse/SO-1207`__ ] - accept a la carte create instance group request from vid +- [`SO-1206 <https://jira.onap.org/browse/SO-1206`__ ] - Added groupInstanceId and groupInstanceName columns +- [`SO-1205 <https://jira.onap.org/browse/SO-1205`__ ] - separate error status from progression status in req db +- [`SO-806 <https://jira.onap.org/browse/SO-806`__ ] - SO PNF PnP workflow shall not set "in-maint" AAI flag +- [`SO-798 <https://jira.onap.org/browse/SO-798`__ ] - Externalize the PNF PnP workflow 鈥?as a Service Instance Deployment workflow 鈥?adding the Controller +- [`SO-747 <https://jira.onap.org/browse/SO-747`__ ] - POC - Enable SO use of Multicloud Generic VNF Instantiation API +- [`SO-700 <https://jira.onap.org/browse/SO-700`__ ] - SO should be able to support CCVPN service assurance +- [`SO-588 <https://jira.onap.org/browse/SO-588`__ ] - Automate robot heatbridge manual step to add VF Module stack resources in AAI +- [`SO-18 <https://jira.onap.org/browse/SO-18`__ ] - Keystone v3 Support in MSO +- [`SO-12 <https://jira.onap.org/browse/SO-12`__ ] - Support Ocata apis +- [`SO-10 <https://jira.onap.org/browse/SO-10`__ ] - Deploy a MSO high availability environment +- [`SO-7 <https://jira.onap.org/browse/SO-7`__ ] - Move modified openstack library to common functions repos +- [`SO-6 <https://jira.onap.org/browse/SO-6`__ ] - Document how to change username/password for UIs + + +Security Notes +-------------- + SO code has been formally scanned during build time using NexusIQ and all Critical vulnerabilities have been addressed, items that remain open have been assessed for risk and determined to be false positive. The SO open Critical security vulnerabilities and their risk assessment have been documented as part of the `project <https://wiki.onap.org/pages/viewpage.action?pageId=43385708>`_. + +Quick Links: + + - `SO project page <https://wiki.onap.org/display/DW/Service+Orchestrator+Project>`_ + - `Passing Badge information for SO <https://bestpractices.coreinfrastructure.org/en/projects/1702>`_ + - `Project Vulnerability Review Table for SO <https://wiki.onap.org/pages/viewpage.action?pageId=43385708>`_ + + +**Known Issues** + + TBD + +**Upgrade Notes** + + N/A + +**Deprecation Notes** + + N/A + +**Other** + + N/A + +Version: 1.4.1 +============== + +:Release Date: 2019-04-19 + +This is the dublin release base version separated from master branch. + + Version: 1.3.7 -------------- diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java index e6e81671cf..5dd99f51cd 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java @@ -29,7 +29,6 @@ import java.util.UUID; import javax.xml.bind.DatatypeConverter; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -38,8 +37,6 @@ import org.onap.so.apihandler.camundabeans.CamundaInput; import org.onap.so.apihandler.camundabeans.CamundaIntegerInput; import org.onap.so.apihandler.camundabeans.CamundaRequest; import org.onap.so.apihandler.camundabeans.CamundaVIDRequest; -import org.onap.so.logger.ErrorCode; -import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; @@ -60,7 +57,7 @@ public class CamundaClient extends RequestClient { @Override public HttpResponse post(String camundaReqXML, String requestId, String requestTimeout, String schemaVersion, - String serviceInstanceId, String action) throws ClientProtocolException, IOException { + String serviceInstanceId, String action) throws IOException { HttpPost post = new HttpPost(url); logger.debug(CAMUNDA_URL_MESAGE + url); String jsonReq = wrapRequest(camundaReqXML, requestId, serviceInstanceId, requestTimeout, schemaVersion); @@ -83,44 +80,18 @@ public class CamundaClient extends RequestClient { private void setupHeaders(HttpPost post) { post.addHeader(ONAPLogConstants.Headers.REQUEST_ID, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); post.addHeader(ONAPLogConstants.Headers.INVOCATION_ID, UUID.randomUUID().toString()); - - String encryptedCredentials = null; - if (props != null) { - encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH); - if (encryptedCredentials != null) { - String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, - props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP)); - if (userCredentials != null) { - post.addHeader(AUTHORIZATION, - BASIC + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes()))); - } - } - } + addAuthorizationHeader(post); } @Override - public HttpResponse post(String jsonReq) throws ClientProtocolException, IOException { + public HttpResponse post(String jsonReq) throws IOException { HttpPost post = new HttpPost(url); logger.debug(CAMUNDA_URL_MESAGE + url); StringEntity input = new StringEntity(jsonReq); input.setContentType(CommonConstants.CONTENT_TYPE_JSON); setupHeaders(post); - - String encryptedCredentials = null; - if (props != null) { - encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH); - if (encryptedCredentials != null) { - String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, - props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP)); - if (userCredentials != null) { - post.addHeader(AUTHORIZATION, - BASIC + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes()))); - } - } - } - - + addAuthorizationHeader(post); post.setEntity(input); HttpResponse response = client.execute(post); logger.debug(CAMUNDA_RESPONSE, response); @@ -128,7 +99,7 @@ public class CamundaClient extends RequestClient { return response; } - public HttpResponse post(RequestClientParameter parameterObject) throws ClientProtocolException, IOException { + public HttpResponse post(RequestClientParameter parameterObject) throws IOException { HttpPost post = new HttpPost(url); logger.debug(CAMUNDA_URL_MESAGE + url); String jsonReq = wrapVIDRequest(parameterObject.getRequestId(), parameterObject.isBaseVfModule(), @@ -143,23 +114,8 @@ public class CamundaClient extends RequestClient { StringEntity input = new StringEntity(jsonReq); input.setContentType(CommonConstants.CONTENT_TYPE_JSON); - - setupHeaders(post); - - String encryptedCredentials = null; - if (props != null) { - encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH); - if (encryptedCredentials != null) { - String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, - props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP)); - if (userCredentials != null) { - post.addHeader(AUTHORIZATION, - BASIC + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes()))); - } - } - } - + addAuthorizationHeader(post); post.setEntity(input); HttpResponse response = client.execute(post); logger.debug(CAMUNDA_RESPONSE, response); @@ -203,8 +159,7 @@ public class CamundaClient extends RequestClient { jsonReq = mapper.writeValueAsString(camundaRequest); logger.trace("request body is {}", jsonReq); } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", "wrapRequest", - ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e); + logger.error("Error in APIH Warp request", e); } return jsonReq; } @@ -242,7 +197,6 @@ public class CamundaClient extends RequestClient { CamundaInput recipeParamsInput = new CamundaInput(); CamundaInput instanceGroupIdInput = new CamundaInput(); - // host.setValue(parseURL()); requestIdInput.setValue(StringUtils.defaultString(requestId)); isBaseVfModuleInput.setValue(isBaseVfModule); recipeTimeoutInput.setValue(recipeTimeout); @@ -295,8 +249,7 @@ public class CamundaClient extends RequestClient { jsonReq = mapper.writeValueAsString(camundaRequest); logger.trace("request body is {}", jsonReq); } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", "wrapVIDRequest", - ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e); + logger.error("Error in APIH Warp request", e); } return jsonReq; } @@ -312,4 +265,19 @@ public class CamundaClient extends RequestClient { } return host; } + + private void addAuthorizationHeader(HttpPost post) { + String encryptedCredentials; + if (props != null) { + encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH); + if (encryptedCredentials != null) { + String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, + props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP)); + if (userCredentials != null) { + post.addHeader(AUTHORIZATION, + BASIC + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes()))); + } + } + } + } } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/PathResourceResolver.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/PathResourceResolver.java index ad8cc3f250..e2ea021811 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/PathResourceResolver.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/PathResourceResolver.java @@ -52,7 +52,7 @@ public class PathResourceResolver implements LSResourceResolver { try { stream = new FileInputStream(path + systemId); } catch (FileNotFoundException e) { - logger.debug("Could not resolve resource based on file: {}", path + systemId, e); + logger.debug("Could not resolve resource based on file: ", e); } input.setPublicId(publicId); diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java index 9b7801711f..318b3ba5af 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java @@ -25,7 +25,6 @@ package org.onap.so.apihandler.common; import java.io.IOException; import java.security.GeneralSecurityException; import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.onap.so.utils.CryptoUtils; import org.slf4j.Logger; @@ -70,22 +69,12 @@ public abstract class RequestClient { public abstract HttpResponse post(String request, String requestId, String requestTimeout, String schemaVersion, String serviceInstanceId, String action) throws IOException; - public abstract HttpResponse post(String request) throws ClientProtocolException, IOException; + public abstract HttpResponse post(String request) throws IOException; - public abstract HttpResponse post(RequestClientParameter parameterObject) - throws ClientProtocolException, IOException; + public abstract HttpResponse post(RequestClientParameter parameterObject) throws IOException; public abstract HttpResponse get() throws IOException; - protected String decryptPropValue(String prop, String defaultValue, String encryptionKey) { - try { - return CryptoUtils.decrypt(prop, encryptionKey); - } catch (GeneralSecurityException e) { - logger.debug("Security exception", e); - } - return defaultValue; - } - protected String getEncryptedPropValue(String prop, String defaultValue, String encryptionKey) { try { return CryptoUtils.decrypt(prop, encryptionKey); diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java index 4149d5ee45..c2ffa7e004 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java @@ -4,6 +4,9 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * * 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 @@ -20,9 +23,7 @@ package org.onap.so.apihandler.common; - - -import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @@ -34,7 +35,7 @@ public class RequestClientFactory { private Environment env; // based on URI, returns BPEL, CamundaTask or Camunda client - public RequestClient getRequestClient(String orchestrationURI) throws IllegalStateException { + public RequestClient getRequestClient(String orchestrationURI) { RequestClient retClient; String url; @@ -45,7 +46,7 @@ public class RequestClientFactory { url = env.getProperty(CommonConstants.CAMUNDA_URL) + orchestrationURI; retClient = new CamundaClient(); } - retClient.setClient(new DefaultHttpClient()); + retClient.setClient(HttpClientBuilder.create().build()); retClient.setProps(env); retClient.setUrl(url); return retClient; diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/XMLValidator.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/XMLValidator.java index b972f7e1db..2b08d1130f 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/XMLValidator.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/XMLValidator.java @@ -32,8 +32,6 @@ import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.apache.commons.io.IOUtils; -import org.onap.so.logger.ErrorCode; -import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; @@ -94,8 +92,7 @@ public class XMLValidator { return "ErrorDetails: " + e.getMessage(); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_CANNOT_READ_SCHEMA.toString(), ErrorCode.SchemaError.getValue(), - "APIH cannot read schema file", e); + logger.error("APIH cannot read schema file", e); return "ErrorDetails: " + "Unable to read the schema file"; } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java index 399e0650f9..a1c1dd1cc4 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java @@ -52,7 +52,7 @@ public class RequestIdFilter implements ContainerRequestFilter { if (infraActiveRequests != null) { MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(HttpStatus.SC_BAD_REQUEST)); - logger.error("RequestID exists in RequestDB.InfraActiveRequests : " + requestId); + logger.error("RequestID exists in RequestDB.InfraActiveRequests : {}", requestId); } } } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java index 77dbff9ebb..6957e1fe73 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java @@ -24,5 +24,27 @@ package org.onap.so.apihandlerinfra; * Enum for Status values returned by API Handler to Tail-F */ public enum Action implements Actions { - createInstance, updateInstance, deleteInstance, configureInstance, replaceInstance, activateInstance, deactivateInstance, enablePort, disablePort, addRelationships, removeRelationships, inPlaceSoftwareUpdate, applyUpdatedConfig, completeTask, assignInstance, unassignInstance, compareModel, scaleInstance, deactivateAndCloudDelete, scaleOut, recreateInstance, addMembers, removeMembers + createInstance, + updateInstance, + deleteInstance, + configureInstance, + replaceInstance, + activateInstance, + deactivateInstance, + enablePort, + disablePort, + addRelationships, + removeRelationships, + inPlaceSoftwareUpdate, + applyUpdatedConfig, + completeTask, + assignInstance, + unassignInstance, + compareModel, + scaleInstance, + deactivateAndCloudDelete, + scaleOut, + recreateInstance, + addMembers, + removeMembers } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java index 3b977639fc..66b86a6961 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java @@ -37,16 +37,14 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; -import org.onap.so.logger.ErrorCode; -import org.onap.so.logger.MessageEnum; import org.onap.so.serviceinstancebeans.RequestError; import org.onap.so.serviceinstancebeans.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; @Provider public class ApiExceptionMapper implements ExceptionMapper<ApiException> { @@ -134,8 +132,7 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> { } catch (JsonProcessingException | JAXBException e) { String errorMsg = "Exception in buildServiceErrorResponse writing exceptionType to string " + e.getMessage(); - logger.error("{} {} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(), "BuildServiceErrorResponse", - ErrorCode.DataError.getValue(), errorMsg, e); + logger.error("BuildServiceErrorResponse", e); return errorMsg; } diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/RequestClientTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/RequestClientTest.java new file mode 100644 index 0000000000..86b12ae8f6 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/RequestClientTest.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (c) 2019 Samsung. 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.apihandler.common; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class RequestClientTest { + + private static final String ENCRYPTION_KEY = "aa3871669d893c7fb8abbcda31b88b4f"; + + private RequestClient requestClient; + + @Before + public void init() { + requestClient = Mockito.mock(RequestClient.class, Mockito.CALLS_REAL_METHODS); + } + + @Test + public void getEncryptedPropValueWithSuccess() { + + String encryptedValue = requestClient.getEncryptedPropValue( + "E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE", + "defaultValue", ENCRYPTION_KEY); + + Assert.assertEquals("apihBpmn:camunda-R1512!", encryptedValue); + } + + @Test + public void getDefaultEncryptedPropValue() { + + String encryptedValue = + requestClient.getEncryptedPropValue("012345678901234567890123456789", "defaultValue", ENCRYPTION_KEY); + + Assert.assertEquals("defaultValue", encryptedValue); + } + +} diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java index 6c674db9f4..9bf83153b3 100644 --- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java +++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.apihandler.filters; import static org.junit.Assert.assertEquals; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java index 974d025ff2..d0302f2e59 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java @@ -22,5 +22,28 @@ package org.onap.so.apihandlerinfra; public enum Action implements Actions { - createInstance, updateInstance, deleteInstance, configureInstance, replaceInstance, replaceInstanceRetainAssignments, activateInstance, deactivateInstance, enablePort, disablePort, addRelationships, removeRelationships, inPlaceSoftwareUpdate, applyUpdatedConfig, completeTask, assignInstance, unassignInstance, compareModel, scaleInstance, deactivateAndCloudDelete, scaleOut, recreateInstance, addMembers, removeMembers + createInstance, + updateInstance, + deleteInstance, + configureInstance, + replaceInstance, + replaceInstanceRetainAssignments, + activateInstance, + deactivateInstance, + enablePort, + disablePort, + addRelationships, + removeRelationships, + inPlaceSoftwareUpdate, + applyUpdatedConfig, + completeTask, + assignInstance, + unassignInstance, + compareModel, + scaleInstance, + deactivateAndCloudDelete, + scaleOut, + recreateInstance, + addMembers, + removeMembers } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java index 3996d511a7..835a24c4ce 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java @@ -38,6 +38,7 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.json.JSONObject; @@ -228,8 +229,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity().toString()); return response; @@ -280,8 +281,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString()); return resp; } @@ -306,7 +307,7 @@ public class E2EServiceInstances { try { operationStatus = requestsDbClient.getOneByServiceIdAndOperationId(serviceId, operationId); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Request DB - Infra Request Lookup", e); Response response = @@ -321,8 +322,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NO_CONTENT, MsoException.ServiceException, "E2E serviceId " + serviceId + " is not found in DB", ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from RequestDB when searching by serviceId"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; @@ -350,8 +351,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -375,8 +376,8 @@ public class E2EServiceInstances { return response; } if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB"); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "Recipe does not exist in catalog DB", ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); @@ -414,8 +415,9 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine"); logger.debug("End of the transaction, the final response is: " + resp.getEntity()); return resp; } @@ -424,8 +426,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -455,8 +457,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -473,8 +475,8 @@ public class E2EServiceInstances { if (requestId != null) { logger.debug("Logging failed message to the database"); } - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -483,7 +485,7 @@ public class E2EServiceInstances { try { recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), @@ -495,8 +497,8 @@ public class E2EServiceInstances { } if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB"); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "Recipe does not exist in catalog DB", ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); @@ -530,8 +532,9 @@ public class E2EServiceInstances { MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine"); logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity()); return getBPMNResp; @@ -541,8 +544,8 @@ public class E2EServiceInstances { Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity()); return getBPMNResp; } @@ -572,8 +575,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -590,8 +593,8 @@ public class E2EServiceInstances { if (requestId != null) { logger.debug("Logging failed message to the database"); } - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -600,7 +603,7 @@ public class E2EServiceInstances { try { recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), @@ -610,8 +613,8 @@ public class E2EServiceInstances { } if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB"); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "Recipe does not exist in catalog DB", ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); @@ -644,8 +647,9 @@ public class E2EServiceInstances { MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -654,8 +658,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -684,8 +688,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -695,7 +699,7 @@ public class E2EServiceInstances { // TODO Get the service template model version uuid from AAI. recipeLookupResult = getServiceInstanceOrchestrationURI(null, action); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, @@ -708,8 +712,8 @@ public class E2EServiceInstances { return response; } if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB"); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "Recipe does not exist in catalog DB", @@ -747,8 +751,9 @@ public class E2EServiceInstances { MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine", e); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine", e); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -757,8 +762,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -790,8 +795,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException, "Request Failed due to BPEL error with HTTP Status= %1 " + '\n' + camundaJSONResponseBody, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(), - ErrorCode.BusinessProcesssError.getValue(), + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), + requestClient.getUrl(), ErrorCode.BusinessProcesssError.getValue(), "Response from BPEL engine is failed with HTTP Status=" + bpelStatus); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java index 4d283f26b1..3d4b2c76fb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java @@ -25,6 +25,7 @@ package org.onap.so.apihandlerinfra; import java.net.URI; import java.util.Collections; +import org.onap.so.logger.LoggingAnchor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -112,7 +113,7 @@ public class GlobalHealthcheckHandler { try { // Generated RequestId String requestId = requestContext.getProperty("requestId").toString(); - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); // set APIH status, this is the main entry point rsp.setApih(HealthcheckStatus.UP.toString()); 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 c1f55c7555..c582e429ff 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 @@ -253,7 +253,7 @@ public class InstanceManagement { if (workflow == null) { return null; } else { - String workflowName = workflow.getArtifactName(); + String workflowName = workflow.getName(); recipeUri = "/mso/async/services/" + workflowName; } return new RecipeLookupResult(recipeUri, 180); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java index 3c06804594..47f978a9e2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java @@ -34,6 +34,7 @@ import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; @@ -91,7 +92,7 @@ public class ManualTasks { @PathParam("taskId") String taskId, @Context ContainerRequestContext requestContext) throws ApiException { String requestId = requestContext.getProperty("requestId").toString(); - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); long startTime = System.currentTimeMillis(); logger.debug("requestId is: {}", requestId); TasksRequest taskRequest = null; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java index 401a6a9db6..45b521d984 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java @@ -44,13 +44,13 @@ import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest; -import org.onap.so.apihandlerinfra.validation.MembersValidation; import org.onap.so.apihandlerinfra.validation.ApplyUpdatedConfigValidation; import org.onap.so.apihandlerinfra.validation.CloudConfigurationValidation; import org.onap.so.apihandlerinfra.validation.ConfigurationParametersValidation; import org.onap.so.apihandlerinfra.validation.CustomWorkflowValidation; import org.onap.so.apihandlerinfra.validation.InPlaceSoftwareUpdateValidation; import org.onap.so.apihandlerinfra.validation.InstanceIdMapValidation; +import org.onap.so.apihandlerinfra.validation.MembersValidation; import org.onap.so.apihandlerinfra.validation.ModelInfoValidation; import org.onap.so.apihandlerinfra.validation.PlatformLOBValidation; import org.onap.so.apihandlerinfra.validation.ProjectOwningEntityValidation; @@ -68,9 +68,7 @@ import org.onap.so.apihandlerinfra.vnfbeans.VnfRequest; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; -import org.onap.so.logger.ErrorCode; import org.onap.so.logger.LogConstants; -import org.onap.so.logger.MessageEnum; import org.onap.so.serviceinstancebeans.CloudConfiguration; import org.onap.so.serviceinstancebeans.InstanceDirection; import org.onap.so.serviceinstancebeans.ModelInfo; @@ -151,8 +149,7 @@ public class MsoRequest { mapper.setSerializationInclusion(Include.NON_DEFAULT); requestErrorStr = mapper.writeValueAsString(re); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_VALIDATION_ERROR.toString(), ErrorCode.DataError.getValue(), - "Exception in buildServiceErrorResponse writing exceptionType to string ", e); + logger.error("Exception in buildServiceErrorResponse writing exceptionType to string ", e); } return builder.buildResponse(httpResponseCode, null, requestErrorStr, version); @@ -396,8 +393,7 @@ public class MsoRequest { aq.setRequestStatus(status.toString()); aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(), - "Exception when creation record request", e); + logger.error("Exception when creation record request", e); if (!status.equals(Status.FAILED)) { throw e; @@ -437,8 +433,7 @@ public class MsoRequest { aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(), - "Exception when creation record request", e); + logger.error("Exception when creation record request", e); if (!status.equals(Status.FAILED)) { throw e; @@ -465,8 +460,7 @@ public class MsoRequest { request.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); requestsDbClient.save(request); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), - ErrorCode.DataError.getValue(), "Exception when updating record in DB"); + logger.error("Exception when updating record in DB", e); logger.debug("Exception: ", e); } } @@ -547,8 +541,7 @@ public class MsoRequest { return null; } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_DOM2STR_ERROR.toString(), ErrorCode.DataError.getValue(), - "Exception in domToStr", e); + logger.error("Exception in domToStr", e); } return null; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java index fd0df1d2b0..13f1e52068 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java @@ -20,9 +20,14 @@ package org.onap.so.apihandlerinfra; public enum MsoSubsystems { - APIH("API Handler"), ASDC("ASDC Controller"), BPMN("BPMN Infra"), CATALOGDB("CatalogDb Adapter"), OPENSTACK( - "Openstack Adapter"), REQUESTDB( - "RequestDB Adapter"), REQUESTDBATT("RequestDB Adapter ATT Svc"), SDNC("SDNC Adapter"); + APIH("API Handler"), + ASDC("ASDC Controller"), + BPMN("BPMN Infra"), + CATALOGDB("CatalogDb Adapter"), + OPENSTACK("Openstack Adapter"), + REQUESTDB("RequestDB Adapter"), + REQUESTDBATT("RequestDB Adapter ATT Svc"), + SDNC("SDNC Adapter"); private String subsystem; private MsoSubsystems(String subsystem) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java index 9810895ad9..3337c62afd 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java @@ -30,6 +30,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpStatus; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; @@ -57,7 +58,7 @@ public class NodeHealthcheckHandler { public Response nodeHealthcheck(@Context ContainerRequestContext requestContext) throws UnknownHostException { // Generated RequestId String requestId = requestContext.getProperty("requestId").toString(); - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); return HEALTH_CHECK_RESPONSE; } } 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 ff8b5d14cd..e14b01792a 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 @@ -290,7 +290,7 @@ public class OrchestrationRequests { return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build(); } - private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar, boolean includeCloudRequest) + protected Request mapInfraActiveRequestToRequest(InfraActiveRequests iar, boolean includeCloudRequest) throws ApiException { String requestBody = iar.getRequestBody(); Request request = new Request(); @@ -304,6 +304,11 @@ public class OrchestrationRequests { String flowStatusMessage = iar.getFlowStatus(); String retryStatusMessage = iar.getRetryStatusMessage(); + String originalRequestId = iar.getOriginalRequestId(); + if (originalRequestId != null) { + request.setOriginalRequestId(originalRequestId); + } + InstanceReferences ir = new InstanceReferences(); if (iar.getNetworkId() != null) ir.setNetworkInstanceId(iar.getNetworkId()); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java index f6fc88d559..f88d244a88 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java @@ -52,6 +52,7 @@ import org.onap.so.apihandler.common.RequestClientFactory; import org.onap.so.apihandler.common.RequestClientParameter; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandler.common.ResponseHandler; +import org.onap.so.apihandlerinfra.TestApi; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException; @@ -59,7 +60,9 @@ import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException; import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; +import org.onap.so.db.catalog.beans.VfModule; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; @@ -67,6 +70,7 @@ import org.onap.so.exceptions.ValidationException; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.LogConstants; import org.onap.so.logger.MessageEnum; +import org.onap.so.serviceinstancebeans.ModelInfo; import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.RelatedInstance; import org.onap.so.serviceinstancebeans.RelatedInstanceList; @@ -621,7 +625,8 @@ public class RequestHandlerUtils { } protected InfraActiveRequests createNewRecordCopyFromInfraActiveRequest(InfraActiveRequests infraActiveRequest, - String requestId, Timestamp startTimeStamp, String source, String requestUri, String requestorId) { + String requestId, Timestamp startTimeStamp, String source, String requestUri, String requestorId, + String originalRequestId) { InfraActiveRequests request = new InfraActiveRequests(); request.setRequestId(requestId); request.setStartTime(startTimeStamp); @@ -630,17 +635,83 @@ public class RequestHandlerUtils { request.setProgress(new Long(5)); request.setRequestorId(requestorId); request.setRequestStatus(Status.IN_PROGRESS.toString()); + request.setOriginalRequestId(originalRequestId); request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); if (infraActiveRequest != null) { request.setTenantId(infraActiveRequest.getTenantId()); - request.setRequestBody(infraActiveRequest.getRequestBody()); + request.setRequestBody(updateRequestorIdInRequestBody(infraActiveRequest, requestorId)); request.setAicCloudRegion(infraActiveRequest.getAicCloudRegion()); request.setRequestScope(infraActiveRequest.getRequestScope()); - request.setServiceInstanceId(infraActiveRequest.getServiceInstanceId()); - request.setServiceInstanceName(infraActiveRequest.getServiceInstanceName()); request.setRequestAction(infraActiveRequest.getRequestAction()); + setInstanceIdAndName(infraActiveRequest, request); } return request; } + protected void setInstanceIdAndName(InfraActiveRequests infraActiveRequest, + InfraActiveRequests currentActiveRequest) { + String requestScope = infraActiveRequest.getRequestScope(); + try { + ModelType type = ModelType.valueOf(requestScope); + type.setName(currentActiveRequest, type.getName(infraActiveRequest)); + type.setId(currentActiveRequest, type.getId(infraActiveRequest)); + } catch (IllegalArgumentException e) { + logger.error( + "requestScope \"{}\" does not match a ModelType enum. Unable to set instanceId and instanceName from the original request.", + requestScope); + } + } + + protected Boolean getIsBaseVfModule(ModelInfo modelInfo, Actions action, String vnfType, + String sdcServiceModelVersion, InfraActiveRequests currentActiveReq) throws ApiException { + // Get VF Module-specific base module indicator + VfModule vfm = null; + String modelVersionId = modelInfo.getModelVersionId(); + Boolean isBaseVfModule = false; + + if (modelVersionId != null) { + vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId); + } else if (modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null) { + vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(), + modelInfo.getModelVersion()); + } + + if (vfm != null) { + if (vfm.getIsBase()) { + isBaseVfModule = true; + } + } else if (action == Action.createInstance || action == Action.updateInstance) { + String serviceVersionText = ""; + if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty()) { + serviceVersionText = " with version " + sdcServiceModelVersion; + } + String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName() + + serviceVersionText + " not found in MSO Catalog DB"; + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage, + HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage()); + throw vfModuleException; + } + return isBaseVfModule; + } + + protected ModelType getModelType(Actions action, ModelInfo modelInfo) { + if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) { + return ModelType.vnf; + } else if (action == Action.addMembers || action == Action.removeMembers) { + return ModelType.instanceGroup; + } else { + return modelInfo.getModelType(); + } + } + + protected String updateRequestorIdInRequestBody(InfraActiveRequests infraActiveRequest, String newRequestorId) { + String requestBody = infraActiveRequest.getRequestBody(); + return requestBody.replaceAll( + "(?s)(\"requestInfo\"\\s*?:\\s*?\\{.*?\"requestorId\"\\s*?:\\s*?\")(.*?)(\"[ ]*(?:,|\\R|\\}))", + "$1" + newRequestorId + "$3"); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java index 6ca23a339b..32d2c50978 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java @@ -47,6 +47,8 @@ import org.onap.so.logger.HttpHeadersConstants; import org.onap.so.logger.LogConstants; import org.onap.so.logger.MdcConstants; import org.onap.so.logger.MessageEnum; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -74,6 +76,8 @@ public class ResumeOrchestrationRequest { @Autowired private RequestsDbClient requestsDbClient; + @Autowired + private MsoRequest msoRequest; @POST @Path("/{version:[vV][7]}/requests/{requestId}/resume") @@ -106,7 +110,7 @@ public class ResumeOrchestrationRequest { } InfraActiveRequests currentActiveRequest = requestHandlerUtils.createNewRecordCopyFromInfraActiveRequest( - infraActiveRequest, currentRequestId, startTimeStamp, source, requestUri, requestorId); + infraActiveRequest, currentRequestId, startTimeStamp, source, requestUri, requestorId, requestId); if (infraActiveRequest == null) { logger.error("No infraActiveRequest record found for requestId: {} in requesteDb lookup", requestId); @@ -128,24 +132,26 @@ public class ResumeOrchestrationRequest { String requestBody = infraActiveRequest.getRequestBody(); Action action = Action.valueOf(infraActiveRequest.getRequestAction()); String requestId = currentActiveRequest.getRequestId(); - String serviceInstanceName = infraActiveRequest.getServiceInstanceName(); String requestScope = infraActiveRequest.getRequestScope(); - String serviceInstanceId = infraActiveRequest.getServiceInstanceId(); + String instanceName = getInstanceName(infraActiveRequest, requestScope, currentActiveRequest); + HashMap<String, String> instanceIdMap = setInstanceIdMap(infraActiveRequest, requestScope); - checkForInProgressRequest(currentActiveRequest, serviceInstanceId, requestScope, serviceInstanceName, action); + checkForInProgressRequest(currentActiveRequest, instanceIdMap, requestScope, instanceName, action); ServiceInstancesRequest sir = null; sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestBody, action, requestId, requestUri); Boolean aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte(); - if (aLaCarte == null) { - aLaCarte = false; - } String pnfCorrelationId = serviceInstances.getPnfCorrelationId(sir); - RecipeLookupResult recipeLookupResult = serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); + RecipeLookupResult recipeLookupResult = serviceInstances.getServiceInstanceOrchestrationURI(sir, action, + msoRequest.getAlacarteFlag(sir), currentActiveRequest); requestDbSave(currentActiveRequest); + if (aLaCarte == null) { + aLaCarte = setALaCarteFlagIfNull(requestScope, action); + } + RequestClientParameter requestClientParameter = setRequestClientParameter(recipeLookupResult, version, infraActiveRequest, currentActiveRequest, pnfCorrelationId, aLaCarte, sir); @@ -153,40 +159,60 @@ public class ResumeOrchestrationRequest { recipeLookupResult.getOrchestrationURI(), requestScope); } - protected void checkForInProgressRequest(InfraActiveRequests currentActiveRequest, String serviceInstanceId, - String requestScope, String serviceInstanceName, Action action) throws ApiException { - boolean inProgress = false; - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - InfraActiveRequests requestInProgress = requestHandlerUtils.duplicateCheck(action, instanceIdMap, - serviceInstanceName, requestScope, currentActiveRequest); - if (requestInProgress != null) { - inProgress = requestHandlerUtils.camundaHistoryCheck(requestInProgress, currentActiveRequest); + protected Boolean setALaCarteFlagIfNull(String requestScope, Action action) { + Boolean aLaCarteFlag; + if (!requestScope.equalsIgnoreCase(ModelType.service.name()) && action != Action.recreateInstance) { + aLaCarteFlag = true; + } else { + aLaCarteFlag = false; } - if (inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveRequest, action, instanceIdMap, - serviceInstanceName, requestScope, requestInProgress); + return aLaCarteFlag; + } + + protected HashMap<String, String> setInstanceIdMap(InfraActiveRequests infraActiveRequest, String requestScope) { + HashMap<String, String> instanceIdMap = new HashMap<>(); + ModelType type; + try { + type = ModelType.valueOf(requestScope); + instanceIdMap.put(type.name() + "InstanceId", type.getId(infraActiveRequest)); + } catch (IllegalArgumentException e) { + logger.error("requestScope \"{}\" does not match a ModelType enum.", requestScope); } + return instanceIdMap; } - protected RecipeLookupResult serviceRecipeLookup(InfraActiveRequests currentActiveRequest, - ServiceInstancesRequest sir, Action action, Boolean aLaCarte) - throws ValidateException, RequestDbFailureException { - RecipeLookupResult recipeLookupResult = null; + protected String getInstanceName(InfraActiveRequests infraActiveRequest, String requestScope, + InfraActiveRequests currentActiveRequest) throws ValidateException, RequestDbFailureException { + ModelType type; + String instanceName = ""; try { - recipeLookupResult = serviceInstances.getServiceURI(sir, action, aLaCarte); - } catch (IOException e) { - logger.error("IOException while performing service recipe lookup", e); - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ValidateException validateException = - new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, - ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); + type = ModelType.valueOf(requestScope); + instanceName = type.getName(infraActiveRequest); + } catch (IllegalArgumentException e) { + logger.error("requestScope \"{}\" does not match a ModelType enum.", requestScope); + ValidateException validateException = new ValidateException.Builder( + "requestScope: \"" + requestScope + "\" from request: " + infraActiveRequest.getRequestId() + + " does not match a ModelType enum.", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).build(); requestHandlerUtils.updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage()); throw validateException; } - return recipeLookupResult; + return instanceName; + } + + protected void checkForInProgressRequest(InfraActiveRequests currentActiveRequest, + HashMap<String, String> instanceIdMap, String requestScope, String instanceName, Action action) + throws ApiException { + boolean inProgress = false; + InfraActiveRequests requestInProgress = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, + requestScope, currentActiveRequest); + if (requestInProgress != null) { + inProgress = requestHandlerUtils.camundaHistoryCheck(requestInProgress, currentActiveRequest); + } + if (inProgress) { + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveRequest, action, instanceIdMap, instanceName, + requestScope, requestInProgress); + } } protected void requestDbSave(InfraActiveRequests currentActiveRequest) throws RequestDbFailureException { @@ -204,23 +230,37 @@ public class ResumeOrchestrationRequest { protected RequestClientParameter setRequestClientParameter(RecipeLookupResult recipeLookupResult, String version, InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest, String pnfCorrelationId, - Boolean aLaCarte, ServiceInstancesRequest sir) throws ValidateException { + Boolean aLaCarte, ServiceInstancesRequest sir) throws ApiException { RequestClientParameter requestClientParameter = null; + Action action = Action.valueOf(infraActiveRequest.getRequestAction()); + ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); + + Boolean isBaseVfModule = false; + if (requestHandlerUtils.getModelType(action, modelInfo).equals(ModelType.vfModule)) { + isBaseVfModule = requestHandlerUtils.getIsBaseVfModule(modelInfo, action, infraActiveRequest.getVnfType(), + msoRequest.getSDCServiceModelVersion(sir), currentActiveRequest); + } + try { - requestClientParameter = new RequestClientParameter.Builder() - .setRequestId(currentActiveRequest.getRequestId()) - .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(infraActiveRequest.getRequestAction()) - .setServiceInstanceId(infraActiveRequest.getServiceInstanceId()) - .setPnfCorrelationId(pnfCorrelationId).setVnfId(infraActiveRequest.getVnfId()) - .setVfModuleId(infraActiveRequest.getVfModuleId()) - .setVolumeGroupId(infraActiveRequest.getVolumeGroupId()) - .setNetworkId(infraActiveRequest.getNetworkId()).setServiceType(infraActiveRequest.getServiceType()) - .setVnfType(infraActiveRequest.getVnfType()).setNetworkType(infraActiveRequest.getNetworkType()) - .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(infraActiveRequest.getRequestBody(), sir, - aLaCarte, Action.valueOf(infraActiveRequest.getRequestAction()))) - .setApiVersion(version).setALaCarte(aLaCarte).setRequestUri(currentActiveRequest.getRequestUrl()) - .setInstanceGroupId(infraActiveRequest.getInstanceGroupId()).build(); + requestClientParameter = + new RequestClientParameter.Builder().setRequestId(currentActiveRequest.getRequestId()) + .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(infraActiveRequest.getRequestAction()) + .setServiceInstanceId(infraActiveRequest.getServiceInstanceId()) + .setPnfCorrelationId(pnfCorrelationId).setVnfId(infraActiveRequest.getVnfId()) + .setVfModuleId(infraActiveRequest.getVfModuleId()) + .setVolumeGroupId(infraActiveRequest.getVolumeGroupId()) + .setNetworkId(infraActiveRequest.getNetworkId()) + .setServiceType(infraActiveRequest.getServiceType()) + .setVnfType(infraActiveRequest.getVnfType()) + .setVfModuleType(msoRequest.getVfModuleType(sir, infraActiveRequest.getRequestScope(), + action, Integer.parseInt(version))) + .setNetworkType(infraActiveRequest.getNetworkType()) + .setRequestDetails(requestHandlerUtils + .mapJSONtoMSOStyle(infraActiveRequest.getRequestBody(), sir, aLaCarte, action)) + .setApiVersion(version).setALaCarte(aLaCarte) + .setRequestUri(currentActiveRequest.getRequestUrl()) + .setInstanceGroupId(infraActiveRequest.getInstanceGroupId()).build(); } catch (IOException e) { logger.error("IOException while generating requestClientParameter to send to BPMN", e); ErrorLoggerInfo errorLoggerInfo = diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java index 45319de5e8..a397676ee2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java @@ -203,7 +203,7 @@ public class ServiceInstances { @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { String requestId = requestHandlerUtils.getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); return serviceInstances(request, Action.unassignInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); @@ -759,10 +759,9 @@ public class ServiceInstances { public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException { - String serviceInstanceId = (instanceIdMap == null) ? null : instanceIdMap.get("serviceInstanceId"); + String serviceInstanceId; Boolean aLaCarte = null; - long startTime = System.currentTimeMillis(); - ServiceInstancesRequest sir = null; + ServiceInstancesRequest sir; String apiVersion = version.substring(1); sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); @@ -814,64 +813,20 @@ public class ServiceInstances { referencesResponse.setRequestId(requestId); serviceResponse.setRequestReferences(referencesResponse); - Boolean isBaseVfModule = false; - RecipeLookupResult recipeLookupResult = getServiceInstanceOrchestrationURI(sir, action, alaCarteFlag, currentActiveReq); String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, alaCarteFlag); - ModelType modelType; - ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); - if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) { - modelType = ModelType.vnf; - } else if (action == Action.addMembers || action == Action.removeMembers) { - modelType = ModelType.instanceGroup; - } else { - modelType = modelInfo.getModelType(); - } - - if (modelType.equals(ModelType.vfModule)) { - - - // Get VF Module-specific base module indicator - VfModule vfm = null; - - String modelVersionId = modelInfo.getModelVersionId(); - if (modelVersionId != null) { - vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId); - } else if (modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null) { - vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(), - modelInfo.getModelVersion()); - } - - if (vfm != null) { - if (vfm.getIsBase()) { - isBaseVfModule = true; - } - } else if (action == Action.createInstance || action == Action.updateInstance) { - // There is no entry for this vfModuleType with this version, if specified, in VF_MODULE table in - // Catalog DB. - // This request cannot proceed - - String serviceVersionText = ""; - if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty()) { - serviceVersionText = " with version " + sdcServiceModelVersion; - } + ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); + ModelType modelType = requestHandlerUtils.getModelType(action, modelInfo); - String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName() - + serviceVersionText + " not found in MSO Catalog DB"; - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage, - HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); - requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage()); + Boolean isBaseVfModule = false; - throw vfModuleException; - } + if (modelType.equals(ModelType.vfModule)) { + isBaseVfModule = requestHandlerUtils.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion, + currentActiveReq); } - serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir); String vnfId = ""; String vfModuleId = ""; @@ -958,7 +913,6 @@ public class ServiceInstances { String requestId, String requestUri, ContainerRequestContext requestContext) throws ApiException { String instanceGroupId = instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID); Boolean aLaCarte = true; - long startTime = System.currentTimeMillis(); String apiVersion = version.substring(1); ServiceInstancesRequest sir = new ServiceInstancesRequest(); sir.setInstanceGroupId(instanceGroupId); @@ -1030,7 +984,7 @@ public class ServiceInstances { .orElse(""); } - private RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action, + protected RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action, boolean alaCarteFlag, InfraActiveRequests currentActiveReq) throws ApiException { RecipeLookupResult recipeLookupResult = null; // if the aLaCarte flag is set to TRUE, the API-H should choose the VID_DEFAULT recipe for the requested action @@ -1275,8 +1229,7 @@ public class ServiceInstances { return mapFlatMapToNameValue(userParams); } - private Service serviceMapper(Map<String, Object> params) - throws JsonProcessingException, IOException, JsonParseException, JsonMappingException { + private Service serviceMapper(Map<String, Object> params) throws IOException { ObjectMapper obj = new ObjectMapper(); String input = obj.writeValueAsString(params.get("service")); return obj.readValue(input, Service.class); @@ -1313,7 +1266,7 @@ public class ServiceInstances { instanceList = servInstReq.getRequestDetails().getRelatedInstanceList(); } - Recipe recipe = null; + Recipe recipe; String defaultSource = requestHandlerUtils.getDefaultModel(servInstReq); String modelCustomizationId = modelInfo.getModelCustomizationId(); String modelCustomizationName = modelInfo.getModelCustomizationName(); @@ -1603,13 +1556,11 @@ public class ServiceInstances { private Response configurationRecipeLookup(String requestJSON, Action action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException { - String serviceInstanceId = (instanceIdMap == null) ? null : instanceIdMap.get("serviceInstanceId"); + String serviceInstanceId; Boolean aLaCarte = null; String apiVersion = version.substring(1); boolean inProgress = false; - - long startTime = System.currentTimeMillis(); - ServiceInstancesRequest sir = null; + ServiceInstancesRequest sir; sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java index c480bdfbd3..bba8064f7c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java @@ -50,6 +50,8 @@ import org.onap.so.db.catalog.beans.WorkflowActivitySpecSequence; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonProcessingException; @@ -69,7 +71,9 @@ public class WorkflowSpecificationsHandler { @Autowired private CatalogDbClient catalogDbClient; + private static Logger logger = LoggerFactory.getLogger(WorkflowSpecificationsHandler.class); private static final String ARTIFACT_TYPE_WORKFLOW = "workflow"; + private static final String NATIVE_WORKFLOW = "native"; @Path("/{version:[vV]1}/workflows") @GET @@ -85,6 +89,12 @@ public class WorkflowSpecificationsHandler { mapper1.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); List<Workflow> workflows = catalogDbClient.findWorkflowByModelUUID(vnfModelVersionId); + + List<Workflow> nativeWorkflows = catalogDbClient.findWorkflowBySource(NATIVE_WORKFLOW); + if (nativeWorkflows != null && nativeWorkflows.size() != 0) { + workflows.addAll(nativeWorkflows); + } + WorkflowSpecifications workflowSpecifications = mapWorkflowsToWorkflowSpecifications(workflows); String jsonResponse = null; @@ -153,6 +163,7 @@ public class WorkflowSpecificationsHandler { if (activitySpec != null) { ActivitySequence activitySequence = new ActivitySequence(); activitySequence.setName(activitySpec.getName()); + logger.debug("Adding activity: " + activitySpec.getName()); activitySequence.setDescription(activitySpec.getDescription()); activitySequences.add(activitySequence); } @@ -164,7 +175,7 @@ public class WorkflowSpecificationsHandler { private List<WorkflowInputParameter> buildWorkflowInputParameters(Workflow workflow) { List<WorkflowActivitySpecSequence> workflowActivitySpecSequences = workflow.getWorkflowActivitySpecSequence(); if (workflowActivitySpecSequences == null || workflowActivitySpecSequences.size() == 0) { - return null; + return new ArrayList<WorkflowInputParameter>(); } Map<String, WorkflowInputParameter> workflowInputParameterMap = new HashMap<String, WorkflowInputParameter>(); for (WorkflowActivitySpecSequence workflowActivitySpecSequence : workflowActivitySpecSequences) { @@ -188,7 +199,7 @@ public class WorkflowSpecificationsHandler { } if (workflowInputParameterMap.size() == 0) { - return null; + return new ArrayList<WorkflowInputParameter>(); } List<WorkflowInputParameter> workflowInputParameterList = workflowInputParameterMap.values().stream().collect(Collectors.toList()); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java index d79d73c036..e8d00ed52b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java @@ -38,6 +38,7 @@ import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandlerinfra.Constants; @@ -125,7 +126,7 @@ public class CloudOrchestration { private Response cloudOrchestration(String requestJSON, Action action, HashMap<String, String> instanceIdMap, String version, String requestId) throws ApiException { - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); long startTime = System.currentTimeMillis(); CloudOrchestrationRequest cor = null; tenantIsolationRequest.setRequestId(requestId); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java index be6d5b06ca..20e8fed32d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java @@ -92,7 +92,7 @@ public class CloudResourcesOrchestration { CloudOrchestrationRequest cor = null; - logger.debug("requestId is: " + requestId); + logger.debug("requestId is: {}", requestId); try { ObjectMapper mapper = new ObjectMapper(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java index 696616099f..007ea938a2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java @@ -45,8 +45,6 @@ import org.onap.so.apihandlerinfra.vnfbeans.RequestStatusType; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; -import org.onap.so.logger.ErrorCode; -import org.onap.so.logger.MessageEnum; import org.onap.so.utils.UUIDChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -356,8 +354,7 @@ public class TenantIsolationRequest { request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); requestsDbClient.save(request); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), - ErrorCode.DataError.getValue(), "Exception when updating record in DB"); + logger.error("Exception when updating record in DB", e); logger.debug("Exception: ", e); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java index d9db5713a7..6942d441e6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java @@ -34,8 +34,6 @@ import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.graphinventory.entities.uri.Depth; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -63,7 +61,7 @@ public class AAIClientHelper { * Update managing ECOMP Environment Info from A&AI * * @param id = operationalEnvironmentId - * @param AAIOperationalEnvironment object + * @param aaiRequest object */ public void updateAaiOperationalEnvironment(String id, OperationalEnvironment aaiRequest) { @@ -75,7 +73,7 @@ public class AAIClientHelper { public void updateAaiOperationalEnvironment(String operationalEnvironmentId, Map<String, String> payload) - throws Exception { + throws AAIClientCallFailed { try { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, operationalEnvironmentId); @@ -90,7 +88,7 @@ public class AAIClientHelper { /** * Create an Operational Environment object in A&AI * - * @param AAIOperationalEnvironment object + * @param operationalEnvironment object */ public void createOperationalEnvironment(OperationalEnvironment operationalEnvironment) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java index b02bd95d97..3b87d91d3f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java @@ -119,12 +119,25 @@ public class RelatedInstancesValidation implements ValidationRule { isRelatedServiceInstancePresent = true; } + if (requestScope.equalsIgnoreCase(ModelType.service.name())) { + if (empty(relatedInstance.getInstanceName()) + && ModelType.vpnBinding.equals(relatedInstanceModelInfo.getModelType())) { + throw new ValidationException("instanceName in relatedInstance for vpnBinding modelType", true); + } + if (empty(relatedInstance.getInstanceName()) + && ModelType.network.equals(relatedInstanceModelInfo.getModelType())) { + throw new ValidationException("instanceName in relatedInstance for network modelType", true); + } + } + if (action != Action.deleteInstance && !requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) { if (!(relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup) || relatedInstanceModelInfo.getModelType().equals(ModelType.connectionPoint) || relatedInstanceModelInfo.getModelType().equals(ModelType.pnf) - || relatedInstanceModelInfo.getModelType().equals(ModelType.networkInstanceGroup))) { + || relatedInstanceModelInfo.getModelType().equals(ModelType.networkInstanceGroup) + || relatedInstanceModelInfo.getModelType().equals(ModelType.network) + || relatedInstanceModelInfo.getModelType().equals(ModelType.vpnBinding))) { if (empty(relatedInstanceModelInfo.getModelInvariantId())) { throw new ValidationException("modelInvariantId in relatedInstance"); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/resources/application.yaml b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application.yaml index e709758223..03934edf20 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/resources/application.yaml +++ b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application.yaml @@ -7,7 +7,7 @@ server: mso: infra: - auditInventory: true + auditInventory: false default: versions: apiMinorVersion: 0 @@ -70,4 +70,4 @@ org: so: adapters: network: - encryptionKey: aa3871669d893c7fb8abbcda31b88b4f
\ No newline at end of file + encryptionKey: aa3871669d893c7fb8abbcda31b88b4f diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java index c30b9dedf2..bc10aa744e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java @@ -83,6 +83,12 @@ public class MsoRequestTest extends BaseTest { return input; } + public String inputStreamVpnBonding(String JsonInput) throws IOException { + JsonInput = "src/test/resources/Validation" + JsonInput; + String input = new String(Files.readAllBytes(Paths.get(JsonInput))); + return input; + } + // Tests for successful validation of incoming JSON requests through the parse method @Test @Parameters(method = "successParameters") @@ -188,6 +194,8 @@ public class MsoRequestTest extends BaseTest { instanceIdMapTest, Action.addRelationships, "5"}, {mapper.readValue(inputStream("/SuccessfulValidation/ServiceAssign.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, "7"}, + {mapper.readValue(inputStream("/RelatedInstances/ServiceInstanceVpnBondingService.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "7"}, {mapper.readValue(inputStream("/SuccessfulValidation/ServiceUnassign.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.unassignInstance, "7"}}); } @@ -546,6 +554,22 @@ public class MsoRequestTest extends BaseTest { mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, 6}, + {"No valid modelType in relatedInstance is specified", + mapper.readValue(inputStreamVpnBonding("/VpnBondingValidation/NoModelType.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + {"No valid instanceId in relatedInstance is specified", + mapper.readValue(inputStreamVpnBonding("/VpnBondingValidation/NoInstanceId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + {"No valid instanceName in relatedInstance for vpnBinding modelType is specified", + mapper.readValue(inputStreamVpnBonding("/VpnBondingValidation/NoInstanceNameVpnBinding.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + {"No valid instanceName in relatedInstance for network modelType is specified", + mapper.readValue(inputStreamVpnBonding("/VpnBondingValidation/NoInstanceNameNetwork.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, {"No valid modelCustomizationName or modelCustomizationId in relatedInstance of vnf is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelCustomizationId.json"), ServiceInstancesRequest.class), diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java new file mode 100644 index 0000000000..19b9d7ea1e --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.apihandlerinfra; + +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertThat; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.serviceinstancebeans.InstanceReferences; +import org.onap.so.serviceinstancebeans.Request; +import org.onap.so.serviceinstancebeans.RequestStatus; + +@RunWith(MockitoJUnitRunner.class) +public class OrchestrationRequestsUnitTest { + + @Spy + private OrchestrationRequests orchestrationRequests; + + private static final String REQUEST_ID = "7cb9aa56-dd31-41e5-828e-d93027d4ebba"; + private static final String SERVICE_INSTANCE_ID = "7cb9aa56-dd31-41e5-828e-d93027d4ebbb"; + private static final String ORIGINAL_REQUEST_ID = "8f2d38a6-7c20-465a-bd7e-075645f1394b"; + private static final String SERVICE = "service"; + private InfraActiveRequests iar; + boolean includeCloudRequest = false; + + @Before + public void setup() { + iar = new InfraActiveRequests(); + iar.setRequestScope(SERVICE); + iar.setRequestId(REQUEST_ID); + iar.setServiceInstanceId(SERVICE_INSTANCE_ID); + } + + @Test + public void mapInfraActiveRequestToRequestWithOriginalRequestIdTest() throws ApiException { + InstanceReferences instanceReferences = new InstanceReferences(); + instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID); + RequestStatus requestStatus = new RequestStatus(); + Request expected = new Request(); + expected.setRequestId(REQUEST_ID); + expected.setOriginalRequestId(ORIGINAL_REQUEST_ID); + expected.setInstanceReferences(instanceReferences); + expected.setRequestStatus(requestStatus); + expected.setRequestScope(SERVICE); + + iar.setOriginalRequestId(ORIGINAL_REQUEST_ID); + + Request result = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest); + assertThat(result, sameBeanAs(expected)); + } + + @Test + public void mapInfraActiveRequestToRequestOriginalRequestIdNullTest() throws ApiException { + InstanceReferences instanceReferences = new InstanceReferences(); + instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID); + RequestStatus requestStatus = new RequestStatus(); + Request expected = new Request(); + expected.setRequestId(REQUEST_ID); + expected.setInstanceReferences(instanceReferences); + expected.setRequestStatus(requestStatus); + expected.setRequestScope(SERVICE); + + Request result = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest); + assertThat(result, sameBeanAs(expected)); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java index e80fd9e690..3cb4e0c9c2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java @@ -21,32 +21,69 @@ package org.onap.so.apihandlerinfra; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.Timestamp; 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.InjectMocks; +import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException; +import org.onap.so.db.catalog.beans.VfModule; +import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.ModelType; @RunWith(MockitoJUnitRunner.class) public class RequestHandlerUtilsUnitTest { + @Mock + private CatalogDbClient catDbClient; + + @InjectMocks @Spy private RequestHandlerUtils requestHandler; + @Rule + public ExpectedException thrown = ExpectedException.none(); + private static final String CURRENT_REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4"; + private static final String RESUMED_REQUEST_ID = "59c7247f-839f-4923-90c3-05faa3ab354d"; private static final String SERVICE_INSTANCE_ID = "00032ab7-na18-42e5-965d-8ea592502018"; + private static final String SERVICE_INSTANCE_NAME = "serviceInstanceName"; + private static final String VNF_ID = "00032ab7-na18-42e5-965d-8ea592502017"; + private static final String VFMODULE_ID = "00032ab7-na18-42e5-965d-8ea592502016"; + private static final String NETWORK_ID = "00032ab7-na18-42e5-965d-8ea592502015"; + private static final String VOLUME_GROUP_ID = "00032ab7-na18-42e5-965d-8ea592502014"; + private static final String VNF_NAME = "vnfName"; + private static final String VFMODULE_NAME = "vfModuleName"; + private static final String NETWORK_NAME = "networkName"; + private static final String VOLUME_GROUP_NAME = "volumeGroupName"; + private static final String MODEL_VERSION_ID = "883f4a7a-b5a5-44e0-8738-361c6413d24c"; + private static final String MODEL_VERSION = "1.0"; + private static final String MODEL_INVARIANT_ID = "d358b828-e7f8-4833-ac96-2782bed1a9a9"; + private static final String MODEL_NAME = "modelName"; private final Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); private String requestUri = "http:localhost:6746/onap/so/infra/orchestrationRequests/v7/00032ab7-na18-42e5-965d-8ea592502019/resume"; private InfraActiveRequests infraActiveRequest = new InfraActiveRequests(); private InfraActiveRequests currentActiveRequest = new InfraActiveRequests(); private InfraActiveRequests currentActiveRequestIARNull = new InfraActiveRequests(); + private Action action = Action.createInstance; + private String vnfType = "vnfType"; + private String sdcServiceModelVersion = "7"; public String getRequestBody(String request) throws IOException { request = "src/test/resources/ResumeOrchestrationRequest" + request; @@ -66,7 +103,7 @@ public class RequestHandlerUtilsUnitTest { infraActiveRequest.setAicCloudRegion("cloudRegion"); infraActiveRequest.setRequestScope("service"); infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); - infraActiveRequest.setServiceInstanceName("serviceInstanceName"); + infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); infraActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); infraActiveRequest.setRequestAction(Action.createInstance.toString()); infraActiveRequest.setServiceType("serviceType"); @@ -77,17 +114,16 @@ public class RequestHandlerUtilsUnitTest { currentActiveRequest.setSource("VID"); currentActiveRequest.setStartTime(startTimeStamp); currentActiveRequest.setTenantId("tenant-id"); - currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + currentActiveRequest.setRequestBody(getRequestBody("/RequestBodyNewRequestorId.json")); currentActiveRequest.setAicCloudRegion("cloudRegion"); currentActiveRequest.setRequestScope("service"); - currentActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); - currentActiveRequest.setServiceInstanceName("serviceInstanceName"); currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); currentActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); currentActiveRequest.setRequestAction(Action.createInstance.toString()); currentActiveRequest.setRequestUrl(requestUri); - currentActiveRequest.setRequestorId("xxxxxx"); + currentActiveRequest.setRequestorId("yyyyyy"); currentActiveRequest.setProgress(new Long(5)); + currentActiveRequest.setOriginalRequestId(RESUMED_REQUEST_ID); } private void setCurrentActiveRequestNullInfraActive() throws IOException { @@ -99,20 +135,275 @@ public class RequestHandlerUtilsUnitTest { currentActiveRequestIARNull.setRequestUrl(requestUri); currentActiveRequestIARNull.setRequestorId("xxxxxx"); currentActiveRequestIARNull.setProgress(new Long(5)); + currentActiveRequestIARNull.setOriginalRequestId(RESUMED_REQUEST_ID); } @Test - public void createNewRecordCopyFromInfraActiveRequestTest() { + public void createNewRecordCopyFromInfraActiveRequestTest() throws IOException { + doNothing().when(requestHandler).setInstanceIdAndName(infraActiveRequest, currentActiveRequest); + doReturn(getRequestBody("/RequestBodyNewRequestorId.json")).when(requestHandler) + .updateRequestorIdInRequestBody(infraActiveRequest, "yyyyyy"); InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(infraActiveRequest, - CURRENT_REQUEST_ID, startTimeStamp, "VID", requestUri, "xxxxxx"); + CURRENT_REQUEST_ID, startTimeStamp, "VID", requestUri, "yyyyyy", RESUMED_REQUEST_ID); assertThat(currentActiveRequest, sameBeanAs(result)); } @Test public void createNewRecordCopyFromInfraActiveRequestNullIARTest() { InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(null, CURRENT_REQUEST_ID, - startTimeStamp, "VID", requestUri, "xxxxxx"); + startTimeStamp, "VID", requestUri, "xxxxxx", RESUMED_REQUEST_ID); assertThat(currentActiveRequestIARNull, sameBeanAs(result)); } + + @Test + public void setInstanceIdAndNameServiceTest() { + InfraActiveRequests serviceRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setServiceInstanceId(SERVICE_INSTANCE_ID); + expected.setServiceInstanceName(SERVICE_INSTANCE_NAME); + + requestHandler.setInstanceIdAndName(infraActiveRequest, serviceRequest); + assertThat(serviceRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameRequestScopeNotValidTest() { + InfraActiveRequests originalServiceRequest = new InfraActiveRequests(); + originalServiceRequest.setRequestScope("test"); + InfraActiveRequests serviceRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + + requestHandler.setInstanceIdAndName(originalServiceRequest, serviceRequest); + assertThat(serviceRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameVnfTest() { + InfraActiveRequests vnfRequestOriginal = new InfraActiveRequests(); + vnfRequestOriginal.setRequestScope("vnf"); + vnfRequestOriginal.setVnfId(VNF_ID); + vnfRequestOriginal.setVnfName(VNF_NAME); + InfraActiveRequests vnfRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setVnfId(VNF_ID); + expected.setVnfName(VNF_NAME); + + requestHandler.setInstanceIdAndName(vnfRequestOriginal, vnfRequest); + assertThat(vnfRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameVfModuleTest() { + InfraActiveRequests vfModuleRequestOriginal = new InfraActiveRequests(); + vfModuleRequestOriginal.setRequestScope("vfModule"); + vfModuleRequestOriginal.setVfModuleId(VFMODULE_ID); + vfModuleRequestOriginal.setVfModuleName(VFMODULE_NAME); + InfraActiveRequests vfModuleRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setVfModuleId(VFMODULE_ID); + expected.setVfModuleName(VFMODULE_NAME); + + requestHandler.setInstanceIdAndName(vfModuleRequestOriginal, vfModuleRequest); + assertThat(vfModuleRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameNetworkTest() { + InfraActiveRequests networkRequestOriginal = new InfraActiveRequests(); + networkRequestOriginal.setRequestScope("network"); + networkRequestOriginal.setNetworkId(NETWORK_ID); + networkRequestOriginal.setNetworkName(NETWORK_NAME); + InfraActiveRequests networkRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setNetworkId(NETWORK_ID); + expected.setNetworkName(NETWORK_NAME); + + requestHandler.setInstanceIdAndName(networkRequestOriginal, networkRequest); + assertThat(networkRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameVolumeGroupTest() { + InfraActiveRequests volumeGroupRequestOriginal = new InfraActiveRequests(); + volumeGroupRequestOriginal.setRequestScope("volumeGroup"); + volumeGroupRequestOriginal.setVolumeGroupId(VOLUME_GROUP_ID); + volumeGroupRequestOriginal.setVolumeGroupName(VOLUME_GROUP_NAME); + InfraActiveRequests volumeGroupRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setVolumeGroupId(VOLUME_GROUP_ID); + expected.setVolumeGroupName(VOLUME_GROUP_NAME); + + requestHandler.setInstanceIdAndName(volumeGroupRequestOriginal, volumeGroupRequest); + assertThat(volumeGroupRequest, sameBeanAs(expected)); + } + + @Test + public void getIsBaseVfModuleTrueTest() throws ApiException { + VfModule vfModule = new VfModule(); + vfModule.setIsBase(true); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId(MODEL_VERSION_ID); + + doReturn(vfModule).when(catDbClient).getVfModuleByModelUUID(MODEL_VERSION_ID); + Boolean expected = true; + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion, + currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleFalseTest() throws ApiException { + VfModule vfModule = new VfModule(); + vfModule.setIsBase(false); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId(MODEL_VERSION_ID); + + doReturn(vfModule).when(catDbClient).getVfModuleByModelUUID(MODEL_VERSION_ID); + Boolean expected = false; + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion, + currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleNullTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId(MODEL_VERSION_ID); + modelInfo.setModelName(MODEL_NAME); + String errorMessage = + "VnfType vnfType and VF Module Model Name modelName with version 7 not found in MSO Catalog DB"; + + doNothing().when(requestHandler).updateStatus(currentActiveRequest, Status.FAILED, errorMessage); + doReturn(null).when(catDbClient).getVfModuleByModelUUID(MODEL_VERSION_ID); + + thrown.expect(VfModuleNotFoundException.class); + thrown.expectMessage(errorMessage); + requestHandler.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion, currentActiveRequest); + } + + @Test + public void getIsBaseVfModuleModelVersionIdNullTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelInvariantId(MODEL_INVARIANT_ID); + modelInfo.setModelVersion(MODEL_VERSION); + modelInfo.setModelName(MODEL_NAME); + Boolean expected = false; + + doReturn(null).when(catDbClient).getVfModuleByModelInvariantUUIDAndModelVersion(MODEL_INVARIANT_ID, + MODEL_VERSION); + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, Action.deleteInstance, vnfType, + sdcServiceModelVersion, currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleModelInfoNotSetTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + Boolean expected = false; + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, Action.deleteInstance, vnfType, + sdcServiceModelVersion, currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleModelVersionNullTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelInvariantId(MODEL_INVARIANT_ID); + modelInfo.setModelName(MODEL_NAME); + Boolean expected = false; + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, Action.deleteInstance, vnfType, + sdcServiceModelVersion, currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleModelVersionNullUpdateTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelInvariantId(MODEL_INVARIANT_ID); + modelInfo.setModelName(MODEL_NAME); + String errorMessage = "VnfType vnfType and VF Module Model Name modelName not found in MSO Catalog DB"; + + doNothing().when(requestHandler).updateStatus(currentActiveRequest, Status.FAILED, errorMessage); + + thrown.expect(VfModuleNotFoundException.class); + thrown.expectMessage(errorMessage); + requestHandler.getIsBaseVfModule(modelInfo, Action.updateInstance, vnfType, null, currentActiveRequest); + } + + @Test + public void getIsBaseVfModulesdcModelVersionEmptyTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelInvariantId(MODEL_INVARIANT_ID); + modelInfo.setModelName(MODEL_NAME); + String errorMessage = "VnfType vnfType and VF Module Model Name modelName not found in MSO Catalog DB"; + + doNothing().when(requestHandler).updateStatus(currentActiveRequest, Status.FAILED, errorMessage); + + thrown.expect(VfModuleNotFoundException.class); + thrown.expectMessage(errorMessage); + requestHandler.getIsBaseVfModule(modelInfo, Action.updateInstance, vnfType, "", currentActiveRequest); + } + + @Test + public void getModelTypeApplyUpdatedConfigTest() { + ModelType modelTypeExpected = ModelType.vnf; + + ModelType modelTypeResult = requestHandler.getModelType(Action.applyUpdatedConfig, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeInPlaceSoftwareUpdateTest() { + ModelType modelTypeExpected = ModelType.vnf; + + ModelType modelTypeResult = requestHandler.getModelType(Action.inPlaceSoftwareUpdate, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeAddMembersTest() { + ModelType modelTypeExpected = ModelType.instanceGroup; + + ModelType modelTypeResult = requestHandler.getModelType(Action.addMembers, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeRemoveMembersTest() { + ModelType modelTypeExpected = ModelType.instanceGroup; + + ModelType modelTypeResult = requestHandler.getModelType(Action.removeMembers, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeTest() { + ModelType modelTypeExpected = ModelType.service; + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelType(ModelType.service); + + ModelType modelTypeResult = requestHandler.getModelType(Action.createInstance, modelInfo); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void updateRequestorIdInRequestBodyTest() throws IOException { + String newRequestorId = "yyyyyy"; + String expected = getRequestBody("/RequestBodyNewRequestorId.json"); + String result = requestHandler.updateRequestorIdInRequestBody(infraActiveRequest, newRequestorId); + assertEquals(expected, result); + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java index 92490a66b8..398966b0b3 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java @@ -30,6 +30,7 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.junit.Assert.assertEquals; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; @@ -53,9 +54,11 @@ import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.ModelInfo; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.springframework.web.client.HttpClientErrorException; import com.fasterxml.jackson.databind.ObjectMapper; +import org.onap.so.serviceinstancebeans.ModelType; @RunWith(MockitoJUnitRunner.class) public class ResumeOrchestrationRequestTest { @@ -81,8 +84,20 @@ public class ResumeOrchestrationRequestTest { private static final String CURRENT_REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4"; private static final String REQUEST_ID = "00032ab7-na18-42e5-965d-8ea592502019"; private static final String SERVICE_INSTANCE_ID = "00032ab7-na18-42e5-965d-8ea592502018"; + private static final String VNF_ID = "00032ab7-na18-42e5-965d-8ea592502017"; + private static final String VFMODULE_ID = "00032ab7-na18-42e5-965d-8ea592502016"; + private static final String NETWORK_ID = "00032ab7-na18-42e5-965d-8ea592502015"; + private static final String VOLUME_GROUP_ID = "00032ab7-na18-42e5-965d-8ea592502014"; private static final String SERVICE_INSTANCE_NAME = "serviceInstanceName"; - private static final String REQUEST_SCOPE = "service"; + private static final String VNF_NAME = "vnfName"; + private static final String VFMODULE_NAME = "vfModuleName"; + private static final String NETWORK_NAME = "networkName"; + private static final String VOLUME_GROUP_NAME = "volumeGroupName"; + private static final String SERVICE = "service"; + private static final String VNF = "vnf"; + private static final String VFMODULE = "vfModule"; + private static final String NETWORK = "network"; + private static final String VOLUME_GROUP = "volumeGroup"; private final Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); private final Action action = Action.createInstance; private final Boolean aLaCarte = false; @@ -91,15 +106,18 @@ public class ResumeOrchestrationRequestTest { "http:localhost:6746/onap/so/infra/orchestrationRequests/v7/00032ab7-na18-42e5-965d-8ea592502019/resume"; private final RecipeLookupResult lookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 80); private RequestClientParameter requestClientParameter = null; + private RequestClientParameter requestClientParameterVfModule = null; private ObjectMapper mapper = new ObjectMapper(); private InfraActiveRequests infraActiveRequest = new InfraActiveRequests(); private InfraActiveRequests currentActiveRequest = new InfraActiveRequests(); + private InfraActiveRequests infraActiveRequestVfModule = new InfraActiveRequests(); private ServiceInstancesRequest sir = new ServiceInstancesRequest(); private ServiceInstancesRequest sirNullALaCarte = new ServiceInstancesRequest(); private String requestBody = null; private String requestBodyNullALaCarte = null; private ContainerRequestContext requestContext = null; private HashMap<String, String> instanceIdMap = new HashMap<>(); + ModelInfo modelInfo; @Before @@ -110,13 +128,16 @@ public class ResumeOrchestrationRequestTest { // Setup InfraActiveRequests setInfraActiveRequest(); setCurrentActiveRequest(); + setInfraActiveRequestVfModule(); requestBody = infraActiveRequest.getRequestBody(); sir = mapper.readValue(requestBody, ServiceInstancesRequest.class); requestBodyNullALaCarte = getRequestBody("/ALaCarteNull.json"); - sirNullALaCarte = sir = mapper.readValue(requestBodyNullALaCarte, ServiceInstancesRequest.class); + sirNullALaCarte = mapper.readValue(requestBodyNullALaCarte, ServiceInstancesRequest.class); setRequestClientParameter(); + setRequestClientParameterVfModule(); instanceIdMap.put("serviceInstanceId", SERVICE_INSTANCE_ID); + modelInfo = sir.getRequestDetails().getModelInfo(); } public String getRequestBody(String request) throws IOException { @@ -128,12 +149,21 @@ public class ResumeOrchestrationRequestTest { infraActiveRequest.setTenantId("tenant-id"); infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); infraActiveRequest.setAicCloudRegion("cloudRegion"); - infraActiveRequest.setRequestScope(REQUEST_SCOPE); + infraActiveRequest.setRequestScope(SERVICE); infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); infraActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); infraActiveRequest.setRequestAction(Action.createInstance.toString()); infraActiveRequest.setServiceType("serviceType"); + infraActiveRequest.setVnfId(VNF_ID); + infraActiveRequest.setVfModuleId(VFMODULE_ID); + infraActiveRequest.setNetworkId(NETWORK_ID); + infraActiveRequest.setVolumeGroupId(VOLUME_GROUP_ID); + infraActiveRequest.setVnfName(VNF_NAME); + infraActiveRequest.setVfModuleName(VFMODULE_NAME); + infraActiveRequest.setNetworkName(NETWORK_NAME); + infraActiveRequest.setVolumeGroupName(VOLUME_GROUP_NAME); + infraActiveRequest.setRequestId(REQUEST_ID); } private void setCurrentActiveRequest() throws IOException { @@ -143,7 +173,7 @@ public class ResumeOrchestrationRequestTest { currentActiveRequest.setTenantId("tenant-id"); currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); currentActiveRequest.setAicCloudRegion("cloudRegion"); - currentActiveRequest.setRequestScope(REQUEST_SCOPE); + currentActiveRequest.setRequestScope(SERVICE); currentActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); currentActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); @@ -154,13 +184,33 @@ public class ResumeOrchestrationRequestTest { currentActiveRequest.setProgress(new Long(5)); } + private void setInfraActiveRequestVfModule() throws IOException { + infraActiveRequestVfModule.setRequestBody(getRequestBody("/RequestBody.json")); + infraActiveRequestVfModule.setRequestScope(VFMODULE); + infraActiveRequestVfModule.setRequestStatus(Status.IN_PROGRESS.toString()); + infraActiveRequestVfModule.setRequestAction(Action.createInstance.toString()); + infraActiveRequestVfModule.setVnfId(VNF_ID); + infraActiveRequestVfModule.setVfModuleId(VFMODULE_ID); + infraActiveRequestVfModule.setVnfName(VNF_NAME); + infraActiveRequestVfModule.setVfModuleName(VFMODULE_NAME); + } + private void setRequestClientParameter() { - requestClientParameter = new RequestClientParameter.Builder().setRequestId(CURRENT_REQUEST_ID) - .setRecipeTimeout(80).setRequestAction(Action.createInstance.toString()) - .setServiceInstanceId(SERVICE_INSTANCE_ID).setPnfCorrelationId("pnfCorrelationId").setVnfId(null) - .setVfModuleId(null).setVolumeGroupId(null).setNetworkId(null).setServiceType("serviceType") - .setVnfType(null).setNetworkType(null).setRequestDetails(requestBody).setApiVersion(version) - .setALaCarte(aLaCarte).setRequestUri(requestUri).setInstanceGroupId(null).build(); + requestClientParameter = + new RequestClientParameter.Builder().setRequestId(CURRENT_REQUEST_ID).setRecipeTimeout(80) + .setRequestAction(Action.createInstance.toString()).setServiceInstanceId(SERVICE_INSTANCE_ID) + .setPnfCorrelationId("pnfCorrelationId").setVnfId(VNF_ID).setVfModuleId(VFMODULE_ID) + .setVolumeGroupId(VOLUME_GROUP_ID).setNetworkId(NETWORK_ID).setServiceType("serviceType") + .setVnfType(null).setNetworkType(null).setRequestDetails(requestBody).setApiVersion(version) + .setALaCarte(aLaCarte).setRequestUri(requestUri).setInstanceGroupId(null).build(); + } + + private void setRequestClientParameterVfModule() { + requestClientParameterVfModule = + new RequestClientParameter.Builder().setRequestId(CURRENT_REQUEST_ID).setRecipeTimeout(80) + .setRequestAction(Action.createInstance.toString()).setPnfCorrelationId("pnfCorrelationId") + .setVnfId(VNF_ID).setVfModuleId(VFMODULE_ID).setRequestDetails(requestBody) + .setApiVersion(version).setALaCarte(aLaCarte).setRequestUri(requestUri).build(); } @Test @@ -169,7 +219,7 @@ public class ResumeOrchestrationRequestTest { when(requestDbClient.getInfraActiveRequestbyRequestId(REQUEST_ID)).thenReturn(infraActiveRequest); doReturn(currentActiveRequest).when(requestHandler).createNewRecordCopyFromInfraActiveRequest( any(InfraActiveRequests.class), nullable(String.class), any(Timestamp.class), nullable(String.class), - nullable(String.class), nullable(String.class)); + nullable(String.class), nullable(String.class), anyString()); doReturn(response).when(resumeReq).resumeRequest(any(InfraActiveRequests.class), any(InfraActiveRequests.class), anyString(), nullable(String.class)); @@ -201,16 +251,20 @@ public class ResumeOrchestrationRequestTest { @Test public void resumeRequestTest() throws ApiException, IOException { Response response = null; + doReturn(instanceIdMap).when(resumeReq).setInstanceIdMap(infraActiveRequest, ModelType.service.toString()); + doReturn(SERVICE_INSTANCE_NAME).when(resumeReq).getInstanceName(infraActiveRequest, + ModelType.service.toString(), currentActiveRequest); when(requestHandler.convertJsonToServiceInstanceRequest(anyString(), any(Actions.class), anyString(), anyString())).thenReturn(sir); when(serviceInstances.getPnfCorrelationId(any(ServiceInstancesRequest.class))).thenReturn("pnfCorrelationId"); - doReturn(lookupResult).when(resumeReq).serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); + doReturn(lookupResult).when(serviceInstances).getServiceInstanceOrchestrationURI(sir, action, aLaCarte, + currentActiveRequest); doReturn(requestClientParameter).when(resumeReq).setRequestClientParameter(lookupResult, version, infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); doNothing().when(resumeReq).requestDbSave(currentActiveRequest); when(requestHandler.postBPELRequest(any(InfraActiveRequests.class), any(RequestClientParameter.class), anyString(), anyString())).thenReturn(response); - doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, + doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME, action); resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version, @@ -220,15 +274,8 @@ public class ResumeOrchestrationRequestTest { } @Test - public void serviceRecipeLookupTest() throws ApiException, IOException { - when(serviceInstances.getServiceURI(any(ServiceInstancesRequest.class), any(Action.class), anyBoolean())) - .thenReturn(lookupResult); - RecipeLookupResult result = resumeReq.serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); - assertThat(result, sameBeanAs(lookupResult)); - } - - @Test public void setRequestClientParameterTest() throws ApiException, IOException { + doReturn(ModelType.service).when(requestHandler).getModelType(action, modelInfo); when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(), any(Action.class))).thenReturn(requestBody); RequestClientParameter result = resumeReq.setRequestClientParameter(lookupResult, version, infraActiveRequest, @@ -237,6 +284,16 @@ public class ResumeOrchestrationRequestTest { } @Test + public void setRequestClientParameterVfModuleTest() throws ApiException, IOException { + when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(), + any(Action.class))).thenReturn(requestBody); + doReturn(ModelType.vfModule).when(requestHandler).getModelType(action, modelInfo); + RequestClientParameter result = resumeReq.setRequestClientParameter(lookupResult, version, + infraActiveRequestVfModule, currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); + assertThat(requestClientParameterVfModule, sameBeanAs(result)); + } + + @Test public void requestDbSaveTest() throws RequestDbFailureException { doNothing().when(requestDbClient).save(currentActiveRequest); resumeReq.requestDbSave(currentActiveRequest); @@ -246,17 +303,22 @@ public class ResumeOrchestrationRequestTest { @Test public void resumeRequestTestALaCarteNull() throws ApiException, IOException { Response response = null; - + doReturn(instanceIdMap).when(resumeReq).setInstanceIdMap(infraActiveRequest, ModelType.service.toString()); + doReturn(SERVICE_INSTANCE_NAME).when(resumeReq).getInstanceName(infraActiveRequest, + ModelType.service.toString(), currentActiveRequest); when(requestHandler.convertJsonToServiceInstanceRequest(anyString(), any(Actions.class), anyString(), anyString())).thenReturn(sirNullALaCarte); when(serviceInstances.getPnfCorrelationId(any(ServiceInstancesRequest.class))).thenReturn("pnfCorrelationId"); - doReturn(lookupResult).when(resumeReq).serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); + doReturn(false).when(msoRequest).getAlacarteFlag(sirNullALaCarte); + doReturn(lookupResult).when(serviceInstances).getServiceInstanceOrchestrationURI(sirNullALaCarte, action, false, + currentActiveRequest); doReturn(requestClientParameter).when(resumeReq).setRequestClientParameter(lookupResult, version, - infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); + infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sirNullALaCarte); + doReturn(false).when(resumeReq).setALaCarteFlagIfNull(SERVICE, action); doNothing().when(resumeReq).requestDbSave(currentActiveRequest); when(requestHandler.postBPELRequest(any(InfraActiveRequests.class), any(RequestClientParameter.class), anyString(), anyString())).thenReturn(response); - doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, + doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME, action); resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version, @@ -266,18 +328,8 @@ public class ResumeOrchestrationRequestTest { } @Test - public void serviceRecipeLookupErrorTest() throws IOException, ApiException { - when(serviceInstances.getServiceURI(sir, action, aLaCarte)) - .thenThrow(new IOException("Error occurred on recipe lookup")); - doNothing().when(requestHandler).updateStatus(any(InfraActiveRequests.class), any(Status.class), anyString()); - - thrown.expect(ValidateException.class); - thrown.expectMessage("Error occurred on recipe lookup"); - resumeReq.serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); - } - - @Test public void setRequestClientParameterErrorTest() throws ApiException, IOException { + doReturn(ModelType.service).when(requestHandler).getModelType(action, modelInfo); when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(), any(Action.class))).thenThrow(new IOException("IOException")); @@ -290,39 +342,141 @@ public class ResumeOrchestrationRequestTest { @Test public void checkForInProgressRequest() throws ApiException { doReturn(infraActiveRequest).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, - REQUEST_SCOPE, currentActiveRequest); + SERVICE, currentActiveRequest); doReturn(true).when(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); doThrow(DuplicateRequestException.class).when(requestHandler).buildErrorOnDuplicateRecord(currentActiveRequest, - action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, infraActiveRequest); + action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, infraActiveRequest); thrown.expect(DuplicateRequestException.class); - resumeReq.checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, - SERVICE_INSTANCE_NAME, action); + resumeReq.checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME, + action); } @Test public void checkForInProgressRequestNoInProgressRequests() throws ApiException { - doReturn(null).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, + doReturn(null).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, currentActiveRequest); - resumeReq.checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, - SERVICE_INSTANCE_NAME, action); - verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, + resumeReq.checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME, + action); + verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, currentActiveRequest); } @Test public void checkForInProgressRequestCamundaHistoryCheckReturnsNoInProgress() throws ApiException { doReturn(infraActiveRequest).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, - REQUEST_SCOPE, currentActiveRequest); + SERVICE, currentActiveRequest); doReturn(false).when(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); - resumeReq.checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, - SERVICE_INSTANCE_NAME, action); - verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, + resumeReq.checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME, + action); + verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, currentActiveRequest); verify(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); } + @Test + public void setInstanceIdMapServiceTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("serviceInstanceId", SERVICE_INSTANCE_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, SERVICE); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapRequestScopeNotValidTest() { + HashMap<String, String> expected = new HashMap<>(); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, "test"); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapVnfTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("vnfInstanceId", VNF_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, VNF); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapVfModuleTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("vfModuleInstanceId", VFMODULE_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, VFMODULE); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapNetworkTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("networkInstanceId", NETWORK_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, NETWORK); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapVolumeGroupTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("volumeGroupInstanceId", VOLUME_GROUP_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, VOLUME_GROUP); + assertEquals(result, expected); + } + + @Test + public void setInstanceNameServiceTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, SERVICE, currentActiveRequest); + assertEquals(result, SERVICE_INSTANCE_NAME); + } + + @Test + public void setInstanceNameRequestScopeNotValidTest() throws ValidateException, RequestDbFailureException { + thrown.expect(ValidateException.class); + thrown.expectMessage( + "requestScope: \"test\" from request: 00032ab7-na18-42e5-965d-8ea592502019 does not match a ModelType enum."); + + resumeReq.getInstanceName(infraActiveRequest, "test", currentActiveRequest); + } + + @Test + public void setInstanceNameVnfTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, VNF, currentActiveRequest); + assertEquals(result, VNF_NAME); + } + @Test + public void setInstanceNameVfModuleTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, VFMODULE, currentActiveRequest); + assertEquals(result, VFMODULE_NAME); + } + + @Test + public void setInstanceNameNetworkTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, NETWORK, currentActiveRequest); + assertEquals(result, NETWORK_NAME); + } + + @Test + public void setInstanceNameVolumeGroupTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, VOLUME_GROUP, currentActiveRequest); + assertEquals(result, VOLUME_GROUP_NAME); + } + + @Test + public void setALaCarteFlagIfNullTest() { + Boolean aLaCarteFlag = resumeReq.setALaCarteFlagIfNull(SERVICE, action); + assertEquals(aLaCarteFlag, false); + } + + @Test + public void setALaCarteFlagIfNullVnfTest() { + Boolean aLaCarteFlag = resumeReq.setALaCarteFlagIfNull(VNF, action); + assertEquals(aLaCarteFlag, true); + } + + @Test + public void setALaCarteFlagIfNullRecreateTest() { + Boolean aLaCarteFlag = resumeReq.setALaCarteFlagIfNull(VNF, Action.recreateInstance); + assertEquals(aLaCarteFlag, false); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java index 48abeacbc5..0beab1bd13 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java @@ -87,6 +87,66 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { .withBody(getWiremockResponseForCatalogdb("WorkflowActivitySpecSequence_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching("/workflowActivitySpecSequence/1/activitySpec")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("ActivitySpecSequence1_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/workflowActivitySpecSequence/2/activitySpec")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("ActivitySpecSequence2_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/workflowActivitySpecSequence/3/activitySpec")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("ActivitySpecSequence3_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpec/1/activitySpecUserParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("ActivitySpecUserParameters1_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpec/2/activitySpecUserParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("ActivitySpecUserParameters2_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpec/3/activitySpecUserParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("ActivitySpecUserParameters3_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpecUserParameters/1/userParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UserParameters1_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpecUserParameters/2/userParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UserParameters2_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpecUserParameters/3/userParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UserParameters3_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpecUserParameters/4/userParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UserParameters4_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpecUserParameters/5/userParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UserParameters5_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/activitySpecUserParameters/6/userParameters")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UserParameters6_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath)) .queryParam("vnfModelVersionId", "b5fa707a-f55a-11e7-a796-005056856d52"); @@ -237,6 +297,17 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { workflow.setWorkflowActivitySpecSequence(workflowActivitySpecSequences); workflows.add(workflow); + Workflow workflowNative = new Workflow(); + workflowNative.setArtifactUUID("da6478e4-ea33-3346-ac12-ab121284a333"); + workflowNative.setArtifactName("VnfInPlaceUpdate.bpmn"); + workflowNative.setVersion(1.0); + workflowNative.setDescription("native workflow"); + workflowNative.setName("VnfInPlaceUpdate"); + workflowNative.setOperationName("inPlaceSoftwareUpdate"); + workflowNative.setSource("native"); + workflowNative.setResourceTarget("vnf"); + workflows.add(workflowNative); + WorkflowSpecifications workflowSpecifications = workflowSpecificationsHandler.mapWorkflowsToWorkflowSpecifications(workflows); ObjectMapper mapper = new ObjectMapper(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java index 54da0baa92..93a19a9531 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java @@ -25,15 +25,38 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.exceptions.ValidationException; +import org.onap.so.serviceinstancebeans.RelatedInstanceList; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import com.fasterxml.jackson.databind.ObjectMapper; public class RelatedInstancesValidationTest extends BaseTest { + RelatedInstancesValidation validation = new RelatedInstancesValidation(); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + public ValidationInformation setupValidationInformation(String path) throws IOException { + String jsonInput = new String(Files.readAllBytes(Paths.get(path))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(jsonInput, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, null, Action.createInstance, 7, false, + sir.getRequestDetails().getRequestParameters()); + + info.setRequestScope("service"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + sir.getRequestDetails().getModelInfo().setModelCustomizationName("name"); + + info.setRequestInfo(sir.getRequestDetails().getRequestInfo()); + return info; + } + @Test public void testCreateVnfNetworkInstanceGroup() throws IOException, ValidationException { String requestJson = new String(Files.readAllBytes( @@ -50,4 +73,64 @@ public class RelatedInstancesValidationTest extends BaseTest { assertEquals(info.getVnfType(), "Test/name"); } + + @Test + public void testCreateSIVpnBonding() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/RelatedInstances/ServiceInstanceVpnBondingService.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 7, false, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("service"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + sir.getRequestDetails().getModelInfo().setModelCustomizationName("name"); + RelatedInstancesValidation validation = new RelatedInstancesValidation(); + validation.validate(info); + RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList(); + + assertEquals(info.getRequestScope(), "service"); + assertEquals(instanceList[0].getRelatedInstance().getModelInfo().getModelType().toString(), "vpnBinding"); + assertEquals(instanceList[1].getRelatedInstance().getModelInfo().getModelType().toString(), "network"); + } + + @Test + public void validateModelTypeExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid modelType in relatedInstance is specified"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/VpnBondingValidation/NoModelType.json")); + } + + @Test + public void validateInstanceNameVpnBindingExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid instanceName in relatedInstance for vpnBinding modelType is specified"); + validation.validate(setupValidationInformation( + "src/test/resources/Validation/VpnBondingValidation/NoInstanceNameVpnBinding.json")); + } + + @Test + public void validateInstanceNameNetworkExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid instanceName in relatedInstance for network modelType is specified"); + validation.validate(setupValidationInformation( + "src/test/resources/Validation/VpnBondingValidation/NoInstanceNameNetwork.json")); + } + + @Test + public void validateInstanceIdExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid instanceId in relatedInstance is specified"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/VpnBondingValidation/NoInstanceId.json")); + } + + @Test + public void validatemodelInvariantIdExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid modelInvariantId in relatedInstance is specified"); + validation.validate(setupValidationInformation( + "src/test/resources/Validation/VpnBondingValidation/NoModelInvariantId.json")); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/RelatedInstances/ServiceInstanceVpnBondingService.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/RelatedInstances/ServiceInstanceVpnBondingService.json new file mode 100644 index 0000000000..573b7a3ebb --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/RelatedInstances/ServiceInstanceVpnBondingService.json @@ -0,0 +1,57 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "vpn-name", + "modelInfo": { + "modelType": "vpnBinding" + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "network-name", + "modelInfo": { + "modelType": "network" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json index 5cd31427a0..d6406338a0 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json @@ -1,5 +1,11 @@ { "requestDetails":{ + "modelInfo":{ + "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7965", + "modelVersion": "1.0", + "modelType":"service", + "modelName":"serviceModel" + }, "requestInfo":{ "source":"VID", "requestorId":"xxxxxx", diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBodyNewRequestorId.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBodyNewRequestorId.json new file mode 100644 index 0000000000..740d4e2ec2 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBodyNewRequestorId.json @@ -0,0 +1,19 @@ +{ + "requestDetails":{ + "modelInfo":{ + "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7965", + "modelVersion": "1.0", + "modelType":"service", + "modelName":"serviceModel" + }, + "requestInfo":{ + "source":"VID", + "requestorId":"yyyyyy", + "instanceName":"testService", + "productFamilyId":"test" + }, + "requestParameters":{ + "aLaCarte":"false" + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceVpnBondingService.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceVpnBondingService.json new file mode 100644 index 0000000000..573b7a3ebb --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceVpnBondingService.json @@ -0,0 +1,57 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "vpn-name", + "modelInfo": { + "modelType": "vpnBinding" + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "network-name", + "modelInfo": { + "modelType": "network" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceId.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceId.json new file mode 100644 index 0000000000..97e480c8d8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceId.json @@ -0,0 +1,56 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceName": "vpn-name", + "modelInfo": { + "modelType": "vpnBinding" + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "network-name", + "modelInfo": { + "modelType": "network" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameNetwork.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameNetwork.json new file mode 100644 index 0000000000..f7ba4761b6 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameNetwork.json @@ -0,0 +1,56 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "vpn-name", + "modelInfo": { + "modelType": "vpnBinding" + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "modelInfo": { + "modelType": "network" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameVpnBinding.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameVpnBinding.json new file mode 100644 index 0000000000..ac570b3830 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameVpnBinding.json @@ -0,0 +1,56 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "modelInfo": { + "modelType": "vpnBinding" + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "network-name", + "modelInfo": { + "modelType": "network" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelInvariantId.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelInvariantId.json new file mode 100644 index 0000000000..ca02c5371a --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelInvariantId.json @@ -0,0 +1,57 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "vpn-name", + "modelInfo": { + "modelType": "vnf" + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "network-name", + "modelInfo": { + "modelType": "service" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelType.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelType.json new file mode 100644 index 0000000000..1d46ce2ccd --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelType.json @@ -0,0 +1,56 @@ +{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21", + "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb", + "modelName": "Test", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "cloudOwner": "test-mgr", + "lcpCloudRegionId": "abc1", + "tenantId": "19123c2924c648eb8e42a3c1f14b7682" + }, + "owningEntity": { + "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489", + "owningEntityName": "PACKET CORE" + }, + "project": { + "projectName": "projectName" + }, + "subscriberInfo": { + "globalSubscriberId": "TEST_123", + "subscriberName": "TEST_123" + }, + "requestInfo": { + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "xxxxxx", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "vpn-name", + "modelInfo": { + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceName": "network-name", + "modelInfo": { + "modelType": "network" + } + } + } + ], + "requestParameters": { + "subscriptionServiceType": "dev-service-type", + "aLaCarte": false + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence1_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence1_Response.json new file mode 100644 index 0000000000..37e32631fb --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence1_Response.json @@ -0,0 +1,20 @@ +{ + "name": "VNFQuiesceTrafficActivity", + "description": "Activity to QuiesceTraffic on VNF", + "version": null, + "created": null, + "activitySpecActivitySpecCategories": null, + "activitySpecActivitySpecParameters": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpec/1" + }, + "activitySpec": { + "href": "http://localhost:8090/activitySpec/1" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpec/1/activitySpecUserParameters" + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence2_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence2_Response.json new file mode 100644 index 0000000000..ee2a02ba33 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence2_Response.json @@ -0,0 +1,20 @@ +{ + "name": "VNFHealthCheckActivity", + "description": "Activity to HealthCheck VNF", + "version": null, + "created": null, + "activitySpecActivitySpecCategories": null, + "activitySpecActivitySpecParameters": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpec/2" + }, + "activitySpec": { + "href": "http://localhost:8090/activitySpec/2" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpec/2/activitySpecUserParameters" + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence3_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence3_Response.json new file mode 100644 index 0000000000..69390eea6b --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecSequence3_Response.json @@ -0,0 +1,20 @@ +{ + "name": "FlowCompleteActivity", + "description": "Activity to Complete the BPMN Flow", + "version": null, + "created": null, + "activitySpecActivitySpecCategories": null, + "activitySpecActivitySpecParameters": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpec/3" + }, + "activitySpec": { + "href": "http://localhost:8090/activitySpec/3" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpec/3/activitySpecUserParameters" + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters1_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters1_Response.json new file mode 100644 index 0000000000..e88691b4d8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters1_Response.json @@ -0,0 +1,103 @@ +{ + "_embedded": { + "activitySpecUserParameters": [ + { + "activitySpecId": 1, + "userParametersId": 1, + "activitySpec": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/1" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/1" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/1/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 2, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/2" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/2" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/2/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 3, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/3" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/3" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/3/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 4, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/4" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/4" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/4/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 5, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/5" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/5" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/5/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 6, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/6" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/6" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/6/userParameters" + } + } + } + ] + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters2_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters2_Response.json new file mode 100644 index 0000000000..e88691b4d8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters2_Response.json @@ -0,0 +1,103 @@ +{ + "_embedded": { + "activitySpecUserParameters": [ + { + "activitySpecId": 1, + "userParametersId": 1, + "activitySpec": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/1" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/1" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/1/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 2, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/2" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/2" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/2/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 3, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/3" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/3" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/3/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 4, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/4" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/4" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/4/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 5, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/5" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/5" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/5/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 6, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/6" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/6" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/6/userParameters" + } + } + } + ] + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters3_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters3_Response.json new file mode 100644 index 0000000000..e88691b4d8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/ActivitySpecUserParameters3_Response.json @@ -0,0 +1,103 @@ +{ + "_embedded": { + "activitySpecUserParameters": [ + { + "activitySpecId": 1, + "userParametersId": 1, + "activitySpec": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/1" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/1" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/1/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 2, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/2" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/2" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/2/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 3, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/3" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/3" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/3/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 4, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/4" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/4" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/4/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 5, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/5" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/5" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/5/userParameters" + } + } + }, + { + "activitySpecId": 1, + "userParametersId": 6, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/activitySpecUserParameters/6" + }, + "activitySpecUserParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/6" + }, + "userParameters": { + "href": "http://localhost:8090/activitySpecUserParameters/6/userParameters" + } + } + } + ] + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters1_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters1_Response.json new file mode 100644 index 0000000000..017add4cd5 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters1_Response.json @@ -0,0 +1,13 @@ +{ + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters2_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters2_Response.json new file mode 100644 index 0000000000..655d659c16 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters2_Response.json @@ -0,0 +1,13 @@ +{ + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters3_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters3_Response.json new file mode 100644 index 0000000000..13e02e7dd6 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters3_Response.json @@ -0,0 +1,13 @@ +{ + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters4_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters4_Response.json new file mode 100644 index 0000000000..e30ec0da88 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters4_Response.json @@ -0,0 +1,13 @@ +{ + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters5_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters5_Response.json new file mode 100644 index 0000000000..98b18522da --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters5_Response.json @@ -0,0 +1,13 @@ +{ + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters6_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters6_Response.json new file mode 100644 index 0000000000..4d8d03b6a7 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/UserParameters6_Response.json @@ -0,0 +1,13 @@ +{ + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowActivitySpecSequence_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowActivitySpecSequence_Response.json index 3192865b52..3df17380d6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowActivitySpecSequence_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowActivitySpecSequence_Response.json @@ -1,432 +1,54 @@ { "_embedded": { - - "workflowActivitySpecSequence": [ - { - "activitySpecId": null, - "workflowId": null, - "activitySpec": { - "name": "VNFQuiesceTrafficActivity", - "description": "Activity to QuiesceTraffic on VNF", - "version": null, - "created": null, - "workflowActivitySpecSequence": null, - "activitySpecActivitySpecCategories": null, - "activitySpecUserParameters": [ - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "operations_timeout", - "payloadLocation": "userParams", - "label": "Operations Timeout", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "existing_software_version", - "payloadLocation": "userParams", - "label": "Existing Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "cloudOwner", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Owner", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "tenantId", - "payloadLocation": "cloudConfiguration", - "label": "Tenant/Project ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 36, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "new_software_version", - "payloadLocation": "userParams", - "label": "New Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "lcpCloudRegionId", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Region ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - } - ], - "activitySpecActivitySpecParameters": null, - "id": null - }, - "workflow": null, - "id": null, - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } - - }, - { - "activitySpecId": null, - "workflowId": null, - "activitySpec": { - "name": "VNFHealthCheckActivity", - "description": "Activity to HealthCheck VNF", - "version": null, - "created": null, - "workflowActivitySpecSequence": null, - "activitySpecActivitySpecCategories": null, - "activitySpecUserParameters": [ - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "operations_timeout", - "payloadLocation": "userParams", - "label": "Operations Timeout", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "existing_software_version", - "payloadLocation": "userParams", - "label": "Existing Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "cloudOwner", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Owner", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "tenantId", - "payloadLocation": "cloudConfiguration", - "label": "Tenant/Project ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 36, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "new_software_version", - "payloadLocation": "userParams", - "label": "New Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "lcpCloudRegionId", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Region ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - } - ], - "activitySpecActivitySpecParameters": null, - "id": null - }, - "workflow": null, - "id": null, - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } - }, - { - "activitySpecId": null, - "workflowId": null, - "activitySpec": { - "name": "FlowCompleteActivity", - "description": "Activity to Complete the BPMN Flow", - "version": null, - "created": null, - "workflowActivitySpecSequence": null, - "activitySpecActivitySpecCategories": null, - "activitySpecUserParameters": [ - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "operations_timeout", - "payloadLocation": "userParams", - "label": "Operations Timeout", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "existing_software_version", - "payloadLocation": "userParams", - "label": "Existing Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "cloudOwner", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Owner", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "tenantId", - "payloadLocation": "cloudConfiguration", - "label": "Tenant/Project ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 36, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "new_software_version", - "payloadLocation": "userParams", - "label": "New Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "lcpCloudRegionId", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Region ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - } - ], - "activitySpecActivitySpecParameters": null, - "id": null - }, - "workflow": null, - "id": null, - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } - } - ] - -} + "workflowActivitySpecSequence": [ + { + "activitySpecId": 1, + "workflowId": 1, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflowActivitySpecSequence//1/workflowActivitySpecSequence" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflowActivitySpecSequence/1/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflowActivitySpecSequence/1/activitySpec" + } + } + }, + { + "activitySpecId": 2, + "workflowId": 1, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflowActivitySpecSequence/2/workflowActivitySpecSequence" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflowActivitySpecSequence/2/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflowActivitySpecSequence/2/activitySpec" + } + } + }, + { + "activitySpecId": 3, + "workflowId": 1, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflowActivitySpecSequence/3" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflowActivitySpecSequence/3/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflowActivitySpecSequence/3/activitySpec" + } + } + } + ] + } }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecifications.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecifications.json index 5556c602be..59bc12d92d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecifications.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecifications.json @@ -108,6 +108,23 @@ } ] } + }, + { + "workflowSpecification": { + + "artifactInfo": { + "artifactType": "workflow", + "artifactUuid": "da6478e4-ea33-3346-ac12-ab121284a333", + "artifactName": "VnfInPlaceUpdate.bpmn", + "artifactVersion": "1.0", + "artifactDescription": "native workflow", + "workflowName": "VnfInPlaceUpdate", + "operationName": "inPlaceSoftwareUpdate", + "workflowSource": "native", + "workflowResourceTarget": "vnf" + }, + "workflowInputParameters": [] + } } ] } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsQuery_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsQuery_Response.json index c12365649e..8919dbbf2c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsQuery_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsQuery_Response.json @@ -1,468 +1,504 @@ { "_embedded": { - "workflows" :[ - { - "artifactUUID": "ab6478e4-ea33-3346-ac12-ab121484a333", - "artifactName": "inPlaceSoftwareUpdate-1_0.bpmn", - "name": "inPlaceSoftwareUpdate", - "operationName": "inPlaceSoftwareUpdate", - "version": 1, - "description": "xyz xyz", - "body": null, - "resourceTarget": "vnf", - "source": "sdc", - "timeoutMinutes": null, - "artifactChecksum": null, - "created": null, - "vnfResourceWorkflow": null, - "workflowActivitySpecSequence": [ - { - "activitySpecId": null, - "workflowId": null, - "activitySpec": { - "name": "VNFQuiesceTrafficActivity", - "description": "Activity to QuiesceTraffic on VNF", - "version": null, - "created": null, - "workflowActivitySpecSequence": null, - "activitySpecActivitySpecCategories": null, - "activitySpecUserParameters": [ - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "operations_timeout", - "payloadLocation": "userParams", - "label": "Operations Timeout", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "existing_software_version", - "payloadLocation": "userParams", - "label": "Existing Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "cloudOwner", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Owner", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "tenantId", - "payloadLocation": "cloudConfiguration", - "label": "Tenant/Project ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 36, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "new_software_version", - "payloadLocation": "userParams", - "label": "New Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "lcpCloudRegionId", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Region ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - } - ], - "activitySpecActivitySpecParameters": null, - "id": null - }, - "workflow": null, - "id": null, - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID[?]vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } - - }, - { - "activitySpecId": null, - "workflowId": null, - "activitySpec": { - "name": "VNFHealthCheckActivity", - "description": "Activity to HealthCheck VNF", - "version": null, - "created": null, - "workflowActivitySpecSequence": null, - "activitySpecActivitySpecCategories": null, - "activitySpecUserParameters": [ - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "operations_timeout", - "payloadLocation": "userParams", - "label": "Operations Timeout", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "existing_software_version", - "payloadLocation": "userParams", - "label": "Existing Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "cloudOwner", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Owner", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "tenantId", - "payloadLocation": "cloudConfiguration", - "label": "Tenant/Project ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 36, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "new_software_version", - "payloadLocation": "userParams", - "label": "New Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "lcpCloudRegionId", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Region ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - } - ], - "activitySpecActivitySpecParameters": null, - "id": null - }, - "workflow": null, - "id": null, - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } - }, - { - "activitySpecId": null, - "workflowId": null, - "activitySpec": { - "name": "FlowCompleteActivity", - "description": "Activity to Complete the BPMN Flow", - "version": null, - "created": null, - "workflowActivitySpecSequence": null, - "activitySpecActivitySpecCategories": null, - "activitySpecUserParameters": [ - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "operations_timeout", - "payloadLocation": "userParams", - "label": "Operations Timeout", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "existing_software_version", - "payloadLocation": "userParams", - "label": "Existing Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "cloudOwner", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Owner", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "tenantId", - "payloadLocation": "cloudConfiguration", - "label": "Tenant/Project ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 36, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "new_software_version", - "payloadLocation": "userParams", - "label": "New Software Version", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 50, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - }, - { - "activitySpecId": null, - "userParametersId": null, - "activitySpec": null, - "userParameters": { - "name": "lcpCloudRegionId", - "payloadLocation": "cloudConfiguration", - "label": "Cloud Region ID", - "type": "text", - "description": null, - "isRequried": true, - "maxLength": 7, - "allowableChars": "someRegEx", - "created": null, - "activitySpecUserParameters": null, - "id": null - }, - "id": null - } - ], - "activitySpecActivitySpecParameters": null, - "id": null - }, - "workflow": null, - "id": null, - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } - } - ], - "id": null, - - "_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/1/workflowActivitySpecSequence" - } - - } - - } -] -}, -"_links": { - "self": { - "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" - }, - "workflowActivitySpecSequence": { - "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" - } - - } + "workflows": [ + { + "artifactUUID": "ab6478e4-ea33-3346-ac12-ab121484a333", + "artifactName": "inPlaceSoftwareUpdate-1_0.bpmn", + "name": "inPlaceSoftwareUpdate", + "operationName": "inPlaceSoftwareUpdate", + "version": 1, + "description": "xyz xyz", + "body": null, + "resourceTarget": "vnf", + "source": "sdc", + "timeoutMinutes": null, + "artifactChecksum": null, + "created": null, + "vnfResourceWorkflow": null, + "workflowActivitySpecSequence": [ + { + "activitySpecId": null, + "workflowId": null, + "activitySpec": { + "name": "VNFQuiesceTrafficActivity", + "description": "Activity to QuiesceTraffic on VNF", + "version": null, + "created": null, + "workflowActivitySpecSequence": null, + "activitySpecActivitySpecCategories": null, + "activitySpecUserParameters": [ + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + } + ], + "activitySpecActivitySpecParameters": null, + "id": null + }, + "workflow": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID[?]vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/activitySpec" + } + } + }, + { + "activitySpecId": null, + "workflowId": null, + "activitySpec": { + "name": "VNFHealthCheckActivity", + "description": "Activity to HealthCheck VNF", + "version": null, + "created": null, + "workflowActivitySpecSequence": null, + "activitySpecActivitySpecCategories": null, + "activitySpecUserParameters": [ + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + } + ], + "activitySpecActivitySpecParameters": null, + "id": null + }, + "workflow": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/activitySpec" + } + } + }, + { + "activitySpecId": null, + "workflowId": null, + "activitySpec": { + "name": "FlowCompleteActivity", + "description": "Activity to Complete the BPMN Flow", + "version": null, + "created": null, + "workflowActivitySpecSequence": null, + "activitySpecActivitySpecCategories": null, + "activitySpecUserParameters": [ + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + } + ], + "activitySpecActivitySpecParameters": null, + "id": null + }, + "workflow": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/activitySpec" + } + } + } + ], + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/1/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/activitySpec" + } + } + }, + { + "artifactUUID": "da6478e4-ea33-3346-ac12-ab121284a333", + "artifactName": "VnfInPlaceUpdate.bpmn", + "name": "VnfInPlaceUpdate", + "operationName": "inPlaceSoftwareUpdate", + "version": 1, + "description": "native workflow", + "body": null, + "resourceTarget": "vnf", + "source": "native", + "timeoutMinutes": null, + "artifactChecksum": null, + "created": null, + "vnfResourceWorkflow": null, + "workflowActivitySpecSequence": [], + "id": null, + "workflow": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflows/b5fa707a-f55a-11e7-a796-005056856d52/activitySpec" + } + } + } + ] + }, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + }, + "activitySpec": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/activitySpec" + } + } }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json index 6e358f7e17..d6ed585537 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json @@ -1,4 +1,5 @@ { "artifactUUID": "71526781-e55c-4cb7-adb3-97e09d9c76be", - "artifactName": "testingWorkflow" + "artifactName": "testingWorkflow.bpmn", + "name": "testingWorkflow" }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql index c2eb21b18e..948283453b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql @@ -806,6 +806,9 @@ CREATE TABLE `service` ( `WORKLOAD_CONTEXT` varchar(200) DEFAULT NULL, `SERVICE_CATEGORY` varchar(200) DEFAULT NULL, `RESOURCE_ORDER` varchar(200) default NULL, + `OVERALL_DISTRIBUTION_STATUS` varchar(45), + `ONAP_GENERATED_NAMING` TINYINT(1) DEFAULT NULL, + `NAMING_POLICY` varchar(200) DEFAULT NULL, PRIMARY KEY (`MODEL_UUID`), KEY `fk_service__tosca_csar1_idx` (`TOSCA_CSAR_ARTIFACT_UUID`), CONSTRAINT `fk_service__tosca_csar1` FOREIGN KEY (`TOSCA_CSAR_ARTIFACT_UUID`) REFERENCES `tosca_csar` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql b/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql index 65372b7b48..a47e1c44af 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql @@ -96,7 +96,9 @@ CREATE TABLE IF NOT EXISTS PUBLIC.INFRA_ACTIVE_REQUESTS( OPERATIONAL_ENV_NAME VARCHAR SELECTIVITY 1, INSTANCE_GROUP_ID VARCHAR SELECTIVITY 1, INSTANCE_GROUP_NAME VARCHAR SELECTIVITY 1, - REQUEST_URL VARCHAR SELECTIVITY 1 + REQUEST_URL VARCHAR SELECTIVITY 1, + ORIGINAL_REQUEST_ID VARCHAR SELECTIVITY 1, + EXT_SYSTEM_ERROR_SOURCE VARCHAR SELECTIVITY 1 ); INSERT INTO PUBLIC.INFRA_ACTIVE_REQUESTS(REQUEST_ID, CLIENT_REQUEST_ID, ACTION, REQUEST_STATUS, STATUS_MESSAGE, PROGRESS, START_TIME, END_TIME, SOURCE, VNF_ID, VNF_NAME, VNF_TYPE, SERVICE_TYPE, AIC_NODE_CLLI, TENANT_ID, PROV_STATUS, VNF_PARAMS, VNF_OUTPUTS, REQUEST_BODY, RESPONSE_BODY, LAST_MODIFIED_BY, MODIFY_TIME, REQUEST_TYPE, VOLUME_GROUP_ID, VOLUME_GROUP_NAME, VF_MODULE_ID, VF_MODULE_NAME, VF_MODULE_MODEL_NAME, AAI_SERVICE_ID, AIC_CLOUD_REGION, CALLBACK_URL, CORRELATOR, NETWORK_ID, NETWORK_NAME, NETWORK_TYPE, REQUEST_SCOPE, REQUEST_ACTION, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, REQUESTOR_ID, CONFIGURATION_ID, CONFIGURATION_NAME, OPERATIONAL_ENV_ID, OPERATIONAL_ENV_NAME, REQUEST_URL) VALUES diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java index 37fbfd023c..9da6ff21ac 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java @@ -87,6 +87,8 @@ public class InfraActiveRequests extends InfraRequests { .append("networkName", getNetworkName()).append("networkType", getNetworkType()) .append("requestorId", getRequestorId()).append("configurationId", getConfigurationId()) .append("configurationName", getConfigurationName()).append("operationalEnvId", getOperationalEnvId()) - .append("operationalEnvName", getOperationalEnvName()).append("requestUrl", getRequestUrl()).toString(); + .append("operationalEnvName", getOperationalEnvName()).append("requestUrl", getRequestUrl()) + .append("originalRequestId", getOriginalRequestId()) + .append("extSystemErrorSource", getExtSystemErrorSource()).toString(); } } diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java index 7c58c6171e..ecc4f46149 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java @@ -22,6 +22,7 @@ package org.onap.so.db.request.beans; import java.net.URI; import java.sql.Timestamp; +import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; @@ -152,10 +153,14 @@ public abstract class InfraRequests implements java.io.Serializable { private String instanceGroupName; @Column(name = "REQUEST_URL", length = 500) private String requestUrl; + @Column(name = "ORIGINAL_REQUEST_ID", length = 45) + private String originalRequestId; + @Column(name = "EXT_SYSTEM_ERROR_SOURCE", length = 80) + private String extSystemErrorSource; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "SO_REQUEST_ID", referencedColumnName = "REQUEST_ID") - private List<CloudApiRequests> cloudApiRequests; + private List<CloudApiRequests> cloudApiRequests = new ArrayList<>(); @ResourceId public URI getRequestURI() { @@ -569,6 +574,22 @@ public abstract class InfraRequests implements java.io.Serializable { this.requestUrl = requestUrl; } + public String getOriginalRequestId() { + return this.originalRequestId; + } + + public void setOriginalRequestId(String originalRequestId) { + this.originalRequestId = originalRequestId; + } + + public String getExtSystemErrorSource() { + return this.extSystemErrorSource; + } + + public void setExtSystemErrorSource(String extSystemErrorSource) { + this.extSystemErrorSource = extSystemErrorSource; + } + @PrePersist protected void onCreate() { if (requestScope == null) @@ -630,6 +651,8 @@ public abstract class InfraRequests implements java.io.Serializable { .append("requestorId", getRequestorId()).append("configurationId", getConfigurationId()) .append("configurationName", getConfigurationName()).append("operationalEnvId", getOperationalEnvId()) .append("operationalEnvName", getOperationalEnvName()).append("instanceGroupId", getInstanceGroupId()) - .append("instanceGroupName", getInstanceGroupName()).append("requestUrl", getRequestUrl()).toString(); + .append("instanceGroupName", getInstanceGroupName()).append("requestUrl", getRequestUrl()) + .append("originalRequestId", originalRequestId).append("extSystemErrorSource", extSystemErrorSource) + .toString(); } } diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java index 2a75c24c46..3c81555b99 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java @@ -86,6 +86,9 @@ public class RequestProcessingData implements Serializable { @Temporal(TemporalType.TIMESTAMP) private Date created = null; + @Column(name = "IS_DATA_INTERNAL") + private Boolean isDataInternal = true; + @Override public boolean equals(final Object other) { if (!(other instanceof RequestProcessingData)) { @@ -105,7 +108,7 @@ public class RequestProcessingData implements Serializable { public String toString() { return new ToStringBuilder(this).append("id", id).append("soRequestId", soRequestId) .append("groupingId", groupingId).append("name", name).append("value", value).append("tag", tag) - .toString(); + .append("isDataInternal", isDataInternal).toString(); } @PrePersist @@ -164,4 +167,12 @@ public class RequestProcessingData implements Serializable { public Date getCreated() { return created; } + + public Boolean getIsDataInternal() { + return isDataInternal; + } + + public void setIsDataInternal(Boolean isDataInternal) { + this.isDataInternal = isDataInternal; + } } 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 ca2f52690c..1867b85de6 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 @@ -338,6 +338,13 @@ public class RequestsDbClient { restTemplate.postForLocation(uri, entity); } + public void updateRequestProcessingData(RequestProcessingData requestProcessingData) { + HttpHeaders headers = getHttpHeaders(); + URI uri = getUri(requestProcessingDataURI); + HttpEntity<RequestProcessingData> entity = new HttpEntity<>(requestProcessingData, headers); + restTemplate.put(uri, entity); + } + public List<RequestProcessingData> getRequestProcessingDataBySoRequestId(String soRequestId) { return this .getRequestProcessingData(getUri(UriBuilder.fromUri(endpoint + findBySoRequestIdOrderByGroupingIdDesc) diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpec.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpec.java index 9a9564023d..20c10748b6 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpec.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpec.java @@ -21,7 +21,7 @@ import com.openpojo.business.annotation.BusinessKey; import uk.co.blackpepper.bowman.annotation.LinkedResource; @Entity -@Table(name = "ACTIVITY_SPEC") +@Table(name = "activity_spec") public class ActivitySpec implements Serializable { private static final long serialVersionUID = 6902290480087262973L; diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategories.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategories.java index f1ee006b60..64c77d27db 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategories.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategories.java @@ -28,7 +28,6 @@ import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; -import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @@ -36,9 +35,9 @@ 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 -@IdClass(ActivitySpecActivitySpecCategoriesId.class) @Table(name = "activity_spec_to_activity_spec_categories") public class ActivitySpecActivitySpecCategories implements Serializable { @@ -116,6 +115,7 @@ public class ActivitySpecActivitySpecCategories implements Serializable { this.activitySpec = activitySpec; } + @LinkedResource public ActivitySpecCategories getActivitySpecCategories() { return activitySpecCategories; } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategoriesId.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategoriesId.java deleted file mode 100644 index e3dcd359ec..0000000000 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecCategoriesId.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 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.db.catalog.beans; - -import java.io.Serializable; -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; - -public class ActivitySpecActivitySpecCategoriesId implements Serializable { - - private static final long serialVersionUID = 1563771827209840959L; - private Integer ID; - @BusinessKey - private Integer activitySpecId; - @BusinessKey - private Integer activitySpecCategoriesId; - - public Integer getID() { - return ID; - } - - public void setID(Integer iD) { - ID = iD; - } - - public Integer getActivitySpecCategoriesId() { - return activitySpecCategoriesId; - } - - public void setActivitySpecCategoriesId(Integer activitySpecCategoriesId) { - this.activitySpecCategoriesId = activitySpecCategoriesId; - } - - public Integer getActivitySpecId() { - return activitySpecId; - } - - public void setActivitySpecId(Integer activitySpecId) { - this.activitySpecId = activitySpecId; - } - - @Override - public String toString() { - return new ToStringBuilder(this).append("activitySpecId", activitySpecId) - .append("activitySpecCategoriesId", activitySpecCategoriesId).toString(); - } - - @Override - public boolean equals(final Object other) { - if (!(other instanceof ActivitySpecActivitySpecCategoriesId)) { - return false; - } - ActivitySpecActivitySpecCategoriesId castOther = (ActivitySpecActivitySpecCategoriesId) other; - return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId) - .append(activitySpecCategoriesId, castOther.activitySpecCategoriesId).isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(activitySpecId).append(activitySpecCategoriesId).toHashCode(); - } -} diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParameters.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParameters.java index 49c5d98943..f3e6a09b7f 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParameters.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParameters.java @@ -28,7 +28,6 @@ import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; -import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @@ -36,9 +35,9 @@ 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 -@IdClass(ActivitySpecActivitySpecParametersId.class) @Table(name = "activity_spec_to_activity_spec_parameters") public class ActivitySpecActivitySpecParameters implements Serializable { @@ -50,12 +49,10 @@ public class ActivitySpecActivitySpecParameters implements Serializable { private Integer ID; @BusinessKey - @Id @Column(name = "ACTIVITY_SPEC_ID") private Integer activitySpecId; @BusinessKey - @Id @Column(name = "ACTIVITY_SPEC_PARAMETERS_ID") private Integer activitySpecParametersId; @@ -70,7 +67,7 @@ public class ActivitySpecActivitySpecParameters implements Serializable { @Override public String toString() { return new ToStringBuilder(this).append("activitySpecId", activitySpecId) - .append("activitySpecCategoriesId", activitySpecParametersId).toString(); + .append("activitySpecParametersId", activitySpecParametersId).toString(); } @Override @@ -108,6 +105,7 @@ public class ActivitySpecActivitySpecParameters implements Serializable { this.activitySpecParametersId = activitySpecParametersId; } + @LinkedResource public ActivitySpec getActivitySpec() { return activitySpec; } @@ -116,6 +114,7 @@ public class ActivitySpecActivitySpecParameters implements Serializable { this.activitySpec = activitySpec; } + @LinkedResource public ActivitySpecParameters getActivitySpecParameters() { return activitySpecParameters; } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParametersId.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParametersId.java deleted file mode 100644 index 8f4cc6d966..0000000000 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecActivitySpecParametersId.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 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.db.catalog.beans; - -import java.io.Serializable; -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; - -public class ActivitySpecActivitySpecParametersId implements Serializable { - - private static final long serialVersionUID = 1563771827209840959L; - - private Integer ID; - @BusinessKey - private Integer activitySpecId; - @BusinessKey - private Integer activitySpecParametersId; - - public Integer getID() { - return ID; - } - - public void setID(Integer iD) { - ID = iD; - } - - public Integer getActivitySpecParametersId() { - return activitySpecParametersId; - } - - public void setActivitySpecParametersId(Integer activitySpecParametersId) { - this.activitySpecParametersId = activitySpecParametersId; - } - - public Integer getActivitySpecId() { - return activitySpecId; - } - - public void setActivitySpecId(Integer activitySpecId) { - this.activitySpecId = activitySpecId; - } - - @Override - public String toString() { - return new ToStringBuilder(this).append("activitySpecId", activitySpecId) - .append("activitySpecCategoriesId", activitySpecParametersId).toString(); - } - - @Override - public boolean equals(final Object other) { - if (!(other instanceof ActivitySpecActivitySpecParametersId)) { - return false; - } - ActivitySpecActivitySpecParametersId castOther = (ActivitySpecActivitySpecParametersId) other; - return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId) - .append(activitySpecParametersId, castOther.activitySpecParametersId).isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(activitySpecId).append(activitySpecParametersId).toHashCode(); - } -} diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecCategories.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecCategories.java index 56aecc4a98..8f3f7a34b0 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecCategories.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecCategories.java @@ -17,7 +17,7 @@ import com.openpojo.business.annotation.BusinessKey; import uk.co.blackpepper.bowman.annotation.LinkedResource; @Entity -@Table(name = "ACTIVITY_SPEC_CATEGORIES") +@Table(name = "activity_spec_categories") public class ActivitySpecCategories implements Serializable { private static final long serialVersionUID = -6251150462067699643L; @@ -31,9 +31,6 @@ public class ActivitySpecCategories implements Serializable { @Column(name = "NAME") private String name; - @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpecCategories") - private List<ActivitySpecActivitySpecCategories> activitySpecActivitySpecCategories; - public Integer getID() { return ID; } @@ -46,20 +43,9 @@ public class ActivitySpecCategories implements Serializable { this.name = name; } - @LinkedResource - public List<ActivitySpecActivitySpecCategories> getActivitySpecActivitySpecCategories() { - return activitySpecActivitySpecCategories; - } - - public void setActivitySpecActivitySpecCategories( - List<ActivitySpecActivitySpecCategories> activitySpecActivitySpecCategories) { - this.activitySpecActivitySpecCategories = activitySpecActivitySpecCategories; - } - @Override public String toString() { - return new ToStringBuilder(this).append("name", name) - .append("activitySpecActivitySpecCategories", activitySpecActivitySpecCategories).toString(); + return new ToStringBuilder(this).append("name", name).toString(); } @Override diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecParameters.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecParameters.java index 49e0f3fa79..ed056400b2 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecParameters.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecParameters.java @@ -1,20 +1,12 @@ package org.onap.so.db.catalog.beans; import java.io.Serializable; -import java.util.ArrayList; import java.util.Date; -import java.util.List; 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.IdClass; -import javax.persistence.JoinColumn; -import javax.persistence.Lob; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.Table; import javax.persistence.Temporal; @@ -23,12 +15,9 @@ 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 org.hibernate.annotations.NotFound; -import org.hibernate.annotations.NotFoundAction; -import uk.co.blackpepper.bowman.annotation.LinkedResource; @Entity -@Table(name = "ACTIVITY_SPEC_PARAMETERS") +@Table(name = "activity_spec_parameters") public class ActivitySpecParameters implements Serializable { private static final long serialVersionUID = 3627711377147710046L; @@ -56,28 +45,14 @@ public class ActivitySpecParameters implements Serializable { @Temporal(TemporalType.TIMESTAMP) private Date created; - @OneToMany(fetch = FetchType.LAZY, mappedBy = "activitySpecParameters") - private List<ActivitySpecActivitySpecParameters> activitySpecActivitySpecParameters; - @PrePersist protected void onCreate() { this.created = new Date(); } - @LinkedResource - public List<ActivitySpecActivitySpecParameters> getActivitySpecActivitySpecParameters() { - return activitySpecActivitySpecParameters; - } - - public void setActivitySpecActivitySpecParameters( - List<ActivitySpecActivitySpecParameters> activitySpecActivitySpecParameters) { - this.activitySpecActivitySpecParameters = activitySpecActivitySpecParameters; - } - @Override public String toString() { - return new ToStringBuilder(this).append("name", name).append("direction", direction) - .append("activitySpecActivitySpecParameters", activitySpecActivitySpecParameters).toString(); + return new ToStringBuilder(this).append("name", name).append("direction", direction).toString(); } @Override diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParameters.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParameters.java index 6a7b5ba0be..d23c782a1a 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParameters.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParameters.java @@ -28,7 +28,6 @@ import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; -import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @@ -36,9 +35,9 @@ 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 -@IdClass(ActivitySpecUserParametersId.class) @Table(name = "activity_spec_to_user_parameters") public class ActivitySpecUserParameters implements Serializable { @@ -50,12 +49,10 @@ public class ActivitySpecUserParameters implements Serializable { private Integer ID; @BusinessKey - @Id @Column(name = "ACTIVITY_SPEC_ID") private Integer activitySpecId; @BusinessKey - @Id @Column(name = "USER_PARAMETERS_ID") private Integer userParametersId; @@ -108,6 +105,7 @@ public class ActivitySpecUserParameters implements Serializable { this.userParametersId = userParametersId; } + @LinkedResource public ActivitySpec getActivitySpec() { return activitySpec; } @@ -116,6 +114,7 @@ public class ActivitySpecUserParameters implements Serializable { this.activitySpec = activitySpec; } + @LinkedResource public UserParameters getUserParameters() { return userParameters; } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParametersId.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParametersId.java deleted file mode 100644 index fd55d6e961..0000000000 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParametersId.java +++ /dev/null @@ -1,84 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 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.db.catalog.beans; - -import java.io.Serializable; -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; - -public class ActivitySpecUserParametersId implements Serializable { - - private static final long serialVersionUID = 1563771827209840959L; - - private Integer ID; - @BusinessKey - private Integer activitySpecId; - @BusinessKey - private Integer userParametersId; - - public Integer getID() { - return ID; - } - - public void setID(Integer iD) { - ID = iD; - } - - public Integer getUserParametersId() { - return userParametersId; - } - - public void setUserParametersId(Integer userParametersId) { - this.userParametersId = userParametersId; - } - - public Integer getActivitySpecId() { - return activitySpecId; - } - - public void setActivitySpecId(Integer activitySpecId) { - this.activitySpecId = activitySpecId; - } - - @Override - public String toString() { - return new ToStringBuilder(this).append("activitySpecId", activitySpecId) - .append("userParametersId", userParametersId).toString(); - } - - @Override - public boolean equals(final Object other) { - if (!(other instanceof ActivitySpecUserParametersId)) { - return false; - } - ActivitySpecUserParametersId castOther = (ActivitySpecUserParametersId) other; - return new EqualsBuilder().append(activitySpecId, castOther.activitySpecId) - .append(userParametersId, castOther.userParametersId).isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(activitySpecId).append(userParametersId).toHashCode(); - } - -} diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResourceCustomization.java index 4599c978ec..3be9e1f1e3 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResourceCustomization.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ConfigurationResourceCustomization.java @@ -64,20 +64,21 @@ public class ConfigurationResourceCustomization implements Serializable { private String modelInstanceName; @Column(name = "CONFIGURATION_FUNCTION") - private String nfFunction; + private String function; @Column(name = "CONFIGURATION_TYPE") - private String nfType; + private String type; @Column(name = "CONFIGURATION_ROLE") - private String nfRole; + private String role; @Column(name = "CREATION_TIMESTAMP", updatable = false) @Temporal(TemporalType.TIMESTAMP) private Date created; - @Column(name = "SERVICE_PROXY_CUSTOMIZATION_MODEL_CUSTOMIZATION_UUID") - private String serviceProxyResourceCustomizationUUID; + @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinColumn(name = "SERVICE_PROXY_CUSTOMIZATION_MODEL_CUSTOMIZATION_UUID") + private ServiceProxyResourceCustomization serviceProxyResourceCustomization; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "CONFIGURATION_CUSTOMIZATION_MODEL_CUSTOMIZATION_ID") @@ -120,40 +121,42 @@ public class ConfigurationResourceCustomization implements Serializable { this.modelInstanceName = modelInstanceName; } - public String getNfFunction() { - return nfFunction; + public String getFunction() { + return function; } - public void setNfFunction(String nfFunction) { - this.nfFunction = nfFunction; + public void setFunction(String function) { + this.function = function; } - public String getNfType() { - return nfType; + public String getType() { + return type; } - public void setNfType(String nfType) { - this.nfType = nfType; + public void setType(String type) { + this.type = type; } - public String getNfRole() { - return nfRole; + public String getRole() { + return role; } - public void setNfRole(String nfRole) { - this.nfRole = nfRole; + public void setRole(String role) { + this.role = role; } public Date getCreated() { return created; } - public String getServiceProxyResourceCustomizationUUID() { - return serviceProxyResourceCustomizationUUID; + @LinkedResource + public ServiceProxyResourceCustomization getServiceProxyResourceCustomization() { + return serviceProxyResourceCustomization; } - public void setServiceProxyResourceCustomizationUUID(String serviceProxyResourceCustomizationUUID) { - this.serviceProxyResourceCustomizationUUID = serviceProxyResourceCustomizationUUID; + public void setServiceProxyResourceCustomization( + ServiceProxyResourceCustomization serviceProxyResourceCustomization) { + this.serviceProxyResourceCustomization = serviceProxyResourceCustomization; } @@ -186,8 +189,8 @@ public class ConfigurationResourceCustomization implements Serializable { @Override public String toString() { return new ToStringBuilder(this).append("id", id).append("modelCustomizationUUID", modelCustomizationUUID) - .append("modelInstanceName", modelInstanceName).append("nfFunction", nfFunction) - .append("nfType", nfType).append("nfRole", nfRole).append("created", created) + .append("modelInstanceName", modelInstanceName).append("function", function).append("type", type) + .append("role", role).append("created", created) // .append("serviceProxyResourceCustomization", serviceProxyResourceCustomization) .append("configResourceCustomization", configResourceCustomization) .append("configurationResource", configurationResource).append("service", service).toString(); diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationAction.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationAction.java index cf8644eedc..b340fdea2b 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationAction.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationAction.java @@ -22,9 +22,17 @@ package org.onap.so.db.catalog.beans; // TODO find this file a new location? public enum OrchestrationAction { - ASSIGN("Assign"), UNASSIGN("Unassign"), ACTIVATE("Activate"), DEACTIVATE("Deactivate"), CHANGE_MODEL( - "ChangeModel"), CREATE("Create"), DELETE("Delete"), UPDATE( - "Update"), ADD_MEMBERS("AddMembers"), REMOVE_MEMBERS("RemoveMembers"), CUSTOM("Custom"); + ASSIGN("Assign"), + UNASSIGN("Unassign"), + ACTIVATE("Activate"), + DEACTIVATE("Deactivate"), + CHANGE_MODEL("ChangeModel"), + CREATE("Create"), + DELETE("Delete"), + UPDATE("Update"), + ADD_MEMBERS("AddMembers"), + REMOVE_MEMBERS("RemoveMembers"), + CUSTOM("Custom"); private final String name; diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatus.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatus.java index e608bfed21..93e2992d3f 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatus.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatus.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,12 +21,18 @@ package org.onap.so.db.catalog.beans; public enum OrchestrationStatus { - ACTIVE("Active", "active"), ASSIGNED("Assigned", "assigned"), CREATED("Created", "created"), INVENTORIED( - "Inventoried", "inventoried"), PENDING("Pending", "pending"), PENDING_ACTIVATION("PendingActivation", - "pending.?activation"), PENDING_CREATE("PendingCreate", "pending.?create"), PENDING_DELETE( - "PendingDelete", "pending.?delete"), PRECREATED("PreCreated", - "pre.?created"), CONFIGASSIGNED("ConfigAssigned", "config.?assigned"), CONFIGURE( - "Configure", "configure"), CONFIGURED("Configured", "configured"); + ACTIVE("Active", "active"), + ASSIGNED("Assigned", "assigned"), + CREATED("Created", "created"), + INVENTORIED("Inventoried", "inventoried"), + PENDING("Pending", "pending"), + PENDING_ACTIVATION("PendingActivation", "pending.?activation"), + PENDING_CREATE("PendingCreate", "pending.?create"), + PENDING_DELETE("PendingDelete", "pending.?delete"), + PRECREATED("PreCreated", "pre.?created"), + CONFIGASSIGNED("ConfigAssigned", "config.?assigned"), + CONFIGURE("Configure", "configure"), + CONFIGURED("Configured", "configured"); private final String name; private final String fuzzyMatcher; @@ -43,7 +49,7 @@ public enum OrchestrationStatus { /** * case insensitive regular expression match to enum value - * + * * @param status * @return */ diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ResourceType.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ResourceType.java index b41548ca99..4fd28c910e 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ResourceType.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ResourceType.java @@ -21,9 +21,15 @@ package org.onap.so.db.catalog.beans; public enum ResourceType { - SERVICE("Service"), VNF("Vnf"), VOLUME_GROUP("VolumeGroup"), VF_MODULE("VfModule"), NETWORK( - "Network"), NETWORK_COLLECTION("NetworkCollection"), CONFIGURATION( - "Configuration"), INSTANCE_GROUP("InstanceGroup"), NO_VALIDATE("NoValidate"); + SERVICE("Service"), + VNF("Vnf"), + VOLUME_GROUP("VolumeGroup"), + VF_MODULE("VfModule"), + NETWORK("Network"), + NETWORK_COLLECTION("NetworkCollection"), + CONFIGURATION("Configuration"), + INSTANCE_GROUP("InstanceGroup"), + NO_VALIDATE("NoValidate"); private final String name; diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Service.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Service.java index 3b57ae0f72..e591552ebf 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Service.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Service.java @@ -136,6 +136,11 @@ public class Service implements Serializable { @JoinColumn(name = "TOSCA_CSAR_ARTIFACT_UUID") private ToscaCsar csar; + @Column(name = "NAMING_POLICY") + private String namingPolicy; + + @Column(name = "ONAP_GENERATED_NAMING") + private Boolean onapGeneratedNaming; @Override public String toString() { @@ -150,7 +155,7 @@ public class Service implements Serializable { .append("serviceProxyCustomizations", serviceProxyCustomizations) .append("configurationCustomizations", configurationCustomizations) .append("pnfCustomizations", pnfCustomizations).append("recipes", recipes).append("csar", csar) - .toString(); + .append("namingPolicy", namingPolicy).append("onapGeneratedNaming", onapGeneratedNaming).toString(); } @PrePersist @@ -370,7 +375,6 @@ public class Service implements Serializable { this.resourceOrder = resourceOrder; } - public String getDistrobutionStatus() { return distrobutionStatus; } @@ -379,4 +383,20 @@ public class Service implements Serializable { this.distrobutionStatus = distrobutionStatus; } + public String getNamingPolicy() { + return namingPolicy; + } + + public void setNamingPolicy(String namingPolicy) { + this.namingPolicy = namingPolicy; + } + + public Boolean getOnapGeneratedNaming() { + return onapGeneratedNaming; + } + + public void setOnapGeneratedNaming(Boolean onapGeneratedNaming) { + this.onapGeneratedNaming = onapGeneratedNaming; + } + } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/UserParameters.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/UserParameters.java index a20647d5c1..c2cf2d7cf6 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/UserParameters.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/UserParameters.java @@ -1,19 +1,12 @@ package org.onap.so.db.catalog.beans; import java.io.Serializable; -import java.util.ArrayList; import java.util.Date; -import java.util.List; 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.Lob; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.Table; import javax.persistence.Temporal; @@ -22,9 +15,6 @@ 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 org.hibernate.annotations.NotFound; -import org.hibernate.annotations.NotFoundAction; -import uk.co.blackpepper.bowman.annotation.LinkedResource; @Entity @Table(name = "USER_PARAMETERS") @@ -66,10 +56,6 @@ public class UserParameters implements Serializable { @Temporal(TemporalType.TIMESTAMP) private Date created; - - @OneToMany(fetch = FetchType.LAZY, mappedBy = "userParameters") - private List<ActivitySpecUserParameters> activitySpecUserParameters; - @PrePersist protected void onCreate() { this.created = new Date(); @@ -87,19 +73,9 @@ public class UserParameters implements Serializable { this.name = name; } - @LinkedResource - public List<ActivitySpecUserParameters> getActivitySpecUserParameters() { - return activitySpecUserParameters; - } - - public void setActivitySpecUserParameters(List<ActivitySpecUserParameters> activitySpecUserParameters) { - this.activitySpecUserParameters = activitySpecUserParameters; - } - @Override public String toString() { - return new ToStringBuilder(this).append("name", name) - .append("ActivitySpecUserParameters", activitySpecUserParameters).toString(); + return new ToStringBuilder(this).append("name", name).toString(); } public String getPayloadLocation() { diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflow.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflow.java index f49ae26305..92cc5d18f0 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflow.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceWorkflow.java @@ -44,7 +44,7 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource; @Entity @IdClass(VnfResourceWorkflowId.class) -@Table(name = "VNF_RESOURCE_TO_WORKFLOW") +@Table(name = "vnf_resource_to_workflow") public class VnfResourceWorkflow implements Serializable { private static final long serialVersionUID = -1326433350241927676L; diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Workflow.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Workflow.java index 1f46bc01f7..d1e60a0f76 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Workflow.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Workflow.java @@ -1,7 +1,6 @@ package org.onap.so.db.catalog.beans; import java.io.Serializable; -import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Column; @@ -10,9 +9,7 @@ import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; -import javax.persistence.JoinColumn; import javax.persistence.Lob; -import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.Table; @@ -21,9 +18,6 @@ import javax.persistence.TemporalType; 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 org.hibernate.annotations.NotFound; -import org.hibernate.annotations.NotFoundAction; import uk.co.blackpepper.bowman.annotation.LinkedResource; @Entity diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequence.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequence.java index 4b497cc7da..f25be45bb2 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequence.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequence.java @@ -21,7 +21,6 @@ package org.onap.so.db.catalog.beans; import java.io.Serializable; -import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; @@ -29,21 +28,17 @@ import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; -import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; -import javax.persistence.PrePersist; import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; 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 -@IdClass(WorkflowActivitySpecSequenceId.class) @Table(name = "workflow_activity_spec_sequence") public class WorkflowActivitySpecSequence implements Serializable { @@ -55,12 +50,10 @@ public class WorkflowActivitySpecSequence implements Serializable { private Integer ID; @BusinessKey - @Id @Column(name = "ACTIVITY_SPEC_ID") private Integer activitySpecId; @BusinessKey - @Id @Column(name = "WORKFLOW_ID") private Integer workflowId; @@ -113,6 +106,7 @@ public class WorkflowActivitySpecSequence implements Serializable { this.workflowId = workflowId; } + @LinkedResource public ActivitySpec getActivitySpec() { return activitySpec; } @@ -121,6 +115,7 @@ public class WorkflowActivitySpecSequence implements Serializable { this.activitySpec = activitySpec; } + @LinkedResource public Workflow getWorkflow() { return workflow; } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequenceId.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequenceId.java deleted file mode 100644 index 41af2ed3a5..0000000000 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/WorkflowActivitySpecSequenceId.java +++ /dev/null @@ -1,84 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 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.db.catalog.beans; - -import java.io.Serializable; -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; - -public class WorkflowActivitySpecSequenceId implements Serializable { - - private static final long serialVersionUID = -8987314754011453123L; - - private Integer ID; - - @BusinessKey - private Integer workflowId; - @BusinessKey - private Integer activitySpecId; - - public Integer getID() { - return ID; - } - - public void setID(Integer ID) { - this.ID = ID; - } - - public Integer getWorkflowId() { - return workflowId; - } - - public void setWorkflowId(Integer workflowId) { - this.workflowId = workflowId; - } - - public Integer getActivitySpecId() { - return activitySpecId; - } - - public void setActivitySpecId(Integer activitySpecId) { - this.activitySpecId = activitySpecId; - } - - @Override - public String toString() { - return new ToStringBuilder(this).append("workflowId", workflowId).append("activitySpecId", activitySpecId) - .toString(); - } - - @Override - public boolean equals(final Object other) { - if (!(other instanceof WorkflowActivitySpecSequenceId)) { - return false; - } - WorkflowActivitySpecSequenceId castOther = (WorkflowActivitySpecSequenceId) other; - return new EqualsBuilder().append(workflowId, castOther.workflowId) - .append(activitySpecId, castOther.activitySpecId).isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(workflowId).append(activitySpecId).toHashCode(); - } -} 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 a1f926e25f..2bfa2856d2 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 @@ -73,6 +73,7 @@ import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; import uk.co.blackpepper.bowman.Client; import uk.co.blackpepper.bowman.ClientFactory; import uk.co.blackpepper.bowman.Configuration; @@ -144,6 +145,7 @@ public class CatalogDbClient { private static final String CLOUD_VERSION = "cloudVersion"; private static final String HOMING_INSTANCE = "/homingInstance"; private static final String ARTIFACT_UUID = "artifactUUID"; + private static final String SOURCE = "source"; private static final String TARGET_ENTITY = "SO:CatalogDB"; private static final String ASTERISK = "*"; @@ -190,6 +192,7 @@ public class CatalogDbClient { private String findPnfResourceCustomizationByModelUuid = "/findPnfResourceCustomizationByModelUuid"; private String findWorkflowByArtifactUUID = "/findByArtifactUUID"; private String findWorkflowByModelUUID = "/findWorkflowByModelUUID"; + private String findWorkflowBySource = "/findBySource"; private String findVnfResourceCustomizationByModelUuid = "/findVnfResourceCustomizationByModelUuid"; private String serviceURI; @@ -326,6 +329,7 @@ public class CatalogDbClient { findWorkflowByArtifactUUID = endpoint + WORKFLOW + SEARCH + findWorkflowByArtifactUUID; findWorkflowByModelUUID = endpoint + WORKFLOW + SEARCH + findWorkflowByModelUUID; + findWorkflowBySource = endpoint + WORKFLOW + SEARCH + findWorkflowBySource; findVnfResourceCustomizationByModelUuid = endpoint + VNF_RESOURCE_CUSTOMIZATION + SEARCH + findVnfResourceCustomizationByModelUuid; @@ -639,10 +643,10 @@ public class CatalogDbClient { "Get Rainy Day Status - Flow Name {}, Service Type: {} , vnfType {} , errorCode {}, workStep {}, errorMessage {}", flowName, serviceType, vnfType, errorCode, workStep, errorMessage); return this.getSingleResource(rainyDayHandlerStatusClient, - getUri(UriBuilder.fromUri(endpoint + RAINY_DAY_HANDLER_MACRO + SEARCH + findRainyDayHandler) + 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().toString())); + .queryParam(ERROR_MESSAGE, errorMessage).build().encode().toUri()); } public ServiceRecipe getFirstByServiceModelUUIDAndAction(String modelUUID, String action) { @@ -819,9 +823,14 @@ public class CatalogDbClient { public VnfResourceCustomization findVnfResourceCustomizationInList(String vnfCustomizationUUID, List<VnfResourceCustomization> vnfResourceCusts) { - List<VnfResourceCustomization> filtered = vnfResourceCusts.stream() - .filter(vnfCustRes -> vnfCustomizationUUID.equals(vnfCustRes.getModelCustomizationUUID())) - .collect(Collectors.toList()); + if (vnfCustomizationUUID == null) { + throw new EntityNotFoundException( + "a NULL UUID was provided in query to search for VnfResourceCustomization"); + } + List<VnfResourceCustomization> filtered = + vnfResourceCusts.stream().filter(v -> v.getModelCustomizationUUID() != null) + .filter(vnfCustRes -> vnfCustomizationUUID.equals(vnfCustRes.getModelCustomizationUUID())) + .collect(Collectors.toList()); if (filtered != null && !filtered.isEmpty() && filtered.size() == 1) { return filtered.get(0); } else @@ -829,9 +838,12 @@ public class CatalogDbClient { "Unable to find VnfResourceCustomization ModelCustomizationUUID:" + vnfCustomizationUUID); } - private VfModuleCustomization findVfModuleCustomizationInList(String vfModuleCustomizationUUID, + protected VfModuleCustomization findVfModuleCustomizationInList(String vfModuleCustomizationUUID, List<VfModuleCustomization> vfModuleList) { - List<VfModuleCustomization> filtered = vfModuleList.stream() + if (vfModuleCustomizationUUID == null) { + throw new EntityNotFoundException("a NULL UUID was provided in query to search for VfModuleCustomization"); + } + List<VfModuleCustomization> filtered = vfModuleList.stream().filter(v -> v.getModelCustomizationUUID() != null) .filter(vfModuleCust -> vfModuleCustomizationUUID.equals(vfModuleCust.getModelCustomizationUUID())) .collect(Collectors.toList()); if (filtered != null && !filtered.isEmpty() && filtered.size() == 1) { @@ -841,9 +853,13 @@ public class CatalogDbClient { "Unable to find VfModuleCustomization ModelCustomizationUUID:" + vfModuleCustomizationUUID); } - private CvnfcCustomization findCvnfcCustomizationInAList(String cvnfcCustomizationUuid, + protected CvnfcCustomization findCvnfcCustomizationInAList(String cvnfcCustomizationUuid, List<CvnfcCustomization> cvnfcCustomList) { - List<CvnfcCustomization> filtered = cvnfcCustomList.stream() + if (cvnfcCustomizationUuid == null) { + throw new EntityNotFoundException( + "a NULL UUID was provided in query to search for CvnfcCustomization" + cvnfcCustomizationUuid); + } + List<CvnfcCustomization> filtered = cvnfcCustomList.stream().filter(c -> c.getModelCustomizationUUID() != null) .filter(cvnfc -> cvnfcCustomizationUuid.equals(cvnfc.getModelCustomizationUUID())) .collect(Collectors.toList()); if (filtered != null && !filtered.isEmpty() && filtered.size() == 1) { @@ -880,4 +896,17 @@ public class CatalogDbClient { return this.getMultipleResources(workflowClient, getUri(UriBuilder.fromUri(findWorkflowByModelUUID) .queryParam(VNF_RESOURCE_MODEL_UUID, vnfResourceModelUUID).build().toString())); } + + public List<Workflow> findWorkflowBySource(String source) { + return this.getMultipleResources(workflowClient, + getUri(UriBuilder.fromUri(findWorkflowBySource).queryParam(SOURCE, source).build().toString())); + } + + public String getEndpoint() { + return endpoint; + } + + public void setEndpoint(String endpoint) { + this.endpoint = endpoint; + } } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ActivitySpecRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ActivitySpecRepository.java index aa474238fd..f86ae14f93 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ActivitySpecRepository.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ActivitySpecRepository.java @@ -25,7 +25,7 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(collectionResourceRel = "activitySpec", path = "activitySpec") -public interface ActivitySpecRepository extends JpaRepository<ActivitySpec, String> { +public interface ActivitySpecRepository extends JpaRepository<ActivitySpec, Integer> { ActivitySpec findByName(String name); diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ActivitySpecUserParametersRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ActivitySpecUserParametersRepository.java new file mode 100644 index 0000000000..5e4340e392 --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ActivitySpecUserParametersRepository.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 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.db.catalog.data.repository; + +import org.onap.so.db.catalog.beans.ActivitySpecUserParameters; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +@RepositoryRestResource(collectionResourceRel = "activitySpecUserParameters", path = "activitySpecUserParameters") +public interface ActivitySpecUserParametersRepository extends JpaRepository<ActivitySpecUserParameters, Integer> { + +} diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/UserParametersRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/UserParametersRepository.java new file mode 100644 index 0000000000..984f8fac99 --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/UserParametersRepository.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 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.db.catalog.data.repository; + +import org.onap.so.db.catalog.beans.UserParameters; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +@RepositoryRestResource(collectionResourceRel = "userParameters", path = "userParameters") +public interface UserParametersRepository extends JpaRepository<UserParameters, Integer> { + +} diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowActivitySpecSequenceRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowActivitySpecSequenceRepository.java new file mode 100644 index 0000000000..0dfbbb9ead --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowActivitySpecSequenceRepository.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 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.db.catalog.data.repository; + +import org.onap.so.db.catalog.beans.WorkflowActivitySpecSequence; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +@RepositoryRestResource(collectionResourceRel = "workflowActivitySpecSequence", path = "workflowActivitySpecSequence") +public interface WorkflowActivitySpecSequenceRepository extends JpaRepository<WorkflowActivitySpecSequence, Integer> { + +} diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java index fb5f202cbc..8bcc60c8be 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java @@ -24,14 +24,15 @@ import java.util.List; import org.onap.so.db.catalog.beans.Workflow; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(collectionResourceRel = "workflow", path = "workflow") -public interface WorkflowRepository extends JpaRepository<Workflow, String> { +public interface WorkflowRepository extends JpaRepository<Workflow, Integer> { Workflow findByArtifactUUID(String artifactUUID); + List<Workflow> findBySource(String source); + /** * Used to fetch the @{link Workflow} by the Model UUID. * diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java new file mode 100644 index 0000000000..9c257bdec3 --- /dev/null +++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java @@ -0,0 +1,173 @@ +/*- + * ============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.db.catalog.client; + +import static org.junit.Assert.assertTrue; +import java.util.ArrayList; +import javax.persistence.EntityNotFoundException; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.so.db.catalog.beans.CvnfcCustomization; +import org.onap.so.db.catalog.beans.VfModuleCustomization; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; + +public class CatalogDbClientTest { + + private CatalogDbClient catalogDbClient; + + @Before + public void init() { + catalogDbClient = new CatalogDbClient(); + } + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public final void testFindVnfResourceCustomizationInListNullInList() { + thrown.expect(EntityNotFoundException.class); + String vnfCustomizationUUID = "a123"; + VnfResourceCustomization vrc = new VnfResourceCustomization(); + vrc.setModelCustomizationUUID("z789J"); + VnfResourceCustomization vrc2 = new VnfResourceCustomization(); + vrc2.setModelCustomizationUUID(null); + ArrayList<VnfResourceCustomization> vrcs = new ArrayList<VnfResourceCustomization>(); + vrcs.add(vrc); + vrcs.add(vrc2); + catalogDbClient.findVnfResourceCustomizationInList(vnfCustomizationUUID, vrcs); + } + + @Test + public final void testFindVnfResourceCustomizationInListNullString() { + thrown.expect(EntityNotFoundException.class); + thrown.expectMessage("a NULL UUID was provided in query to search for VnfResourceCustomization"); + String vnfCustomizationUUID = null; + VnfResourceCustomization vrc = new VnfResourceCustomization(); + vrc.setModelCustomizationUUID("z789J"); + VnfResourceCustomization vrc2 = new VnfResourceCustomization(); + vrc2.setModelCustomizationUUID("a123"); + ArrayList<VnfResourceCustomization> vrcs = new ArrayList<VnfResourceCustomization>(); + vrcs.add(vrc); + vrcs.add(vrc2); + catalogDbClient.findVnfResourceCustomizationInList(vnfCustomizationUUID, vrcs); + } + + @Test + public final void testFindVnfResourceCustomizationInListNoNulls() { + String vnfCustomizationUUID = "a123"; + VnfResourceCustomization vrc = new VnfResourceCustomization(); + vrc.setModelCustomizationUUID("z789J"); + VnfResourceCustomization vrc2 = new VnfResourceCustomization(); + vrc2.setModelCustomizationUUID("a123"); + ArrayList<VnfResourceCustomization> vrcs = new ArrayList<VnfResourceCustomization>(); + vrcs.add(vrc); + vrcs.add(vrc2); + VnfResourceCustomization aVrc = catalogDbClient.findVnfResourceCustomizationInList(vnfCustomizationUUID, vrcs); + assertTrue(aVrc.getModelCustomizationUUID().equals("a123")); + } + + @Test + public final void testFindVfModuleCustomizationInListNullInList() { + thrown.expect(EntityNotFoundException.class); + String vfModuleCustomizationUUID = "a123"; + VfModuleCustomization vmc = new VfModuleCustomization(); + vmc.setModelCustomizationUUID("z789J"); + VfModuleCustomization vmc2 = new VfModuleCustomization(); + vmc2.setModelCustomizationUUID(null); + ArrayList<VfModuleCustomization> vmcs = new ArrayList<VfModuleCustomization>(); + vmcs.add(vmc); + vmcs.add(vmc2); + catalogDbClient.findVfModuleCustomizationInList(vfModuleCustomizationUUID, vmcs); + } + + @Test + public final void testFindVfModuleCustomizationInListNullString() { + thrown.expect(EntityNotFoundException.class); + thrown.expectMessage("a NULL UUID was provided in query to search for VfModuleCustomization"); + String vfModuleCustomizationUUID = null; + VfModuleCustomization vmc = new VfModuleCustomization(); + vmc.setModelCustomizationUUID("z789J"); + VfModuleCustomization vmc2 = new VfModuleCustomization(); + vmc2.setModelCustomizationUUID("a123"); + ArrayList<VfModuleCustomization> vmcs = new ArrayList<VfModuleCustomization>(); + vmcs.add(vmc); + vmcs.add(vmc2); + catalogDbClient.findVfModuleCustomizationInList(vfModuleCustomizationUUID, vmcs); + } + + @Test + public final void testFindVfModuleCustomizationInListNoNulls() { + String vfModuleCustomizationUUID = "a123"; + VfModuleCustomization vmc = new VfModuleCustomization(); + vmc.setModelCustomizationUUID("z789J"); + VfModuleCustomization vmc2 = new VfModuleCustomization(); + vmc2.setModelCustomizationUUID("a123"); + ArrayList<VfModuleCustomization> vmcs = new ArrayList<VfModuleCustomization>(); + vmcs.add(vmc); + vmcs.add(vmc2); + VfModuleCustomization aVmc = catalogDbClient.findVfModuleCustomizationInList(vfModuleCustomizationUUID, vmcs); + assertTrue(aVmc.getModelCustomizationUUID().equals("a123")); + } + + @Test + public final void testFindCvnfcCustomizationInListNullInList() { + thrown.expect(EntityNotFoundException.class); + String cvnfcCustomizationUuid = "a123"; + CvnfcCustomization cvnfc = new CvnfcCustomization(); + cvnfc.setModelCustomizationUUID("z789J"); + CvnfcCustomization cvnfc2 = new CvnfcCustomization(); + cvnfc2.setModelCustomizationUUID(null); + ArrayList<CvnfcCustomization> cvnfcs = new ArrayList<CvnfcCustomization>(); + cvnfcs.add(cvnfc); + cvnfcs.add(cvnfc2); + catalogDbClient.findCvnfcCustomizationInAList(cvnfcCustomizationUuid, cvnfcs); + } + + @Test + public final void testFindCvnfcCustomizationInListNullString() { + thrown.expect(EntityNotFoundException.class); + thrown.expectMessage("a NULL UUID was provided in query to search for CvnfcCustomization"); + String cvnfcCustomizationUuid = null; + CvnfcCustomization cvnfc = new CvnfcCustomization(); + cvnfc.setModelCustomizationUUID("z789J"); + CvnfcCustomization cvnfc2 = new CvnfcCustomization(); + cvnfc2.setModelCustomizationUUID("a123"); + ArrayList<CvnfcCustomization> cvnfcs = new ArrayList<CvnfcCustomization>(); + cvnfcs.add(cvnfc); + cvnfcs.add(cvnfc2); + catalogDbClient.findCvnfcCustomizationInAList(cvnfcCustomizationUuid, cvnfcs); + } + + @Test + public final void testFindCvnfcCustomizationInListNoNulls() { + String cvnfcCustomizationUuid = "a123"; + CvnfcCustomization cvnfc = new CvnfcCustomization(); + cvnfc.setModelCustomizationUUID("z789J"); + CvnfcCustomization cvnfc2 = new CvnfcCustomization(); + cvnfc2.setModelCustomizationUUID("a123"); + ArrayList<CvnfcCustomization> cvnfcs = new ArrayList<CvnfcCustomization>(); + cvnfcs.add(cvnfc); + cvnfcs.add(cvnfc2); + CvnfcCustomization aCvnfc = catalogDbClient.findCvnfcCustomizationInAList(cvnfcCustomizationUuid, cvnfcs); + assertTrue(aCvnfc.getModelCustomizationUUID().equals("a123")); + } +} diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/WorkflowRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/WorkflowRepositoryTest.java index 4f31e4b38c..7d1b8d0d96 100644 --- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/WorkflowRepositoryTest.java +++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/WorkflowRepositoryTest.java @@ -15,8 +15,6 @@ package org.onap.so.db.catalog.data.repository; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Assert; import org.junit.Test; @@ -33,7 +31,7 @@ public class WorkflowRepositoryTest extends BaseTest { public void findByArtifactUuid_ValidUuid_ExpectedOutput() throws Exception { Workflow workflow = workflowRepository.findByArtifactUUID("5b0c4322-643d-4c9f-b184-4516049e99b1"); - assertEquals("artifactName", "testingWorkflow", workflow.getArtifactName()); + assertEquals("artifactName", "testingWorkflow.bpmn", workflow.getArtifactName()); } @Test @@ -43,7 +41,17 @@ public class WorkflowRepositoryTest extends BaseTest { Assert.assertTrue(workflows != null); Assert.assertTrue(workflows.size() != 0); - Assert.assertTrue("testingWorkflow".equals(workflows.get(0).getArtifactName())); + Assert.assertTrue("testingWorkflow.bpmn".equals(workflows.get(0).getArtifactName())); + } + + @Test + public void findBySourceTest() throws Exception { + List<Workflow> workflows = workflowRepository.findBySource("sdc"); + + Assert.assertTrue(workflows != null); + Assert.assertTrue(workflows.size() != 0); + + Assert.assertTrue("testingWorkflow.bpmn".equals(workflows.get(0).getArtifactName())); } } diff --git a/mso-catalog-db/src/test/resources/data.sql b/mso-catalog-db/src/test/resources/data.sql index f6d04263c0..13ab018a27 100644 --- a/mso-catalog-db/src/test/resources/data.sql +++ b/mso-catalog-db/src/test/resources/data.sql @@ -266,18 +266,43 @@ VALUES ('DeleteVfModuleBB', 'VF_MODULE', 'DELETE'), ('DeleteNetworkBB', 'NETWORK', 'DELETE'), ('DeleteNetworkCollectionBB', 'NETWORK', 'DELETE'), -('AssignAndActivateVpnBondingLinksBB', 'CUSTOM', 'CUSTOM'), -('AvpnAssignServiceInstanceBB', 'CUSTOM', 'CUSTOM'), -('CreateCustomerVpnBindingBB', 'CUSTOM', 'CUSTOM'), -('SniroHoming', 'CUSTOM', 'CUSTOM'), -('DeactivateAndUnassignVpnBondingLinksBB', 'CUSTOM', 'CUSTOM'), -('DeactivateNetworkCollectionBB', 'CUSTOM', 'CUSTOM'), -('AAICheckVnfInMaintBB', 'CUSTOM', 'CUSTOM'), -('AAISetVnfInMaintBB', 'CUSTOM', 'CUSTOM'), -('AAIUnsetVnfInMaintBB', 'CUSTOM', 'CUSTOM'), -('SDNOVnfHealthCheckBB', 'CUSTOM', 'CUSTOM'), -('VNF-Macro-Replace', 'CUSTOM', 'CUSTOM'), -('HomingBB', 'CUSTOM', 'CUSTOM'); +('AssignAndActivateVpnBondingLinksBB', 'NO_VALIDATE', 'CUSTOM'), +('AvpnAssignServiceInstanceBB', 'NO_VALIDATE', 'CUSTOM'), +('CreateCustomerVpnBindingBB', 'NO_VALIDATE', 'CUSTOM'), +('SniroHoming', 'NO_VALIDATE', 'CUSTOM'), +('DeactivateAndUnassignVpnBondingLinksBB', 'NO_VALIDATE', 'CUSTOM'), +('DeactivateNetworkCollectionBB', 'NO_VALIDATE', 'CUSTOM'), +('AAICheckVnfInMaintBB', 'NO_VALIDATE', 'CUSTOM'), +('AAISetVnfInMaintBB', 'NO_VALIDATE', 'CUSTOM'), +('AAIUnsetVnfInMaintBB', 'NO_VALIDATE', 'CUSTOM'), +('SDNOVnfHealthCheckBB', 'NO_VALIDATE', 'CUSTOM'), +('VNF-Macro-Replace', 'NO_VALIDATE', 'CUSTOM'), +('HomingBB', 'NO_VALIDATE', 'CUSTOM'), +('VNFSetInMaintFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFCheckPserversLockedFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFCheckInMaintFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFCheckClosedLoopDisabledFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFSetClosedLoopDisabledFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUnsetClosedLoopDisabledFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFLockActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUnlockActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFStopActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFStartActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFSnapShotActivity', 'NO_VALIDATE', 'CUSTOM'), +('FlowCompleteActivity', 'NO_VALIDATE', 'CUSTOM'), +('PauseForManualTaskActivity', 'NO_VALIDATE', 'CUSTOM'), +('DistributeTrafficActivity', 'NO_VALIDATE', 'CUSTOM'), +('DistributeTrafficCheckActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFHealthCheckActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFQuiesceTrafficActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFResumeTrafficActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUnsetInMaintFlagActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUpgradeBackupActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUpgradePostCheckActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUpgradePreCheckActivity', 'NO_VALIDATE', 'CUSTOM'), +('VNFUpgradeSoftwareActivity', 'NO_VALIDATE', 'CUSTOM'), +('VnfInPlaceSoftwareUpdate', 'NO_VALIDATE', 'CUSTOM'); + INSERT INTO orchestration_flow_reference(COMPOSITE_ACTION, SEQ_NO, FLOW_NAME, FLOW_VERSION, NB_REQ_REF_LOOKUP_ID) VALUES ('Service-Create', '1', 'AssignServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'Service-Create')), @@ -644,15 +669,15 @@ VALUES ('VOLUME_GROUP', 'PENDING', 'DELETE', 'SILENT_SUCCESS'), ('VF_MODULE', 'PENDING', 'DELETE', 'FAIL'), ('NETWORK', 'PENDING', 'DELETE', 'FAIL'), -('CUSTOM', 'ACTIVE', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'ASSIGNED', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'CREATED', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'INVENTORIED', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'PENDING', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'PENDING_ACTIVATION', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'PENDING_CREATE', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'PENDING_DELETE', 'CUSTOM', 'CONTINUE'), -('CUSTOM', 'PRECREATED', 'CUSTOM', 'CONTINUE'); +('NO_VALIDATE', 'ACTIVE', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'ASSIGNED', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'CREATED', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'INVENTORIED', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'PENDING', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'PENDING_ACTIVATION', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'PENDING_CREATE', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'PENDING_DELETE', 'CUSTOM', 'CONTINUE'), +('NO_VALIDATE', 'PRECREATED', 'CUSTOM', 'CONTINUE'); INSERT INTO `cloudify_managers` (`ID`, `CLOUDIFY_URL`, `USERNAME`, `PASSWORD`, `VERSION`, `LAST_UPDATED_BY`, `CREATION_TIMESTAMP`, `UPDATE_TIMESTAMP`) VALUES ('mtn13', 'http://localhost:28090/v2.0', 'm93945', '93937EA01B94A10A49279D4572B48369', NULL, 'MSO_USER', '2018-07-17 14:05:08', '2018-07-17 14:05:08'); @@ -742,7 +767,7 @@ insert into pnf_resource_customization_to_service(service_model_uuid, resource_m ('5df8b6de-2083-11e7-93ae-92361f002676', '68dc9a92-214c-11e7-93ae-92361f002680'); insert into workflow(artifact_uuid, artifact_name, name, operation_name, version, description, body, resource_target, source) values -('5b0c4322-643d-4c9f-b184-4516049e99b1', 'testingWorkflow', 'testingWorkflow', 'create', 1, 'Test Workflow', null, 'vnf', 'sdc'); +('5b0c4322-643d-4c9f-b184-4516049e99b1', 'testingWorkflow.bpmn', 'testingWorkflow', 'create', 1, 'Test Workflow', null, 'vnf', 'sdc'); insert into vnf_resource_to_workflow(vnf_resource_model_uuid, workflow_id) values ('ff2ae348-214a-11e7-93ae-92361f002671', '1'); diff --git a/mso-catalog-db/src/test/resources/schema.sql b/mso-catalog-db/src/test/resources/schema.sql index 0856a4cbe2..7cd13a3780 100644 --- a/mso-catalog-db/src/test/resources/schema.sql +++ b/mso-catalog-db/src/test/resources/schema.sql @@ -803,7 +803,9 @@ CREATE TABLE `service` ( `WORKLOAD_CONTEXT` varchar(200) DEFAULT NULL, `SERVICE_CATEGORY` varchar(200) DEFAULT NULL, `RESOURCE_ORDER` varchar(200) default NULL, - OVERALL_DISTRIBUTION_STATUS varchar(45), + `OVERALL_DISTRIBUTION_STATUS` varchar(45), + `ONAP_GENERATED_NAMING` TINYINT(1) DEFAULT NULL, + `NAMING_POLICY` varchar(200) DEFAULT NULL, PRIMARY KEY (`MODEL_UUID`), KEY `fk_service__tosca_csar1_idx` (`TOSCA_CSAR_ARTIFACT_UUID`), CONSTRAINT `fk_service__tosca_csar1` FOREIGN KEY (`TOSCA_CSAR_ARTIFACT_UUID`) REFERENCES `tosca_csar` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE @@ -49,8 +49,7 @@ <sonar.cpd.exclusions>**/*</sonar.cpd.exclusions> <jacoco.version>0.7.5.201505241946</jacoco.version> <org.apache.maven.user-settings /> - <!-- TODO: update to version 1.4.0 for Dublin --> - <openstack.version>1.4.0-SNAPSHOT</openstack.version> + <openstack.version>1.5.0-SNAPSHOT</openstack.version> <maven.build.timestamp.format>yyyyMMdd'T'HHmm</maven.build.timestamp.format> <originalClassifier>original</originalClassifier> <docker.skip>true</docker.skip> diff --git a/project-configs/code-tools/onap-eclipse-format.xml b/project-configs/code-tools/onap-eclipse-format.xml index cd136171fa..093866afc5 100644 --- a/project-configs/code-tools/onap-eclipse-format.xml +++ b/project-configs/code-tools/onap-eclipse-format.xml @@ -30,7 +30,7 @@ <setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/> <setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/> <setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/> -<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="48"/> <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="0"/> <setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/> <setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/> @@ -194,7 +194,7 @@ <setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/> <setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/> <setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/> -<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="48"/> <setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/> <setting id="org.eclipse.jdt.core.formatter.wrap_before_assignment_operator" value="false"/> <setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/> @@ -310,4 +310,4 @@ <setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/> <setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/> </profile> -</profiles> +</profiles>
\ No newline at end of file diff --git a/vnfm-simulator/vnfm-service/pom.xml b/vnfm-simulator/vnfm-service/pom.xml index 380381f53b..c09c5f070a 100644 --- a/vnfm-simulator/vnfm-service/pom.xml +++ b/vnfm-simulator/vnfm-service/pom.xml @@ -1,149 +1,148 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>org.onap.so.vnfm</groupId> - <artifactId>vnfm-simulator</artifactId> - <version>1.4.0-SNAPSHOT</version> - </parent> - <artifactId>vnfm-service</artifactId> - <name>${project.artifactId}</name> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.so.vnfm</groupId> + <artifactId>vnfm-simulator</artifactId> + <version>1.4.0-SNAPSHOT</version> + </parent> + <artifactId>vnfm-service</artifactId> + <name>${project.artifactId}</name> - <properties> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <java.version>1.8</java.version> - <okhttp-version>2.7.5</okhttp-version> - <gson-version>2.8.1</gson-version> - </properties> - <dependencies> - <dependency> - <groupId>org.onap.so.adapters</groupId> - <artifactId>mso-vnfm-adapter-ext-clients</artifactId> - <version>${project.version}</version> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-web</artifactId> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-data-jpa</artifactId> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-actuator</artifactId> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-test</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-devtools</artifactId> - <scope>runtime</scope> - </dependency> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>io.swagger</groupId> - <artifactId>swagger-jaxrs</artifactId> - <version>1.5.0</version> - </dependency> - <dependency> - <groupId>org.apache.directory.studio</groupId> - <artifactId>org.apache.commons.io</artifactId> - <version>2.4</version> - </dependency> - <dependency> - <groupId>com.googlecode.json-simple</groupId> - <artifactId>json-simple</artifactId> - <version>1.1.1</version> - </dependency> + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <java.version>1.8</java.version> + <okhttp-version>2.7.5</okhttp-version> + <gson-version>2.8.1</gson-version> + </properties> + <dependencies> + <dependency> + <groupId>org.onap.so.adapters</groupId> + <artifactId>mso-vnfm-adapter-ext-clients</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-web</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-data-jpa</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-actuator</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-test</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-devtools</artifactId> + <scope>runtime</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>io.swagger</groupId> + <artifactId>swagger-jaxrs</artifactId> + <version>1.5.0</version> + </dependency> + <dependency> + <groupId>org.apache.directory.studio</groupId> + <artifactId>org.apache.commons.io</artifactId> + <version>2.4</version> + </dependency> + <dependency> + <groupId>com.googlecode.json-simple</groupId> + <artifactId>json-simple</artifactId> + <version>1.1.1</version> + </dependency> - <dependency> - <groupId>io.springfox</groupId> - <artifactId>springfox-swagger-ui</artifactId> - <version>2.6.1</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>io.springfox</groupId> - <artifactId>springfox-swagger2</artifactId> - <version>2.6.1</version> - <scope>compile</scope> - </dependency> - <dependency> - <groupId>com.fasterxml.jackson.core</groupId> - <artifactId>jackson-databind</artifactId> - <version>2.9.8</version> - </dependency> - <dependency> - <groupId>com.h2database</groupId> - <artifactId>h2</artifactId> - </dependency> - <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils --> - <dependency> - <groupId>commons-beanutils</groupId> - <artifactId>commons-beanutils</artifactId> - <version>1.9.3</version> - </dependency> - <dependency> - <groupId>org.modelmapper</groupId> - <artifactId>modelmapper</artifactId> - <version>2.3.0</version> - </dependency> - <dependency> - <groupId>com.squareup.okio</groupId> - <artifactId>okio</artifactId> - <version>1.13.0</version> - </dependency> - <dependency> - <groupId>com.squareup.okhttp</groupId> - <artifactId>okhttp</artifactId> - <version>${okhttp-version}</version> - </dependency> - <dependency> - <groupId>com.squareup.okhttp</groupId> - <artifactId>logging-interceptor</artifactId> - <version>${okhttp-version}</version> - </dependency> - <dependency> - <groupId>com.google.code.gson</groupId> - <artifactId>gson</artifactId> - <version>${gson-version}</version> - </dependency> - <dependency> - <groupId>org.onap.so</groupId> - <artifactId>common</artifactId> - <version>${project.version}</version> - </dependency> - </dependencies> - <build> - <plugins> - <plugin> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-maven-plugin</artifactId> - <version>${springboot.version}</version> - <configuration> - <mainClass>org.onap.svnfm.simulator.config.SvnfmApplication</mainClass> - </configuration> - <executions> - <execution> - <goals> - <goal>repackage</goal> - </goals> - </execution> - </executions> - </plugin> - <plugin> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-maven-plugin</artifactId> - </plugin> - </plugins> - </build> + <dependency> + <groupId>io.springfox</groupId> + <artifactId>springfox-swagger-ui</artifactId> + <version>2.6.1</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>io.springfox</groupId> + <artifactId>springfox-swagger2</artifactId> + <version>2.6.1</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-databind</artifactId> + <version>2.9.8</version> + </dependency> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + </dependency> + <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils --> + <dependency> + <groupId>commons-beanutils</groupId> + <artifactId>commons-beanutils</artifactId> + <version>1.9.3</version> + </dependency> + <dependency> + <groupId>org.modelmapper</groupId> + <artifactId>modelmapper</artifactId> + <version>2.3.0</version> + </dependency> + <dependency> + <groupId>com.squareup.okio</groupId> + <artifactId>okio</artifactId> + <version>1.13.0</version> + </dependency> + <dependency> + <groupId>com.squareup.okhttp</groupId> + <artifactId>okhttp</artifactId> + <version>${okhttp-version}</version> + </dependency> + <dependency> + <groupId>com.squareup.okhttp</groupId> + <artifactId>logging-interceptor</artifactId> + <version>${okhttp-version}</version> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>${gson-version}</version> + </dependency> + <dependency> + <groupId>org.onap.so</groupId> + <artifactId>common</artifactId> + <version>${project.version}</version> + </dependency> + </dependencies> + <build> + <plugins> + <plugin> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-maven-plugin</artifactId> + <version>${springboot.version}</version> + <configuration> + <mainClass>org.onap.svnfm.simulator.config.SvnfmApplication</mainClass> + </configuration> + <executions> + <execution> + <goals> + <goal>repackage</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-maven-plugin</artifactId> + </plugin> + </plugins> + </build> </project> |