diff options
344 files changed, 8797 insertions, 2496 deletions
diff --git a/adapters/mso-adapter-utils/pom.xml b/adapters/mso-adapter-utils/pom.xml index 7918072323..aa9a1cea9e 100644 --- a/adapters/mso-adapter-utils/pom.xml +++ b/adapters/mso-adapter-utils/pom.xml @@ -147,5 +147,10 @@ <artifactId>cxf-rt-transports-http</artifactId> <version>${cxf.version}</version> </dependency> + <dependency> + <groupId>org.onap.so</groupId> + <artifactId>mso-requests-db</artifactId> + <version>${project.version}</version> + </dependency> </dependencies> </project> diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java index f717144562..35c928c3b5 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/KeystoneV3Authentication.java @@ -72,9 +72,7 @@ public class KeystoneV3Authentication { OpenStackRequest<Token> v3Request = keystoneTenantClient.tokens().authenticate(v3Credentials); - KeystoneAuthHolder holder = makeRequest(v3Request, type, region); - - return holder; + return makeRequest(v3Request, type, region); } protected KeystoneAuthHolder makeRequest(OpenStackRequest<Token> v3Request, String type, String region) { diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java index 02ace5665d..072bf404e7 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/beans/DeploymentInfoBuilder.java @@ -72,22 +72,22 @@ public final class DeploymentInfoBuilder { this.errorMessage = execution.getError(); // Compute the status based on the last workflow - if (lastAction.equals("install")) { - if (actionStatus.equals("terminated")) { + if (("install").equals(lastAction)) { + if (("terminated").equals(actionStatus)) { this.deploymentStatus = DeploymentStatus.INSTALLED; - } else if (actionStatus.equals("failed")) { + } else if (("failed").equals(actionStatus)) { this.deploymentStatus = DeploymentStatus.FAILED; - } else if (actionStatus.equals("started") || actionStatus.equals("pending")) { + } else if (("started").equals(actionStatus) || ("pending").equals(actionStatus)) { this.deploymentStatus = DeploymentStatus.INSTALLING; } else { this.deploymentStatus = DeploymentStatus.UNKNOWN; } - } else if (lastAction.equals("uninstall")) { - if (actionStatus.equals("terminated")) { + } else if (("uninstall").equals(lastAction)) { + if (("terminated").equals(actionStatus)) { this.deploymentStatus = DeploymentStatus.CREATED; - } else if (actionStatus.equals("failed")) { + } else if (("failed").equals(actionStatus)) { this.deploymentStatus = DeploymentStatus.FAILED; - } else if (actionStatus.equals("started") || actionStatus.equals("pending")) { + } else if (("started").equals(actionStatus) || ("pending").equals(actionStatus)) { this.deploymentStatus = DeploymentStatus.UNINSTALLING; } else { this.deploymentStatus = DeploymentStatus.UNKNOWN; diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java index 5c2348dffa..2251575671 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/exceptions/MsoCloudifyWorkflowException.java @@ -38,8 +38,8 @@ public class MsoCloudifyWorkflowException extends MsoCloudifyException { super(0, "Workflow Exception", "Workflow " + workflowId + " failed on deployment " + deploymentId + ": " + message); this.workflowStatus = workflowStatus; - if (workflowStatus.equals("pending") || workflowStatus.equals("started") || workflowStatus.equals("cancelling") - || workflowStatus.equals("force_cancelling")) { + if (("pending").equals(workflowStatus) || ("started").equals(workflowStatus) + || ("cancelling").equals(workflowStatus) || ("force_cancelling").equals(workflowStatus)) { workflowStillRunning = true; } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java index 0a0f2787da..dd43837c76 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java @@ -109,6 +109,8 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin { private static final String DELETE_DEPLOYMENT = "DeleteDeployment"; private static final String TERMINATED = "terminated"; private static final String CANCELLED = "cancelled"; + private static final String UNINSTALL = "uninstall"; + private static final String UPLOAD_BLUEPRINT = "UPLOAD_BLUEPRINT"; // Fetch cloud configuration each time (may be cached in CloudConfig class) @Autowired @@ -181,11 +183,11 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin { Map<String, Object> expandedInputs = new HashMap<>(inputs); String platform = cloudSite.get().getPlatform(); - if (platform == null || platform.equals("") || platform.equalsIgnoreCase("OPENSTACK")) { + if (platform == null || platform.isEmpty() || ("OPENSTACK").equalsIgnoreCase(platform)) { // Create the Cloudify OpenstackConfig with the credentials OpenstackConfig openstackConfig = getOpenstackConfig(cloudSite.get(), tenantId); expandedInputs.put("openstack_config", openstackConfig); - } else if (platform.equalsIgnoreCase("AZURE")) { + } else if (("AZURE").equalsIgnoreCase(platform)) { // Create Cloudify AzureConfig with the credentials AzureConfig azureConfig = getAzureConfig(cloudSite.get(), tenantId); expandedInputs.put("azure_config", azureConfig); @@ -265,7 +267,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin { try { // Run the uninstall to undo the install - Execution uninstallWorkflow = executeWorkflow(cloudify, deploymentId, "uninstall", null, + Execution uninstallWorkflow = executeWorkflow(cloudify, deploymentId, UNINSTALL, null, pollForCompletion, deletePollTimeout, deletePollInterval); if (uninstallWorkflow.getStatus().equals(TERMINATED)) { @@ -306,7 +308,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin { try { // Run the uninstall to undo the install. // Always try to run it, as it should be idempotent - executeWorkflow(cloudify, deploymentId, "uninstall", null, pollForCompletion, deletePollTimeout, + executeWorkflow(cloudify, deploymentId, UNINSTALL, null, pollForCompletion, deletePollTimeout, deletePollInterval); // Delete the deployment itself @@ -402,7 +404,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin { GetExecution queryExecution = cloudify.executions().byId(executionId); command = "query"; - while (!timedOut && !(status.equals(TERMINATED) || status.equals("failed") || status.equals(CANCELLED))) { + while (!timedOut && !(status.equals(TERMINATED) || ("failed").equals(status) || status.equals(CANCELLED))) { // workflow is still running; check for timeout if (pollTimeout <= 0) { logger.debug("workflow {} timed out on deployment {}", execution.getWorkflowId(), @@ -425,7 +427,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin { // Success! logger.debug("Workflow '{}' completed successfully on deployment '{}'", workflowId, deploymentId); return execution; - } else if (status.equals("failed")) { + } else if (("failed").equals(status)) { // Workflow failed. Log it and return the execution object (don't throw exception here) logger.error("{} Cloudify workflow failure: {} {} Execute Workflow: Failed: {}", MessageEnum.RA_CREATE_STACK_ERR, execution.getError(), @@ -665,7 +667,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin { try { uninstallWorkflow = - executeWorkflow(cloudify, deploymentId, "uninstall", null, true, pollTimeout, deletePollInterval); + executeWorkflow(cloudify, deploymentId, UNINSTALL, null, true, pollTimeout, deletePollInterval); if (uninstallWorkflow.getStatus().equals(TERMINATED)) { // Successful uninstall. @@ -812,7 +814,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin { try { // Put the root directory - String rootDir = blueprintId + ((blueprintId.endsWith("/") ? "" : "/")); + String rootDir = blueprintId + (blueprintId.endsWith("/") ? "" : "/"); zipOut.putNextEntry(new ZipEntry(rootDir)); zipOut.closeEntry(); @@ -836,13 +838,13 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin { Blueprint blueprint = uploadRequest.execute(); logger.debug("Successfully uploaded blueprint {}", blueprint.getId()); } catch (CloudifyResponseException | CloudifyConnectException e) { - throw cloudifyExceptionToMsoException(e, "UPLOAD_BLUEPRINT"); + throw cloudifyExceptionToMsoException(e, UPLOAD_BLUEPRINT); } catch (RuntimeException e) { // Catch-all - throw runtimeExceptionToMsoException(e, "UPLOAD_BLUEPRINT"); + throw runtimeExceptionToMsoException(e, UPLOAD_BLUEPRINT); } catch (IOException e) { // for try-with-resources - throw ioExceptionToMsoException(e, "UPLOAD_BLUEPRINT"); + throw ioExceptionToMsoException(e, UPLOAD_BLUEPRINT); } return true; @@ -960,14 +962,14 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin { String type = templateParam.getParamType(); logger.debug("Parameter: {} is of type {}", templateParam.getParamName(), type); - if (type.equalsIgnoreCase("number")) { + if (("number").equalsIgnoreCase(type)) { try { return Integer.valueOf(inputValue.toString()); } catch (Exception e) { logger.debug("Unable to convert {} to an integer!", inputValue); return null; } - } else if (type.equalsIgnoreCase("json")) { + } else if (("json").equalsIgnoreCase(type)) { try { if (inputValue instanceof String) { return JSON_MAPPER.readTree(inputValue.toString()); @@ -978,7 +980,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin { logger.debug("Unable to convert {} to a JsonNode!", inputValue); return null; } - } else if (type.equalsIgnoreCase("boolean")) { + } else if (("boolean").equalsIgnoreCase(type)) { return new Boolean(inputValue.toString()); } 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 c9a548d5f1..79c042b10b 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 @@ -67,9 +67,6 @@ public class MsoCommonUtils { protected <T> T executeAndRecordOpenstackRequest(OpenStackRequest<T> request) { - int limit; - - long start = System.currentTimeMillis(); String requestType; if (request.getClass().getEnclosingClass() != null) { requestType = diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java index a21db78cee..723bed17f7 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java @@ -70,7 +70,7 @@ public class MsoHeatEnvironmentEntry { logger.debug("Exception:", e); this.valid = false; this.errorString = e.getMessage(); - // e.printStackTrace(); + } } @@ -173,7 +173,7 @@ public class MsoHeatEnvironmentEntry { // Basically give back the envt - but exclude the params that aren't in the HeatTemplate StringBuilder sb = new StringBuilder(); - ArrayList<String> paramNameList = new ArrayList<String>(params.size()); + ArrayList<String> paramNameList = new ArrayList<>(params.size()); for (HeatTemplateParam htp : params) { paramNameList.add(htp.getParamName()); } 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 b54301509f..8093f045eb 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 @@ -23,6 +23,7 @@ package org.onap.so.openstack.utils; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.woorea.openstack.base.client.OpenStackConnectException; @@ -47,6 +48,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.adapters.vdu.CloudInfo; import org.onap.so.adapters.vdu.PluginAction; import org.onap.so.adapters.vdu.VduArtifact; @@ -67,6 +69,9 @@ 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; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.HeatStatus; @@ -82,6 +87,7 @@ 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; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; @@ -100,6 +106,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { protected static final String HEAT_ERROR = "HeatError"; protected static final String CREATE_STACK = "CreateStack"; + public static final String FOUND = "Found: {}"; + public static final String EXCEPTION_ROLLING_BACK_STACK = + "{} Create Stack: Nested exception rolling back stack: {} "; + public static final String IN_PROGRESS = "in_progress"; // Fetch cloud configuration each time (may be cached in CloudConfig class) @Autowired @@ -117,6 +127,9 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { @Autowired private KeystoneV3Authentication keystoneV3Authentication; + @Autowired + RequestsDbClient requestDBClient; + private static final Logger logger = LoggerFactory.getLogger(MsoHeatUtils.class); // Properties names and variables (with default values) @@ -124,8 +137,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { private String deletePollIntervalProp = "org.onap.so.adapters.po.pollInterval"; private String deletePollTimeoutProp = "org.onap.so.adapters.po.pollTimeout"; - protected static final String createPollIntervalDefault = "15"; - private static final String deletePollIntervalDefault = "15"; + protected static final String CREATE_POLL_INTERVAL_DEFAULT = "15"; + private static final String DELETE_POLL_INTERVAL_DEFAULT = "15"; private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); @@ -226,17 +239,18 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { // Obtain the cloud site information where we will create the stack CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); - logger.debug("Found: {}", cloudSite); + 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(FOUND, heatClient); logger.debug("Ready to Create Stack ({}) with input params: {}", heatTemplate, stackInputs); Stack heatStack = null; 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())); @@ -272,11 +286,27 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { return new StackInfoMapper(heatStack).map(); } + private void saveStackRequest(OpenStackRequest<Stack> request, String requestId, String stackName) { + try { + ObjectMapper mapper = new ObjectMapper(); + InfraActiveRequests foundRequest = requestDBClient.getInfraActiveRequestbyRequestId(requestId); + String stackRequest = mapper.writeValueAsString(request.entity()); + CloudApiRequests cloudReq = new CloudApiRequests(); + cloudReq.setCloudIdentifier(stackName); + cloudReq.setRequestBody(stackRequest); + cloudReq.setRequestId(requestId); + 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, createPollIntervalDefault)); + Integer.parseInt(this.environment.getProperty(createPollIntervalProp, CREATE_POLL_INTERVAL_DEFAULT)); int pollTimeout = (timeoutMinutes * 60) + createPollInterval; int deletePollInterval = createPollInterval; int deletePollTimeout = pollTimeout; @@ -361,15 +391,14 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { } catch (Exception e3) { // Just log this one. We will report the original exception. - logger.error("{} Create Stack: Nested exception rolling back stack: {} ", - MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), - e3); + 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("{} Create Stack: Nested exception rolling back stack: {} ", - MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e2); + logger.error(EXCEPTION_ROLLING_BACK_STACK, MessageEnum.RA_CREATE_STACK_ERR, + ErrorCode.BusinessProcesssError.getValue(), e2); } } @@ -465,8 +494,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { } } catch (Exception e2) { // shouldn't happen - but handle - logger.error("{} Create Stack: Nested exception rolling back stack: {} ", - MessageEnum.RA_CREATE_STACK_ERR, ErrorCode.BusinessProcesssError.getValue(), e2); + logger.error(EXCEPTION_ROLLING_BACK_STACK, MessageEnum.RA_CREATE_STACK_ERR, + ErrorCode.BusinessProcesssError.getValue(), e2); } } MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString()); @@ -494,14 +523,14 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { // 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()); + 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()); + logger.debug(FOUND, heatClient.toString()); } } catch (MsoTenantNotFound e) { // Tenant doesn't exist, so stack doesn't either @@ -553,14 +582,14 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { // 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()); + 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()); + logger.debug(FOUND, heatClient.toString()); } } catch (MsoTenantNotFound e) { // Tenant doesn't exist, so stack doesn't either @@ -621,9 +650,9 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { // Set a timeout on polling int pollInterval = Integer - .parseInt(this.environment.getProperty(deletePollIntervalProp, "" + deletePollIntervalDefault)); + .parseInt(this.environment.getProperty(deletePollIntervalProp, "" + DELETE_POLL_INTERVAL_DEFAULT)); int pollTimeout = Integer - .parseInt(this.environment.getProperty(deletePollTimeoutProp, "" + deletePollIntervalDefault)); + .parseInt(this.environment.getProperty(deletePollTimeoutProp, "" + DELETE_POLL_INTERVAL_DEFAULT)); // When querying by canonical name, Openstack returns DELETE_COMPLETE status // instead of "404" (which would result from query by stack name). @@ -805,14 +834,14 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { // Obtain an MSO token for the tenant CloudIdentity cloudIdentity = cloudSite.getIdentityService(); - logger.debug("Found: {}", cloudIdentity.toString()); + 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; - Calendar expiration = null; + try { if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) { Keystone keystoneTenantClient = new Keystone(keystoneUrl); @@ -849,12 +878,12 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { throw new MsoAdapterException(error, e); } tokenId = access.getToken().getId(); - expiration = access.getToken().getExpires(); + } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) { try { KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "orchestration"); tokenId = holder.getId(); - expiration = holder.getexpiration(); + heatUrl = holder.getServiceUrl(); } catch (ServiceEndpointNotFoundException e) { // This comes back for not found (probably an incorrect region ID) @@ -1027,8 +1056,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { private String convertNode(final JsonNode node) { try { final Object obj = JSON_MAPPER.treeToValue(node, Object.class); - final String json = JSON_MAPPER.writeValueAsString(obj); - return json; + return JSON_MAPPER.writeValueAsString(obj); } catch (Exception e) { logger.debug("Error converting json to string {} ", e.getMessage(), e); } @@ -1321,19 +1349,19 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { * This helpful method added for Valet */ public String getCloudSiteKeystoneUrl(String cloudSiteId) throws MsoCloudSiteNotFound { - String keystone_url = null; + String keystoneUrl = null; try { CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); CloudIdentity cloudIdentity = cloudSite.getIdentityService(); - keystone_url = cloudIdentity.getIdentityUrl(); + keystoneUrl = cloudIdentity.getIdentityUrl(); } catch (Exception e) { throw new MsoCloudSiteNotFound(cloudSiteId); } - if (keystone_url == null || keystone_url.isEmpty()) { + if (keystoneUrl == null || keystoneUrl.isEmpty()) { throw new MsoCloudSiteNotFound(cloudSiteId); } - return keystone_url; + return keystoneUrl; } /* @@ -1550,7 +1578,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) { vduStatus.setState(VduStateType.INSTANTIATING); - vduStatus.setLastAction((new PluginAction("create", "in_progress", statusMessage))); + vduStatus.setLastAction((new PluginAction("create", IN_PROGRESS, statusMessage))); } else if (heatStatus == HeatStatus.NOTFOUND) { vduStatus.setState(VduStateType.NOTFOUND); } else if (heatStatus == HeatStatus.CREATED) { @@ -1561,10 +1589,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { vduStatus.setLastAction((new PluginAction("update", "complete", statusMessage))); } else if (heatStatus == HeatStatus.UPDATING) { vduStatus.setState(VduStateType.UPDATING); - vduStatus.setLastAction((new PluginAction("update", "in_progress", statusMessage))); + vduStatus.setLastAction((new PluginAction("update", IN_PROGRESS, statusMessage))); } else if (heatStatus == HeatStatus.DELETING) { vduStatus.setState(VduStateType.DELETING); - vduStatus.setLastAction((new PluginAction("delete", "in_progress", statusMessage))); + vduStatus.setLastAction((new PluginAction("delete", IN_PROGRESS, statusMessage))); } else if (heatStatus == HeatStatus.FAILED) { vduStatus.setState(VduStateType.FAILED); vduStatus.setErrorMessage(stackInfo.getStatusMessage()); 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 1bf780f6d3..a2e386adea 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 @@ -60,6 +60,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { private static final Logger logger = LoggerFactory.getLogger(MsoHeatUtilsWithUpdate.class); private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); + public static final String EXCEPTION = "Exception :"; @Autowired private Environment environment; @@ -221,8 +222,8 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { // Set a time limit on overall polling. // Use the resource (template) timeout for Openstack (expressed in minutes) // and add one poll interval to give Openstack a chance to fail on its own. - int createPollInterval = - Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault)); + int createPollInterval = Integer + .parseInt(this.environment.getProperty(createPollIntervalProp, CREATE_POLL_INTERVAL_DEFAULT)); int pollTimeout = (timeoutMinutes * 60) + createPollInterval; boolean loopAgain = true; @@ -335,7 +336,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { String str = JSON_MAPPER.writeValueAsString(obj); sb.append(str).append(" (a java.util.LinkedHashMap)"); } catch (Exception e) { - logger.debug("Exception :", e); + logger.debug(EXCEPTION, e); sb.append("(a LinkedHashMap value that would not convert nicely)"); } } else if (obj instanceof Integer) { @@ -343,7 +344,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { try { str = obj.toString() + " (an Integer)\n"; } catch (Exception e) { - logger.debug("Exception :", e); + logger.debug(EXCEPTION, e); str = "(an Integer unable to call .toString() on)"; } sb.append(str); @@ -352,7 +353,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { try { str = obj.toString() + " (an ArrayList)"; } catch (Exception e) { - logger.debug("Exception :", e); + logger.debug(EXCEPTION, e); str = "(an ArrayList unable to call .toString() on?)"; } sb.append(str); @@ -361,7 +362,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { try { str = obj.toString() + " (a Boolean)"; } catch (Exception e) { - logger.debug("Exception :", e); + logger.debug(EXCEPTION, e); str = "(an Boolean unable to call .toString() on?)"; } sb.append(str); @@ -370,7 +371,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { try { str = obj.toString() + " (unknown Object type)"; } catch (Exception e) { - logger.debug("Exception :", e); + logger.debug(EXCEPTION, e); str = "(a value unable to call .toString() on?)"; } sb.append(str); @@ -384,8 +385,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { private String convertNodeWithUpdate(final JsonNode node) { try { final Object obj = JSON_MAPPER.treeToValue(node, Object.class); - final String json = JSON_MAPPER.writeValueAsString(obj); - return json; + return JSON_MAPPER.writeValueAsString(obj); } catch (Exception e) { logger.debug("Error converting json to string {} ", e.getMessage(), e); } 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 cfc8c23c5f..ab93a6c4c6 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 @@ -58,6 +58,7 @@ import org.springframework.stereotype.Component; @Component public class MsoKeystoneUtils extends MsoTenantUtils { + public static final String DELETE_TENANT = "Delete Tenant"; private static Logger logger = LoggerFactory.getLogger(MsoKeystoneUtils.class); @Autowired @@ -207,7 +208,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { return null; } - Map<String, String> metadata = new HashMap<String, String>(); + Map<String, String> metadata = new HashMap<>(); if (cloudSite.getIdentityService().getTenantMetadata()) { OpenStackRequest<Metadata> request = keystoneAdminClient.tenants().showMetadata(tenant.getId()); Metadata tenantMetadata = executeAndRecordOpenstackRequest(request); @@ -252,7 +253,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { return null; } - Map<String, String> metadata = new HashMap<String, String>(); + Map<String, String> metadata = new HashMap<>(); if (cloudSite.getIdentityService().getTenantMetadata()) { OpenStackRequest<Metadata> request = keystoneAdminClient.tenants().showMetadata(tenant.getId()); Metadata tenantMetadata = executeAndRecordOpenstackRequest(request); @@ -304,10 +305,10 @@ public class MsoKeystoneUtils extends MsoTenantUtils { logger.debug("Deleted Tenant {} ({})", tenant.getId(), tenant.getName()); } catch (OpenStackBaseException e) { // Convert Keystone OpenStackResponseException to MsoOpenstackException - throw keystoneErrorToMsoException(e, "Delete Tenant"); + throw keystoneErrorToMsoException(e, DELETE_TENANT); } catch (RuntimeException e) { // Catch-all - throw runtimeExceptionToMsoException(e, "DeleteTenant"); + throw runtimeExceptionToMsoException(e, DELETE_TENANT); } return true; @@ -354,10 +355,10 @@ public class MsoKeystoneUtils extends MsoTenantUtils { } catch (OpenStackBaseException e) { // Note: It doesn't seem to matter if tenant doesn't exist, no exception is thrown. // Convert Keystone OpenStackResponseException to MsoOpenstackException - throw keystoneErrorToMsoException(e, "DeleteTenant"); + throw keystoneErrorToMsoException(e, DELETE_TENANT); } catch (RuntimeException e) { // Catch-all - throw runtimeExceptionToMsoException(e, "DeleteTenant"); + throw runtimeExceptionToMsoException(e, DELETE_TENANT); } return true; @@ -379,7 +380,6 @@ public class MsoKeystoneUtils extends MsoTenantUtils { public Keystone getKeystoneAdminClient(CloudSite cloudSite) throws MsoException { CloudIdentity cloudIdentity = cloudSite.getIdentityService(); - String cloudId = cloudIdentity.getId(); String adminTenantName = cloudIdentity.getAdminTenant(); String region = cloudSite.getRegionId(); 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 e16bf90d4d..1db0411f7c 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 @@ -339,7 +339,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { workloadStack = JSON_MAPPER.treeToValue(node.at("/stacks/0"), Stack.class); } else { workloadStack = new Stack(); - workloadStack.setStackStatus(HeatStatus.NOTFOUND.toString()); + workloadStack.setStackStatus("NOT_FOUND"); } } catch (Exception e) { logger.debug("Multicloud Get Exception mapping /stack/0: {} ", node.toString(), e); @@ -467,7 +467,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { } int updatePollInterval = - Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault)); + Integer.parseInt(this.environment.getProperty(createPollIntervalProp, CREATE_POLL_INTERVAL_DEFAULT)); int pollTimeout = (timeoutMinutes * 60) + updatePollInterval; boolean updateTimedOut = false; logger.debug("updatePollInterval=" + updatePollInterval + ", pollTimeout=" + pollTimeout); @@ -535,8 +535,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { // Use the resource (template) timeout for Openstack (expressed in minutes) // and add one poll interval to give Openstack a chance to fail on its own.s - int createPollInterval = - Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault)); + int createPollInterval = Integer + .parseInt(this.environment.getProperty(createPollIntervalProp, CREATE_POLL_INTERVAL_DEFAULT)); int pollTimeout = (timeoutMinutes * 60) + createPollInterval; // New 1610 - poll on delete if we rollback - use same values for now int deletePollInterval = createPollInterval; 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 78db27f65e..6f08afc55f 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 @@ -373,7 +373,7 @@ public class MsoNeutronUtils extends MsoCommonUtils { final String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity); String neutronUrl = null; String tokenId = null; - Calendar expiration = null; + try { if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) { Keystone keystoneTenantClient = new Keystone(keystoneUrl); @@ -396,12 +396,12 @@ public class MsoNeutronUtils extends MsoCommonUtils { throw new MsoAdapterException(error, e); } tokenId = access.getToken().getId(); - expiration = access.getToken().getExpires(); + } else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) { try { KeystoneAuthHolder holder = keystoneV3Authentication.getToken(cloudSite, tenantId, "network"); tokenId = holder.getId(); - expiration = holder.getexpiration(); + neutronUrl = holder.getServiceUrl(); if (!neutronUrl.endsWith("/")) { neutronUrl += "/v2.0/"; diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java index 0541a8f51b..9ee8a09ea6 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java @@ -40,6 +40,7 @@ import org.yaml.snakeyaml.Yaml; public class MsoYamlEditorWithEnvt { private static final Logger logger = LoggerFactory.getLogger(MsoYamlEditorWithEnvt.class); + public static final String EXCEPTION = "Exception:"; private Map<String, Object> yml; private Yaml yaml = new Yaml(); @@ -68,7 +69,7 @@ public class MsoYamlEditorWithEnvt { try { resourceMap = (Map<String, Object>) yml.get("parameters"); } catch (Exception e) { - logger.debug("Exception:", e); + logger.debug(EXCEPTION, e); return paramSet; } if (resourceMap == null) { @@ -89,7 +90,7 @@ public class MsoYamlEditorWithEnvt { try { value = JSON_MAPPER.writeValueAsString(obj); } catch (Exception e) { - logger.debug("Exception:", e); + logger.debug(EXCEPTION, e); value = "_BAD_JSON_MAPPING"; } } else { @@ -118,7 +119,7 @@ public class MsoYamlEditorWithEnvt { } return resourceList; } catch (Exception e) { - logger.debug("Exception:", e); + logger.debug(EXCEPTION, e); } return null; } @@ -137,7 +138,7 @@ public class MsoYamlEditorWithEnvt { try { value = resourceEntry.get("default"); } catch (ClassCastException cce) { - logger.debug("Exception:", cce); + logger.debug(EXCEPTION, cce); // This exception only - the value is an integer. For what we're doing // here - we don't care - so set value to something - and it will // get marked as not being required - which is correct. diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java index a4cdba22a1..16671bbe50 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateHeatResponse.java @@ -31,7 +31,7 @@ import org.apache.commons.lang.builder.ToStringBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "links"}) public class MulticloudCreateHeatResponse implements Serializable { - private final static long serialVersionUID = -5215028275577848311L; + private static final long serialVersionUID = -5215028275577848311L; @JsonProperty("id") private String id; diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java index e8a5b1480e..1f55aa92a2 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateLinkResponse.java @@ -31,7 +31,7 @@ import org.apache.commons.lang.builder.ToStringBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"href", "rel"}) public class MulticloudCreateLinkResponse implements Serializable { - private final static long serialVersionUID = -5215028275577848311L; + private static final long serialVersionUID = -5215028275577848311L; @JsonProperty("href") private String href; 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 bb15e58c88..fc08201bcb 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 @@ -30,7 +30,7 @@ import org.apache.commons.lang.builder.ToStringBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"template_type", "workload_id", "template_response"}) public class MulticloudCreateResponse implements Serializable { - private final static long serialVersionUID = -5215028275577848311L; + private static final long serialVersionUID = -5215028275577848311L; @JsonProperty("template_type") private String templateType; diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java index 67cb73539d..67d1cbff4e 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudCreateStackResponse.java @@ -30,7 +30,7 @@ import org.apache.commons.lang.builder.ToStringBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"stack"}) public class MulticloudCreateStackResponse implements Serializable { - private final static long serialVersionUID = -5215028275577848311L; + private static final long serialVersionUID = -5215028275577848311L; @JsonProperty("stack") private MulticloudCreateHeatResponse stack; diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java index a22937aea3..ad37b39f30 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java @@ -31,7 +31,7 @@ import org.apache.commons.lang.builder.ToStringBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"template_type", "workload_id", "workload_status", "workload_status_reason"}) public class MulticloudQueryResponse implements Serializable { - private final static long serialVersionUID = -5215028275577848311L; + private static final long serialVersionUID = -5215028275577848311L; @JsonProperty("template_type") private String templateType; diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java index b733552a2b..95dd48caa6 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java @@ -33,7 +33,7 @@ import org.apache.commons.lang.builder.ToStringBuilder; "vf-module-model-customization-id", "oof_directives", "sdnc_directives", "user_directives", "template_type", "template_data"}) public class MulticloudRequest implements Serializable { - private final static long serialVersionUID = -5215028275577848311L; + private static final long serialVersionUID = -5215028275577848311L; @JsonProperty("generic-vnf-id") private String genericVnfId; diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfResponseCommon.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfResponseCommon.java index 23bbbb3f43..7a2d4ec3e1 100644 --- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfResponseCommon.java +++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfResponseCommon.java @@ -24,6 +24,8 @@ package org.onap.so.adapters.vnfrest; import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.HashMap; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import com.fasterxml.jackson.databind.ObjectMapper; @@ -71,7 +73,7 @@ public abstract class VfResponseCommon { public String toXmlString() { try { ByteArrayOutputStream bs = new ByteArrayOutputStream(); - JAXBContext context = JAXBContext.newInstance(this.getClass()); + JAXBContext context = JAXBContext.newInstance(this.getClass(), ArrayList.class, HashMap.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // pretty print XML marshaller.marshal(this, bs); 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 d20d2b7758..0327fd67a3 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 @@ -20,9 +20,16 @@ package org.onap.so.openstack.mappers; +import java.util.List; +import java.util.Map; import javax.xml.bind.annotation.XmlElement; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; public class MapElements { + private static final Logger logger = LoggerFactory.getLogger(MapElements.class); @XmlElement public String key; @XmlElement @@ -32,6 +39,21 @@ public class MapElements { public MapElements(String key, Object value) { this.key = key; - this.value = value; + // this is required to handle marshalling raw json + // always write values as strings for XML + if (value != null) { + if (value instanceof List || value instanceof Map) { + try { + this.value = new ObjectMapper().writeValueAsString(value); + } catch (JsonProcessingException e) { + logger.warn("could not marshal value to json, calling toString"); + this.value = value.toString(); + } + } else { + this.value = value; + } + } else { + this.value = value; + } } } diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/StackInfoMapper.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/StackInfoMapper.java index 8efa48ce79..d830e706f7 100644 --- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/StackInfoMapper.java +++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/openstack/mappers/StackInfoMapper.java @@ -95,5 +95,6 @@ public class StackInfoMapper { heatStatusMap.put("UPDATE_IN_PROGRESS", HeatStatus.UPDATING); heatStatusMap.put("UPDATE_FAILED", HeatStatus.FAILED); heatStatusMap.put("UPDATE_COMPLETE", HeatStatus.UPDATED); + heatStatusMap.put("NOT_FOUND", HeatStatus.NOTFOUND); } } 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 8d27e54892..189d4cca3e 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 @@ -24,17 +24,19 @@ import static org.junit.Assert.assertEquals; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; +import java.util.Arrays; 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 { @Test - public void xmlMarshalTest() throws IOException, JAXBException { + public void xmlUnMarshalTest() throws IOException, JAXBException { JAXBContext context = JAXBContext.newInstance(CreateVfModuleRequest.class); CreateVfModuleRequest request = (CreateVfModuleRequest) context.createUnmarshaller().unmarshal( @@ -43,6 +45,20 @@ public class JAXBMarshallingTest { assertEquals("ubuntu-16-04-cloud-amd64", request.getVfModuleParams().get("vcpe_image_name")); assertEquals("10.2.0.0/24", request.getVfModuleParams().get("cpe_public_net_cidr")); assertEquals("", request.getVfModuleParams().get("workload_context")); + assertEquals("[\"a\",\"b\",\"c\"]", request.getVfModuleParams().get("raw-json-param")); + } + + @Test + public void xmlMarshalTest() throws IOException, JAXBException { + + CreateVfModuleRequest request = new CreateVfModuleRequest(); + request.getVfModuleParams().put("test-null", null); + request.getVfModuleParams().put("test array", Arrays.asList("a", "b", "c")); + + assertEquals("documents are equal", + new String(Files + .readAllBytes(Paths.get("src/test/resources/VfRequest-marshalled-with-complex-object.xml"))), + 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 new file mode 100644 index 0000000000..ce175127df --- /dev/null +++ b/adapters/mso-adapters-rest-interface/src/test/resources/VfRequest-marshalled-with-complex-object.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<createVfModuleRequest> + <failIfExists>false</failIfExists> + <backout>true</backout> + <vfModuleParams> + <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-null</key> + </entry> + </vfModuleParams> + <msoRequest/> +</createVfModuleRequest> diff --git a/adapters/mso-adapters-rest-interface/src/test/resources/createVfModuleRequest-with-params.xml b/adapters/mso-adapters-rest-interface/src/test/resources/createVfModuleRequest-with-params.xml index 1ff24a50f6..2718f1df61 100644 --- a/adapters/mso-adapters-rest-interface/src/test/resources/createVfModuleRequest-with-params.xml +++ b/adapters/mso-adapters-rest-interface/src/test/resources/createVfModuleRequest-with-params.xml @@ -1,4 +1,4 @@ -<createVfModuleRequest> + <createVfModuleRequest> <cloudSiteId>RegionOne</cloudSiteId> <cloudOwner>CloudOwner</cloudOwner> <tenantId>09d8566ea45e43aa974cf447ed591d77</tenantId> @@ -196,7 +196,10 @@ <key>vf_module_index</key> <value>0</value> </entry> - + <entry> + <key>raw-json-param</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> </vfModuleParams> <msoRequest> <requestId>11c8ec20-a1f8-4aa2-926f-e55d67a30f8b</requestId> diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java index db73d4afec..0e526e59fb 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java @@ -24,6 +24,7 @@ import javax.annotation.PostConstruct; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; import org.onap.so.adapters.catalogdb.rest.CatalogDbAdapterRest; +import org.onap.so.adapters.catalogdb.rest.ServiceRestImpl; import org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging; import org.springframework.context.annotation.Configuration; import io.swagger.jaxrs.config.BeanConfig; @@ -40,6 +41,7 @@ public class JerseyConfiguration extends ResourceConfig { register(ApiListingResource.class); register(SwaggerSerializers.class); register(JaxRsFilterLogging.class); + register(ServiceRestImpl.class); BeanConfig beanConfig = new BeanConfig(); beanConfig.setVersion("1.0.2"); beanConfig.setSchemes(new String[] {"http"}); diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryAllottedResourceCustomization.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryAllottedResourceCustomization.java index e550394931..c1acc319f7 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryAllottedResourceCustomization.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryAllottedResourceCustomization.java @@ -104,7 +104,7 @@ public class QueryAllottedResourceCustomization extends CatalogQuery { first = false; - boolean arNull = o.getAllottedResource() == null ? true : false; + boolean arNull = o.getAllottedResource() == null; put(valueMap, "MODEL_NAME", arNull ? null : o.getAllottedResource().getModelName()); put(valueMap, "MODEL_UUID", arNull ? null : o.getAllottedResource().getModelUUID()); diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryGroups.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryGroups.java new file mode 100644 index 0000000000..c15b0d9df1 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryGroups.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.adapters.catalogdb.catalogrest; + +import org.onap.so.db.catalog.beans.InstanceGroup; +import org.onap.so.db.catalog.beans.VFCInstanceGroup; +import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@XmlRootElement(name = "groups") +public class QueryGroups extends CatalogQuery { + + private List<VnfcInstanceGroupCustomization> vnfcInstanceGroupCustomizations; + private static final String TEMPLATE = "\n" + "\t{ \"modelInfo\" : {\n" + + "\t\t\"modelName\" : <MODEL_NAME>,\n" + "\t\t\"modelUuid\" : <MODEL_UUID>,\n" + + "\t\t\"modelInvariantUuid\" : <MODEL_INVARIANT_ID>,\n" + + "\t\t\"modelVersion\" : <MODEL_VERSION>\n" + "\t\t},\n" + "<_VNFCS_>\n" + "\t}"; + + public QueryGroups() { + super(); + vnfcInstanceGroupCustomizations = new ArrayList<>(); + + } + + public QueryGroups(List<VnfcInstanceGroupCustomization> vnfcInstanceGroupCustomizations) { + this.vnfcInstanceGroupCustomizations = new ArrayList<>(); + if (vnfcInstanceGroupCustomizations != null) { + for (VnfcInstanceGroupCustomization g : vnfcInstanceGroupCustomizations) { + if (logger.isDebugEnabled()) { + logger.debug(g.toString()); + } + this.vnfcInstanceGroupCustomizations.add(g); + } + } + } + + @Override + public String JSON2(boolean isArray, boolean isEmbed) { + StringBuilder sb = new StringBuilder(); + if (!isEmbed && isArray) + sb.append("{ "); + if (isArray) + sb.append("\"groups\": ["); + Map<String, String> valueMap = new HashMap<>(); + String sep = ""; + boolean first = true; + + for (VnfcInstanceGroupCustomization o : vnfcInstanceGroupCustomizations) { + if (first) + sb.append("\n"); + first = false; + + boolean vnfcCustomizationNull = o.getVnfcCustomizations() == null; + InstanceGroup instanceGroup = o.getInstanceGroup(); + + if (instanceGroup != null) { + put(valueMap, "MODEL_NAME", instanceGroup.getModelName()); + put(valueMap, "MODEL_UUID", instanceGroup.getModelInvariantUUID()); + put(valueMap, "MODEL_INVARIANT_ID", instanceGroup.getModelInvariantUUID()); + put(valueMap, "MODEL_VERSION", instanceGroup.getModelUUID()); + } + + String subItem = new QueryVnfcs(vnfcCustomizationNull ? null : o.getVnfcCustomizations()).JSON2(true, true); + valueMap.put("_VNFCS_", subItem.replaceAll("(?m)^", "\t\t")); + sb.append(sep).append(this.setTemplate(TEMPLATE, valueMap)); + sep = ",\n"; + } + if (!first) + sb.append("\n"); + if (isArray) + sb.append("]"); + if (!isEmbed && isArray) + sb.append("}"); + return sb.toString(); + } +} diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceNetworks.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceNetworks.java index 96ea797631..5573b23a8d 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceNetworks.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceNetworks.java @@ -104,7 +104,7 @@ public class QueryServiceNetworks extends CatalogQuery { if (first) sb.append("\n"); first = false; - boolean nrNull = o.getNetworkResource() == null ? true : false; + boolean nrNull = o.getNetworkResource() == null; put(valueMap, "MODEL_NAME", nrNull ? null : o.getNetworkResource().getModelName()); put(valueMap, "MODEL_UUID", nrNull ? null : o.getNetworkResource().getModelUUID()); put(valueMap, "MODEL_INVARIANT_ID", nrNull ? null : o.getNetworkResource().getModelInvariantUUID()); diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceVnfs.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceVnfs.java index b1bdeda445..a0d822d394 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceVnfs.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceVnfs.java @@ -25,8 +25,12 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import javax.xml.bind.annotation.XmlRootElement; +import org.onap.so.db.catalog.beans.InstanceGroup; +import org.onap.so.db.catalog.beans.VFCInstanceGroup; import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,7 +49,8 @@ public class QueryServiceVnfs extends CatalogQuery { + "\t\"nfFunction\" : <NF_FUNCTION>,\n" + "\t\"nfType\" : <NF_TYPE>,\n" + "\t\"nfRole\" : <NF_ROLE>,\n" + "\t\"nfNamingCode\" : <NF_NAMING_CODE>,\n" + "\t\"multiStageDesign\" : <MULTI_STEP_DESIGN>,\n" - + "\t\"resourceInput\" : <RESOURCE_INPUT>,\n" + "<_VFMODULES_>\n" + "\t}"; + + "\t\"vnfcInstGroupOrder\" : <VNFC_INSTANCE_GROUP_ORDER>,\n" + + "\t\"resourceInput\" : <RESOURCE_INPUT>,\n" + "<_VFMODULES_>,\n" + "<_GROUPS_>\n" + "\t}"; public QueryServiceVnfs() { super(); @@ -101,7 +106,7 @@ public class QueryServiceVnfs extends CatalogQuery { sb.append("\n"); first = false; - boolean vrNull = o.getVnfResources() == null ? true : false; + boolean vrNull = o.getVnfResources() == null; put(valueMap, "MODEL_NAME", vrNull ? null : o.getVnfResources().getModelName()); put(valueMap, "MODEL_UUID", vrNull ? null : o.getVnfResources().getModelUUID()); @@ -114,12 +119,19 @@ public class QueryServiceVnfs extends CatalogQuery { put(valueMap, "NF_TYPE", o.getNfType()); put(valueMap, "NF_ROLE", o.getNfRole()); put(valueMap, "NF_NAMING_CODE", o.getNfNamingCode()); + put(valueMap, "VNFC_INSTANCE_GROUP_ORDER", o.getVnfcInstanceGroupOrder()); put(valueMap, "MULTI_STEP_DESIGN", o.getMultiStageDesign()); put(valueMap, "RESOURCE_INPUT", o.getResourceInput()); String subitem = new QueryVfModule(vrNull ? null : o.getVfModuleCustomizations()).JSON2(true, true); valueMap.put("_VFMODULES_", subitem.replaceAll("(?m)^", "\t\t")); + List<VnfcInstanceGroupCustomization> vnfcInstanceGroupCustomizations = + o.getVnfcInstanceGroupCustomizations(); + + String grpSubItem = new QueryGroups(vrNull ? null : vnfcInstanceGroupCustomizations).JSON2(true, true); + valueMap.put("_GROUPS_", grpSubItem.replaceAll("(?m)^", "\t\t")); + sb.append(sep).append(this.setTemplate(TEMPLATE, valueMap)); sep = ",\n"; } diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModule.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModule.java index 1dec9cecae..1604e99a72 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModule.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVfModule.java @@ -97,7 +97,7 @@ public class QueryVfModule extends CatalogQuery { sb.append("\n"); first = false; - boolean vfNull = o.getVfModule() == null ? true : false; + boolean vfNull = o.getVfModule() == null; boolean hasVolumeGroup = false; HeatEnvironment envt = o.getVolumeHeatEnv(); if (envt != null) { @@ -109,10 +109,10 @@ public class QueryVfModule extends CatalogQuery { put(valueMap, "MODEL_INVARIANT_ID", vfNull ? null : o.getVfModule().getModelInvariantUUID()); put(valueMap, "MODEL_VERSION", vfNull ? null : o.getVfModule().getModelVersion()); put(valueMap, "MODEL_CUSTOMIZATION_UUID", o.getModelCustomizationUUID()); - put(valueMap, "IS_BASE", vfNull ? false : o.getVfModule().getIsBase() ? true : false); + put(valueMap, "IS_BASE", !vfNull && (o.getVfModule().getIsBase())); put(valueMap, "VF_MODULE_LABEL", o.getLabel()); put(valueMap, "INITIAL_COUNT", o.getInitialCount()); - put(valueMap, "HAS_VOLUME_GROUP", new Boolean(hasVolumeGroup)); + put(valueMap, "HAS_VOLUME_GROUP", hasVolumeGroup); sb.append(sep).append(this.setTemplate(TEMPLATE, valueMap)); sep = ",\n"; diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVnfcs.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVnfcs.java new file mode 100644 index 0000000000..dc73fe904d --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVnfcs.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.adapters.catalogdb.catalogrest; + +import org.onap.so.db.catalog.beans.VnfcCustomization; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@XmlRootElement(name = "vnfcs") +public class QueryVnfcs extends CatalogQuery { + private List<VnfcCustomization> vnfcCustomizations; + private static final String TEMPLATE = + "\t{\n" + "\t\t\"modelInfo\" : { \n" + "\t\t\t\"modelName\" : <MODEL_NAME>,\n" + + "\t\t\t\"modelUuid\" : <MODEL_UUID>,\n" + + "\t\t\t\"modelInvariantUuid\" : <MODEL_INVARIANT_ID>,\n" + + "\t\t\t\"modelVersion\" : <MODEL_VERSION>,\n" + + "\t\t\t\"modelCustomizationUuid\" : <MODEL_CUSTOMIZATION_UUID>\n" + "\t\t},\n" + + "\t\t\"resourceInput\" : <RESOURCE_INPUT>\n" + "\t}"; + + public QueryVnfcs() { + super(); + vnfcCustomizations = new ArrayList(); + } + + public QueryVnfcs(List<VnfcCustomization> vnfcCustomizations) { + this.vnfcCustomizations = new ArrayList(); + if (vnfcCustomizations != null) { + for (VnfcCustomization vnfcCustomization : vnfcCustomizations) { + if (logger.isDebugEnabled()) { + logger.debug(vnfcCustomization.toString()); + } + this.vnfcCustomizations.add(vnfcCustomization); + } + } + } + + public List<VnfcCustomization> getVnfcCustomizations() { + return vnfcCustomizations; + } + + public void setVnfcCustomizations(List<VnfcCustomization> vnfcCustomizations) { + this.vnfcCustomizations = vnfcCustomizations; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + boolean first = true; + int i = 1; + for (VnfcCustomization o : vnfcCustomizations) { + sb.append(i).append("\t"); + if (!first) { + sb.append("\n"); + } + first = false; + sb.append(o); + } + return sb.toString(); + } + + @Override + public String JSON2(boolean isArray, boolean isEmbed) { + StringBuilder sb = new StringBuilder(); + if (!isEmbed && isArray) { + sb.append("{"); + } + + if (isArray) { + sb.append("\"vnfcs\": ["); + } + + Map<String, String> valueMap = new HashMap<>(); + String sep = ""; + boolean first = true; + + for (VnfcCustomization o : vnfcCustomizations) { + if (first) + sb.append("\n"); + first = false; + + put(valueMap, "MODEL_NAME", o.getModelName()); + put(valueMap, "MODEL_UUID", o.getModelUUID()); + put(valueMap, "MODEL_INVARIANT_ID", o.getModelInvariantUUID()); + put(valueMap, "MODEL_VERSION", o.getModelVersion()); + put(valueMap, "MODEL_CUSTOMIZATION_UUID", o.getModelCustomizationUUID()); + put(valueMap, "RESOURCE_INPUT", o.getResourceInput()); + + sb.append(sep).append(this.setTemplate(TEMPLATE, valueMap)); + sep = ",\n"; + } + if (!first) + sb.append("\n"); + if (isArray) + sb.append("]"); + if (!isEmbed && isArray) + sb.append("}"); + return sb.toString(); + } +} diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java index 6cc53e6ec9..589f119337 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java @@ -279,6 +279,7 @@ public class CatalogDbAdapterRest { @QueryParam("serviceModelUuid") String modelUUID, @QueryParam("serviceModelInvariantUuid") String modelInvariantUUID, @QueryParam("serviceModelVersion") String modelVersion) { + QueryServiceMacroHolder qryResp; int respStatus = HttpStatus.SC_OK; String uuid = ""; diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceMapper.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceMapper.java new file mode 100644 index 0000000000..dd18767762 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceMapper.java @@ -0,0 +1,128 @@ +/*- + * ============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.adapters.catalogdb.rest; + +import java.util.ArrayList; +import java.util.List; +import org.onap.so.db.catalog.beans.HeatEnvironment; +import org.onap.so.db.catalog.beans.VfModuleCustomization; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.rest.catalog.beans.Service; +import org.onap.so.rest.catalog.beans.VfModule; +import org.onap.so.rest.catalog.beans.Vnf; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + + +@Component +public class ServiceMapper { + private static final Logger logger = LoggerFactory.getLogger(ServiceMapper.class); + + public Service mapService(org.onap.so.db.catalog.beans.Service service, int depth) { + Service restService = new Service(); + restService.setCategory(service.getCategory()); + restService.setCreated(service.getCreated()); + restService.setDescription(service.getDescription()); + restService.setDistrobutionStatus(service.getDistrobutionStatus()); + restService.setEnvironmentContext(service.getEnvironmentContext()); + restService.setModelInvariantId(service.getModelInvariantUUID()); + restService.setModelName(service.getModelName()); + restService.setModelVersionId(service.getModelUUID()); + restService.setModelVersion(service.getModelVersion()); + restService.setServiceRole(service.getServiceRole()); + restService.setServiceType(service.getServiceType()); + restService.setWorkloadContext(service.getWorkloadContext()); + if (depth > 0) + restService.setVnf(mapVnfs(service, depth)); + return restService; + } + + private List<Vnf> mapVnfs(org.onap.so.db.catalog.beans.Service service, int depth) { + List<Vnf> vnfs = new ArrayList<>(); + logger.info("Vnf Count : {}", service.getVnfCustomizations().size()); + service.getVnfCustomizations().parallelStream().forEach(vnf -> vnfs.add(mapVnf(vnf, depth))); + return vnfs; + } + + private Vnf mapVnf(org.onap.so.db.catalog.beans.VnfResourceCustomization vnfResourceCustomization, int depth) { + Vnf vnf = new Vnf(); + vnf.setAvailabilityZoneMaxCount(vnfResourceCustomization.getAvailabilityZoneMaxCount()); + vnf.setCategory(vnfResourceCustomization.getVnfResources().getCategory()); + vnf.setCloudVersionMax(vnfResourceCustomization.getVnfResources().getAicVersionMax()); + vnf.setCloudVersionMin(vnfResourceCustomization.getVnfResources().getAicVersionMin()); + vnf.setMaxInstances(vnfResourceCustomization.getMaxInstances()); + vnf.setMinInstances(vnfResourceCustomization.getMinInstances()); + vnf.setModelCustomizationId(vnfResourceCustomization.getModelCustomizationUUID()); + vnf.setModelInstanceName(vnfResourceCustomization.getModelInstanceName()); + vnf.setModelInvariantId(vnfResourceCustomization.getVnfResources().getModelInvariantId()); + vnf.setModelName(vnfResourceCustomization.getVnfResources().getModelName()); + vnf.setModelVersionId(vnfResourceCustomization.getVnfResources().getModelUUID()); + vnf.setModelVersion(vnfResourceCustomization.getVnfResources().getModelVersion()); + vnf.setMultiStageDesign(vnfResourceCustomization.getMultiStageDesign()); + vnf.setNfFunction(vnfResourceCustomization.getNfFunction()); + vnf.setNfNamingCode(vnfResourceCustomization.getNfNamingCode()); + vnf.setNfRole(vnfResourceCustomization.getNfRole()); + vnf.setOrchestrationMode(vnfResourceCustomization.getVnfResources().getOrchestrationMode()); + vnf.setSubCategory(vnfResourceCustomization.getVnfResources().getSubCategory()); + vnf.setToscaNodeType(vnfResourceCustomization.getVnfResources().getToscaNodeType()); + if (depth > 1) { + vnf.setVfModule(mapVfModules(vnfResourceCustomization, depth)); + } + return vnf; + } + + private List<VfModule> mapVfModules(VnfResourceCustomization vnfResourceCustomization, int depth) { + List<VfModule> vfModules = new ArrayList<>(); + vnfResourceCustomization.getVfModuleCustomizations().parallelStream() + .forEach(vfModule -> vfModules.add(mapVfModule(vfModule))); + return vfModules; + } + + private VfModule mapVfModule(VfModuleCustomization vfModuleCust) { + VfModule vfModule = new VfModule(); + vfModule.setAvailabilityZoneCount(vfModuleCust.getAvailabilityZoneCount()); + vfModule.setCreated(vfModuleCust.getCreated()); + vfModule.setDescription(vfModuleCust.getVfModule().getDescription()); + vfModule.setInitialCount(vfModuleCust.getInitialCount()); + vfModule.setIsBase(vfModuleCust.getVfModule().getIsBase()); + vfModule.setIsVolumeGroup(getIsVolumeGroup(vfModuleCust)); + vfModule.setMaxInstances(vfModuleCust.getMaxInstances()); + vfModule.setMinInstances(vfModuleCust.getMinInstances()); + vfModule.setLabel(vfModuleCust.getLabel()); + vfModule.setModelCustomizationId(vfModuleCust.getModelCustomizationUUID()); + vfModule.setModelInvariantId(vfModuleCust.getVfModule().getModelInvariantUUID()); + vfModule.setModelName(vfModuleCust.getVfModule().getModelName()); + vfModule.setModelVersionId(vfModuleCust.getVfModule().getModelUUID()); + vfModule.setModelVersion(vfModuleCust.getVfModule().getModelVersion()); + return vfModule; + } + + private boolean getIsVolumeGroup(VfModuleCustomization vfModuleCust) { + boolean isVolumeGroup = false; + HeatEnvironment envt = vfModuleCust.getVolumeHeatEnv(); + if (envt != null) { + isVolumeGroup = true; + } + return isVolumeGroup; + } + +} diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceRestImpl.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceRestImpl.java new file mode 100644 index 0000000000..1ca8998396 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceRestImpl.java @@ -0,0 +1,76 @@ +/*- + * ============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.adapters.catalogdb.rest; + +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.so.db.catalog.data.repository.ServiceRepository; +import org.onap.so.rest.catalog.beans.Service; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; +import com.google.common.base.Strings; +import io.swagger.annotations.ApiOperation; + +@Path("/v1/") +@Component +public class ServiceRestImpl { + + @Autowired + private ServiceRepository serviceRepo; + + @Autowired + private ServiceMapper serviceMapper; + + @GET + @Path("/services/{modelUUID}") + @Produces({MediaType.APPLICATION_JSON}) + @Transactional(readOnly = true) + public Service findService(@PathParam("modelUUID") String modelUUID, @QueryParam("depth") int depth) { + org.onap.so.db.catalog.beans.Service service = serviceRepo.findOneByModelUUID(modelUUID); + return serviceMapper.mapService(service, depth); + } + + @GET + @Path("/services") + @ApiOperation(value = "Find Service Models", response = Service.class, responseContainer = "List") + @Produces({MediaType.APPLICATION_JSON}) + @Transactional(readOnly = true) + public List<Service> queryServices(@QueryParam("modelName") String modelName, + @QueryParam("distributionStatus") String distributionStatus, @QueryParam("depth") int depth) { + List<Service> services = new ArrayList<>(); + List<org.onap.so.db.catalog.beans.Service> serviceFromDB = new ArrayList<>(); + if (!Strings.isNullOrEmpty(modelName) && !Strings.isNullOrEmpty(distributionStatus)) { + serviceFromDB = serviceRepo.findByModelNameAndDistrobutionStatus(modelName, distributionStatus); + } else if (!Strings.isNullOrEmpty(modelName)) { + serviceFromDB = serviceRepo.findByModelName(modelName); + } + serviceFromDB.stream().forEach(serviceDB -> services.add(serviceMapper.mapService(serviceDB, depth))); + return services; + } +} diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/application.yaml b/adapters/mso-catalog-db-adapter/src/main/resources/application.yaml index 07b000875e..b1528a0897 100644 --- a/adapters/mso-catalog-db-adapter/src/main/resources/application.yaml +++ b/adapters/mso-catalog-db-adapter/src/main/resources/application.yaml @@ -28,7 +28,6 @@ spring: password: ${DB_ADMIN_PASSWORD} outOfOrder: true validateOnMigrate: false - repeatableSqlMigrationPrefix: RATT jpa: show-sql: true hibernate: @@ -53,4 +52,4 @@ management: 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 + diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/manual/Migrate_Distrobution_Status.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/manual/Migrate_Distrobution_Status.sql new file mode 100644 index 0000000000..4a9c2cce9f --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/manual/Migrate_Distrobution_Status.sql @@ -0,0 +1,11 @@ + +UPDATE catalogdb.service serv SET OVERALL_DISTRIBUTION_STATUS =( +SELECT wds.DISTRIBUTION_ID_STATUS +FROM requestdb.watchdog_distributionid_status wds +INNER JOIN requestdb.watchdog_service_mod_ver_id_lookup wdlook +ON wds.DISTRIBUTION_ID = wdlook.DISTRIBUTION_ID +WHERE wdlook.SERVICE_MODEL_VERSION_ID = serv.MODEL_UUID +ORDER BY wdlook.MODIFY_TIME DESC LIMIT 1); + +UPDATE catalogdb.service SET OVERALL_DISTRIBUTION_STATUS = 'DISTRIBUTION_COMPLETE_OK' +WHERE service.OVERALL_DISTRIBUTION_STATUS = NULL;
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.11__AddVnfResourceOrder.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.11__AddVnfResourceOrder.sql new file mode 100644 index 0000000000..16e6ecf4bf --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.11__AddVnfResourceOrder.sql @@ -0,0 +1,7 @@ +use catalogdb; + +ALTER TABLE vnf_resource_customization +ADD VNFCINSTANCEGROUP_ORDER varchar(255); + +ALTER TABLE vnfc_customization +ADD RESOURCE_INPUT varchar(2000);
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.12__Add_Relation_VnfcCustomization.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.12__Add_Relation_VnfcCustomization.sql new file mode 100644 index 0000000000..95a2c25eb8 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.12__Add_Relation_VnfcCustomization.sql @@ -0,0 +1,2 @@ +use catalogdb; +ALTER TABLE vnfc_customization ADD vnfc_instance_group_customization_id INTEGER NULL;
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.6.6__Add_Column_For_Distrobution_Status.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.6.6__Add_Column_For_Distrobution_Status.sql new file mode 100644 index 0000000000..ae416ffbfe --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.6.6__Add_Column_For_Distrobution_Status.sql @@ -0,0 +1 @@ +ALTER TABLE catalogdb.service ADD COLUMN IF NOT EXISTS OVERALL_DISTRIBUTION_STATUS varchar(45);
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7.2__Add_Error_Message_Rainy_Day.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7.2__Add_Error_Message_Rainy_Day.sql new file mode 100644 index 0000000000..cf54d55fde --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7.2__Add_Error_Message_Rainy_Day.sql @@ -0,0 +1,2 @@ +use catalogdb; +ALTER TABLE rainy_day_handler_macro ADD COLUMN IF NOT EXISTS REG_EX_ERROR_MESSAGE varchar(300) DEFAULT NULL;
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryGroupsTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryGroupsTest.java new file mode 100644 index 0000000000..00db6d5938 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryGroupsTest.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.adapters.catalogdb.catalogrest; + +import org.assertj.core.api.Assertions; +import org.junit.Test; +import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.catalog.beans.VFCInstanceGroup; +import org.onap.so.db.catalog.beans.VnfResource; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.db.catalog.beans.VnfcCustomization; +import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization; +import org.onap.so.db.catalog.rest.beans.ServiceMacroHolder; +import org.onap.so.jsonpath.JsonPathUtil; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class QueryGroupsTest { + + @Test + public void convertToJson_successful() { + QueryGroups queryGroups = new QueryGroups(createList()); + String jsonResult = queryGroups.JSON2(true, false); + + Assertions.assertThat(JsonPathUtil.getInstance().locateResult(jsonResult, "$.groups[0].modelInfo.modelName")) + .contains("test"); + Assertions + .assertThat( + JsonPathUtil.getInstance().locateResult(jsonResult, "$.groups[0].vnfcs[0].modelInfo.modelName")) + .contains("test"); + } + + private List<VnfcInstanceGroupCustomization> createList() { + + VnfcCustomization vnfcCustomization = new VnfcCustomization(); + vnfcCustomization.setModelCustomizationUUID("test"); + vnfcCustomization.setModelVersion("test"); + vnfcCustomization.setModelInvariantUUID("test"); + vnfcCustomization.setModelName("test"); + + VFCInstanceGroup vfcInstanceGroup = new VFCInstanceGroup(); + vfcInstanceGroup.setModelName("test"); + vfcInstanceGroup.setModelUUID("test"); + vfcInstanceGroup.setModelInvariantUUID("test"); + vfcInstanceGroup.setModelVersion("test"); + + VnfcInstanceGroupCustomization vnfcInstanceGroupCustomization = new VnfcInstanceGroupCustomization(); + vnfcInstanceGroupCustomization.setVnfcCustomizations(Arrays.asList(vnfcCustomization)); + vnfcInstanceGroupCustomization.setInstanceGroup(vfcInstanceGroup); + + + vfcInstanceGroup.setVnfcInstanceGroupCustomizations(Arrays.asList(vnfcInstanceGroupCustomization)); + return Arrays.asList(vnfcInstanceGroupCustomization); + } +} diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVnfcsTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVnfcsTest.java new file mode 100644 index 0000000000..abc59352b0 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/QueryVnfcsTest.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.adapters.catalogdb.catalogrest; + +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; +import org.onap.so.db.catalog.beans.VnfcCustomization; +import org.onap.so.jsonpath.JsonPathUtil; +import java.util.ArrayList; +import java.util.List; + +public class QueryVnfcsTest { + + @Test + public void convertToJson_successful() { + QueryVnfcs queryVnfcs = new QueryVnfcs(createList()); + String jsonResult = queryVnfcs.JSON2(true, false); + System.out.println(jsonResult); + assertThat(JsonPathUtil.getInstance().locateResult(jsonResult, "$.vnfcs[0].modelInfo.modelName")) + .contains("model1"); + assertThat(JsonPathUtil.getInstance().locateResult(jsonResult, "$.vnfcs[1].modelInfo.modelName")) + .contains("model2"); + + } + + private List<VnfcCustomization> createList() { + List<VnfcCustomization> customizations = new ArrayList(); + + VnfcCustomization c1 = new VnfcCustomization(); + c1.setModelName("model1"); + c1.setModelUUID("uuid1"); + c1.setModelInvariantUUID("inv1"); + c1.setModelVersion("v1"); + c1.setModelCustomizationUUID("cust1"); + c1.setResourceInput("resourceInput1"); + + VnfcCustomization c2 = new VnfcCustomization(); + c2.setModelName("model2"); + c2.setModelUUID("uuid2"); + c2.setModelInvariantUUID("inv2"); + c2.setModelVersion("v2"); + c2.setModelCustomizationUUID("cust2"); + c2.setResourceInput("resourceInput2"); + + customizations.add(c1); + customizations.add(c2); + return customizations; + } +} 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 new file mode 100644 index 0000000000..b8161de6b2 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java @@ -0,0 +1,134 @@ +package org.onap.so.adapters.catalogdb.catalogrest; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.junit.Test; +import org.onap.so.adapters.catalogdb.rest.ServiceMapper; +import org.onap.so.db.catalog.beans.HeatTemplate; +import org.onap.so.db.catalog.beans.HeatTemplateParam; +import org.onap.so.db.catalog.beans.VfModuleCustomization; +import org.onap.so.rest.catalog.beans.Service; +import wiremock.com.fasterxml.jackson.core.JsonParseException; +import wiremock.com.fasterxml.jackson.databind.JsonMappingException; +import wiremock.com.fasterxml.jackson.databind.ObjectMapper; + +public class ServiceMapperTest { + + private ServiceMapper serviceMapper = new ServiceMapper(); + + @Test + public void service_map_test() throws JsonParseException, JsonMappingException, IOException { + Service actual = serviceMapper.mapService(getTestService(), 2); + assertThat(actual, sameBeanAs(getExpectedService())); + } + + private Service getExpectedService() throws JsonParseException, JsonMappingException, IOException { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(getJson("ExpectedService.json"), Service.class); + } + + + private org.onap.so.db.catalog.beans.Service getTestService() { + org.onap.so.db.catalog.beans.Service testService = new org.onap.so.db.catalog.beans.Service(); + testService.setCategory("category"); + testService.setDescription("description"); + testService.setDistrobutionStatus("distrobutionStatus"); + testService.setEnvironmentContext("environmentContext"); + testService.setModelInvariantUUID("modelInvariantUUID"); + testService.setModelName("modelName"); + testService.setModelUUID("modelUUID"); + testService.setModelVersion("modelVersion"); + testService.setServiceType("serviceType"); + testService.setServiceRole("serviceRole"); + testService.getVnfCustomizations().add(getTestVnfCustomization()); + return testService; + } + + private org.onap.so.db.catalog.beans.VnfResourceCustomization getTestVnfCustomization() { + org.onap.so.db.catalog.beans.VnfResourceCustomization test = + new org.onap.so.db.catalog.beans.VnfResourceCustomization(); + test.setId(1); + test.setAvailabilityZoneMaxCount(11); + test.setMaxInstances(3); + test.setMinInstances(1); + test.setModelCustomizationUUID("modelCustomizationUUID"); + test.setModelInstanceName("modelInstanceName"); + test.setMultiStageDesign("multiStageDesign"); + test.setNfFunction("nfFunction"); + test.setNfNamingCode("nfNamingCode"); + test.setNfRole("nfRole"); + test.setNfType("nfType"); + test.setService(new org.onap.so.db.catalog.beans.Service()); + test.setVnfResources(getTestVnfResource()); + test.setVfModuleCustomizations(getTestVfModuleCust()); + return test; + } + + private List<VfModuleCustomization> getTestVfModuleCust() { + List<VfModuleCustomization> test = new ArrayList<>(); + VfModuleCustomization testVfMod = new VfModuleCustomization(); + testVfMod.setAvailabilityZoneCount(10); + testVfMod.setInitialCount(1); + testVfMod.setLabel("label"); + testVfMod.setMaxInstances(3); + testVfMod.setMinInstances(1); + testVfMod.setModelCustomizationUUID("modelCustomizationUUID"); + org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule(); + vfModule.setDescription("description"); + vfModule.setIsBase(false); + vfModule.setModelInvariantUUID("modelInvariantUUID"); + vfModule.setModelName("modelName"); + vfModule.setModelUUID("modelUUID"); + vfModule.setModelVersion("modelVersion"); + HeatTemplate moduleHeatTemplate = new HeatTemplate(); + moduleHeatTemplate.setArtifactChecksum("artifactChecksum"); + moduleHeatTemplate.setArtifactUuid("artifactUuid"); + List<HeatTemplate> childTemplates; + // moduleHeatTemplate.setChildTemplates(childTemplates); + moduleHeatTemplate.setDescription("description"); + Set<HeatTemplateParam> parameters = new HashSet<>(); + HeatTemplateParam heatParam = new HeatTemplateParam(); + heatParam.setHeatTemplateArtifactUuid("heatTemplateArtifactUuid"); + heatParam.setParamAlias("paramAlias"); + heatParam.setParamName("paramName"); + heatParam.setParamType("paramType"); + heatParam.setRequired(false); + parameters.add(heatParam); + moduleHeatTemplate.setParameters(parameters); + moduleHeatTemplate.setTemplateBody("templateBody"); + moduleHeatTemplate.setTemplateName("templateName"); + moduleHeatTemplate.setTimeoutMinutes(1000); + moduleHeatTemplate.setVersion("version"); + vfModule.setModuleHeatTemplate(moduleHeatTemplate); + testVfMod.setVfModule(vfModule); + test.add(testVfMod); + return test; + } + + private org.onap.so.db.catalog.beans.VnfResource getTestVnfResource() { + org.onap.so.db.catalog.beans.VnfResource test = new org.onap.so.db.catalog.beans.VnfResource(); + test.setCategory("category"); + test.setDescription("description"); + test.setModelInvariantUUID("modelInvariantUUID"); + test.setModelName("modelName"); + test.setModelUUID("modelUUID"); + test.setModelVersion("modelVersion"); + test.setAicVersionMax("cloudVersionMax"); + test.setAicVersionMin("cloudVersionMin"); + test.setOrchestrationMode("orchestrationMode"); + test.setSubCategory("subCategory"); + test.setToscaNodeType("toscaNodeType"); + return test; + } + + private String getJson(String filename) throws IOException { + return new String(Files.readAllBytes(Paths.get("src/test/resources/" + filename))); + } +} 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 51b44b0d3a..31cb1248d6 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 @@ -79,20 +79,12 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { client.wiremockPort = String.valueOf(port); } - @Test - public void testGetRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep() { - RainyDayHandlerStatus rainyDayHandlerStatus = - client.getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep( - "AssignServiceInstanceBB", "*", "*", "*", "*"); - Assert.assertEquals("Rollback", rainyDayHandlerStatus.getPolicy()); - } @Test - public void testGetRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStepRecordNotFound() { - RainyDayHandlerStatus rainyDayHandlerStatus = - client.getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep( - UUID.randomUUID().toString(), "*", "*", "*", "*"); - Assert.assertNull(rainyDayHandlerStatus); + public void testGetRainyDayHandler_Regex() { + RainyDayHandlerStatus rainyDayHandlerStatus = client.getRainyDayHandlerStatus("AssignServiceInstanceBB", "*", + "*", "*", "*", "The Flavor ID (nd.c6r16d20) could not be found."); + Assert.assertEquals("Rollback", rainyDayHandlerStatus.getPolicy()); } @Test @@ -289,7 +281,6 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { Assert.assertNotNull(vnfResource.getModelInvariantId()); Assert.assertNotNull(vnfResource.getModelVersion()); Assert.assertNotNull(vnfResource.getHeatTemplates()); - Assert.assertNotNull(vnfResource.getVnfResourceCustomizations()); Assert.assertEquals("vSAMP10a", vnfResource.getModelName()); } diff --git a/adapters/mso-catalog-db-adapter/src/test/resources/ExpectedService.json b/adapters/mso-catalog-db-adapter/src/test/resources/ExpectedService.json new file mode 100644 index 0000000000..cc5145f0e3 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/test/resources/ExpectedService.json @@ -0,0 +1,52 @@ +{ + "modelName": "modelName", + "description": "description", + "modelVersionId": "modelUUID", + "modelInvariantId": "modelInvariantUUID", + "modelVersion": "modelVersion", + "serviceType": "serviceType", + "serviceRole": "serviceRole", + "environmentContext": "environmentContext", + "category": "category", + "distrobutionStatus": "distrobutionStatus", + "vnf": [ + { + "modelName": "modelName", + "modelVersionId": "modelUUID", + "modelInvariantId": "modelInvariantUUID", + "modelVersion": "modelVersion", + "modelCustomizationId": "modelCustomizationUUID", + "modelInstanceName": "modelInstanceName", + "minInstances": 1, + "maxInstances": 3, + "availabilityZoneMaxCount": 11, + "toscaNodeType": "toscaNodeType", + "nfFunction": "nfFunction", + "nfRole": "nfRole", + "nfNamingCode": "nfNamingCode", + "multiStageDesign": "multiStageDesign", + "orchestrationMode": "orchestrationMode", + "cloudVersionMin": "cloudVersionMin", + "cloudVersionMax": "cloudVersionMax", + "category": "category", + "subCategory": "subCategory", + "vfModule": [ + { + "modelVersionId": "modelUUID", + "modelInvariantId": "modelInvariantUUID", + "modelName": "modelName", + "modelVersion": "modelVersion", + "description": "description", + "isBase": false, + "modelCustomizationId": "modelCustomizationUUID", + "label": "label", + "minInstances": 1, + "maxInstances": 3, + "initialCount": "1", + "availabilityZoneCount": 10, + "isVolumeGroup": false + } + ] + } + ] +}
\ No newline at end of file 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 0229dd0d85..0e981f2b70 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 @@ -183,7 +183,10 @@ VALUES ( '9bcce658-9b37-11e8-98d0-529269fb1459', 'toscaNodeType', 'testVnfcCustomizationDescription', '2018-07-17 14:05:08'); - + +INSERT INTO `rainy_day_handler_macro` (`FLOW_NAME`,`SERVICE_TYPE`,`VNF_TYPE`,`ERROR_CODE`,`WORK_STEP`,`POLICY`,`SECONDARY_POLICY`,`REG_EX_ERROR_MESSAGE`) +VALUES ('AssignServiceInstanceBB','*','*','*','*','Rollback','Rollback','The Flavor ID.*could not be found.'); + INSERT INTO `cvnfc_customization` (`id`, `model_customization_uuid`, diff --git a/adapters/mso-catalog-db-adapter/src/test/resources/logback-test.xml b/adapters/mso-catalog-db-adapter/src/test/resources/logback-test.xml index 463be2e527..97a4503190 100644 --- a/adapters/mso-catalog-db-adapter/src/test/resources/logback-test.xml +++ b/adapters/mso-catalog-db-adapter/src/test/resources/logback-test.xml @@ -1,45 +1,46 @@ <configuration> - - <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> - <encoder> + + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - %msg%n</pattern> </encoder> - </appender> - - <appender name="test" - class="org.onap.so.adapters.catalogdb.catalogrest.TestAppender" /> - - <logger name="com.att.ecomp.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"> - <appender-ref ref="STDOUT" /> - </logger> - - <logger name="org.onap" level="${so.log.level:-DEBUG}" additivity="false"> - <appender-ref ref="STDOUT" /> - <appender-ref ref="test" /> - </logger> - - <logger name="org.flywaydb" level="DEBUG" additivity="false"> - <appender-ref ref="STDOUT" /> - </logger> - - - <logger name="ch.vorburger" level="WARN" additivity="false"> - <appender-ref ref="STDOUT" /> - </logger> - - - <root level="WARN"> - <appender-ref ref="STDOUT" /> - <appender-ref ref="test" /> - </root> + </appender> + + <appender name="test" class="org.onap.so.adapters.catalogdb.catalogrest.TestAppender" /> + + <logger name="com.att.ecomp.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"> + <appender-ref ref="STDOUT" /> + </logger> + + <logger name="org.onap" level="${so.log.level:-DEBUG}" additivity="false"> + <appender-ref ref="STDOUT" /> + <appender-ref ref="test" /> + </logger> + + <logger name="org.flywaydb" level="DEBUG" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + <logger name="org.hibernate" level="DEBUG" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + + <logger name="ch.vorburger" level="WARN" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + + + <root level="WARN"> + <appender-ref ref="STDOUT" /> + <appender-ref ref="test" /> + </root> </configuration>
\ No newline at end of file diff --git a/adapters/mso-openstack-adapters/pom.xml b/adapters/mso-openstack-adapters/pom.xml index 088f9499ce..d174de7e2f 100644 --- a/adapters/mso-openstack-adapters/pom.xml +++ b/adapters/mso-openstack-adapters/pom.xml @@ -82,7 +82,7 @@ <keep>true</keep> </configuration> </execution> - + <execution> <id>generate-vnf-async-stubs</id> <phase>process-classes</phase> @@ -123,7 +123,7 @@ </configuration> </execution> </executions> - </plugin> + </plugin> --> <plugin> <groupId>org.jacoco</groupId> diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java index 52f5478f2f..2e62beb083 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java @@ -3,6 +3,8 @@ package org.onap.so.adapters.audit; import java.util.Optional; import org.camunda.bpm.client.task.ExternalTask; import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.objects.audit.AAIObjectAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java index 947c6ddfeb..77229919cd 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.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. @@ -29,6 +29,7 @@ import org.camunda.bpm.client.task.ExternalTask; import org.camunda.bpm.client.task.ExternalTaskService; import org.onap.so.audit.beans.AuditInventory; import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.objects.audit.AAIObjectAuditList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -57,6 +58,8 @@ public class AuditCreateStackService extends AbstractAuditService { Optional<AAIObjectAuditList> auditListOpt = heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(), auditInventory.getCloudOwner(), auditInventory.getTenantId(), auditInventory.getHeatStackName()); if (auditListOpt.isPresent()) { + auditListOpt.get().setAuditType("create"); + auditListOpt.get().setHeatStackName(auditInventory.getHeatStackName()); GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get())); success = !didCreateAuditFail(auditListOpt); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java index 048e6dbba2..9b245ba695 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.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. @@ -27,6 +27,7 @@ import org.camunda.bpm.client.task.ExternalTask; import org.camunda.bpm.client.task.ExternalTaskService; import org.onap.so.audit.beans.AuditInventory; import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.objects.audit.AAIObjectAuditList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -55,9 +56,11 @@ public class AuditDeleteStackService extends AbstractAuditService { Optional<AAIObjectAuditList> auditListOpt = heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(), auditInventory.getCloudOwner(), auditInventory.getTenantId(), auditInventory.getHeatStackName()); if (auditListOpt.isPresent()) { + auditListOpt.get().setAuditType("delete"); + auditListOpt.get().setHeatStackName(auditInventory.getHeatStackName()); GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get())); - success = didDeleteAuditFail(auditListOpt); + success = !didDeleteAuditFail(auditListOpt); } } catch (Exception e) { logger.error("Error during audit of stack", e); @@ -74,7 +77,7 @@ public class AuditDeleteStackService extends AbstractAuditService { UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000); } else if (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) { logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId()); - externalTaskService.complete(externalTask); + externalTaskService.complete(externalTask, variables); } else { logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", externalTask.getId(), externalTask.getRetries() - 1, diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java index 5ca045d988..e009c0e2fd 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java @@ -28,6 +28,8 @@ 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.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.objects.audit.AAIObjectAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java index 889f6fe860..2be87ff076 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java @@ -35,6 +35,7 @@ import org.onap.aai.domain.yang.LInterfaces; import org.onap.aai.domain.yang.Vlan; import org.onap.aai.domain.yang.Vlans; import org.onap.aai.domain.yang.Vserver; +import org.onap.so.objects.audit.AAIObjectAuditList; import org.onap.so.openstack.utils.MsoHeatUtils; import org.onap.so.openstack.utils.MsoNeutronUtils; import org.slf4j.Logger; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java index 608832f49f..69e16986da 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java @@ -22,11 +22,11 @@ package org.onap.so.adapters.inventory.create; import java.util.Optional; import java.util.stream.Stream; -import org.onap.so.adapters.audit.AAIObjectAudit; -import org.onap.so.adapters.audit.AAIObjectAuditList; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.objects.audit.AAIObjectAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; import org.springframework.stereotype.Component; @Component diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java index 8d0c2bdfc1..74cf7c38c9 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.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,12 +20,11 @@ package org.onap.so.adapters.inventory.create; -import java.io.IOException; import org.camunda.bpm.client.task.ExternalTask; import org.camunda.bpm.client.task.ExternalTaskService; import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.adapters.audit.AAIObjectAuditList; import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.objects.audit.AAIObjectAuditList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; @@ -47,22 +46,26 @@ public class CreateInventoryTask { public Environment env; protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + setupMDC(externalTask); boolean success = true; + boolean inventoryException = false; String auditInventoryString = externalTask.getVariable("auditInventoryResult"); - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); AAIObjectAuditList auditInventory = null; try { + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); auditInventory = objectMapper.getMapper().readValue(auditInventoryString, AAIObjectAuditList.class); - } catch (IOException e1) { - success = false; + } catch (Exception e) { + logger.error("Error Parsing Audit Results", e); } - setupMDC(externalTask); - if (auditInventory != null) { try { logger.info("Executing External Task Create Inventory, Retry Number: {} \n {}", auditInventory, externalTask.getRetries()); createInventory.createInventory(auditInventory); + } catch (InventoryException e) { + logger.error("Error during inventory of stack", e); + success = false; + inventoryException = true; } catch (Exception e) { logger.error("Error during inventory of stack", e); success = false; @@ -70,6 +73,9 @@ public class CreateInventoryTask { if (success) { externalTaskService.complete(externalTask); logger.debug("The External Task Id: {} Successful", externalTask.getId()); + } else if (inventoryException) { + logger.debug("The External Task Id: {} Failed, Retry not needed", externalTask.getId()); + externalTaskService.handleBpmnError(externalTask, "AAIInventoryFailure"); } else { if (externalTask.getRetries() == null) { logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", @@ -96,9 +102,13 @@ public class CreateInventoryTask { } private void setupMDC(ExternalTask externalTask) { - String msoRequestId = (String) externalTask.getVariable("mso-request-id"); - if (msoRequestId != null && !msoRequestId.isEmpty()) - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId); + try { + String msoRequestId = (String) externalTask.getVariable("mso-request-id"); + if (msoRequestId != null && !msoRequestId.isEmpty()) + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId); + } catch (Exception e) { + logger.error("Error in setting up MDC", e); + } } protected long calculateRetryDelay(int currentRetries) { diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java index c15fc0d204..b12d2397f9 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java @@ -87,6 +87,7 @@ public class NetworkAdapterRest { private static final Logger logger = LoggerFactory.getLogger(NetworkAdapterRest.class); private static final String TESTING_KEYWORD = "___TESTING___"; private String exceptionMsg = "Exception:"; + private static final String SHARED = "shared"; @Autowired private MsoNetworkAdapterImpl adapter; @@ -170,7 +171,7 @@ public class NetworkAdapterRest { HashMap<String, String> params = (HashMap<String, String>) req.getNetworkParams(); if (params == null) { - params = new HashMap<String, String>(); + params = new HashMap<>(); } String shared = null; String external = null; @@ -192,8 +193,8 @@ public class NetworkAdapterRest { ctn = new ContrailNetwork(); req.setContrailNetwork(ctn); } - if (params.containsKey("shared")) { - shared = params.get("shared"); + if (params.containsKey(SHARED)) { + shared = params.get(SHARED); } else { if (ctn.getShared() != null) { shared = ctn.getShared(); @@ -218,8 +219,8 @@ public class NetworkAdapterRest { pvn = new ProviderVlanNetwork(); req.setProviderVlanNetwork(pvn); } - if (params.containsKey("shared")) - shared = params.get("shared"); + if (params.containsKey(SHARED)) + shared = params.get(SHARED); if (params.containsKey("external")) external = params.get("external"); adapter.createNetwork(req.getCloudSiteId(), req.getTenantId(), req.getNetworkType(), @@ -573,8 +574,8 @@ public class NetworkAdapterRest { ctn = new ContrailNetwork(); req.setContrailNetwork(ctn); } - if (params.containsKey("shared")) { - shared = params.get("shared"); + if (params.containsKey(SHARED)) { + shared = params.get(SHARED); } else { if (ctn.getShared() != null) { shared = ctn.getShared(); @@ -598,8 +599,8 @@ public class NetworkAdapterRest { pvn = new ProviderVlanNetwork(); req.setProviderVlanNetwork(pvn); } - if (params.containsKey("shared")) { - shared = params.get("shared"); + if (params.containsKey(SHARED)) { + shared = params.get(SHARED); } if (params.containsKey("external")) { external = params.get("external"); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java index 906c285c28..62e9d562a6 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java @@ -204,7 +204,6 @@ public class BpelRestClient { * @return true if the post succeeded, false if all retries failed */ public boolean bpelPost(final String toBpelStr, final String bpelUrl, final boolean isxml) { - debug("Sending response to BPEL: " + toBpelStr); int totalretries = 0; int retryint = retryInterval; while (true) { 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 d2dfae4b4b..9236945d37 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 @@ -65,6 +65,7 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { private static final String BPEL_AUTH_PROP = "org.onap.so.adapters.vnf.bpelauth"; private static final String ENCRYPTION_KEY_PROP = "org.onap.so.adapters.network.encryptionKey"; private static final String UPDATE_VNFA = "{} UpdateVnfA"; + private static final String EXCEPTION_UPDATEVNF_NOTIFICATION = "{} {} Exception sending updateVnf notification "; @Autowired private Environment environment; @@ -188,7 +189,7 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { vnfAdapter.updateVnf(cloudSiteId, cloudOwner, tenantId, vnfType, vnfVersion, vnfName, requestType, volumeGroupHeatStackId, inputs, msoRequest, outputs, vnfRollback); } catch (VnfException e) { - logger.error("{} {} Exception sending updateVnf notification ", MessageEnum.RA_UPDATE_VNF_ERR, + logger.error(EXCEPTION_UPDATEVNF_NOTIFICATION, MessageEnum.RA_UPDATE_VNF_ERR, ErrorCode.BusinessProcesssError.getValue(), e); org.onap.so.adapters.vnf.async.client.MsoExceptionCategory exCat = null; String eMsg = null; @@ -205,7 +206,7 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl); notifyPort.updateVnfNotification(messageId, false, exCat, eMsg, null, null); } catch (Exception e1) { - logger.error("{} {} Exception sending updateVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, + logger.error(EXCEPTION_UPDATEVNF_NOTIFICATION, MessageEnum.RA_SEND_VNF_NOTIF_ERR, ErrorCode.BusinessProcesssError.getValue(), e1); } logger.info(UPDATE_VNFA, MessageEnum.RA_ASYNC_UPDATE_VNF_COMPLETE); @@ -218,7 +219,7 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { notifyPort.updateVnfNotification(messageId, true, null, null, copyUpdateOutputs(outputs), copyVrb(vnfRollback)); } catch (Exception e) { - logger.error("{} {} Exception sending updateVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, + logger.error(EXCEPTION_UPDATEVNF_NOTIFICATION, MessageEnum.RA_SEND_VNF_NOTIF_ERR, ErrorCode.BusinessProcesssError.getValue(), e); } logger.info(UPDATE_VNFA, MessageEnum.RA_ASYNC_UPDATE_VNF_COMPLETE); 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 b59a1fa79a..bac41a1f8b 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 @@ -6,6 +6,7 @@ * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ * Modifications Copyright (c) 2019 Samsung + * Modifications Copyright (c) 2019 IBM * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,7 +67,6 @@ 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.heatbridge.openstack.api.OpenstackClient; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.HeatStatus; import org.onap.so.openstack.beans.StackInfo; @@ -189,7 +189,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { String vfModuleId = ""; // Create a hook here to catch shortcut createVf requests: if (requestType != null && requestType.startsWith("VFMOD")) { - logger.debug("Calling createVfModule from createVnf -- requestType=" + requestType); + logger.debug("Calling createVfModule from createVnf -- requestType={}", requestType); String newRequestType = requestType.substring(5); String vfVolGroupHeatStackId = ""; String vfBaseHeatStackId = ""; @@ -251,13 +251,11 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { Holder<Boolean> vnfExists, Holder<String> vnfId, Holder<VnfStatus> status, Holder<Map<String, String>> outputs) throws VnfException { - logger.debug("Querying VNF {} in {}", vnfName, cloudSiteId + "/" + tenantId); + logger.debug("Querying VNF {} in {}/{}", vnfName, cloudSiteId, tenantId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis(); - StackInfo heatStack = null; - long subStartTime = System.currentTimeMillis(); + StackInfo heatStack; try { heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vnfName); } catch (MsoException me) { @@ -310,14 +308,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { throws VnfException { logger.debug("Deleting VNF {} in {}", vnfName, cloudSiteId + "/" + tenantId); - // Will capture execution time for metrics - long startTime = System.currentTimeMillis(); - // Use the MsoHeatUtils to delete the stack. Set the polling flag to true. - // The possible outcomes of deleteStack are a StackInfo object with status - // of NOTFOUND (on success) or FAILED (on error). Also, MsoOpenstackException - // could be thrown. - long subStartTime = System.currentTimeMillis(); try { heat.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true); } catch (MsoException me) { @@ -344,7 +335,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { */ @Override public void rollbackVnf(VnfRollback rollback) throws VnfException { - 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"); @@ -437,13 +427,13 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { logger.debug(" HeatBridgeMain.py returned {} with code {}", wait, p.exitValue()); return wait && p.exitValue() == 0; } catch (IOException e) { - logger.debug(" HeatBridgeMain.py failed with IO Exception! " + e); + logger.debug(" HeatBridgeMain.py failed with IO Exception! {}", e); return false; } catch (RuntimeException e) { - logger.debug(" HeatBridgeMain.py failed during runtime!" + e); + logger.debug(" HeatBridgeMain.py failed during runtime! {}", e); return false; } catch (Exception e) { - logger.debug(" HeatBridgeMain.py failed for unknown reasons! " + e); + logger.debug(" HeatBridgeMain.py failed for unknown reasons! {}", e); return false; } } @@ -461,7 +451,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { HeatBridgeApi heatBridgeClient = new HeatBridgeImpl(new AAIResourcesClient(), cloudIdentity, cloudOwner, cloudSiteId, tenantId); - OpenstackClient openstackClient = heatBridgeClient.authenticate(); List<Resource> stackResources = heatBridgeClient.queryNestedHeatStackResources(heatStackId); List<Server> osServers = heatBridgeClient.getAllOpenstackServers(stackResources); @@ -590,7 +579,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { useMCUuid = false; mcu = ""; } else { - logger.debug("Found modelCustomizationUuid! Will use that: " + mcu); + logger.debug("Found modelCustomizationUuid! Will use that: {}", mcu); useMCUuid = true; } } @@ -1277,7 +1266,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { logger.debug("VF Module {} successfully created", vfModuleName); // call heatbridge heatbridge(heatStack, cloudOwner, cloudSiteId, tenantId, genericVnfName, vfModuleId); - return; } catch (Exception e) { logger.debug("unhandled exception in create VF", e); throw new VnfException("Exception during create VF " + e.getMessage()); @@ -1290,7 +1278,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { logger.debug("Deleting VF {} in ", vnfName, cloudOwner + "/" + cloudSiteId + "/" + tenantId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis(); // 1702 capture the output parameters on a delete // so we'll need to query first @@ -1323,11 +1310,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { msoRequest, failRequestOnValetFailure); } - // Use the MsoHeatUtils to delete the stack. Set the polling flag to true. - // The possible outcomes of deleteStack are a StackInfo object with status - // of NOTFOUND (on success) or FAILED (on error). Also, MsoOpenstackException - // could be thrown. - long subStartTime = System.currentTimeMillis(); try { heat.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true); } catch (MsoException me) { @@ -2033,7 +2015,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { outputs.value = copyStringOutputs(heatStack.getOutputs()); rollback.value = vfRollback; - return; } private String getVfModuleNameFromModuleStackId(String vfModuleStackId) { @@ -2199,13 +2180,13 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { Map<String, Object> newInputs = vur.getParameters(); if (newInputs != null) { Map<String, Object> oldGold = goldenInputs; - logger.debug("parameters before being modified by valet:{}", oldGold.toString()); - goldenInputs = new HashMap<String, Object>(); + logger.debug("parameters before being modified by valet:{}", oldGold); + goldenInputs = new HashMap<>(); for (String key : newInputs.keySet()) { goldenInputs.put(key, newInputs.get(key)); } valetModifiedParamsHolder.value = goldenInputs; - logger.debug("parameters after being modified by valet:{}", goldenInputs.toString()); + logger.debug("parameters after being modified by valet:{}", goldenInputs); valetSucceeded = true; } } else { 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 9d6c944747..d092b49d8c 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 @@ -83,6 +83,8 @@ 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 OPENSTACK = "OpenStack"; @Autowired protected CloudConfig cloudConfig; @@ -190,9 +192,8 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { me.addContext("QueryVNF"); String error = "Query VNF (Cloudify): " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, - cloudSiteId, tenantId, CLOUDIFY, "QueryVNF", ErrorCode.DataError.getValue(), - "Exception - queryDeployment", me); + logger.error(BRACKETS, MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, tenantId, + CLOUDIFY, "QueryVNF", ErrorCode.DataError.getValue(), "Exception - queryDeployment", me); logger.debug(error); throw new VnfException(me); } @@ -241,7 +242,7 @@ public class MsoVnfCloudifyAdapterImpl 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("{} {} {}", MessageEnum.RA_ROLLBACK_NULL.toString(), OPENSTACK, "rollbackVnf"); return; } @@ -281,8 +282,8 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { me.addContext("RollbackVNF"); String error = "Rollback VF Module: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, - cloudSiteId, tenantId, CLOUDIFY, "DeleteDeployment", ErrorCode.DataError.getValue(), + logger.error(BRACKETS, MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, cloudSiteId, + tenantId, CLOUDIFY, "DeleteDeployment", ErrorCode.DataError.getValue(), "Exception - DeleteDeployment", me); logger.debug(error); throw new VnfException(me); @@ -607,7 +608,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("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, OPENSTACK, ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); @@ -647,9 +648,9 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { if (failIfExists != null && failIfExists) { String error = "Create VF: Deployment " + vfModuleName + " already exists in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), - vfModuleName, cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", - ErrorCode.DataError.getValue(), "Deployment " + vfModuleName + " already exists"); + logger.error(BRACKETS, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), + "Deployment " + vfModuleName + " already exists"); logger.debug(error); throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId()); @@ -668,8 +669,8 @@ public class MsoVnfCloudifyAdapterImpl 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, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), + logger.error(BRACKETS, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), "Deployment " + vfModuleName + " already exists"); logger.debug(error); throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId()); @@ -677,8 +678,8 @@ public class MsoVnfCloudifyAdapterImpl 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, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), + logger.error(BRACKETS, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), "Deployment " + vfModuleName + " already " + "exists and is in FAILED state"); logger.debug(error); throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId()); @@ -687,8 +688,8 @@ public class MsoVnfCloudifyAdapterImpl 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, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), + logger.error(BRACKETS, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), "Deployment " + vfModuleName + " already " + "exists and is in " + status.toString() + " state"); logger.debug(error); @@ -698,8 +699,8 @@ public class MsoVnfCloudifyAdapterImpl 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, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), + logger.error(BRACKETS, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, + cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), "Deployment " + vfModuleName + " already " + "exists and is in an unknown state"); logger.debug(error); throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId()); @@ -721,9 +722,9 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { // Failed to query the Volume GroupDeployment due to a cloudify 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, CLOUDIFY, "queryDeployment(volume)", - ErrorCode.DataError.getValue(), "Exception - queryDeployment(volume)", me); + logger.error(BRACKETS, MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, cloudOwner, cloudSiteId, + tenantId, CLOUDIFY, "queryDeployment(volume)", ErrorCode.DataError.getValue(), + "Exception - queryDeployment(volume)", me); logger.debug(error); // Convert to a generic VnfException me.addContext("CreateVFModule(QueryVolume)"); @@ -733,9 +734,8 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { if (volumeDeployment == null || volumeDeployment.getStatus() == DeploymentStatus.NOTFOUND) { String error = "Create VFModule: Attached Volume Group DOES NOT EXIST " + volumeGroupId + " in " + cloudSiteId + "/" + tenantId + " USER ERROR"; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, - cloudSiteId, tenantId, error, CLOUDIFY, "queryDeployment(volume)", - ErrorCode.BusinessProcesssError.getValue(), + logger.error(BRACKETS, MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, cloudSiteId, tenantId, + error, CLOUDIFY, "queryDeployment(volume)", ErrorCode.BusinessProcesssError.getValue(), "Create VFModule: Attached Volume Group DOES NOT EXIST"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); @@ -771,9 +771,9 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { // Failed to query the Volume GroupDeployment due to a cloudify exception. String error = "Create VF Module: Query Base " + baseVfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, - cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment(Base)", - ErrorCode.DataError.getValue(), "Exception - queryDeployment(Base)", me); + logger.error(BRACKETS, MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, cloudOwner, + cloudSiteId, tenantId, CLOUDIFY, "queryDeployment(Base)", ErrorCode.DataError.getValue(), + "Exception - queryDeployment(Base)", me); logger.debug(error); // Convert to a generic VnfException me.addContext("CreateVFModule(QueryBase)"); @@ -783,8 +783,8 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { if (baseDeployment == null || baseDeployment.getStatus() == DeploymentStatus.NOTFOUND) { String error = "Create VFModule: Base Module DOES NOT EXIST " + baseVfModuleId + " in " + cloudSiteId + "/" + tenantId + " USER ERROR"; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, - cloudSiteId, tenantId, error, CLOUDIFY, "queryDeployment(Base)", + logger.error(BRACKETS, MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, cloudSiteId, + tenantId, error, CLOUDIFY, "queryDeployment(Base)", ErrorCode.BusinessProcesssError.getValue(), "Create VFModule: Base " + "Module DOES NOT EXIST"); logger.debug(error); @@ -820,7 +820,7 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + ", reqType=" + requestType; logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", - vfModuleType, "OpenStack", ErrorCode.DataError.getValue(), error); + vfModuleType, OPENSTACK, ErrorCode.DataError.getValue(), error); throw new VnfException(error, MsoExceptionCategory.INTERNAL); } else { logger.debug("Got HEAT Template from DB: {}", heatTemplate.getHeatTemplate()); @@ -829,7 +829,7 @@ 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", - "OpenStack", ErrorCode.DataError.getValue(), error); + OPENSTACK, ErrorCode.DataError.getValue(), error); // Alarm on this error, configuration must be fixed throw new VnfException(error, MsoExceptionCategory.INTERNAL); } else { @@ -1108,9 +1108,8 @@ public class MsoVnfCloudifyAdapterImpl 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, CLOUDIFY, "QueryDeployment", ErrorCode.DataError.getValue(), - "Exception - QueryDeployment", me); + logger.error(BRACKETS, MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, tenantId, + CLOUDIFY, "QueryDeployment", ErrorCode.DataError.getValue(), "Exception - QueryDeployment", me); logger.debug(error); throw new VnfException(me); } @@ -1130,8 +1129,8 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { // 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, "DeleteDeployment", "DeleteDeployment", ErrorCode.DataError.getValue(), + logger.error(BRACKETS, MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, tenantId, + "DeleteDeployment", "DeleteDeployment", ErrorCode.DataError.getValue(), "Exception - DeleteDeployment: " + me.getMessage()); logger.debug(error); throw new VnfException(me); 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 7b48d0b07f..ed797f10d9 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 @@ -68,7 +68,6 @@ import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.VnfRollback; import org.onap.so.openstack.beans.VnfStatus; -import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoExceptionCategory; import org.onap.so.openstack.utils.MsoHeatEnvironmentEntry; @@ -91,7 +90,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Transactional public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { - private static final String MSO_CONFIGURATION_ERROR = "MsoConfigurationError"; private static Logger logger = LoggerFactory.getLogger(MsoVnfPluginAdapterImpl.class); private static final String CHECK_REQD_PARAMS = "org.onap.so.adapters.vnf.checkRequiredParameters"; @@ -122,16 +120,8 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { protected VfModuleCustomizationToVduMapper vduMapper; /** - * Health Check web method. Does nothing but return to show the adapter is deployed. - */ - @Override - public void healthCheck() { - logger.debug("Health check call in VNF Plugin Adapter"); - } - - /** * DO NOT use that constructor to instantiate this class, the msoPropertiesfactory will be NULL. - * + * * @see MsoVnfPluginAdapterImpl#MsoVnfAdapterImpl(MsoPropertiesFactory, CloudConfigFactory) */ public MsoVnfPluginAdapterImpl() { @@ -139,6 +129,14 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { } /** + * Health Check web method. Does nothing but return to show the adapter is deployed. + */ + @Override + public void healthCheck() { + logger.debug("Health check call in VNF Plugin Adapter"); + } + + /** * This is the "Create VNF" web service implementation. This function is now unsupported and will return an 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 e81b211b27..20ce4170af 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 @@ -379,7 +379,7 @@ public class VnfAdapterRest { BpelRestClient bpelClient = bpelRestClientProvider.get(); bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); } - logger.debug("CreateVfModuleTask exit: code=" + getStatusCode() + RESP + getResponse()); + logger.debug("CreateVfModuleTask exit: code=" + getStatusCode()); } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify_Service.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify_Service.java index 073ea35f9e..402d0af8e4 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify_Service.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify_Service.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,7 +31,7 @@ import javax.xml.ws.WebServiceFeature; /** * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.9-b14002 Generated source version: 2.2 - * + * */ @WebServiceClient(name = "vnfAdapterNotify", targetNamespace = "http://org.onap.so/vnfNotify", wsdlLocation = "/VnfAdapterNotify.wsdl") @@ -39,7 +39,8 @@ public class VnfAdapterNotify_Service extends Service { private static final URL VNFADAPTERNOTIFY_WSDL_LOCATION; private static final WebServiceException VNFADAPTERNOTIFY_EXCEPTION; - private static final QName VNFADAPTERNOTIFY_QNAME = new QName("http://org.onap.so/vnfNotify", "vnfAdapterNotify"); + private static final String VNF_NOTIFY_URL = "http://org.onap.so/vnfNotify"; + private static final QName VNFADAPTERNOTIFY_QNAME = new QName(VNF_NOTIFY_URL, "vnfAdapterNotify"); static { VNFADAPTERNOTIFY_WSDL_LOCATION = org.onap.so.adapters.vnf.async.client.VnfAdapterNotify_Service.class @@ -77,25 +78,23 @@ public class VnfAdapterNotify_Service extends Service { } /** - * + * * @return returns VnfAdapterNotify */ @WebEndpoint(name = "MsoVnfAdapterAsyncImplPort") public VnfAdapterNotify getMsoVnfAdapterAsyncImplPort() { - return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"), - VnfAdapterNotify.class); + return super.getPort(new QName(VNF_NOTIFY_URL, "MsoVnfAdapterAsyncImplPort"), VnfAdapterNotify.class); } /** - * + * * @param features A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features * not in the <code>features</code> parameter will have their default values. * @return returns VnfAdapterNotify */ @WebEndpoint(name = "MsoVnfAdapterAsyncImplPort") public VnfAdapterNotify getMsoVnfAdapterAsyncImplPort(WebServiceFeature... features) { - return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"), - VnfAdapterNotify.class, features); + return super.getPort(new QName(VNF_NOTIFY_URL, "MsoVnfAdapterAsyncImplPort"), VnfAdapterNotify.class, features); } private static URL getWsdlLocation() { diff --git a/adapters/mso-openstack-adapters/src/main/resources/application.yaml b/adapters/mso-openstack-adapters/src/main/resources/application.yaml index f66d77db48..1982961ae7 100644 --- a/adapters/mso-openstack-adapters/src/main/resources/application.yaml +++ b/adapters/mso-openstack-adapters/src/main/resources/application.yaml @@ -25,10 +25,10 @@ spring: driver-class-name: org.mariadb.jdbc.Driver initialization-mode: never jpa: - show-sql: true + show-sql: false hibernate: dialect: org.hibernate.dialect.MySQL5Dialect - ddl-auto: validate + ddl-auto: none naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy enable-lazy-load-no-trans: true org: diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/AllTestsTestSuite.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/AllTestsTestSuite.java index a7bddd3ada..a9365a3946 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/AllTestsTestSuite.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/AllTestsTestSuite.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.vnf; +package org.onap.so; import org.junit.runner.RunWith; import com.googlecode.junittoolbox.SuiteClasses; diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceDataTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceDataTest.java index 80b2a21419..f23486c45c 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceDataTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceDataTest.java @@ -37,6 +37,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.so.audit.beans.AuditInventory; +import org.onap.so.objects.audit.AAIObjectAuditList; import org.springframework.core.env.Environment; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java index d43dbd99f9..2075557721 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java @@ -48,6 +48,7 @@ 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.objects.audit.AAIObjectAuditList; import org.skyscreamer.jsonassert.JSONAssert; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonParseException; diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java index bc7ce53b8d..c995064ab2 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java @@ -43,6 +43,7 @@ import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.LInterface; import org.onap.aai.domain.yang.LInterfaces; import org.onap.aai.domain.yang.Vserver; +import org.onap.so.objects.audit.AAIObjectAuditList; import org.onap.so.openstack.utils.MsoHeatUtils; import org.onap.so.openstack.utils.MsoNeutronUtils; import org.skyscreamer.jsonassert.JSONAssert; diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java index 0fd2bd4b7f..8226f4fed8 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java @@ -38,12 +38,12 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.onap.so.adapters.audit.AAIObjectAuditList; import org.onap.so.audit.beans.AuditInventory; 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.objects.audit.AAIObjectAuditList; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; 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 new file mode 100644 index 0000000000..8513f30d4b --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateInventoryTaskTest.java @@ -0,0 +1,56 @@ +package org.onap.so.adapters.inventory.create; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.objects.audit.AAIObjectAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; +import com.fasterxml.jackson.core.JsonProcessingException; + +public class CreateInventoryTaskTest { + + @Mock + ExternalTask externalTask; + + @Mock + CreateAAIInventory createAAIInventory; + + @Mock + ExternalTaskService externalTaskService; + + @InjectMocks + CreateInventoryTask inventoryTask; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void test_Runtime_Parse_Exception() { + doReturn(null).when(externalTask).getVariable("auditInventoryResult"); + inventoryTask.executeExternalTask(externalTask, externalTaskService); + Mockito.verify(externalTaskService, times(1)).handleBpmnError(externalTask, "AAIInventoryFailure"); + } + + @Test + public void testExecuteExternalTask_InventoryException() throws InventoryException, JsonProcessingException { + AAIObjectAuditList object = new AAIObjectAuditList(); + AAIObjectAudit e = new AAIObjectAudit(); + e.setDoesObjectExist(true); + object.getAuditList().add(e); + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + doReturn(objectMapper.getMapper().writeValueAsString(e)).when(externalTask).getVariable("auditInventoryResult"); + Mockito.doThrow(InventoryException.class).when(createAAIInventory).createInventory(Mockito.any()); + inventoryTask.executeExternalTask(externalTask, externalTaskService); + Mockito.verify(externalTaskService, times(1)).handleBpmnError(externalTask, "AAIInventoryFailure"); + } +} diff --git a/adapters/mso-openstack-adapters/src/test/resources/GetResources.json b/adapters/mso-openstack-adapters/src/test/resources/GetResources.json index 0d403a62b5..d4e84fb3c9 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/GetResources.json +++ b/adapters/mso-openstack-adapters/src/test/resources/GetResources.json @@ -90,7 +90,7 @@ "resource_status_reason": "state changed", "resource_type": "OS::Heat::ResourceGroup", "updated_time": "2019-01-23T19:34:15Z" - }, + }, { "links": [ { diff --git a/adapters/mso-openstack-adapters/src/test/resources/application-nomigrate.yaml b/adapters/mso-openstack-adapters/src/test/resources/application-nomigrate.yaml index d1a5bd9fa3..20384465a1 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/application-nomigrate.yaml +++ b/adapters/mso-openstack-adapters/src/test/resources/application-nomigrate.yaml @@ -113,3 +113,20 @@ management: endpoint: info: enabled: true + +appc: + client: + key: iaEMAfjsVsZnraBP + response: + timeout: '120000' + secret: wcivUjsjXzmGFBfxMmyJu9dz + poolMembers: localhost + service: ueb + topic: + read: + name: APPC-TEST-AMDOCS2 + timeout: '120000' + write: APPC-TEST-AMDOCS1-DEV3 + sdnc: + read: SDNC-LCM-READ + write: SDNC-LCM-WRITE
\ 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 694aedae10..ce576f00e1 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml +++ b/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml @@ -106,7 +106,6 @@ mariaDB4j: port: 3308 databaseName: catalogdb - #Actuator management: endpoints: @@ -121,3 +120,20 @@ management: prometheus: enabled: true # Whether exporting of metrics to Prometheus is enabled. step: 1m # Step size (i.e. reporting frequency) to use. + +appc: + client: + key: iaEMAfjsVsZnraBP + response: + timeout: '120000' + secret: wcivUjsjXzmGFBfxMmyJu9dz + poolMembers: localhost + service: ueb + topic: + read: + name: APPC-TEST-AMDOCS2 + timeout: '120000' + write: APPC-TEST-AMDOCS1-DEV3 + sdnc: + read: SDNC-LCM-READ + write: SDNC-LCM-WRITE diff --git a/adapters/mso-openstack-adapters/src/test/resources/schema.sql b/adapters/mso-openstack-adapters/src/test/resources/schema.sql index dbb3469e77..83023e53db 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/schema.sql +++ b/adapters/mso-openstack-adapters/src/test/resources/schema.sql @@ -803,6 +803,7 @@ 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), 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 @@ -1106,6 +1107,7 @@ CREATE TABLE `vnf_resource_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), KEY `fk_vnf_resource_customization__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`), @@ -1132,6 +1134,8 @@ CREATE TABLE `vnfc_customization` ( `MODEL_NAME` varchar(200) NOT NULL, `TOSCA_NODE_TYPE` varchar(200) NOT NULL, `DESCRIPTION` varchar(1200) DEFAULT NULL, + `RESOURCE_INPUT` varchar(20000) DEFAULT NULL, + `VNFC_INSTANCE_GROUP_CUSTOMIZATION_ID` integer DEFAULT NULL, `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; @@ -1196,6 +1200,14 @@ CREATE TABLE IF NOT EXISTS `pnf_resource_customization_to_service` ( PRIMARY KEY (`SERVICE_MODEL_UUID`,`RESOURCE_MODEL_CUSTOMIZATION_UUID`) )ENGINE=InnoDB DEFAULT CHARSET=latin1; +CREATE TABLE IF NOT EXISTS `homing_instances` ( +`SERVICE_INSTANCE_ID` varchar(50) NOT NULL, +`CLOUD_OWNER` VARCHAR(200) NOT NULL, +`CLOUD_REGION_ID` VARCHAR(200) NOT NULL, +`OOF_DIRECTIVES` longtext NULL DEFAULT NULL, +PRIMARY KEY (`SERVICE_INSTANCE_ID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + CREATE TABLE IF NOT EXISTS `workflow` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `ARTIFACT_UUID` varchar(200) NOT NULL, @@ -1226,4 +1238,134 @@ CREATE TABLE IF NOT EXISTS `vnf_resource_to_workflow` ( CONSTRAINT `fk_vnf_resource_to_workflow__workflow1` FOREIGN KEY (`WORKFLOW_ID`) REFERENCES `workflow` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1; +CREATE TABLE IF NOT EXISTS `activity_spec` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `NAME` VARCHAR(200) NOT NULL, + `DESCRIPTION` VARCHAR(1200) NOT NULL, + `VERSION` DOUBLE NOT NULL, + `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_activity_spec` (`NAME` ASC, `VERSION` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `user_parameters` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `NAME` VARCHAR(200) NOT NULL, + `PAYLOAD_LOCATION` VARCHAR(500) NULL, + `LABEL` VARCHAR(200) NOT NULL, + `TYPE` VARCHAR(200) NOT NULL, + `DESCRIPTION` VARCHAR(1200) NULL, + `IS_REQUIRED` TINYINT(1) NOT NULL, + `MAX_LENGTH` INT(11) NULL, + `ALLOWABLE_CHARS` VARCHAR(200) NULL, + `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_user_parameters` (`NAME` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `workflow_activity_spec_sequence` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `WORKFLOW_ID` INT(11) NOT NULL, + `ACTIVITY_SPEC_ID` INT(11) NOT NULL, + `SEQ_NO` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_workflow_activity_spec_sequence` (`WORKFLOW_ID` ASC, `ACTIVITY_SPEC_ID` ASC, `SEQ_NO` ASC), + INDEX `fk_workflow_activity_spec_sequence__activity_spec_idx` (`ACTIVITY_SPEC_ID` ASC), + INDEX `fk_workflow_activity_spec_sequence__workflow_actifact_uuid_idx` (`WORKFLOW_ID` ASC), + CONSTRAINT `fk_workflow_activity_spec_sequence__activity_spec1` + FOREIGN KEY (`ACTIVITY_SPEC_ID`) + REFERENCES `activity_spec` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_workflow_activity_spec_sequence__workflow1` + FOREIGN KEY (`WORKFLOW_ID`) + REFERENCES `workflow` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `activity_spec_parameters` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `NAME` VARCHAR(200) NOT NULL, + `TYPE` VARCHAR(200) NOT NULL, + `DIRECTION` VARCHAR(200) NULL, + `DESCRIPTION` VARCHAR(1200) NULL, + `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_activity_spec_parameters` (`NAME` ASC, `DIRECTION` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; +CREATE TABLE IF NOT EXISTS `activity_spec_categories` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `NAME` VARCHAR(200) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_activity_spec_categories` (`NAME` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `activity_spec_to_activity_spec_categories` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `ACTIVITY_SPEC_ID` INT(11) NOT NULL, + `ACTIVITY_SPEC_CATEGORIES_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_activity_spec_to_activity_spec_categories` (`ACTIVITY_SPEC_ID` ASC, `ACTIVITY_SPEC_CATEGORIES_ID` ASC), + INDEX `fk_activity_spec_to_activity_spec_categories__activity_spec_idx` (`ACTIVITY_SPEC_CATEGORIES_ID` ASC), + INDEX `fk_activity_spec_to_activity_spec_categories__activity_spec_idx1` (`ACTIVITY_SPEC_ID` ASC), + CONSTRAINT `fk_activity_spec_to_activity_spec_categories__activity_spec1` + FOREIGN KEY (`ACTIVITY_SPEC_ID`) + REFERENCES `activity_spec` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_activity_spec_to_activity_spec_categories__activity_spec_c1` + FOREIGN KEY (`ACTIVITY_SPEC_CATEGORIES_ID`) + REFERENCES `activity_spec_categories` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `activity_spec_to_activity_spec_parameters` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `ACTIVITY_SPEC_ID` INT(11) NOT NULL, + `ACTIVITY_SPEC_PARAMETERS_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + INDEX `fk_activity_spec_to_activity_spec_params__act_sp_param_id_idx` (`ACTIVITY_SPEC_PARAMETERS_ID` ASC), + UNIQUE INDEX `UK_activity_spec_to_activity_spec_parameters` (`ACTIVITY_SPEC_ID` ASC, `ACTIVITY_SPEC_PARAMETERS_ID` ASC), + INDEX `fk_activity_spec_to_activity_spec_parameters__act_spec_id_idx` (`ACTIVITY_SPEC_ID` ASC), + CONSTRAINT `fk_activity_spec_to_activity_spec_parameters__activity_spec_1` + FOREIGN KEY (`ACTIVITY_SPEC_ID`) + REFERENCES `activity_spec` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_activity_spec_to_activity_spec_parameters__activ_spec_param1` + FOREIGN KEY (`ACTIVITY_SPEC_PARAMETERS_ID`) + REFERENCES `activity_spec_parameters` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `activity_spec_to_user_parameters` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `ACTIVITY_SPEC_ID` INT(11) NOT NULL, + `USER_PARAMETERS_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_activity_spec_to_user_parameters` (`ACTIVITY_SPEC_ID` ASC, `USER_PARAMETERS_ID` ASC), + INDEX `fk_activity_spec_to_user_parameters__user_parameters1_idx` (`USER_PARAMETERS_ID` ASC), + INDEX `fk_activity_spec_to_user_parameters__activity_spec1_idx` (`ACTIVITY_SPEC_ID` ASC), + CONSTRAINT `fk_activity_spec_to_user_parameters__activity_spec1` + FOREIGN KEY (`ACTIVITY_SPEC_ID`) + REFERENCES `activity_spec` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_activity_spec_to_user_parameters__user_parameters1` + FOREIGN KEY (`USER_PARAMETERS_ID`) + REFERENCES `user_parameters` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; diff --git a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V5.7__Add_OpenStack_Request_Information.sql b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V5.7__Add_OpenStack_Request_Information.sql new file mode 100644 index 0000000000..5635a1eb80 --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V5.7__Add_OpenStack_Request_Information.sql @@ -0,0 +1,13 @@ +use requestdb; + +CREATE TABLE IF NOT EXISTS cloud_api_requests( +`ID` INT(13) NOT NULL AUTO_INCREMENT, +`REQUEST_BODY` LONGTEXT NOT NULL, +`CLOUD_IDENTIFIER` VARCHAR(200) NULL, +`SO_REQUEST_ID` VARCHAR(45) NOT NULL, +`CREATE_TIME` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, +PRIMARY KEY (`ID`), +CONSTRAINT fk_cloud_api_req_infra_requests + FOREIGN KEY (SO_REQUEST_ID) + REFERENCES infra_active_requests (REQUEST_ID)) +ENGINE = InnoDB DEFAULT CHARSET=latin1;
\ No newline at end of file diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/HealthCheckHandlerTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/HealthCheckHandlerTest.java index 514e5ad923..9faba0df67 100644 --- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/HealthCheckHandlerTest.java +++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/HealthCheckHandlerTest.java @@ -50,35 +50,10 @@ public class HealthCheckHandlerTest extends RequestsAdapterBase { @Test public void testHealthcheck() throws JSONException { - TestAppender.events.clear(); HttpEntity<String> entity = new HttpEntity<String>(null, headers); - ResponseEntity<String> response = restTemplate.exchange(createURLWithPort("/manage/health"), HttpMethod.GET, entity, String.class); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INSTANCE_UUID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("/manage/health", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor") - && logEvent.getMarker() != null && logEvent.getMarker() != null - && logEvent.getMarker().getName().equals("EXIT")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("200", mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("/manage/health", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("COMPLETED", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } - TestAppender.events.clear(); } private String createURLWithPort(String uri) { diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java index 3b737c6768..03df115574 100644 --- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java +++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java @@ -25,6 +25,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.onap.so.adapters.requestsdb.RequestsAdapterBase; import org.onap.so.adapters.requestsdb.application.MSORequestDBApplication; +import org.onap.so.db.request.beans.CloudApiRequests; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.beans.OperationStatus; import org.onap.so.db.request.beans.OperationalEnvDistributionStatus; @@ -41,9 +42,9 @@ import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertFalse; @@ -87,6 +88,14 @@ public class RequestsDbClientTest extends RequestsAdapterBase { infraActiveRequests.setRequestAction("someaction"); infraActiveRequests .setRequestUrl("http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances"); + List<CloudApiRequests> cloudApiRequests = new ArrayList<>(); + CloudApiRequests cloudRequest = new CloudApiRequests(); + cloudRequest.setCloudIdentifier("heatstackanme/id"); + cloudRequest.setId(1); + cloudRequest.setRequestBody("requestBody"); + cloudRequest.setRequestId(infraActiveRequests.getRequestId()); + cloudApiRequests.add(cloudRequest); + infraActiveRequests.setCloudApiRequests(cloudApiRequests); requestsDbClient.save(infraActiveRequests); } @@ -96,7 +105,8 @@ public class RequestsDbClientTest extends RequestsAdapterBase { private void verifyInfraActiveRequests(InfraActiveRequests infraActiveRequestsResponse) { - assertThat(infraActiveRequestsResponse, sameBeanAs(infraActiveRequests).ignoring("modifyTime").ignoring("log")); + assertThat(infraActiveRequestsResponse, sameBeanAs(infraActiveRequests).ignoring("modifyTime").ignoring("log") + .ignoring("cloudApiRequests.created").ignoring("cloudApiRequests.id")); } @Test @@ -113,7 +123,6 @@ public class RequestsDbClientTest extends RequestsAdapterBase { verifyInfraActiveRequests(infraActiveRequestsResponse); } - @Test public void checkVnfIdStatusTest() { InfraActiveRequests infraActiveRequestsResponse = @@ -182,7 +191,7 @@ public class RequestsDbClientTest extends RequestsAdapterBase { public void getInfraActiveRequestbyRequestIdWhereRequestUrlNullTest() { // requestUrl setup to null and save infraActiveRequests.setRequestUrl(null); - requestsDbClient.save(infraActiveRequests); + requestsDbClient.updateInfraActiveRequests(infraActiveRequests); InfraActiveRequests infraActiveRequestsResponse = requestsDbClient.getInfraActiveRequestbyRequestId(infraActiveRequests.getRequestId()); verifyInfraActiveRequests(infraActiveRequestsResponse); diff --git a/adapters/mso-requests-db-adapter/src/test/resources/logback-test.xml b/adapters/mso-requests-db-adapter/src/test/resources/logback-test.xml index d1596cd374..a63bd27378 100644 --- a/adapters/mso-requests-db-adapter/src/test/resources/logback-test.xml +++ b/adapters/mso-requests-db-adapter/src/test/resources/logback-test.xml @@ -1,18 +1,7 @@ <configuration> - <property name="p_tim" value="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX", UTC}"/> - <property name="p_lvl" value="%level"/> - <property name="p_log" value="%logger"/> - <property name="p_mdc" value="%replace(%replace(%mdc){'\t','\\\\t'}){'\n', '\\\\n'}"/> - <property name="p_msg" value="%replace(%replace(%msg){'\t', '\\\\t'}){'\n','\\\\n'}"/> - <property name="p_exc" value="%replace(%replace(%rootException){'\t', '\\\\t'}){'\n','\\\\n'}"/> - <property name="p_mak" value="%replace(%replace(%marker){'\t', '\\\\t'}){'\n','\\\\n'}"/> - <property name="p_thr" value="%thread"/> - <property name="pattern" value="%nopexception${p_tim}\t${p_thr}\t${p_lvl}\t${p_log}\t${p_mdc}\t${p_msg}\t${p_exc}\t${p_mak}\t%n"/> - - <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> - <pattern>${pattern}</pattern> + <pattern>%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}||%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}||%X{Timer}|%msg%n</pattern> </encoder> </appender> @@ -44,6 +33,10 @@ <logger name="ch.vorburger" level="WARN" additivity="false"> <appender-ref ref="STDOUT" /> </logger> + + <logger name="org.hibernate" level="DEBUG" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> <root level="WARN"> 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 21ce06eaf1..7d412b77ad 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 @@ -5,7 +5,7 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ - * Modifications Copyright (C) 2018 IBM. + * Modifications Copyright (C) 2019 IBM. * Modifications Copyright (c) 2019 Samsung * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -77,13 +77,12 @@ public class SDNCRestClient { private static Logger logger = LoggerFactory.getLogger(SDNCRestClient.class); private static final String EXCEPTION_MSG = "Exception while evaluate xpath"; - private static final String MSO_INTERNAL_ERROR = "MsoInternalError"; private static final String CAMUNDA = "Camunda"; @Async public void executeRequest(SDNCAdapterRequest bpelRequest) { - logger.debug("BPEL Request:" + bpelRequest.toString()); + logger.debug("BPEL Request: {}", bpelRequest); // Added delay to allow completion of create request to SDNC // before executing activate of create request. @@ -96,8 +95,6 @@ public class SDNCRestClient { Thread.currentThread().interrupt(); } - String action = bpelRequest.getRequestHeader().getSvcAction(); - String operation = bpelRequest.getRequestHeader().getSvcOperation(); String bpelReqId = bpelRequest.getRequestHeader().getRequestId(); String callbackUrl = bpelRequest.getRequestHeader().getCallbackUrl(); @@ -118,12 +115,9 @@ public class SDNCRestClient { Document reqDoc = node.getOwnerDocument(); sdncReqBody = Utils.genSdncPutReq(reqDoc, rt); } - long sdncStartTime = System.currentTimeMillis(); SDNCResponse sdncResp = getSdncResp(sdncReqBody, rt); logger.debug("Got the SDNC Response: {}", sdncResp.getSdncRespXml()); - long bpelStartTime = System.currentTimeMillis(); sendRespToBpel(callbackUrl, sdncResp); - return; } public SDNCResponse getSdncResp(String sdncReqBody, RequestTunables rt) { @@ -288,7 +282,6 @@ public class SDNCRestClient { try { wsdlUrl = new URL(bpelUrl); } catch (MalformedURLException e1) { - error = "Caught exception initializing Callback wsdl " + e1.getMessage(); logger.error("{} {} {} {}", MessageEnum.RA_INIT_CALLBACK_WSDL_ERR.toString(), CAMUNDA, ErrorCode.DataError.getValue(), "Exception initializing Callback wsdl", e1); @@ -317,7 +310,6 @@ public class SDNCRestClient { reqCtx.put(MessageContext.HTTP_REQUEST_HEADERS, headers); headers.put("Authorization", Collections.singletonList(basicAuth)); } catch (Exception e2) { - error = "Unable to set authorization in callback request " + e2.getMessage(); logger.error("{} {} {} {}", MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA, ErrorCode.BusinessProcesssError.getValue(), "Exception - Unable to set authorization in callback request", e2); @@ -333,6 +325,5 @@ public class SDNCRestClient { MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), error, e); } logger.info(MessageEnum.RA_CALLBACK_BPEL_COMPLETE.name(), CAMUNDA); - return; } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml index 66a1cb1ca7..9d9e33a524 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml @@ -100,5 +100,10 @@ <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> + <dependency> + <groupId>com.squareup.okio</groupId> + <artifactId>okio</artifactId> + <version>1.13.0</version> + </dependency> </dependencies> </project> diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/pom.xml b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/pom.xml index da778d286e..91478e1f8e 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/pom.xml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/pom.xml @@ -62,7 +62,6 @@ <apiPackage>org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.api</apiPackage> <modelPackage>org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model</modelPackage> <configOptions> - <jackson>true</jackson> <sourceFolder>src/gen/java/main</sourceFolder> <withXml>true</withXml> <useRxJava2>true</useRxJava2> @@ -79,15 +78,16 @@ <inputSpec>${basedir}/src/main/resources/SOL003-VNFLifecycleOperationGranting-API.json </inputSpec> <language>java</language> - <library>retrofit2</library> + <library>okhttp-gson</library> <output>${project.build.directory}/generated-sources/sol003-vnf-grant</output> - <generateApis>false</generateApis> + <apiPackage>org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.api</apiPackage> <modelPackage>org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model</modelPackage> <configOptions> <generateSupportingFiles>false</generateSupportingFiles> <sourceFolder>src/gen/java/main</sourceFolder> <withXml>true</withXml> <useRxJava2>true</useRxJava2> + <serializableModel>true</serializableModel> </configOptions> </configuration> </execution> diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/pom.xml b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/pom.xml index c561721b3e..09c28f93f1 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/pom.xml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/pom.xml @@ -63,6 +63,12 @@ <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> + <exclusions> + <exclusion> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-databind</artifactId> + </exclusion> + </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmAdapterApplication.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmAdapterApplication.java index 30ce0c2253..62d2f7e2a9 100755 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmAdapterApplication.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmAdapterApplication.java @@ -20,11 +20,13 @@ package org.onap.so.adapters.vnfmadapter; +import static org.slf4j.LoggerFactory.getLogger; import org.onap.so.adapters.vnfmadapter.rest.VnfmAdapterController; import org.slf4j.Logger; import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; -import static org.slf4j.LoggerFactory.getLogger; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; /** * The spring boot application for the VNFM (Virtual Network Function Manager) Adapter. @@ -36,6 +38,7 @@ import static org.slf4j.LoggerFactory.getLogger; * SOL003 v2.5.1</a> */ @SpringBootApplication(scanBasePackages = {"org.onap.so"}) +@EnableAutoConfiguration(exclude = {JacksonAutoConfiguration.class}) public class VnfmAdapterApplication { private static final Logger logger = getLogger(VnfmAdapterApplication.class); diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/SdcPackageProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/SdcPackageProvider.java index f1074bcba8..fd92910e36 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/SdcPackageProvider.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/SdcPackageProvider.java @@ -22,20 +22,21 @@ package org.onap.so.adapters.vnfmadapter.extclients; +import static com.google.common.base.Splitter.on; +import static com.google.common.collect.Iterables.filter; +import static com.google.common.io.ByteStreams.toByteArray; +import static java.lang.String.format; +import static org.apache.http.HttpHeaders.ACCEPT; +import static org.apache.http.HttpHeaders.AUTHORIZATION; +import static org.onap.so.adapters.vnfmadapter.NvfmAdapterUtils.abortOperation; +import static org.onap.so.adapters.vnfmadapter.NvfmAdapterUtils.child; +import static org.onap.so.adapters.vnfmadapter.NvfmAdapterUtils.childElement; +import static org.onap.so.adapters.vnfmadapter.NvfmAdapterUtils.children; +import static org.slf4j.LoggerFactory.getLogger; +import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE; import com.google.common.io.ByteStreams; import com.google.gson.Gson; import com.google.gson.JsonObject; -import org.apache.commons.codec.binary.Base64; -import org.apache.http.HttpEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.onap.so.utils.CryptoUtils; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; -import org.yaml.snakeyaml.Yaml; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -48,25 +49,24 @@ import java.util.NoSuchElementException; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; -import static com.google.common.base.Splitter.on; -import static com.google.common.collect.Iterables.filter; -import static com.google.common.io.ByteStreams.toByteArray; -import static java.lang.String.format; -import static org.apache.http.HttpHeaders.ACCEPT; -import static org.apache.http.HttpHeaders.AUTHORIZATION; -import static org.onap.so.adapters.vnfmadapter.NvfmAdapterUtils.abortOperation; -import static org.onap.so.adapters.vnfmadapter.NvfmAdapterUtils.child; -import static org.onap.so.adapters.vnfmadapter.NvfmAdapterUtils.childElement; -import static org.onap.so.adapters.vnfmadapter.NvfmAdapterUtils.children; -import static org.slf4j.LoggerFactory.getLogger; -import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.onap.so.utils.CryptoUtils; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.yaml.snakeyaml.Yaml; @Component public class SdcPackageProvider { - private static final String GET_PACKAGE_URL = "%s/catalog/resources/%s/toscaModel"; + private static final String GET_PACKAGE_URL = "%s/sdc/v1/catalog/resources/%s/toscaModel"; @Value("${sdc.toscametapath:TOSCA-Metadata/TOSCA.meta}") private List<String> toscaMetaPaths; - private final String TOSCA_VNFD_KEY = "Entry-Definitions"; + private static final String TOSCA_VNFD_KEY = "Entry-Definitions"; private static Logger logger = getLogger(SdcPackageProvider.class); @Value("${sdc.username}") @@ -78,7 +78,7 @@ public class SdcPackageProvider { @Value("${sdc.endpoint}") private String baseUrl; - public String getVnfdId(String csarId) { + public String getVnfdId(final String csarId) { return getVnfNodeProperty(csarId, "descriptor_id"); } @@ -96,7 +96,7 @@ public class SdcPackageProvider { for (final JsonObject child : children(nodeTemplates)) { final String type = childElement(child, "type").getAsString(); String propertyValue = null; - if (type.equals("tosca.nodes.nfv.VNF")) { + if ("tosca.nodes.nfv.VNF".equals(type)) { final JsonObject properties = child(child, "properties"); logger.debug("properties: " + properties.toString()); @@ -119,7 +119,7 @@ public class SdcPackageProvider { final JsonObject nodeTypes = child(root, "node_types"); final JsonObject nodeType = child(nodeTypes, nodeTypeName); - if (childElement(nodeType, "derived_from").getAsString().equals("tosca.nodes.nfv.VNF")) { + if ("tosca.nodes.nfv.VNF".equals(childElement(nodeType, "derived_from").getAsString())) { final JsonObject properties = child(nodeType, "properties"); logger.debug("properties: " + properties.toString()); final JsonObject property = child(properties, propertyName); @@ -130,34 +130,33 @@ public class SdcPackageProvider { return null; } - private byte[] getPackage(String csarId) { + private byte[] getPackage(final String csarId) { final String SERVICE_NAME = "vnfm-adapter"; try (CloseableHttpClient client = HttpClients.createDefault()) { - HttpGet httpget = new HttpGet(format(GET_PACKAGE_URL, baseUrl, csarId)); + final HttpGet httpget = new HttpGet(format(GET_PACKAGE_URL, baseUrl, csarId)); httpget.setHeader(ACCEPT, APPLICATION_OCTET_STREAM_VALUE); httpget.setHeader("X-ECOMP-InstanceID", SERVICE_NAME); httpget.setHeader("X-FromAppId", SERVICE_NAME); - String auth = sdcUsername + ":" + CryptoUtils.decrypt(sdcPassword, sdcKey); - byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1)); - String authHeader = "Basic " + new String(encodedAuth); + final String auth = sdcUsername + ":" + CryptoUtils.decrypt(sdcPassword, sdcKey); + final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1)); + final String authHeader = "Basic " + new String(encodedAuth); httpget.setHeader(AUTHORIZATION, authHeader); logger.debug("Fetching from SDC: " + httpget); - CloseableHttpResponse response = client.execute(httpget); - HttpEntity entity = response.getEntity(); - InputStream is = entity.getContent(); - byte[] bytes = toByteArray(is); - return bytes; - } catch (Exception e) { + final CloseableHttpResponse response = client.execute(httpget); + final HttpEntity entity = response.getEntity(); + final InputStream is = entity.getContent(); + return toByteArray(is); + } catch (final Exception e) { throw abortOperation("Unable to download " + csarId + " package from SDC", e); } } - private String getVnfdLocation(InputStream stream) throws IOException { - Iterator pathIterator = toscaMetaPaths.iterator(); + private String getVnfdLocation(final InputStream stream) throws IOException { + final Iterator<String> pathIterator = toscaMetaPaths.iterator(); while (pathIterator.hasNext()) { - String toscaMetadata = new String(getFileInZip(stream, pathIterator.next().toString()).toByteArray()); + final String toscaMetadata = new String(getFileInZip(stream, pathIterator.next()).toByteArray()); if (!toscaMetadata.isEmpty()) { - String toscaVnfdLine = + final String toscaVnfdLine = filter(on("\n").split(toscaMetadata), line -> line.contains(TOSCA_VNFD_KEY)).iterator().next(); return toscaVnfdLine.replace(TOSCA_VNFD_KEY + ":", "").trim(); } @@ -165,20 +164,21 @@ public class SdcPackageProvider { throw abortOperation("Unable to find valid Tosca Path"); } - private static ByteArrayOutputStream getFileInZip(InputStream zip, String path) throws IOException { - ZipInputStream zipInputStream = new ZipInputStream(zip); - ByteArrayOutputStream fileContent = getFileInZip(zipInputStream, path); + private static ByteArrayOutputStream getFileInZip(final InputStream zip, final String path) throws IOException { + final ZipInputStream zipInputStream = new ZipInputStream(zip); + final ByteArrayOutputStream fileContent = getFileInZip(zipInputStream, path); zipInputStream.close(); return fileContent; } - private static ByteArrayOutputStream getFileInZip(ZipInputStream zipInputStream, String path) throws IOException { + private static ByteArrayOutputStream getFileInZip(final ZipInputStream zipInputStream, final String path) + throws IOException { ZipEntry zipEntry; - Set<String> items = new HashSet<>(); + final Set<String> items = new HashSet<>(); while ((zipEntry = zipInputStream.getNextEntry()) != null) { items.add(zipEntry.getName()); if (zipEntry.getName().matches(path)) { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ByteStreams.copy(zipInputStream, byteArrayOutputStream); return byteArrayOutputStream; } @@ -187,7 +187,7 @@ public class SdcPackageProvider { throw new NoSuchElementException("Unable to find the " + path + " in archive found: " + items); } - public String getFlavourId(String csarId) { + public String getFlavourId(final String csarId) { return getVnfNodeProperty(csarId, "flavour_id"); } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiHelper.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiHelper.java index 50fd5bcf3a..1374e89a19 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiHelper.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiHelper.java @@ -20,6 +20,10 @@ package org.onap.so.adapters.vnfmadapter.extclients.aai; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.aai.domain.yang.EsrSystemInfoList; import org.onap.aai.domain.yang.EsrVnfm; @@ -40,9 +44,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; /** * Provides helper methods for interactions with AAI. @@ -110,7 +111,7 @@ public class AaiHelper { */ public String getIdOfAssignedVnfm(final GenericVnf vnf) { final Relationship relationship = getRelationship(vnf, "esr-vnfm"); - return getRelationshipKey(relationship, "esr-vnfm.vnfm-id"); + return getRelationshipData(relationship, "esr-vnfm.vnfm-id"); } /** @@ -121,9 +122,9 @@ public class AaiHelper { */ public Tenant getAssignedTenant(final GenericVnf vnf) { final Relationship relationship = getRelationship(vnf, "tenant"); - final String cloudOwner = getRelationshipKey(relationship, "cloud-region.cloud-owner"); - final String cloudRegion = getRelationshipKey(relationship, "cloud-region.cloud-region-id"); - final String tenantId = getRelationshipKey(relationship, "tenant.tenant-id"); + final String cloudOwner = getRelationshipData(relationship, "cloud-region.cloud-owner"); + final String cloudRegion = getRelationshipData(relationship, "cloud-region.cloud-region-id"); + final String tenantId = getRelationshipData(relationship, "tenant.tenant-id"); if (cloudOwner == null || cloudRegion == null || tenantId == null) { throw new TenantNotFoundException("No matching Tenant found in AAI. VNFID: " + vnf.getVnfId()); } else { @@ -141,10 +142,17 @@ public class AaiHelper { return null; } - private String getRelationshipKey(final Relationship relationship, final String relationshipKey) { + /** + * Get the value of the relationship data with the given key in the given relationship. + * + * @param relationship the relationship + * @param relationshipDataKey the key for the relationship data + * @return the value of the relationship data for the given key + */ + public String getRelationshipData(final Relationship relationship, final String relationshipDataKey) { if (relationship != null) { for (final RelationshipData relationshipData : relationship.getRelationshipData()) { - if (relationshipData.getRelationshipKey().equals(relationshipKey)) { + if (relationshipData.getRelationshipKey().equals(relationshipDataKey)) { return relationshipData.getRelationshipValue(); } } @@ -153,6 +161,32 @@ public class AaiHelper { } /** + * Delete from the given VNF the relationship matching the given criteria. + * + * @param vnf the VNF + * @param relationshipRelatedToValue the related-to value for the relationship + * @param dataKey the relationship data key to match on + * @param dataValue the value the relationship data with the given key must match + * @return the deleted relationship or <code>null</code> if none found matching the given criteria + */ + public Relationship deleteRelationshipWithDataValue(final GenericVnf vnf, final String relationshipRelatedToValue, + final String dataKey, final String dataValue) { + final Iterator<Relationship> relationships = + vnf.getRelationshipList() == null ? Collections.<Relationship>emptyList().iterator() + : vnf.getRelationshipList().getRelationship().iterator(); + + while (relationships.hasNext()) { + final Relationship relationship = relationships.next(); + if (relationship.getRelatedTo().equals(relationshipRelatedToValue) + && dataValue.equals(getRelationshipData(relationship, dataKey))) { + relationships.remove(); + return relationship; + } + } + return null; + } + + /** * Select a VNFM to use for the given generic VNF. Should only be used when no VNFM has already been assigned to the * VNF. * @@ -257,7 +291,12 @@ public class AaiHelper { relationship.setRelatedTo("tenant"); relationship.setRelatedLink("/aai/" + AAIVersion.LATEST + AAIUriFactory.createResourceUri(AAIObjectType.TENANT, tenant.getCloudOwner(), tenant.getRegionName(), tenant.getTenantId()).build().toString()); + relationship.getRelationshipData() + .add(createRelationshipData("cloud-region.cloud-owner", tenant.getCloudOwner())); + relationship.getRelationshipData() + .add(createRelationshipData("cloud-region.cloud-region-id", tenant.getRegionName())); relationship.getRelationshipData().add(createRelationshipData("tenant.tenant-id", tenant.getTenantId())); return relationship; } + } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProvider.java index f991ffafba..7021c02511 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProvider.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProvider.java @@ -24,9 +24,9 @@ import org.onap.aai.domain.yang.EsrSystemInfoList; import org.onap.aai.domain.yang.EsrVnfm; import org.onap.aai.domain.yang.EsrVnfmList; import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.GenericVnfs; import org.onap.aai.domain.yang.Vserver; import org.onap.vnfmadapter.v1.model.Tenant; -import java.util.List; /** * Provides methods for invoking REST calls to AAI. @@ -47,7 +47,7 @@ public interface AaiServiceProvider { * @param selfLink the selfLink * @return the matching generic vnfs */ - List<GenericVnf> invokeQueryGenericVnf(final String selfLink); + GenericVnfs invokeQueryGenericVnf(final String selfLink); /** * Invoke a GET request for the VNFMs. diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProviderImpl.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProviderImpl.java index fa07ab5720..50e579dd83 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProviderImpl.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProviderImpl.java @@ -24,6 +24,7 @@ import org.onap.aai.domain.yang.EsrSystemInfoList; import org.onap.aai.domain.yang.EsrVnfm; import org.onap.aai.domain.yang.EsrVnfmList; import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.GenericVnfs; import org.onap.aai.domain.yang.Vserver; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.entities.uri.AAIUriFactory; @@ -32,7 +33,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.util.List; @Service public class AaiServiceProviderImpl implements AaiServiceProvider { @@ -56,9 +56,9 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { } @Override - public List<GenericVnf> invokeQueryGenericVnf(final String selfLink) { + public GenericVnfs invokeQueryGenericVnf(final String selfLink) { return aaiClientProvider.getAaiClient() - .get(List.class, + .get(GenericVnfs.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNFS).queryParam("selflink", selfLink)) .orElseGet(() -> { logger.debug("No vnf found in AAI with selflink: {}", selfLink); @@ -104,7 +104,7 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { @Override public void invokePutVserver(final String cloudOwner, final String cloudRegion, final String tenant, final Vserver vserver) { - aaiClientProvider.getAaiClient().update(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, + aaiClientProvider.getAaiClient().create(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenant, vserver.getVserverId()), vserver); } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHelper.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHelper.java index 31399f7720..249cf74cb2 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHelper.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHelper.java @@ -20,10 +20,16 @@ package org.onap.so.adapters.vnfmadapter.extclients.vnfm; +import static org.onap.so.adapters.vnfmadapter.Constants.BASE_URL; +import static org.onap.so.adapters.vnfmadapter.Constants.OPERATION_NOTIFICATION_ENDPOINT; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.so.adapters.vnfmadapter.extclients.aai.AaiServiceProvider; import org.onap.so.adapters.vnfmadapter.extclients.vim.model.AccessInfo; @@ -40,7 +46,7 @@ import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.SubscriptionsFilte import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.SubscriptionsFilterVnfInstanceSubscriptionFilter; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.VnfInstancesvnfInstanceIdinstantiateExtVirtualLinks; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.VnfInstancesvnfInstanceIdinstantiateVimConnectionInfo; -import org.onap.so.security.WebSecurityConfig; +import org.onap.so.utils.CryptoUtils; import org.onap.vnfmadapter.v1.model.CreateVnfRequest; import org.onap.vnfmadapter.v1.model.ExternalVirtualLink; import org.onap.vnfmadapter.v1.model.Tenant; @@ -49,11 +55,6 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import static org.onap.so.adapters.vnfmadapter.Constants.BASE_URL; -import static org.onap.so.adapters.vnfmadapter.Constants.OPERATION_NOTIFICATION_ENDPOINT; /** * Provides helper methods for interactions with VNFM. @@ -64,15 +65,19 @@ public class VnfmHelper { private static final Logger logger = LoggerFactory.getLogger(VnfmHelper.class); private static final String SEPARATOR = "_"; private final AaiServiceProvider aaiServiceProvider; - private final WebSecurityConfig webSecurityConfig; @Value("${vnfmadapter.endpoint}") private String vnfmAdapterEndoint; + @Value("${vnfmadapter.auth:E39823AAB2739CC654C4E92B52C05BC34149342D0A46451B00CA508C8EDC62242CE4E9DA9445D3C01A3F13}") + private String vnfmAdapterAuth; + + @Value("${mso.key}") + private String msoEncryptionKey; + @Autowired - public VnfmHelper(final AaiServiceProvider aaiServiceProvider, final WebSecurityConfig webSecurityConfig) { + public VnfmHelper(final AaiServiceProvider aaiServiceProvider) { this.aaiServiceProvider = aaiServiceProvider; - this.webSecurityConfig = webSecurityConfig; } /** @@ -171,8 +176,10 @@ public class VnfmHelper { * * @param the ID of the VNF notifications are required for * @return the request + * @throws GeneralSecurityException */ - public LccnSubscriptionRequest createNotificationSubscriptionRequest(final String vnfId) { + public LccnSubscriptionRequest createNotificationSubscriptionRequest(final String vnfId) + throws GeneralSecurityException { final LccnSubscriptionRequest lccnSubscriptionRequest = new LccnSubscriptionRequest(); lccnSubscriptionRequest.setAuthentication(getSubscriptionsAuthentication()); lccnSubscriptionRequest.setCallbackUri(vnfmAdapterEndoint + BASE_URL + OPERATION_NOTIFICATION_ENDPOINT); @@ -186,12 +193,11 @@ public class VnfmHelper { return lccnSubscriptionRequest; } - private SubscriptionsAuthentication getSubscriptionsAuthentication() { + private SubscriptionsAuthentication getSubscriptionsAuthentication() throws GeneralSecurityException { final SubscriptionsAuthenticationParamsBasic basicAuthParams = new SubscriptionsAuthenticationParamsBasic(); - basicAuthParams.setUserName("vnfm"); - basicAuthParams.setPassword(webSecurityConfig.getUsercredentials().stream() - .filter(userCredentials -> "vnfm".equals(userCredentials.getUsername())).findFirst().get() - .getPassword()); + final String[] decrypedAuth = CryptoUtils.decrypt(vnfmAdapterAuth, msoEncryptionKey).split(":"); + basicAuthParams.setUserName(decrypedAuth[0]); + basicAuthParams.setPassword(decrypedAuth[1]); final SubscriptionsAuthentication authentication = new SubscriptionsAuthentication(); authentication.addAuthTypeItem(AuthTypeEnum.BASIC); diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderImpl.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderImpl.java index 951c6f187b..e66f86b66f 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderImpl.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderImpl.java @@ -84,10 +84,12 @@ public class VnfmServiceProviderImpl implements VnfmServiceProvider { @Override public InlineResponse2001 subscribeForNotifications(final String vnfmId, final LccnSubscriptionRequest subscriptionRequest) { + logger.info("Subscribing for notifications {}", subscriptionRequest); final String url = urlProvider.getSubscriptionsUrl(vnfmId); ResponseEntity<InlineResponse2001> response = null; try { response = httpServiceProvider.postHttpRequest(subscriptionRequest, url, InlineResponse2001.class); + logger.info("Subscribing for notifications response {}", response); } catch (final Exception exception) { final String errorMessage = "Subscription to VNFM " + vnfmId + " resulted in exception" + subscriptionRequest; @@ -131,7 +133,7 @@ public class VnfmServiceProviderImpl implements VnfmServiceProvider { public void deleteVnf(final String vnfSelfLink) { logger.debug("Sending delete request to : " + vnfSelfLink); final ResponseEntity<Void> response = httpServiceProvider.deleteHttpRequest(vnfSelfLink, Void.class); - if (response.getStatusCode() != HttpStatus.OK) { + if (response.getStatusCode() != HttpStatus.NO_CONTENT) { throw new VnfmRequestFailureException( "Delete request to " + vnfSelfLink + " return status code: " + response.getStatusCode()); } @@ -146,6 +148,7 @@ public class VnfmServiceProviderImpl implements VnfmServiceProvider { @Override public Optional<InlineResponse201> createVnf(final String vnfmId, final CreateVnfRequest createVnfRequest) { final String url = urlProvider.getCreationUrl(vnfmId); + logger.debug("Sending create request {} to : {}", createVnfRequest, url); try { return httpServiceProvider.post(createVnfRequest, url, InlineResponse201.class); } catch (final Exception exception) { diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmUrlProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmUrlProvider.java index d4aa65d159..f948f3cfac 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmUrlProvider.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmUrlProvider.java @@ -20,6 +20,8 @@ package org.onap.so.adapters.vnfmadapter.extclients.vnfm; +import static org.slf4j.LoggerFactory.getLogger; +import java.net.URI; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.aai.domain.yang.EsrSystemInfoList; import org.onap.so.adapters.vnfmadapter.extclients.aai.AaiServiceProvider; @@ -28,8 +30,6 @@ import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.util.UriComponentsBuilder; -import java.net.URI; -import static org.slf4j.LoggerFactory.getLogger; /** * Provides URLs for REST calls to a VNFM. 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 e61bf860b3..345ff5119a 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 @@ -20,8 +20,11 @@ package org.onap.so.adapters.vnfmadapter.jobmanagement; +import static org.slf4j.LoggerFactory.getLogger; import com.google.common.base.Optional; import com.google.common.collect.Maps; +import java.util.Map; +import java.util.UUID; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.VnfmServiceProvider; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200; import org.onap.so.adapters.vnfmadapter.rest.exceptions.JobNotFoundException; @@ -32,9 +35,6 @@ import org.onap.vnfmadapter.v1.model.QueryJobResponse; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.Map; -import java.util.UUID; -import static org.slf4j.LoggerFactory.getLogger; /** * Manages jobs enabling the status of jobs to be queried. A job is associated with an operation on a VNFM. @@ -123,12 +123,15 @@ public class JobManager { public void notificationProcessedForOperation(final String operationId, final boolean notificationProcessingWasSuccessful) { + logger.debug("Notification processed for operation ID {} success?: {}", operationId, + notificationProcessingWasSuccessful); final java.util.Optional<VnfmOperation> relatedOperation = mapOfJobIdToVnfmOperation.values().stream() .filter(operation -> operation.getOperationId().equals(operationId)).findFirst(); if (relatedOperation.isPresent()) { relatedOperation.get().setNotificationProcessed(notificationProcessingWasSuccessful); + } else { + logger.debug("No operation found for operation ID " + operationId); } - logger.debug("No operation found for operation ID " + operationId); } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/VnfmOperation.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/VnfmOperation.java index 3ed66ad713..7ce08df52f 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/VnfmOperation.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/jobmanagement/VnfmOperation.java @@ -94,4 +94,11 @@ public class VnfmOperation { NOTIFICATION_PROCESSING_FAILED; } + @Override + public String toString() { + return "VnfmOperation [vnfmId=" + vnfmId + ", operationId=" + operationId + ", notificationStatus=" + + notificationStatus + "]"; + } + + } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/lifecycle/LifecycleManager.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/lifecycle/LifecycleManager.java index e6b787bacc..32bb9b93a4 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/lifecycle/LifecycleManager.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/lifecycle/LifecycleManager.java @@ -21,6 +21,7 @@ package org.onap.so.adapters.vnfmadapter.lifecycle; import com.google.common.base.Optional; +import java.util.Map; import org.onap.aai.domain.yang.EsrVnfm; import org.onap.aai.domain.yang.GenericVnf; import org.onap.so.adapters.vnfmadapter.extclients.SdcPackageProvider; @@ -46,7 +47,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.Map; /** * Manages lifecycle operations towards the VNFMs. @@ -64,7 +64,7 @@ public class LifecycleManager { @Autowired LifecycleManager(final AaiServiceProvider aaiServiceProvider, final AaiHelper aaiHelper, final VnfmHelper vnfmHelper, final VnfmServiceProvider vnfmServiceProvider, final JobManager jobManager, - SdcPackageProvider packageProvider) { + final SdcPackageProvider packageProvider) { this.aaiServiceProvider = aaiServiceProvider; this.vnfmServiceProvider = vnfmServiceProvider; this.aaiHelper = aaiHelper; @@ -90,7 +90,11 @@ public class LifecycleManager { aaiHelper.addRelationshipFromGenericVnfToVnfm(genericVnf, vnfm.getVnfmId()); } aaiHelper.addRelationshipFromGenericVnfToTenant(genericVnf, request.getTenant()); - InlineResponse201 vnfmResponse = sendCreateRequestToVnfm(request, genericVnf, vnfIdInAai, vnfm.getVnfmId()); + final InlineResponse201 vnfmResponse = + sendCreateRequestToVnfm(request, genericVnf, vnfIdInAai, vnfm.getVnfmId()); + + logger.info("Create response: {}", vnfmResponse); + genericVnf.setSelflink(vnfmResponse.getLinks().getSelf().getHref()); aaiServiceProvider.invokePutGenericVnf(genericVnf); final String vnfIdInVnfm = vnfmResponse.getId(); @@ -135,18 +139,18 @@ public class LifecycleManager { } } - private InlineResponse201 sendCreateRequestToVnfm(CreateVnfRequest aaiRequest, GenericVnf genericVnf, - String vnfIdInAai, String vnfmId) { + private InlineResponse201 sendCreateRequestToVnfm(final CreateVnfRequest aaiRequest, final GenericVnf genericVnf, + final String vnfIdInAai, final String vnfmId) { logger.debug("Sending a create request to SVNFM " + aaiRequest); - org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.CreateVnfRequest vnfmRequest = + final org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.CreateVnfRequest vnfmRequest = new org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.CreateVnfRequest(); - String vnfdId = packageProvider.getVnfdId(genericVnf.getModelVersionId()); + final String vnfdId = packageProvider.getVnfdId(genericVnf.getModelVersionId()); vnfmRequest.setVnfdId(vnfdId); vnfmRequest.setVnfInstanceName(aaiRequest.getName().replaceAll(" ", "_")); vnfmRequest.setVnfInstanceDescription(vnfIdInAai); - Optional<InlineResponse201> optionalResponse = vnfmServiceProvider.createVnf(vnfmId, vnfmRequest); + final Optional<InlineResponse201> optionalResponse = vnfmServiceProvider.createVnf(vnfmId, vnfmRequest); try { return optionalResponse.get(); diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/notificationhandling/NotificationHandler.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/notificationhandling/NotificationHandler.java index a339b9be70..c09aa0cd48 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/notificationhandling/NotificationHandler.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/notificationhandling/NotificationHandler.java @@ -20,9 +20,14 @@ package org.onap.so.adapters.vnfmadapter.notificationhandling; +import static org.slf4j.LoggerFactory.getLogger; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.Relationship; import org.onap.aai.domain.yang.Vserver; import org.onap.so.adapters.vnfmadapter.extclients.aai.AaiHelper; import org.onap.so.adapters.vnfmadapter.extclients.aai.AaiServiceProvider; @@ -30,16 +35,13 @@ import org.onap.so.adapters.vnfmadapter.extclients.aai.OamIpAddressSource; import org.onap.so.adapters.vnfmadapter.extclients.aai.OamIpAddressSource.OamIpAddressType; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.VnfmServiceProvider; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs.ChangeTypeEnum; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.VnfLcmOperationOccurrenceNotification; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.VnfLcmOperationOccurrenceNotification.OperationStateEnum; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201VimConnectionInfo; import org.onap.so.adapters.vnfmadapter.jobmanagement.JobManager; import org.slf4j.Logger; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import static org.slf4j.LoggerFactory.getLogger; /** * Performs updates to AAI based on a received notification. The updates are executed in a separate thread so as the @@ -93,15 +95,14 @@ public class NotificationHandler implements Runnable { } private void handleVnfInstantiateCompleted() { - final GenericVnf genericVnf = - aaiServiceProvider.invokeQueryGenericVnf(vnfInstance.getLinks().getSelf().getHref()).get(0); + final GenericVnf genericVnf = aaiServiceProvider + .invokeQueryGenericVnf(vnfInstance.getLinks().getSelf().getHref()).getGenericVnf().get(0); setOamIpAddress(genericVnf, vnfInstance); genericVnf.setOrchestrationStatus("Created"); aaiServiceProvider.invokePutGenericVnf(genericVnf); - updateVservers(vnfLcmOperationOccurrenceNotification, genericVnf.getVnfId(), - vnfInstance.getVimConnectionInfo()); + addVservers(vnfLcmOperationOccurrenceNotification, genericVnf.getVnfId(), vnfInstance.getVimConnectionInfo()); logger.debug("Finished handling notification for vnfm: " + vnfInstance.getId()); } @@ -114,16 +115,17 @@ public class NotificationHandler implements Runnable { } if (oamIpAddressSource.getType().equals(OamIpAddressType.LITERAL)) { genericVnf.setIpv4OamAddress(oamIpAddressSource.getValue()); - } - try { - logger.debug("ConfigurableProperties: " + vnfInstance.getVnfConfigurableProperties()); - if (vnfInstance.getVnfConfigurableProperties() == null) { - logger.warn("No ConfigurableProperties, cannot set OAM IP Address"); + } else { + try { + logger.debug("ConfigurableProperties: " + vnfInstance.getVnfConfigurableProperties()); + if (vnfInstance.getVnfConfigurableProperties() == null) { + logger.warn("No ConfigurableProperties, cannot set OAM IP Address"); + } + final JSONObject properties = new JSONObject((Map) vnfInstance.getVnfConfigurableProperties()); + genericVnf.setIpv4OamAddress(properties.get(oamIpAddressSource.getValue()).toString()); + } catch (final JSONException jsonException) { + logger.error("Error getting vnfIpAddress", jsonException); } - final JSONObject properties = new JSONObject((Map) vnfInstance.getVnfConfigurableProperties()); - genericVnf.setIpv4OamAddress(properties.get(oamIpAddressSource.getValue()).toString()); - } catch (final JSONException jsonException) { - logger.error("Error getting vnfIpAddress", jsonException); } } @@ -141,32 +143,31 @@ public class NotificationHandler implements Runnable { } private void handleVnfTerminateFailed() { - final GenericVnf genericVnf = - aaiServiceProvider.invokeQueryGenericVnf(vnfInstance.getLinks().getSelf().getHref()).get(0); - updateVservers(vnfLcmOperationOccurrenceNotification, genericVnf.getVnfId(), - vnfInstance.getVimConnectionInfo()); - jobManager.notificationProcessedForOperation(vnfLcmOperationOccurrenceNotification.getId(), false); + final GenericVnf genericVnf = aaiServiceProvider + .invokeQueryGenericVnf(vnfInstance.getLinks().getSelf().getHref()).getGenericVnf().get(0); + deleteVservers(vnfLcmOperationOccurrenceNotification, genericVnf); + jobManager.notificationProcessedForOperation(vnfLcmOperationOccurrenceNotification.getVnfLcmOpOccId(), false); } private void handleVnfTerminateCompleted() { - final GenericVnf genericVnf = - aaiServiceProvider.invokeQueryGenericVnf(vnfInstance.getLinks().getSelf().getHref()).get(0); - updateVservers(vnfLcmOperationOccurrenceNotification, genericVnf.getVnfId(), - vnfInstance.getVimConnectionInfo()); + final GenericVnf genericVnf = aaiServiceProvider + .invokeQueryGenericVnf(vnfInstance.getLinks().getSelf().getHref()).getGenericVnf().get(0); + deleteVservers(vnfLcmOperationOccurrenceNotification, genericVnf); boolean deleteSuccessful = false; try { vnfmServiceProvider.deleteVnf(genericVnf.getSelflink()); deleteSuccessful = true; } finally { - jobManager.notificationProcessedForOperation(vnfLcmOperationOccurrenceNotification.getId(), + jobManager.notificationProcessedForOperation(vnfLcmOperationOccurrenceNotification.getVnfLcmOpOccId(), deleteSuccessful); genericVnf.setOrchestrationStatus("Assigned"); + genericVnf.setSelflink(""); aaiServiceProvider.invokePutGenericVnf(genericVnf); } } - private void updateVservers(final VnfLcmOperationOccurrenceNotification notification, final String vnfId, + private void addVservers(final VnfLcmOperationOccurrenceNotification notification, final String vnfId, final List<InlineResponse201VimConnectionInfo> vnfInstancesVimConnectionInfo) { final Map<String, InlineResponse201VimConnectionInfo> vimConnectionIdToVimConnectionInfo = new HashMap<>(); for (final InlineResponse201VimConnectionInfo vimConnectionInfo : vnfInstancesVimConnectionInfo) { @@ -176,22 +177,28 @@ public class NotificationHandler implements Runnable { for (final LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs vnfc : notification.getAffectedVnfcs()) { final InlineResponse201VimConnectionInfo vimConnectionInfo = getVimConnectionInfo(vimConnectionIdToVimConnectionInfo, vnfc); - switch (vnfc.getChangeType()) { - case ADDED: - final Vserver vserver = aaiHelper.createVserver(vnfc); - aaiHelper.addRelationshipFromVserverVnfToGenericVnf(vserver, vnfId); - - aaiServiceProvider.invokePutVserver(getCloudOwner(vimConnectionInfo), - getCloudRegion(vimConnectionInfo), getTenant(vimConnectionInfo), vserver); - break; - case REMOVED: - aaiServiceProvider.invokeDeleteVserver(getCloudOwner(vimConnectionInfo), - getCloudRegion(vimConnectionInfo), getTenant(vimConnectionInfo), - vnfc.getComputeResource().getResourceId()); - break; - case MODIFIED: - case TEMPORARY: - default: + if (ChangeTypeEnum.ADDED.equals(vnfc.getChangeType())) { + final Vserver vserver = aaiHelper.createVserver(vnfc); + aaiHelper.addRelationshipFromVserverVnfToGenericVnf(vserver, vnfId); + + aaiServiceProvider.invokePutVserver(getCloudOwner(vimConnectionInfo), getCloudRegion(vimConnectionInfo), + getTenant(vimConnectionInfo), vserver); + } + } + } + + private void deleteVservers(final VnfLcmOperationOccurrenceNotification notification, final GenericVnf vnf) { + for (final LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs vnfc : notification.getAffectedVnfcs()) { + if (ChangeTypeEnum.REMOVED.equals(vnfc.getChangeType())) { + + final Relationship relationshipToVserver = aaiHelper.deleteRelationshipWithDataValue(vnf, "vserver", + "vserver.vserver-id", vnfc.getComputeResource().getResourceId()); + + aaiServiceProvider.invokeDeleteVserver( + aaiHelper.getRelationshipData(relationshipToVserver, "cloud-region.cloud-owner"), + aaiHelper.getRelationshipData(relationshipToVserver, "cloud-region.cloud-region-id"), + aaiHelper.getRelationshipData(relationshipToVserver, "tenant.tenant-id"), + vnfc.getComputeResource().getResourceId()); } } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003GrantController.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003GrantController.java index 6b8802eed2..3ead98fce2 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003GrantController.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003GrantController.java @@ -20,6 +20,11 @@ package org.onap.so.adapters.vnfmadapter.rest; +import static org.onap.so.adapters.vnfmadapter.Constants.BASE_URL; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import javax.ws.rs.core.MediaType; import org.onap.so.adapters.vnfmadapter.extclients.aai.AaiHelper; import org.onap.so.adapters.vnfmadapter.extclients.aai.AaiServiceProvider; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.VnfmHelper; @@ -36,15 +41,10 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; -import javax.ws.rs.core.MediaType; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import static org.onap.so.adapters.vnfmadapter.Constants.BASE_URL; +import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping(value = BASE_URL, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON) @@ -52,9 +52,6 @@ public class Sol003GrantController { private static final String SEPARATOR = "_"; private static final String VIM_TYPE = "OPENSTACK"; - private static final String CLOUD_OWNER = "myTestCloudOwner"; - private static final String REGION = "myTestRegion"; - private static final String TENANT_ID = "myTestTenantId"; private static final Logger logger = LoggerFactory.getLogger(Sol003GrantController.class); public final AaiServiceProvider aaiServiceProvider; public final AaiHelper aaiHelper; @@ -71,7 +68,7 @@ public class Sol003GrantController { @GetMapping(value = "/grants/{grantId}") public ResponseEntity<InlineResponse201> grantsGrantIdGet(@PathVariable("grantId") final String grantId) { logger.info("Get grant received from VNFM, grant id: " + grantId); - return new ResponseEntity<InlineResponse201>(HttpStatus.NOT_IMPLEMENTED); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @PostMapping(value = "/grants") @@ -80,7 +77,7 @@ public class Sol003GrantController { final InlineResponse201 grantResponse = createGrantResponse(grantRequest); logger.info("Grant request returning to VNFM: " + grantResponse); - return new ResponseEntity<InlineResponse201>(grantResponse, HttpStatus.CREATED); + return new ResponseEntity<>(grantResponse, HttpStatus.CREATED); } private InlineResponse201 createGrantResponse(final GrantRequest grantRequest) { @@ -88,8 +85,9 @@ public class Sol003GrantController { grantResponse.setId(UUID.randomUUID().toString()); grantResponse.setVnfInstanceId(grantRequest.getVnfInstanceId()); grantResponse.setVnfLcmOpOccId(grantRequest.getVnfLcmOpOccId()); - final Tenant tenant = - aaiHelper.getAssignedTenant(aaiServiceProvider.invokeGetGenericVnf((grantRequest.getVnfInstanceId()))); + final String vnfSelfLink = grantRequest.getLinks().getVnfInstance().getHref(); + final Tenant tenant = aaiHelper + .getAssignedTenant(aaiServiceProvider.invokeQueryGenericVnf(vnfSelfLink).getGenericVnf().get(0)); String vimConnectionId = ""; final InlineResponse201VimConnections vimConnection = vnfmHelper.getVimConnections(tenant); @@ -99,19 +97,11 @@ public class Sol003GrantController { if (grantRequest.getOperation().equals(GrantRequest.OperationEnum.INSTANTIATE)) { grantResponse.addResources(getResources(grantRequest.getAddResources(), vimConnectionId)); } else if (grantRequest.getOperation().equals(GrantRequest.OperationEnum.TERMINATE)) { - grantResponse.addResources(getResources(grantRequest.getRemoveResources(), vimConnectionId)); + grantResponse.removeResources(getResources(grantRequest.getRemoveResources(), vimConnectionId)); } return grantResponse; } - private InlineResponse201VimConnections getVimConnectionsItem(final Tenant tenant) { - final InlineResponse201VimConnections vimConnection = new InlineResponse201VimConnections(); - vimConnection.setId(createVimConnectionId(tenant.getCloudOwner(), tenant.getRegionName())); - vimConnection.setVimId(vimConnection.getId()); - vimConnection.setVimType(VIM_TYPE); - return vimConnection; - } - private List<InlineResponse201AddResources> getResources(final List<GrantsAddResources> requestResources, final String vimId) { final List<InlineResponse201AddResources> resources = new ArrayList<>(); @@ -123,8 +113,4 @@ public class Sol003GrantController { } return resources; } - - private String createVimConnectionId(String cloudOwner, String cloudRegionId) { - return cloudOwner + SEPARATOR + cloudRegionId; - } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/resources/application.yaml b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/resources/application.yaml index 4fb110349d..951d4a3bb9 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/resources/application.yaml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/resources/application.yaml @@ -11,6 +11,19 @@ # 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. +spring: + security: + usercredentials: + - username: test + password: '$2a$12$Zi3AuYcZoZO/gBQyUtST2.F5N6HqcTtaNci2Et.ufsQhski56srIu' + role: BPEL-Client + - username: vnfm + password: '$2a$10$Fh9ffgPw2vnmsghsRD3ZauBL1aKXebigbq3BB1RPWtE62UDILsjke' + role: BPEL-Client + http: + converters: + preferred-json-mapper: gson + server: port: 9092 tomcat: @@ -29,6 +42,9 @@ sdc: password: sdcPassword key: adadadadad endpoint: http://sdc.onap/1234A + +vnfmadapter: + endpoint: http://so-vnfm-adapter.onap:9092 #Actuator management: diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003GrantControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003GrantControllerTest.java index b7f5e96eab..69223d7922 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003GrantControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003GrantControllerTest.java @@ -20,7 +20,15 @@ package org.onap.so.adapters.vnfmadapter.rest; -import com.google.gson.Gson; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.Before; @@ -30,6 +38,7 @@ import org.mockito.hamcrest.MockitoHamcrest; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.aai.domain.yang.EsrSystemInfoList; import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.GenericVnfs; import org.onap.aai.domain.yang.Relationship; import org.onap.aai.domain.yang.RelationshipData; import org.onap.aai.domain.yang.RelationshipList; @@ -38,6 +47,8 @@ import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantRequest import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantRequest.OperationEnum; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantsAddResources; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantsAddResources.TypeEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantsLinks; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantsLinksVnfLcmOpOcc; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.InlineResponse201; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.InlineResponse201VimConnections; import org.onap.so.client.aai.AAIResourcesClient; @@ -54,12 +65,6 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; -import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doReturn; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; @RunWith(SpringRunner.class) @SpringBootTest(classes = VnfmAdapterApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) @@ -84,7 +89,6 @@ public class Sol003GrantControllerTest { @Autowired private Sol003GrantController controller; - private final Gson gson = new Gson(); @Before public void setUp() throws Exception { @@ -94,17 +98,18 @@ public class Sol003GrantControllerTest { @Test public void grantRequest_ValidRequestInstantiate_GrantApproved() { - GrantRequest grantRequest = createGrantRequest("INSTANTIATE"); + final GrantRequest grantRequest = createGrantRequest("INSTANTIATE"); setUpGenericVnfWithVnfmRelationshipInMockAai("vnfmType", "vnfm1"); final ResponseEntity<InlineResponse201> response = controller.grantsPost(grantRequest); assertEquals(HttpStatus.CREATED, response.getStatusCode()); assertEquals(1, response.getBody().getAddResources().size()); + assertNull(response.getBody().getRemoveResources()); assertEquals(vimConnectionId, response.getBody().getAddResources().get(0).getVimConnectionId()); - assertEquals("myTestVnfId", response.getBody().getVnfInstanceId()); + assertEquals("myTestVnfIdOnVnfm", response.getBody().getVnfInstanceId()); assertEquals("123456", response.getBody().getVnfLcmOpOccId()); - InlineResponse201VimConnections vimConnections = response.getBody().getVimConnections().get(0); + final InlineResponse201VimConnections vimConnections = response.getBody().getVimConnections().get(0); assertEquals(vimConnectionId, vimConnections.getVimId()); assertEquals("OPENSTACK", vimConnections.getVimType()); assertNotNull(vimConnections.getAccessInfo()); @@ -120,17 +125,18 @@ public class Sol003GrantControllerTest { @Test public void grantRequest_ValidRequestTerminate_GrantApproved() { - GrantRequest grantRequest = createGrantRequest("TERMINATE"); + final GrantRequest grantRequest = createGrantRequest("TERMINATE"); setUpGenericVnfWithVnfmRelationshipInMockAai("vnfmType", "vnfm1"); final ResponseEntity<InlineResponse201> response = controller.grantsPost(grantRequest); assertEquals(HttpStatus.CREATED, response.getStatusCode()); - assertEquals(1, response.getBody().getAddResources().size()); - assertEquals(vimConnectionId, response.getBody().getAddResources().get(0).getVimConnectionId()); - assertEquals("myTestVnfId", response.getBody().getVnfInstanceId()); + assertNull(response.getBody().getAddResources()); + assertEquals(1, response.getBody().getRemoveResources().size()); + assertEquals(vimConnectionId, response.getBody().getRemoveResources().get(0).getVimConnectionId()); + assertEquals("myTestVnfIdOnVnfm", response.getBody().getVnfInstanceId()); assertEquals("123456", response.getBody().getVnfLcmOpOccId()); - InlineResponse201VimConnections vimConnections = response.getBody().getVimConnections().get(0); + final InlineResponse201VimConnections vimConnections = response.getBody().getVimConnections().get(0); assertEquals(vimConnectionId, vimConnections.getVimId()); assertEquals("OPENSTACK", vimConnections.getVimType()); assertNotNull(vimConnections.getAccessInfo()); @@ -139,19 +145,21 @@ public class Sol003GrantControllerTest { } - private GrantRequest createGrantRequest(String operation) { - GrantRequest grantRequest = new GrantRequest(); - grantRequest.setVnfInstanceId("myTestVnfId"); + private GrantRequest createGrantRequest(final String operation) { + final GrantRequest grantRequest = new GrantRequest(); + grantRequest.setVnfInstanceId("myTestVnfIdOnVnfm"); grantRequest.setVnfLcmOpOccId("123456"); + grantRequest.links(new GrantsLinks() + .vnfInstance(new GrantsLinksVnfLcmOpOcc().href("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))); if (operation == "INSTANTIATE") { grantRequest.setOperation(OperationEnum.INSTANTIATE); - GrantsAddResources resource = new GrantsAddResources(); + final GrantsAddResources resource = new GrantsAddResources(); resource.setId("123"); resource.setType(TypeEnum.COMPUTE); grantRequest.addAddResourcesItem(resource); } else if (operation == "TERMINATE") { grantRequest.setOperation(OperationEnum.TERMINATE); - GrantsAddResources resource = new GrantsAddResources(); + final GrantsAddResources resource = new GrantsAddResources(); resource.setId("123"); resource.setType(TypeEnum.COMPUTE); grantRequest.addRemoveResourcesItem(resource); @@ -210,6 +218,14 @@ public class Sol003GrantControllerTest { doReturn(Optional.of(genericVnf)).when(aaiResourcesClient).get(eq(GenericVnf.class), MockitoHamcrest.argThat(new AaiResourceUriMatcher("/network/generic-vnfs/generic-vnf/myTestVnfId"))); + + final List<GenericVnf> listOfGenericVnfs = new ArrayList<>(); + listOfGenericVnfs.add(genericVnf); + final GenericVnfs genericVnfs = new GenericVnfs(); + genericVnfs.getGenericVnf().addAll(listOfGenericVnfs); + doReturn(Optional.of(genericVnfs)).when(aaiResourcesClient).get(eq(GenericVnfs.class), + MockitoHamcrest.argThat(new AaiResourceUriMatcher( + "/network/generic-vnfs?selflink=http%3A%2F%2Fvnfm%3A8080%2Fvnfs%2FmyTestVnfIdOnVnfm"))); } private class AaiResourceUriMatcher extends BaseMatcher<AAIResourceUri> { diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003LcnControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003LcnControllerTest.java index 66e8e99f72..aeb7cd3540 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003LcnControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003LcnControllerTest.java @@ -20,7 +20,25 @@ package org.onap.so.adapters.vnfmadapter.rest; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; import com.google.gson.Gson; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.inject.Inject; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.Before; @@ -29,7 +47,10 @@ import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.hamcrest.MockitoHamcrest; import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.GenericVnfs; import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; import org.onap.aai.domain.yang.Vserver; import org.onap.so.adapters.vnfmadapter.VnfmAdapterApplication; import org.onap.so.adapters.vnfmadapter.extclients.aai.AaiHelper; @@ -64,24 +85,6 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; -import javax.inject.Inject; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.timeout; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.verify; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; @RunWith(SpringRunner.class) @SpringBootTest(classes = VnfmAdapterApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) @@ -166,9 +169,11 @@ public class Sol003LcnControllerTest { .andRespond(withSuccess(gson.toJson(vnfInstance), MediaType.APPLICATION_JSON)); final GenericVnf genericVnf = createGenericVnf("vnfmType1"); - final List<GenericVnf> genericVnfs = new ArrayList<>(); - genericVnfs.add(genericVnf); - doReturn(Optional.of(genericVnfs)).when(aaiResourcesClient).get(eq(List.class), + final List<GenericVnf> listOfGenericVnfs = new ArrayList<>(); + listOfGenericVnfs.add(genericVnf); + final GenericVnfs genericVnfs = new GenericVnfs(); + genericVnfs.getGenericVnf().addAll(listOfGenericVnfs); + doReturn(Optional.of(genericVnfs)).when(aaiResourcesClient).get(eq(GenericVnfs.class), MockitoHamcrest.argThat(new AaiResourceUriMatcher( "/network/generic-vnfs?selflink=http%3A%2F%2Fvnfm%3A8080%2Fvnfs%2FmyTestVnfIdOnVnfm"))); @@ -176,23 +181,27 @@ public class Sol003LcnControllerTest { controller.lcnVnfLcmOperationOccurrenceNotificationPost(vnfLcmOperationOccurrenceNotification); assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - final ArgumentCaptor<Object> bodyArgument = ArgumentCaptor.forClass(Object.class); - final ArgumentCaptor<AAIResourceUri> uriArgument = ArgumentCaptor.forClass(AAIResourceUri.class); + final ArgumentCaptor<Object> bodyArgument1 = ArgumentCaptor.forClass(Object.class); + final ArgumentCaptor<AAIResourceUri> uriArgument1 = ArgumentCaptor.forClass(AAIResourceUri.class); - verify(aaiResourcesClient, timeout(1000).times(2)).update(uriArgument.capture(), bodyArgument.capture()); + verify(aaiResourcesClient, timeout(1000)).update(uriArgument1.capture(), bodyArgument1.capture()); assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", - uriArgument.getAllValues().get(0).build().toString()); - final GenericVnf updatedGenericVnf = (GenericVnf) bodyArgument.getAllValues().get(0); + uriArgument1.getAllValues().get(0).build().toString()); + final GenericVnf updatedGenericVnf = (GenericVnf) bodyArgument1.getAllValues().get(0); assertEquals("10.10.10.10", updatedGenericVnf.getIpv4OamAddress()); assertEquals("Created", updatedGenericVnf.getOrchestrationStatus()); + final ArgumentCaptor<Object> bodyArgument2 = ArgumentCaptor.forClass(Object.class); + final ArgumentCaptor<AAIResourceUri> uriArgument2 = ArgumentCaptor.forClass(AAIResourceUri.class); + verify(aaiResourcesClient, timeout(1000)).create(uriArgument2.capture(), bodyArgument2.capture()); + assertEquals( "/cloud-infrastructure/cloud-regions/cloud-region/" + CLOUD_OWNER + "/" + REGION + "/tenants/tenant/" + TENANT_ID + "/vservers/vserver/myVnfc1", - uriArgument.getAllValues().get(1).build().toString()); + uriArgument2.getAllValues().get(0).build().toString()); - final Vserver vserver = (Vserver) bodyArgument.getAllValues().get(1); + final Vserver vserver = (Vserver) bodyArgument2.getAllValues().get(0); assertEquals("myVnfc1", vserver.getVserverId()); final Relationship relationship = vserver.getRelationshipList().getRelationship().get(0); assertEquals("generic-vnf", relationship.getRelatedTo()); @@ -214,13 +223,17 @@ public class Sol003LcnControllerTest { .andRespond(withSuccess(gson.toJson(vnfInstance), MediaType.APPLICATION_JSON)); mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))) - .andRespond(withStatus(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON)); + .andRespond(withStatus(HttpStatus.NO_CONTENT).contentType(MediaType.APPLICATION_JSON)); final GenericVnf genericVnf = createGenericVnf("vnfmType1"); genericVnf.setSelflink("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"); - final List<GenericVnf> genericVnfs = new ArrayList<>(); - genericVnfs.add(genericVnf); - doReturn(Optional.of(genericVnfs)).when(aaiResourcesClient).get(eq(List.class), + final List<GenericVnf> listOfGenericVnfs = new ArrayList<>(); + listOfGenericVnfs.add(genericVnf); + final GenericVnfs genericVnfs = new GenericVnfs(); + genericVnfs.getGenericVnf().addAll(listOfGenericVnfs); + addRelationshipFromGenericVnfToVserver(genericVnf, "myVnfc1"); + + doReturn(Optional.of(genericVnfs)).when(aaiResourcesClient).get(eq(GenericVnfs.class), MockitoHamcrest.argThat(new AaiResourceUriMatcher( "/network/generic-vnfs?selflink=http%3A%2F%2Fvnfm%3A8080%2Fvnfs%2FmyTestVnfIdOnVnfm"))); @@ -310,6 +323,31 @@ public class Sol003LcnControllerTest { return genericVnf; } + private void addRelationshipFromGenericVnfToVserver(final GenericVnf genericVnf, final String vserverId) { + final Relationship relationshipToVserver = new Relationship(); + relationshipToVserver.setRelatedTo("vserver"); + final RelationshipData relationshipData1 = new RelationshipData(); + relationshipData1.setRelationshipKey("vserver.vserver-id"); + relationshipData1.setRelationshipValue(vserverId); + relationshipToVserver.getRelationshipData().add(relationshipData1); + final RelationshipData relationshipData2 = new RelationshipData(); + relationshipData2.setRelationshipKey("cloud-region.cloud-owner"); + relationshipData2.setRelationshipValue(CLOUD_OWNER); + relationshipToVserver.getRelationshipData().add(relationshipData2); + final RelationshipData relationshipData3 = new RelationshipData(); + relationshipData3.setRelationshipKey("cloud-region.cloud-region-id"); + relationshipData3.setRelationshipValue(REGION); + relationshipToVserver.getRelationshipData().add(relationshipData3); + final RelationshipData relationshipData4 = new RelationshipData(); + relationshipData4.setRelationshipKey("tenant.tenant-id"); + relationshipData4.setRelationshipValue(TENANT_ID); + relationshipToVserver.getRelationshipData().add(relationshipData4); + + final RelationshipList relationshipList = new RelationshipList(); + relationshipList.getRelationship().add(relationshipToVserver); + genericVnf.setRelationshipList(relationshipList); + } + private class AaiResourceUriMatcher extends BaseMatcher<AAIResourceUri> { final String uriAsString; 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 20a074b2ba..73a49e9c40 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 @@ -20,7 +20,21 @@ package org.onap.so.adapters.vnfmadapter.rest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withBadRequest; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; import com.google.gson.Gson; +import java.net.URI; +import java.util.Optional; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.Before; @@ -36,24 +50,23 @@ import org.onap.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.Relationship; 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.model.InlineResponse200; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse2001; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201Links; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201LinksSelf; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfmNotFoundException; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.vnfmadapter.v1.model.CreateVnfRequest; import org.onap.vnfmadapter.v1.model.CreateVnfResponse; import org.onap.vnfmadapter.v1.model.DeleteVnfResponse; import org.onap.vnfmadapter.v1.model.OperationEnum; import org.onap.vnfmadapter.v1.model.OperationStateEnum; import org.onap.vnfmadapter.v1.model.QueryJobResponse; -import org.onap.so.adapters.vnfmadapter.VnfmAdapterApplication; -import org.onap.so.adapters.vnfmadapter.extclients.SdcPackageProvider; -import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.*; -import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfmNotFoundException; -import org.onap.so.client.aai.AAIResourcesClient; -import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.vnfmadapter.v1.model.CreateVnfRequest; import org.onap.vnfmadapter.v1.model.Tenant; -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; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; @@ -72,18 +85,6 @@ import org.springframework.web.client.RestTemplate; import org.threeten.bp.LocalDateTime; import org.threeten.bp.OffsetDateTime; import org.threeten.bp.ZoneOffset; -import java.net.URI; -import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.verify; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.*; @RunWith(SpringRunner.class) @SpringBootTest(classes = VnfmAdapterApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) @@ -131,7 +132,7 @@ public class VnfmAdapterControllerTest { setUpVimInMockAai(); final String expectedsubscriptionRequest = - "{\"filter\":{\"vnfInstanceSubscriptionFilter\":{\"vnfInstanceIds\":[\"vnfId\"]},\"notificationTypes\":[\"VnfLcmOperationOccurrenceNotification\"]},\"callbackUri\":\"https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/lcn/VnfLcmOperationOccurrenceNotification\",\"authentication\":{\"authType\":[\"BASIC\"],\"paramsBasic\":{\"userName\":\"vnfm\",\"password\":\"$2a$10$Fh9ffgPw2vnmsghsRD3ZauBL1aKXebigbq3BB1RPWtE62UDILsjke\"}}}"; + "{\"filter\":{\"vnfInstanceSubscriptionFilter\":{\"vnfInstanceIds\":[\"vnfId\"]},\"notificationTypes\":[\"VnfLcmOperationOccurrenceNotification\"]},\"callbackUri\":\"https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/lcn/VnfLcmOperationOccurrenceNotification\",\"authentication\":{\"authType\":[\"BASIC\"],\"paramsBasic\":{\"userName\":\"vnfm\",\"password\":\"password1$\"}}}"; final InlineResponse2001 subscriptionResponse = new InlineResponse2001(); final InlineResponse201 createResponse = createCreateResponse(); 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 87008f1d8f..43eb277d21 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 @@ -91,7 +91,7 @@ public class DeployActivitySpecs { if (activitySpecActivitySpecCategories == null || activitySpecActivitySpecCategories.size() == 0) { return; } - List<String> categoryList = new ArrayList<String>(); + List<String> categoryList = new ArrayList<>(); for (ActivitySpecActivitySpecCategories activitySpecCat : activitySpecActivitySpecCategories) { if (activitySpecCat != null) { if (activitySpecCat.getActivitySpecCategories() != null) { @@ -107,8 +107,8 @@ public class DeployActivitySpecs { if (activitySpecActivitySpecParameters == null || activitySpecActivitySpecParameters.size() == 0) { return; } - List<Input> inputs = new ArrayList<Input>(); - List<Output> outputs = new ArrayList<Output>(); + List<Input> inputs = new ArrayList<>(); + List<Output> outputs = new ArrayList<>(); for (ActivitySpecActivitySpecParameters activitySpecParam : activitySpecActivitySpecParameters) { if (activitySpecParam != null) { if (activitySpecParam.getActivitySpecParameters() != null) { 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 9b838c4d98..ea1d194c68 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 @@ -62,7 +62,9 @@ import org.onap.so.asdc.installer.heat.ToscaResourceInstaller; import org.onap.so.asdc.tenantIsolation.DistributionStatus; import org.onap.so.asdc.tenantIsolation.WatchdogDistribution; import org.onap.so.asdc.util.ASDCNotificationLogging; +import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus; import org.onap.so.db.request.beans.WatchdogDistributionStatus; +import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatusRepository; import org.onap.so.db.request.data.repository.WatchdogDistributionStatusRepository; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; @@ -77,6 +79,8 @@ public class ASDCController { protected static final Logger logger = LoggerFactory.getLogger(ASDCController.class); + private static final String UNKNOWN = "Unknown"; + protected boolean isAsdcClientAutoManaged = false; protected String controllerName; @@ -92,6 +96,9 @@ public class ASDCController { private WatchdogDistributionStatusRepository wdsRepo; @Autowired + protected WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository; + + @Autowired private ASDCConfiguration asdcConfig; @Autowired @@ -104,12 +111,33 @@ public class ASDCController { private static final String UUID_PARAM = "(UUID:"; + protected static final String MSO = "SO"; + @Autowired private WatchdogDistribution wd; @Autowired DeployActivitySpecs deployActivitySpecs; + public ASDCController() { + this(""); + } + + public ASDCController(String controllerConfigName) { + isAsdcClientAutoManaged = true; + this.controllerName = controllerConfigName; + } + + public ASDCController(String controllerConfigName, IDistributionClient asdcClient, + IVfResourceInstaller resourceinstaller) { + distributionClient = asdcClient; + } + + public ASDCController(String controllerConfigName, IDistributionClient asdcClient) { + distributionClient = asdcClient; + this.controllerName = controllerConfigName; + } + public int getNbOfNotificationsOngoing() { return nbOfNotificationsOngoing; } @@ -150,25 +178,6 @@ public class ASDCController { return this.controllerStatus; } - public ASDCController() { - this(""); - } - - public ASDCController(String controllerConfigName) { - isAsdcClientAutoManaged = true; - this.controllerName = controllerConfigName; - } - - public ASDCController(String controllerConfigName, IDistributionClient asdcClient, - IVfResourceInstaller resourceinstaller) { - distributionClient = asdcClient; - } - - public ASDCController(String controllerConfigName, IDistributionClient asdcClient) { - distributionClient = asdcClient; - this.controllerName = controllerConfigName; - } - public String getControllerName() { return controllerName; } @@ -268,6 +277,52 @@ public class ASDCController { } } + protected void notifyErrorToAsdc(INotificationData iNotif, ToscaResourceStructure toscaResourceStructure, + DistributionStatusEnum deployStatus, VfResourceStructure resourceStructure, String errorMessage) { + // do csar lever first + this.sendCsarDeployNotification(iNotif, resourceStructure, toscaResourceStructure, deployStatus, errorMessage); + // at resource level + for (IResourceInstance resource : iNotif.getResources()) { + resourceStructure = new VfResourceStructure(iNotif, resource); + errorMessage = String.format("Resource with UUID: %s already exists", resource.getResourceUUID()); + this.sendCsarDeployNotification(iNotif, resourceStructure, toscaResourceStructure, deployStatus, + errorMessage); + } + } + + protected boolean isCsarAlreadyDeployed(INotificationData iNotif, ToscaResourceStructure toscaResourceStructure) { + VfResourceStructure resourceStructure = null; + String errorMessage = ""; + boolean csarAlreadyDeployed = false; + DistributionStatusEnum deployStatus = DistributionStatusEnum.DEPLOY_OK; + WatchdogComponentDistributionStatus wdStatus = + new WatchdogComponentDistributionStatus(iNotif.getDistributionID(), MSO); + try { + csarAlreadyDeployed = toscaInstaller.isCsarAlreadyDeployed(toscaResourceStructure); + if (csarAlreadyDeployed) { + deployStatus = DistributionStatusEnum.ALREADY_DEPLOYED; + resourceStructure = new VfResourceStructure(iNotif, null); + errorMessage = String.format("Csar with UUID: %s already exists", + toscaResourceStructure.getToscaArtifact().getArtifactUUID()); + wdStatus.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name()); + watchdogCDStatusRepository.saveAndFlush(wdStatus); + logger.error(errorMessage); + } + } catch (ArtifactInstallerException e) { + deployStatus = DistributionStatusEnum.DEPLOY_ERROR; + resourceStructure = new VfResourceStructure(iNotif, null); + errorMessage = e.getMessage(); + wdStatus.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name()); + watchdogCDStatusRepository.saveAndFlush(wdStatus); + logger.warn("Tosca Checksums don't match, Tosca validation check failed", e); + } + + if (deployStatus != DistributionStatusEnum.DEPLOY_OK) { + notifyErrorToAsdc(iNotif, toscaResourceStructure, deployStatus, resourceStructure, errorMessage); + } + + return csarAlreadyDeployed; + } protected IDistributionClientDownloadResult downloadTheArtifact(IArtifactInfo artifact, String distributionId) throws ASDCDownloadException { @@ -356,7 +411,7 @@ public class ASDCController { for (IArtifactInfo artifactInfo : resourceStructure.getResourceInstance().getArtifacts()) { if ((DistributionStatusEnum.DEPLOY_OK.equals(distribStatus) - && !artifactInfo.getArtifactType().equalsIgnoreCase("OTHER") + && !("OTHER").equalsIgnoreCase(artifactInfo.getArtifactType()) && !resourceStructure.isAlreadyDeployed()) // This could be NULL if the artifact is a VF module artifact, this won't be present in the MAP && resourceStructure.getArtifactsMapByUUID().get(artifactInfo.getArtifactUUID()) != null @@ -376,23 +431,14 @@ public class ASDCController { } protected void sendCsarDeployNotification(INotificationData iNotif, ResourceStructure resourceStructure, - ToscaResourceStructure toscaResourceStructure, boolean deploySuccessful, String errorReason) { + ToscaResourceStructure toscaResourceStructure, DistributionStatusEnum statusEnum, String errorReason) { IArtifactInfo csarArtifact = toscaResourceStructure.getToscaArtifact(); - if (deploySuccessful) { - - this.sendASDCNotification(NotificationType.DEPLOY, csarArtifact.getArtifactURL(), - asdcConfig.getConsumerID(), resourceStructure.getNotification().getDistributionID(), - DistributionStatusEnum.DEPLOY_OK, errorReason, System.currentTimeMillis()); - - } else { - - this.sendASDCNotification(NotificationType.DEPLOY, csarArtifact.getArtifactURL(), - asdcConfig.getConsumerID(), resourceStructure.getNotification().getDistributionID(), - DistributionStatusEnum.DEPLOY_ERROR, errorReason, System.currentTimeMillis()); + this.sendASDCNotification(NotificationType.DEPLOY, csarArtifact.getArtifactURL(), asdcConfig.getConsumerID(), + resourceStructure.getNotification().getDistributionID(), statusEnum, errorReason, + System.currentTimeMillis()); - } } protected void deployResourceStructure(ResourceStructure resourceStructure, @@ -442,7 +488,7 @@ public class ASDCController { status.name(), artifactURL, "ASDC", "sendASDCNotification"); logger.debug(event); - String action = ""; + try { IDistributionStatusMessage message = new DistributionStatusMessage(artifactURL, consumerID, distributionID, status, timestamp); @@ -454,7 +500,7 @@ public class ASDCController { } else { this.distributionClient.sendDownloadStatus(message); } - action = "sendDownloadStatus"; + break; case DEPLOY: if (errorReason != null) { @@ -462,7 +508,7 @@ public class ASDCController { } else { this.distributionClient.sendDeploymentStatus(message); } - action = "sendDeploymentdStatus"; + break; default: break; @@ -597,6 +643,8 @@ public class ASDCController { } } + wd.updateCatalogDBStatus(iNotif.getServiceInvariantUUID(), overallStatus); + if (isDeploySuccess && watchdogError == null) { sendFinalDistributionStatus(iNotif.getDistributionID(), DistributionStatusEnum.DISTRIBUTION_COMPLETE_OK, null); @@ -611,7 +659,6 @@ public class ASDCController { wdsRepo.save(wds); } - } catch (ObjectOptimisticLockingFailureException e) { logger.debug( @@ -657,7 +704,7 @@ public class ASDCController { String msoConfigPath = getMsoConfigPath(); boolean hasVFResource = false; ToscaResourceStructure toscaResourceStructure = new ToscaResourceStructure(msoConfigPath); - boolean deploySuccessful = true; + DistributionStatusEnum deployStatus = DistributionStatusEnum.DEPLOY_OK; String errorMessage = null; boolean serviceDeployed = false; @@ -667,16 +714,21 @@ public class ASDCController { String filePath = msoConfigPath + "/ASDC/" + iArtifact.getArtifactVersion() + "/" + iArtifact.getArtifactName(); File csarFile = new File(filePath); - String csarFilePath = csarFile.getAbsolutePath(); + + + if (isCsarAlreadyDeployed(iNotif, toscaResourceStructure)) { + return; + } for (IResourceInstance resource : iNotif.getResources()) { String resourceType = resource.getResourceType(); - String category = resource.getCategory(); + logger.info("Processing Resource Type: {}, Model UUID: {}", resourceType, resource.getResourceUUID()); - if ("VF".equals(resourceType)) { + if ("VF".equals(resourceType) && resource.getArtifacts() != null + && !resource.getArtifacts().isEmpty()) { resourceStructure = new VfResourceStructure(iNotif, resource); } else if ("PNF".equals(resourceType)) { resourceStructure = new PnfResourceStructure(iNotif, resource); @@ -694,7 +746,8 @@ public class ASDCController { logger.debug("Processing Resource Type: " + resourceType + " and Model UUID: " + resourceStructure.getResourceInstance().getResourceUUID()); - if ("VF".equals(resourceType)) { + if ("VF".equals(resourceType) && resource.getArtifacts() != null + && !resource.getArtifacts().isEmpty()) { hasVFResource = true; for (IArtifactInfo artifact : resource.getArtifacts()) { IDistributionClientDownloadResult resultArtifact = @@ -730,7 +783,7 @@ public class ASDCController { } } catch (ArtifactInstallerException e) { - deploySuccessful = false; + deployStatus = DistributionStatusEnum.DEPLOY_ERROR; errorMessage = e.getMessage(); logger.error("Exception occurred", e); } @@ -743,12 +796,12 @@ public class ASDCController { try { this.deployResourceStructure(resourceStructure, toscaResourceStructure); } catch (ArtifactInstallerException e) { - deploySuccessful = false; + deployStatus = DistributionStatusEnum.DEPLOY_ERROR; errorMessage = e.getMessage(); logger.error("Exception occurred", e); } } - this.sendCsarDeployNotification(iNotif, resourceStructure, toscaResourceStructure, deploySuccessful, + this.sendCsarDeployNotification(iNotif, resourceStructure, toscaResourceStructure, deployStatus, errorMessage); } @@ -832,7 +885,7 @@ public class ASDCController { } } - private static final String UNKNOWN = "Unknown"; + /** * @return the address of the ASDC we are connected to. diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaData.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaData.java index f4d3e5ce48..20cd9801e9 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaData.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/JsonVfModuleMetaData.java @@ -33,16 +33,16 @@ public class JsonVfModuleMetaData implements IVfModuleData { @JsonProperty("artifacts") private List<String> artifacts; @JsonProperty("properties") - // private List<Map<String, Object>> properties = new ArrayList<>(); + private Map<String, String> properties = new HashMap<>(); + @JsonIgnore + private Map<String, Object> attributesMap = new HashMap<>(); + public Map<String, String> getProperties() { return properties; } - @JsonIgnore - private Map<String, Object> attributesMap = new HashMap<>(); - @Override public List<String> getArtifacts() { return artifacts; diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/NotificationDataImpl.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/NotificationDataImpl.java index c61306fb77..9fd5c2adeb 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/NotificationDataImpl.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/NotificationDataImpl.java @@ -124,7 +124,7 @@ public class NotificationDataImpl implements INotificationData { @Override public List<IResourceInstance> getResources() { - List<IResourceInstance> ret = new ArrayList<IResourceInstance>(); + List<IResourceInstance> ret = new ArrayList<>(); if (resources != null) { ret.addAll(resources); } @@ -145,7 +145,7 @@ public class NotificationDataImpl implements INotificationData { @Override public List<IArtifactInfo> getServiceArtifacts() { - List<IArtifactInfo> temp = new ArrayList<IArtifactInfo>(); + List<IArtifactInfo> temp = new ArrayList<>(); if (serviceArtifacts != null) { temp.addAll(serviceArtifacts); } diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImpl.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImpl.java index 62d11ffec9..2f109cd9d3 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImpl.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/test/emulators/ResourceInfoImpl.java @@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class ResourceInfoImpl implements IResourceInstance { - public ResourceInfoImpl() {} private String resourceInstanceName; private String resourceCustomizationUUID; @@ -44,6 +43,8 @@ public class ResourceInfoImpl implements IResourceInstance { private String subcategory; private List<ArtifactInfoImpl> artifacts; + public ResourceInfoImpl() {} + private ResourceInfoImpl(IResourceInstance resourceInstance) { resourceInstanceName = resourceInstance.getResourceInstanceName(); resourceCustomizationUUID = resourceInstance.getResourceCustomizationUUID(); @@ -58,7 +59,7 @@ public class ResourceInfoImpl implements IResourceInstance { } public static List<ResourceInfoImpl> convertToJsonContainer(List<IResourceInstance> resources) { - List<ResourceInfoImpl> buildResources = new ArrayList<ResourceInfoImpl>(); + List<ResourceInfoImpl> buildResources = new ArrayList<>(); if (resources != null) { for (IResourceInstance resourceInstance : resources) { buildResources.add(new ResourceInfoImpl(resourceInstance)); @@ -114,7 +115,7 @@ public class ResourceInfoImpl implements IResourceInstance { @Override public List<IArtifactInfo> getArtifacts() { - List<IArtifactInfo> temp = new ArrayList<IArtifactInfo>(); + List<IArtifactInfo> temp = new ArrayList<>(); if (artifacts != null) { temp.addAll(artifacts); } 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 14ea0cde4b..6a9c1aa848 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 @@ -50,13 +50,12 @@ import org.springframework.stereotype.Component; * This is a TEST only rest interface. It is not used in production, it is used to aid in testing the ASDC service on * jboss without the need to be connected to the ASDC service broker. It starts the test at the treatNotification step * and simulates both the notification step as well as the artifact download step. - * + * <p> * i.e. http://localhost:8080/asdc/treatNotification/v1 - * + * <p> * i.e. http://localhost:8080/asdc/statusData/v1 - * - * @author jm5423 * + * @author jm5423 */ @Path("/") @@ -64,10 +63,6 @@ import org.springframework.stereotype.Component; @Profile("test") public class ASDCRestInterface { - private static DistributionClientEmulator distributionClientEmulator; - - private static JsonStatusData statusData; - private static final Logger logger = LoggerFactory.getLogger(ASDCRestInterface.class); @Autowired @@ -83,7 +78,7 @@ public class ASDCRestInterface { public Response invokeASDCService(NotificationDataImpl request, @HeaderParam("resource-location") String resourceLocation) throws ASDCControllerException, ASDCParametersException, IOException { - distributionClientEmulator = new DistributionClientEmulator(resourceLocation); + DistributionClientEmulator distributionClientEmulator = new DistributionClientEmulator(resourceLocation); asdcController.setControllerName("asdc-controller1"); asdcController.setDistributionClient(distributionClientEmulator); @@ -100,22 +95,24 @@ public class ASDCRestInterface { public Response invokeASDCStatusData(String request) { try { - distributionClientEmulator = new DistributionClientEmulator("resource-examples/"); - statusData = JsonStatusData.instantiateNotifFromJsonFile("resource-examples/"); + DistributionClientEmulator distributionClientEmulator = + new DistributionClientEmulator("resource-examples/"); + JsonStatusData statusData = JsonStatusData.instantiateNotifFromJsonFile("resource-examples/"); - ASDCController asdcController = new ASDCController("asdc-controller1", distributionClientEmulator); - asdcController.initASDC(); + ASDCController controller = new ASDCController("asdc-controller1", distributionClientEmulator); + controller.initASDC(); toscaInstaller.installTheComponentStatus(statusData); - asdcController.closeASDC(); + controller.closeASDC(); + + logger.info("{} {} {} {}", 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(), "Exception caught during ASDCRestInterface", "ASDC", "invokeASDCService", ErrorCode.BusinessProcesssError.getValue(), "Exception in invokeASDCService", e); } - logger.info("ASDC Updates are complete"); - logger.info("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_DEPLOY_SUC.toString(), statusData.getDistributionID(), - "ASDC", "ASDC Updates Are Complete"); + return null; } } diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ASDCElementInfo.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ASDCElementInfo.java index 043055e23c..81b0843671 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ASDCElementInfo.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ASDCElementInfo.java @@ -47,7 +47,7 @@ public class ASDCElementInfo { * <li>{@link ASDCElementTypeEnum#VNF_RESOURCE}</li> * <ul> */ - public static enum ASDCElementTypeEnum { + public enum ASDCElementTypeEnum { /** * The type VNF_RESOURCE. Represents a VNF_RESOURCE element. */ 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 50a555882d..edf8ff338c 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 @@ -26,6 +26,7 @@ package org.onap.so.asdc.installer.heat; import java.sql.Timestamp; import java.util.ArrayList; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -34,6 +35,8 @@ import java.util.List; import java.util.Map; import java.util.Optional; 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.hibernate.exception.ConstraintViolationException; @@ -47,14 +50,7 @@ import org.onap.sdc.tosca.parser.elements.queries.EntityQuery; import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery; import org.onap.sdc.tosca.parser.enums.SdcTypes; import org.onap.sdc.tosca.parser.impl.SdcPropertyNames; -import org.onap.sdc.toscaparser.api.CapabilityAssignment; -import org.onap.sdc.toscaparser.api.CapabilityAssignments; -import org.onap.sdc.toscaparser.api.Group; -import org.onap.sdc.toscaparser.api.NodeTemplate; -import org.onap.sdc.toscaparser.api.Policy; -import org.onap.sdc.toscaparser.api.Property; -import org.onap.sdc.toscaparser.api.RequirementAssignment; -import org.onap.sdc.toscaparser.api.RequirementAssignments; +import org.onap.sdc.toscaparser.api.*; import org.onap.sdc.toscaparser.api.elements.Metadata; import org.onap.sdc.toscaparser.api.functions.GetInput; import org.onap.sdc.toscaparser.api.parameters.Input; @@ -112,6 +108,8 @@ import org.onap.so.db.catalog.data.repository.ConfigurationResourceCustomization import org.onap.so.db.catalog.data.repository.ConfigurationResourceRepository; import org.onap.so.db.catalog.data.repository.CvnfcCustomizationRepository; import org.onap.so.db.catalog.data.repository.ExternalServiceToInternalServiceRepository; +import org.onap.so.db.catalog.data.repository.HeatEnvironmentRepository; +import org.onap.so.db.catalog.data.repository.HeatFilesRepository; import org.onap.so.db.catalog.data.repository.HeatTemplateRepository; import org.onap.so.db.catalog.data.repository.InstanceGroupRepository; import org.onap.so.db.catalog.data.repository.NetworkResourceCustomizationRepository; @@ -121,6 +119,7 @@ import org.onap.so.db.catalog.data.repository.PnfResourceRepository; import org.onap.so.db.catalog.data.repository.ServiceProxyResourceCustomizationRepository; import org.onap.so.db.catalog.data.repository.ServiceRepository; import org.onap.so.db.catalog.data.repository.TempNetworkHeatTemplateRepository; +import org.onap.so.db.catalog.data.repository.ToscaCsarRepository; import org.onap.so.db.catalog.data.repository.VFModuleCustomizationRepository; import org.onap.so.db.catalog.data.repository.VFModuleRepository; import org.onap.so.db.catalog.data.repository.VnfResourceRepository; @@ -142,6 +141,7 @@ import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.util.CollectionUtils; @Component public class ToscaResourceInstaller { @@ -226,6 +226,12 @@ public class ToscaResourceInstaller { protected HeatTemplateRepository heatRepo; @Autowired + protected HeatEnvironmentRepository heatEnvRepo; + + @Autowired + protected HeatFilesRepository heatFilesRepo; + + @Autowired protected NetworkResourceCustomizationRepository networkCustomizationRepo; @Autowired @@ -242,6 +248,9 @@ public class ToscaResourceInstaller { protected ExternalServiceToInternalServiceRepository externalServiceToInternalServiceRepository; @Autowired + protected ToscaCsarRepository toscaCsarRepo; + + @Autowired protected PnfResourceRepository pnfResourceRepository; @Autowired @@ -252,6 +261,31 @@ public class ToscaResourceInstaller { protected static final Logger logger = LoggerFactory.getLogger(ToscaResourceInstaller.class); + public boolean isCsarAlreadyDeployed(ToscaResourceStructure toscaResourceStructure) + throws ArtifactInstallerException { + boolean deployed = false; + if (toscaResourceStructure == null) { + return deployed; + } + + IArtifactInfo inputToscaCsar = toscaResourceStructure.getToscaArtifact(); + String checkSum = inputToscaCsar.getArtifactChecksum(); + String artifactUuid = inputToscaCsar.getArtifactUUID(); + + Optional<ToscaCsar> toscaCsarObj = toscaCsarRepo.findById(artifactUuid); + if (toscaCsarObj.isPresent()) { + ToscaCsar toscaCsar = toscaCsarObj.get(); + if (!toscaCsar.getArtifactChecksum().equalsIgnoreCase(checkSum)) { + String errorMessage = + String.format("Csar with UUID: %s already exists.Their checksums don't match", artifactUuid); + throw new ArtifactInstallerException(errorMessage); + } else if (toscaCsar.getArtifactChecksum().equalsIgnoreCase(checkSum)) { + deployed = true; + } + } + return deployed; + } + public boolean isResourceAlreadyDeployed(ResourceStructure vfResourceStruct, boolean serviceDeployed) throws ArtifactInstallerException { boolean status = false; @@ -526,27 +560,31 @@ public class ToscaResourceInstaller { logger.debug(" resourceSeq for service uuid(" + service.getModelUUID() + ") : " + resourceSeqStr); } - private static String getValue(Object value, List<Input> servInputs) { - String output = null; + + // this of temporary solution + private static String getValue(Object value, List<Input> inputs) { + String outInput; + String defaultValue = null; if (value instanceof Map) { - // currently this logic handles only one level of nesting. - return ((LinkedHashMap) value).values().toArray()[0].toString(); + outInput = ((LinkedHashMap) value).values().toArray()[0].toString(); } else if (value instanceof GetInput) { String inputName = ((GetInput) value).getInputName(); - - for (Input input : servInputs) { - if (input.getName().equals(inputName)) { - // keep both input name and default value - // if service input does not supplies value the use default value - String defaultValue = input.getDefault() != null ? (String) input.getDefault().toString() : ""; - output = inputName + "|" + defaultValue;// return default value - } + Optional<Input> inputOptional = + inputs.stream().filter(input -> input.getName().equals(inputName)).findFirst(); + if (inputOptional.isPresent()) { + Input input = inputOptional.get(); + defaultValue = input.getDefault() != null ? input.getDefault().toString() : ""; } - + // Gets a value between [ and ] + String regex = "\\[.*?\\]"; + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(value.toString()); + String valueStr = matcher.find() ? matcher.group() : inputName; + outInput = valueStr + "|" + defaultValue; } else { - output = value != null ? value.toString() : ""; + outInput = value != null ? value.toString() : ""; } - return output; // return property value + return outInput; } String getResourceInput(ToscaResourceStructure toscaResourceStructure, String resourceCustomizationUuid) @@ -983,8 +1021,15 @@ public class ToscaResourceInstaller { vnfcInstanceGroupCustomizationRepo.saveAndFlush(vnfcInstanceGroupCustomization); } - - service.getVnfCustomizations().add(vnfResource); + List<String> seqResult = processVNFCGroupSequence(toscaResourceStruct, groupList); + if (!CollectionUtils.isEmpty(seqResult)) { + String resultStr = seqResult.stream().collect(Collectors.joining(",")); + vnfResource.setVnfcInstanceGroupOrder(resultStr); + logger.debug( + "vnfcGroupOrder result for service uuid(" + service.getModelUUID() + ") : " + resultStr); + } + // add this vnfResource with existing vnfResource for this service + addVnfCustomization(service, vnfResource); } else { logger.debug("Notification VF ResourceCustomizationUUID: " + vfNotificationResource.getResourceCustomizationUUID() + " doesn't match " @@ -993,6 +1038,85 @@ public class ToscaResourceInstaller { } } + private List<String> processVNFCGroupSequence(ToscaResourceStructure toscaResourceStructure, + List<Group> groupList) { + if (CollectionUtils.isEmpty(groupList)) { + return Collections.emptyList(); + } + + ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper(); + List<String> strSequence = new ArrayList<>(groupList.size()); + List<Group> tempGroupList = new ArrayList<>(groupList.size()); + List<NodeTemplate> nodes = new ArrayList<>(); + tempGroupList.addAll(groupList); + + for (Group group : groupList) { + List<NodeTemplate> nodeList = group.getMemberNodes(); + boolean hasRequirements = false; + for (NodeTemplate node : nodeList) { + RequirementAssignments requirements = iSdcCsarHelper.getRequirementsOf(node); + if (requirements != null && requirements.getAll() != null && !requirements.getAll().isEmpty()) { + hasRequirements = true; + break; + } + } + + if (!hasRequirements) { + strSequence.add(group.getName()); + tempGroupList.remove(group); + nodes.addAll(nodeList); + } + } + + getVNFCGroupSequenceList(strSequence, tempGroupList, nodes, iSdcCsarHelper); + + return strSequence; + + } + + private void getVNFCGroupSequenceList(List<String> strSequence, List<Group> groupList, List<NodeTemplate> nodes, + ISdcCsarHelper iSdcCsarHelper) { + if (CollectionUtils.isEmpty(groupList)) { + return; + } + + List<Group> tempGroupList = new ArrayList<>(); + tempGroupList.addAll(groupList); + + for (Group group : groupList) { + ArrayList<NodeTemplate> members = group.getMemberNodes(); + for (NodeTemplate memberNode : members) { + boolean isAllExists = true; + RequirementAssignments requirements = iSdcCsarHelper.getRequirementsOf(memberNode); + if (requirements == null || requirements.getAll() == null || requirements.getAll().isEmpty()) { + continue; + } + List<RequirementAssignment> rqaList = requirements.getAll(); + for (RequirementAssignment rqa : rqaList) { + String name = rqa.getNodeTemplateName(); + for (NodeTemplate node : nodes) { + if (name.equals(node.getName())) { + break; + } + } + + isAllExists = false; + break; + } + + if (isAllExists) { + strSequence.add(group.getName()); + tempGroupList.remove(group); + nodes.addAll(group.getMemberNodes()); + } + } + + if (tempGroupList.size() != 0 && tempGroupList.size() < groupList.size()) { + getVNFCGroupSequenceList(strSequence, tempGroupList, nodes, iSdcCsarHelper); + } + } + } + public void processWatchdog(String distributionId, String servideUUID, Optional<String> distributionNotification, String consumerId) { WatchdogServiceModVerIdLookup modVerIdLookup = @@ -1108,77 +1232,95 @@ public class ToscaResourceInstaller { protected void createHeatTemplateFromArtifact(VfResourceStructure vfResourceStructure, ToscaResourceStructure toscaResourceStruct, VfModuleArtifact vfModuleArtifact) { - HeatTemplate heatTemplate = new HeatTemplate(); - List<String> typeList = new ArrayList<>(); - typeList.add(ASDCConfiguration.HEAT_NESTED); - typeList.add(ASDCConfiguration.HEAT_ARTIFACT); - heatTemplate.setTemplateBody( - verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList)); - heatTemplate.setTemplateName(vfModuleArtifact.getArtifactInfo().getArtifactName()); + HeatTemplate existingHeatTemplate = + heatRepo.findByArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - if (vfModuleArtifact.getArtifactInfo().getArtifactTimeout() != null) { - heatTemplate.setTimeoutMinutes(vfModuleArtifact.getArtifactInfo().getArtifactTimeout()); - } else { - heatTemplate.setTimeoutMinutes(240); - } + if (existingHeatTemplate == null) { + HeatTemplate heatTemplate = new HeatTemplate(); + List<String> typeList = new ArrayList<>(); + typeList.add(ASDCConfiguration.HEAT_NESTED); + typeList.add(ASDCConfiguration.HEAT_ARTIFACT); - heatTemplate.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); - heatTemplate.setVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); - heatTemplate.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + heatTemplate.setTemplateBody( + verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList)); + heatTemplate.setTemplateName(vfModuleArtifact.getArtifactInfo().getArtifactName()); - if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { - heatTemplate.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); - } else { - heatTemplate.setArtifactChecksum(MANUAL_RECORD); - } + if (vfModuleArtifact.getArtifactInfo().getArtifactTimeout() != null) { + heatTemplate.setTimeoutMinutes(vfModuleArtifact.getArtifactInfo().getArtifactTimeout()); + } else { + heatTemplate.setTimeoutMinutes(240); + } + + heatTemplate.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); + heatTemplate.setVersion(BigDecimalVersion + .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); + heatTemplate.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - Set<HeatTemplateParam> heatParam = extractHeatTemplateParameters(vfModuleArtifact.getResult(), - vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - heatTemplate.setParameters(heatParam); - vfModuleArtifact.setHeatTemplate(heatTemplate); + if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { + heatTemplate.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); + } else { + heatTemplate.setArtifactChecksum(MANUAL_RECORD); + } + + Set<HeatTemplateParam> heatParam = extractHeatTemplateParameters(vfModuleArtifact.getResult(), + vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + heatTemplate.setParameters(heatParam); + vfModuleArtifact.setHeatTemplate(heatTemplate); + } } protected void createHeatEnvFromArtifact(VfResourceStructure vfResourceStructure, VfModuleArtifact vfModuleArtifact) { - HeatEnvironment heatEnvironment = new HeatEnvironment(); - heatEnvironment.setName(vfModuleArtifact.getArtifactInfo().getArtifactName()); - List<String> typeList = new ArrayList<>(); - typeList.add(ASDCConfiguration.HEAT); - typeList.add(ASDCConfiguration.HEAT_VOL); - heatEnvironment.setEnvironment( - verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList)); - heatEnvironment.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); - heatEnvironment.setVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); - heatEnvironment.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - - if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { - heatEnvironment.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); - } else { - heatEnvironment.setArtifactChecksum(MANUAL_RECORD); + + HeatEnvironment existingHeatEnvironment = + heatEnvRepo.findByArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + + if (existingHeatEnvironment == null) { + HeatEnvironment heatEnvironment = new HeatEnvironment(); + heatEnvironment.setName(vfModuleArtifact.getArtifactInfo().getArtifactName()); + List<String> typeList = new ArrayList<>(); + typeList.add(ASDCConfiguration.HEAT); + typeList.add(ASDCConfiguration.HEAT_VOL); + heatEnvironment.setEnvironment( + verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList)); + heatEnvironment.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); + heatEnvironment.setVersion(BigDecimalVersion + .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); + heatEnvironment.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + + if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { + heatEnvironment.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); + } else { + heatEnvironment.setArtifactChecksum(MANUAL_RECORD); + } + vfModuleArtifact.setHeatEnvironment(heatEnvironment); } - vfModuleArtifact.setHeatEnvironment(heatEnvironment); } protected void createHeatFileFromArtifact(VfResourceStructure vfResourceStructure, VfModuleArtifact vfModuleArtifact, ToscaResourceStructure toscaResourceStruct) { - HeatFiles heatFile = new HeatFiles(); - heatFile.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - heatFile.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); - heatFile.setFileBody(vfModuleArtifact.getResult()); - heatFile.setFileName(vfModuleArtifact.getArtifactInfo().getArtifactName()); - heatFile.setVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); - toscaResourceStruct.setHeatFilesUUID(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { - heatFile.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); - } else { - heatFile.setArtifactChecksum(MANUAL_RECORD); + HeatFiles existingHeatFiles = + heatFilesRepo.findByArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + + if (existingHeatFiles == null) { + HeatFiles heatFile = new HeatFiles(); + heatFile.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + heatFile.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); + heatFile.setFileBody(vfModuleArtifact.getResult()); + heatFile.setFileName(vfModuleArtifact.getArtifactInfo().getArtifactName()); + heatFile.setVersion(BigDecimalVersion + .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); + toscaResourceStruct.setHeatFilesUUID(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { + heatFile.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); + } else { + heatFile.setArtifactChecksum(MANUAL_RECORD); + } + vfModuleArtifact.setHeatFiles(heatFile); + } - vfModuleArtifact.setHeatFiles(heatFile); } protected Service createService(ToscaResourceStructure toscaResourceStructure, @@ -1704,11 +1846,65 @@ public class ToscaResourceInstaller { .getNodeTemplatePropertyLeafValue(vnfcNodeTemplate, getInputName)); vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup); + ArrayList<Input> inputs = vnfcNodeTemplate.getSubMappingToscaTemplate().getInputs(); + createVFCInstanceGroupMembers(vfcInstanceGroupCustom, group, inputs); return vfcInstanceGroupCustom; } + private void createVFCInstanceGroupMembers(VnfcInstanceGroupCustomization vfcInstanceGroupCustom, Group group, + List<Input> inputList) { + List<NodeTemplate> members = group.getMemberNodes(); + if (!CollectionUtils.isEmpty(members)) { + for (NodeTemplate vfcTemplate : members) { + VnfcCustomization vnfcCustomization = new VnfcCustomization(); + + Metadata metadata = vfcTemplate.getMetaData(); + vnfcCustomization + .setModelCustomizationUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + vnfcCustomization.setModelInstanceName(vfcTemplate.getName()); + vnfcCustomization.setModelUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + vnfcCustomization + .setModelInvariantUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + vnfcCustomization.setModelVersion(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + vnfcCustomization.setModelName(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + vnfcCustomization.setToscaNodeType(testNull(vfcTemplate.getType())); + vnfcCustomization + .setDescription(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + vnfcCustomization.setResourceInput(getVnfcResourceInput(vfcTemplate, inputList)); + vfcInstanceGroupCustom.getVnfcCustomizations().add(vnfcCustomization); + } + } + } + + public String getVnfcResourceInput(NodeTemplate vfcTemplate, List<Input> inputList) { + Map<String, String> resouceRequest = new HashMap<>(); + LinkedHashMap<String, Property> vfcTemplateProperties = vfcTemplate.getProperties(); + for (String key : vfcTemplateProperties.keySet()) { + Property property = vfcTemplateProperties.get(key); + String resourceValue = getValue(property.getValue(), inputList); + resouceRequest.put(key, resourceValue); + } + + String resourceCustomizationUuid = + vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); + + String jsonStr = null; + try { + ObjectMapper objectMapper = new ObjectMapper(); + jsonStr = objectMapper.writeValueAsString(resouceRequest); + jsonStr = jsonStr.replace("\"", "\\\""); + logger.debug("vfcResource request for resource customization id (" + resourceCustomizationUuid + ") : " + + jsonStr); + } catch (JsonProcessingException e) { + logger.debug("Json Exception: {}", e.getMessage()); + logger.error("Exception occurred", e); + } + + return jsonStr; + } + protected VfModuleCustomization createVFModuleResource(Group group, NodeTemplate vfTemplate, ToscaResourceStructure toscaResourceStructure, VfResourceStructure vfResourceStructure, IVfModuleData vfModuleData, VnfResourceCustomization vnfResource, Service service, @@ -2124,10 +2320,12 @@ public class ToscaResourceInstaller { vfModuleCustomization.setVolumeHeatEnv(volVfModuleArtifact.getHeatEnvironment()); vfModuleArtifact.incrementDeployedInDB(); } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) { - if (vfModuleArtifact.getHeatEnvironment().getName().contains("volume")) { - vfModuleCustomization.setVolumeHeatEnv(vfModuleArtifact.getHeatEnvironment()); - } else { - vfModuleCustomization.setHeatEnvironment(vfModuleArtifact.getHeatEnvironment()); + if (vfModuleArtifact.getHeatEnvironment() != null) { + if (vfModuleArtifact.getHeatEnvironment().getName().contains("volume")) { + vfModuleCustomization.setVolumeHeatEnv(vfModuleArtifact.getHeatEnvironment()); + } else { + vfModuleCustomization.setHeatEnvironment(vfModuleArtifact.getHeatEnvironment()); + } } vfModuleArtifact.incrementDeployedInDB(); } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ARTIFACT)) { @@ -2158,7 +2356,7 @@ public class ToscaResourceInstaller { // setting resource input for vnf customization vnfResourceCustomization.setResourceInput( getResourceInput(toscaResourceStructure, vnfResourceCustomization.getModelCustomizationUUID())); - vnfResource.getVnfResourceCustomizations().add(vnfResourceCustomization); + service.getVnfCustomizations().add(vnfResourceCustomization); } return vnfResourceCustomization; @@ -2228,6 +2426,13 @@ public class ToscaResourceInstaller { } + if (vnfResourceCustomization.getMinInstances() == null && vnfResourceCustomization.getMaxInstances() == null) { + vnfResourceCustomization.setMinInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); + vnfResourceCustomization.setMaxInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); + } + toscaResourceStructure.setCatalogVnfResourceCustomization(vnfResourceCustomization); return vnfResourceCustomization; @@ -2440,6 +2645,19 @@ public class ToscaResourceInstaller { return inputName; } + // this method add provided vnfCustomization to service with + // existing customization available in db. + private void addVnfCustomization(Service service, VnfResourceCustomization vnfResourceCustomization) { + List<Service> services = serviceRepo.findByModelUUID(service.getModelUUID()); + if (services.size() > 0) { + // service exist in db + Service existingService = services.get(0); + List<VnfResourceCustomization> vnfCustomizations = existingService.getVnfCustomizations(); + vnfCustomizations.forEach(e -> service.getVnfCustomizations().add(e)); + } + service.getVnfCustomizations().add(vnfResourceCustomization); + } + protected static Timestamp getCurrentTimeStamp() { diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/WatchdogDistribution.java b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/WatchdogDistribution.java index 3659ceed12..0128078a59 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/WatchdogDistribution.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/tenantIsolation/WatchdogDistribution.java @@ -30,6 +30,7 @@ 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.graphinventory.entities.uri.Depth; +import org.onap.so.db.catalog.beans.Service; import org.onap.so.db.catalog.data.repository.ServiceRepository; import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus; import org.onap.so.db.request.beans.WatchdogDistributionStatus; @@ -140,7 +141,6 @@ public class WatchdogDistribution { logger.debug("Updating overall DistributionStatus to: {} for distributionId: ", status, distributionId); - watchdogDistributionStatus.setDistributionIdStatus(status); watchdogDistributionStatusRepository.save(watchdogDistributionStatus); } else { logger.debug("Components Size Didn't match with the WatchdogComponentDistributionStatus results."); @@ -181,6 +181,8 @@ public class WatchdogDistribution { throw new Exception(error); } + + AAIResourceUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.MODEL_VER, serviceModelInvariantUUID, serviceModelVersionId); aaiUri.depth(Depth.ZERO); // Do not return relationships if any @@ -198,6 +200,16 @@ public class WatchdogDistribution { } } + public void updateCatalogDBStatus(String serviceModelVersionId, String status) { + try { + Service foundService = serviceRepo.findOneByModelUUID(serviceModelVersionId); + foundService.setDistrobutionStatus(status); + serviceRepo.save(foundService); + } catch (Exception e) { + logger.error("Error updating CatalogDBStatus", e); + } + } + public AAIResourcesClient getAaiClient() { if (aaiClient == null) { aaiClient = new AAIResourcesClient(); diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInputTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInputTest.java index 844adeede2..846eaf47e2 100644 --- a/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInputTest.java +++ b/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInputTest.java @@ -33,10 +33,7 @@ import org.onap.sdc.toscaparser.api.parameters.Input; import org.onap.so.asdc.client.exceptions.ArtifactInstallerException; import org.onap.so.asdc.installer.ToscaResourceStructure; import org.onap.so.db.catalog.beans.Service; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; +import java.util.*; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; @@ -61,6 +58,27 @@ public class ToscaResourceInputTest { Input input; @Test + public void getListResourceInput() { + ToscaResourceInstaller toscaResourceInstaller = new ToscaResourceInstaller(); + LinkedHashMap<String, Property> hashMap = new LinkedHashMap<>(); + hashMap.put("key1", property); + Map<String, Object> map = new HashMap<>(); + map.put("customizationUUID", "69df3303-d2b3-47a1-9d04-41604d3a95fd"); + Metadata metadata = new Metadata(map); + when(nodeTemplate.getProperties()).thenReturn(hashMap); + when(property.getValue()).thenReturn(getInput); + when(getInput.getInputName()).thenReturn("nameKey"); + when(input.getName()).thenReturn("nameKey"); + when(input.getDefault()).thenReturn("defaultValue"); + when(getInput.toString()).thenReturn("getinput:[sites,INDEX,role]"); + when(nodeTemplate.getMetaData()).thenReturn(metadata); + List<Input> inputs = new ArrayList<>(); + inputs.add(input); + String resourceInput = toscaResourceInstaller.getVnfcResourceInput(nodeTemplate, inputs); + assertEquals("{\\\"key1\\\":\\\"[sites,INDEX,role]|defaultValue\\\"}", resourceInput); + } + + @Test public void processResourceSequenceTest() { ToscaResourceInstaller toscaResourceInstaller = new ToscaResourceInstaller(); ToscaResourceStructure toscaResourceStructure = new ToscaResourceStructure(); 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 ce70a252c9..dd107f7775 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 @@ -24,12 +24,14 @@ 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.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; 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.util.ArrayList; import java.util.List; import org.hibernate.exception.LockAcquisitionException; @@ -39,6 +41,7 @@ import org.junit.Test; 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.IResourceInstance; import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; import org.onap.sdc.tosca.parser.impl.SdcCsarHelperImpl; @@ -58,15 +61,17 @@ import org.onap.so.db.catalog.beans.ConfigurationResource; 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 org.onap.so.db.catalog.beans.ToscaCsar; import org.onap.so.db.catalog.data.repository.AllottedResourceCustomizationRepository; import org.onap.so.db.catalog.data.repository.AllottedResourceRepository; import org.onap.so.db.catalog.data.repository.ConfigurationResourceCustomizationRepository; import org.onap.so.db.catalog.data.repository.ServiceRepository; +import org.onap.so.db.catalog.data.repository.ToscaCsarRepository; import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus; import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatusRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.util.ReflectionTestUtils; - +import java.util.Optional; public class ToscaResourceInstallerTest extends BaseTest { @Autowired @@ -117,6 +122,37 @@ public class ToscaResourceInstallerTest extends BaseTest { } @Test + public void isCsarAlreadyDeployedTest() throws ArtifactInstallerException { + IArtifactInfo inputCsar = mock(IArtifactInfo.class); + String artifactUuid = "0122c05e-e13a-4c63-b5d2-475ccf13aa74"; + String checkSum = "MGUzNjJjMzk3OTBkYzExYzQ0MDg2ZDc2M2E2ZjZiZmY="; + + doReturn(checkSum).when(inputCsar).getArtifactChecksum(); + doReturn(artifactUuid).when(inputCsar).getArtifactUUID(); + + doReturn(inputCsar).when(toscaResourceStructure).getToscaArtifact(); + + ToscaCsar toscaCsar = mock(ToscaCsar.class); + + Optional<ToscaCsar> returnValue = Optional.of(toscaCsar); + + ToscaCsarRepository toscaCsarRepo = spy(ToscaCsarRepository.class); + + + doReturn(artifactUuid).when(toscaCsar).getArtifactUUID(); + doReturn(checkSum).when(toscaCsar).getArtifactChecksum(); + doReturn(returnValue).when(toscaCsarRepo).findById(artifactUuid); + + ReflectionTestUtils.setField(toscaInstaller, "toscaCsarRepo", toscaCsarRepo); + + boolean isCsarDeployed = toscaInstaller.isCsarAlreadyDeployed(toscaResourceStructure); + assertTrue(isCsarDeployed); + verify(toscaCsarRepo, times(1)).findById(artifactUuid); + verify(toscaResourceStructure, times(1)).getToscaArtifact(); + verify(toscaCsar, times(2)).getArtifactChecksum(); + } + + @Test public void isResourceAlreadyDeployedTest() throws Exception { notificationData.setServiceName("serviceName"); notificationData.setServiceVersion("123456"); 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 fe0b9f3131..260ff86916 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/schema.sql b/asdc-controller/src/test/resources/schema.sql index 8cc5ee9d49..0e8024da0a 100644 --- a/asdc-controller/src/test/resources/schema.sql +++ b/asdc-controller/src/test/resources/schema.sql @@ -806,6 +806,7 @@ 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), 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 @@ -1109,6 +1110,7 @@ CREATE TABLE `vnf_resource_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), KEY `fk_vnf_resource_customization__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`), @@ -1135,6 +1137,8 @@ CREATE TABLE `vnfc_customization` ( `MODEL_NAME` varchar(200) NOT NULL, `TOSCA_NODE_TYPE` varchar(200) NOT NULL, `DESCRIPTION` varchar(1200) DEFAULT NULL, + `RESOURCE_INPUT` varchar(20000) DEFAULT NULL, + `VNFC_INSTANCE_GROUP_CUSTOMIZATION_ID` integer DEFAULT NULL, `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; 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 c087d586e7..83a44cfe8b 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 @@ -9,7 +9,7 @@ * 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. 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 31fef7c6f7..734262aa55 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,10 +112,6 @@ public class DelegateExecutionImpl implements BuildingBlockExecution, Serializab return this.get("flowToBeCalled"); } - @JsonIgnore - public DelegateExecution getDelegateExecution() { - return this.execution; - } public void setDelegateExecution(final DelegateExecution execution) { this.execution = execution; @@ -126,6 +122,11 @@ public class DelegateExecutionImpl implements BuildingBlockExecution, Serializab }); } + @JsonIgnore + public DelegateExecution getDelegateExecution() { + return this.execution; + } + @SuppressWarnings("unchecked") protected <T> T get(final String key) { final Object value = this.execution.getVariable(key); 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 new file mode 100644 index 0000000000..71ea3b565b --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/InstanceResourceList.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.bpmn.common.resource; + +import com.google.common.reflect.TypeToken; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +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 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 static Map<String, List<List<GroupResource>>> convertUUIReqTOStd(final JsonObject reqInputJsonObj, + List<Resource> seqResourceList) { + + Map<String, List<List<GroupResource>>> normalizedRequest = new HashMap<>(); + for (Resource r : seqResourceList) { + + if (r.getResourceType() == ResourceType.VNF) { + String pk = getPrimaryKey(r); + + JsonElement vfNode = reqInputJsonObj.get(pk); + + // if the service property is type of array then it + // means it is a VF resource + if (vfNode instanceof JsonArray) { + + for (int i = 0; i < ((JsonArray) vfNode).size(); i++) { + List<List<GroupResource>> groupsList = normalizedRequest.get(pk); + if (groupsList == null) { + groupsList = new ArrayList<>(); + normalizedRequest.put(pk, groupsList); + } + + groupsList.add(new ArrayList<>()); + } + } + + } else if (r.getResourceType() == ResourceType.GROUP) { + String sk = getPrimaryKey(r); + + for (String pk : normalizedRequest.keySet()) { + JsonArray vfs = reqInputJsonObj.getAsJsonArray(pk); + + for (int i = 0; i < vfs.size(); i++) { + + JsonElement vfcsNode = vfs.get(i).getAsJsonObject().get(sk); + if (vfcsNode instanceof JsonArray) { + + List<GroupResource> groupResources = normalizedRequest.get(pk).get(i); + + if (groupResources == null) { + groupResources = new ArrayList<>(); + normalizedRequest.get(pk).add(i, groupResources); + } + + for (int j = 0; j < ((JsonArray) vfcsNode).size(); j++) { + groupResources.add((GroupResource) r); + } + } + } + } + } + } + return normalizedRequest; + } + + // this method returns key from resource input + // e.g. {\"sdwansite_emails\" : \"[sdwansiteresource_list(PK), INDEX, sdwansite_emails]|default\", + // ....} + // it will return sdwansiteresource_list + private static String getPrimaryKey(Resource resource) { + String pk = ""; + + String resourceInput = ""; + if (resource instanceof VnfResource) { + resourceInput = ((VnfResource) resource).getResourceInput(); + } else if (resource instanceof GroupResource) { + resourceInput = ((GroupResource) resource).getVnfcs().get(0).getResourceInput(); + } + + Gson gson = new Gson(); + Type type = new TypeToken<Map<String, String>>() {}.getType(); + Map<String, String> map = gson.fromJson(resourceInput, type); + + Optional<String> pkOpt = map.values().stream().filter(e -> e.contains("[")).map(e -> e.replace("[", "")) + .map(e -> e.split(",")[0]).findFirst(); + + return pkOpt.isPresent() ? pkOpt.get() : ""; + } + + private static List<Resource> convertToInstanceResourceList(Map<String, List<List<GroupResource>>> normalizedReq, + List<Resource> seqResourceList) { + List<Resource> flatResourceList = new ArrayList<>(); + for (Resource r : seqResourceList) { + if (r.getResourceType() == ResourceType.VNF) { + String primaryKey = getPrimaryKey(r); + for (String pk : normalizedReq.keySet()) { + + if (primaryKey.equalsIgnoreCase(pk)) { + + List<List<GroupResource>> vfs = normalizedReq.get(pk); + + vfs.stream().forEach(e -> { + flatResourceList.add(r); + flatResourceList.addAll(e); + }); + } + } + } + } + return flatResourceList; + } + + public static List<Resource> getInstanceResourceList(final List<Resource> seqResourceList, + final String uuiRequest) { + + Gson gson = new Gson(); + JsonObject servJsonObject = gson.fromJson(uuiRequest, JsonObject.class); + JsonObject reqInputJsonObj = servJsonObject.getAsJsonObject("service").getAsJsonObject("parameters") + .getAsJsonObject("requestInputs"); + + // this will convert UUI request to normalized form + Map<String, List<List<GroupResource>>> normalizedRequest = convertUUIReqTOStd(reqInputJsonObj, seqResourceList); + return convertToInstanceResourceList(normalizedRequest, seqResourceList); + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceLevel.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceLevel.java new file mode 100644 index 0000000000..a3c75dbd41 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceLevel.java @@ -0,0 +1,5 @@ +package org.onap.so.bpmn.common.resource; + +public enum ResourceLevel { + FIRST, SECOND +} 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 0dbf2c2a75..8aab4ec818 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 @@ -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,9 @@ package org.onap.so.bpmn.common.resource; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; @@ -31,6 +34,7 @@ import java.util.List; import java.util.Map; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; +import org.apache.commons.lang.StringUtils; import org.camunda.bpm.engine.runtime.Execution; import org.onap.so.bpmn.core.UrnPropertiesReader; import org.onap.so.bpmn.core.json.JsonUtils; @@ -82,20 +86,20 @@ public class ResourceRequestBuilder { * "requestInputs":{K,V} } <br> * * @param execution Execution context - * + * * @param serviceUuid The service template uuid - * + * * @param resourceCustomizationUuid The resource customization uuid - * + * * @param serviceParameters the service parameters passed from the API - * + * * @return the resource instantiate parameters - * + * * @since ONAP Beijing Release */ @SuppressWarnings("unchecked") public static String buildResourceRequestParameters(Execution execution, String serviceUuid, - String resourceCustomizationUuid, String serviceParameters) { + String resourceCustomizationUuid, String serviceParameters, Map<String, Object> currentVFData) { List<String> resourceList = jsonUtil.StringArrayToList(execution, (String) JsonUtils.getJsonValue(serviceParameters, "resources")); // Get the right location str for resource. default is an empty array. @@ -126,7 +130,7 @@ public class ResourceRequestBuilder { } Map<String, Object> resourceInputsFromServiceDeclaredLevel = - buildResouceRequest(serviceUuid, resourceCustomizationUuid, serviceInput); + buildResouceRequest(serviceUuid, resourceCustomizationUuid, serviceInput, currentVFData); resourceInputsFromUuiMap.putAll(resourceInputsFromServiceDeclaredLevel); String resourceInputsStr = getJsonString(resourceInputsFromUuiMap); String result = "{\n" + "\"locationConstraints\":" + locationConstraints + ",\n" + "\"requestInputs\":" @@ -136,7 +140,7 @@ public class ResourceRequestBuilder { @SuppressWarnings("unchecked") public static Map<String, Object> buildResouceRequest(String serviceUuid, String resourceCustomizationUuid, - Map<String, Object> serviceInputs) { + Map<String, Object> serviceInputs, Map<String, Object> currentVFData) { try { Map<String, Object> serviceInstnace = getServiceInstnace(serviceUuid); // find match of customization uuid in vnf @@ -144,73 +148,253 @@ public class ResourceRequestBuilder { (Map<String, Map<String, Object>>) serviceInstnace.get("serviceResources"); List<Map<String, Object>> serviceVnfCust = (List<Map<String, Object>>) serviceResources.get("serviceVnfs"); - String resourceInputStr = getResourceInputStr(serviceVnfCust, resourceCustomizationUuid); + Map<String, String> resourceInputData = getResourceInputStr(serviceVnfCust, resourceCustomizationUuid); // find match in network resource - if (resourceInputStr == null) { + if (resourceInputData.isEmpty()) { List<Map<String, Object>> serviceNetworkCust = (List<Map<String, Object>>) serviceResources.get("serviceNetworks"); - resourceInputStr = getResourceInputStr(serviceNetworkCust, resourceCustomizationUuid); + resourceInputData = getResourceInputStr(serviceNetworkCust, resourceCustomizationUuid); // find match in AR resource - if (resourceInputStr == null) { + if (resourceInputData.isEmpty()) { List<Map<String, Object>> serviceArCust = (List<Map<String, Object>>) serviceResources.get("serviceAllottedResources"); - resourceInputStr = getResourceInputStr(serviceArCust, resourceCustomizationUuid); + resourceInputData = getResourceInputStr(serviceArCust, resourceCustomizationUuid); } } - if (resourceInputStr != null && !resourceInputStr.isEmpty()) { - return getResourceInput(resourceInputStr, serviceInputs); + String resourceInputStr = null; + ResourceLevel resourceLevel = null; + if (!resourceInputData.isEmpty()) { + resourceInputStr = resourceInputData.get("resourceInput"); + resourceLevel = ResourceLevel.valueOf(resourceInputData.get("nodeType")); + } + + if (resourceInputStr != null && !resourceInputStr.isEmpty() && resourceLevel != null) { + return getResourceInput(resourceInputStr, serviceInputs, resourceLevel, currentVFData); } } catch (Exception e) { - logger.error("not able to retrieve service instance"); + logger.error("not able to retrieve service instance", e); } return new HashMap(); } - private static String getResourceInputStr(List<Map<String, Object>> resources, String resCustomizationUuid) { + private static Map<String, String> getResourceInputStr(List<Map<String, Object>> resources, + String resCustomizationUuid) { + Map<String, String> resourceInputMap = new HashMap<>(2); for (Map<String, Object> resource : resources) { Map<String, String> modelInfo = (Map<String, String>) resource.get("modelInfo"); if (modelInfo.get("modelCustomizationUuid").equalsIgnoreCase(resCustomizationUuid)) { - return (String) resource.get("resourceInput"); + resourceInputMap.put("resourceInput", (String) resource.get("resourceInput")); + String nodeType = ResourceLevel.FIRST.toString(); + if (((String) resource.get("toscaNodeType")).contains(".vf.")) { + nodeType = ResourceLevel.FIRST.toString(); + } else if (((String) resource.get("toscaNodeType")).contains(".vfc.")) { + nodeType = ResourceLevel.SECOND.toString(); + } + resourceInputMap.put("nodeType", nodeType); + return resourceInputMap; } } - return null; + return new HashMap<>(); } // this method combines resource input with service input - private static Map<String, Object> getResourceInput(String resourceInputStr, Map<String, Object> serviceInputs) { + private static Map<String, Object> getResourceInput(String resourceInputStr, Map<String, Object> serviceInputs, + ResourceLevel resourceLevel, Map<String, Object> currentVFData) { Gson gson = new Gson(); Type type = new TypeToken<Map<String, String>>() {}.getType(); Map<String, Object> resourceInput = gson.fromJson(resourceInputStr, type); + JsonParser parser = new JsonParser(); + + Map<String, Object> uuiServiceInput = serviceInputs; + + int firstLevelIndex = 0; + int secondLevelIndex = 0; + String firstLevelKey = null; + String secondLevelKey = null; + boolean levelKeyNameUpdated = false; + int indexToPick = 0; + + if (null != currentVFData) { + firstLevelIndex = getIntValue(currentVFData.get("currentFirstLevelIndex"), 0); + secondLevelIndex = getIntValue(currentVFData.get("currentSecondLevelIndex"), 0); + final String lastFirstLevelKey = firstLevelKey = (String) currentVFData.get("currentFirstLevelKey"); + final String lastSecondLevelKey = secondLevelKey = (String) currentVFData.get("currentSecondLevelKey"); + + if (null != currentVFData.get("lastNodeTypeProcessed")) { + ResourceLevel lastResourceLevel = + ResourceLevel.valueOf(currentVFData.get("lastNodeTypeProcessed").toString()); + switch (resourceLevel) { + case FIRST: + // if it is next request for same group then increment first level index + switch (lastResourceLevel) { + case FIRST: + boolean isSameLevelRequest = resourceInput.values().stream().anyMatch(item -> { + JsonElement tree = parser.parse(((String) item).split("\\|")[0]); + return tree.isJsonArray() && tree.getAsJsonArray().get(0).getAsString() + .equalsIgnoreCase(lastFirstLevelKey); + }); + if (isSameLevelRequest) { + firstLevelIndex++; + } + break; + case SECOND: + firstLevelIndex = 0; + secondLevelKey = null; + break; + + } + indexToPick = firstLevelIndex; + break; + case SECOND: + // if it is next request for same group then increment second level index + switch (lastResourceLevel) { + case FIRST: + secondLevelIndex = 0; + break; + case SECOND: + boolean isSameLevelRequest = resourceInput.values().stream().anyMatch(item -> { + JsonElement tree = parser.parse(((String) item).split("\\|")[0]); + return tree.isJsonArray() && tree.getAsJsonArray().get(0).getAsString() + .equalsIgnoreCase(lastSecondLevelKey); + }); + if (isSameLevelRequest) { + secondLevelIndex++; + } + break; + } + // get actual parent object to search for second level objects + if (null != lastFirstLevelKey) { + Object currentObject = serviceInputs.get(lastFirstLevelKey); + if ((null != currentObject) && (currentObject instanceof List)) { + List currentFirstLevelList = (List) currentObject; + if (currentFirstLevelList.size() > firstLevelIndex) { + uuiServiceInput = (Map<String, Object>) currentFirstLevelList.get(firstLevelIndex); + } + + } + } + indexToPick = secondLevelIndex; + break; + + } + } + + + } // replace value if key is available in service input for (String key : resourceInput.keySet()) { String value = (String) resourceInput.get(key); if (value.contains("|")) { + + // check which level + // node it type of getinput String[] split = value.split("\\|"); String tmpKey = split[0]; - if (serviceInputs.containsKey(tmpKey)) { - value = (String) serviceInputs.get(tmpKey); + + JsonElement jsonTree = parser.parse(tmpKey); + + // check if it is a list type + if (jsonTree.isJsonArray()) { + JsonArray jsonArray = jsonTree.getAsJsonArray(); + boolean matchFound = false; + if (jsonArray.size() == 3) { + String keyName = jsonArray.get(0).getAsString(); + String keyType = jsonArray.get(2).getAsString(); + if (!levelKeyNameUpdated) { + switch (resourceLevel) { + case FIRST: + firstLevelKey = keyName; + break; + case SECOND: + secondLevelKey = keyName; + break; + } + levelKeyNameUpdated = true; + } + + if (uuiServiceInput.containsKey(keyName)) { + Object vfcLevelObject = uuiServiceInput.get(keyName); + // it will be always list + if (vfcLevelObject instanceof List) { + List vfcObject = (List) vfcLevelObject; + if (vfcObject.size() > indexToPick) { + Map<String, Object> vfMap = (Map<String, Object>) vfcObject.get(indexToPick); + if (vfMap.containsKey(keyType)) { + if (vfMap.get(keyType) instanceof String) { + value = (String) vfMap.get(keyType); + } else { + value = getJsonString(vfMap.get(keyType)); + } + matchFound = true; + } + } + } + } + } + + if (!matchFound) { + if (split.length == 1) { // means value is empty e.g. "a":"key1|" + value = ""; + } else { + value = split[1]; + } + } + } else { - if (split.length == 1) { // means value is empty e.g. "a":"key1|" - value = ""; + + // if not a list type + if (uuiServiceInput.containsKey(tmpKey)) { + value = (String) uuiServiceInput.get(tmpKey); } else { - value = split[1]; + if (split.length == 1) { // means value is empty e.g. "a":"key1|" + value = ""; + } else { + value = split[1]; + } } } + } resourceInput.put(key, value); } + // store current processed details into map + if (null != currentVFData) { + currentVFData.put("currentFirstLevelKey", firstLevelKey); + currentVFData.put("currentFirstLevelIndex", firstLevelIndex); + currentVFData.put("currentSecondLevelKey", secondLevelKey); + currentVFData.put("currentSecondLevelIndex", secondLevelIndex); + currentVFData.put("lastNodeTypeProcessed", resourceLevel.toString()); + } + return resourceInput; } + private static int getIntValue(Object inputObj, int defaultValue) { + if (null != inputObj) { + if (inputObj instanceof Integer) { + return ((Integer) inputObj).intValue(); + } + if (StringUtils.isNotEmpty(inputObj.toString())) { + try { + int val = Integer.parseInt(inputObj.toString()); + return val; + } catch (NumberFormatException e) { + logger.warn("Unable to parse to int", e.getMessage()); + } + } + } + return defaultValue; + } + public static Map<String, Object> getServiceInstnace(String uuid) throws Exception { String catalogEndPoint = UrnPropertiesReader.getVariable("mso.catalog.db.endpoint"); 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 6c3a0c43ed..b9f5a6af8e 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 @@ -78,6 +78,8 @@ public class ServiceInstance implements Serializable, ShallowCopy<ServiceInstanc private ModelInfoServiceInstance modelInfoServiceInstance; @JsonProperty("instance-groups") private List<InstanceGroup> instanceGroups = new ArrayList<>(); + @JsonProperty("service-proxies") + private List<ServiceProxy> serviceProxies = new ArrayList<ServiceProxy>(); public List<GenericVnf> getVnfs() { return vnfs; @@ -211,6 +213,10 @@ public class ServiceInstance implements Serializable, ShallowCopy<ServiceInstanc this.instanceGroups = instanceGroups; } + public List<ServiceProxy> getServiceProxies() { + return serviceProxies; + } + @Override public boolean equals(final Object other) { if (!(other instanceof ServiceInstance)) { 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 db5c11a954..4c91ad38a0 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 @@ -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. @@ -34,7 +34,6 @@ public class SolutionCandidates implements Serializable { private List<Candidate> requiredCandidates = new ArrayList<Candidate>(); @JsonProperty("excludedCandidates") private List<Candidate> excludedCandidates = new ArrayList<Candidate>(); - // TODO figure out best way to do this @JsonProperty("existingCandidates") private List<Candidate> existingCandidates = new ArrayList<Candidate>(); diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java index c8e296d5ac..0a7a75c89b 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java @@ -82,7 +82,6 @@ public class ExecuteBuildingBlockRainyDay { boolean aLaCarte = (boolean) execution.getVariable("aLaCarte"); boolean suppressRollback = (boolean) execution.getVariable("suppressRollback"); String handlingCode = ""; - WorkflowException workflowException = (WorkflowException) execution.getVariable("WorkflowException"); try { // Extract error data to be returned to WorkflowAction @@ -97,6 +96,9 @@ public class ExecuteBuildingBlockRainyDay { try { serviceType = gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0) .getModelInfoServiceInstance().getServiceType(); + if (serviceType == null || serviceType.isEmpty()) { + serviceType = ASTERISK; + } } catch (Exception ex) { // keep default serviceType value } @@ -118,6 +120,7 @@ public class ExecuteBuildingBlockRainyDay { } catch (Exception ex) { // keep default errorCode value } + try { errorCode = "" + (String) execution.getVariable("WorkflowExceptionCode"); } catch (Exception ex) { @@ -131,29 +134,19 @@ public class ExecuteBuildingBlockRainyDay { // keep default workStep value } - RainyDayHandlerStatus rainyDayHandlerStatus; - rainyDayHandlerStatus = catalogDbClient - .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(bbName, - serviceType, vnfType, errorCode, workStep); - if (rainyDayHandlerStatus == null) { - rainyDayHandlerStatus = catalogDbClient - .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(bbName, - ASTERISK, ASTERISK, errorCode, ASTERISK); + String errorMessage = ASTERISK; + try { + errorMessage = workflowException.getErrorMessage(); + } catch (Exception ex) { + // keep default workStep value } + RainyDayHandlerStatus rainyDayHandlerStatus; + rainyDayHandlerStatus = catalogDbClient.getRainyDayHandlerStatus(bbName, serviceType, vnfType, + errorCode, workStep, errorMessage); + if (rainyDayHandlerStatus == null) { - rainyDayHandlerStatus = catalogDbClient - .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(bbName, - ASTERISK, ASTERISK, ASTERISK, ASTERISK); - if (rainyDayHandlerStatus == null) { - handlingCode = "Abort"; - } else { - if (primaryPolicy) { - handlingCode = rainyDayHandlerStatus.getPolicy(); - } else { - handlingCode = rainyDayHandlerStatus.getSecondaryPolicy(); - } - } + handlingCode = "Abort"; } else { if (primaryPolicy) { handlingCode = rainyDayHandlerStatus.getPolicy(); 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 4332a6cf4e..86bbead9a4 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 @@ -47,7 +47,7 @@ public class ExtractPojosForBB { return extractByKey(execution, key, execution.getLookupMap().get(key)); } - public <T> T extractByKey(BuildingBlockExecution execution, ResourceKey key, String value) + protected <T> T extractByKey(BuildingBlockExecution execution, ResourceKey key, String value) throws BBObjectNotFoundException { Optional<T> result = Optional.empty(); diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BadResponseException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BadResponseException.java index 333d99ed2e..7b1066d48c 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BadResponseException.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/BadResponseException.java @@ -22,10 +22,21 @@ package org.onap.so.client.exception; public class BadResponseException extends Exception { + String responseCode; + public BadResponseException() {} public BadResponseException(String message) { super(message); } + public BadResponseException(String message, String responseCode) { + super(message); + this.responseCode = responseCode; + } + + public String getResponseCode() { + return responseCode; + } + } 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 ae5e41f7ce..b69ab151c4 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 @@ -22,21 +22,40 @@ package org.onap.so.client.exception; +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.camunda.bpm.engine.delegate.BpmnError; import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.onap.aai.domain.yang.LInterface; +import org.onap.aai.domain.yang.Vserver; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.common.DelegateExecutionImpl; import org.onap.so.bpmn.core.WorkflowException; import org.onap.so.logger.ErrorCode; +import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; +import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; +import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; import org.onap.so.logger.MessageEnum; +import org.onap.so.objects.audit.AAIObjectAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; + @Component public class ExceptionBuilder { private static final Logger logger = LoggerFactory.getLogger(ExceptionBuilder.class); + + protected ExtractPojosForBB getExtractPojosForBB() { + return new ExtractPojosForBB(); + } + public void buildAndThrowWorkflowException(BuildingBlockExecution execution, int errorCode, Exception exception) { String msg = "Exception in %s.%s "; try { @@ -132,4 +151,63 @@ public class ExceptionBuilder { return execution.getProcessEngineServices().getRepositoryService() .getProcessDefinition(execution.getProcessDefinitionId()).getKey(); } + + public void processAuditException(DelegateExecutionImpl execution) { + logger.info("Building a WorkflowException for Subflow"); + + 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(" 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."); + + WorkflowException exception = new WorkflowException(processKey, 400, errorMessage.toString()); + execution.setVariable("WorkflowException", exception); + execution.setVariable("WorkflowExceptionErrorMessage", errorMessage); + logger.info("Outgoing WorkflowException is {}", exception); + logger.info("Throwing MSOWorkflowException"); + throw new BpmnError("AAIInventoryFailure"); + } } 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 new file mode 100644 index 0000000000..84cf491355 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/UnexpectedDataException.java @@ -0,0 +1,17 @@ +package org.onap.so.client.exception; + + +public class UnexpectedDataException extends Exception { + + public UnexpectedDataException() {} + + public UnexpectedDataException(String message, String system) { + super("Unexpected data found in " + system + ". " + message); + } + + public UnexpectedDataException(String message) { + super("Unexpected data found. " + message); + } + + +} 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 79a94d5298..3bb417741f 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java @@ -325,6 +325,7 @@ public class BuildingBlockTestDataSetup { gBBInput.setCustomer(buildCustomer()); } gBBInput.getCustomer().getServiceSubscription().getServiceInstances().add(serviceInstance); + gBBInput.setServiceInstance(serviceInstance); lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstance.getServiceInstanceId()); return serviceInstance; diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/baseclient/BaseClientTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/baseclient/BaseClientTest.java index ee2c10ca4b..05af5f71f8 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/baseclient/BaseClientTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/baseclient/BaseClientTest.java @@ -29,6 +29,7 @@ import java.util.Map; import javax.ws.rs.core.UriBuilder; import org.junit.Test; import org.onap.so.BaseTest; +import org.onap.so.client.BaseClient; import org.springframework.core.ParameterizedTypeReference; import wiremock.org.apache.http.entity.ContentType; diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/resource/InstnaceResourceListTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/resource/InstnaceResourceListTest.java new file mode 100644 index 0000000000..3be67c965c --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/resource/InstnaceResourceListTest.java @@ -0,0 +1,46 @@ +package org.onap.so.bpmn.common.resource; + +import org.junit.Assert; +import org.junit.Test; +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 java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class InstnaceResourceListTest { + + public static String RESOURCE_PATH = "src/test/resources/__files/InstanceResourceList/"; + + @Test + public void testInstanceResourceList() throws IOException { + String uuiRequest = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "InstanceResourceList" + ".json"))); + List<Resource> instanceResourceList = + InstanceResourceList.getInstanceResourceList(createResourceSequence(), uuiRequest); + Assert.assertEquals(4, instanceResourceList.size()); + Assert.assertEquals(ResourceType.VNF, instanceResourceList.get(0).getResourceType()); + Assert.assertEquals(ResourceType.GROUP, instanceResourceList.get(1).getResourceType()); + Assert.assertEquals(ResourceType.VNF, instanceResourceList.get(2).getResourceType()); + Assert.assertEquals(ResourceType.GROUP, instanceResourceList.get(3).getResourceType()); + } + + private List<Resource> createResourceSequence() { + List<Resource> resourceList = new ArrayList<>(); + VnfResource vnfResource = new VnfResource(); + vnfResource.setResourceInput("{\"a\":\"[sdwansiteresource_list,INDEX,sdwansiteresource_list]\"}"); + + VnfcResource vnfcResource = new VnfcResource(); + vnfcResource.setResourceInput("{\"a\":\"[sdwansitewan_list,INDEX,test]\"}"); + + GroupResource groupResource = new GroupResource(); + groupResource.setVnfcs(Arrays.asList(vnfcResource)); + + return Arrays.asList(vnfResource, groupResource); + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilderTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilderTest.java index c7c181744f..adfee796f2 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilderTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilderTest.java @@ -19,19 +19,53 @@ */ package org.onap.so.bpmn.common.resource; +import org.junit.Assert; +import org.junit.Before; import org.junit.Test; import org.onap.so.BaseTest; import java.util.HashMap; import java.util.List; import java.util.Map; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.onap.so.bpmn.mock.FileUtil; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.ok; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.junit.Assert.assertEquals; - +import static org.junit.Assert.assertTrue; public class ResourceRequestBuilderTest extends BaseTest { + private Map<String, Object> userInputMap = null; + + private String serviceInput = null; + + @Before + public void initializeMockObjects() { + + if (null == this.userInputMap) { + ObjectMapper mapper = new ObjectMapper(); + + try { + String serviceInputRequest = FileUtil.readResourceFile("__files/UUI-SO-REQ.json"); + this.userInputMap = mapper.readValue(serviceInputRequest, new TypeReference<Map<String, Object>>() {}); + } catch (Exception e) { + Assert.fail(e.getMessage()); + } + } + + if (null == this.serviceInput) { + + try { + this.serviceInput = FileUtil.readResourceFile("__files/SERVICE-SO-REQ-INPUT.json"); + } catch (Exception e) { + Assert.fail(e.getMessage()); + } + } + + } + @Test public void getResourceInputTest() throws Exception { @@ -102,7 +136,7 @@ public class ResourceRequestBuilderTest extends BaseTest { HashMap serviceInput = new HashMap(); serviceInput.put("key", "value"); Map<String, Object> stringObjectMap = ResourceRequestBuilder.buildResouceRequest( - "c3954379-4efe-431c-8258-f84905b158e5", "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput); + "c3954379-4efe-431c-8258-f84905b158e5", "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput, null); assertEquals(stringObjectMap.get("a"), "value"); } @@ -173,7 +207,7 @@ public class ResourceRequestBuilderTest extends BaseTest { HashMap serviceInput = new HashMap(); serviceInput.put("key1", "value"); Map<String, Object> stringObjectMap = ResourceRequestBuilder.buildResouceRequest( - "c3954379-4efe-431c-8258-f84905b158e5", "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput); + "c3954379-4efe-431c-8258-f84905b158e5", "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput, null); assertEquals(stringObjectMap.get("a"), "default_value"); } @@ -244,7 +278,7 @@ public class ResourceRequestBuilderTest extends BaseTest { HashMap serviceInput = new HashMap(); serviceInput.put("key1", "value"); Map<String, Object> stringObjectMap = ResourceRequestBuilder.buildResouceRequest( - "c3954379-4efe-431c-8258-f84905b158e5", "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput); + "c3954379-4efe-431c-8258-f84905b158e5", "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput, null); assertEquals(stringObjectMap.get("a"), "value"); } @@ -337,7 +371,7 @@ public class ResourceRequestBuilderTest extends BaseTest { HashMap serviceInput = new HashMap(); serviceInput.put("key1", "value"); Map<String, Object> stringObjectMap = ResourceRequestBuilder.buildResouceRequest( - "c3954379-4efe-431c-8258-f84905b158e5", "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput); + "c3954379-4efe-431c-8258-f84905b158e5", "e776449e-2b10-45c5-9217-2775c88ca1a0", serviceInput, null); assertEquals(0, stringObjectMap.size()); } @@ -382,8 +416,78 @@ public class ResourceRequestBuilderTest extends BaseTest { HashMap serviceInput = new HashMap(); serviceInput.put("key2", "value"); Map<String, Object> stringObjectMap = ResourceRequestBuilder.buildResouceRequest( - "c3954379-4efe-431c-8258-f84905b158e5", "a00404d5-d7eb-4c46-b6b6-9cf2d087e545", serviceInput); + "c3954379-4efe-431c-8258-f84905b158e5", "a00404d5-d7eb-4c46-b6b6-9cf2d087e545", serviceInput, null); assertEquals(stringObjectMap.get("a"), ""); } + @Test + public void getListResourceInputTest() throws Exception { + + + + wireMockServer.stubFor(get(urlEqualTo( + "/ecomp/mso/catalog/v2/serviceResources?serviceModelUuid=c3954379-4efe-431c-8258-f84905b158e5")) + .willReturn(ok(this.serviceInput))); + + // when(UrnPropertiesReader.getVariable(anyString())).thenReturn("http://localhost:8080"); + + // VF level request + Map<String, Object> currentVFData = new HashMap<>(); + Map<String, Object> stringObjectMap = + ResourceRequestBuilder.buildResouceRequest("c3954379-4efe-431c-8258-f84905b158e5", + "a00404d5-d7eb-4c46-b6b6-9cf2d087e545", this.userInputMap, currentVFData); + assertEquals("b", stringObjectMap.get("a")); + assertEquals("hub_spoke", stringObjectMap.get("topology")); + assertEquals("defaultvpn", stringObjectMap.get("name")); + assertTrue(((String) stringObjectMap.get("sitelist")).contains("[")); + + // vfc level request + stringObjectMap = ResourceRequestBuilder.buildResouceRequest("c3954379-4efe-431c-8258-f84905b158e5", + "e776449e-2b10-45c5-9217-2775c88ca1a0", this.userInputMap, currentVFData); + assertEquals("", stringObjectMap.get("a")); + assertEquals("layer3-port", stringObjectMap.get("portswitch")); + assertEquals("192.168.10.1", stringObjectMap.get("ipAddress")); + assertEquals("vCPE", stringObjectMap.get("deviceName")); + + // vfc level request + stringObjectMap = ResourceRequestBuilder.buildResouceRequest("c3954379-4efe-431c-8258-f84905b158e5", + "e776449e-2b10-45c5-9217-2775c88ca1a1", this.userInputMap, currentVFData); + assertEquals("", stringObjectMap.get("a")); + assertEquals("layer2-port", stringObjectMap.get("portswitch")); + assertEquals("192.168.11.1", stringObjectMap.get("ipAddress")); + assertEquals("CPE_Beijing", stringObjectMap.get("deviceName")); + + // VF level request + stringObjectMap = ResourceRequestBuilder.buildResouceRequest("c3954379-4efe-431c-8258-f84905b158e5", + "e776449e-2b10-45c5-9217-2775c88ca1c1", this.userInputMap, currentVFData); + assertEquals("Huawei Private Cloud", stringObjectMap.get("address")); + assertEquals("dsvpn_hub1", stringObjectMap.get("role")); + assertTrue(((String) stringObjectMap.get("wanlist")).contains("[")); + assertTrue(((String) stringObjectMap.get("devlist")).contains("[")); + + // VFC request + stringObjectMap = ResourceRequestBuilder.buildResouceRequest("c3954379-4efe-431c-8258-f84905b158e5", + "e776449e-2b10-45c5-9217-2775c88cb1a1", this.userInputMap, currentVFData); + assertEquals("Huawei Private Cloud", stringObjectMap.get("address")); + assertEquals("20000", stringObjectMap.get("postcode")); + assertEquals("single_gateway", stringObjectMap.get("type")); + assertEquals("vCPE", stringObjectMap.get("deviceName")); + assertEquals("20.20.20.1", stringObjectMap.get("systemip")); + assertEquals("default_ipv6", stringObjectMap.get("systemipv6")); + + + // VFC request again + /* + * stringObjectMap = ResourceRequestBuilder.buildResouceRequest( "c3954379-4efe-431c-8258-f84905b158e5", + * "e776449e-2b10-45c5-9217-2775c88cb1f1", this.userInputMap, currentVFData); + * assertEquals("Huawei Public Cloud", stringObjectMap.get("address")); assertEquals("20001", + * stringObjectMap.get("postcode")); assertEquals("multiple_gateway", stringObjectMap.get("type")); + * assertEquals("CPE_Beijing", stringObjectMap.get("deviceName")); assertEquals("20.20.20.2", + * stringObjectMap.get("systemip")); + */ + + + } + + } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java index e8d597a823..c5da3cbd51 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java @@ -68,6 +68,8 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { delegateExecution.setVariable("WorkflowException", new WorkflowException("", 7000, "")); delegateExecution.setVariable("buildingBlock", executeBuildingBlock); delegateExecution.setVariable("lookupKeyMap", lookupKeyMap); + + delegateExecution.setVariable("WorkflowException", new WorkflowException("processKey", 7000, "errorMessage")); } @Test @@ -101,12 +103,10 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { rainyDayHandlerStatus.setPolicy("Rollback"); rainyDayHandlerStatus.setWorkStep(ASTERISK); - doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient) - .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep( - "AssignServiceInstanceBB", "st1", "vnft1", "7000", "*"); + doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB", + "st1", "vnft1", "7000", "*", "errorMessage"); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); - assertEquals("Rollback", delegateExecution.getVariable("handlingCode")); } @@ -126,15 +126,9 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { rainyDayHandlerStatus.setPolicy("Rollback"); rainyDayHandlerStatus.setWorkStep(ASTERISK); - doReturn(null).when(MOCK_catalogDbClient) - .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep( - "AssignServiceInstanceBB", "st1", "vnft1", "7000", ASTERISK); - doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient) - .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep( - "AssignServiceInstanceBB", ASTERISK, ASTERISK, ASTERISK, ASTERISK); - + doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB", + "st1", "vnft1", ASTERISK, ASTERISK, "errorMessage"); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); - assertEquals("Rollback", delegateExecution.getVariable("handlingCode")); assertEquals(5, delegateExecution.getVariable("maxRetries")); } @@ -145,9 +139,8 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { serviceInstance.getModelInfoServiceInstance().setServiceType("st1"); vnf.setVnfType("vnft1"); delegateExecution.setVariable("aLaCarte", true); - doReturn(null).when(MOCK_catalogDbClient) - .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(isA(String.class), - isA(String.class), isA(String.class), isA(String.class), isA(String.class)); + doReturn(null).when(MOCK_catalogDbClient).getRainyDayHandlerStatus(isA(String.class), isA(String.class), + isA(String.class), isA(String.class), isA(String.class), isA(String.class)); delegateExecution.setVariable("suppressRollback", false); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); @@ -157,9 +150,8 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { @Test public void queryRainyDayTableExceptionTest() { - doThrow(RuntimeException.class).when(MOCK_catalogDbClient) - .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(isA(String.class), - isA(String.class), isA(String.class), isA(String.class), isA(String.class)); + doThrow(RuntimeException.class).when(MOCK_catalogDbClient).getRainyDayHandlerStatus(isA(String.class), + isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class)); delegateExecution.setVariable("aLaCarte", true); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); delegateExecution.setVariable("suppressRollback", false); @@ -184,9 +176,8 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { rainyDayHandlerStatus.setWorkStep(ASTERISK); rainyDayHandlerStatus.setSecondaryPolicy("Abort"); - doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient) - .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep( - "AssignServiceInstanceBB", "st1", "vnft1", "7000", "*"); + doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB", + "st1", "vnft1", "7000", "*", "errorMessage"); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, false); @@ -210,9 +201,8 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { rainyDayHandlerStatus.setWorkStep(ASTERISK); rainyDayHandlerStatus.setSecondaryPolicy("Abort"); - doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient) - .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep( - "AssignServiceInstanceBB", "st1", "vnft1", "7000", "*"); + doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB", + "st1", "vnft1", "7000", "*", "errorMessage"); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); @@ -236,9 +226,8 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { rainyDayHandlerStatus.setWorkStep(ASTERISK); rainyDayHandlerStatus.setSecondaryPolicy("Abort"); - doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient) - .getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep( - "AssignServiceInstanceBB", "st1", "vnft1", "7000", "*"); + doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB", + "st1", "vnft1", "7000", "*", "errorMessage"); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true); 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 ef066853ca..4ade9dbe32 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 @@ -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,17 +21,66 @@ package org.onap.so.client.exception; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; import org.camunda.bpm.engine.delegate.BpmnError; +import org.junit.Before; import org.junit.Test; -import org.onap.so.bpmn.mock.FileUtil; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.onap.aai.domain.yang.Vserver; import org.onap.so.BaseTest; +import org.onap.so.bpmn.common.DelegateExecutionImpl; +import org.onap.so.bpmn.core.WorkflowException; +import org.onap.so.bpmn.mock.FileUtil; +import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; +import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.objects.audit.AAIObjectAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; +import org.springframework.beans.BeanUtils; +import com.fasterxml.jackson.core.JsonProcessingException; public class ExceptionBuilderTest extends BaseTest { private static final String RESOURCE_PATH = "__files/"; private static final String VALID_ERROR_MESSAGE = "{test error message}"; + @Mock + protected ExtractPojosForBB extractPojosForBB; + + @Spy + @InjectMocks + private ExceptionBuilder exceptionBuilder = new ExceptionBuilder(); + + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + + @Before + public void before() throws BBObjectNotFoundException, JsonProcessingException { + setCloudRegion(); + when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))) + .thenReturn(buildVfModule()); + AAIObjectAuditList auditList = new AAIObjectAuditList(); + auditList.setAuditType("create"); + auditList.setHeatStackName("testStackName"); + AAIObjectAudit vserver = new AAIObjectAudit(); + vserver.setAaiObjectType(AAIObjectType.VSERVER.typeName()); + vserver.setDoesObjectExist(false); + Vserver vs = new Vserver(); + vs.setVserverId("testVServerId"); + Vserver vServerShallow = new Vserver(); + BeanUtils.copyProperties(vs, vServerShallow, "LInterfaces"); + vserver.setAaiObject(vServerShallow); + auditList.getAuditList().add(vserver); + + execution.setVariable("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditList)); + } + @Test public void buildAndThrowWorkflowExceptionTest() { @@ -77,4 +126,20 @@ public class ExceptionBuilderTest extends BaseTest { assertEquals("MSOWorkflowException", bpmnException.getErrorCode()); } } + + @Test + public void processAuditExceptionTest() { + try { + Mockito.doReturn(extractPojosForBB).when(exceptionBuilder).getExtractPojosForBB(); + exceptionBuilder.processAuditException((DelegateExecutionImpl) execution); + } catch (BpmnError bpmnException) { + assertEquals("AAIInventoryFailure", bpmnException.getErrorCode()); + 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.", + we.getErrorMessage()); + } + } + } diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/InstanceResourceList/InstanceResourceList.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/InstanceResourceList/InstanceResourceList.json new file mode 100644 index 0000000000..0b3d9f0bbe --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/InstanceResourceList/InstanceResourceList.json @@ -0,0 +1,175 @@ +{ + "service":{ + "name":"SiteService", + "description":"SiteService", + "serviceInvariantUuid":"5c13f3fb-2744-4635-9f1f-c59c92dc8f70", + "serviceUuid":"3a76b1f5-fb0d-4b6b-82d5-0e8a4ebc3838", + "globalSubscriberId":"test_custormer", + "serviceType":"example-service-type", + "parameters":{ + "locationConstraints":[ + + ], + "resources":[ + { + "resourceIndex":"1", + "resourceName":"sdwanvpnresource", + "resourceInvariantUuid":"0c0e1cbe-6e01-4f9e-8c45-a9700ebc14df", + "resourceUuid":"4ad2d390-5c51-45f5-9710-b467a4ec7a73", + "resourceCustomizationUuid":"66590e07-0777-415c-af44-36347cf3ddd3", + "parameters":{ + "locationConstraints":[ + + ], + "resources":[ + + ], + "requestInputs":{ + + } + } + }, + { + "resourceIndex":"1", + "resourceName":"sdwansiteresource", + "resourceInvariantUuid":"97a3e552-08c4-4697-aeeb-d8d3e09ce58e", + "resourceUuid":"63d8e1af-32dc-4c71-891d-e3f7b6a976d2", + "resourceCustomizationUuid":"205456e7-3dc0-40c4-8cb0-28e6c1877042", + "parameters":{ + "locationConstraints":[ + + ], + "resources":[ + + ], + "requestInputs":{ + + } + } + }, + { + "resourceIndex":"2", + "resourceName":"sdwansiteresource", + "resourceInvariantUuid":"97a3e552-08c4-4697-aeeb-d8d3e09ce58e", + "resourceUuid":"63d8e1af-32dc-4c71-891d-e3f7b6a976d2", + "resourceCustomizationUuid":"205456e7-3dc0-40c4-8cb0-28e6c1877042", + "parameters":{ + "locationConstraints":[ + + ], + "resources":[ + + ], + "requestInputs":{ + + } + } + } + ], + "requestInputs":{ + "sdwanvpnresource_list":[ + { + "sdwanvpn_topology":"hub_spoke", + "sdwanvpn_name":"defaultvpn", + "sdwansitelan_list":[ + { + "role":"Hub", + "portType":"GE", + "portSwitch":"layer3-port", + "vlanId":"", + "ipAddress":"192.168.10.1", + "deviceName":"vCPE", + "portNumer":"0/0/1" + }, + { + "role":"Hub", + "portType":"GE", + "portSwitch":"layer2-port", + "vlanId":"55", + "ipAddress":"192.168.11.1", + "deviceName":"CPE_Beijing", + "portNumer":"0/0/1" + } + ] + } + ], + "sdwansiteresource_list":[ + { + "sdwansite_emails":"chenchuanyu@huawei.com", + "sdwansite_address":"Huawei Public Cloud", + "sdwansite_description":"DC Site", + "sdwansite_role":"dsvpn_hub", + "sdwansite_postcode":"20000", + "sdwansite_type":"single_gateway", + "sdwansite_latitude":"", + "sdwansite_controlPoint":"", + "sdwansite_longitude":"", + "sdwansitewan_list":[ + { + "providerIpAddress":"", + "portType":"GE", + "inputBandwidth":"1000", + "ipAddress":"", + "name":"10000", + "transportNetworkName":"internet", + "outputBandwidth":"10000", + "deviceName":"vCPE", + "portNumber":"0/0/0", + "ipMode":"DHCP", + "publicIP":"119.3.7.113" + } + ], + "sdwandevice_list":[ + { + "esn":"XXXXXXX", + "vendor":"Huawei", + "name":"vCPE", + "type":"AR1000V", + "version":"1.0", + "class":"VNF", + "systemIp":"20.20.20.1" + } + ] + }, + { + "sdwansite_emails":"chenchuanyu@huawei.com", + "sdwansite_address":"Huawei Public Cloud", + "sdwansite_description":"DC Site", + "sdwansite_role":"dsvpn_hub", + "sdwansite_postcode":"20000", + "sdwansite_type":"single_gateway", + "sdwansite_latitude":"", + "sdwansite_controlPoint":"", + "sdwansite_longitude":"", + "sdwansitewan_list":[ + { + "providerIpAddress":"", + "portType":"GE", + "inputBandwidth":"1000", + "ipAddress":"172.18.1.2/24", + "name":"10000", + "transportNetworkName":"internet", + "outputBandwidth":"10000", + "deviceName":"CPE_Beijing", + "portNumber":"0/0/0", + "ipMode":"Static", + "publicIP":"" + } + ], + "sdwandevice_list":[ + { + "esn":"XXXXXXX", + "vendor":"Huawei", + "name":"CPE_Beijing", + "type":"AR161", + "version":"1.0", + "class":"PNF", + "systemIp":"20.20.20.2" + } + ] + } + ] + } + } + } +}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/SERVICE-SO-REQ-INPUT.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/SERVICE-SO-REQ-INPUT.json new file mode 100644 index 0000000000..938b45e5a4 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/SERVICE-SO-REQ-INPUT.json @@ -0,0 +1,206 @@ +{ + "serviceResources": { + "modelInfo": { + "modelName": "demoVFWCL", + "modelUuid": "c3954379-4efe-431c-8258-f84905b158e5", + "modelInvariantUuid": "0cbff61e-3b0a-4eed-97ce-b1b4faa03493", + "modelVersion": "1.0" + }, + "serviceType": "", + "serviceRole": "", + "environmentContext": null, + "resourceOrder": "res1,res2", + "workloadContext": "Production", + "serviceVnfs": [ + + { + "modelInfo": { + "modelName": "15968a6e-2fe5-41bf-a481", + "modelUuid": "808abda3-2023-4105-92d2-e62644b61d53", + "modelInvariantUuid": "6e4ffc7c-497e-4a77-970d-af966e642d31", + "modelVersion": "1.0", + "modelCustomizationUuid": "a00404d5-d7eb-4c46-b6b6-9cf2d087e545", + "modelInstanceName": "15968a6e-2fe5-41bf-a481 0" + }, + "toscaNodeType": "org.openecomp.resource.vf.15968a6e2fe541bfA481", + "nfFunction": null, + "resourceInput": "{\"a\":\"b\",\"topology\":\"[sdwanvpnresource_list,INDEX,sdwanvpn_topology]|default_topo\",\"name\":\"[sdwanvpnresource_list,INDEX,sdwanvpn_name]|default_name\",\"sitelist\":\"[sdwanvpnresource_list,INDEX,sdwansitelan_list]|default_sitelist\"}", + "nfType": null, + "nfRole": null, + "nfNamingCode": null, + "multiStageDesign": "false", + "vfModules": [{ + "modelInfo": { + "modelName": "15968a6e2fe541bfA481..base_vfw..module-0", + "modelUuid": "ec7fadde-1e5a-42f7-8255-cb19e475ff45", + "modelInvariantUuid": "61ab8b64-a014-4cf3-8a5a-b5ef388f8819", + "modelVersion": "1", + "modelCustomizationUuid": "123aff6b-854f-4026-ae1e-cc74a3924576" + }, + "isBase": true, + "vfModuleLabel": "base_vfw", + "initialCount": 1, + "hasVolumeGroup": true + }] + }, + + { + "modelInfo": { + "modelName": "f971106a-248f-4202-9d1f", + "modelUuid": "4fbc08a4-35ed-4a59-9e47-79975e4add7e", + "modelInvariantUuid": "c669799e-adf1-46ae-8c70-48b326fe89f3", + "modelVersion": "1.0", + "modelCustomizationUuid": "e776449e-2b10-45c5-9217-2775c88ca1a0", + "modelInstanceName": "f971106a-248f-4202-9d1f 0" + }, + "toscaNodeType": "org.openecomp.resource.vfc.F971106a248f42029d1f", + "nfFunction": null, + "nfType": null, + "nfRole": null, + "resourceInput": "{\"a\":\"b|\",\"portswitch\":\"[sdwansitelan_list,INDEX,portSwitch]|default_portswitch\",\"ipAddress\":\"[sdwansitelan_list,INDEX,ipAddress]|default_ipAddress\",\"deviceName\":\"[sdwansitelan_list,INDEX,deviceName]|default_deviceName\"}", + "nfNamingCode": null, + "multiStageDesign": "false", + "vfModules": [{ + "modelInfo": { + "modelName": "F971106a248f42029d1f..base_vpkg..module-0", + "modelUuid": "47d5273a-7456-4786-9035-b3911944cc35", + "modelInvariantUuid": "0ea3e57e-ac7a-425a-928b-b4aee8806c15", + "modelVersion": "1", + "modelCustomizationUuid": "9ed9fef6-d3f8-4433-9807-7e23393a16bc" + }, + "isBase": true, + "vfModuleLabel": "base_vpkg", + "initialCount": 1, + "hasVolumeGroup": true + }] + }, + + { + "modelInfo": { + "modelName": "f971106a-248f-4202-9d1e", + "modelUuid": "4fbc08a4-35ed-4a59-9e47-79975e4add7d", + "modelInvariantUuid": "c669799e-adf1-46ae-8c70-48b326fe89f2", + "modelVersion": "1.0", + "modelCustomizationUuid": "e776449e-2b10-45c5-9217-2775c88ca1a1", + "modelInstanceName": "f971106a-248f-4202-9d1e 0" + }, + "toscaNodeType": "org.openecomp.resource.vfc.F971106a248f42029d1f", + "nfFunction": null, + "nfType": null, + "nfRole": null, + "resourceInput": "{\"a\":\"b|\",\"portswitch\":\"[sdwansitelan_list,INDEX,portSwitch]|default_portswitch\",\"ipAddress\":\"[sdwansitelan_list,INDEX,ipAddress]|default_ipAddress\",\"deviceName\":\"[sdwansitelan_list,INDEX,deviceName]|default_deviceName\"}", + "nfNamingCode": null, + "multiStageDesign": "false", + "vfModules": [{ + "modelInfo": { + "modelName": "F971106a248f42029d1f..base_vpkg..module-0", + "modelUuid": "47d5273a-7456-4786-9035-b3911944cc35", + "modelInvariantUuid": "0ea3e57e-ac7a-425a-928b-b4aee8806c15", + "modelVersion": "1", + "modelCustomizationUuid": "9ed9fef6-d3f8-4433-9807-7e23393a16bc" + }, + "isBase": true, + "vfModuleLabel": "base_vpkg", + "initialCount": 1, + "hasVolumeGroup": true + }] + }, + + { + "modelInfo": { + "modelName": "f971106a-248f-4202-9d2e", + "modelUuid": "4fbc08a4-35ed-4a59-9e47-79975e4add8d", + "modelInvariantUuid": "c669799e-adf1-46ae-8c70-48b326fe89c2", + "modelVersion": "1.0", + "modelCustomizationUuid": "e776449e-2b10-45c5-9217-2775c88ca1c1", + "modelInstanceName": "f971106a-248f-4202-9d2e 0" + }, + "toscaNodeType": "org.openecomp.resource.vf.F971106a248f42029d1f", + "nfFunction": null, + "nfType": null, + "nfRole": null, + "resourceInput": "{\"address\":\"[sdwansiteresource_list,INDEX,sdwansite_address]|default_address\",\"role\":\"[sdwansiteresource_list,INDEX,sdwansite_role]|default_role\",\"wanlist\":\"[sdwansiteresource_list,INDEX,sdwansitewan_list]|default_wanlist\",\"devlist\":\"[sdwansiteresource_list,INDEX,sdwandevice_list]|default_devlist\"}", + "nfNamingCode": null, + "multiStageDesign": "false", + "vfModules": [{ + "modelInfo": { + "modelName": "F971106a248f42029d1f..base_vpkg..module-0", + "modelUuid": "47d5273a-7456-4786-9035-b3911944cc35", + "modelInvariantUuid": "0ea3e57e-ac7a-425a-928b-b4aee8806c15", + "modelVersion": "1", + "modelCustomizationUuid": "9ed9fef6-d3f8-4433-9807-7e23393a16bc" + }, + "isBase": true, + "vfModuleLabel": "base_vpkg", + "initialCount": 1, + "hasVolumeGroup": true + }] + }, + + { + "modelInfo": { + "modelName": "f971106a-248f-4202-9d3e", + "modelUuid": "4fbc08a4-35ed-4a59-9e47-79975e4add9d", + "modelInvariantUuid": "c669799e-adf1-46ae-8c70-48b326fe89f3", + "modelVersion": "1.0", + "modelCustomizationUuid": "e776449e-2b10-45c5-9217-2775c88cb1a1", + "modelInstanceName": "f971106a-248f-4202-9d3e 0" + }, + "toscaNodeType": "org.openecomp.resource.vfc.F971106a248f42029d1f", + "nfFunction": null, + "nfType": null, + "nfRole": null, + "resourceInput": "{\"address\":\"sdwansite_address|default_address\", \"postcode\":\"sdwansite_postcode|default_postcode\",\"type\":\"sdwansite_type|default_role\",\"deviceName\":\"[sdwansitewan_list,INDEX,deviceName]|default_deviceName\",\"systemip\":\"[sdwandevice_list,INDEX,systemIp]|default_systemip\", \"systemipv6\":\"[sdwandevice_list,INDEX,systemIpv6]|default_ipv6\"}", + "nfNamingCode": null, + "multiStageDesign": "false", + "vfModules": [{ + "modelInfo": { + "modelName": "F971106a248f42029d1f..base_vpkg..module-0", + "modelUuid": "47d5273a-7456-4786-9035-b3911944cc35", + "modelInvariantUuid": "0ea3e57e-ac7a-425a-928b-b4aee8806c15", + "modelVersion": "1", + "modelCustomizationUuid": "9ed9fef6-d3f8-4433-9807-7e23393a16bc" + }, + "isBase": true, + "vfModuleLabel": "base_vpkg", + "initialCount": 1, + "hasVolumeGroup": true + }] + }, + + { + "modelInfo": { + "modelName": "f971106a-248f-4202-9d5e", + "modelUuid": "4fbc08a4-35ed-4a59-9e47-79975e4add3d", + "modelInvariantUuid": "c669799e-adf1-46ae-8c70-48b326fe8393", + "modelVersion": "1.0", + "modelCustomizationUuid": "e776449e-2b10-45c5-9217-2775c88cb1f1", + "modelInstanceName": "f971106a-248f-4202-9d5e 0" + }, + "toscaNodeType": "org.openecomp.resource.vfc.F971106a248f42029d3f", + "nfFunction": null, + "nfType": null, + "nfRole": null, + "resourceInput": "{\"address\":\"sdwansite_address|default_address\", \"postcode\":\"sdwansite_postcode|default_postcode\",\"type\":\"sdwansite_type|default_role\",\"deviceName\":\"[sdwansitewan_list,INDEX,deviceName]|default_deviceName\",\"systemip\":\"[sdwandevice_list,INDEX,systemIp]|default_systemip\"}", + "nfNamingCode": null, + "multiStageDesign": "false", + "vfModules": [{ + "modelInfo": { + "modelName": "F971106a248f42029d1f..base_vpkg..module-0", + "modelUuid": "47d5273a-7456-4786-9035-b3911944cc35", + "modelInvariantUuid": "0ea3e57e-ac7a-425a-928b-b4aee8806c15", + "modelVersion": "1", + "modelCustomizationUuid": "9ed9fef6-d3f8-4433-9807-7e23393a16bc" + }, + "isBase": true, + "vfModuleLabel": "base_vpkg", + "initialCount": 1, + "hasVolumeGroup": true + }] + } + + ], + "serviceNetworks": [], + "serviceAllottedResources": [] + } +}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/UUI-SO-REQ.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/UUI-SO-REQ.json new file mode 100644 index 0000000000..e6161862ae --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/UUI-SO-REQ.json @@ -0,0 +1 @@ +{
"sdwanvpnresource_list":[
{
"sdwanvpn_topology":"hub_spoke",
"sdwanvpn_name":"defaultvpn",
"sdwansitelan_list":[
{
"role":"Hub",
"portType":"GE",
"portSwitch":"layer3-port",
"vlanId":"",
"ipAddress":"192.168.10.1",
"deviceName":"vCPE",
"portNumer":"0/0/1"
},
{
"role":"Hub",
"portType":"GE",
"portSwitch":"layer2-port",
"vlanId":"55",
"ipAddress":"192.168.11.1",
"deviceName":"CPE_Beijing",
"portNumer":"0/0/1"
}
]
}
],
"sdwansiteresource_list":[
{
"sdwansite_emails":"chenchuanyu@huawei.com",
"sdwansite_address":"Huawei Private Cloud",
"sdwansite_description":"DC Site",
"sdwansite_role":"dsvpn_hub1",
"sdwansite_postcode":"20000",
"sdwansite_type":"single_gateway",
"sdwansite_latitude":"",
"sdwansite_controlPoint":"",
"sdwansite_longitude":"",
"sdwansitewan_list":[
{
"providerIpAddress":"",
"portType":"GE",
"inputBandwidth":"1000",
"ipAddress":"",
"name":"10000",
"transportNetworkName":"internet",
"outputBandwidth":"10000",
"deviceName":"vCPE",
"portNumber":"0/0/0",
"ipMode":"DHCP",
"publicIP":"119.3.7.113"
}
],
"sdwandevice_list":[
{
"esn":"XXXXXXX",
"vendor":"Huawei",
"name":"vCPE",
"type":"AR1000V",
"version":"1.0",
"class":"VNF",
"systemIp":"20.20.20.1"
}
]
},
{
"sdwansite_emails":"chenchuanyu@huawei.com",
"sdwansite_address":"Huawei Public Cloud",
"sdwansite_description":"DC Site",
"sdwansite_role":"dsvpn_hub",
"sdwansite_postcode":"20001",
"sdwansite_type":"multiple_gateway",
"sdwansite_latitude":"",
"sdwansite_controlPoint":"",
"sdwansite_longitude":"",
"sdwansitewan_list":[
{
"providerIpAddress":"",
"portType":"GE",
"inputBandwidth":"1000",
"ipAddress":"172.18.1.2/24",
"name":"10000",
"transportNetworkName":"internet",
"outputBandwidth":"10000",
"deviceName":"CPE_Beijing",
"portNumber":"0/0/0",
"ipMode":"Static",
"publicIP":""
}
],
"sdwandevice_list":[
{
"esn":"XXXXXXX",
"vendor":"Huawei",
"name":"CPE_Beijing",
"type":"AR161",
"version":"1.0",
"class":"PNF",
"systemIp":"20.20.20.2"
}
]
}
]
}
\ No newline at end of file diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/ResponseBuilder.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/ResponseBuilder.java index a3f5253765..6f8d34e760 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/ResponseBuilder.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/ResponseBuilder.java @@ -40,6 +40,7 @@ import org.slf4j.LoggerFactory; */ public class ResponseBuilder implements java.io.Serializable { private static final long serialVersionUID = 1L; + private static final String WORKFLOWEXCEPTION = "WorkflowException"; private static final Logger logger = LoggerFactory.getLogger(ResponseBuilder.class); /** @@ -61,7 +62,7 @@ public class ResponseBuilder implements java.io.Serializable { logger.debug("processKey=" + processKey); // See if there"s already a WorkflowException object in the execution. - WorkflowException theException = (WorkflowException) execution.getVariable("WorkflowException"); + WorkflowException theException = (WorkflowException) execution.getVariable(WORKFLOWEXCEPTION); if (theException != null) { logger.debug("Exited " + method + " - propagated " + theException); @@ -138,7 +139,7 @@ public class ResponseBuilder implements java.io.Serializable { // Create a new WorkflowException object theException = new WorkflowException(processKey, intResponseCode, errorResponse); - execution.setVariable("WorkflowException", theException); + execution.setVariable(WORKFLOWEXCEPTION, theException); logger.debug("Exited " + method + " - created " + theException); return theException; } @@ -163,7 +164,7 @@ public class ResponseBuilder implements java.io.Serializable { Object theResponse = null; - WorkflowException theException = (WorkflowException) execution.getVariable("WorkflowException"); + WorkflowException theException = (WorkflowException) execution.getVariable(WORKFLOWEXCEPTION); String errorResponse = trimString(execution.getVariable(prefix + "ErrorResponse"), null); String responseCode = trimString(execution.getVariable(prefix + "ResponseCode"), null); @@ -222,7 +223,7 @@ public class ResponseBuilder implements java.io.Serializable { } String s = String.valueOf(object).trim(); - return s.equals("") ? emptyStringValue : s; + return "".equals(s) ? emptyStringValue : s; } /** diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/AllottedResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/AllottedResource.java index 841eaee675..c37b77d332 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/AllottedResource.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/AllottedResource.java @@ -22,7 +22,6 @@ package org.onap.so.bpmn.core.domain; import java.util.UUID; import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonRootName; /** @@ -35,14 +34,6 @@ public class AllottedResource extends Resource { private static final long serialVersionUID = 1L; /* - * set resourceType for this object - */ - public AllottedResource() { - resourceType = ResourceType.ALLOTTED_RESOURCE; - setResourceId(UUID.randomUUID().toString()); - } - - /* * fields specific to Allotted Resource resource type */ private String allottedResourceType; @@ -60,6 +51,14 @@ public class AllottedResource extends Resource { private String resourceInput; /* + * set resourceType for this object + */ + public AllottedResource() { + resourceType = ResourceType.ALLOTTED_RESOURCE; + setResourceId(UUID.randomUUID().toString()); + } + + /* * GET and SET */ public String getAllottedResourceType() { diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/GroupResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/GroupResource.java new file mode 100644 index 0000000000..79714d0f0e --- /dev/null +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/GroupResource.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.bpmn.core.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.UUID; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class GroupResource extends Resource { + private static final long serialVersionUID = 1L; + + @JsonProperty("vnfcs") + private List<VnfcResource> vnfcs; + + public GroupResource() { + resourceType = ResourceType.GROUP; + setResourceId(UUID.randomUUID().toString()); + } + + public List<VnfcResource> getVnfcs() { + return vnfcs; + } + + public void setVnfcs(List<VnfcResource> vnfcs) { + this.vnfcs = vnfcs; + } +} diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/HomingSolution.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/HomingSolution.java index 897cbe3573..309b053589 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/HomingSolution.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/HomingSolution.java @@ -21,7 +21,6 @@ package org.onap.so.bpmn.core.domain; import java.io.Serializable; -import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonRootName; diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/JsonWrapper.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/JsonWrapper.java index 602172f8a4..bf53c880e9 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/JsonWrapper.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/JsonWrapper.java @@ -45,6 +45,7 @@ import org.slf4j.LoggerFactory; */ @JsonInclude(Include.NON_NULL) public abstract class JsonWrapper implements Serializable { + private static final String EXCEPTION = "Exception :"; private static final Logger logger = LoggerFactory.getLogger(JsonWrapper.class); @@ -63,7 +64,7 @@ public abstract class JsonWrapper implements Serializable { jsonString = ow.writeValueAsString(this); } catch (Exception e) { - logger.debug("Exception :", e); + logger.debug(EXCEPTION, e); } return jsonString; } @@ -76,14 +77,10 @@ public abstract class JsonWrapper implements Serializable { JSONObject json = new JSONObject(); try { json = new JSONObject(mapper.writeValueAsString(this)); - } catch (JsonGenerationException e) { - logger.debug("Exception :", e); - } catch (JsonMappingException e) { - logger.debug("Exception :", e); - } catch (JSONException e) { - logger.debug("Exception :", e); + } catch (JsonGenerationException | JsonMappingException | JSONException e) { + logger.debug(EXCEPTION, e); } catch (IOException e) { - logger.debug("Exception :", e); + logger.debug(EXCEPTION, e); } return json; } @@ -95,12 +92,10 @@ public abstract class JsonWrapper implements Serializable { String jsonString = ""; try { jsonString = mapper.writeValueAsString(list); - } catch (JsonGenerationException e) { - logger.debug("Exception :", e); - } catch (JsonMappingException e) { - logger.debug("Exception :", e); + } catch (JsonGenerationException | JsonMappingException e) { + logger.debug(EXCEPTION, e); } catch (IOException e) { - logger.debug("Exception :", e); + logger.debug(EXCEPTION, e); } return jsonString; } @@ -118,7 +113,7 @@ public abstract class JsonWrapper implements Serializable { jsonString = ow.writeValueAsString(this); } catch (Exception e) { - logger.debug("Exception :", e); + logger.debug(EXCEPTION, e); } return jsonString; } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceType.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceType.java index a30d0df825..0e17d4c826 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceType.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ResourceType.java @@ -22,5 +22,5 @@ package org.onap.so.bpmn.core.domain; public enum ResourceType { - VNF, NETWORK, MODULE, ALLOTTED_RESOURCE, CONFIGURATION // etc. + VNF, NETWORK, MODULE, ALLOTTED_RESOURCE, CONFIGURATION, GROUP, VNFC // etc. } 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 419f545cdf..b3439d58e3 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 @@ -245,7 +245,7 @@ public class ServiceDecomposition extends JsonWrapper implements Serializable { */ @JsonIgnore public List<Resource> getServiceResources() { - ArrayList serviceResources = new ArrayList(); + ArrayList<Resource> serviceResources = new ArrayList(); if (this.getAllottedResources() != null) { serviceResources.addAll(this.getAllottedResources()); } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfResource.java index f66ad36058..9688a57630 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfResource.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfResource.java @@ -32,6 +32,7 @@ import com.fasterxml.jackson.annotation.JsonRootName; * Encapsulates VNF resource data set * */ +@JsonIgnoreProperties(ignoreUnknown = true) @JsonRootName("vnfResource") public class VnfResource extends Resource { @@ -50,6 +51,13 @@ public class VnfResource extends Resource { */ @JsonProperty("vfModules") private List<ModuleResource> vfModules; + + @JsonProperty("groups") + private List<GroupResource> groups; + + @JsonProperty("vnfcInstGroupOrder") + private String groupOrder; + private String vnfHostname; private String vnfType; private String nfFunction; @@ -59,7 +67,7 @@ public class VnfResource extends Resource { private String multiStageDesign; private String orchestrationStatus; - @JsonIgnore + @JsonProperty("resourceInput") private String resourceInput; /* @@ -150,6 +158,22 @@ public class VnfResource extends Resource { this.resourceInput = resourceInput; } + public List<GroupResource> getGroups() { + return groups; + } + + public void setGroups(List<GroupResource> groups) { + this.groups = groups; + } + + public String getGroupOrder() { + return groupOrder; + } + + public void setGroupOrder(String groupOrder) { + this.groupOrder = groupOrder; + } + /** * Returns a list of all VfModule objects. Base module is first entry in the list * diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfcResource.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfcResource.java new file mode 100644 index 0000000000..50bd3e2355 --- /dev/null +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/VnfcResource.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.bpmn.core.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.UUID; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class VnfcResource extends Resource { + private static final long serialVersionUID = 1L; + + @JsonProperty("resourceInput") + private String resourceInput; + + public VnfcResource() { + resourceType = ResourceType.VNFC; + setResourceId(UUID.randomUUID().toString()); + } + + public String getResourceInput() { + return resourceInput; + } + + public void setResourceInput(String resourceInput) { + this.resourceInput = resourceInput; + } +} diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceDecompositionTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceDecompositionTest.java index 5db277628e..7ef7deea30 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceDecompositionTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/ServiceDecompositionTest.java @@ -52,6 +52,22 @@ public class ServiceDecompositionTest { configResource.setResourceId("configResourceId"); } + + @Test + public void serviceDecompositionWithGroupandVnfc() throws IOException { + String sericeStr = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "ServiceWithGroupandVnfc.json"))); + ServiceDecomposition serviceDecomposition = new ServiceDecomposition(sericeStr); + + assertEquals(1, serviceDecomposition.getVnfResources().size()); + assertEquals(1, serviceDecomposition.getVnfResources().get(0).getGroups().size()); + assertEquals(1, serviceDecomposition.getVnfResources().get(0).getGroups().get(0).getVnfcs().size()); + + VnfcResource vnfcResource = serviceDecomposition.getVnfResources().get(0).getGroups().get(0).getVnfcs().get(0); + + assertEquals("xfs", vnfcResource.getModelInfo().getModelName()); + assertEquals("22", vnfcResource.getModelInfo().getModelUuid()); + } + @Test public void serviceDecompositionTest() throws JsonProcessingException, IOException { // covering methods not covered by openpojo test diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/VnfResourceTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/VnfResourceTest.java index 09bcfe8470..de7b21ed73 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/VnfResourceTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/domain/VnfResourceTest.java @@ -14,12 +14,13 @@ */ package org.onap.so.bpmn.core.domain; -import static org.junit.Assert.*; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class VnfResourceTest { @@ -58,6 +59,19 @@ public class VnfResourceTest { VnfResource vnfResource = objectMapper.readValue(jsonStr, VnfResource.class); assertTrue(vnfResource != null); + assertEquals("sample", vnfResource.getResourceInput()); + assertEquals("home", vnfResource.getVnfHostname()); + } + + @Test + public void vnfResourceMapperTestNoResourceInput() throws IOException { + String jsonStr = "{\"vnfHostname\": \"home\"}"; + ObjectMapper objectMapper = new ObjectMapper(); + VnfResource vnfResource = objectMapper.readValue(jsonStr, VnfResource.class); + + assertTrue(vnfResource != null); + assertEquals(null, vnfResource.getResourceInput()); + assertEquals("home", vnfResource.getVnfHostname()); } @Test diff --git a/bpmn/MSOCoreBPMN/src/test/resources/json-examples/ServiceWithGroupandVnfc.json b/bpmn/MSOCoreBPMN/src/test/resources/json-examples/ServiceWithGroupandVnfc.json new file mode 100644 index 0000000000..9d0326e66a --- /dev/null +++ b/bpmn/MSOCoreBPMN/src/test/resources/json-examples/ServiceWithGroupandVnfc.json @@ -0,0 +1,58 @@ +{ + "serviceResources": { + "modelInfo": { + "modelName": "NSService", + "modelUuid": "0bad8c92-7d22-49f0-b092-b64e6ca564a7", + "modelInvariantUuid": "69161960-515b-4bf3-91f1-313b813f5e1d", + "modelVersion": "1.0" + }, + "serviceType": "", + "serviceRole": "", + "environmentContext": "General_Revenue-Bearing", + "resourceOrder": "NF", + "workloadContext": "Production", + "serviceVnfs": [ + { + "modelInfo": { + "modelName": "", + "modelUuid": "123", + "modelInvariantUuid": "", + "modelVersion": "", + "modelCustomizationUuid": "1234", + "modelInstanceName": "test" + }, + "toscaNodeType": "", + "nfFunction": "", + "nfType": "", + "nfRole": "", + "nfNamingCode": "", + "multiStageDesign": "", + "resourceInput": "", + "vfModules": [], + "groups": [ + { + "modelInfo": { + "modelName": "test", + "modelUuid": "11", + "modelInvariantUuid": "11", + "modelVersion": "2" + }, + "vnfcs": [ + { + "modelInfo": { + "modelName": "xfs", + "modelUuid": "22", + "modelInvariantUuid": "2222", + "modelVersion": "22222", + "modelCustomizationUuid": "2222" + } + } + ] + } + ] + } + ], + "serviceNetworks": [], + "serviceAllottedResources": [] + } +}
\ No newline at end of file diff --git a/bpmn/mso-infrastructure-bpmn/pom.xml b/bpmn/mso-infrastructure-bpmn/pom.xml index 4dd7a467ea..e9ed15aa0f 100644 --- a/bpmn/mso-infrastructure-bpmn/pom.xml +++ b/bpmn/mso-infrastructure-bpmn/pom.xml @@ -152,12 +152,12 @@ <groupId>org.camunda.bpm.springboot</groupId> <artifactId>camunda-bpm-spring-boot-starter-rest</artifactId> <version>${camunda.springboot.version}</version> - <exclusions> - <exclusion> - <groupId>org.camunda.bpmn</groupId> - <artifactId>camunda-engine-rest-core</artifactId> - </exclusion> - </exclusions> + <exclusions> + <exclusion> + <groupId>org.camunda.bpmn</groupId> + <artifactId>camunda-engine-rest-core</artifactId> + </exclusion> + </exclusions> </dependency> <dependency> <groupId>org.camunda.bpm.springboot</groupId> diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/DeleteVnfNotification.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/DeleteVnfNotification.java index cd4257ec60..e0760b5d4a 100644 --- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/DeleteVnfNotification.java +++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/common/adapter/vnf/DeleteVnfNotification.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 @@ -160,12 +162,4 @@ public class DeleteVnfNotification { return deleteVnfNotification; } - /* - * public String toString() { StringWriter writer = new StringWriter(); try { JAXBContext context = JAXBContext - * .newInstance(DeleteVnfNotification.class); Marshaller m = context.createMarshaller(); - * m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.marshal(this, writer); - * //System.out.println("toString() - " + writer.getBuffer().toString()); return writer.getBuffer().toString(); } - * catch (JAXBException e) { //System.out.println("JAXBException - " + e.getStackTrace()); return ""; } } - */ - } diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateAndActivatePnfResourceTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateAndActivatePnfResourceTest.java index 3734510eed..3ff240ebc2 100644 --- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateAndActivatePnfResourceTest.java +++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateAndActivatePnfResourceTest.java @@ -34,6 +34,8 @@ import org.camunda.bpm.engine.runtime.ProcessInstance; import org.junit.Before; import org.junit.Test; import org.onap.so.BaseIntegrationTest; +import org.onap.so.bpmn.common.recipe.ResourceInput; +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder; import org.springframework.beans.factory.annotation.Autowired; public class CreateAndActivatePnfResourceTest extends BaseIntegrationTest { @@ -61,6 +63,7 @@ public class CreateAndActivatePnfResourceTest extends BaseIntegrationTest { public void shouldWaitForMessageFromDmaapAndUpdateAaiEntryWhenAaiEntryExists() { // given variables.put(PNF_CORRELATION_ID, PnfManagementTestImpl.ID_WITH_ENTRY); + variables.put("resourceInput", getUpdateResInputObj("OLT").toString()); // when ProcessInstance instance = runtimeService.startProcessInstanceByKey("CreateAndActivatePnfResource", "businessKey", variables); @@ -79,6 +82,7 @@ public class CreateAndActivatePnfResourceTest extends BaseIntegrationTest { public void shouldCreateAaiEntryWaitForMessageFromDmaapAndUpdateAaiEntryWhenNoAaiEntryExists() { // given variables.put(PNF_CORRELATION_ID, PnfManagementTestImpl.ID_WITHOUT_ENTRY); + variables.put("resourceInput", getUpdateResInputObj("OLT").toString()); // when ProcessInstance instance = runtimeService.startProcessInstanceByKey("CreateAndActivatePnfResource", "businessKey", variables); @@ -93,4 +97,31 @@ public class CreateAndActivatePnfResourceTest extends BaseIntegrationTest { Assertions.assertThat(pnfManagementTest.getServiceAndPnfRelationMap()) .containsOnly(MapEntry.entry(SERVICE_INSTANCE_ID, PnfManagementTestImpl.ID_WITHOUT_ENTRY)); } + + private ResourceInput getUpdateResInputObj(String modelName) { + + String resourceInput = "{\n" + "\t\"resourceInstanceName\": \"SotnFc-wan-connection_wanconnection-37\",\n" + + "\t\"resourceInstanceDes\": null,\n" + "\t\"globalSubscriberId\": \"sdwandemo\",\n" + + "\t\"serviceType\": \"CCVPN\",\n" + "\t\"operationId\": \"df3387b5-4fbf-41bd-82a0-13a955ac178a\",\n" + + "\t\"serviceModelInfo\": {\n" + "\t\t\"modelName\": \"WanConnectionSvc03\",\n" + + "\t\t\"modelUuid\": \"198b066c-0771-4157-9594-1824adfdda7e\",\n" + + "\t\t\"modelInvariantUuid\": \"43fb5165-7d03-4009-8951-a8f45d3f0148\",\n" + + "\t\t\"modelVersion\": \"1.0\",\n" + "\t\t\"modelCustomizationUuid\": \"\",\n" + + "\t\t\"modelCustomizationName\": \"\",\n" + "\t\t\"modelInstanceName\": \"\",\n" + + "\t\t\"modelType\": \"\"\n" + "\t},\n" + "\t\"resourceModelInfo\": {\n" + "\t\t\"modelName\": \"" + + modelName + "\",\n" + "\t\t\"modelUuid\": \"6a0bf88b-343c-415b-88c1-6f73702452c4\",\n" + + "\t\t\"modelInvariantUuid\": \"50bc3415-2e01-4e50-a9e1-ec9584599bb3\",\n" + + "\t\t\"modelCustomizationUuid\": \"b205d620-84bd-4058-afa0-e3aeee8bb712\",\n" + + "\t\t\"modelCustomizationName\": \"\",\n" + + "\t\t\"modelInstanceName\": \"SotnFc-wan-connection 0\",\n" + "\t\t\"modelType\": \"\"\n" + "\t},\n" + + "\t\"resourceInstancenUuid\": null,\n" + + "\t\"resourceParameters\": \"{\\n\\\"locationConstraints\\\":[],\\n\\\"requestInputs\\\":{\\\"sotnfcspecwanconnection0_route-objective-function\\\":null,\\\"sotnfcspecwanconnection0_colorAware\\\":null,\\\"3rdctlspecwanconnection0_thirdPartyAdaptorRpc\\\":null,\\\"sotnfcspecwanconnection0_couplingFlag\\\":null,\\\"sotnfcspecwanconnection0_pbs\\\":null,\\\"3rdctlspecwanconnection0_thirdPartySdncId\\\":null,\\\"sotnfcspecwanconnection0_cbs\\\":null,\\\"3rdctlspecwanconnection0_thirdpartySdncName\\\":null,\\\"sotnfcspecwanconnection0_total-size\\\":null,\\\"3rdctlspecwanconnection0_templateFileName\\\":\\\"sotn_create_zte_template.json\\\",\\\"fcwanconnection0_type\\\":null,\\\"sotnfcspecwanconnection0_cir\\\":null,\\\"fcwanconnection0_uuid\\\":null,\\\"sotnfcspecwanconnection0_diversity-policy\\\":null,\\\"nf_naming\\\":true,\\\"multi_stage_design\\\":false,\\\"availability_zone_max_count\\\":1,\\\"3rdctlspecwanconnection0_restapiUrl\\\":\\\"http://10.80.80.21:8443/restconf/operations/ZTE-API-ConnectivityService:create-connectivity-service\\\",\\\"max_instances\\\":null,\\\"sotnfcspecwanconnection0_reroute\\\":null,\\\"fcwanconnection0_name\\\":null,\\\"sotnfcspecwanconnection0_dualLink\\\":null,\\\"min_instances\\\":null,\\\"sotnfcspecwanconnection0_pir\\\":null,\\\"sotnfcspecwanconnection0_service-type\\\":null}\\n}\",\n" + + "\t\"operationType\": \"createInstance\",\n" + + "\t\"serviceInstanceId\": \"ffa07ae4-f820-45af-9439-1416b3bc1d39\",\n" + + "\t\"requestsInputs\": \"{\\r\\n\\t\\\"service\\\": {\\r\\n\\t\\t\\\"name\\\": \\\"wanconnection-37\\\",\\r\\n\\t\\t\\\"description\\\": \\\"deafe\\\",\\r\\n\\t\\t\\\"serviceInvariantUuid\\\": \\\"43fb5165-7d03-4009-8951-a8f45d3f0148\\\",\\r\\n\\t\\t\\\"serviceUuid\\\": \\\"198b066c-0771-4157-9594-1824adfdda7e\\\",\\r\\n\\t\\t\\\"globalSubscriberId\\\": \\\"sdwandemo\\\",\\r\\n\\t\\t\\\"serviceType\\\": \\\"CCVPN\\\",\\r\\n\\t\\t\\\"parameters\\\": {\\r\\n\\t\\t\\t\\\"resources\\\": [\\r\\n\\t\\t\\t],\\r\\n\\t\\t\\t\\\"requestInputs\\\": {\\r\\n\\t\\t\\t\\t\\\"sotnfcwanconnection0_3rdctlspecwanconnection0_restapiUrl\\\": \\\"http://10.80.80.21:8443/restconf/operations/ZTE-API-ConnectivityService:create-connectivity-service\\\",\\r\\n\\t\\t\\t\\t\\\"sotnfcwanconnection0_3rdctlspecwanconnection0_templateFileName\\\": \\\"sotn_create_zte_template.json\\\",\\r\\n\\t\\t\\t\\t\\\"sdwanfcwanconnection0_3rdctlspecwanconnection0_restapiUrl\\\": \\\"http://10.80.80.21:8443/restconf/operations/ZTE-API-ConnectivityService:create-connectivity-service\\\",\\r\\n\\t\\t\\t\\t\\\"sdwanfcwanconnection0_3rdctlspecwanconnection0_templateFileName\\\": \\\"sdwan_create_zte_template.json\\\",\\\"ont_ont_manufacturer\\\":\\\"huawei\\\",\\\"ont_ont_serial_num\\\":\\\"123\\\"\\r\\n\\t\\t\\t}\\r\\n\\t\\t}\\r\\n\\t}\\r\\n}\"\n" + + "}"; + + ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class); + return resourceInputObj; + } } diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/DmaapClientTestImpl.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/DmaapClientTestImpl.java index e7ff69ab3b..dd993bca51 100644 --- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/DmaapClientTestImpl.java +++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/DmaapClientTestImpl.java @@ -20,7 +20,9 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate; +import java.util.HashMap; import java.util.Objects; +import java.util.Optional; import org.onap.so.bpmn.infrastructure.pnf.dmaap.DmaapClient; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @@ -33,7 +35,8 @@ public class DmaapClientTestImpl implements DmaapClient { private Runnable informConsumer; @Override - public void registerForUpdate(String pnfCorrelationId, Runnable informConsumer) { + public void registerForUpdate(String pnfCorrelationId, Runnable informConsumer, + Optional<HashMap<String, String>> updateInfo) { this.pnfCorrelationId = pnfCorrelationId; this.informConsumer = informConsumer; } diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ActivateVfModuleBB.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ActivateVfModuleBB.bpmn index 289ab6e155..435d85d032 100644 --- a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ActivateVfModuleBB.bpmn +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ActivateVfModuleBB.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.7.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_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="1.10.0"> <bpmn:process id="ActivateVfModuleBB" name="ActivateVfModuleBB" isExecutable="true"> <bpmn:startEvent id="ActivateVfModuleBB_Start"> <bpmn:outgoing>SequenceFlow_0ieafii</bpmn:outgoing> @@ -9,9 +9,7 @@ <bpmn:incoming>SequenceFlow_0xsp0pv</bpmn:incoming> </bpmn:endEvent> <bpmn:serviceTask id="ActivateVfModule" name=" SDNC Activate (vf module) " camunda:expression="${SDNCActivateTasks.activateVfModule(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> - <bpmn:incoming>SequenceFlow_07ybdik</bpmn:incoming> - <bpmn:incoming>SequenceFlow_109oxx2</bpmn:incoming> - <bpmn:incoming>SequenceFlow_0arwo1o</bpmn:incoming> + <bpmn:incoming>SequenceFlow_1b63lv4</bpmn:incoming> <bpmn:outgoing>SequenceFlow_1a495wm</bpmn:outgoing> </bpmn:serviceTask> <bpmn:serviceTask id="UpdateVfModuleActiveStatus" name=" AAI Update (vf module) " camunda:expression="${AAIUpdateTasks.updateOrchestrationStatusActivateVfModule(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> @@ -40,13 +38,8 @@ <bpmn:incoming>SequenceFlow_0xndboi</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0ee42yq</bpmn:outgoing> </bpmn:serviceTask> - <bpmn:exclusiveGateway id="ExclusiveGateway_1v8bmbu" default="SequenceFlow_07ybdik"> - <bpmn:incoming>SequenceFlow_1xqyur9</bpmn:incoming> - <bpmn:outgoing>SequenceFlow_07ybdik</bpmn:outgoing> - <bpmn:outgoing>SequenceFlow_0ghzwlo</bpmn:outgoing> - </bpmn:exclusiveGateway> - <bpmn:sequenceFlow id="SequenceFlow_07ybdik" sourceRef="ExclusiveGateway_1v8bmbu" targetRef="ActivateVfModule" /> - <bpmn:sequenceFlow id="SequenceFlow_0ghzwlo" sourceRef="ExclusiveGateway_1v8bmbu" targetRef="Setup_AAI_Inventory_Audit"> + <bpmn:sequenceFlow id="SequenceFlow_07ybdik" name="No" sourceRef="ExclusiveGateway_1v8bmbu" targetRef="ExclusiveGateway_0sqvzll" /> + <bpmn:sequenceFlow id="SequenceFlow_0ghzwlo" name="Yes" sourceRef="ExclusiveGateway_1v8bmbu" targetRef="Setup_AAI_Inventory_Audit"> <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("auditInventoryNeeded") == true}]]></bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:sequenceFlow id="SequenceFlow_0ee42yq" sourceRef="Audit_AAI_Inventory" targetRef="ExclusiveGateway_1h8avxn" /> @@ -55,154 +48,252 @@ <bpmn:outgoing>SequenceFlow_1xqyur9</bpmn:outgoing> </bpmn:serviceTask> <bpmn:sequenceFlow id="SequenceFlow_1xqyur9" sourceRef="CheckAuditVariable" targetRef="ExclusiveGateway_1v8bmbu" /> - <bpmn:exclusiveGateway id="ExclusiveGateway_1h8avxn" default="SequenceFlow_1bo83qk"> - <bpmn:incoming>SequenceFlow_0ee42yq</bpmn:incoming> - <bpmn:outgoing>SequenceFlow_109oxx2</bpmn:outgoing> - <bpmn:outgoing>SequenceFlow_1bo83qk</bpmn:outgoing> - </bpmn:exclusiveGateway> - <bpmn:sequenceFlow id="SequenceFlow_109oxx2" sourceRef="ExclusiveGateway_1h8avxn" targetRef="ActivateVfModule"> + <bpmn:sequenceFlow id="SequenceFlow_109oxx2" name="No" sourceRef="ExclusiveGateway_1h8avxn" targetRef="ExclusiveGateway_0y0ek7t"> <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("auditIsSuccessful")== true }]]></bpmn:conditionExpression> </bpmn:sequenceFlow> - <bpmn:sequenceFlow id="SequenceFlow_1bo83qk" name="If Audit Fails" sourceRef="ExclusiveGateway_1h8avxn" targetRef="Create_AAI_Inventory" /> - <bpmn:sequenceFlow id="SequenceFlow_0arwo1o" sourceRef="Create_AAI_Inventory" targetRef="ActivateVfModule" /> + <bpmn:sequenceFlow id="SequenceFlow_1bo83qk" name="Yes" sourceRef="ExclusiveGateway_1h8avxn" targetRef="Create_AAI_Inventory" /> + <bpmn:sequenceFlow id="SequenceFlow_0arwo1o" sourceRef="Create_AAI_Inventory" targetRef="ExclusiveGateway_0y0ek7t" /> <bpmn:serviceTask id="Create_AAI_Inventory" name="Create A&AI Inventory" camunda:type="external" camunda:topic="InventoryCreate"> <bpmn:incoming>SequenceFlow_1bo83qk</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0arwo1o</bpmn:outgoing> </bpmn:serviceTask> + <bpmn:sequenceFlow id="SequenceFlow_1b63lv4" sourceRef="ExclusiveGateway_0sqvzll" targetRef="ActivateVfModule" /> + <bpmn:sequenceFlow id="SequenceFlow_18faffa" sourceRef="ExclusiveGateway_0y0ek7t" targetRef="ExclusiveGateway_0sqvzll" /> + <bpmn:subProcess id="SubProcess_0bpsptg" name="Audit Exception Sub Process" triggeredByEvent="true"> + <bpmn:startEvent id="catchInventoryException"> + <bpmn:outgoing>SequenceFlow_19gbhlj</bpmn:outgoing> + <bpmn:errorEventDefinition errorRef="Error_1s3kxze" /> + </bpmn:startEvent> + <bpmn:endEvent id="EndEvent_067jv1n"> + <bpmn:incoming>SequenceFlow_0l4jzc5</bpmn:incoming> + </bpmn:endEvent> + <bpmn:sequenceFlow id="SequenceFlow_19gbhlj" sourceRef="catchInventoryException" targetRef="processAuditException" /> + <bpmn:sequenceFlow id="SequenceFlow_0l4jzc5" sourceRef="processAuditException" targetRef="EndEvent_067jv1n" /> + <bpmn:serviceTask id="processAuditException" name="Proccess Error" camunda:expression="${ExceptionBuilder.processAuditException(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:incoming>SequenceFlow_19gbhlj</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0l4jzc5</bpmn:outgoing> + </bpmn:serviceTask> + </bpmn:subProcess> + <bpmn:inclusiveGateway id="ExclusiveGateway_1v8bmbu" name="Audit Enabled?" default="SequenceFlow_07ybdik"> + <bpmn:incoming>SequenceFlow_1xqyur9</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_07ybdik</bpmn:outgoing> + <bpmn:outgoing>SequenceFlow_0ghzwlo</bpmn:outgoing> + </bpmn:inclusiveGateway> + <bpmn:inclusiveGateway id="ExclusiveGateway_0sqvzll"> + <bpmn:incoming>SequenceFlow_07ybdik</bpmn:incoming> + <bpmn:incoming>SequenceFlow_18faffa</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1b63lv4</bpmn:outgoing> + </bpmn:inclusiveGateway> + <bpmn:inclusiveGateway id="ExclusiveGateway_1h8avxn" name="Audit Failed?" default="SequenceFlow_1bo83qk"> + <bpmn:incoming>SequenceFlow_0ee42yq</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_109oxx2</bpmn:outgoing> + <bpmn:outgoing>SequenceFlow_1bo83qk</bpmn:outgoing> + </bpmn:inclusiveGateway> + <bpmn:inclusiveGateway id="ExclusiveGateway_0y0ek7t"> + <bpmn:incoming>SequenceFlow_109oxx2</bpmn:incoming> + <bpmn:incoming>SequenceFlow_0arwo1o</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_18faffa</bpmn:outgoing> + </bpmn:inclusiveGateway> </bpmn:process> <bpmn:error id="Error_0q258vt" errorCode="7000" /> + <bpmn:error id="Error_0zgccif" name="org.onap.so.adapters.inventory.create.InventoryException" errorCode="org.onap.so.adapters.inventory.create.InventoryException" /> + <bpmn:error id="Error_1s3kxze" name="Error_3q664s5" errorCode="AAIInventoryFailure" /> <bpmndi:BPMNDiagram id="BPMNDiagram_1"> <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="ActivateVfModuleBB"> <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="ActivateVfModuleBB_Start"> - <dc:Bounds x="73" y="102" width="36" height="36" /> + <dc:Bounds x="85" y="234" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="46" y="138" width="90" height="12" /> + <dc:Bounds x="58" y="270" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0ieafii_di" bpmnElement="SequenceFlow_0ieafii"> - <di:waypoint xsi:type="dc:Point" x="109" y="120" /> - <di:waypoint xsi:type="dc:Point" x="161" y="120" /> + <di:waypoint xsi:type="dc:Point" x="121" y="252" /> + <di:waypoint xsi:type="dc:Point" x="201" y="252" /> <bpmndi:BPMNLabel> - <dc:Bounds x="90" y="99" width="90" height="12" /> + <dc:Bounds x="116" y="231" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="EndEvent_1v967li_di" bpmnElement="ActivateVfModuleBB_End"> - <dc:Bounds x="1104" y="102" width="36" height="36" /> + <dc:Bounds x="1404" y="235" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="935" y="142" width="90" height="12" /> + <dc:Bounds x="1235" y="275" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ServiceTask_0hawa84_di" bpmnElement="ActivateVfModule"> - <dc:Bounds x="647" y="80" width="100" height="80" /> + <dc:Bounds x="958" y="212" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ServiceTask_175e9ul_di" bpmnElement="UpdateVfModuleActiveStatus"> - <dc:Bounds x="952" y="80" width="100" height="80" /> + <dc:Bounds x="1214" y="212" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0xsp0pv_di" bpmnElement="SequenceFlow_0xsp0pv"> - <di:waypoint xsi:type="dc:Point" x="1052" y="120" /> - <di:waypoint xsi:type="dc:Point" x="1104" y="120" /> + <di:waypoint xsi:type="dc:Point" x="1314" y="252" /> + <di:waypoint xsi:type="dc:Point" x="1404" y="253" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1033" y="99" width="90" height="12" /> + <dc:Bounds x="1314" y="231.5" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="CallActivity_03jkesd_di" bpmnElement="CallActivity_sdncHandler"> - <dc:Bounds x="794" y="80" width="100" height="80" /> + <dc:Bounds x="1086" y="212" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1a495wm_di" bpmnElement="SequenceFlow_1a495wm"> - <di:waypoint xsi:type="dc:Point" x="747" y="120" /> - <di:waypoint xsi:type="dc:Point" x="794" y="120" /> + <di:waypoint xsi:type="dc:Point" x="1058" y="252" /> + <di:waypoint xsi:type="dc:Point" x="1086" y="252" /> <bpmndi:BPMNLabel> - <dc:Bounds x="725.5" y="99" width="90" height="12" /> + <dc:Bounds x="1027" y="231" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1j4x1ej_di" bpmnElement="SequenceFlow_1j4x1ej"> - <di:waypoint xsi:type="dc:Point" x="894" y="120" /> - <di:waypoint xsi:type="dc:Point" x="952" y="120" /> + <di:waypoint xsi:type="dc:Point" x="1186" y="252" /> + <di:waypoint xsi:type="dc:Point" x="1214" y="252" /> <bpmndi:BPMNLabel> - <dc:Bounds x="878" y="99" width="90" height="12" /> + <dc:Bounds x="1155" y="231" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0xndboi_di" bpmnElement="SequenceFlow_0xndboi"> - <di:waypoint xsi:type="dc:Point" x="365" y="256" /> - <di:waypoint xsi:type="dc:Point" x="408" y="256" /> + <di:waypoint xsi:type="dc:Point" x="491" y="175" /> + <di:waypoint xsi:type="dc:Point" x="513" y="175" /> <bpmndi:BPMNLabel> - <dc:Bounds x="341.5" y="234.5" width="90" height="13" /> + <dc:Bounds x="457" y="153.5" width="90" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_0krf1ur_di" bpmnElement="Setup_AAI_Inventory_Audit"> - <dc:Bounds x="265" y="216" width="100" height="80" /> + <dc:Bounds x="391" y="135" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ServiceTask_08rxjeb_di" bpmnElement="Audit_AAI_Inventory"> - <dc:Bounds x="408" y="216" width="100" height="80" /> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="ExclusiveGateway_1v8bmbu_di" bpmnElement="ExclusiveGateway_1v8bmbu" isMarkerVisible="true"> - <dc:Bounds x="290" y="95" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="315" y="148" width="0" height="13" /> - </bpmndi:BPMNLabel> + <dc:Bounds x="513" y="135" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_07ybdik_di" bpmnElement="SequenceFlow_07ybdik"> - <di:waypoint xsi:type="dc:Point" x="340" y="120" /> - <di:waypoint xsi:type="dc:Point" x="647" y="120" /> + <di:waypoint xsi:type="dc:Point" x="355" y="277" /> + <di:waypoint xsi:type="dc:Point" x="355" y="315" /> + <di:waypoint xsi:type="dc:Point" x="881" y="315" /> + <di:waypoint xsi:type="dc:Point" x="881" y="277" /> <bpmndi:BPMNLabel> - <dc:Bounds x="448.5" y="98.5" width="90" height="13" /> + <dc:Bounds x="364" y="294" width="14" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0ghzwlo_di" bpmnElement="SequenceFlow_0ghzwlo"> - <di:waypoint xsi:type="dc:Point" x="315" y="145" /> - <di:waypoint xsi:type="dc:Point" x="315" y="216" /> + <di:waypoint xsi:type="dc:Point" x="355" y="227" /> + <di:waypoint xsi:type="dc:Point" x="355" y="175" /> + <di:waypoint xsi:type="dc:Point" x="391" y="175" /> <bpmndi:BPMNLabel> - <dc:Bounds x="330" y="174" width="0" height="13" /> + <dc:Bounds x="362" y="185" width="19" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0ee42yq_di" bpmnElement="SequenceFlow_0ee42yq"> - <di:waypoint xsi:type="dc:Point" x="508" y="256" /> - <di:waypoint xsi:type="dc:Point" x="566" y="256" /> + <di:waypoint xsi:type="dc:Point" x="613" y="175" /> + <di:waypoint xsi:type="dc:Point" x="638" y="175" /> <bpmndi:BPMNLabel> - <dc:Bounds x="492" y="234.5" width="90" height="13" /> + <dc:Bounds x="580.5" y="153.5" width="90" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_1eg5ryx_di" bpmnElement="CheckAuditVariable"> - <dc:Bounds x="161" y="80" width="100" height="80" /> + <dc:Bounds x="201" y="212" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1xqyur9_di" bpmnElement="SequenceFlow_1xqyur9"> - <di:waypoint xsi:type="dc:Point" x="261" y="120" /> - <di:waypoint xsi:type="dc:Point" x="290" y="120" /> + <di:waypoint xsi:type="dc:Point" x="301" y="252" /> + <di:waypoint xsi:type="dc:Point" x="330" y="252" /> <bpmndi:BPMNLabel> - <dc:Bounds x="275.5" y="98.5" width="0" height="13" /> + <dc:Bounds x="270.5" y="230.5" width="90" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="ExclusiveGateway_1h8avxn_di" bpmnElement="ExclusiveGateway_1h8avxn" isMarkerVisible="true"> - <dc:Bounds x="566" y="231" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="591" y="284" width="0" height="13" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_109oxx2_di" bpmnElement="SequenceFlow_109oxx2"> - <di:waypoint xsi:type="dc:Point" x="616" y="256" /> - <di:waypoint xsi:type="dc:Point" x="670" y="256" /> - <di:waypoint xsi:type="dc:Point" x="670" y="160" /> + <di:waypoint xsi:type="dc:Point" x="663" y="200" /> + <di:waypoint xsi:type="dc:Point" x="663" y="230" /> + <di:waypoint xsi:type="dc:Point" x="834" y="230" /> + <di:waypoint xsi:type="dc:Point" x="834" y="200" /> <bpmndi:BPMNLabel> - <dc:Bounds x="643" y="234.5" width="0" height="13" /> + <dc:Bounds x="670" y="207" width="14" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1bo83qk_di" bpmnElement="SequenceFlow_1bo83qk"> - <di:waypoint xsi:type="dc:Point" x="591" y="281" /> - <di:waypoint xsi:type="dc:Point" x="591" y="345" /> - <di:waypoint xsi:type="dc:Point" x="656" y="345" /> + <di:waypoint xsi:type="dc:Point" x="663" y="150" /> + <di:waypoint xsi:type="dc:Point" x="663" y="101" /> + <di:waypoint xsi:type="dc:Point" x="691" y="101" /> <bpmndi:BPMNLabel> - <dc:Bounds x="560" y="358" width="61" height="12" /> + <dc:Bounds x="667" y="111" width="19" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0arwo1o_di" bpmnElement="SequenceFlow_0arwo1o"> - <di:waypoint xsi:type="dc:Point" x="706" y="305" /> - <di:waypoint xsi:type="dc:Point" x="706" y="160" /> + <di:waypoint xsi:type="dc:Point" x="791" y="101" /> + <di:waypoint xsi:type="dc:Point" x="834" y="101" /> + <di:waypoint xsi:type="dc:Point" x="834" y="150" /> <bpmndi:BPMNLabel> - <dc:Bounds x="721" y="226" width="0" height="13" /> + <dc:Bounds x="767.5" y="79.5" width="90" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_1eb09gr_di" bpmnElement="Create_AAI_Inventory"> - <dc:Bounds x="656" y="305" width="100" height="80" /> + <dc:Bounds x="691" y="61" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1b63lv4_di" bpmnElement="SequenceFlow_1b63lv4"> + <di:waypoint xsi:type="dc:Point" x="906" y="252" /> + <di:waypoint xsi:type="dc:Point" x="958" y="252" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="887" y="231" width="90" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_18faffa_di" bpmnElement="SequenceFlow_18faffa"> + <di:waypoint xsi:type="dc:Point" x="859" y="175" /> + <di:waypoint xsi:type="dc:Point" x="881" y="175" /> + <di:waypoint xsi:type="dc:Point" x="881" y="227" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="825" y="154" width="90" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="SubProcess_0mbkb7v_di" bpmnElement="SubProcess_0bpsptg" isExpanded="true"> + <dc:Bounds x="293" y="449" width="350" height="200" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="StartEvent_12r96di_di" bpmnElement="catchInventoryException"> + <dc:Bounds x="324" y="532" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="341.15269461077844" y="571.6127744510978" width="0" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="EndEvent_067jv1n_di" bpmnElement="EndEvent_067jv1n"> + <dc:Bounds x="572.1526946107784" y="532" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="590.1526946107784" y="572" width="0" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_19gbhlj_di" bpmnElement="SequenceFlow_19gbhlj"> + <di:waypoint xsi:type="dc:Point" x="360" y="550" /> + <di:waypoint xsi:type="dc:Point" x="415" y="550" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="387.5" y="529" width="0" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0l4jzc5_di" bpmnElement="SequenceFlow_0l4jzc5"> + <di:waypoint xsi:type="dc:Point" x="515" y="550" /> + <di:waypoint xsi:type="dc:Point" x="572" y="550" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="543.5" y="529" width="0" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ServiceTask_08xffml_di" bpmnElement="processAuditException"> + <dc:Bounds x="415" y="510" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="InclusiveGateway_03pi9y4_di" bpmnElement="ExclusiveGateway_1v8bmbu"> + <dc:Bounds x="330" y="227" width="50" height="50" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="383" y="246" width="73" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="InclusiveGateway_16ap4e3_di" bpmnElement="ExclusiveGateway_0sqvzll"> + <dc:Bounds x="856" y="227" width="50" height="50" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="836" y="281" width="0" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="InclusiveGateway_00n600s_di" bpmnElement="ExclusiveGateway_1h8avxn"> + <dc:Bounds x="638" y="150" width="50" height="50" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="693" y="169" width="63" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="InclusiveGateway_0xx6c29_di" bpmnElement="ExclusiveGateway_0y0ek7t"> + <dc:Bounds x="809" y="150" width="50" height="50" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="789" y="204" width="0" height="12" /> + </bpmndi:BPMNLabel> </bpmndi:BPMNShape> </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 e1b36cfe65..41c3966626 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 @@ -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.7.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_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="1.10.0"> <bpmn:process id="DeleteVfModuleBB" name="DeleteVfModuleBB" isExecutable="true"> <bpmn:startEvent id="DeleteVfModuleBB_Start"> <bpmn:outgoing>SequenceFlow_1537yw5</bpmn:outgoing> @@ -51,22 +51,22 @@ <bpmn:sequenceFlow id="SequenceFlow_01vfwtp" sourceRef="UpdateVfModuleHeatStackId" targetRef="UpdateVfModuleDeleteStatus" /> <bpmn:sequenceFlow id="SequenceFlow_09l7pcg" sourceRef="UpdateVfModuleDeleteStatus" targetRef="DeleteVfModuleBB_End" /> <bpmn:sequenceFlow id="SequenceFlow_0xyu3pk" sourceRef="DeleteNetworkPolicies" targetRef="UpdateVnfIpv4OamAddress" /> - <bpmn:serviceTask id="DeleteNetworkPolicies" name="AAI Delete (network policies)" camunda:expression="${AAIDeleteTasks.deleteNetworkPolicies(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> - <bpmn:incoming>SequenceFlow_14bu4ys</bpmn:incoming> + <bpmn:serviceTask id="DeleteNetworkPolicies" name=" AAI Delete (net policies) " camunda:expression="${AAIDeleteTasks.deleteNetworkPolicies(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:incoming>SequenceFlow_179btn2</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0xyu3pk</bpmn:outgoing> </bpmn:serviceTask> - <bpmn:serviceTask id="UpdateVnfManagementV6Address" name="AAI Update (VNF)" camunda:expression="${AAIUpdateTasks.updateManagementV6AddressVnf(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:serviceTask id="UpdateVnfManagementV6Address" name=" AAI Update (vnf) " camunda:expression="${AAIUpdateTasks.updateManagementV6AddressVnf(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> <bpmn:incoming>SequenceFlow_0jtem3b</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0khqfnc</bpmn:outgoing> </bpmn:serviceTask> <bpmn:sequenceFlow id="SequenceFlow_0jtem3b" sourceRef="UpdateVnfIpv4OamAddress" targetRef="UpdateVnfManagementV6Address" /> - <bpmn:serviceTask id="UpdateVnfIpv4OamAddress" name="AAI Update (VNF)" camunda:expression="${AAIUpdateTasks.updateIpv4OamAddressVnf(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:serviceTask id="UpdateVnfIpv4OamAddress" name=" AAI Update (vnf) " camunda:expression="${AAIUpdateTasks.updateIpv4OamAddressVnf(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> <bpmn:incoming>SequenceFlow_0xyu3pk</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0jtem3b</bpmn:outgoing> </bpmn:serviceTask> <bpmn:sequenceFlow id="SequenceFlow_0khqfnc" sourceRef="UpdateVnfManagementV6Address" targetRef="UpdateVfModuleContrailServiceInstanceFqdn" /> <bpmn:sequenceFlow id="SequenceFlow_0yuz21z" sourceRef="UpdateVfModuleContrailServiceInstanceFqdn" targetRef="UpdateVfModuleHeatStackId" /> - <bpmn:serviceTask id="UpdateVfModuleContrailServiceInstanceFqdn" name="AAI Update (vf module) " camunda:expression="${AAIUpdateTasks.updateContrailServiceInstanceFqdnVfModule(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:serviceTask id="UpdateVfModuleContrailServiceInstanceFqdn" name=" AAI Update (vf module) " camunda:expression="${AAIUpdateTasks.updateContrailServiceInstanceFqdnVfModule(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> <bpmn:incoming>SequenceFlow_0khqfnc</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0yuz21z</bpmn:outgoing> </bpmn:serviceTask> @@ -79,13 +79,8 @@ <bpmn:sequenceFlow id="SequenceFlow_032jv5j" name="Yes " sourceRef="ExclusiveGateway_1h2ystu" targetRef="Setup_Audit_Variable"> <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("auditInventoryNeeded") == true}]]></bpmn:conditionExpression> </bpmn:sequenceFlow> - <bpmn:sequenceFlow id="SequenceFlow_0qfmmgt" sourceRef="Audit_Inventory" targetRef="ExclusiveGateway_1pydilb" /> - <bpmn:sequenceFlow id="SequenceFlow_14bu4ys" sourceRef="ExclusiveGateway_1yvh16a" targetRef="DeleteNetworkPolicies" /> - <bpmn:parallelGateway id="ExclusiveGateway_1yvh16a"> - <bpmn:incoming>SequenceFlow_02lpx87</bpmn:incoming> - <bpmn:incoming>SequenceFlow_1ut7n32</bpmn:incoming> - <bpmn:outgoing>SequenceFlow_14bu4ys</bpmn:outgoing> - </bpmn:parallelGateway> + <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:incoming>SequenceFlow_1v3jgqe</bpmn:incoming> @@ -109,240 +104,356 @@ <bpmn:outgoing>SequenceFlow_1mgunf3</bpmn:outgoing> </bpmn:exclusiveGateway> <bpmn:exclusiveGateway id="ExclusiveGateway_1pydilb"> - <bpmn:incoming>SequenceFlow_0qfmmgt</bpmn:incoming> <bpmn:incoming>SequenceFlow_1mgunf3</bpmn:incoming> + <bpmn:incoming>SequenceFlow_17cd9e2</bpmn:incoming> <bpmn:outgoing>SequenceFlow_1ut7n32</bpmn:outgoing> </bpmn:exclusiveGateway> + <bpmn:subProcess id="SubProcess_0grvkj2" name="Audit Exception Sub Process" triggeredByEvent="true"> + <bpmn:startEvent id="StartEvent_1euiddy"> + <bpmn:outgoing>SequenceFlow_0xuodpy</bpmn:outgoing> + <bpmn:errorEventDefinition errorRef="Error_0jjnve8" /> + </bpmn:startEvent> + <bpmn:endEvent id="EndEvent_1gzq57j"> + <bpmn:incoming>SequenceFlow_1fhst92</bpmn:incoming> + </bpmn:endEvent> + <bpmn:serviceTask id="ServiceTask_1isbxvo" name="Proccess Error" camunda:expression="${ExceptionBuilder.processAuditException(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:incoming>SequenceFlow_0xuodpy</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1fhst92</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:sequenceFlow id="SequenceFlow_0xuodpy" sourceRef="StartEvent_1euiddy" targetRef="ServiceTask_1isbxvo" /> + <bpmn:sequenceFlow id="SequenceFlow_1fhst92" sourceRef="ServiceTask_1isbxvo" targetRef="EndEvent_1gzq57j" /> + </bpmn:subProcess> + <bpmn:sequenceFlow id="SequenceFlow_179btn2" sourceRef="aaiCatch" targetRef="DeleteNetworkPolicies" /> + <bpmn:intermediateThrowEvent id="aaiThrow" name="Update AAI"> + <bpmn:incoming>SequenceFlow_14bu4ys</bpmn:incoming> + <bpmn:linkEventDefinition name="AAI" /> + </bpmn:intermediateThrowEvent> + <bpmn:intermediateCatchEvent id="aaiCatch" name="Update AAI"> + <bpmn:outgoing>SequenceFlow_179btn2</bpmn:outgoing> + <bpmn:linkEventDefinition name="AAI" /> + </bpmn:intermediateCatchEvent> + <bpmn:exclusiveGateway id="auditSuccessfulCheck" name="Audit Successful?" default="SequenceFlow_17cd9e2"> + <bpmn:incoming>SequenceFlow_0qfmmgt</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_17cd9e2</bpmn:outgoing> + <bpmn:outgoing>SequenceFlow_1gdyk9j</bpmn:outgoing> + </bpmn:exclusiveGateway> + <bpmn:sequenceFlow id="SequenceFlow_17cd9e2" name="Yes" sourceRef="auditSuccessfulCheck" targetRef="ExclusiveGateway_1pydilb" /> + <bpmn:sequenceFlow id="SequenceFlow_1gdyk9j" name="No" sourceRef="auditSuccessfulCheck" targetRef="EndEvent_0b0ocu0"> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("auditIsSuccessful") == false}]]></bpmn:conditionExpression> + </bpmn:sequenceFlow> + <bpmn:endEvent id="EndEvent_0b0ocu0"> + <bpmn:incoming>SequenceFlow_1gdyk9j</bpmn:incoming> + <bpmn:errorEventDefinition errorRef="Error_0jjnve8" /> + </bpmn:endEvent> + <bpmn:inclusiveGateway id="ExclusiveGateway_1yvh16a"> + <bpmn:incoming>SequenceFlow_02lpx87</bpmn:incoming> + <bpmn:incoming>SequenceFlow_1ut7n32</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_14bu4ys</bpmn:outgoing> + </bpmn:inclusiveGateway> </bpmn:process> + <bpmn:error id="Error_0jjnve8" name="Error_3k24na6" errorCode="AAIInventoryFailure" /> <bpmndi:BPMNDiagram id="BPMNDiagram_1"> <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="DeleteVfModuleBB"> <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="DeleteVfModuleBB_Start"> - <dc:Bounds x="159" y="241" width="36" height="36" /> + <dc:Bounds x="159" y="266" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="132" y="277" width="90" height="12" /> + <dc:Bounds x="132" y="302" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ServiceTask_16798zf_di" bpmnElement="DeleteVfModuleVnfAdapter"> - <dc:Bounds x="382" y="278" width="100" height="80" /> + <dc:Bounds x="382" y="303" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1537yw5_di" bpmnElement="SequenceFlow_1537yw5"> - <di:waypoint xsi:type="dc:Point" x="195" y="259" /> - <di:waypoint xsi:type="dc:Point" x="282" y="259" /> + <di:waypoint xsi:type="dc:Point" x="195" y="284" /> + <di:waypoint xsi:type="dc:Point" x="282" y="284" /> <bpmndi:BPMNLabel> - <dc:Bounds x="193.5" y="238" width="90" height="12" /> + <dc:Bounds x="194" y="263" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_0pbhsub_di" bpmnElement="UpdateVfModuleDeleteStatus"> - <dc:Bounds x="840" y="443" width="100" height="80" /> + <dc:Bounds x="907" y="468" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_08tvhtf_di" bpmnElement="SequenceFlow_08tvhtf"> - <di:waypoint xsi:type="dc:Point" x="482" y="318" /> - <di:waypoint xsi:type="dc:Point" x="511" y="318" /> + <di:waypoint xsi:type="dc:Point" x="482" y="343" /> + <di:waypoint xsi:type="dc:Point" x="511" y="343" /> <bpmndi:BPMNLabel> - <dc:Bounds x="451.5" y="297" width="90" height="12" /> + <dc:Bounds x="452" y="322" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="EndEvent_1rn6yvh_di" bpmnElement="DeleteVfModuleBB_End"> - <dc:Bounds x="1087" y="465" width="36" height="36" /> + <dc:Bounds x="1136" y="490" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1060" y="505" width="90" height="0" /> + <dc:Bounds x="1109" y="530" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="CallActivity_0whogn3_di" bpmnElement="VnfAdapter"> - <dc:Bounds x="511" y="278" width="100" height="80" /> + <dc:Bounds x="511" y="303" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_02lpx87_di" bpmnElement="SequenceFlow_02lpx87"> - <di:waypoint xsi:type="dc:Point" x="611" y="318" /> - <di:waypoint xsi:type="dc:Point" x="836" y="318" /> - <di:waypoint xsi:type="dc:Point" x="836" y="284" /> + <di:waypoint xsi:type="dc:Point" x="611" y="343" /> + <di:waypoint xsi:type="dc:Point" x="925" y="343" /> + <di:waypoint xsi:type="dc:Point" x="925" y="309" /> <bpmndi:BPMNLabel> - <dc:Bounds x="678.5" y="303" width="90" height="0" /> + <dc:Bounds x="723" y="328" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="SubProcess_11p7mrh_di" bpmnElement="SubProcess_11p7mrh" isExpanded="true"> - <dc:Bounds x="294" y="618" width="231" height="135" /> + <dc:Bounds x="290" y="878" width="231" height="135" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="StartEvent_1xp6ewt_di" bpmnElement="StartEvent_1xp6ewt"> - <dc:Bounds x="337" y="680" width="36" height="36" /> + <dc:Bounds x="333" y="940" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="265" y="716" width="90" height="0" /> + <dc:Bounds x="261" y="976" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="EndEvent_0guhjau_di" bpmnElement="EndEvent_0guhjau"> - <dc:Bounds x="466" y="680" width="36" height="36" /> + <dc:Bounds x="462" y="940" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="394" y="716" width="90" height="0" /> + <dc:Bounds x="390" y="976" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0h607z0_di" bpmnElement="SequenceFlow_0h607z0"> - <di:waypoint xsi:type="dc:Point" x="373" y="698" /> - <di:waypoint xsi:type="dc:Point" x="466" y="698" /> + <di:waypoint xsi:type="dc:Point" x="369" y="958" /> + <di:waypoint xsi:type="dc:Point" x="462" y="958" /> <bpmndi:BPMNLabel> - <dc:Bounds x="375" y="677" width="90" height="0" /> + <dc:Bounds x="371" y="937" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_0vlgqod_di" bpmnElement="UpdateVfModuleHeatStackId"> - <dc:Bounds x="706" y="443" width="100" height="80" /> + <dc:Bounds x="779" y="468" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_01vfwtp_di" bpmnElement="SequenceFlow_01vfwtp"> - <di:waypoint xsi:type="dc:Point" x="806" y="483" /> - <di:waypoint xsi:type="dc:Point" x="840" y="483" /> + <di:waypoint xsi:type="dc:Point" x="879" y="508" /> + <di:waypoint xsi:type="dc:Point" x="907" y="508" /> <bpmndi:BPMNLabel> - <dc:Bounds x="778" y="468" width="90" height="0" /> + <dc:Bounds x="848" y="493" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_09l7pcg_di" bpmnElement="SequenceFlow_09l7pcg"> - <di:waypoint xsi:type="dc:Point" x="940" y="483" /> - <di:waypoint xsi:type="dc:Point" x="1087" y="483" /> + <di:waypoint xsi:type="dc:Point" x="1007" y="508" /> + <di:waypoint xsi:type="dc:Point" x="1136" y="508" /> <bpmndi:BPMNLabel> - <dc:Bounds x="968.5" y="468" width="90" height="0" /> + <dc:Bounds x="1027" y="493" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0xyu3pk_di" bpmnElement="SequenceFlow_0xyu3pk"> - <di:waypoint xsi:type="dc:Point" x="998" y="259" /> - <di:waypoint xsi:type="dc:Point" x="1072" y="259" /> - <di:waypoint xsi:type="dc:Point" x="1072" y="399" /> - <di:waypoint xsi:type="dc:Point" x="233" y="399" /> - <di:waypoint xsi:type="dc:Point" x="233" y="483" /> - <di:waypoint xsi:type="dc:Point" x="280" y="483" /> + <di:waypoint xsi:type="dc:Point" x="376" y="508" /> + <di:waypoint xsi:type="dc:Point" x="404" y="508" /> <bpmndi:BPMNLabel> - <dc:Bounds x="607.5" y="384" width="90" height="0" /> + <dc:Bounds x="345" y="493" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_0tty0ac_di" bpmnElement="DeleteNetworkPolicies"> - <dc:Bounds x="898" y="219" width="100" height="80" /> + <dc:Bounds x="276" y="468" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ServiceTask_0lrrd16_di" bpmnElement="UpdateVnfManagementV6Address"> - <dc:Bounds x="421" y="443" width="100" height="80" /> + <dc:Bounds x="531" y="468" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0jtem3b_di" bpmnElement="SequenceFlow_0jtem3b"> - <di:waypoint xsi:type="dc:Point" x="380" y="483" /> - <di:waypoint xsi:type="dc:Point" x="421" y="483" /> + <di:waypoint xsi:type="dc:Point" x="504" y="508" /> + <di:waypoint xsi:type="dc:Point" x="531" y="508" /> <bpmndi:BPMNLabel> - <dc:Bounds x="355.5" y="468" width="90" height="0" /> + <dc:Bounds x="473" y="493" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_0w9805b_di" bpmnElement="UpdateVnfIpv4OamAddress"> - <dc:Bounds x="280" y="443" width="100" height="80" /> + <dc:Bounds x="404" y="468" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0khqfnc_di" bpmnElement="SequenceFlow_0khqfnc"> - <di:waypoint xsi:type="dc:Point" x="521" y="483" /> - <di:waypoint xsi:type="dc:Point" x="561" y="483" /> + <di:waypoint xsi:type="dc:Point" x="631" y="508" /> + <di:waypoint xsi:type="dc:Point" x="654" y="508" /> <bpmndi:BPMNLabel> - <dc:Bounds x="496" y="468" width="90" height="0" /> + <dc:Bounds x="598" y="493" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0yuz21z_di" bpmnElement="SequenceFlow_0yuz21z"> - <di:waypoint xsi:type="dc:Point" x="661" y="483" /> - <di:waypoint xsi:type="dc:Point" x="706" y="483" /> + <di:waypoint xsi:type="dc:Point" x="754" y="508" /> + <di:waypoint xsi:type="dc:Point" x="779" y="508" /> <bpmndi:BPMNLabel> - <dc:Bounds x="638.5" y="468" width="90" height="0" /> + <dc:Bounds x="722" y="493" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_0v8naz9_di" bpmnElement="UpdateVfModuleContrailServiceInstanceFqdn"> - <dc:Bounds x="561" y="443" width="100" height="80" /> + <dc:Bounds x="654" y="468" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1n8gab5_di" bpmnElement="SequenceFlow_1n8gab5"> - <di:waypoint xsi:type="dc:Point" x="307" y="284" /> - <di:waypoint xsi:type="dc:Point" x="307" y="318" /> - <di:waypoint xsi:type="dc:Point" x="382" y="318" /> + <di:waypoint xsi:type="dc:Point" x="307" y="309" /> + <di:waypoint xsi:type="dc:Point" x="307" y="343" /> + <di:waypoint xsi:type="dc:Point" x="382" y="343" /> <bpmndi:BPMNLabel> - <dc:Bounds x="277" y="294.5" width="90" height="13" /> + <dc:Bounds x="277" y="320" width="90" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ParallelGateway_18x6mx2_di" bpmnElement="ExclusiveGateway_0xrgzm7"> - <dc:Bounds x="282" y="234" width="50" height="50" /> + <dc:Bounds x="282" y="259" width="50" height="50" /> <bpmndi:BPMNLabel> - <dc:Bounds x="262" y="287" width="90" height="13" /> + <dc:Bounds x="262" y="312" width="90" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_032jv5j_di" bpmnElement="SequenceFlow_032jv5j"> - <di:waypoint xsi:type="dc:Point" x="492" y="149" /> - <di:waypoint xsi:type="dc:Point" x="492" y="108" /> - <di:waypoint xsi:type="dc:Point" x="531" y="108" /> + <di:waypoint xsi:type="dc:Point" x="492" y="174" /> + <di:waypoint xsi:type="dc:Point" x="492" y="133" /> + <di:waypoint xsi:type="dc:Point" x="531" y="133" /> <bpmndi:BPMNLabel> - <dc:Bounds x="499" y="114" width="18" height="25" /> + <dc:Bounds x="499" y="139" width="19" height="24" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0qfmmgt_di" bpmnElement="SequenceFlow_0qfmmgt"> - <di:waypoint xsi:type="dc:Point" x="754" y="108" /> - <di:waypoint xsi:type="dc:Point" x="784" y="108" /> - <di:waypoint xsi:type="dc:Point" x="784" y="149" /> + <di:waypoint xsi:type="dc:Point" x="754" y="133" /> + <di:waypoint xsi:type="dc:Point" x="780" y="133" /> <bpmndi:BPMNLabel> - <dc:Bounds x="724" y="86.5" width="90" height="13" /> + <dc:Bounds x="722" y="111.5" width="90" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_14bu4ys_di" bpmnElement="SequenceFlow_14bu4ys"> - <di:waypoint xsi:type="dc:Point" x="861" y="259" /> - <di:waypoint xsi:type="dc:Point" x="898" y="259" /> + <di:waypoint xsi:type="dc:Point" x="950" y="284" /> + <di:waypoint xsi:type="dc:Point" x="1100" y="283" /> <bpmndi:BPMNLabel> - <dc:Bounds x="834.5" y="237.5" width="90" height="13" /> + <dc:Bounds x="980" y="262" width="90" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="ParallelGateway_02fjfb8_di" bpmnElement="ExclusiveGateway_1yvh16a"> - <dc:Bounds x="811" y="234" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="790" y="287" width="90" height="13" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1mgunf3_di" bpmnElement="SequenceFlow_1mgunf3"> - <di:waypoint xsi:type="dc:Point" x="492" y="199" /> - <di:waypoint xsi:type="dc:Point" x="492" y="232" /> - <di:waypoint xsi:type="dc:Point" x="784" y="232" /> - <di:waypoint xsi:type="dc:Point" x="784" y="199" /> + <di:waypoint xsi:type="dc:Point" x="492" y="224" /> + <di:waypoint xsi:type="dc:Point" x="492" y="257" /> + <di:waypoint xsi:type="dc:Point" x="868" y="257" /> + <di:waypoint xsi:type="dc:Point" x="868" y="224" /> <bpmndi:BPMNLabel> - <dc:Bounds x="499" y="212" width="15" height="13" /> + <dc:Bounds x="503.9261744966443" y="237" width="14" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_1vmz3zo_di" bpmnElement="Check_Audit"> - <dc:Bounds x="339" y="134" width="100" height="80" /> + <dc:Bounds x="339" y="159" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1v3jgqe_di" bpmnElement="SequenceFlow_1v3jgqe"> - <di:waypoint xsi:type="dc:Point" x="307" y="234" /> - <di:waypoint xsi:type="dc:Point" x="307" y="174" /> - <di:waypoint xsi:type="dc:Point" x="339" y="174" /> + <di:waypoint xsi:type="dc:Point" x="307" y="259" /> + <di:waypoint xsi:type="dc:Point" x="307" y="199" /> + <di:waypoint xsi:type="dc:Point" x="339" y="199" /> <bpmndi:BPMNLabel> - <dc:Bounds x="277" y="197.5" width="90" height="13" /> + <dc:Bounds x="277" y="223" width="90" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1odt2wt_di" bpmnElement="SequenceFlow_1odt2wt"> - <di:waypoint xsi:type="dc:Point" x="439" y="174" /> - <di:waypoint xsi:type="dc:Point" x="467" y="174" /> + <di:waypoint xsi:type="dc:Point" x="439" y="199" /> + <di:waypoint xsi:type="dc:Point" x="467" y="199" /> <bpmndi:BPMNLabel> - <dc:Bounds x="408" y="152.5" width="90" height="13" /> + <dc:Bounds x="408" y="178" width="90" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1swistn_di" bpmnElement="SequenceFlow_1swistn"> - <di:waypoint xsi:type="dc:Point" x="631" y="108" /> - <di:waypoint xsi:type="dc:Point" x="654" y="108" /> + <di:waypoint xsi:type="dc:Point" x="631" y="133" /> + <di:waypoint xsi:type="dc:Point" x="654" y="133" /> <bpmndi:BPMNLabel> - <dc:Bounds x="597.5" y="86.5" width="90" height="13" /> + <dc:Bounds x="598" y="112" width="90" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_1l8r2a6_di" bpmnElement="Audit_Inventory"> - <dc:Bounds x="654" y="68" width="100" height="80" /> + <dc:Bounds x="654" y="93" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ServiceTask_1gttdjr_di" bpmnElement="Setup_Audit_Variable"> - <dc:Bounds x="531" y="68" width="100" height="80" /> + <dc:Bounds x="531" y="93" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1ut7n32_di" bpmnElement="SequenceFlow_1ut7n32"> - <di:waypoint xsi:type="dc:Point" x="809" y="174" /> - <di:waypoint xsi:type="dc:Point" x="836" y="174" /> - <di:waypoint xsi:type="dc:Point" x="836" y="234" /> + <di:waypoint xsi:type="dc:Point" x="893" y="199" /> + <di:waypoint xsi:type="dc:Point" x="925" y="199" /> + <di:waypoint xsi:type="dc:Point" x="925" y="259" /> <bpmndi:BPMNLabel> - <dc:Bounds x="777.5" y="152.5" width="90" height="13" /> + <dc:Bounds x="864" y="177.5" width="90" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ExclusiveGateway_1olwkdn_di" bpmnElement="ExclusiveGateway_1h2ystu" isMarkerVisible="true"> - <dc:Bounds x="467" y="149" width="50" height="50" /> + <dc:Bounds x="467" y="174" width="50" height="50" /> <bpmndi:BPMNLabel> - <dc:Bounds x="518" y="162" width="47" height="25" /> + <dc:Bounds x="519" y="187" width="45" height="24" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ExclusiveGateway_1d1pmqz_di" bpmnElement="ExclusiveGateway_1pydilb" isMarkerVisible="true"> - <dc:Bounds x="759" y="149" width="50" height="50" /> + <dc:Bounds x="843" y="174" width="50" height="50" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="733" y="227" width="90" height="13" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="SubProcess_0grvkj2_di" bpmnElement="SubProcess_0grvkj2" isExpanded="true"> + <dc:Bounds x="231" y="642" width="350" height="200" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="StartEvent_1euiddy_di" bpmnElement="StartEvent_1euiddy"> + <dc:Bounds x="262" y="725" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="189" y="765" width="90" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="EndEvent_1gzq57j_di" bpmnElement="EndEvent_1gzq57j"> + <dc:Bounds x="510" y="725" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="438" y="765" width="90" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ServiceTask_1isbxvo_di" bpmnElement="ServiceTask_1isbxvo"> + <dc:Bounds x="353" y="703" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_0xuodpy_di" bpmnElement="SequenceFlow_0xuodpy"> + <di:waypoint xsi:type="dc:Point" x="298" y="743" /> + <di:waypoint xsi:type="dc:Point" x="353" y="743" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="237" y="722" width="90" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_1fhst92_di" bpmnElement="SequenceFlow_1fhst92"> + <di:waypoint xsi:type="dc:Point" x="453" y="743" /> + <di:waypoint xsi:type="dc:Point" x="510" y="743" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="393" y="722" width="90" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_179btn2_di" bpmnElement="SequenceFlow_179btn2"> + <di:waypoint xsi:type="dc:Point" x="195" y="508" /> + <di:waypoint xsi:type="dc:Point" x="276" y="508" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="191" y="487" width="90" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="IntermediateThrowEvent_1sftyjz_di" bpmnElement="aaiThrow"> + <dc:Bounds x="1100" y="266" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="1092" y="305" width="55" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="IntermediateCatchEvent_13y483m_di" bpmnElement="aaiCatch"> + <dc:Bounds x="159" y="490" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="150" y="530" width="55" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ExclusiveGateway_187bfld_di" bpmnElement="auditSuccessfulCheck" isMarkerVisible="true"> + <dc:Bounds x="779.6431784107947" y="108" width="50" height="50" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="775" y="162" width="60" height="24" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_17cd9e2_di" bpmnElement="SequenceFlow_17cd9e2"> + <di:waypoint xsi:type="dc:Point" x="830" y="133" /> + <di:waypoint xsi:type="dc:Point" x="868" y="133" /> + <di:waypoint xsi:type="dc:Point" x="868" y="174" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="838" y="114" width="19" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_1gdyk9j_di" bpmnElement="SequenceFlow_1gdyk9j"> + <di:waypoint xsi:type="dc:Point" x="805" y="108" /> + <di:waypoint xsi:type="dc:Point" x="805" y="56" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="812" y="77.49056603773585" width="14" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="EndEvent_1wydovd_di" bpmnElement="EndEvent_0b0ocu0"> + <dc:Bounds x="787" y="20" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="805" y="59.13043478260869" width="0" height="12" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="InclusiveGateway_0cjvlht_di" bpmnElement="ExclusiveGateway_1yvh16a"> + <dc:Bounds x="900" y="259" width="50" height="50" /> <bpmndi:BPMNLabel> - <dc:Bounds x="694" y="202" width="0" height="13" /> + <dc:Bounds x="879" y="312" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> </bpmndi:BPMNPlane> diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStartActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStartActivityTest.java index a8e974d63a..2163e0b7a8 100644 --- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStartActivityTest.java +++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFStartActivityTest.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. diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnlockActivityTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnlockActivityTest.java index b6faf1b806..c5ddd56880 100644 --- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnlockActivityTest.java +++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VNFUnlockActivityTest.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. 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 3e059e53bf..6a5a9021b2 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 @@ -216,7 +216,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { * This method updates the resource input by collecting required info from AAI * @param execution */ - public void updateResourceInput(DelegateExecution execution) { + public ResourceInput updateResourceInput(DelegateExecution execution) { ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(execution.getVariable(Prefix + "resourceInput"), ResourceInput.class) String modelName = resourceInputObj.getResourceModelInfo().getModelName() @@ -232,9 +232,29 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { String incomingRequest = resourceInputObj.getRequestsInputs() String serviceParameters = JsonUtils.getJsonValue(incomingRequest, "service.parameters") String requestInputs = JsonUtils.getJsonValue(serviceParameters, "requestInputs") - String cvlan = "10" - String svlan = "100" - String accessId = "AC9.0234.0337" + String cvlan + String svlan + String remoteId + + List<Metadatum> metadatum = getMetaDatum(resourceInputObj.getGlobalSubscriberId(), + resourceInputObj.getServiceType(), + resourceInputObj.getServiceInstanceId()) + for(Metadatum datum: metadatum) { + if (datum.getMetaname().equalsIgnoreCase("cvlan")) { + cvlan = datum.getMetaval() + } + + if (datum.getMetaname().equalsIgnoreCase("svlan")) { + svlan = datum.getMetaval() + } + + if (datum.getMetaname().equalsIgnoreCase("remoteId")) { + remoteId = datum.getMetaval() + } + } + + logger.debug("cvlan: "+cvlan+" | svlan: "+svlan+" | remoteId: "+remoteId) + String manufacturer = jsonUtil.getJsonValue(serInput, "service.parameters.requestInputs.ont_ont_manufacturer") String ontsn = jsonUtil.getJsonValue(serInput, @@ -242,14 +262,14 @@ 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", accessId) + uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.accessID", remoteId) uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.manufacturer", manufacturer) uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ONTSN", ontsn) - msoLogger.debug("old resource input:" + resourceInputObj.toString()) + logger.debug("old resource input:" + resourceInputObj.toString()) resourceInputObj.setResourceParameters(uResourceInput) execution.setVariable(Prefix + "resourceInput", resourceInputObj.toString()) - msoLogger.debug("new resource Input :" + resourceInputObj.toString()) + logger.debug("new resource Input :" + resourceInputObj.toString()) break case ~/[\w\s\W]*EdgeInternetProfile[\w\s\W]*/ : @@ -260,23 +280,41 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { String requestInputs = JsonUtils.getJsonValue(serviceParameters, "requestInputs") JSONObject inputParameters = new JSONObject(requestInputs) - String cvlan = "100" - String svlan = "1000" + String cvlan + String svlan + String remoteId String manufacturer = jsonUtil.getJsonValue(serInput, "service.parameters.requestInputs.ont_ont_manufacturer") - String accessId = "AC9.0234.0337" + String ontsn = jsonUtil.getJsonValue(serInput, "service.parameters.requestInputs.ont_ont_serial_num") + List<Metadatum> metadatum = getMetaDatum(resourceInputObj.getGlobalSubscriberId(), + resourceInputObj.getServiceType(), + resourceInputObj.getServiceInstanceId()) + for(Metadatum datum: metadatum) { + if (datum.getMetaname().equalsIgnoreCase("cvlan")) { + cvlan = datum.getMetaval() + } + + if (datum.getMetaname().equalsIgnoreCase("svlan")) { + svlan = datum.getMetaval() + } + + if (datum.getMetaname().equalsIgnoreCase("remoteId")) { + remoteId = datum.getMetaval() + } + } + String uResourceInput = jsonUtil.addJsonValue(resourceInput, "requestInputs.c_vlan", cvlan) uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.s_vlan", svlan) uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.manufacturer", manufacturer) - uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_access_id", accessId) + uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_access_id", remoteId) uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ont_sn", ontsn) - msoLogger.debug("old resource input:" + resourceInputObj.toString()) + logger.debug("old resource input:" + resourceInputObj.toString()) resourceInputObj.setResourceParameters(uResourceInput) execution.setVariable(Prefix + "resourceInput", resourceInputObj.toString()) - msoLogger.debug("new resource Input :" + resourceInputObj.toString()) + logger.debug("new resource Input :" + resourceInputObj.toString()) break @@ -320,6 +358,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { default: break } + return resourceInputObj } /** diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelofE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelofE2EServiceInstance.groovy index 7ad929b1c2..c99c702af0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelofE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelofE2EServiceInstance.groovy @@ -184,7 +184,7 @@ public class DoCompareModelofE2EServiceInstance extends AbstractServiceTaskProce rmodel.setResourceCustomizationUuid(resourceCustomizationUuid) addedResourceList.add(rmodel) - Map<String, Object> resourceParameters = ResourceRequestBuilder.buildResouceRequest(serviceModelUuid, resourceCustomizationUuid, null) + Map<String, Object> resourceParameters = ResourceRequestBuilder.buildResouceRequest(serviceModelUuid, resourceCustomizationUuid, null, null) requestInputs.addAll(resourceParameters.keySet()) } 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 98def612de..fd698d486f 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 @@ -22,7 +22,9 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.bpmn.common.resource.InstanceResourceList import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory +import org.onap.so.bpmn.core.domain.GroupResource import org.onap.so.bpmn.infrastructure.properties.BPMNProperties import org.apache.commons.lang3.StringUtils import org.apache.http.HttpResponse @@ -87,6 +89,16 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ logger.trace("Exit preProcessRequest ") } + // this method will convert resource list to instance_resource_list + void prepareInstanceResourceList(DelegateExecution execution) { + + String uuiRequest = execution.getVariable("uuiRequest") + List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList") + List<Resource> instanceResourceList = InstanceResourceList.getInstanceResourceList(sequencedResourceList, uuiRequest) + + execution.setVariable("instanceResourceList", instanceResourceList) + } + public void sequenceResoure(DelegateExecution execution) { logger.trace("Start sequenceResoure Process ") @@ -117,6 +129,22 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ if (StringUtils.containsIgnoreCase(resource.getModelInfo().getModelName(), resourceType)) { sequencedResourceList.add(resource) + // 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{ V1{G1, G1, G2}} + if (resource instanceof VnfResource) { + if (resource.getGroups() != null) { + String[] grpSequence = resource.getGroupOrder().split(",") + for (String grpType in grpSequence) { + for (GroupResource gResource in resource.getGroups()) { + if (StringUtils.containsIgnoreCase(gResource.getModelInfo().getModelName(), grpType)) { + sequencedResourceList.add(gResource) + } + } + } + } + } if (resource instanceof NetworkResource) { networkResourceList.add(resource) } @@ -126,7 +154,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ } else { //define sequenced resource list, we deploy vf first and then network and then ar - //this is defaule sequence + //this is default sequence List<VnfResource> vnfResourceList = new ArrayList<VnfResource>() List<AllottedResource> arResourceList = new ArrayList<AllottedResource>() @@ -181,11 +209,11 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ public void getCurrentResoure(DelegateExecution execution){ logger.trace("Start getCurrentResoure Process ") def currentIndex = execution.getVariable("currentResourceIndex") - List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList") - Resource currentResource = sequencedResourceList.get(currentIndex) + List<Resource> instanceResourceList = execution.getVariable("instanceResourceList") + Resource currentResource = instanceResourceList.get(currentIndex) execution.setVariable("resourceType", currentResource.getModelInfo().getModelName()) - logger.info("Now we deal with resouce:" + currentResource.getModelInfo().getModelName()) - logger.trace("COMPLETED getCurrentResoure Process ") + logger.info("Now we deal with resource:" + currentResource.getModelInfo().getModelName()) + logger.trace("COMPLETED getCurrentResource Process ") } public void parseNextResource(DelegateExecution execution){ @@ -193,8 +221,8 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ def currentIndex = execution.getVariable("currentResourceIndex") def nextIndex = currentIndex + 1 execution.setVariable("currentResourceIndex", nextIndex) - List<String> sequencedResourceList = execution.getVariable("sequencedResourceList") - if(nextIndex >= sequencedResourceList.size()){ + List<Resource> instanceResourceList = execution.getVariable("instanceResourceList") + if(nextIndex >= instanceResourceList.size()){ execution.setVariable("allResourceFinished", "true") }else{ execution.setVariable("allResourceFinished", "false") @@ -221,7 +249,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ resourceInput.setOperationId(operationId) resourceInput.setOperationType(operationType); def currentIndex = execution.getVariable("currentResourceIndex") - List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList") + List<Resource> sequencedResourceList = execution.getVariable("instanceResourceList") Resource currentResource = sequencedResourceList.get(currentIndex) resourceInput.setResourceModelInfo(currentResource.getModelInfo()); ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") @@ -232,11 +260,16 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ //set the requestInputs from tempalte To Be Done String serviceModelUuid = jsonUtil.getJsonValue(incomingRequest,"service.serviceUuid") String serviceParameters = jsonUtil.getJsonValue(incomingRequest, "service.parameters") - String resourceParameters = ResourceRequestBuilder.buildResourceRequestParameters(execution, serviceModelUuid, resourceCustomizationUuid, serviceParameters) + Map<String, Object> currentVFData = (Map) execution.getVariable("currentVFData"); + if (null == currentVFData) { + currentVFData = new HashMap<>(); + } + String resourceParameters = ResourceRequestBuilder.buildResourceRequestParameters(execution, serviceModelUuid, resourceCustomizationUuid, serviceParameters, currentVFData) resourceInput.setResourceParameters(resourceParameters) resourceInput.setRequestsInputs(incomingRequest) execution.setVariable("resourceInput", resourceInput.toString()) execution.setVariable("resourceModelUUID", resourceInput.getResourceModelInfo().getModelUuid()) + execution.setVariable("currentVFData",currentVFData); logger.trace("COMPLETED prepareResourceRecipeRequest Process ") } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClient.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClient.java index 94ceddae97..2ababac7e3 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClient.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClient.java @@ -24,11 +24,17 @@ 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.Execution; +import org.onap.aai.domain.yang.v13.Metadatum; +import org.onap.so.bpmn.common.recipe.ResourceInput; +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder; +import org.onap.so.bpmn.core.json.JsonUtils; import org.onap.so.bpmn.infrastructure.pnf.dmaap.DmaapClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.HashMap; +import java.util.Optional; @Component public class InformDmaapClient implements JavaDelegate { @@ -41,8 +47,25 @@ public class InformDmaapClient implements JavaDelegate { String pnfCorrelationId = (String) execution.getVariable(ExecutionVariableNames.PNF_CORRELATION_ID); RuntimeService runtimeService = execution.getProcessEngineServices().getRuntimeService(); String processBusinessKey = execution.getProcessBusinessKey(); - dmaapClient.registerForUpdate(pnfCorrelationId, () -> runtimeService.createMessageCorrelation("WorkflowMessage") - .processInstanceBusinessKey(processBusinessKey).correlateWithResult()); + HashMap<String, String> updateInfo = createUpdateInfo(execution); + updateInfo.put("pnfCorrelationId", pnfCorrelationId); + dmaapClient + .registerForUpdate(pnfCorrelationId, + () -> runtimeService.createMessageCorrelation("WorkflowMessage") + .processInstanceBusinessKey(processBusinessKey).correlateWithResult(), + Optional.of(updateInfo)); + } + + private HashMap<String, String> createUpdateInfo(DelegateExecution execution) { + HashMap<String, String> map = new HashMap(); + + ResourceInput resourceInputObj = ResourceRequestBuilder + + .getJsonObject((String) execution.getVariable("resourceInput"), ResourceInput.class); + map.put("globalSubscriberID", resourceInputObj.getGlobalSubscriberId()); + map.put("serviceType", resourceInputObj.getServiceType()); + map.put("serviceInstanceId", resourceInputObj.getServiceInstanceId()); + return map; } @Autowired diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/DmaapClient.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/DmaapClient.java index fbf86cc411..d513684659 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/DmaapClient.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/DmaapClient.java @@ -20,9 +20,13 @@ package org.onap.so.bpmn.infrastructure.pnf.dmaap; +import java.util.HashMap; +import java.util.Optional; + public interface DmaapClient { - void registerForUpdate(String pnfCorrelationId, Runnable informConsumer); + void registerForUpdate(String pnfCorrelationId, Runnable informConsumer, + Optional<HashMap<String, String>> updateInfo); Runnable unregister(String pnfCorrelationId); } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClient.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClient.java index 96562fe90f..9f8a456002 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClient.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClient.java @@ -23,9 +23,7 @@ package org.onap.so.bpmn.infrastructure.pnf.dmaap; import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; @@ -40,6 +38,10 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.AAIObjectType; @Component public class PnfEventReadyDmaapClient implements DmaapClient { @@ -53,6 +55,8 @@ public class PnfEventReadyDmaapClient implements DmaapClient { private volatile ScheduledThreadPoolExecutor executor; private volatile boolean dmaapThreadListenerIsRunning; + public volatile List<HashMap<String, String>> updateInfoMap; + @Autowired public PnfEventReadyDmaapClient(Environment env) { httpClient = HttpClientBuilder.create().build(); @@ -64,11 +68,19 @@ public class PnfEventReadyDmaapClient implements DmaapClient { .port(env.getProperty("pnf.dmaap.port", Integer.class)).path(env.getProperty("pnf.dmaap.topicName")) .path(env.getProperty("pnf.dmaap.consumerGroup")).path(env.getProperty("pnf.dmaap.consumerId")) .build()); + updateInfoMap = new ArrayList<>(); } @Override - public synchronized void registerForUpdate(String pnfCorrelationId, Runnable informConsumer) { + public synchronized void registerForUpdate(String pnfCorrelationId, Runnable informConsumer, + Optional<HashMap<String, String>> updateInfo) { logger.debug("registering for pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId); + HashMap<String, String> map = updateInfo.get(); + if (map != null && map.size() > 0) { + synchronized (updateInfoMap) { + updateInfoMap.add(map); + } + } pnfCorrelationIdToThreadMap.put(pnfCorrelationId, informConsumer); if (!dmaapThreadListenerIsRunning) { startDmaapThreadListener(); @@ -78,7 +90,17 @@ public class PnfEventReadyDmaapClient implements DmaapClient { @Override public synchronized Runnable unregister(String pnfCorrelationId) { logger.debug("unregistering from pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId); - Runnable runnable = pnfCorrelationIdToThreadMap.remove(pnfCorrelationId); + Runnable runnable = runnable = pnfCorrelationIdToThreadMap.remove(pnfCorrelationId); + synchronized (updateInfoMap) { + for (int i = updateInfoMap.size() - 1; i >= 0; i--) { + if (!updateInfoMap.get(i).containsKey("pnfCorrelationId")) + continue; + String id = updateInfoMap.get(i).get("pnfCorrelationId"); + if (id != pnfCorrelationId) + continue; + updateInfoMap.remove(i); + } + } if (pnfCorrelationIdToThreadMap.isEmpty()) { stopDmaapThreadListener(); } @@ -111,7 +133,16 @@ public class PnfEventReadyDmaapClient implements DmaapClient { try { logger.debug("dmaap listener starts listening pnf ready dmaap topic"); HttpResponse response = httpClient.execute(getRequest); - getPnfCorrelationIdListFromResponse(response).forEach(this::informAboutPnfReadyIfPnfCorrelationIdFound); + List<String> idList = getPnfCorrelationIdListFromResponse(response); + + if (idList != null && idList.size() > 0) { + // send only body of response + registerClientResponse(idList.get(0), EntityUtils.toString(response.getEntity(), "UTF-8")); + } + + if (idList != null) { + idList.forEach(this::informAboutPnfReadyIfPnfCorrelationIdFound); + } } catch (IOException e) { logger.error("Exception caught during sending rest request to dmaap for listening event topic", e); } finally { @@ -136,5 +167,36 @@ public class PnfEventReadyDmaapClient implements DmaapClient { runnable.run(); } } + + private void registerClientResponse(String pnfCorrelationId, String response) { + + String customerId = null; + String serviceType = null; + String serId = null; + synchronized (updateInfoMap) { + for (HashMap<String, String> map : updateInfoMap) { + if (!map.containsKey("pnfCorrelationId")) + continue; + if (pnfCorrelationId != map.get("pnfCorrelationId")) + continue; + if (!map.containsKey("globalSubscriberID")) + continue; + if (!map.containsKey("serviceType")) + continue; + if (!map.containsKey("serviceInstanceId")) + continue; + customerId = map.get("pnfCorrelationId"); + serviceType = map.get("serviceType"); + serId = map.get("serviceInstanceId"); + } + } + if (customerId == null || serviceType == null || serId == null) + return; + AAIResourcesClient client = new AAIResourcesClient(); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE_METADATA, customerId, + serviceType, serId); + client.update(uri, response); + } + } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResourceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResourceTest.groovy index 8dde45be81..e547981b2d 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResourceTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResourceTest.groovy @@ -27,6 +27,7 @@ import org.junit.Test import org.mockito.MockitoAnnotations import org.onap.so.bpmn.common.recipe.ResourceInput import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +import org.onap.so.bpmn.core.json.JsonUtils import static org.mockito.Mockito.* /** @@ -106,6 +107,46 @@ class CreateSDNCNetworkResourceTest extends GroovyTestCase { return resourceInputObj } + private ResourceInput getUpdateResInputObj(String modelName) { + + String resourceInput = "{\n" + + "\t\"resourceInstanceName\": \"SotnFc-wan-connection_wanconnection-37\",\n" + + "\t\"resourceInstanceDes\": null,\n" + + "\t\"globalSubscriberId\": \"sdwandemo\",\n" + + "\t\"serviceType\": \"CCVPN\",\n" + + "\t\"operationId\": \"df3387b5-4fbf-41bd-82a0-13a955ac178a\",\n" + + "\t\"serviceModelInfo\": {\n" + + "\t\t\"modelName\": \"WanConnectionSvc03\",\n" + + "\t\t\"modelUuid\": \"198b066c-0771-4157-9594-1824adfdda7e\",\n" + + "\t\t\"modelInvariantUuid\": \"43fb5165-7d03-4009-8951-a8f45d3f0148\",\n" + + "\t\t\"modelVersion\": \"1.0\",\n" + + "\t\t\"modelCustomizationUuid\": \"\",\n" + + "\t\t\"modelCustomizationName\": \"\",\n" + + "\t\t\"modelInstanceName\": \"\",\n" + + "\t\t\"modelType\": \"\"\n" + + "\t},\n" + + "\t\"resourceModelInfo\": {\n" + + "\t\t\"modelName\": \"" + + modelName + + "\",\n" + + "\t\t\"modelUuid\": \"6a0bf88b-343c-415b-88c1-6f73702452c4\",\n" + + "\t\t\"modelInvariantUuid\": \"50bc3415-2e01-4e50-a9e1-ec9584599bb3\",\n" + + "\t\t\"modelCustomizationUuid\": \"b205d620-84bd-4058-afa0-e3aeee8bb712\",\n" + + "\t\t\"modelCustomizationName\": \"\",\n" + + "\t\t\"modelInstanceName\": \"SotnFc-wan-connection 0\",\n" + + "\t\t\"modelType\": \"\"\n" + + "\t},\n" + + "\t\"resourceInstancenUuid\": null,\n" + + "\t\"resourceParameters\": \"{\\n\\\"locationConstraints\\\":[],\\n\\\"requestInputs\\\":{\\\"sotnfcspecwanconnection0_route-objective-function\\\":null,\\\"sotnfcspecwanconnection0_colorAware\\\":null,\\\"3rdctlspecwanconnection0_thirdPartyAdaptorRpc\\\":null,\\\"sotnfcspecwanconnection0_couplingFlag\\\":null,\\\"sotnfcspecwanconnection0_pbs\\\":null,\\\"3rdctlspecwanconnection0_thirdPartySdncId\\\":null,\\\"sotnfcspecwanconnection0_cbs\\\":null,\\\"3rdctlspecwanconnection0_thirdpartySdncName\\\":null,\\\"sotnfcspecwanconnection0_total-size\\\":null,\\\"3rdctlspecwanconnection0_templateFileName\\\":\\\"sotn_create_zte_template.json\\\",\\\"fcwanconnection0_type\\\":null,\\\"sotnfcspecwanconnection0_cir\\\":null,\\\"fcwanconnection0_uuid\\\":null,\\\"sotnfcspecwanconnection0_diversity-policy\\\":null,\\\"nf_naming\\\":true,\\\"multi_stage_design\\\":false,\\\"availability_zone_max_count\\\":1,\\\"3rdctlspecwanconnection0_restapiUrl\\\":\\\"http://10.80.80.21:8443/restconf/operations/ZTE-API-ConnectivityService:create-connectivity-service\\\",\\\"max_instances\\\":null,\\\"sotnfcspecwanconnection0_reroute\\\":null,\\\"fcwanconnection0_name\\\":null,\\\"sotnfcspecwanconnection0_dualLink\\\":null,\\\"min_instances\\\":null,\\\"sotnfcspecwanconnection0_pir\\\":null,\\\"sotnfcspecwanconnection0_service-type\\\":null}\\n}\",\n" + + "\t\"operationType\": \"createInstance\",\n" + + "\t\"serviceInstanceId\": \"ffa07ae4-f820-45af-9439-1416b3bc1d39\",\n" + + "\t\"requestsInputs\": \"{\\r\\n\\t\\\"service\\\": {\\r\\n\\t\\t\\\"name\\\": \\\"wanconnection-37\\\",\\r\\n\\t\\t\\\"description\\\": \\\"deafe\\\",\\r\\n\\t\\t\\\"serviceInvariantUuid\\\": \\\"43fb5165-7d03-4009-8951-a8f45d3f0148\\\",\\r\\n\\t\\t\\\"serviceUuid\\\": \\\"198b066c-0771-4157-9594-1824adfdda7e\\\",\\r\\n\\t\\t\\\"globalSubscriberId\\\": \\\"sdwandemo\\\",\\r\\n\\t\\t\\\"serviceType\\\": \\\"CCVPN\\\",\\r\\n\\t\\t\\\"parameters\\\": {\\r\\n\\t\\t\\t\\\"resources\\\": [\\r\\n\\t\\t\\t],\\r\\n\\t\\t\\t\\\"requestInputs\\\": {\\r\\n\\t\\t\\t\\t\\\"sotnfcwanconnection0_3rdctlspecwanconnection0_restapiUrl\\\": \\\"http://10.80.80.21:8443/restconf/operations/ZTE-API-ConnectivityService:create-connectivity-service\\\",\\r\\n\\t\\t\\t\\t\\\"sotnfcwanconnection0_3rdctlspecwanconnection0_templateFileName\\\": \\\"sotn_create_zte_template.json\\\",\\r\\n\\t\\t\\t\\t\\\"sdwanfcwanconnection0_3rdctlspecwanconnection0_restapiUrl\\\": \\\"http://10.80.80.21:8443/restconf/operations/ZTE-API-ConnectivityService:create-connectivity-service\\\",\\r\\n\\t\\t\\t\\t\\\"sdwanfcwanconnection0_3rdctlspecwanconnection0_templateFileName\\\": \\\"sdwan_create_zte_template.json\\\",\\\"ont_ont_manufacturer\\\":\\\"huawei\\\",\\\"ont_ont_serial_num\\\":\\\"123\\\"\\r\\n\\t\\t\\t}\\r\\n\\t\\t}\\r\\n\\t}\\r\\n}\"\n" + + "}" + + ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) + return resourceInputObj + } + @Test void testAfterCreateSDNCCall() { init() @@ -132,4 +173,30 @@ class CreateSDNCNetworkResourceTest extends GroovyTestCase { def instanceId = response."response-data"."RequestData"."output"."network-response-information"."instance-id" return instanceId } + + @Test + void testUpdateResourceInput() { + init() + + def execution = getExecutionDelegate("OLT") + CreateSDNCNetworkResource createSDNCNetworkResource = new CreateSDNCNetworkResource() + def inputObject = createSDNCNetworkResource.updateResourceInput(execution) + + println(inputObject.getResourceParameters()) + assert JsonUtils.jsonElementExist(inputObject.getResourceParameters(), "requestInputs.SVLAN") + assert JsonUtils.jsonElementExist(inputObject.getResourceParameters(), "requestInputs.CVLAN") + assert JsonUtils.jsonElementExist(inputObject.getResourceParameters(), "requestInputs.manufacturer") + assert JsonUtils.jsonElementExist(inputObject.getResourceParameters(), "requestInputs.ONTSN") + } + + private ExecutionEntity getExecutionDelegate(String modelName) { + def input = getUpdateResInputObj(modelName) + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable(Prefix + "sdncCreateReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "SuccessIndicator")).thenReturn("false") + when(mockExecution.getVariable("isActivateRequired")).thenReturn("true") + when(mockExecution.getVariable("CRENWKI_createSDNCResponse")).thenReturn(sdncAdapterWorkflowResponse) + when(mockExecution.getVariable(Prefix + "resourceInput")).thenReturn(input.toString()) + return mockExecution + } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CancelDmaapSubscriptionTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CancelDmaapSubscriptionTest.java index e755214362..bfaf9cfee0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CancelDmaapSubscriptionTest.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CancelDmaapSubscriptionTest.java @@ -42,7 +42,7 @@ public class CancelDmaapSubscriptionTest { .thenReturn(TEST_PNF_CORRELATION_ID); when(delegateExecution.getProcessBusinessKey()).thenReturn("testBusinessKey"); dmaapClientTest.registerForUpdate("testPnfCorrelationId", () -> { - }); + }, null); // when delegate.execute(delegateExecution); // then diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/DmaapClientTestImpl.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/DmaapClientTestImpl.java index 19ba18f6de..2634f03d4b 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/DmaapClientTestImpl.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/DmaapClientTestImpl.java @@ -21,7 +21,9 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate; import org.onap.so.bpmn.infrastructure.pnf.dmaap.DmaapClient; +import java.util.HashMap; import java.util.Objects; +import java.util.Optional; public class DmaapClientTestImpl implements DmaapClient { @@ -29,7 +31,8 @@ public class DmaapClientTestImpl implements DmaapClient { private Runnable informConsumer; @Override - public void registerForUpdate(String pnfCorrelationId, Runnable informConsumer) { + public void registerForUpdate(String pnfCorrelationId, Runnable informConsumer, + Optional<HashMap<String, String>> updateInfo) { this.pnfCorrelationId = pnfCorrelationId; this.informConsumer = informConsumer; } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java index df060ed014..93a71b31ec 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java @@ -34,10 +34,12 @@ import org.camunda.bpm.engine.runtime.MessageCorrelationBuilder; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; +import org.onap.so.bpmn.common.recipe.ResourceInput; +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder; public class InformDmaapClientTest { @Before - public void setUp() throws Exception { + public void setUp() { informDmaapClient = new InformDmaapClient(); dmaapClientTest = new DmaapClientTestImpl(); informDmaapClient.setDmaapClient(dmaapClientTest); @@ -53,7 +55,7 @@ public class InformDmaapClientTest { private MessageCorrelationBuilder messageCorrelationBuilder; @Test - public void shouldSendListenerToDmaapClient() throws Exception { + public void shouldSendListenerToDmaapClient() { // when informDmaapClient.execute(delegateExecution); // then @@ -63,7 +65,7 @@ public class InformDmaapClientTest { } @Test - public void shouldSendListenerToDmaapClientAndSendMessageToCamunda() throws Exception { + public void shouldSendListenerToDmaapClientAndSendMessageToCamunda() { // when informDmaapClient.execute(delegateExecution); dmaapClientTest.getInformConsumer().run(); @@ -74,11 +76,41 @@ public class InformDmaapClientTest { inOrder.verify(messageCorrelationBuilder).correlateWithResult(); } + private ResourceInput getUpdateResInputObj(String modelName) { + + String resourceInput = "{\n" + "\t\"resourceInstanceName\": \"SotnFc-wan-connection_wanconnection-37\",\n" + + "\t\"resourceInstanceDes\": null,\n" + "\t\"globalSubscriberId\": \"sdwandemo\",\n" + + "\t\"serviceType\": \"CCVPN\",\n" + "\t\"operationId\": \"df3387b5-4fbf-41bd-82a0-13a955ac178a\",\n" + + "\t\"serviceModelInfo\": {\n" + "\t\t\"modelName\": \"WanConnectionSvc03\",\n" + + "\t\t\"modelUuid\": \"198b066c-0771-4157-9594-1824adfdda7e\",\n" + + "\t\t\"modelInvariantUuid\": \"43fb5165-7d03-4009-8951-a8f45d3f0148\",\n" + + "\t\t\"modelVersion\": \"1.0\",\n" + "\t\t\"modelCustomizationUuid\": \"\",\n" + + "\t\t\"modelCustomizationName\": \"\",\n" + "\t\t\"modelInstanceName\": \"\",\n" + + "\t\t\"modelType\": \"\"\n" + "\t},\n" + "\t\"resourceModelInfo\": {\n" + "\t\t\"modelName\": \"" + + modelName + "\",\n" + "\t\t\"modelUuid\": \"6a0bf88b-343c-415b-88c1-6f73702452c4\",\n" + + "\t\t\"modelInvariantUuid\": \"50bc3415-2e01-4e50-a9e1-ec9584599bb3\",\n" + + "\t\t\"modelCustomizationUuid\": \"b205d620-84bd-4058-afa0-e3aeee8bb712\",\n" + + "\t\t\"modelCustomizationName\": \"\",\n" + + "\t\t\"modelInstanceName\": \"SotnFc-wan-connection 0\",\n" + "\t\t\"modelType\": \"\"\n" + "\t},\n" + + "\t\"resourceInstancenUuid\": null,\n" + + "\t\"resourceParameters\": \"{\\n\\\"locationConstraints\\\":[],\\n\\\"requestInputs\\\":{\\\"sotnfcspecwanconnection0_route-objective-function\\\":null,\\\"sotnfcspecwanconnection0_colorAware\\\":null,\\\"3rdctlspecwanconnection0_thirdPartyAdaptorRpc\\\":null,\\\"sotnfcspecwanconnection0_couplingFlag\\\":null,\\\"sotnfcspecwanconnection0_pbs\\\":null,\\\"3rdctlspecwanconnection0_thirdPartySdncId\\\":null,\\\"sotnfcspecwanconnection0_cbs\\\":null,\\\"3rdctlspecwanconnection0_thirdpartySdncName\\\":null,\\\"sotnfcspecwanconnection0_total-size\\\":null,\\\"3rdctlspecwanconnection0_templateFileName\\\":\\\"sotn_create_zte_template.json\\\",\\\"fcwanconnection0_type\\\":null,\\\"sotnfcspecwanconnection0_cir\\\":null,\\\"fcwanconnection0_uuid\\\":null,\\\"sotnfcspecwanconnection0_diversity-policy\\\":null,\\\"nf_naming\\\":true,\\\"multi_stage_design\\\":false,\\\"availability_zone_max_count\\\":1,\\\"3rdctlspecwanconnection0_restapiUrl\\\":\\\"http://10.80.80.21:8443/restconf/operations/ZTE-API-ConnectivityService:create-connectivity-service\\\",\\\"max_instances\\\":null,\\\"sotnfcspecwanconnection0_reroute\\\":null,\\\"fcwanconnection0_name\\\":null,\\\"sotnfcspecwanconnection0_dualLink\\\":null,\\\"min_instances\\\":null,\\\"sotnfcspecwanconnection0_pir\\\":null,\\\"sotnfcspecwanconnection0_service-type\\\":null}\\n}\",\n" + + "\t\"operationType\": \"createInstance\",\n" + + "\t\"serviceInstanceId\": \"ffa07ae4-f820-45af-9439-1416b3bc1d39\",\n" + + "\t\"requestsInputs\": \"{\\r\\n\\t\\\"service\\\": {\\r\\n\\t\\t\\\"name\\\": \\\"wanconnection-37\\\",\\r\\n\\t\\t\\\"description\\\": \\\"deafe\\\",\\r\\n\\t\\t\\\"serviceInvariantUuid\\\": \\\"43fb5165-7d03-4009-8951-a8f45d3f0148\\\",\\r\\n\\t\\t\\\"serviceUuid\\\": \\\"198b066c-0771-4157-9594-1824adfdda7e\\\",\\r\\n\\t\\t\\\"globalSubscriberId\\\": \\\"sdwandemo\\\",\\r\\n\\t\\t\\\"serviceType\\\": \\\"CCVPN\\\",\\r\\n\\t\\t\\\"parameters\\\": {\\r\\n\\t\\t\\t\\\"resources\\\": [\\r\\n\\t\\t\\t],\\r\\n\\t\\t\\t\\\"requestInputs\\\": {\\r\\n\\t\\t\\t\\t\\\"sotnfcwanconnection0_3rdctlspecwanconnection0_restapiUrl\\\": \\\"http://10.80.80.21:8443/restconf/operations/ZTE-API-ConnectivityService:create-connectivity-service\\\",\\r\\n\\t\\t\\t\\t\\\"sotnfcwanconnection0_3rdctlspecwanconnection0_templateFileName\\\": \\\"sotn_create_zte_template.json\\\",\\r\\n\\t\\t\\t\\t\\\"sdwanfcwanconnection0_3rdctlspecwanconnection0_restapiUrl\\\": \\\"http://10.80.80.21:8443/restconf/operations/ZTE-API-ConnectivityService:create-connectivity-service\\\",\\r\\n\\t\\t\\t\\t\\\"sdwanfcwanconnection0_3rdctlspecwanconnection0_templateFileName\\\": \\\"sdwan_create_zte_template.json\\\",\\\"ont_ont_manufacturer\\\":\\\"huawei\\\",\\\"ont_ont_serial_num\\\":\\\"123\\\"\\r\\n\\t\\t\\t}\\r\\n\\t\\t}\\r\\n\\t}\\r\\n}\"\n" + + "}"; + + ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class); + return resourceInputObj; + } + private DelegateExecution mockDelegateExecution() { + ResourceInput input = getUpdateResInputObj("OLT"); DelegateExecution delegateExecution = mock(DelegateExecution.class); + when(delegateExecution.getVariable(eq(ExecutionVariableNames.PNF_CORRELATION_ID))) .thenReturn("testPnfCorrelationId"); when(delegateExecution.getProcessBusinessKey()).thenReturn("testBusinessKey"); + when(delegateExecution.getVariable("resourceInput")).thenReturn(input.toString()); ProcessEngineServices processEngineServices = mock(ProcessEngineServices.class); when(delegateExecution.getProcessEngineServices()).thenReturn(processEngineServices); RuntimeService runtimeService = mock(RuntimeService.class); @@ -86,6 +118,7 @@ public class InformDmaapClientTest { messageCorrelationBuilder = mock(MessageCorrelationBuilder.class); when(runtimeService.createMessageCorrelation(any())).thenReturn(messageCorrelationBuilder); when(messageCorrelationBuilder.processInstanceBusinessKey(any())).thenReturn(messageCorrelationBuilder); + return delegateExecution; } } diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateResources.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateResources.bpmn index dc2cf9b676..75767929aa 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateResources.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateResources.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.11.3" 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="1.16.2" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"> <bpmn2:process id="DoCreateResourcesV3" name="DoCreateResourcesV3" isExecutable="true"> <bpmn2:startEvent id="createSI_startEvent" name="Start Flow"> <bpmn2:outgoing>SequenceFlow_1qiiycn</bpmn2:outgoing> @@ -7,17 +7,17 @@ <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 DoCreateResources() dcsi.preProcessRequest(execution) -]]></bpmn2:script> +</bpmn2:script> </bpmn2:scriptTask> <bpmn2:scriptTask id="ScriptTask_1xdjlzm" name="Post Config Service Instance Creation" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_16nxl6h</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_0epxs3b</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def csi = new DoCreateResources() -csi.postConfigRequest(execution)]]></bpmn2:script> +csi.postConfigRequest(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:serviceTask id="Task_0io5qby" name="Call Sync SDNC service Create " camunda:class="org.onap.so.bpmn.infrastructure.workflow.serviceTask.SdncServiceTopologyOperationTask"> <bpmn2:incoming>SequenceFlow_0k0f7lm</bpmn2:incoming> @@ -27,9 +27,9 @@ csi.postConfigRequest(execution)]]></bpmn2:script> <bpmn2:scriptTask id="ScriptTask_1y0los4" name="Sequence Resource" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_1hbesp9</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_13d9g1n</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def ddsi = new DoCreateResources() -ddsi.sequenceResoure(execution)]]></bpmn2:script> +ddsi.sequenceResoure(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:sequenceFlow id="SequenceFlow_13d9g1n" sourceRef="ScriptTask_1y0los4" targetRef="ExclusiveGateway_07rr3wp" /> <bpmn2:exclusiveGateway id="ExclusiveGateway_0n9y4du" name="All ResourceFinished?" default="SequenceFlow_0q6uy30"> @@ -41,18 +41,18 @@ ddsi.sequenceResoure(execution)]]></bpmn2:script> <bpmn2:scriptTask id="ScriptTask_0y4u2ty" name="Parse Next Resource" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_13c7bhn</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_1jenxlp</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def ddsi = new DoCreateResources() -ddsi.parseNextResource(execution)]]></bpmn2:script> +ddsi.parseNextResource(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:sequenceFlow id="SequenceFlow_1jenxlp" sourceRef="ScriptTask_0y4u2ty" targetRef="ExclusiveGateway_0n9y4du" /> <bpmn2:scriptTask id="ScriptTask_0l4nkqr" name="Get Current Resource" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_0q6uy30</bpmn2:incoming> - <bpmn2:incoming>SequenceFlow_1qozd66</bpmn2:incoming> + <bpmn2:incoming>SequenceFlow_1obf0cq</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_0uiygod</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def ddsi = new DoCreateResources() -ddsi.getCurrentResoure(execution)]]></bpmn2:script> +ddsi.getCurrentResoure(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:exclusiveGateway id="ExclusiveGateway_07rr3wp" name="Is SDN-C Service Needed" default="SequenceFlow_18wj44x"> <bpmn2:incoming>SequenceFlow_13d9g1n</bpmn2:incoming> @@ -63,16 +63,16 @@ ddsi.getCurrentResoure(execution)]]></bpmn2:script> <bpmn2:scriptTask id="Task_0qlkmvt" name="Prepare resource recipe Request" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_0uiygod</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_1u9k0dm</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def ddsi = new DoCreateResources() -ddsi.prepareResourceRecipeRequest(execution)]]></bpmn2:script> +ddsi.prepareResourceRecipeRequest(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:scriptTask id="Task_12ghoph" name="Execute Resource Recipe" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_1u9k0dm</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_13c7bhn</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def ddsi = new DoCreateResources() -ddsi.executeResourceRecipe(execution)]]></bpmn2:script> +ddsi.executeResourceRecipe(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:intermediateThrowEvent id="IntermediateThrowEvent_0bq4fxs" name="Go to StratPrepareService"> <bpmn2:incoming>SequenceFlow_0w9t6tc</bpmn2:incoming> @@ -86,7 +86,7 @@ ddsi.executeResourceRecipe(execution)]]></bpmn2:script> <bpmn2:linkEventDefinition name="ResourceLoop" /> </bpmn2:intermediateThrowEvent> <bpmn2:sequenceFlow id="SequenceFlow_1vprtt9" name="yes" sourceRef="ExclusiveGateway_07rr3wp" targetRef="Task_1blaq0f"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression"><![CDATA[#{(execution.getVariable("isContainsWanResource" ) == "true" )}]]></bpmn2:conditionExpression> + <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression">#{(execution.getVariable("isContainsWanResource" ) == "true" )}</bpmn2:conditionExpression> </bpmn2:sequenceFlow> <bpmn2:intermediateCatchEvent id="IntermediateCatchEvent_05dus9b" name="StartPrepareResource"> <bpmn2:outgoing>SequenceFlow_1hbesp9</bpmn2:outgoing> @@ -98,12 +98,12 @@ ddsi.executeResourceRecipe(execution)]]></bpmn2:script> <bpmn2:linkEventDefinition name="ResourceLoop" /> </bpmn2:intermediateCatchEvent> <bpmn2:sequenceFlow id="SequenceFlow_16nxl6h" name="yes" sourceRef="ExclusiveGateway_0n9y4du" targetRef="ScriptTask_1xdjlzm"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression"><![CDATA[#{(execution.getVariable("allResourceFinished" ) == "true" )}]]></bpmn2:conditionExpression> + <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression">#{(execution.getVariable("allResourceFinished" ) == "true" )}</bpmn2:conditionExpression> </bpmn2:sequenceFlow> <bpmn2:sequenceFlow id="SequenceFlow_0uiygod" sourceRef="ScriptTask_0l4nkqr" targetRef="Task_0qlkmvt" /> <bpmn2:sequenceFlow id="SequenceFlow_1u9k0dm" sourceRef="Task_0qlkmvt" targetRef="Task_12ghoph" /> <bpmn2:sequenceFlow id="SequenceFlow_13c7bhn" sourceRef="Task_12ghoph" targetRef="ScriptTask_0y4u2ty" /> - <bpmn2:sequenceFlow id="SequenceFlow_1qozd66" sourceRef="IntermediateCatchEvent_02bah5m" targetRef="ScriptTask_0l4nkqr" /> + <bpmn2:sequenceFlow id="SequenceFlow_1qozd66" sourceRef="IntermediateCatchEvent_02bah5m" targetRef="Task_0g7zo7b" /> <bpmn2:endEvent id="EndEvent_1ddg1di"> <bpmn2:incoming>SequenceFlow_0epxs3b</bpmn2:incoming> </bpmn2:endEvent> @@ -119,9 +119,9 @@ ddsi.executeResourceRecipe(execution)]]></bpmn2:script> <bpmn2:scriptTask id="ScriptTask_1648adp" name="Log / Print Unexpected Error" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_0gr9xqj</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_0a6l29p</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* + <bpmn2:script>import org.onap.so.bpmn.common.scripts.* ExceptionUtil ex = new ExceptionUtil() -ex.processJavaException(execution)]]></bpmn2:script> +ex.processJavaException(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:sequenceFlow id="SequenceFlow_0gr9xqj" name="" sourceRef="StartEvent_0x7o2ug" targetRef="ScriptTask_1648adp" /> <bpmn2:sequenceFlow id="SequenceFlow_0a6l29p" name="" sourceRef="ScriptTask_1648adp" targetRef="EndEvent_0lgdyyb" /> @@ -129,11 +129,19 @@ ex.processJavaException(execution)]]></bpmn2:script> <bpmn2:scriptTask id="Task_1blaq0f" name="Prepare SDNC service Create" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_1vprtt9</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_0k0f7lm</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.infrastructure.scripts.* + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* def ddsi = new DoCreateResources() -ddsi.prepareServiceTopologyRequest(execution)]]></bpmn2:script> +ddsi.prepareServiceTopologyRequest(execution)</bpmn2:script> </bpmn2:scriptTask> <bpmn2:sequenceFlow id="SequenceFlow_0k0f7lm" sourceRef="Task_1blaq0f" targetRef="Task_0io5qby" /> + <bpmn2:sequenceFlow id="SequenceFlow_1obf0cq" sourceRef="Task_0g7zo7b" targetRef="ScriptTask_0l4nkqr" /> + <bpmn2:scriptTask id="Task_0g7zo7b" name="Prepare Instnace ResourceList" scriptFormat="groovy"> + <bpmn2:incoming>SequenceFlow_1qozd66</bpmn2:incoming> + <bpmn2:outgoing>SequenceFlow_1obf0cq</bpmn2:outgoing> + <bpmn2:script>import org.onap.so.bpmn.infrastructure.scripts.* +def ddsi = new DoCreateResources() +ddsi.prepareInstanceResourceList(execution)</bpmn2:script> + </bpmn2:scriptTask> </bpmn2:process> <bpmn2:error id="Error_2" name="MSOWorkflowException" errorCode="MSOWorkflowException" /> <bpmn2:error id="Error_1" name="java.lang.Exception" errorCode="java.lang.Exception" /> @@ -155,10 +163,10 @@ ddsi.prepareServiceTopologyRequest(execution)]]></bpmn2:script> <dc:Bounds x="1047" y="353" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_11f2zuu_di" bpmnElement="SequenceFlow_11f2zuu"> - <di:waypoint xsi:type="dc:Point" x="1147" y="393" /> - <di:waypoint xsi:type="dc:Point" x="1219" y="393" /> - <di:waypoint xsi:type="dc:Point" x="1219" y="300" /> - <di:waypoint xsi:type="dc:Point" x="1315" y="300" /> + <di:waypoint x="1147" y="393" /> + <di:waypoint x="1219" y="393" /> + <di:waypoint x="1219" y="300" /> + <di:waypoint x="1315" y="300" /> <bpmndi:BPMNLabel> <dc:Bounds x="1189" y="340.5" width="90" height="12" /> </bpmndi:BPMNLabel> @@ -167,8 +175,8 @@ ddsi.prepareServiceTopologyRequest(execution)]]></bpmn2:script> <dc:Bounds x="444" y="260" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_13d9g1n_di" bpmnElement="SequenceFlow_13d9g1n"> - <di:waypoint xsi:type="dc:Point" x="544" y="300" /> - <di:waypoint xsi:type="dc:Point" x="753" y="300" /> + <di:waypoint x="544" y="300" /> + <di:waypoint x="753" y="300" /> <bpmndi:BPMNLabel> <dc:Bounds x="603.5" y="279" width="90" height="12" /> </bpmndi:BPMNLabel> @@ -180,10 +188,10 @@ ddsi.prepareServiceTopologyRequest(execution)]]></bpmn2:script> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0q6uy30_di" bpmnElement="SequenceFlow_0q6uy30"> - <di:waypoint xsi:type="dc:Point" x="954" y="550" /> - <di:waypoint xsi:type="dc:Point" x="954" y="691" /> - <di:waypoint xsi:type="dc:Point" x="246" y="691" /> - <di:waypoint xsi:type="dc:Point" x="246" y="565" /> + <di:waypoint x="954" y="550" /> + <di:waypoint x="954" y="691" /> + <di:waypoint x="246" y="691" /> + <di:waypoint x="246" y="565" /> <bpmndi:BPMNLabel> <dc:Bounds x="593" y="670" width="15" height="12" /> </bpmndi:BPMNLabel> @@ -192,8 +200,8 @@ ddsi.prepareServiceTopologyRequest(execution)]]></bpmn2:script> <dc:Bounds x="728" y="485" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1jenxlp_di" bpmnElement="SequenceFlow_1jenxlp"> - <di:waypoint xsi:type="dc:Point" x="828" y="525" /> - <di:waypoint xsi:type="dc:Point" x="929" y="525" /> + <di:waypoint x="828" y="525" /> + <di:waypoint x="929" y="525" /> <bpmndi:BPMNLabel> <dc:Bounds x="833.5" y="504" width="90" height="12" /> </bpmndi:BPMNLabel> @@ -208,8 +216,8 @@ ddsi.prepareServiceTopologyRequest(execution)]]></bpmn2:script> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_18wj44x_di" bpmnElement="SequenceFlow_18wj44x"> - <di:waypoint xsi:type="dc:Point" x="803" y="300" /> - <di:waypoint xsi:type="dc:Point" x="1315" y="300" /> + <di:waypoint x="803" y="300" /> + <di:waypoint x="1315" y="300" /> <bpmndi:BPMNLabel> <dc:Bounds x="831" y="294" width="15" height="12" /> </bpmndi:BPMNLabel> @@ -227,17 +235,17 @@ ddsi.prepareServiceTopologyRequest(execution)]]></bpmn2:script> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1qiiycn_di" bpmnElement="SequenceFlow_1qiiycn"> - <di:waypoint xsi:type="dc:Point" x="54" y="-189" /> - <di:waypoint xsi:type="dc:Point" x="126" y="-189" /> + <di:waypoint x="54" y="-189" /> + <di:waypoint x="126" y="-189" /> <bpmndi:BPMNLabel> <dc:Bounds x="90" y="-210" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0w9t6tc_di" bpmnElement="SequenceFlow_0w9t6tc"> - <di:waypoint xsi:type="dc:Point" x="226" y="-189" /> - <di:waypoint xsi:type="dc:Point" x="771" y="-189" /> - <di:waypoint xsi:type="dc:Point" x="771" y="-189" /> - <di:waypoint xsi:type="dc:Point" x="1315" y="-189" /> + <di:waypoint x="226" y="-189" /> + <di:waypoint x="771" y="-189" /> + <di:waypoint x="771" y="-189" /> + <di:waypoint x="1315" y="-189" /> <bpmndi:BPMNLabel> <dc:Bounds x="786" y="-195" width="0" height="12" /> </bpmndi:BPMNLabel> @@ -249,9 +257,9 @@ ddsi.prepareServiceTopologyRequest(execution)]]></bpmn2:script> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1vprtt9_di" bpmnElement="SequenceFlow_1vprtt9"> - <di:waypoint xsi:type="dc:Point" x="778" y="325" /> - <di:waypoint xsi:type="dc:Point" x="778" y="393" /> - <di:waypoint xsi:type="dc:Point" x="861" y="394" /> + <di:waypoint x="778" y="325" /> + <di:waypoint x="778" y="393" /> + <di:waypoint x="861" y="394" /> <bpmndi:BPMNLabel> <dc:Bounds x="784" y="353" width="20" height="12" /> </bpmndi:BPMNLabel> @@ -263,49 +271,49 @@ ddsi.prepareServiceTopologyRequest(execution)]]></bpmn2:script> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1hbesp9_di" bpmnElement="SequenceFlow_1hbesp9"> - <di:waypoint xsi:type="dc:Point" x="54" y="300" /> - <di:waypoint xsi:type="dc:Point" x="444" y="300" /> + <di:waypoint x="54" y="300" /> + <di:waypoint x="444" y="300" /> <bpmndi:BPMNLabel> <dc:Bounds x="204" y="279" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="IntermediateCatchEvent_02bah5m_di" bpmnElement="IntermediateCatchEvent_02bah5m"> - <dc:Bounds x="18" y="507" width="36" height="36" /> + <dc:Bounds x="-26" y="507" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="2" y="543" width="73" height="12" /> + <dc:Bounds x="-41" y="543" width="72" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_16nxl6h_di" bpmnElement="SequenceFlow_16nxl6h"> - <di:waypoint xsi:type="dc:Point" x="979" y="525" /> - <di:waypoint xsi:type="dc:Point" x="1119" y="525" /> + <di:waypoint x="979" y="525" /> + <di:waypoint x="1119" y="525" /> <bpmndi:BPMNLabel> <dc:Bounds x="1040" y="504" width="19" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0uiygod_di" bpmnElement="SequenceFlow_0uiygod"> - <di:waypoint xsi:type="dc:Point" x="296" y="525" /> - <di:waypoint xsi:type="dc:Point" x="357" y="525" /> + <di:waypoint x="296" y="525" /> + <di:waypoint x="357" y="525" /> <bpmndi:BPMNLabel> <dc:Bounds x="326.5" y="504" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1u9k0dm_di" bpmnElement="SequenceFlow_1u9k0dm"> - <di:waypoint xsi:type="dc:Point" x="457" y="525" /> - <di:waypoint xsi:type="dc:Point" x="551" y="525" /> + <di:waypoint x="457" y="525" /> + <di:waypoint x="551" y="525" /> <bpmndi:BPMNLabel> <dc:Bounds x="504" y="504" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_13c7bhn_di" bpmnElement="SequenceFlow_13c7bhn"> - <di:waypoint xsi:type="dc:Point" x="651" y="525" /> - <di:waypoint xsi:type="dc:Point" x="728" y="525" /> + <di:waypoint x="651" y="525" /> + <di:waypoint x="728" y="525" /> <bpmndi:BPMNLabel> <dc:Bounds x="689.5" y="504" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1qozd66_di" bpmnElement="SequenceFlow_1qozd66"> - <di:waypoint xsi:type="dc:Point" x="54" y="525" /> - <di:waypoint xsi:type="dc:Point" x="196" y="525" /> + <di:waypoint x="10" y="525" /> + <di:waypoint x="52" y="525" /> <bpmndi:BPMNLabel> <dc:Bounds x="125" y="504" width="0" height="12" /> </bpmndi:BPMNLabel> @@ -317,8 +325,8 @@ ddsi.prepareServiceTopologyRequest(execution)]]></bpmn2:script> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0epxs3b_di" bpmnElement="SequenceFlow_0epxs3b"> - <di:waypoint xsi:type="dc:Point" x="1219" y="525" /> - <di:waypoint xsi:type="dc:Point" x="1315" y="525" /> + <di:waypoint x="1219" y="525" /> + <di:waypoint x="1315" y="525" /> <bpmndi:BPMNLabel> <dc:Bounds x="1267" y="504" width="0" height="12" /> </bpmndi:BPMNLabel> @@ -342,15 +350,15 @@ ddsi.prepareServiceTopologyRequest(execution)]]></bpmn2:script> <dc:Bounds x="511" y="863" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0gr9xqj_di" bpmnElement="SequenceFlow_0gr9xqj"> - <di:waypoint xsi:type="dc:Point" x="443" y="903" /> - <di:waypoint xsi:type="dc:Point" x="511" y="903" /> + <di:waypoint x="443" y="903" /> + <di:waypoint x="511" y="903" /> <bpmndi:BPMNLabel> <dc:Bounds x="387" y="888" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0a6l29p_di" bpmnElement="SequenceFlow_0a6l29p"> - <di:waypoint xsi:type="dc:Point" x="611" y="903" /> - <di:waypoint xsi:type="dc:Point" x="700" y="903" /> + <di:waypoint x="611" y="903" /> + <di:waypoint x="700" y="903" /> <bpmndi:BPMNLabel> <dc:Bounds x="567.5" y="888" width="0" height="12" /> </bpmndi:BPMNLabel> @@ -359,12 +367,19 @@ ddsi.prepareServiceTopologyRequest(execution)]]></bpmn2:script> <dc:Bounds x="861" y="354" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0k0f7lm_di" bpmnElement="SequenceFlow_0k0f7lm"> - <di:waypoint xsi:type="dc:Point" x="961" y="394" /> - <di:waypoint xsi:type="dc:Point" x="1047" y="393" /> + <di:waypoint x="961" y="394" /> + <di:waypoint x="1047" y="393" /> <bpmndi:BPMNLabel> <dc:Bounds x="1004" y="372.5" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_1obf0cq_di" bpmnElement="SequenceFlow_1obf0cq"> + <di:waypoint x="152" y="525" /> + <di:waypoint x="196" y="525" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_0iag9tv_di" bpmnElement="Task_0g7zo7b"> + <dc:Bounds x="52" y="485" width="100" height="80" /> + </bpmndi:BPMNShape> </bpmndi:BPMNPlane> </bpmndi:BPMNDiagram> </bpmn2:definitions> diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/HomingV2.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/HomingV2.java index 513ff74180..4e74e5d414 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/HomingV2.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/HomingV2.java @@ -55,7 +55,7 @@ public class HomingV2 { private boolean isOof(BuildingBlockExecution execution) { for (Map<String, Object> params : execution.getGeneralBuildingBlock().getRequestContext().getRequestParameters() .getUserParams()) { - if (params.containsKey(HOMINGSOLUTION) && params.get(HOMINGSOLUTION).equals("oof")) { + if (params.containsKey(HOMINGSOLUTION) && ("oof").equals(params.get(HOMINGSOLUTION))) { return true; } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/OofHomingV2.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/OofHomingV2.java index 2696313daf..d5a085aba7 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/OofHomingV2.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/OofHomingV2.java @@ -81,6 +81,7 @@ import static org.apache.commons.lang3.StringUtils.isNotBlank; @Component("OofHoming") public class OofHomingV2 { + public static final String ERROR_WHILE_PREPARING_OOF_REQUEST = " Error - while preparing oof request: "; private static final Logger logger = LoggerFactory.getLogger(OofHomingV2.class); private JsonUtils jsonUtils = new JsonUtils(); @Autowired @@ -91,13 +92,9 @@ public class OofHomingV2 { private OofValidator oofValidator; @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: "; @@ -128,7 +125,7 @@ public class OofHomingV2 { OofRequest oofRequest = new OofRequest(); - RequestInfo requestInfo = (RequestInfo) buildRequestInfo(requestId, timeout); + RequestInfo requestInfo = buildRequestInfo(requestId, timeout); oofRequest.setRequestInformation(requestInfo); ServiceInfo serviceInfo = buildServiceInfo(serviceInstance); @@ -157,13 +154,13 @@ public class OofHomingV2 { logger.trace("Completed Oof Homing Call Oof"); } catch (BpmnError e) { - logger.debug(" Error - while preparing oof request: " + e.getStackTrace()); + logger.debug(ERROR_WHILE_PREPARING_OOF_REQUEST + e.getStackTrace()); exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(e.getErrorCode()), e.getMessage()); } catch (BadResponseException e) { - logger.debug(" Error - while preparing oof request: " + e.getStackTrace()); + logger.debug(ERROR_WHILE_PREPARING_OOF_REQUEST + e.getStackTrace()); exceptionUtil.buildAndThrowWorkflowException(execution, 400, e.getMessage()); } catch (Exception e) { - logger.debug(" Error - while preparing oof request: " + e.getStackTrace()); + logger.debug(ERROR_WHILE_PREPARING_OOF_REQUEST + e.getStackTrace()); exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL, "Internal Error - occurred while " + "preparing oof request: " + e + " Stack:" + ExceptionUtils.getFullStackTrace(e)); } 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 2f898b6697..2b9729f7c7 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 @@ -334,6 +334,18 @@ public class SniroHomingV2 { } } } + List<ServiceProxy> serviceProxies = serviceInstance.getServiceProxies(); + if (!serviceProxies.isEmpty()) { + logger.debug("Adding service proxies to placement demands list"); + for (ServiceProxy sp : serviceProxies) { + if (isBlank(sp.getId())) { + sp.setId(UUID.randomUUID().toString()); + } + Demand demand = buildDemand(sp.getId(), sp.getModelInfoServiceProxy()); + addCandidates(sp, demand); + placementDemands.add(demand); + } + } return placementDemands; } @@ -400,6 +412,7 @@ public class SniroHomingV2 { 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>(); @@ -424,7 +437,18 @@ public class SniroHomingV2 { } demand.setExcludedCandidates(cans); } - // TODO support existing candidates + 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) { + 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.setExistingCandidates(cans); + } } /** @@ -462,6 +486,7 @@ public class SniroHomingV2 { List<VpnBondingLink> links = serviceInstance.getVpnBondingLinks(); List<AllottedResource> allottes = serviceInstance.getAllottedResources(); List<GenericVnf> vnfs = serviceInstance.getVnfs(); + List<ServiceProxy> serviceProxies = serviceInstance.getServiceProxies(); logger.debug("Processing placement solution " + i + 1); for (int p = 0; p < placements.length(); p++) { @@ -502,6 +527,12 @@ public class SniroHomingV2 { break search; } } + for (ServiceProxy proxy : serviceProxies) { + if (placement.getString(SERVICE_RESOURCE_ID).equals(proxy.getId())) { + proxy.setServiceInstance(setSolution(solutionInfo, placement)); + break search; + } + } } } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java index 3304d1b113..01bdc09419 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java @@ -481,6 +481,16 @@ public class AAIUpdateTasks { } } + public void updateOrchestrationStatusAssignFabricConfiguration(BuildingBlockExecution execution) { + try { + Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID); + aaiConfigurationResources.updateOrchestrationStatusConfiguration(configuration, + OrchestrationStatus.ASSIGNED); + } catch (Exception ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + } + public void updateOrchestrationStatusActivateFabricConfiguration(BuildingBlockExecution execution) { try { Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID); 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 05d4f56fdc..a37f43727e 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 @@ -85,7 +85,7 @@ public class ExecuteActivity implements JavaDelegate { Map<String, Object> variables = new HashMap<>(); variables.put("buildingBlock", executeBuildingBlock); - variables.put("mso-request-id", requestId); + variables.put(G_REQUEST_ID, requestId); variables.put("retryCount", 1); variables.put("aLaCarte", true); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasks.java index 77898dd5cc..428f5e703d 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasks.java @@ -32,7 +32,6 @@ import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; import org.onap.so.client.adapter.network.mapper.NetworkAdapterObjectMapper; import org.onap.so.client.exception.ExceptionBuilder; -import org.onap.so.client.orchestration.NetworkAdapterResources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -40,7 +39,6 @@ import org.springframework.stereotype.Component; @Component public class NetworkAdapterUpdateTasks { - private static final Logger logger = LoggerFactory.getLogger(NetworkAdapterUpdateTasks.class); @Autowired private ExtractPojosForBB extractPojosForBB; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java index 849465e787..b257e91165 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java @@ -47,7 +47,7 @@ import static org.apache.commons.lang3.StringUtils.*; @Component public class VnfAdapterCreateTasks { - private static final Logger logger = LoggerFactory.getLogger(VnfAdapterCreateTasks.class); + public static final String SDNCQUERY_RESPONSE = "SDNCQueryResponse_"; private static final String VNFREST_REQUEST = "VNFREST_Request"; @Autowired @@ -73,7 +73,7 @@ public class VnfAdapterCreateTasks { try { vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); if (vfModule.getSelflink() != null && !vfModule.getSelflink().isEmpty()) { - sdncVfModuleQueryResponse = execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId()); + sdncVfModuleQueryResponse = execution.getVariable(SDNCQUERY_RESPONSE + vfModule.getVfModuleId()); } else { throw new Exception("Vf Module " + vfModule.getVfModuleId() + " exists in gBuildingBlock but does not have a selflink value"); @@ -109,8 +109,8 @@ public class VnfAdapterCreateTasks { CloudRegion cloudRegion = gBBInput.getCloudRegion(); RequestContext requestContext = gBBInput.getRequestContext(); OrchestrationContext orchestrationContext = gBBInput.getOrchContext(); - String sdncVfModuleQueryResponse = execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId()); - String sdncVnfQueryResponse = execution.getVariable("SDNCQueryResponse_" + genericVnf.getVnfId()); + String sdncVfModuleQueryResponse = execution.getVariable(SDNCQUERY_RESPONSE + vfModule.getVfModuleId()); + String sdncVnfQueryResponse = execution.getVariable(SDNCQUERY_RESPONSE + genericVnf.getVnfId()); CreateVfModuleRequest createVfModuleRequest = vnfAdapterVfModuleResources.createVfModuleRequest( requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, vfModule, diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasks.java index 116dc30d63..5fe80b79f9 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasks.java @@ -42,7 +42,7 @@ import org.springframework.stereotype.Component; @Component public class VnfAdapterDeleteTasks { - private static final Logger logger = LoggerFactory.getLogger(VnfAdapterDeleteTasks.class); + private static final String VNFREST_REQUEST = "VNFREST_Request"; @Autowired 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 bfa76c5053..48426fa725 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 @@ -63,6 +63,7 @@ public class VnfAdapterImpl { private static final String OAM_MANAGEMENT_V4_ADDRESS = "oamManagementV4Address"; private static final String OAM_MANAGEMENT_V6_ADDRESS = "oamManagementV6Address"; private static final String CONTRAIL_NETWORK_POLICY_FQDN_LIST = "contrailNetworkPolicyFqdnList"; + public static final String HEAT_STACK_ID = "heatStackId"; @Autowired private ExtractPojosForBB extractPojosForBB; @@ -77,7 +78,7 @@ public class VnfAdapterImpl { extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); execution.setVariable("mso-request-id", gBBInput.getRequestContext().getMsoRequestId()); execution.setVariable("mso-service-instance-id", serviceInstance.getServiceInstanceId()); - execution.setVariable("heatStackId", null); + execution.setVariable(HEAT_STACK_ID, null); execution.setVariable(CONTRAIL_SERVICE_INSTANCE_FQDN, null); execution.setVariable(OAM_MANAGEMENT_V4_ADDRESS, null); execution.setVariable(OAM_MANAGEMENT_V6_ADDRESS, null); @@ -97,7 +98,7 @@ public class VnfAdapterImpl { String heatStackId = ((CreateVfModuleResponse) vnfRestResponse).getVfModuleStackId(); if (!StringUtils.isEmpty(heatStackId)) { vfModule.setHeatStackId(heatStackId); - execution.setVariable("heatStackId", heatStackId); + execution.setVariable(HEAT_STACK_ID, heatStackId); } Map<String, String> vfModuleOutputs = ((CreateVfModuleResponse) vnfRestResponse).getVfModuleOutputs(); @@ -110,7 +111,7 @@ public class VnfAdapterImpl { Boolean vfModuleDelete = ((DeleteVfModuleResponse) vnfRestResponse).getVfModuleDeleted(); if (null != vfModuleDelete && vfModuleDelete) { vfModule.setHeatStackId(null); - execution.setVariable("heatStackId", null); + execution.setVariable(HEAT_STACK_ID, null); Map<String, String> vfModuleOutputs = ((DeleteVfModuleResponse) vnfRestResponse).getVfModuleOutputs(); if (vfModuleOutputs != null) { @@ -134,7 +135,7 @@ public class VnfAdapterImpl { String heatStackId = ((CreateVolumeGroupResponse) vnfRestResponse).getVolumeGroupStackId(); if (!StringUtils.isEmpty(heatStackId)) { volumeGroup.setHeatStackId(heatStackId); - execution.setVariable("heatStackId", heatStackId); + execution.setVariable(HEAT_STACK_ID, heatStackId); } else { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "HeatStackId is missing from create VolumeGroup Vnf Adapter response."); @@ -144,7 +145,7 @@ public class VnfAdapterImpl { Boolean volumeGroupDelete = ((DeleteVolumeGroupResponse) vnfRestResponse).getVolumeGroupDeleted(); if (null != volumeGroupDelete && volumeGroupDelete) { volumeGroup.setHeatStackId(null); - execution.setVariable("heatStackId", null); + execution.setVariable(HEAT_STACK_ID, null); } } } @@ -184,7 +185,7 @@ public class VnfAdapterImpl { try { VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); - List<String> contrailNetworkPolicyFqdnList = new ArrayList<String>(); + List<String> contrailNetworkPolicyFqdnList = new ArrayList<>(); Iterator<String> keys = vfModuleOutputs.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); 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 f193967a32..e0176eb802 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 @@ -42,6 +42,7 @@ import com.google.common.base.Optional; public class VnfmAdapterServiceProviderImpl implements VnfmAdapterServiceProvider { private static final Logger LOGGER = LoggerFactory.getLogger(VnfmAdapterServiceProviderImpl.class); + public static final String RECEIVED_RESPONSE_WITHOUT_BODY = "Received response without body: {}"; private final VnfmAdapterUrlProvider urlProvider; private final HttpRestServiceProvider httpServiceProvider; @@ -69,7 +70,7 @@ public class VnfmAdapterServiceProviderImpl implements VnfmAdapterServiceProvide } if (!response.hasBody()) { - LOGGER.error("Received response without body: {}", response); + LOGGER.error(RECEIVED_RESPONSE_WITHOUT_BODY, response); return Optional.absent(); } @@ -107,7 +108,7 @@ public class VnfmAdapterServiceProviderImpl implements VnfmAdapterServiceProvide } if (!response.hasBody()) { - LOGGER.error("Received response without body: {}", response); + LOGGER.error(RECEIVED_RESPONSE_WITHOUT_BODY, response); return Optional.absent(); } final DeleteVnfResponse deleteVnfResponse = response.getBody(); @@ -139,7 +140,7 @@ public class VnfmAdapterServiceProviderImpl implements VnfmAdapterServiceProvide } if (!response.hasBody()) { - LOGGER.error("Received response without body: {}", response); + LOGGER.error(RECEIVED_RESPONSE_WITHOUT_BODY, response); return Optional.absent(); } return Optional.of(response.getBody()); 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 ef882b4694..f9bd8c546f 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 @@ -47,6 +47,9 @@ import org.springframework.stereotype.Component; @Component public class AppcRunTasks { private static final Logger logger = LoggerFactory.getLogger(AppcRunTasks.class); + public static final String ROLLBACK_VNF_STOP = "rollbackVnfStop"; + public static final String ROLLBACK_VNF_LOCK = "rollbackVnfLock"; + public static final String ROLLBACK_QUIESCE_TRAFFIC = "rollbackQuiesceTraffic"; @Autowired private ExceptionBuilder exceptionUtil; @Autowired @@ -71,9 +74,9 @@ public class AppcRunTasks { execution.setVariable("actionHealthCheck", Action.HealthCheck); execution.setVariable("actionDistributeTraffic", Action.DistributeTraffic); execution.setVariable("actionDistributeTrafficCheck", Action.DistributeTrafficCheck); - execution.setVariable("rollbackVnfStop", false); - execution.setVariable("rollbackVnfLock", false); - execution.setVariable("rollbackQuiesceTraffic", false); + execution.setVariable(ROLLBACK_VNF_STOP, false); + execution.setVariable(ROLLBACK_VNF_LOCK, false); + execution.setVariable(ROLLBACK_QUIESCE_TRAFFIC, false); } public void runAppcCommand(BuildingBlockExecution execution, Action action) { @@ -153,17 +156,17 @@ public class AppcRunTasks { protected void mapRollbackVariables(BuildingBlockExecution execution, Action action, String appcCode) { if (appcCode.equals("0") && action != null) { if (action.equals(Action.Lock)) { - execution.setVariable("rollbackVnfLock", true); + execution.setVariable(ROLLBACK_VNF_LOCK, true); } else if (action.equals(Action.Unlock)) { - execution.setVariable("rollbackVnfLock", false); + execution.setVariable(ROLLBACK_VNF_LOCK, false); } else if (action.equals(Action.Start)) { - execution.setVariable("rollbackVnfStop", false); + execution.setVariable(ROLLBACK_VNF_STOP, false); } else if (action.equals(Action.Stop)) { - execution.setVariable("rollbackVnfStop", true); + execution.setVariable(ROLLBACK_VNF_STOP, true); } else if (action.equals(Action.QuiesceTraffic)) { - execution.setVariable("rollbackQuiesceTraffic", true); + execution.setVariable(ROLLBACK_QUIESCE_TRAFFIC, true); } else if (action.equals(Action.ResumeTraffic)) { - execution.setVariable("rollbackQuiesceTraffic", false); + execution.setVariable(ROLLBACK_QUIESCE_TRAFFIC, false); } } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtils.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtils.java index ab8818f682..4b88f741de 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtils.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkBBUtils.java @@ -54,9 +54,9 @@ public class AssignNetworkBBUtils { * @return */ public boolean networkFoundByName(BuildingBlockExecution execution) throws Exception { - boolean found = false; + // TODO - populate logic after iTrack MSO-2143 implemented - return found; + return false; } /** @@ -71,7 +71,7 @@ public class AssignNetworkBBUtils { CloudRegion cloudRegion = gBBInput.getCloudRegion(); String cloudRegionSdnc; String cloudRegionPo = cloudRegion.getLcpCloudRegionId(); - if (cloudRegion.getCloudRegionVersion().equalsIgnoreCase("2.5")) { + if ("2.5".equalsIgnoreCase(cloudRegion.getCloudRegionVersion())) { cloudRegionSdnc = "AAIAIC25"; } else { cloudRegionSdnc = cloudRegionPo; 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 359f19285f..4ec8b932c0 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 @@ -40,9 +40,9 @@ import org.springframework.stereotype.Component; @Component public class ConfigDeployVnf { private static final Logger logger = LoggerFactory.getLogger(ConfigDeployVnf.class); - private final static String ORIGINATOR_ID = "SO"; - private final static String ACTION_NAME = "config-deploy"; - private final static String MODE = "async"; + private static final String ORIGINATOR_ID = "SO"; + private static final String ACTION_NAME = "config-deploy"; + private static final String MODE = "async"; @Autowired private ExceptionBuilder exceptionUtil; 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 1925d8b69f..0ad88d0676 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 @@ -160,7 +160,7 @@ public class ConfigurationScaleOut { logger.error("Error Message: " + appcMessage); logger.error("ERROR CODE: " + appcCode); logger.trace("End of runAppCommand "); - if (appcCode != null && !appcCode.equals("0")) { + if (appcCode != null && !("0").equals(appcCode)) { exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage); } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetwork.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetwork.java index c2d9c6e7bb..b7ddc11f35 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetwork.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetwork.java @@ -39,7 +39,7 @@ import org.springframework.stereotype.Component; @Component public class CreateNetwork { - private static final Logger logger = LoggerFactory.getLogger(CreateNetwork.class); + @Autowired private ExceptionBuilder exceptionUtil; @Autowired diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollection.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollection.java index 4eaec381e9..36eab8f981 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollection.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollection.java @@ -36,7 +36,7 @@ import org.springframework.stereotype.Component; @Component public class CreateNetworkCollection { - private static final Logger logger = LoggerFactory.getLogger(CreateNetworkCollection.class); + @Autowired private ExceptionBuilder exceptionUtil; @Autowired 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 98b602eca1..8f0c809e1f 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 @@ -45,6 +45,9 @@ import org.springframework.stereotype.Component; public class GenericVnfHealthCheck { private static final Logger logger = LoggerFactory.getLogger(GenericVnfHealthCheck.class); + public static final String VNF_NAME = "vnfName"; + public static final String OAM_IP_ADDRESS = "oamIpAddress"; + public static final String VNF_HOST_IP_ADDRESS = "vnfHostIpAddress"; @Autowired private ExceptionBuilder exceptionUtil; @Autowired @@ -71,9 +74,9 @@ public class GenericVnfHealthCheck { String controllerName = controllerSelectionReference.getControllerName(); execution.setVariable("vnfId", vnfId); - execution.setVariable("vnfName", vnfName); - execution.setVariable("oamIpAddress", oamIpAddress); - execution.setVariable("vnfHostIpAddress", oamIpAddress); + execution.setVariable(VNF_NAME, vnfName); + execution.setVariable(OAM_IP_ADDRESS, oamIpAddress); + execution.setVariable(VNF_HOST_IP_ADDRESS, oamIpAddress); execution.setVariable("msoRequestId", gBBInput.getRequestContext().getMsoRequestId()); execution.setVariable("action", actionCategory); execution.setVariable("controllerType", controllerName); @@ -98,11 +101,11 @@ public class GenericVnfHealthCheck { payload = Optional.of(pay); } String controllerType = execution.getVariable("controllerType"); - HashMap<String, String> payloadInfo = new HashMap<String, String>(); - payloadInfo.put("vnfName", execution.getVariable("vnfName")); + HashMap<String, String> payloadInfo = new HashMap<>(); + payloadInfo.put(VNF_NAME, execution.getVariable(VNF_NAME)); payloadInfo.put("vfModuleId", execution.getVariable("vfModuleId")); - payloadInfo.put("oamIpAddress", execution.getVariable("oamIpAddress")); - payloadInfo.put("vnfHostIpAddress", execution.getVariable("vnfHostIpAddress")); + payloadInfo.put(OAM_IP_ADDRESS, execution.getVariable(OAM_IP_ADDRESS)); + payloadInfo.put(VNF_HOST_IP_ADDRESS, execution.getVariable(VNF_HOST_IP_ADDRESS)); logger.debug("Running APP-C action: {}", action.toString()); logger.debug("VNFID: {}", vnfId); @@ -133,7 +136,7 @@ public class GenericVnfHealthCheck { logger.error("Error Message: " + appcMessage); logger.error("ERROR CODE: " + appcCode); logger.trace("End of runAppCommand "); - if (appcCode != null && !appcCode.equals("0")) { + if (appcCode != null && !("0").equals(appcCode)) { exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage); } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java index 27415190cc..7466df53b2 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java @@ -38,11 +38,10 @@ import org.springframework.stereotype.Component; @Component public class UnassignNetworkBB { - private static final Logger logger = LoggerFactory.getLogger(UnassignNetworkBB.class); - private static String MESSAGE_CANNOT_PERFORM_UNASSIGN = + private static String messageCannotPerformUnassign = "Cannot perform Unassign Network. Network is still related to "; - private static String MESSAGE_ERROR_ROLLBACK = " Rollback is not possible. Please restore data manually."; + private static String messageErrorRollback = " Rollback is not possible. Please restore data manually."; @Autowired private ExceptionBuilder exceptionUtil; @@ -72,7 +71,7 @@ public class UnassignNetworkBB { Optional<org.onap.aai.domain.yang.L3Network> network = aaiResultWrapper.asBean(org.onap.aai.domain.yang.L3Network.class); if (networkBBUtils.isRelationshipRelatedToExists(network, relatedToValue)) { - String msg = MESSAGE_CANNOT_PERFORM_UNASSIGN + relatedToValue; + String msg = messageCannotPerformUnassign + relatedToValue; execution.setVariable("ErrorUnassignNetworkBB", msg); exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg); } @@ -109,7 +108,7 @@ public class UnassignNetworkBB { boolean isRollbackNeeded = execution.getVariable("isRollbackNeeded") != null ? execution.getVariable("isRollbackNeeded") : false; if (isRollbackNeeded == true) { - msg = execution.getVariable("ErrorUnassignNetworkBB") + MESSAGE_ERROR_ROLLBACK; + msg = execution.getVariable("ErrorUnassignNetworkBB") + messageErrorRollback; } else { msg = execution.getVariable("ErrorUnassignNetworkBB"); } 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 b906b8a662..61fc8ffc48 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 @@ -23,6 +23,14 @@ public class ManualHandlingTasks { private static final String TASK_TYPE_PAUSE = "pause"; private static final String TASK_TYPE_FALLOUT = "fallout"; + public static final String VNF_TYPE = "vnfType"; + public static final String SERVICE_TYPE = "serviceType"; + public static final String MSO_REQUEST_ID = "msoRequestId"; + public static final String REQUESTOR_ID = "requestorId"; + public static final String ERROR_CODE = "errorCode"; + public static final String VALID_RESPONSES = "validResponses"; + public static final String DESCRIPTION = "description"; + public static final String BPMN_EXCEPTION = "BPMN exception: "; @Autowired private ExceptionBuilder exceptionUtil; @@ -37,39 +45,39 @@ public class ManualHandlingTasks { String taskId = task.getId(); logger.debug("taskId is: " + taskId); String type = TASK_TYPE_FALLOUT; - String nfRole = (String) execution.getVariable("vnfType"); - String subscriptionServiceType = (String) execution.getVariable("serviceType"); - String originalRequestId = (String) execution.getVariable("msoRequestId"); - String originalRequestorId = (String) execution.getVariable("requestorId"); + String nfRole = (String) execution.getVariable(VNF_TYPE); + String subscriptionServiceType = (String) execution.getVariable(SERVICE_TYPE); + String originalRequestId = (String) execution.getVariable(MSO_REQUEST_ID); + String originalRequestorId = (String) execution.getVariable(REQUESTOR_ID); String description = ""; String timeout = ""; String errorSource = (String) execution.getVariable("failedActivity"); - String errorCode = (String) execution.getVariable("errorCode"); + String errorCode = (String) execution.getVariable(ERROR_CODE); String errorMessage = (String) execution.getVariable("errorText"); String buildingBlockName = (String) execution.getVariable("currentActivity"); String buildingBlockStep = (String) execution.getVariable("workStep"); - String validResponses = (String) execution.getVariable("validResponses"); + String validResponses = (String) execution.getVariable(VALID_RESPONSES); - Map<String, String> taskVariables = new HashMap<String, String>(); + Map<String, String> taskVariables = new HashMap<>(); taskVariables.put("type", type); taskVariables.put("nfRole", nfRole); taskVariables.put("subscriptionServiceType", subscriptionServiceType); taskVariables.put("originalRequestId", originalRequestId); taskVariables.put("originalRequestorId", originalRequestorId); taskVariables.put("errorSource", errorSource); - taskVariables.put("errorCode", errorCode); + taskVariables.put(ERROR_CODE, errorCode); taskVariables.put("errorMessage", errorMessage); taskVariables.put("buildingBlockName", buildingBlockName); taskVariables.put("buildingBlockStep", buildingBlockStep); - taskVariables.put("validResponses", validResponses); + taskVariables.put(VALID_RESPONSES, validResponses); taskVariables.put("tmeout", timeout); - taskVariables.put("description", description); + taskVariables.put(DESCRIPTION, description); TaskService taskService = execution.getProcessEngineServices().getTaskService(); taskService.setVariables(taskId, taskVariables); logger.debug("successfully created fallout task: " + taskId); } catch (BpmnError e) { - logger.debug("BPMN exception: " + e.getMessage()); + logger.debug(BPMN_EXCEPTION + e.getMessage()); throw e; } catch (Exception ex) { String msg = "Exception in setFalloutTaskVariables " + ex.getMessage(); @@ -86,39 +94,39 @@ public class ManualHandlingTasks { String taskId = task.getId(); logger.debug("taskId is: " + taskId); String type = TASK_TYPE_PAUSE; - String nfRole = (String) execution.getVariable("vnfType"); - String subscriptionServiceType = (String) execution.getVariable("serviceType"); - String originalRequestId = (String) execution.getVariable("msoRequestId"); - String originalRequestorId = (String) execution.getVariable("requestorId"); - String description = (String) execution.getVariable("description"); + String nfRole = (String) execution.getVariable(VNF_TYPE); + String subscriptionServiceType = (String) execution.getVariable(SERVICE_TYPE); + String originalRequestId = (String) execution.getVariable(MSO_REQUEST_ID); + String originalRequestorId = (String) execution.getVariable(REQUESTOR_ID); + String description = (String) execution.getVariable(DESCRIPTION); String timeout = (String) execution.getVariable("taskTimeout"); String errorSource = ""; String errorCode = ""; String errorMessage = ""; String buildingBlockName = ""; String buildingBlockStep = ""; - String validResponses = (String) execution.getVariable("validResponses"); + String validResponses = (String) execution.getVariable(VALID_RESPONSES); - Map<String, String> taskVariables = new HashMap<String, String>(); + Map<String, String> taskVariables = new HashMap<>(); taskVariables.put("type", type); taskVariables.put("nfRole", nfRole); - taskVariables.put("description", description); + taskVariables.put(DESCRIPTION, description); taskVariables.put("timeout", timeout); taskVariables.put("subscriptionServiceType", subscriptionServiceType); taskVariables.put("originalRequestId", originalRequestId); taskVariables.put("originalRequestorId", originalRequestorId); taskVariables.put("errorSource", errorSource); - taskVariables.put("errorCode", errorCode); + taskVariables.put(ERROR_CODE, errorCode); taskVariables.put("errorMessage", errorMessage); taskVariables.put("buildingBlockName", buildingBlockName); taskVariables.put("buildingBlockStep", buildingBlockStep); - taskVariables.put("validResponses", validResponses); + taskVariables.put(VALID_RESPONSES, validResponses); TaskService taskService = execution.getProcessEngineServices().getTaskService(); taskService.setVariables(taskId, taskVariables); logger.debug("successfully created pause task: " + taskId); } catch (BpmnError e) { - logger.debug("BPMN exception: " + e.getMessage()); + logger.debug(BPMN_EXCEPTION + e.getMessage()); throw e; } catch (Exception ex) { String msg = "Exception in setPauseTaskVariables " + ex.getMessage(); @@ -149,7 +157,7 @@ public class ManualHandlingTasks { execution.setVariable("responseValueTask", responseValueUppercaseStart); } catch (BpmnError e) { - logger.debug("BPMN exception: " + e.getMessage()); + logger.debug(BPMN_EXCEPTION + e.getMessage()); throw e; } catch (Exception ex) { String msg = "Exception in completeManualTask " + ex.getMessage(); @@ -164,15 +172,15 @@ public class ManualHandlingTasks { try { ExternalTicket ticket = new ExternalTicket(); - ticket.setRequestId((String) execution.getVariable("msoRequestId")); + ticket.setRequestId((String) execution.getVariable(MSO_REQUEST_ID)); ticket.setCurrentActivity((String) execution.getVariable("currentActivity")); - ticket.setNfRole((String) execution.getVariable("vnfType")); - ticket.setDescription((String) execution.getVariable("description")); - ticket.setSubscriptionServiceType((String) execution.getVariable("serviceType")); - ticket.setRequestorId((String) execution.getVariable("requestorId")); + ticket.setNfRole((String) execution.getVariable(VNF_TYPE)); + ticket.setDescription((String) execution.getVariable(DESCRIPTION)); + ticket.setSubscriptionServiceType((String) execution.getVariable(SERVICE_TYPE)); + ticket.setRequestorId((String) execution.getVariable(REQUESTOR_ID)); ticket.setTimeout((String) execution.getVariable("taskTimeout")); ticket.setErrorSource((String) execution.getVariable("failedActivity")); - ticket.setErrorCode((String) execution.getVariable("errorCode")); + ticket.setErrorCode((String) execution.getVariable(ERROR_CODE)); ticket.setErrorMessage((String) execution.getVariable("errorText")); ticket.setWorkStep((String) execution.getVariable("workStep")); @@ -191,7 +199,7 @@ public class ManualHandlingTasks { public void updateRequestDbStatus(DelegateExecution execution, String status) { try { - String requestId = (String) execution.getVariable("msoRequestId"); + String requestId = (String) execution.getVariable(MSO_REQUEST_ID); InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId); request.setRequestStatus(status); 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 7a0008d5a2..32276891c7 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 @@ -50,7 +50,8 @@ import org.springframework.stereotype.Component; @Component public class SDNCActivateTasks { - private static final Logger logger = LoggerFactory.getLogger(SDNCActivateTasks.class); + + public static final String SDNC_REQUEST = "SDNCRequest"; @Autowired private SDNCVnfResources sdncVnfResources; @Autowired @@ -77,7 +78,7 @@ public class SDNCActivateTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VNF); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -103,7 +104,7 @@ public class SDNCActivateTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.NETWORK); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -126,7 +127,7 @@ public class SDNCActivateTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VFMODULE); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } 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 d3878f06b7..111f008159 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 @@ -54,6 +54,7 @@ import org.springframework.stereotype.Component; @Component public class SDNCAssignTasks { private static final Logger logger = LoggerFactory.getLogger(SDNCAssignTasks.class); + public static final String SDNC_REQUEST = "SDNCRequest"; @Autowired private SDNCServiceInstanceResources sdncSIResources; @Autowired @@ -79,7 +80,7 @@ public class SDNCAssignTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.SERVICE); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -99,7 +100,7 @@ public class SDNCAssignTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VNF); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -126,7 +127,7 @@ public class SDNCAssignTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VFMODULE); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -152,7 +153,7 @@ public class SDNCAssignTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.NETWORK); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } 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 50cf0fb074..4ffb397707 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 @@ -47,6 +47,7 @@ import org.springframework.stereotype.Component; @Component public class SDNCChangeAssignTasks { + public static final String SDNC_REQUEST = "SDNCRequest"; @Autowired private SDNCNetworkResources sdncNetworkResources; @Autowired @@ -70,7 +71,7 @@ public class SDNCChangeAssignTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.SERVICE); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -87,7 +88,7 @@ public class SDNCChangeAssignTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VNF); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -104,7 +105,7 @@ public class SDNCChangeAssignTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.NETWORK); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -125,7 +126,7 @@ public class SDNCChangeAssignTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VFMODULE); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } 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 3a1528946d..e587830c74 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 @@ -51,7 +51,8 @@ import org.springframework.stereotype.Component; @Component public class SDNCDeactivateTasks { - private static final Logger logger = LoggerFactory.getLogger(SDNCDeactivateTasks.class); + + public static final String SDNC_REQUEST = "SDNCRequest"; @Autowired private SDNCNetworkResources sdncNetworkResources; @Autowired @@ -80,7 +81,7 @@ public class SDNCDeactivateTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VFMODULE); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -107,7 +108,7 @@ public class SDNCDeactivateTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VNF); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -132,7 +133,7 @@ public class SDNCDeactivateTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.SERVICE); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -157,7 +158,7 @@ public class SDNCDeactivateTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.NETWORK); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasks.java index 7ae6117c61..fcc67d0ef7 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasks.java @@ -39,7 +39,8 @@ import org.springframework.stereotype.Component; @Component public class SDNCQueryTasks { - private static final Logger logger = LoggerFactory.getLogger(SDNCQueryTasks.class); + + public static final String SDNCQUERY_RESPONSE = "SDNCQueryResponse_"; @Autowired private SDNCVnfResources sdncVnfResources; @Autowired @@ -61,7 +62,7 @@ public class SDNCQueryTasks { genericVnf.setSelflink(selfLink); } String response = sdncVnfResources.queryVnf(genericVnf); - execution.setVariable("SDNCQueryResponse_" + genericVnf.getVnfId(), response); + execution.setVariable(SDNCQUERY_RESPONSE + genericVnf.getVnfId(), response); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -82,7 +83,7 @@ public class SDNCQueryTasks { } if (vfModule.getSelflink() != null && !vfModule.getSelflink().isEmpty()) { String response = sdncVfModuleResources.queryVfModule(vfModule); - execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), response); + execution.setVariable(SDNCQUERY_RESPONSE + vfModule.getVfModuleId(), response); } else { throw new Exception("Vf Module " + vfModule.getVfModuleId() + " exists in gBuildingBlock but does not have a selflink value"); @@ -97,7 +98,7 @@ public class SDNCQueryTasks { VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); if (vfModule.getSelflink() != null && !vfModule.getSelflink().isEmpty()) { String response = sdncVfModuleResources.queryVfModule(vfModule); - execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), response); + execution.setVariable(SDNCQUERY_RESPONSE + vfModule.getVfModuleId(), response); } else { throw new Exception("Vf Module " + vfModule.getVfModuleId() + " exists in gBuildingBlock but does not have a selflink value"); 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 e9848d1646..fba189fcfc 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 @@ -51,7 +51,8 @@ import org.springframework.stereotype.Component; @Component public class SDNCUnassignTasks { - private static final Logger logger = LoggerFactory.getLogger(SDNCUnassignTasks.class); + + public static final String SDNC_REQUEST = "SDNCRequest"; @Autowired private SDNCServiceInstanceResources sdncSIResources; @Autowired @@ -77,7 +78,7 @@ public class SDNCUnassignTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.SERVICE); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -94,7 +95,7 @@ public class SDNCUnassignTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VFMODULE); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -114,7 +115,7 @@ public class SDNCUnassignTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.VNF); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } @@ -136,7 +137,7 @@ public class SDNCUnassignTasks { SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); sdncRequest.setTopology(SDNCTopology.NETWORK); - execution.setVariable("SDNCRequest", sdncRequest); + execution.setVariable(SDNC_REQUEST, sdncRequest); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofClient.java index e31285f044..e8a7fef1bd 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofClient.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/oof/OofClient.java @@ -22,8 +22,8 @@ package org.onap.so.client.oof; import org.camunda.bpm.engine.delegate.BpmnError; -import org.onap.so.bpmn.common.baseclient.BaseClient; import org.onap.so.bpmn.core.UrnPropertiesReader; +import org.onap.so.client.BaseClient; import org.onap.so.client.exception.BadResponseException; import org.onap.so.client.oof.beans.OofProperties; import org.onap.so.client.oof.beans.OofRequest; 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 746f136e96..1453e40653 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 @@ -49,7 +49,7 @@ public class AAIConfigurationResources { public void createConfiguration(Configuration configuration) { AAIResourceUri configurationURI = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configuration.getConfigurationId()); - configuration.setOrchestrationStatus(OrchestrationStatus.ASSIGNED); + configuration.setOrchestrationStatus(OrchestrationStatus.INVENTORIED); org.onap.aai.domain.yang.Configuration aaiConfiguration = aaiObjectMapper.mapConfiguration(configuration); injectionHelper.getAaiClient().create(configurationURI, aaiConfiguration); } 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 e391349d2c..f84afbe4a2 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 @@ -61,9 +61,9 @@ public class AAIServiceInstanceResources { AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, customer.getGlobalCustomerId(), customer.getServiceSubscription().getServiceType(), serviceInstance.getServiceInstanceId()); serviceInstance.setOrchestrationStatus(OrchestrationStatus.INVENTORIED); - org.onap.aai.domain.yang.ServiceInstance AAIServiceInstance = + org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = aaiObjectMapper.mapServiceInstance(serviceInstance); - injectionHelper.getAaiClient().createIfNotExists(serviceInstanceURI, Optional.of(AAIServiceInstance)); + injectionHelper.getAaiClient().createIfNotExists(serviceInstanceURI, Optional.of(aaiServiceInstance)); } /** @@ -87,24 +87,24 @@ public class AAIServiceInstanceResources { public void createProject(Project project) { AAIResourceUri projectURI = AAIUriFactory.createResourceUri(AAIObjectType.PROJECT, project.getProjectName()); - org.onap.aai.domain.yang.Project AAIProject = aaiObjectMapper.mapProject(project); - injectionHelper.getAaiClient().createIfNotExists(projectURI, Optional.of(AAIProject)); + org.onap.aai.domain.yang.Project aaiProject = aaiObjectMapper.mapProject(project); + injectionHelper.getAaiClient().createIfNotExists(projectURI, Optional.of(aaiProject)); } public void createProjectandConnectServiceInstance(Project project, ServiceInstance serviceInstance) { AAIResourceUri projectURI = AAIUriFactory.createResourceUri(AAIObjectType.PROJECT, project.getProjectName()); AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance.getServiceInstanceId()); - org.onap.aai.domain.yang.Project AAIProject = aaiObjectMapper.mapProject(project); - injectionHelper.getAaiClient().createIfNotExists(projectURI, Optional.of(AAIProject)).connect(projectURI, + org.onap.aai.domain.yang.Project aaiProject = aaiObjectMapper.mapProject(project); + injectionHelper.getAaiClient().createIfNotExists(projectURI, Optional.of(aaiProject)).connect(projectURI, serviceInstanceURI); } public void createOwningEntity(OwningEntity owningEntity) { AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntity.getOwningEntityId()); - org.onap.aai.domain.yang.OwningEntity AAIOwningEntity = aaiObjectMapper.mapOwningEntity(owningEntity); - injectionHelper.getAaiClient().createIfNotExists(owningEntityURI, Optional.of(AAIOwningEntity)); + org.onap.aai.domain.yang.OwningEntity aaiOwningEntity = aaiObjectMapper.mapOwningEntity(owningEntity); + injectionHelper.getAaiClient().createIfNotExists(owningEntityURI, Optional.of(aaiOwningEntity)); } public boolean existsOwningEntity(OwningEntity owningEntity) { @@ -134,8 +134,8 @@ public class AAIServiceInstanceResources { AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntity.getOwningEntityId()); AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance.getServiceInstanceId()); - org.onap.aai.domain.yang.OwningEntity AAIOwningEntity = aaiObjectMapper.mapOwningEntity(owningEntity); - injectionHelper.getAaiClient().createIfNotExists(owningEntityURI, Optional.of(AAIOwningEntity)) + org.onap.aai.domain.yang.OwningEntity aaiOwningEntity = aaiObjectMapper.mapOwningEntity(owningEntity); + injectionHelper.getAaiClient().createIfNotExists(owningEntityURI, Optional.of(aaiOwningEntity)) .connect(owningEntityURI, serviceInstanceURI); } @@ -152,9 +152,9 @@ public class AAIServiceInstanceResources { public void updateServiceInstance(ServiceInstance serviceInstance) { AAIResourceUri serviceInstanceURI = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstance.getServiceInstanceId()); - org.onap.aai.domain.yang.ServiceInstance AAIServiceInstance = + org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = aaiObjectMapper.mapServiceInstance(serviceInstance); - injectionHelper.getAaiClient().update(serviceInstanceURI, AAIServiceInstance); + injectionHelper.getAaiClient().update(serviceInstanceURI, aaiServiceInstance); } 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 83fe31a116..514f48ffc8 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 @@ -40,7 +40,6 @@ import org.springframework.stereotype.Component; @Component public class AAIVfModuleResources { - private static final Logger logger = LoggerFactory.getLogger(AAIVfModuleResources.class); @Autowired private InjectionHelper injectionHelper; @@ -97,8 +96,8 @@ public class AAIVfModuleResources { public void changeAssignVfModule(VfModule vfModule, GenericVnf vnf) { AAIResourceUri vfModuleURI = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnf.getVnfId(), vfModule.getVfModuleId()); - org.onap.aai.domain.yang.VfModule AAIVfModule = aaiObjectMapper.mapVfModule(vfModule); - injectionHelper.getAaiClient().update(vfModuleURI, AAIVfModule); + org.onap.aai.domain.yang.VfModule aaiVfModule = aaiObjectMapper.mapVfModule(vfModule); + injectionHelper.getAaiClient().update(vfModuleURI, aaiVfModule); } public void connectVfModuleToVolumeGroup(GenericVnf vnf, VfModule vfModule, VolumeGroup volumeGroup, 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 fc61d862aa..eb66f6bef5 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 @@ -43,7 +43,6 @@ import org.springframework.stereotype.Component; @Component public class AAIVnfResources { - private static final Logger logger = LoggerFactory.getLogger(AAIVnfResources.class); @Autowired private InjectionHelper injectionHelper; 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 c24d1483e2..f4c285fdb3 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 @@ -38,7 +38,6 @@ import org.springframework.stereotype.Component; @Component public class AAIVolumeGroupResources { - private static final Logger logger = LoggerFactory.getLogger(AAIVolumeGroupResources.class); @Autowired private InjectionHelper injectionHelper; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVpnBindingResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVpnBindingResources.java index 3ac61dff60..168d370521 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVpnBindingResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVpnBindingResources.java @@ -21,7 +21,6 @@ package org.onap.so.client.orchestration; import java.util.Optional; -import javax.ws.rs.NotFoundException; import org.onap.aai.domain.yang.VpnBindings; import org.onap.so.bpmn.common.InjectionHelper; import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCConfigurationResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCConfigurationResources.java index ca32130c23..4aa6a1026a 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCConfigurationResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCConfigurationResources.java @@ -28,9 +28,7 @@ import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext; import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer; import org.onap.so.client.exception.BadResponseException; import org.onap.so.client.exception.MapperException; -import org.onap.so.client.sdnc.SDNCClient; import org.onap.so.client.sdnc.beans.SDNCSvcAction; -import org.onap.so.client.sdnc.endpoint.SDNCTopology; import org.onap.so.client.sdnc.mapper.GCTopologyOperationRequestMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCNetworkResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCNetworkResources.java index 54a9cabb57..d4a4cfbd8a 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCNetworkResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCNetworkResources.java @@ -39,7 +39,6 @@ import org.springframework.stereotype.Component; @Component public class SDNCNetworkResources { - private static final Logger logger = LoggerFactory.getLogger(SDNCNetworkResources.class); @Autowired private NetworkTopologyOperationRequestMapper sdncRM; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVnfResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVnfResources.java index 954cbc1b1d..0e32955eed 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVnfResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/SDNCVnfResources.java @@ -42,7 +42,6 @@ import org.springframework.stereotype.Component; @Component public class SDNCVnfResources { - private static final Logger logger = LoggerFactory.getLogger(SDNCVnfResources.class); @Autowired private VnfTopologyOperationRequestMapper sdncRM; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResources.java index 939f53727d..efe5f34824 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVfModuleResources.java @@ -40,7 +40,6 @@ import org.springframework.stereotype.Component; @Component public class VnfAdapterVfModuleResources { - private static final Logger logger = LoggerFactory.getLogger(VnfAdapterVfModuleResources.class); @Autowired private VnfAdapterVfModuleObjectMapper vnfAdapterVfModuleObjectMapper; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResources.java index c97ca8e0ea..2ec63182a0 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/VnfAdapterVolumeGroupResources.java @@ -39,7 +39,6 @@ import org.springframework.stereotype.Component; @Component public class VnfAdapterVolumeGroupResources { - private static final Logger logger = LoggerFactory.getLogger(VnfAdapterVolumeGroupResources.class); @Autowired private VnfAdapterObjectMapper vnfAdapterObjectMapper; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SDNCClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SDNCClient.java index 732bba8489..2e7877fe3b 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SDNCClient.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SDNCClient.java @@ -24,7 +24,7 @@ package org.onap.so.client.sdnc; import java.util.LinkedHashMap; import javax.ws.rs.core.UriBuilder; -import org.onap.so.bpmn.common.baseclient.BaseClient; +import org.onap.so.client.BaseClient; import org.onap.so.client.exception.BadResponseException; import org.onap.so.client.exception.MapperException; import org.onap.so.client.sdnc.beans.SDNCProperties; @@ -39,8 +39,6 @@ import org.springframework.stereotype.Component; @Component public class SDNCClient { - private static final Logger logger = LoggerFactory.getLogger(SDNCClient.class); - @Autowired private SDNCProperties properties; @Autowired 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 e21f64accd..fe1f3f4308 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 @@ -52,6 +52,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 = "{} {} {} {} {}"; /*** * @@ -66,8 +67,8 @@ public class SdnCommonTasks { try { jsonRequest = objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(request); } catch (JsonProcessingException e) { - logger.error("{} {} {} {} {}", MessageEnum.JAXB_EXCEPTION.toString(), COULD_NOT_CONVERT_SDNC_POJO_TO_JSON, - "BPMN", ErrorCode.DataError.getValue(), e.getMessage()); + logger.error(BRACKETS, MessageEnum.JAXB_EXCEPTION.toString(), COULD_NOT_CONVERT_SDNC_POJO_TO_JSON, "BPMN", + ErrorCode.DataError.getValue(), e.getMessage()); throw new MapperException(COULD_NOT_CONVERT_SDNC_POJO_TO_JSON); } jsonRequest = "{\"input\":" + jsonRequest + "}"; @@ -84,7 +85,7 @@ public class SdnCommonTasks { HttpHeaders httpHeader = new HttpHeaders(); httpHeader.set("Authorization", auth); httpHeader.setContentType(MediaType.APPLICATION_JSON); - List<MediaType> acceptMediaTypes = new ArrayList<MediaType>(); + List<MediaType> acceptMediaTypes = new ArrayList<>(); acceptMediaTypes.add(MediaType.APPLICATION_JSON); httpHeader.setAccept(acceptMediaTypes); return httpHeader; @@ -98,7 +99,7 @@ public class SdnCommonTasks { */ public String validateSDNResponse(LinkedHashMap<String, Object> output) throws BadResponseException { if (CollectionUtils.isEmpty(output)) { - logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), NO_RESPONSE_FROM_SDNC, "BPMN", + logger.error(BRACKETS, MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), NO_RESPONSE_FROM_SDNC, "BPMN", ErrorCode.UnknownError.getValue(), NO_RESPONSE_FROM_SDNC); throw new BadResponseException(NO_RESPONSE_FROM_SDNC); } @@ -125,7 +126,7 @@ public class SdnCommonTasks { return jsonResponse; } else { String errorMessage = String.format(SDNC_CODE_NOT_0_OR_IN_200_299, responseMessage); - logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), errorMessage, "BPMN", + logger.error(BRACKETS, MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), errorMessage, "BPMN", ErrorCode.DataError.getValue(), errorMessage); throw new BadResponseException(errorMessage); } @@ -139,7 +140,7 @@ public class SdnCommonTasks { */ public String validateSDNGetResponse(LinkedHashMap<String, Object> output) throws BadResponseException { if (CollectionUtils.isEmpty(output)) { - logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), NO_RESPONSE_FROM_SDNC, "BPMN", + logger.error(BRACKETS, MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), NO_RESPONSE_FROM_SDNC, "BPMN", ErrorCode.UnknownError.getValue(), NO_RESPONSE_FROM_SDNC); throw new BadResponseException(NO_RESPONSE_FROM_SDNC); } @@ -149,7 +150,7 @@ public class SdnCommonTasks { try { stringOutput = objMapper.writeValueAsString(output); } catch (Exception e) { - logger.error("{} {} {} {} {}", MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), BAD_RESPONSE_FROM_SDNC, "BPMN", + logger.error(BRACKETS, MessageEnum.RA_RESPONSE_FROM_SDNC.toString(), BAD_RESPONSE_FROM_SDNC, "BPMN", ErrorCode.UnknownError.getValue(), BAD_RESPONSE_FROM_SDNC); throw new BadResponseException(BAD_RESPONSE_FROM_SDNC); } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java index f7aad558b2..21c0b971b8 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java @@ -24,8 +24,8 @@ package org.onap.so.client.sniro; import java.util.LinkedHashMap; import org.camunda.bpm.engine.delegate.BpmnError; -import org.onap.so.bpmn.common.baseclient.BaseClient; import org.onap.so.bpmn.core.UrnPropertiesReader; +import org.onap.so.client.BaseClient; import org.onap.so.client.exception.BadResponseException; import org.onap.so.client.sniro.beans.ManagerProperties; import org.onap.so.client.sniro.beans.SniroConductorRequest; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroValidator.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroValidator.java index a448082cfe..eb73001f42 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroValidator.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroValidator.java @@ -49,7 +49,7 @@ public class SniroValidator { JSONObject jsonResponse = new JSONObject(response); if (jsonResponse.has("requestStatus")) { String status = jsonResponse.getString("requestStatus"); - if (status.equals("accepted")) { + if ("accepted".equals(status)) { logger.debug("Sniro Managers synchronous response indicates accepted"); } else { String message = jsonResponse.getString("statusMessage"); @@ -111,7 +111,7 @@ public class SniroValidator { if (!response.isEmpty()) { String status = (String) response.get("status"); if (isNotBlank(status)) { - if (status.equals("success")) { + if ("success".equals(status)) { logger.debug("Sniro Conductors synchronous response indicates success"); } else { String message = (String) response.get("message"); 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 19378cdbfa..fe2b63ff92 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 @@ -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,6 +38,8 @@ public class Demand implements Serializable { private List<Candidate> requiredCandidates; @JsonProperty("excludedCandidates") private List<Candidate> excludedCandidates; + @JsonProperty("existingCandidates") + private List<Candidate> existingCandidates; public List<Candidate> getRequiredCandidates() { @@ -80,4 +82,12 @@ public class Demand implements Serializable { this.modelInfo = modelInfo; } + public List<Candidate> getExistingCandidates() { + return existingCandidates; + } + + public void setExistingCandidates(List<Candidate> existingCandidates) { + this.existingCandidates = existingCandidates; + } + } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/LicenseInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/LicenseInfo.java index d71b4ec5fc..9ab3ae673a 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/LicenseInfo.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/LicenseInfo.java @@ -30,7 +30,7 @@ public class LicenseInfo implements Serializable { private static final long serialVersionUID = 6878164369491185856L; @JsonProperty("licenseDemands") - private List<Demand> demands = new ArrayList<Demand>(); + private List<Demand> demands = new ArrayList<>(); public List<Demand> getDemands() { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/PlacementInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/PlacementInfo.java index ae13903a22..bbbbf9cfd6 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/PlacementInfo.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/PlacementInfo.java @@ -37,7 +37,7 @@ public class PlacementInfo implements Serializable { @JsonProperty("subscriberInfo") private SubscriberInfo subscriberInfo; @JsonProperty("placementDemands") - private List<Demand> demands = new ArrayList<Demand>(); + private List<Demand> demands = new ArrayList<>(); @JsonRawValue @JsonProperty("requestParameters") private String requestParameters; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroConductorRequest.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroConductorRequest.java index f632424c26..b8896a2bab 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroConductorRequest.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SniroConductorRequest.java @@ -40,7 +40,7 @@ public class SniroConductorRequest implements Serializable { private static final Logger logger = LoggerFactory.getLogger(SniroConductorRequest.class); @JsonProperty("release-locks") - private List<Resource> resources = new ArrayList<Resource>(); + private List<Resource> resources = new ArrayList<>(); public List<Resource> getResources() { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SubscriberInfo.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SubscriberInfo.java index eaf8b6e379..35a4cac459 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SubscriberInfo.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/beans/SubscriberInfo.java @@ -22,7 +22,6 @@ package org.onap.so.client.sniro.beans; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonRawValue; import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("subscriberInfo") diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasksTest.java index 7109ac8826..905f244278 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasksTest.java @@ -666,6 +666,18 @@ public class AAIUpdateTasksTest extends BaseTaskTest { } @Test + public void updateOrchestrationStatusAssignedFabricConfigurationTest() throws Exception { + gBBInput = execution.getGeneralBuildingBlock(); + doNothing().when(aaiConfigurationResources).updateOrchestrationStatusConfiguration(configuration, + OrchestrationStatus.ASSIGNED); + + aaiUpdateTasks.updateOrchestrationStatusAssignFabricConfiguration(execution); + + verify(aaiConfigurationResources, times(1)).updateOrchestrationStatusConfiguration(configuration, + OrchestrationStatus.ASSIGNED); + } + + @Test public void updateContrailServiceInstanceFqdnVfModuleTest() throws Exception { execution.setVariable("contrailServiceInstanceFqdn", "newContrailServiceInstanceFqdn"); doNothing().when(aaiVfModuleResources).updateContrailServiceInstanceFqdnVfModule(vfModule, genericVnf); 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 8d51ceb65f..b5a8318ce9 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 @@ -23,7 +23,7 @@ package org.onap.so.bpmn.infrastructure.flowspecific.tasks; 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.urlEqualTo; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.isA; @@ -53,6 +53,7 @@ import org.onap.so.client.exception.BadResponseException; import org.onap.so.client.sniro.beans.SniroManagerRequest; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; public class SniroHomingV2IT extends BaseIntegrationTest { @@ -107,6 +108,18 @@ public class SniroHomingV2IT extends BaseIntegrationTest { serviceInstance.getAllottedResources().add(setAllottedResource("3")); } + public void beforeServiceProxy() { + ServiceProxy sp = setServiceProxy("1", "infrastructure"); + Candidate requiredCandidate = new Candidate(); + requiredCandidate.setIdentifierType(CandidateType.CLOUD_REGION_ID); + List<String> c = new ArrayList<String>(); + c.add("testCloudRegionId"); + requiredCandidate.setCloudOwner("att"); + requiredCandidate.setIdentifiers(c); + sp.addRequiredCandidates(requiredCandidate); + serviceInstance.getServiceProxies().add(sp); + } + public void beforeVnf() { setGenericVnf(); } @@ -191,6 +204,23 @@ public class SniroHomingV2IT extends BaseIntegrationTest { verify(sniroClient, times(1)).postDemands(isA(SniroManagerRequest.class)); } + @Test + public void testCallSniro_success_1ServiceProxy() throws JsonProcessingException, BadResponseException { + beforeServiceProxy(); + + wireMockServer.stubFor(post(urlEqualTo("/sniro/api/placement/v2")).willReturn( + aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(mockResponse))); + + sniroHoming.callSniro(execution); + + String request = readResourceFile(RESOURCE_PATH + "SniroManagerRequest1SP.json"); + request = request.replace("28080", wireMockPort); + + ArgumentCaptor<SniroManagerRequest> argument = ArgumentCaptor.forClass(SniroManagerRequest.class); + verify(sniroClient, times(1)).postDemands(argument.capture()); + assertEquals(request, argument.getValue().toJsonString()); + } + @Test(expected = Test.None.class) public void testProcessSolution_success_1VpnLink_1Solution() { beforeVpnBondingLink("1"); @@ -563,10 +593,57 @@ public class SniroHomingV2IT extends BaseIntegrationTest { assertEquals(2, vnf.getLicense().getLicenseKeyGroupUuids().size()); assertEquals("f1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getEntitlementPoolUuids().get(0)); assertEquals("s1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getLicenseKeyGroupUuids().get(0)); + } + + @Test + public void testProcessSolution_success_1ServiceProxy_1Solutions() { + beforeServiceProxy(); + + JSONObject asyncResponse = new JSONObject(); + asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", + "completed"); + JSONArray solution1 = new JSONArray(); + solution1 + .put(new JSONObject() + .put("serviceResourceId", "testProxyId1").put( + "solution", + new JSONObject() + .put("identifierType", "serviceInstanceId") + .put("identifiers", new JSONArray().put("testServiceInstanceId1"))) + .put("assignmentInfo", + new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False")) + .put(new JSONObject().put("key", "cloudOwner").put("value", "")) + .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1")) + .put(new JSONObject().put("key", "aicVersion").put("value", "3")) + .put(new JSONObject().put("key", "cloudRegionId").put("value", "")) + .put(new JSONObject().put("key", "primaryPnfName").put("value", + "testPrimaryPnfName")) + .put(new JSONObject().put("key", "secondaryPnfName").put("value", + "testSecondaryPnfName")))); + + asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1)) + .put("licenseSolutions", new JSONArray())); + sniroHoming.processSolution(execution, asyncResponse.toString()); + ServiceInstance si = + execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0); + + ServiceProxy sp = si.getServiceProxies().get(0); + assertNotNull(sp); + assertNotNull(sp.getServiceInstance()); + + assertEquals("testServiceInstanceId1", sp.getServiceInstance().getServiceInstanceId()); + assertNotNull(sp.getServiceInstance().getSolutionInfo()); + + assertFalse(sp.getServiceInstance().getPnfs().isEmpty()); + assertEquals("testPrimaryPnfName", sp.getServiceInstance().getPnfs().get(0).getPnfName()); + assertEquals("primary", sp.getServiceInstance().getPnfs().get(0).getRole()); + assertEquals("testSecondaryPnfName", sp.getServiceInstance().getPnfs().get(1).getPnfName()); + assertEquals("secondary", sp.getServiceInstance().getPnfs().get(1).getRole()); } + @Test(expected = BpmnError.class) public void testCallSniro_error_0Resources() throws BadResponseException, JsonProcessingException { 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 2e1a40dd22..be58ccb046 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 @@ -98,7 +98,7 @@ public class AAIConfigurationResourcesTest extends TestDataSetup { aaiConfigurationResources.createConfiguration(configuration); - assertEquals(OrchestrationStatus.ASSIGNED, configuration.getOrchestrationStatus()); + assertEquals(OrchestrationStatus.INVENTORIED, configuration.getOrchestrationStatus()); verify(MOCK_aaiResourcesClient, times(1)).create(any(AAIResourceUri.class), isA(org.onap.aai.domain.yang.Configuration.class)); } 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 new file mode 100644 index 0000000000..27463350ab --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest1SP.json @@ -0,0 +1,46 @@ +{ + "requestInfo" : { + "transactionId" : "testRequestId", + "requestId" : "testRequestId", + "callbackUrl" : "http://localhost:28080/mso/WorkflowMesssage/SNIROResponse/testRequestId", + "sourceId" : "mso", + "requestType" : "create", + "timeout" : 1800 + }, + "serviceInfo" : { + "modelInfo" : { + "modelName" : "testModelName1", + "modelVersionId" : "testModelUUID1", + "modelVersion" : "testModelVersion1", + "modelInvariantId" : "testModelInvariantUUID1" + }, + "serviceRole" : "testServiceRole1", + "serviceInstanceId" : "testServiceInstanceId1", + "serviceName" : "testServiceType1" + }, + "placementInfo" : { + "subscriberInfo" : { + "globalSubscriberId" : "testCustomerId", + "subscriberName" : "testCustomerName" + }, + "placementDemands" : [ { + "serviceResourceId" : "testProxyId1", + "resourceModuleName" : "testProxyInstanceName1", + "resourceModelInfo" : { + "modelName" : "testProxyModelName1", + "modelVersionId" : "testProxyModelUuid1", + "modelVersion" : "testProxyModelVersion1", + "modelInvariantId" : "testProxyModelInvariantUuid1" + }, + "requiredCandidates" : [ { + "identifierType" : "cloudRegionId", + "identifiers" : [ "testCloudRegionId" ], + "cloudOwner" : "att" + } ] + } ], + "requestParameters" : {"subscriptionServiceType":"testSubscriptionServiceType","aLaCarte":false} + }, + "licenseInfo" : { + "licenseDemands" : [ ] + } +}
\ No newline at end of file diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyRequest.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyRequest.java index 0f9ad2da39..df63bd18d3 100644 --- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyRequest.java +++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyRequest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,20 +31,6 @@ public class CloudifyRequest<R> { private CloudifyClient client; - public CloudifyRequest() { - - } - - public CloudifyRequest(CloudifyClient client, HttpMethod method, CharSequence path, Entity<?> entity, - Class<R> returnType) { - this.client = client; - this.method = method; - this.path = new StringBuilder(path); - this.entity = entity; - this.returnType = returnType; - header("Accept", "application/json"); - } - private String endpoint; private HttpMethod method; @@ -61,6 +47,20 @@ public class CloudifyRequest<R> { private String user = null; private String password = null; + public CloudifyRequest() { + + } + + public CloudifyRequest(CloudifyClient client, HttpMethod method, CharSequence path, Entity<?> entity, + Class<R> returnType) { + this.client = client; + this.method = method; + this.path = new StringBuilder(path); + this.entity = entity; + this.returnType = returnType; + header("Accept", "application/json"); + } + public CloudifyRequest<R> endpoint(String endpoint) { this.endpoint = endpoint; return this; @@ -151,7 +151,7 @@ public class CloudifyRequest<R> { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/BlueprintsResource.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/BlueprintsResource.java index 3eae02bcee..9877eb9f43 100644 --- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/BlueprintsResource.java +++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/BlueprintsResource.java @@ -31,6 +31,7 @@ import org.onap.so.cloudify.base.client.CloudifyRequest; public class BlueprintsResource { private final CloudifyClient client; + private static final String BLUEPRINTS_PATH = "/api/v3/blueprints/"; public BlueprintsResource(CloudifyClient client) { this.client = client; @@ -72,7 +73,7 @@ public class BlueprintsResource { // If a URL is provided, add it to the query string // If a Stream is provided, set it as the Entity body super(client, HttpMethod.PUT, - "/api/v3/blueprints/" + blueprintId + "?application_file_name=" + mainFileName + BLUEPRINTS_PATH + blueprintId + "?application_file_name=" + mainFileName + ((blueprintUrl != null) ? "&blueprint_archive=" + blueprintUrl : ""), ((blueprint != null) ? Entity.stream(blueprint) : null), Blueprint.class); } @@ -80,13 +81,13 @@ public class BlueprintsResource { public class DeleteBlueprint extends CloudifyRequest<Blueprint> { public DeleteBlueprint(String blueprintId) { - super(client, HttpMethod.DELETE, "/api/v3/blueprints/" + blueprintId, null, Blueprint.class); + super(client, HttpMethod.DELETE, BLUEPRINTS_PATH + blueprintId, null, Blueprint.class); } } public class GetBlueprint extends CloudifyRequest<Blueprint> { public GetBlueprint(String id, String queryArgs) { - super(client, HttpMethod.GET, "/api/v3/blueprints/" + id + queryArgs, null, Blueprint.class); + super(client, HttpMethod.GET, BLUEPRINTS_PATH + id + queryArgs, null, Blueprint.class); } } diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/DeploymentsResource.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/DeploymentsResource.java index 262045a367..335f6b1697 100644 --- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/DeploymentsResource.java +++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/DeploymentsResource.java @@ -32,6 +32,7 @@ import org.onap.so.cloudify.base.client.CloudifyRequest; public class DeploymentsResource { private final CloudifyClient client; + private static final String DEPLOYMENT_PATH = "/api/v3/deployments/"; public DeploymentsResource(CloudifyClient client) { this.client = client; @@ -59,25 +60,25 @@ public class DeploymentsResource { public class CreateDeployment extends CloudifyRequest<Deployment> { public CreateDeployment(String deploymentId, CreateDeploymentParams body) { - super(client, HttpMethod.PUT, "/api/v3/deployments/" + deploymentId, Entity.json(body), Deployment.class); + super(client, HttpMethod.PUT, DEPLOYMENT_PATH + deploymentId, Entity.json(body), Deployment.class); } } public class DeleteDeployment extends CloudifyRequest<Deployment> { public DeleteDeployment(String deploymentId) { - super(client, HttpMethod.DELETE, "/api/v3/deployments/" + deploymentId, null, Deployment.class); + super(client, HttpMethod.DELETE, DEPLOYMENT_PATH + deploymentId, null, Deployment.class); } } public class GetDeployment extends CloudifyRequest<Deployment> { public GetDeployment(String id) { - super(client, HttpMethod.GET, "/api/v3/deployments/" + id, null, Deployment.class); + super(client, HttpMethod.GET, DEPLOYMENT_PATH + id, null, Deployment.class); } } public class GetDeploymentOutputs extends CloudifyRequest<DeploymentOutputs> { public GetDeploymentOutputs(String id) { - super(client, HttpMethod.GET, "/api/v3/deployments/" + id + "/outputs", null, DeploymentOutputs.class); + super(client, HttpMethod.GET, DEPLOYMENT_PATH + id + "/outputs", null, DeploymentOutputs.class); } } diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/ExecutionsResource.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/ExecutionsResource.java index 51aaea94bb..34251bfe52 100644 --- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/ExecutionsResource.java +++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/client/ExecutionsResource.java @@ -33,6 +33,7 @@ import org.onap.so.cloudify.base.client.CloudifyRequest; public class ExecutionsResource { private final CloudifyClient client; + private static final String EXECUTIONS_PATH = "/api/v3/executions/"; public ExecutionsResource(CloudifyClient client) { this.client = client; @@ -76,7 +77,7 @@ public class ExecutionsResource { public class GetExecution extends CloudifyRequest<Execution> { public GetExecution(String id) { - super(client, HttpMethod.GET, "/api/v3/executions/" + id, null, Execution.class); + super(client, HttpMethod.GET, EXECUTIONS_PATH + id, null, Execution.class); } } @@ -95,13 +96,13 @@ public class ExecutionsResource { public class UpdateExecution extends CloudifyRequest<Execution> { public UpdateExecution(String executionId, UpdateExecutionParams body) { - super(client, HttpMethod.PATCH, "/api/v3/executions/" + executionId, Entity.json(body), Execution.class); + super(client, HttpMethod.PATCH, EXECUTIONS_PATH + executionId, Entity.json(body), Execution.class); } } public class CancelExecution extends CloudifyRequest<Execution> { public CancelExecution(String executionId, CancelExecutionParams body) { - super(client, HttpMethod.POST, "/api/v3/executions/" + executionId, Entity.json(body), Execution.class); + super(client, HttpMethod.POST, EXECUTIONS_PATH + executionId, Entity.json(body), Execution.class); } } diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CancelExecutionParams.java b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CancelExecutionParams.java index 0fbe1fc33d..7f96b8f7c6 100644 --- a/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CancelExecutionParams.java +++ b/cloudify-client/src/main/java/org/onap/so/cloudify/v3/model/CancelExecutionParams.java @@ -30,8 +30,8 @@ public class CancelExecutionParams implements Serializable { @JsonProperty("action") private String action; - public final static String CANCEL_ACTION = "cancel"; - public final static String FORCE_CANCEL_ACTION = "force-cancel"; + public static final String CANCEL_ACTION = "cancel"; + public static final String FORCE_CANCEL_ACTION = "force-cancel"; public String getAction() { return action; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/baseclient/BaseClient.java b/common/src/main/java/org/onap/so/client/BaseClient.java index 73047cf961..d939a33358 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/baseclient/BaseClient.java +++ b/common/src/main/java/org/onap/so/client/BaseClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.baseclient; +package org.onap.so.client; import java.util.ArrayList; import java.util.List; @@ -34,7 +34,6 @@ import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; -// TODO move to common location public class BaseClient<I, O> { private HttpHeaders httpHeader; diff --git a/common/src/main/java/org/onap/so/client/dmaap/DmaapConsumer.java b/common/src/main/java/org/onap/so/client/dmaap/DmaapConsumer.java index 3dd0c751e3..4de546e9da 100644 --- a/common/src/main/java/org/onap/so/client/dmaap/DmaapConsumer.java +++ b/common/src/main/java/org/onap/so/client/dmaap/DmaapConsumer.java @@ -28,6 +28,7 @@ import org.onap.so.client.dmaap.exceptions.ExceededMaximumPollingTime; import org.onap.so.client.dmaap.rest.RestConsumer; public abstract class DmaapConsumer extends DmaapClient { + static final int MAX_ELAPSED_TIME = 180000; public DmaapConsumer() throws IOException { super("dmaap/default-consumer.properties"); @@ -125,7 +126,7 @@ public abstract class DmaapConsumer extends DmaapClient { * time in milliseconds */ public int getMaximumElapsedTime() { - return 180000; + return MAX_ELAPSED_TIME; } diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java index bf33e8f8d3..f7f5d78604 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java @@ -56,9 +56,9 @@ public class DSLNodeKey implements QueryStep { result.append("('").append(keyName).append("', "); List<String> temp = new ArrayList<>(); for (String item : values) { - if (item.equals("null")) { + if ("null".equals(item)) { temp.add(String.format("' %s '", item)); - } else if (item.equals("")) { + } else if ("".equals(item)) { temp.add("' '"); } else { temp.add(String.format("'%s'", item)); diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java index 5d0a33909a..41ba07ad6c 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java @@ -44,8 +44,8 @@ public class SimpleUri implements GraphInventoryResourceUri, Serializable { private static final long serialVersionUID = -337701171277616439L; protected transient UriBuilder internalURI; - protected final static String relationshipAPI = "/relationship-list/relationship"; - protected final static String relatedTo = "/related-to"; + protected static final String relationshipAPI = "/relationship-list/relationship"; + protected static final String relatedTo = "/related-to"; protected final Object[] values; protected final GraphInventoryObjectType type; protected final GraphInventoryObjectPlurals pluralType; diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImpl.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImpl.java index 14a46c243b..71afdb83d9 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImpl.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImpl.java @@ -20,7 +20,6 @@ package org.onap.so.client.graphinventory.entities.uri.parsers; -import java.io.UnsupportedEncodingException; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; diff --git a/common/src/main/java/org/onap/so/client/policy/entities/DictionaryJson.java b/common/src/main/java/org/onap/so/client/policy/entities/DictionaryJson.java index 5b99fe1a05..6e7baa37e6 100644 --- a/common/src/main/java/org/onap/so/client/policy/entities/DictionaryJson.java +++ b/common/src/main/java/org/onap/so/client/policy/entities/DictionaryJson.java @@ -31,7 +31,7 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; public class DictionaryJson { @JsonProperty("DictionaryDatas") - private List<DictionaryData> dictionaryDatas = new ArrayList<DictionaryData>(); + private List<DictionaryData> dictionaryDatas = new ArrayList<>(); @JsonProperty("DictionaryDatas") public List<DictionaryData> getDictionaryDatas() { diff --git a/common/src/main/java/org/onap/so/client/sdno/SDNOValidatorImpl.java b/common/src/main/java/org/onap/so/client/sdno/SDNOValidatorImpl.java index 4aafd145b7..8e674fb77b 100644 --- a/common/src/main/java/org/onap/so/client/sdno/SDNOValidatorImpl.java +++ b/common/src/main/java/org/onap/so/client/sdno/SDNOValidatorImpl.java @@ -28,7 +28,6 @@ import javax.ws.rs.NotFoundException; import org.onap.aai.domain.yang.GenericVnf; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; -import org.onap.so.client.aai.AAIVersion; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.dmaap.DmaapConsumer; diff --git a/common/src/main/java/org/onap/so/client/sdno/beans/Body.java b/common/src/main/java/org/onap/so/client/sdno/beans/Body.java index 84dd83ea6f..8c40b749a6 100644 --- a/common/src/main/java/org/onap/so/client/sdno/beans/Body.java +++ b/common/src/main/java/org/onap/so/client/sdno/beans/Body.java @@ -37,8 +37,8 @@ public class Body implements Serializable { @JsonProperty("input") private Input input; @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - private final static long serialVersionUID = 9101706044452851559L; + private Map<String, Object> additionalProperties = new HashMap<>(); + private static final long serialVersionUID = 9101706044452851559L; @JsonProperty("input") public Input getInput() { diff --git a/common/src/main/java/org/onap/so/client/sdno/beans/Input.java b/common/src/main/java/org/onap/so/client/sdno/beans/Input.java index ea537bba09..c8122c06f6 100644 --- a/common/src/main/java/org/onap/so/client/sdno/beans/Input.java +++ b/common/src/main/java/org/onap/so/client/sdno/beans/Input.java @@ -40,7 +40,7 @@ public class Input implements Serializable { private RequestHdCustom requestHdCustom; @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + private Map<String, Object> additionalProperties = new HashMap<>(); private final static long serialVersionUID = 7155546785389227528L; @JsonProperty("request-healthdiagnostic") diff --git a/common/src/main/java/org/onap/so/client/sdno/beans/RequestHdCustom.java b/common/src/main/java/org/onap/so/client/sdno/beans/RequestHdCustom.java index c08d1ef386..485f64673f 100644 --- a/common/src/main/java/org/onap/so/client/sdno/beans/RequestHdCustom.java +++ b/common/src/main/java/org/onap/so/client/sdno/beans/RequestHdCustom.java @@ -49,7 +49,7 @@ public class RequestHdCustom implements Serializable { @JsonProperty("send-detailed-cmd-response") private String sendDetailedCmdResponse = "false"; @JsonProperty("aai-param-list") - private List<AAIParamList> aaiParamList = new ArrayList<AAIParamList>(); + private List<AAIParamList> aaiParamList = new ArrayList<>(); /** * No args constructor for use in serialization diff --git a/common/src/main/java/org/onap/so/client/sdno/beans/RequestHealthDiagnostic.java b/common/src/main/java/org/onap/so/client/sdno/beans/RequestHealthDiagnostic.java index c05b470b0e..b1b75ab412 100644 --- a/common/src/main/java/org/onap/so/client/sdno/beans/RequestHealthDiagnostic.java +++ b/common/src/main/java/org/onap/so/client/sdno/beans/RequestHealthDiagnostic.java @@ -52,8 +52,8 @@ public class RequestHealthDiagnostic implements Serializable { @JsonProperty("health-diagnostic-code") private String healthDiagnosticCode; @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - private final static long serialVersionUID = 1166788526178388021L; + private Map<String, Object> additionalProperties = new HashMap<>(); + private static final long serialVersionUID = 1166788526178388021L; @JsonProperty("request-client-name") public String getRequestClientName() { diff --git a/common/src/main/java/org/onap/so/client/sdno/beans/ResultInfo.java b/common/src/main/java/org/onap/so/client/sdno/beans/ResultInfo.java index 93826c752f..8b84cf6659 100644 --- a/common/src/main/java/org/onap/so/client/sdno/beans/ResultInfo.java +++ b/common/src/main/java/org/onap/so/client/sdno/beans/ResultInfo.java @@ -44,7 +44,7 @@ public class ResultInfo { @JsonProperty("status") private String status; @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + private Map<String, Object> additionalProperties = new HashMap<>(); @JsonProperty("client-name") public String getClientName() { diff --git a/common/src/main/java/org/onap/so/client/sdno/beans/SDNO.java b/common/src/main/java/org/onap/so/client/sdno/beans/SDNO.java index 09f408c967..46e2c1d1fc 100644 --- a/common/src/main/java/org/onap/so/client/sdno/beans/SDNO.java +++ b/common/src/main/java/org/onap/so/client/sdno/beans/SDNO.java @@ -43,8 +43,8 @@ public class SDNO implements Serializable { @JsonProperty("body") private Body body; @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - private final static long serialVersionUID = -5303297382564282650L; + private Map<String, Object> additionalProperties = new HashMap<>(); + private static final long serialVersionUID = -5303297382564282650L; @JsonProperty("operation") public String getOperation() { 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 9f8417e047..e3212733c8 100644 --- a/common/src/main/java/org/onap/so/logger/MdcConstants.java +++ b/common/src/main/java/org/onap/so/logger/MdcConstants.java @@ -10,4 +10,5 @@ public class MdcConstants { public static final String SERVICE_NAME = "ServiceName"; public static final String STATUSCODE = "StatusCode"; public static final String ENDTIME = "EndTimestamp"; + public static final String ORIGINAL_PARTNER_NAME = "OriginalPartnerName"; } diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java index 4741f7f099..7e2b603ba6 100644 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java +++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java @@ -20,7 +20,6 @@ package org.onap.so.logging.jaxrs.filter; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.annotation.Annotation; @@ -40,7 +39,9 @@ import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Providers; import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.logger.HttpHeadersConstants; import org.onap.so.logger.LogConstants; +import org.onap.so.logger.MdcConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; @@ -76,8 +77,10 @@ public class JaxRsFilterLogging implements ContainerRequestFilter, ContainerResp mdcSetup.setClientIPAddress(httpServletRequest); mdcSetup.setInstanceUUID(); mdcSetup.setEntryTimeStamp(); + MDC.put(HttpHeadersConstants.REQUESTOR_ID, headers.getFirst("X-RequestorID")); MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); MDC.put(LogConstants.URI_BASE, containerRequest.getUriInfo().getBaseUri().toString()); + MDC.put(MdcConstants.ORIGINAL_PARTNER_NAME, MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); } catch (Exception e) { logger.warn("Error in incoming JAX-RS Inteceptor", e); @@ -127,7 +130,6 @@ public class JaxRsFilterLogging implements ContainerRequestFilter, ContainerResp return message; } - private void setRequestId(MultivaluedMap<String, String> headers) { String requestId = headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID); if (requestId == null || requestId.isEmpty()) @@ -168,6 +170,4 @@ public class JaxRsFilterLogging implements ContainerRequestFilter, ContainerResp MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME); } - - } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAudit.java b/common/src/main/java/org/onap/so/objects/audit/AAIObjectAudit.java index 0a186ccb82..a27e8fbbd1 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAudit.java +++ b/common/src/main/java/org/onap/so/objects/audit/AAIObjectAudit.java @@ -1,4 +1,4 @@ -package org.onap.so.adapters.audit; +package org.onap.so.objects.audit; import java.io.Serializable; import java.net.URI; @@ -7,7 +7,7 @@ import org.apache.commons.lang3.builder.ToStringBuilder; public class AAIObjectAudit implements Serializable { /** - * + * */ private static final long serialVersionUID = -4560928512855386021L; private boolean doesObjectExist = false; @@ -52,4 +52,5 @@ public class AAIObjectAudit implements Serializable { public void setResourceURI(URI resourceURI) { this.resourceURI = resourceURI; } + } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAuditList.java b/common/src/main/java/org/onap/so/objects/audit/AAIObjectAuditList.java index f3a2cfea9b..675701d598 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAuditList.java +++ b/common/src/main/java/org/onap/so/objects/audit/AAIObjectAuditList.java @@ -1,17 +1,20 @@ -package org.onap.so.adapters.audit; +package org.onap.so.objects.audit; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.builder.ToStringBuilder; + public class AAIObjectAuditList implements Serializable { /** - * + * */ private static final long serialVersionUID = 6712662349909726930L; private List<AAIObjectAudit> auditList = new ArrayList<>(); + private String auditType; + private String heatStackName; @Override public String toString() { @@ -22,4 +25,22 @@ public class AAIObjectAuditList implements Serializable { return auditList; } + + public String getAuditType() { + return auditType; + } + + + public void setAuditType(String auditType) { + this.auditType = auditType; + } + + public String getHeatStackName() { + return heatStackName; + } + + public void setHeatStackName(String heatStackName) { + this.heatStackName = heatStackName; + } + } diff --git a/common/src/main/java/org/onap/so/openpojo/rules/EqualsAndHashCodeTester.java b/common/src/main/java/org/onap/so/openpojo/rules/EqualsAndHashCodeTester.java index e63e226457..6e2bc97ee9 100644 --- a/common/src/main/java/org/onap/so/openpojo/rules/EqualsAndHashCodeTester.java +++ b/common/src/main/java/org/onap/so/openpojo/rules/EqualsAndHashCodeTester.java @@ -73,9 +73,9 @@ public class EqualsAndHashCodeTester implements Tester { boolean hasEquals = false; boolean hasHashcode = false; for (Method method : methods) { - if (method.getName().equals("equals")) { + if ("equals".equals(method.getName())) { hasEquals = true; - } else if (method.getName().equals("hashCode")) { + } else if ("hashCode".equals(method.getName())) { hasHashcode = true; } } @@ -114,7 +114,7 @@ public class EqualsAndHashCodeTester implements Tester { Affirm.affirmTrue("HashCode test failed for [" + classInstanceOne.getClass().getName() + "]", classInstanceOne.hashCode() == classInstanceTwo.hashCode()); - Affirm.affirmFalse("Expected false for comparison of two unlike objects", classInstanceOne.equals("test")); + Affirm.affirmFalse("Expected false for comparison of two unlike objects", "test".equals(classInstanceOne)); } } diff --git a/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationMatcher.java b/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationMatcher.java index 9062f60280..42dda850f5 100644 --- a/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationMatcher.java +++ b/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationMatcher.java @@ -64,6 +64,6 @@ public class HasAnnotationMatcher<T extends PojoField> extends TypeSafeDiagnosin public static <T extends PojoField> Matcher<T> hasAnnotation(final Class<? extends Annotation> annotationType, final Matcher<? super T> annotationMatcher) { - return new HasAnnotationMatcher<T>(annotationType, annotationMatcher); + return new HasAnnotationMatcher<>(annotationType, annotationMatcher); } } diff --git a/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationPropertyWithValueMatcher.java b/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationPropertyWithValueMatcher.java index 8a47299c73..a55113b0d0 100644 --- a/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationPropertyWithValueMatcher.java +++ b/common/src/main/java/org/onap/so/openpojo/rules/HasAnnotationPropertyWithValueMatcher.java @@ -78,6 +78,6 @@ public class HasAnnotationPropertyWithValueMatcher<T extends PojoField> extends public static <T extends PojoField> Matcher<T> hasAnnotationPropertyWithValue(Class<? extends Annotation> clazz, String attribute, final Matcher<?> annotationMatcher) { - return new HasAnnotationPropertyWithValueMatcher<T>(clazz, attribute, annotationMatcher); + return new HasAnnotationPropertyWithValueMatcher<>(clazz, attribute, annotationMatcher); } } diff --git a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java index 8e6ebab43a..a627e82802 100644 --- a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java +++ b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java @@ -96,7 +96,7 @@ public class HttpRestServiceProviderImpl implements HttpRestServiceProvider { private <T> Optional<T> createOptional(final ResponseEntity<T> response, final String url, final HttpMethod httpMethod) { - if (!response.getStatusCode().equals(HttpStatus.OK)) { + if (!response.getStatusCode().equals(HttpStatus.OK) && !response.getStatusCode().equals(HttpStatus.CREATED)) { final String message = "Unable to invoke HTTP " + httpMethod + " using URL: " + url + ", Response Code: " + response.getStatusCode(); LOGGER.error(message); diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/CloudRequestData.java b/common/src/main/java/org/onap/so/serviceinstancebeans/CloudRequestData.java new file mode 100644 index 0000000000..abaef26562 --- /dev/null +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/CloudRequestData.java @@ -0,0 +1,59 @@ +/*- + * ============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.serviceinstancebeans; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +public class CloudRequestData { + + Object cloudRequest; + String cloudIdentifier; + + public CloudRequestData() {} + + public CloudRequestData(Object cloudRequest, String cloudIdentifier) { + this.cloudRequest = cloudRequest; + this.cloudIdentifier = cloudIdentifier; + } + + public Object getCloudRequest() { + return cloudRequest; + } + + public void setCloudRequest(Object cloudRequest) { + this.cloudRequest = cloudRequest; + } + + public String getCloudIdentifier() { + return cloudIdentifier; + } + + public void setCloudIdentifier(String cloudIdentifier) { + this.cloudIdentifier = cloudIdentifier; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("cloudRequest", cloudRequest).append("cloudIdentifier", cloudIdentifier) + .toString(); + } +} 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 8635af5b94..fbdb27c0ec 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java @@ -20,7 +20,9 @@ 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; @@ -38,6 +40,7 @@ public class Request { protected InstanceReferences instanceReferences; protected RequestStatus requestStatus; protected List<RequestProcessingData> requestProcessingData; + protected List<CloudRequestData> cloudRequestData = new ArrayList<>(); public String getRequestId() { @@ -112,12 +115,22 @@ public class Request { this.requestProcessingData = requestProcessingData; } + + public List<CloudRequestData> getCloudRequestData() { + return cloudRequestData; + } + + public void setCloudRequestData(List<CloudRequestData> cloudRequestData) { + this.cloudRequestData = cloudRequestData; + } + @Override public String toString() { return new ToStringBuilder(this).append("requestId", requestId).append("startTime", startTime) .append("finishTime", finishTime).append("requestScope", requestScope) .append("requestType", requestType).append("requestDetails", requestDetails) .append("instanceReferences", instanceReferences).append("requestStatus", requestStatus) - .append("requestProcessingData", requestProcessingData).toString(); + .append("requestProcessingData", requestProcessingData).append("cloudRequestData", cloudRequestData) + .toString(); } } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java index f239774d57..2123b2f6fc 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java @@ -24,7 +24,6 @@ package org.onap.so.serviceinstancebeans; import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/docs/Developer_Info.rst b/docs/Developer_Info.rst index 59dc9d6f1c..46c114f193 100644 --- a/docs/Developer_Info.rst +++ b/docs/Developer_Info.rst @@ -10,5 +10,5 @@ Developer Information Install_Configure_SO.rst
architecture.rst
- FAQs.rst
+
\ No newline at end of file diff --git a/docs/architecture/SO Internal Arc.pptx b/docs/architecture/SO Internal Arc.pptx Binary files differindex bff3e352e0..ee4b112b3b 100644 --- a/docs/architecture/SO Internal Arc.pptx +++ b/docs/architecture/SO Internal Arc.pptx diff --git a/docs/developer_info/developer_information.rst b/docs/developer_info/developer_information.rst index f6d66b913d..bae1e2e348 100644 --- a/docs/developer_info/developer_information.rst +++ b/docs/developer_info/developer_information.rst @@ -13,6 +13,7 @@ SO Developer Information Working_with_SO_Docker.rst Camunda_Cockpit_Community_Edition.rst Camunda_Cockpit_Enterprise_Edition.rst + FAQs.rst .. developer_info_Project_Structure.rst .. developer_info_Main_Process_Flows.rst .. developer_info_Subprocess_Process_Flows.rst diff --git a/docs/images/SO_1.png b/docs/images/SO_1.png Binary files differindex 715801330b..5bdc14644f 100644 --- a/docs/images/SO_1.png +++ b/docs/images/SO_1.png diff --git a/docs/index.rst b/docs/index.rst index ebb8b0b552..fd5f1241e6 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -12,4 +12,4 @@ ONAP SO architecture/architecture.rst
api/offered_consumed_apis.rst
developer_info/developer_information.rst
- release_notes/release-notes.rst
\ No newline at end of file + release-notes.rst
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaResponse.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaResponse.java index 8977f11e36..7fb5df7af6 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaResponse.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaResponse.java @@ -40,6 +40,8 @@ public class CamundaResponse { @JsonProperty("variables") private String variables; + public CamundaResponse() {} + public String getProcessInstanceID() { return processInstanceID; } @@ -56,8 +58,6 @@ public class CamundaResponse { this.variables = variables; } - public CamundaResponse() {} - public String getResponse() { return response; } 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 d11f1706e9..e6e81671cf 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 @@ -49,6 +49,9 @@ import com.fasterxml.jackson.databind.SerializationFeature; public class CamundaClient extends RequestClient { private static Logger logger = LoggerFactory.getLogger(CamundaClient.class); private static final String CAMUNDA_URL_MESAGE = "Camunda url is: "; + private static final String CAMUNDA_RESPONSE = "Response is: {}"; + private static final String AUTHORIZATION = "Authorization"; + private static final String BASIC = "Basic "; public CamundaClient() { super(CommonConstants.CAMUNDA); @@ -71,7 +74,7 @@ public class CamundaClient extends RequestClient { setupHeaders(post); HttpResponse response = client.execute(post); - logger.debug("Response is: {}", response); + logger.debug(CAMUNDA_RESPONSE, response); return response; } @@ -88,8 +91,8 @@ public class CamundaClient extends RequestClient { 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()))); + post.addHeader(AUTHORIZATION, + BASIC + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes()))); } } } @@ -111,8 +114,8 @@ public class CamundaClient extends RequestClient { 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()))); + post.addHeader(AUTHORIZATION, + BASIC + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes()))); } } } @@ -120,7 +123,7 @@ public class CamundaClient extends RequestClient { post.setEntity(input); HttpResponse response = client.execute(post); - logger.debug("Response is: {}", response); + logger.debug(CAMUNDA_RESPONSE, response); return response; } @@ -151,15 +154,15 @@ public class CamundaClient extends RequestClient { 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()))); + post.addHeader(AUTHORIZATION, + BASIC + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes()))); } } } post.setEntity(input); HttpResponse response = client.execute(post); - logger.debug("Response is: {}", response); + logger.debug(CAMUNDA_RESPONSE, response); return response; } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ErrorNumbers.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ErrorNumbers.java index 468fe61562..7400c0aaae 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ErrorNumbers.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ErrorNumbers.java @@ -22,8 +22,6 @@ package org.onap.so.apihandler.common; public final class ErrorNumbers { - private ErrorNumbers() {} - public static final String REQUEST_FAILED_SCHEMA_VALIDATION = "1000"; public static final String RECIPE_DOES_NOT_EXIST = "1010"; public static final String VFMODULE_TYPE_DOES_NOT_EXIST = "1011"; @@ -73,4 +71,6 @@ public final class ErrorNumbers { public static final String SVC_NO_SERVER_RESOURCES = "SVC1000"; public static final String SVC_DETAILED_SERVICE_ERROR = "SVC2000"; + private ErrorNumbers() {} + } 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 0aac35d5a9..9b7801711f 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 @@ -79,8 +79,7 @@ public abstract class RequestClient { protected String decryptPropValue(String prop, String defaultValue, String encryptionKey) { try { - String result = CryptoUtils.decrypt(prop, encryptionKey); - return result; + return CryptoUtils.decrypt(prop, encryptionKey); } catch (GeneralSecurityException e) { logger.debug("Security exception", e); } @@ -89,14 +88,10 @@ public abstract class RequestClient { protected String getEncryptedPropValue(String prop, String defaultValue, String encryptionKey) { try { - String result = CryptoUtils.decrypt(prop, encryptionKey); - return result; + return CryptoUtils.decrypt(prop, encryptionKey); } catch (GeneralSecurityException e) { logger.debug("Security exception", e); } return defaultValue; } - - - } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java index fff4c1d508..095182fe98 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java @@ -80,12 +80,8 @@ public class ResponseHandler { new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError) .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - ValidateException validateException = - new ValidateException.Builder("IOException getting Camunda response body", - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - throw validateException; + throw new ValidateException.Builder("IOException getting Camunda response body", HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); } ObjectMapper mapper = new ObjectMapper(); @@ -96,11 +92,8 @@ public class ResponseHandler { new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - ValidateException validateException = - new ValidateException.Builder("Cannot parse Camunda Response", HttpStatus.SC_BAD_REQUEST, - ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); - throw validateException; + throw new ValidateException.Builder("Cannot parse Camunda Response", HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); } if (response != null) { responseBody = response.getResponse(); @@ -125,22 +118,16 @@ public class ResponseHandler { } catch (IOException e) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - ValidateException validateException = - new ValidateException.Builder("Could not convert BPEL response to string", - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - throw validateException; + + throw new ValidateException.Builder("Could not convert BPEL response to string", HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); } if (status != HttpStatus.SC_ACCEPTED) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_ERROR_FROM_BPEL_SERVER, ErrorCode.BusinessProcesssError).targetEntity("BPEL").targetServiceName("parseBpel").build(); - - BPMNFailureException bpmnFailureException = - new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL) - .errorInfo(errorLoggerInfo).build(); - - throw bpmnFailureException; + throw new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL) + .errorInfo(errorLoggerInfo).build(); } } @@ -157,24 +144,17 @@ public class ResponseHandler { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - - ValidateException validateException = - new ValidateException.Builder("Could not convert CamundaTask response to string", - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - throw validateException; + throw new ValidateException.Builder("Could not convert CamundaTask response to string", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo) + .build(); } if (status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_ACCEPTED) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_ERROR_FROM_BPEL_SERVER, ErrorCode.BusinessProcesssError).targetEntity("CAMUNDATASK").targetServiceName("parseCamundaTask") .build(); - - BPMNFailureException bpmnFailureException = - new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL) - .errorInfo(errorLoggerInfo).build(); - - throw bpmnFailureException; + throw new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL) + .errorInfo(errorLoggerInfo).build(); } } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Constants.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Constants.java index 0bbc3e336f..ec583645ae 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Constants.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Constants.java @@ -23,8 +23,6 @@ package org.onap.so.apihandlerinfra; public class Constants { - private Constants() {} - public static final String REQUEST_ID_PATH = "/{request-id}"; public static final String STATUS_SUCCESS = "SUCCESS"; @@ -43,11 +41,13 @@ public class Constants { public static final String A_LA_CARTE = "aLaCarte"; - public final static String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA"; + public static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA"; - public final static String VNF_REQUEST_SCOPE = "vnf"; - public final static String SERVICE_INSTANCE_PATH = "/serviceInstances"; - public final static String SERVICE_INSTANTIATION_PATH = "/serviceInstantiation"; - public final static String ORCHESTRATION_REQUESTS_PATH = "/orchestrationRequests"; + public static final String VNF_REQUEST_SCOPE = "vnf"; + public static final String SERVICE_INSTANCE_PATH = "/serviceInstances"; + public static final String SERVICE_INSTANTIATION_PATH = "/serviceInstantiation"; + public static final String ORCHESTRATION_REQUESTS_PATH = "/orchestrationRequests"; + + private Constants() {} } 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 c491444f39..c1f55c7555 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 @@ -115,8 +115,7 @@ public class InstanceManagement { String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix); - sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, - requestId, requestUri); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -149,16 +148,15 @@ public class InstanceManagement { InfraActiveRequests dup = null; boolean inProgress = false; - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope, - currentActiveReq); + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); if (dup != null) { inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, null, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, + dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java index 67d6a0d1fc..7c0d327db7 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java @@ -24,8 +24,8 @@ import javax.annotation.PostConstruct; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletProperties; -import org.onap.so.apihandler.filters.RequestUriFilter; import org.onap.so.apihandler.filters.RequestIdFilter; +import org.onap.so.apihandler.filters.RequestUriFilter; import org.onap.so.apihandlerinfra.exceptions.ApiExceptionMapper; import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestration; import org.onap.so.apihandlerinfra.tenantisolation.CloudResourcesOrchestration; @@ -41,8 +41,6 @@ import io.swagger.jaxrs.listing.SwaggerSerializers; @ApplicationPath("/") public class JerseyConfiguration extends ResourceConfig { - - @PostConstruct public void setUp() { register(GlobalHealthcheckHandler.class); @@ -64,6 +62,7 @@ public class JerseyConfiguration extends ResourceConfig { register(E2EServiceInstances.class); register(WorkflowSpecificationsHandler.class); register(InstanceManagement.class); + register(ResumeOrchestrationRequest.class); // this registration seems to be needed to get predictable // execution behavior for the above JSON Exception Mappers register(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider.class); 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 34dcd4b0c4..ff8b5d14cd 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 @@ -35,6 +35,7 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -53,6 +54,7 @@ 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.serviceinstancebeans.CloudRequestData; import org.onap.so.serviceinstancebeans.GetOrchestrationListResponse; import org.onap.so.serviceinstancebeans.GetOrchestrationResponse; import org.onap.so.serviceinstancebeans.InstanceReferences; @@ -61,6 +63,7 @@ import org.onap.so.serviceinstancebeans.RequestDetails; import org.onap.so.serviceinstancebeans.RequestList; import org.onap.so.serviceinstancebeans.RequestStatus; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.onap.so.utils.UUIDChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -76,7 +79,6 @@ public class OrchestrationRequests { private static Logger logger = LoggerFactory.getLogger(OrchestrationRequests.class); - @Autowired private RequestsDbClient requestsDbClient; @@ -92,14 +94,23 @@ public class OrchestrationRequests { @Produces(MediaType.APPLICATION_JSON) @Transactional public Response getOrchestrationRequest(@PathParam("requestId") String requestId, - @PathParam("version") String version) throws ApiException { + @PathParam("version") String version, @QueryParam("includeCloudRequest") boolean includeCloudRequest) + throws ApiException { String apiVersion = version.substring(1); GetOrchestrationResponse orchestrationResponse = new GetOrchestrationResponse(); - InfraActiveRequests infraActiveRequest = null; List<org.onap.so.db.request.beans.RequestProcessingData> requestProcessingData = null; + + if (!UUIDChecker.isValidUUID(requestId)) { + + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MODIFIED_BY_APIHANDLER).build(); + throw new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); + } try { infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId); requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(requestId); @@ -109,14 +120,11 @@ public class OrchestrationRequests { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build(); - - ValidateException validateException = new ValidateException.Builder("Exception while communciate with Request DB - Infra Request Lookup", HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) .errorInfo(errorLoggerInfo).build(); - throw validateException; } @@ -126,7 +134,6 @@ public class OrchestrationRequests { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB", HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) @@ -135,7 +142,7 @@ public class OrchestrationRequests { throw validateException; } - Request request = mapInfraActiveRequestToRequest(infraActiveRequest); + Request request = mapInfraActiveRequestToRequest(infraActiveRequest, includeCloudRequest); if (!requestProcessingData.isEmpty()) { request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); } @@ -150,8 +157,8 @@ public class OrchestrationRequests { @ApiOperation(value = "Find Orchestrated Requests for a URI Information", response = Response.class) @Produces(MediaType.APPLICATION_JSON) @Transactional - public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version) - throws ApiException { + public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version, + @QueryParam("includeCloudRequest") boolean includeCloudRequest) throws ApiException { long startTime = System.currentTimeMillis(); @@ -188,7 +195,7 @@ public class OrchestrationRequests { List<RequestProcessingData> requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId()); RequestList requestList = new RequestList(); - Request request = mapInfraActiveRequestToRequest(infraActive); + Request request = mapInfraActiveRequestToRequest(infraActive, includeCloudRequest); if (!requestProcessingData.isEmpty()) { request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); } @@ -200,7 +207,6 @@ public class OrchestrationRequests { return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion); } - @POST @Path("/{version: [vV][4-7]}/{requestId}/unlock") @Consumes(MediaType.APPLICATION_JSON) @@ -251,7 +257,6 @@ public class OrchestrationRequests { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder("Null response from RequestDB when searching by RequestId", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo) @@ -273,7 +278,6 @@ public class OrchestrationRequests { new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) .build(); - ValidateException validateException = new ValidateException.Builder( "Orchestration RequestId " + requestId + " has a status of " + status + " and can not be unlocked", @@ -286,8 +290,8 @@ public class OrchestrationRequests { return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build(); } - private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException { - + private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar, boolean includeCloudRequest) + throws ApiException { String requestBody = iar.getRequestBody(); Request request = new Request(); @@ -300,7 +304,6 @@ public class OrchestrationRequests { String flowStatusMessage = iar.getFlowStatus(); String retryStatusMessage = iar.getRetryStatusMessage(); - InstanceReferences ir = new InstanceReferences(); if (iar.getNetworkId() != null) ir.setNetworkInstanceId(iar.getNetworkId()); @@ -329,8 +332,6 @@ public class OrchestrationRequests { if (iar.getInstanceGroupName() != null) ir.setInstanceGroupName(iar.getInstanceGroupName()); - - request.setInstanceReferences(ir); RequestDetails requestDetails = null; @@ -401,7 +402,6 @@ public class OrchestrationRequests { status.setTimeStamp(timeStamp); } - if (iar.getRequestStatus() != null) { status.setRequestState(iar.getRequestStatus()); } @@ -410,8 +410,19 @@ public class OrchestrationRequests { status.setPercentProgress(iar.getProgress().intValue()); } - request.setRequestStatus(status); + if (iar.getCloudApiRequests() != null && !iar.getCloudApiRequests().isEmpty() && includeCloudRequest) { + iar.getCloudApiRequests().stream().forEach(cloudRequest -> { + try { + request.getCloudRequestData() + .add(new CloudRequestData(mapper.readValue(cloudRequest.getRequestBody(), Object.class), + cloudRequest.getCloudIdentifier())); + } catch (Exception e) { + logger.error("Error reading Cloud Request", e); + } + }); + } + request.setRequestStatus(status); return request; } 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 bbcc120ab6..f6fc88d559 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 @@ -24,8 +24,20 @@ package org.onap.so.apihandlerinfra; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.databind.ObjectMapper; +import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; +import java.io.IOException; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.xml.bind.DatatypeConverter; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; @@ -76,20 +88,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestTemplate; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.xml.bind.DatatypeConverter; -import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; -import java.io.IOException; -import java.net.URL; -import java.security.GeneralSecurityException; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.ObjectMapper; @Component public class RequestHandlerUtils { @@ -293,9 +293,8 @@ public class RequestHandlerUtils { return requestUri; } - public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime, - MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) - throws ApiException { + public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, + String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { InfraActiveRequests dup = null; try { if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance @@ -369,8 +368,7 @@ public class RequestHandlerUtils { } public ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action, - long startTime, ServiceInstancesRequest sir, MsoRequest msoRequest, String requestId, String requestUri) - throws ApiException { + String requestId, String requestUri) throws ApiException { try { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(requestJSON, ServiceInstancesRequest.class); @@ -415,8 +413,8 @@ public class RequestHandlerUtils { } public void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action, - HashMap<String, String> instanceIdMap, long startTime, MsoRequest msoRequest, String instanceName, - String requestScope, InfraActiveRequests dup) throws ApiException { + HashMap<String, String> instanceIdMap, String instanceName, String requestScope, InfraActiveRequests dup) + throws ApiException { String instance = null; if (instanceName != null) { @@ -622,4 +620,27 @@ public class RequestHandlerUtils { return requestScope; } + protected InfraActiveRequests createNewRecordCopyFromInfraActiveRequest(InfraActiveRequests infraActiveRequest, + String requestId, Timestamp startTimeStamp, String source, String requestUri, String requestorId) { + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId(requestId); + request.setStartTime(startTimeStamp); + request.setSource(source); + request.setRequestUrl(requestUri); + request.setProgress(new Long(5)); + request.setRequestorId(requestorId); + request.setRequestStatus(Status.IN_PROGRESS.toString()); + request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + if (infraActiveRequest != null) { + request.setTenantId(infraActiveRequest.getTenantId()); + request.setRequestBody(infraActiveRequest.getRequestBody()); + request.setAicCloudRegion(infraActiveRequest.getAicCloudRegion()); + request.setRequestScope(infraActiveRequest.getRequestScope()); + request.setServiceInstanceId(infraActiveRequest.getServiceInstanceId()); + request.setServiceInstanceName(infraActiveRequest.getServiceInstanceName()); + request.setRequestAction(infraActiveRequest.getRequestAction()); + } + return request; + } + } 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 new file mode 100644 index 0000000000..6ca23a339b --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java @@ -0,0 +1,236 @@ +/*- + * ============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 java.io.IOException; +import java.sql.Timestamp; +import java.util.HashMap; +import javax.transaction.Transactional; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +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.apache.http.HttpStatus; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; +import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.logger.ErrorCode; +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.ServiceInstancesRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("onap/so/infra/orchestrationRequests") +@Api(value = "onap/so/infra/orchestrationRequests") +@Component +public class ResumeOrchestrationRequest { + private static Logger logger = LoggerFactory.getLogger(ResumeOrchestrationRequest.class); + private static final String SAVE_TO_DB = "save instance to db"; + private static String uriPrefix = "/orchestrationRequests/"; + + @Autowired + private RequestHandlerUtils requestHandlerUtils; + + @Autowired + private ServiceInstances serviceInstances; + + @Autowired + private RequestsDbClient requestsDbClient; + + + @POST + @Path("/{version:[vV][7]}/requests/{requestId}/resume") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Resume request for a given requestId", response = Response.class) + @Transactional + public Response resumeOrchestrationRequest(@PathParam("requestId") String requestId, + @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { + + Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + String currentRequestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + logger.info("Beginning resume operation for new request: {}", currentRequestId); + InfraActiveRequests infraActiveRequest = null; + String source = MDC.get(MdcConstants.ORIGINAL_PARTNER_NAME); + String requestorId = MDC.get(HttpHeadersConstants.REQUESTOR_ID); + requestHandlerUtils.getRequestUri(requestContext, uriPrefix); + String requestUri = MDC.get(LogConstants.HTTP_URL); + version = version.substring(1); + + try { + infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId); + } catch (HttpClientErrorException e) { + logger.error("Error occurred while performing requestDb lookup by requestId: " + requestId, e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build(); + throw new ValidateException.Builder("Exception while performing requestDb lookup by requestId", + HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) + .errorInfo(errorLoggerInfo).build(); + } + + InfraActiveRequests currentActiveRequest = requestHandlerUtils.createNewRecordCopyFromInfraActiveRequest( + infraActiveRequest, currentRequestId, startTimeStamp, source, requestUri, requestorId); + + if (infraActiveRequest == null) { + logger.error("No infraActiveRequest record found for requestId: {} in requesteDb lookup", requestId); + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, + ErrorCode.BusinessProcesssError).build(); + ValidateException validateException = new ValidateException.Builder( + "Null response from requestDB when searching by requestId: " + requestId, HttpStatus.SC_NOT_FOUND, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + requestHandlerUtils.updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage()); + throw validateException; + + } + + return resumeRequest(infraActiveRequest, currentActiveRequest, version, requestUri); + } + + protected Response resumeRequest(InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest, + String version, String requestUri) throws ApiException { + 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(); + + checkForInProgressRequest(currentActiveRequest, serviceInstanceId, requestScope, serviceInstanceName, 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); + + requestDbSave(currentActiveRequest); + + RequestClientParameter requestClientParameter = setRequestClientParameter(recipeLookupResult, version, + infraActiveRequest, currentActiveRequest, pnfCorrelationId, aLaCarte, sir); + + return requestHandlerUtils.postBPELRequest(currentActiveRequest, requestClientParameter, + 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); + } + if (inProgress) { + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveRequest, action, instanceIdMap, + serviceInstanceName, requestScope, requestInProgress); + } + } + + protected RecipeLookupResult serviceRecipeLookup(InfraActiveRequests currentActiveRequest, + ServiceInstancesRequest sir, Action action, Boolean aLaCarte) + throws ValidateException, RequestDbFailureException { + RecipeLookupResult recipeLookupResult = null; + 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(); + requestHandlerUtils.updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage()); + throw validateException; + } + return recipeLookupResult; + } + + protected void requestDbSave(InfraActiveRequests currentActiveRequest) throws RequestDbFailureException { + try { + requestsDbClient.save(currentActiveRequest); + } catch (Exception e) { + logger.error("Exception while saving request to requestDb", e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); + } + } + + protected RequestClientParameter setRequestClientParameter(RecipeLookupResult recipeLookupResult, String version, + InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest, String pnfCorrelationId, + Boolean aLaCarte, ServiceInstancesRequest sir) throws ValidateException { + RequestClientParameter requestClientParameter = null; + 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(); + } catch (IOException e) { + logger.error("IOException while generating requestClientParameter to send to BPMN", e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new ValidateException.Builder( + "IOException while generating requestClientParameter to send to BPMN: " + e.getMessage(), + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo) + .build(); + } + return requestClientParameter; + } +} 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 931a1eb52b..7c8d24742d 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 @@ -765,8 +765,7 @@ public class ServiceInstances { ServiceInstancesRequest sir = null; String apiVersion = version.substring(1); - sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, - requestId, requestUri); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -797,16 +796,15 @@ public class ServiceInstances { InfraActiveRequests dup = null; boolean inProgress = false; - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName, - requestScope, currentActiveReq); + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq); if (dup != null) { inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, instanceName, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, + requestScope, dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -968,8 +966,8 @@ public class ServiceInstances { throw validateException; } - InfraActiveRequests dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, - requestScope, currentActiveReq); + InfraActiveRequests dup = + requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); boolean inProgress = false; if (dup != null) { @@ -977,8 +975,8 @@ public class ServiceInstances { } if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, null, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, + dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -1011,7 +1009,7 @@ public class ServiceInstances { recipeLookupResult.getOrchestrationURI(), requestScope); } - private String getPnfCorrelationId(ServiceInstancesRequest sir) { + protected String getPnfCorrelationId(ServiceInstancesRequest sir) { return Optional.of(sir).map(ServiceInstancesRequest::getRequestDetails) .map(RequestDetails::getRequestParameters).map(parameters -> parameters.getUserParamValue("pnfId")) .orElse(""); @@ -1103,8 +1101,8 @@ public class ServiceInstances { return recipeLookupResult; } - private RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action, boolean alaCarteFlag) - throws IOException { + protected RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action, + boolean alaCarteFlag) throws IOException { // SERVICE REQUEST // Construct the default service name // TODO need to make this a configurable property @@ -1598,8 +1596,7 @@ public class ServiceInstances { long startTime = System.currentTimeMillis(); ServiceInstancesRequest sir = null; - sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, - requestId, requestUri); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -1613,16 +1610,15 @@ public class ServiceInstances { InfraActiveRequests dup = null; - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName, - requestScope, currentActiveReq); + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq); if (dup != null) { inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (instanceIdMap != null && dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, instanceName, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, + requestScope, dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java index 77abbbfa9a..6e77ce84a6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java @@ -21,7 +21,7 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; -import java.sql.Timestamp; + import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java index f7fa01aeb0..4fc6181bf8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java @@ -29,13 +29,7 @@ public class GetE2EServiceInstanceResponse { protected OperationStatus operation; - // public OperationStatus getOperationStatus() { - // return operation; - // } - // - // public void setOperationStatus(OperationStatus requestDB) { - // this.operation = requestDB; - // } + public OperationStatus getOperation() { return operation; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java index 44592ce2e4..ae462ebffa 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java @@ -39,6 +39,9 @@ public class ResourceRequest { @JsonProperty("resourceCustomizationUuid") private String resourceCustomizationUuid; + @JsonProperty("resourceIndex") + private String resourceIndex; + @JsonProperty("parameters") private E2EParameters parameters; @@ -98,4 +101,12 @@ public class ResourceRequest { public void setParameters(E2EParameters parameters) { this.parameters = parameters; } + + public String getResourceIndex() { + return resourceIndex; + } + + public void setResourceIndex(String resourceIndex) { + this.resourceIndex = resourceIndex; + } } 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 8b3b91ae1a..d9db5713a7 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 @@ -42,7 +42,7 @@ import org.springframework.stereotype.Component; @Component public class AAIClientHelper { - private static Logger logger = LoggerFactory.getLogger(AAIClientHelper.class); + /** * Get managing ECOMP Environment Info from A&AI diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java index 98b49d39d7..1e5958c540 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java @@ -31,7 +31,7 @@ import org.springframework.stereotype.Component; @Component public class ActivateVnfDBHelper { - private static Logger logger = LoggerFactory.getLogger(ActivateVnfDBHelper.class); + /** * Insert record to OperationalEnvServiceModelStatus table diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java index 4c66a3118e..c50f18c594 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java @@ -34,7 +34,7 @@ public class Manifest implements Serializable { private static final long serialVersionUID = -3460949513229380541L; @JsonProperty("serviceModelList") - private List<ServiceModelList> serviceModelList = new ArrayList<ServiceModelList>(); + private List<ServiceModelList> serviceModelList = new ArrayList<>(); public List<ServiceModelList> getServiceModelList() { return serviceModelList; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java index 907bc942eb..2cf01f9390 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java @@ -29,51 +29,59 @@ import org.onap.so.utils.UUIDChecker; public class InstanceIdMapValidation implements ValidationRule { + private static final String Service_InstanceId = "serviceInstanceId"; + private static final String Vnf_InstanceId = "vnfInstanceId"; + private static final String vfModule_InstanceId = "vfModuleInstanceId"; + + private static final String volume_Group_InstanceId = "volumeGroupInstanceId"; + private static final String Network_Instance_Id = "networkInstanceId"; + private static final String Configuration_Instance_Id = "configurationInstanceId"; + @Override public ValidationInformation validate(ValidationInformation info) throws ValidationException { HashMap<String, String> instanceIdMap = info.getInstanceIdMap(); ServiceInstancesRequest sir = info.getSir(); if (instanceIdMap != null) { - if (instanceIdMap.get("serviceInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("serviceInstanceId"))) { - throw new ValidationException("serviceInstanceId"); + if (instanceIdMap.get(Service_InstanceId) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(Service_InstanceId))) { + throw new ValidationException(Service_InstanceId); } - sir.setServiceInstanceId(instanceIdMap.get("serviceInstanceId")); + sir.setServiceInstanceId(instanceIdMap.get(Service_InstanceId)); } - if (instanceIdMap.get("vnfInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("vnfInstanceId"))) { - throw new ValidationException("vnfInstanceId"); + if (instanceIdMap.get(Vnf_InstanceId) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(Vnf_InstanceId))) { + throw new ValidationException(Vnf_InstanceId); } - sir.setVnfInstanceId(instanceIdMap.get("vnfInstanceId")); + sir.setVnfInstanceId(instanceIdMap.get(Vnf_InstanceId)); } - if (instanceIdMap.get("vfModuleInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("vfModuleInstanceId"))) { - throw new ValidationException("vfModuleInstanceId"); + if (instanceIdMap.get(vfModule_InstanceId) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(vfModule_InstanceId))) { + throw new ValidationException(vfModule_InstanceId); } - sir.setVfModuleInstanceId(instanceIdMap.get("vfModuleInstanceId")); + sir.setVfModuleInstanceId(instanceIdMap.get(vfModule_InstanceId)); } - if (instanceIdMap.get("volumeGroupInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("volumeGroupInstanceId"))) { - throw new ValidationException("volumeGroupInstanceId"); + if (instanceIdMap.get(volume_Group_InstanceId) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(volume_Group_InstanceId))) { + throw new ValidationException(volume_Group_InstanceId); } - sir.setVolumeGroupInstanceId(instanceIdMap.get("volumeGroupInstanceId")); + sir.setVolumeGroupInstanceId(instanceIdMap.get(volume_Group_InstanceId)); } - if (instanceIdMap.get("networkInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("networkInstanceId"))) { - throw new ValidationException("networkInstanceId"); + if (instanceIdMap.get(Network_Instance_Id) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(Network_Instance_Id))) { + throw new ValidationException(Network_Instance_Id); } - sir.setNetworkInstanceId(instanceIdMap.get("networkInstanceId")); + sir.setNetworkInstanceId(instanceIdMap.get(Network_Instance_Id)); } - if (instanceIdMap.get("configurationInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("configurationInstanceId"))) { - throw new ValidationException("configurationInstanceId"); + if (instanceIdMap.get(Configuration_Instance_Id) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(Configuration_Instance_Id))) { + throw new ValidationException(Configuration_Instance_Id); } - sir.setConfigurationId(instanceIdMap.get("configurationInstanceId")); + sir.setConfigurationId(instanceIdMap.get(Configuration_Instance_Id)); } if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java index 2236b09f2a..7a0a6fe633 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java @@ -49,8 +49,7 @@ import javax.xml.namespace.QName; public class ObjectFactory { private final static QName _VnfParams_QNAME = new QName("http://org.onap/so/infra/vnf-request/v1", "vnf-params"); - private final static QName _NetworkParams_QNAME = - new QName("http://org.onap/so/infra/vnf-request/v1", "network-params"); + /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java index 321ea3ac7d..f82f5ac746 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java @@ -42,12 +42,12 @@ import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; -import org.junit.Ignore; import org.junit.Test; import org.onap.so.apihandler.common.ErrorNumbers; 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.serviceinstancebeans.CloudRequestData; import org.onap.so.serviceinstancebeans.GetOrchestrationListResponse; import org.onap.so.serviceinstancebeans.GetOrchestrationResponse; import org.onap.so.serviceinstancebeans.Request; @@ -119,7 +119,7 @@ public class OrchestrationRequestsTest extends BaseTest { assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - assertEquals("00032ab7-na18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0)); + assertEquals("00032ab7-1a18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0)); assertNotNull(response.getBody().getRequest().getFinishTime()); } @@ -149,12 +149,22 @@ public class OrchestrationRequestsTest extends BaseTest { } @Test - public void testGetOrchestrationRequestRequestDetails() throws Exception { - setupTestGetOrchestrationRequestRequestDetails("00032ab7-3fb3-42e5-965d-8ea592502017", "COMPLETED"); + public void testGetOrchestrationRequestWithOpenstackDetails() throws Exception { + setupTestGetOrchestrationRequestOpenstackDetails("00032ab7-3fb3-42e5-965d-8ea592502017", "COMPLETED"); // Test request with modelInfo request body GetOrchestrationResponse testResponse = new GetOrchestrationResponse(); Request request = ORCHESTRATION_LIST.getRequestList().get(0).getRequest(); + List<CloudRequestData> cloudRequestData = new ArrayList<>(); + CloudRequestData cloudData = new CloudRequestData(); + cloudData.setCloudIdentifier("heatstackName/123123"); + ObjectMapper mapper = new ObjectMapper(); + Object reqData = mapper.readValue( + "{\r\n \"test\": \"00032ab7-3fb3-42e5-965d-8ea592502016\",\r\n \"test2\": \"deleteInstance\",\r\n \"test3\": \"COMPLETE\",\r\n \"test4\": \"Vf Module has been deleted successfully.\",\r\n \"test5\": 100\r\n}", + Object.class); + cloudData.setCloudRequest(reqData); + cloudRequestData.add(cloudData); + request.setCloudRequestData(cloudRequestData); testResponse.setRequest(request); String testRequestId = request.getRequestId(); @@ -163,13 +173,14 @@ public class OrchestrationRequestsTest extends BaseTest { headers.set("Content-Type", MediaType.APPLICATION_JSON); HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); - UriComponentsBuilder builder = UriComponentsBuilder - .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort( + "/onap/so/infra/orchestrationRequests/v7/" + testRequestId + "?includeCloudRequest=true")); ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); - + System.out.println("Response :" + response.getBody().toString()); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("request.startTime") .ignoring("request.finishTime").ignoring("request.requestStatus.timeStamp")); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); @@ -194,6 +205,29 @@ public class OrchestrationRequestsTest extends BaseTest { } @Test + public void testGetOrchestrationRequestInvalidRequestID() throws Exception { + setupTestGetOrchestrationRequest(); + // TEST INVALID REQUESTID + GetOrchestrationResponse testResponse = new GetOrchestrationResponse(); + + Request request = ORCHESTRATION_LIST.getRequestList().get(1).getRequest(); + testResponse.setRequest(request); + String testRequestId = "00032ab7-pfb3-42e5-965d-8ea592502016"; + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); + + UriComponentsBuilder builder = UriComponentsBuilder + .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)); + + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + } + + @Test public void testGetOrchestrationRequestFilter() throws Exception { setupTestGetOrchestrationRequestFilter(); List<String> values = new ArrayList<>(); @@ -319,75 +353,11 @@ public class OrchestrationRequestsTest extends BaseTest { "/onap/so/infra/orchestrationRequests/v7/" + "5ffbabd6-b793-4377-a1ab-082670fbc7ac" + "/unlock")); response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); - // Cannot assert anything further here, already have a wiremock in place which ensures that the post was + // Cannot assert anything further here, already have a wiremock in place + // which ensures that the post was // properly called to update. } - @Ignore // What is this testing? - @Test - public void testGetOrchestrationRequestRequestDetailsWhiteSpace() throws Exception { - InfraActiveRequests requests = new InfraActiveRequests(); - requests.setAction("create"); - requests.setRequestBody(" "); - requests.setRequestId("requestId"); - requests.setRequestScope("service"); - requests.setRequestType("createInstance"); - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writeValueAsString(requests); - - requestsDbClient.save(requests); - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder - .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId")); - - ResponseEntity<GetOrchestrationResponse> response = - restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); - assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); - assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); - assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - assertEquals("requestId", response.getHeaders().get("X-TransactionID").get(0)); - } - - @Ignore // What is this testing? - @Test - public void testGetOrchestrationRequestRequestDetailsAlaCarte() throws IOException { - InfraActiveRequests requests = new InfraActiveRequests(); - - String requestJSON = new String( - Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/AlaCarteRequest.json"))); - - requests.setAction("create"); - requests.setRequestBody(requestJSON); - requests.setRequestId("requestId"); - requests.setRequestScope("service"); - requests.setRequestType("createInstance"); - // iar.save(requests); - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder - .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId")); - - ResponseEntity<GetOrchestrationResponse> response = - restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); - assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); - assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); - assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - assertEquals("requestId", response.getHeaders().get("X-TransactionID").get(0)); - } - @Test public void mapRequestProcessingDataTest() throws JsonParseException, JsonMappingException, IOException { RequestProcessingData entry = new RequestProcessingData(); @@ -423,14 +393,14 @@ public class OrchestrationRequestsTest extends BaseTest { public void setupTestGetOrchestrationRequest() throws Exception { // For testGetOrchestrationRequest - wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")) + wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-1a18-42e5-965d-8ea592502018")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(new String(Files.readAllBytes( Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequest.json")))) .withStatus(HttpStatus.SC_OK))); wireMockServer .stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) - .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) + .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-1a18-42e5-965d-8ea592502018")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(new String(Files.readAllBytes(Paths .get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) @@ -439,14 +409,14 @@ public class OrchestrationRequestsTest extends BaseTest { public void setupTestGetOrchestrationRequestInstanceGroup() throws Exception { // For testGetOrchestrationRequest - wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")) + wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-1a18-42e5-965d-8ea592502018")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(new String(Files.readAllBytes(Paths.get( "src/test/resources/OrchestrationRequest/getOrchestrationRequestInstanceGroup.json")))) .withStatus(HttpStatus.SC_OK))); wireMockServer .stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) - .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) + .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-1a18-42e5-965d-8ea592502018")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(new String(Files.readAllBytes(Paths .get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) @@ -461,15 +431,20 @@ public class OrchestrationRequestsTest extends BaseTest { .withStatus(HttpStatus.SC_OK))); } + private void setupTestGetOrchestrationRequestOpenstackDetails(String requestId, String status) throws Exception { + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes(Paths + .get("src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json")))) + .withStatus(HttpStatus.SC_OK))); + } + private void setupTestUnlockOrchestrationRequest(String requestId, String status) { wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(String.format(getResponseTemplate, requestId, status)).withStatus(HttpStatus.SC_OK))); - } - - private void setupTestUnlockOrchestrationRequest_invalid_Json() { wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(INVALID_REQUEST_ID))).willReturn(aResponse() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_NOT_FOUND))); 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 new file mode 100644 index 0000000000..e80fd9e690 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java @@ -0,0 +1,118 @@ +/*- + * ============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 java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.Timestamp; +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.db.request.beans.InfraActiveRequests; + +@RunWith(MockitoJUnitRunner.class) +public class RequestHandlerUtilsUnitTest { + + @Spy + private RequestHandlerUtils requestHandler; + + private static final String CURRENT_REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4"; + private static final String SERVICE_INSTANCE_ID = "00032ab7-na18-42e5-965d-8ea592502018"; + 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(); + + public String getRequestBody(String request) throws IOException { + request = "src/test/resources/ResumeOrchestrationRequest" + request; + return new String(Files.readAllBytes(Paths.get(request))); + } + + @Before + public void setup() throws IOException { + setInfraActiveRequest(); + setCurrentActiveRequest(); + setCurrentActiveRequestNullInfraActive(); + } + + private void setInfraActiveRequest() throws IOException { + infraActiveRequest.setTenantId("tenant-id"); + infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + infraActiveRequest.setAicCloudRegion("cloudRegion"); + infraActiveRequest.setRequestScope("service"); + infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); + infraActiveRequest.setServiceInstanceName("serviceInstanceName"); + infraActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + infraActiveRequest.setRequestAction(Action.createInstance.toString()); + infraActiveRequest.setServiceType("serviceType"); + } + + private void setCurrentActiveRequest() throws IOException { + currentActiveRequest.setRequestId(CURRENT_REQUEST_ID); + currentActiveRequest.setSource("VID"); + currentActiveRequest.setStartTime(startTimeStamp); + currentActiveRequest.setTenantId("tenant-id"); + currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.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.setProgress(new Long(5)); + } + + private void setCurrentActiveRequestNullInfraActive() throws IOException { + currentActiveRequestIARNull.setRequestId(CURRENT_REQUEST_ID); + currentActiveRequestIARNull.setSource("VID"); + currentActiveRequestIARNull.setStartTime(startTimeStamp); + currentActiveRequestIARNull.setRequestStatus(Status.IN_PROGRESS.toString()); + currentActiveRequestIARNull.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + currentActiveRequestIARNull.setRequestUrl(requestUri); + currentActiveRequestIARNull.setRequestorId("xxxxxx"); + currentActiveRequestIARNull.setProgress(new Long(5)); + } + + + @Test + public void createNewRecordCopyFromInfraActiveRequestTest() { + InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(infraActiveRequest, + CURRENT_REQUEST_ID, startTimeStamp, "VID", requestUri, "xxxxxx"); + assertThat(currentActiveRequest, sameBeanAs(result)); + } + + @Test + public void createNewRecordCopyFromInfraActiveRequestNullIARTest() { + InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(null, CURRENT_REQUEST_ID, + startTimeStamp, "VID", requestUri, "xxxxxx"); + assertThat(currentActiveRequestIARNull, sameBeanAs(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 new file mode 100644 index 0000000000..92490a66b8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java @@ -0,0 +1,328 @@ +/*- + * ============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.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.doNothing; +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 java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.Timestamp; +import java.util.HashMap; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Response; +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.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +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.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.springframework.web.client.HttpClientErrorException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(MockitoJUnitRunner.class) +public class ResumeOrchestrationRequestTest { + @Mock + private RequestHandlerUtils requestHandler; + + @Mock + private MsoRequest msoRequest; + + @Mock + private ServiceInstances serviceInstances; + + @Mock + private RequestsDbClient requestDbClient; + + @InjectMocks + @Spy + private ResumeOrchestrationRequest resumeReq; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + 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 SERVICE_INSTANCE_NAME = "serviceInstanceName"; + private static final String REQUEST_SCOPE = "service"; + private final Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + private final Action action = Action.createInstance; + private final Boolean aLaCarte = false; + private final String version = "7"; + private final String requestUri = + "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 ObjectMapper mapper = new ObjectMapper(); + private InfraActiveRequests infraActiveRequest = new InfraActiveRequests(); + private InfraActiveRequests currentActiveRequest = 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<>(); + + + @Before + public void setup() throws ValidateException, IOException { + // Setup general requestHandler mocks + when(requestHandler.getRequestUri(any(), anyString())).thenReturn(requestUri); + + // Setup InfraActiveRequests + setInfraActiveRequest(); + setCurrentActiveRequest(); + + requestBody = infraActiveRequest.getRequestBody(); + sir = mapper.readValue(requestBody, ServiceInstancesRequest.class); + requestBodyNullALaCarte = getRequestBody("/ALaCarteNull.json"); + sirNullALaCarte = sir = mapper.readValue(requestBodyNullALaCarte, ServiceInstancesRequest.class); + setRequestClientParameter(); + instanceIdMap.put("serviceInstanceId", SERVICE_INSTANCE_ID); + } + + public String getRequestBody(String request) throws IOException { + request = "src/test/resources/ResumeOrchestrationRequest" + request; + return new String(Files.readAllBytes(Paths.get(request))); + } + + private void setInfraActiveRequest() throws IOException { + infraActiveRequest.setTenantId("tenant-id"); + infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + infraActiveRequest.setAicCloudRegion("cloudRegion"); + infraActiveRequest.setRequestScope(REQUEST_SCOPE); + infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); + infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); + infraActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + infraActiveRequest.setRequestAction(Action.createInstance.toString()); + infraActiveRequest.setServiceType("serviceType"); + } + + private void setCurrentActiveRequest() throws IOException { + currentActiveRequest.setRequestId(CURRENT_REQUEST_ID); + currentActiveRequest.setSource("VID"); + currentActiveRequest.setStartTime(startTimeStamp); + currentActiveRequest.setTenantId("tenant-id"); + currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + currentActiveRequest.setAicCloudRegion("cloudRegion"); + currentActiveRequest.setRequestScope(REQUEST_SCOPE); + currentActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); + currentActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); + currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + currentActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + currentActiveRequest.setRequestAction(Action.createInstance.toString()); + currentActiveRequest.setRequestUrl(requestUri); + currentActiveRequest.setRequestorId("xxxxxx"); + currentActiveRequest.setProgress(new Long(5)); + } + + 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(); + } + + @Test + public void resumeOrchestationRequestTest() throws Exception { + Response response = null; + 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)); + doReturn(response).when(resumeReq).resumeRequest(any(InfraActiveRequests.class), any(InfraActiveRequests.class), + anyString(), nullable(String.class)); + + resumeReq.resumeOrchestrationRequest(REQUEST_ID, "v7", requestContext); + + verify(resumeReq).resumeRequest(infraActiveRequest, currentActiveRequest, version, null); + } + + @Test + public void resumeOrchestationRequestDbNullResultTest() throws Exception { + when(requestDbClient.getInfraActiveRequestbyRequestId("00032ab7-na18-42e5-965d-8ea592502018")).thenReturn(null); + + thrown.expect(ValidateException.class); + thrown.expectMessage( + "Null response from requestDB when searching by requestId: 00032ab7-na18-42e5-965d-8ea592502018"); + resumeReq.resumeOrchestrationRequest("00032ab7-na18-42e5-965d-8ea592502018", "v7", requestContext); + } + + @Test + public void resumeOrchestationRequestDbErrorTest() throws Exception { + when(requestDbClient.getInfraActiveRequestbyRequestId("00032ab7-na18-42e5-965d-8ea592502018")) + .thenThrow(HttpClientErrorException.class); + + thrown.expect(ValidateException.class); + thrown.expectMessage("Exception while performing requestDb lookup by requestId"); + resumeReq.resumeOrchestrationRequest("00032ab7-na18-42e5-965d-8ea592502018", "v7", requestContext); + } + + @Test + public void resumeRequestTest() throws ApiException, IOException { + Response response = null; + 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(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, + SERVICE_INSTANCE_NAME, action); + + resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version, + "/onap/so/infra/orchestrationRequests/v7/requests/00032ab7-na18-42e5-965d-8ea592502018/resume"); + verify(requestHandler).postBPELRequest(currentActiveRequest, requestClientParameter, + lookupResult.getOrchestrationURI(), infraActiveRequest.getRequestScope()); + } + + @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 { + when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(), + any(Action.class))).thenReturn(requestBody); + RequestClientParameter result = resumeReq.setRequestClientParameter(lookupResult, version, infraActiveRequest, + currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); + assertThat(requestClientParameter, sameBeanAs(result)); + } + + @Test + public void requestDbSaveTest() throws RequestDbFailureException { + doNothing().when(requestDbClient).save(currentActiveRequest); + resumeReq.requestDbSave(currentActiveRequest); + verify(requestDbClient).save(currentActiveRequest); + } + + @Test + public void resumeRequestTestALaCarteNull() throws ApiException, IOException { + Response response = null; + + 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(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, + SERVICE_INSTANCE_NAME, action); + + resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version, + "/onap/so/infra/orchestrationRequests/v7/requests/00032ab7-na18-42e5-965d-8ea592502018/resume"); + verify(requestHandler).postBPELRequest(currentActiveRequest, requestClientParameter, + lookupResult.getOrchestrationURI(), infraActiveRequest.getRequestScope()); + } + + @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 { + when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(), + any(Action.class))).thenThrow(new IOException("IOException")); + + thrown.expect(ValidateException.class); + thrown.expectMessage("IOException while generating requestClientParameter to send to BPMN: IOException"); + resumeReq.setRequestClientParameter(lookupResult, version, infraActiveRequest, currentActiveRequest, + "pnfCorrelationId", aLaCarte, sir); + } + + @Test + public void checkForInProgressRequest() throws ApiException { + doReturn(infraActiveRequest).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, + REQUEST_SCOPE, currentActiveRequest); + doReturn(true).when(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); + doThrow(DuplicateRequestException.class).when(requestHandler).buildErrorOnDuplicateRecord(currentActiveRequest, + action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, infraActiveRequest); + + thrown.expect(DuplicateRequestException.class); + resumeReq.checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, + SERVICE_INSTANCE_NAME, action); + } + + @Test + public void checkForInProgressRequestNoInProgressRequests() throws ApiException { + doReturn(null).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, + currentActiveRequest); + + resumeReq.checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, + SERVICE_INSTANCE_NAME, action); + verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, + currentActiveRequest); + } + + @Test + public void checkForInProgressRequestCamundaHistoryCheckReturnsNoInProgress() throws ApiException { + doReturn(infraActiveRequest).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, + REQUEST_SCOPE, 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, + currentActiveRequest); + verify(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); + } + + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json index 90089c0c7e..baddb21617 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json @@ -34,7 +34,7 @@ }, { "request":{ - "requestId":"00032ab7-na18-42e5-965d-8ea592502018", + "requestId":"00032ab7-1a18-42e5-965d-8ea592502018", "requestScope":"vfModule", "requestType":"deleteInstance", "requestDetails":{ @@ -298,7 +298,7 @@ }, { "request":{ - "requestId":"00032ab7-na18-42e5-965d-8ea592502018", + "requestId":"00032ab7-1a18-42e5-965d-8ea592502018", "requestScope":"instanceGroup", "requestType":"addMembers", "requestDetails":{ diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json new file mode 100644 index 0000000000..41d7e4d706 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json @@ -0,0 +1,62 @@ +{ + "clientRequestId": "00032ab7-3fb3-42e5-965d-8ea592502016", + "action": "deleteInstance", + "requestStatus": "COMPLETE", + "statusMessage": "Vf Module has been deleted successfully.", + "progress": 100, + "startTime": "2016-12-22T13:29:54.000+0000", + "endTime": "2016-12-22T13:30:28.000+0000", + "source": "VID", + "vnfId": "b92f60c8-8de3-46c1-8dc1-e4390ac2b005", + "vnfName": null, + "vnfType": null, + "serviceType": null, + "aicNodeClli": null, + "tenantId": "6accefef3cb442ff9e644d589fb04107", + "provStatus": null, + "vnfParams": null, + "vnfOutputs": null, + "requestBody": "{\"modelInfo\":{\"modelType\":\"vfModule\",\"modelName\":\"test::base::module-0\"},\"requestInfo\":{\"source\":\"VID\"},\"cloudConfiguration\":{\"tenantId\":\"6accefef3cb442ff9e644d589fb04107\",\"lcpCloudRegionId\":\"n6\"}}", + "responseBody": null, + "lastModifiedBy": "BPMN", + "modifyTime": "2016-12-22T13:30:28.000+0000", + "requestType": null, + "volumeGroupId": null, + "volumeGroupName": null, + "vfModuleId": "c7d527b1-7a91-49fd-b97d-1c8c0f4a7992", + "vfModuleName": null, + "vfModuleModelName": "test::base::module-0", + "aaiServiceId": null, + "aicCloudRegion": "n6", + "callBackUrl": null, + "correlator": null, + "serviceInstanceId": "e3b5744d-2ad1-4cdd-8390-c999a38829bc", + "serviceInstanceName": null, + "requestScope": "vfModule", + "requestAction": "deleteInstance", + "networkId": null, + "networkName": null, + "networkType": null, + "requestorId": null, + "configurationId": null, + "configurationName": null, + "operationalEnvId": null, + "operationalEnvName": null, + "cloudApiRequests":[ + { + "id": 1, + "cloudIdentifier": "heatstackName/123123", + "requestBody":"{\r\n \"test\": \"00032ab7-3fb3-42e5-965d-8ea592502016\",\r\n \"test2\": \"deleteInstance\",\r\n \"test3\": \"COMPLETE\",\r\n \"test4\": \"Vf Module has been deleted successfully.\",\r\n \"test5\": 100\r\n}", + "created": "2016-12-22T13:29:54.000+0000" + } + ], + "requestURI": "00032ab7-3fb3-42e5-965d-8ea592502017", + "_links": { + "self": { + "href": "http://localhost:8087/infraActiveRequests/00032ab7-3fb3-42e5-965d-8ea592502017" + }, + "infraActiveRequests": { + "href": "http://localhost:8087/infraActiveRequests/00032ab7-3fb3-42e5-965d-8ea592502017" + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json new file mode 100644 index 0000000000..5da139e711 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json @@ -0,0 +1,13 @@ +{ + "requestDetails":{ + "requestInfo":{ + "source":"VID", + "requestorId":"xxxxxx", + "instanceName":"testService", + "productFamilyId":"test" + }, + "requestParameters":{ + "usePreload": "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 new file mode 100644 index 0000000000..5cd31427a0 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json @@ -0,0 +1,13 @@ +{ + "requestDetails":{ + "requestInfo":{ + "source":"VID", + "requestorId":"xxxxxx", + "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/application-test.yaml b/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml index 712fbf54ca..2e1c6a9bdc 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml @@ -83,6 +83,8 @@ mso: spring: + jersey: + type: filter datasource: jdbcUrl: jdbc:mariadb://localhost:3307/catalogdb username: root @@ -97,11 +99,10 @@ spring: naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy enable-lazy-load-no-trans: true database-platform: org.hibernate.dialect.MySQL5InnoDBDialect - jersey: - type: filter + security: usercredentials: - - + - username: test password: '$2a$12$Zi3AuYcZoZO/gBQyUtST2.F5N6HqcTtaNci2Et.ufsQhski56srIu' role: InfraPortal-Client 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 bc9003f5d0..c2eb21b18e 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 @@ -1108,6 +1108,7 @@ CREATE TABLE `vnf_resource_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), KEY `fk_vnf_resource_customization__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`), @@ -1134,6 +1135,8 @@ CREATE TABLE `vnfc_customization` ( `MODEL_NAME` varchar(200) NOT NULL, `TOSCA_NODE_TYPE` varchar(200) NOT NULL, `DESCRIPTION` varchar(1200) DEFAULT NULL, + `RESOURCE_INPUT` varchar(20000) DEFAULT NULL, + `VNFC_INSTANCE_GROUP_CUSTOMIZATION_ID` integer DEFAULT NULL, `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; @@ -1460,6 +1463,16 @@ create table if not exists model ( FOREIGN KEY (`RECIPE`) REFERENCES `model_recipe` (`MODEL_ID`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1; +CREATE TABLE IF NOT EXISTS `requestdb`.`cloud_api_requests` ( +`ID` INT(13) NOT NULL AUTO_INCREMENT, +`REQUEST_BODY` LONGTEXT NOT NULL, +`CLOUD_IDENTIFIER` VARCHAR(200) NULL, +`SO_REQUEST_ID` VARCHAR(45) NOT NULL, +`CREATE_TIME` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, +PRIMARY KEY (`ID`), +INDEX `fk_cloud_api_requests__so_request_id_idx` (`SO_REQUEST_ID` ASC)) +ENGINE = InnoDB DEFAULT CHARSET=latin1; + CREATE TABLE IF NOT EXISTS `workflow` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `ARTIFACT_UUID` varchar(200) NOT NULL, @@ -1477,8 +1490,3 @@ CREATE TABLE IF NOT EXISTS `workflow` ( PRIMARY KEY (`ID`), UNIQUE KEY `UK_workflow` (`ARTIFACT_UUID`,`NAME`,`VERSION`,`SOURCE`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; - - - - - diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java index b3d57b0137..3c4b1fa66b 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java @@ -89,6 +89,7 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep protected static final String REQUEST_ID = "requestId"; protected static final String REQUESTOR_ID = "requestorId"; protected static final String ACTION = "action"; + protected static final String OPENV = "operationalEnvironment"; private static final List<String> VALID_COLUMNS = Arrays.asList(REQUEST_ID, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, ACTION, REQUEST_STATUS); @@ -173,13 +174,13 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep predicates.add(cb.equal(tableRoot.get(NETWORK_INSTANCE_NAME), instanceName)); } else if (requestScope.equals("configuration")) { predicates.add(cb.equal(tableRoot.get(CONFIGURATION_INSTANCE_NAME), instanceName)); - } else if (requestScope.equals("operationalEnvironment")) { + } else if (requestScope.equals(OPENV)) { predicates.add(cb.equal(tableRoot.get(OPERATIONAL_ENV_NAME), instanceName)); } } else { if (instanceIdMap != null) { - if ("service".equals(requestScope) && instanceIdMap.get("serviceInstanceId") != null) { + if ("service".equals(requestScope) && instanceIdMap.get(SERVICE_INSTANCE_ID) != null) { predicates .add(cb.equal(tableRoot.get(SERVICE_INSTANCE_ID), instanceIdMap.get("serviceInstanceId"))); } @@ -208,8 +209,7 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep instanceIdMap.get("configurationInstanceId"))); } - if (requestScope.equals("operationalEnvironment") - && instanceIdMap.get("operationalEnvironmentId") != null) { + if (requestScope.equals(OPENV) && instanceIdMap.get("operationalEnvironmentId") != null) { predicates.add( cb.equal(tableRoot.get(OPERATIONAL_ENV_ID), instanceIdMap.get("operationalEnvironmentId"))); } @@ -336,7 +336,7 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep // as the same requestorId can also match on different API methods final String resourceType = orchestrationMap.get("resourceType"); if (resourceType == null) { - predicates.add(cb.equal(tableRoot.get("requestScope"), "operationalEnvironment")); + predicates.add(cb.equal(tableRoot.get("requestScope"), OPENV)); } for (final Map.Entry<String, String> entry : orchestrationMap.entrySet()) { 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 2bd9936b3a..65372b7b48 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 @@ -1,5 +1,5 @@ -create table ACTIVATE_OPERATIONAL_ENV_SERVICE_MODEL_DISTRIBUTION_STATUS ( +create table IF NOT EXISTS ACTIVATE_OPERATIONAL_ENV_SERVICE_MODEL_DISTRIBUTION_STATUS ( REQUEST_ID varchar(255) not null, OPERATIONAL_ENV_ID varchar(255) not null, SERVICE_MODEL_VERSION_ID varchar(255) not null, @@ -13,7 +13,7 @@ create table ACTIVATE_OPERATIONAL_ENV_SERVICE_MODEL_DISTRIBUTION_STATUS ( primary key (REQUEST_ID,OPERATIONAL_ENV_ID, SERVICE_MODEL_VERSION_ID) ); -create table OPERATION_STATUS ( +create table IF NOT EXISTS OPERATION_STATUS ( SERVICE_ID varchar(255) not null, OPERATION_ID varchar(255) not null, SERVICE_NAME varchar(255), @@ -46,7 +46,7 @@ INSERT INTO PUBLIC.OPERATION_STATUS(SERVICE_ID, OPERATION_ID, OPERATION_TYPE, US primary key (SERVICE_ID,OPERATION_ID,RESOURCE_TEMPLATE_UUID) ); -CREATE CACHED TABLE PUBLIC.INFRA_ACTIVE_REQUESTS( +CREATE TABLE IF NOT EXISTS PUBLIC.INFRA_ACTIVE_REQUESTS( REQUEST_ID VARCHAR NOT NULL SELECTIVITY 100, CLIENT_REQUEST_ID VARCHAR SELECTIVITY 6, ACTION VARCHAR SELECTIVITY 1, @@ -168,6 +168,17 @@ CREATE CACHED TABLE PUBLIC.ARCHIVED_INFRA_REQUESTS( REQUEST_URL VARCHAR SELECTIVITY 1 ); +CREATE TABLE IF NOT EXISTS cloud_api_requests( +`ID` INT(13) NOT NULL AUTO_INCREMENT, +`REQUEST_BODY` LONGTEXT NOT NULL, +`CLOUD_IDENTIFIER` VARCHAR(200) NULL, +`SO_REQUEST_ID` VARCHAR(45) NOT NULL, +`CREATE_TIME` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, +PRIMARY KEY (`ID`), +CONSTRAINT fk_cloud_api_req_infra_requests + FOREIGN KEY (SO_REQUEST_ID) + REFERENCES infra_active_requests (REQUEST_ID)); + CREATE CACHED TABLE PUBLIC.SITE_STATUS( SITE_NAME VARCHAR NOT NULL, STATUS VARCHAR, diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/CloudApiRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/CloudApiRequests.java new file mode 100644 index 0000000000..690d0ffbaf --- /dev/null +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/CloudApiRequests.java @@ -0,0 +1,138 @@ +/*- + * ============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.db.request.beans; + +import java.io.Serializable; +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +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.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.openpojo.business.annotation.BusinessKey; + + +@Entity +@JsonInclude(Include.NON_NULL) +@Table(name = "cloud_api_requests") +public class CloudApiRequests implements Serializable { + + + /** + * + */ + private static final long serialVersionUID = 4686890103198488984L; + + @JsonIgnore + @Id + @BusinessKey + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "ID") + private Integer id; + + + @Column(name = "SO_REQUEST_ID") + private String requestId; + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + @Column(name = "CLOUD_IDENTIFIER") + private String cloudIdentifier; + + @Column(name = "REQUEST_BODY", columnDefinition = "LONGTEXT") + private String requestBody; + + @Column(name = "CREATE_TIME", insertable = false, updatable = false) + @Temporal(TemporalType.TIMESTAMP) + private Date created = null; + + + @Override + public boolean equals(final Object other) { + if (!(other instanceof CloudApiRequests)) { + return false; + } + CloudApiRequests castOther = (CloudApiRequests) other; + return new EqualsBuilder().append(id, castOther.id).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(id).toHashCode(); + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("id", id).append("cloudIdentifier", cloudIdentifier) + .append("requestBody", requestBody).append("created", created).toString(); + } + + @PrePersist + protected void createdAt() { + this.created = new Date(); + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getCloudIdentifier() { + return cloudIdentifier; + } + + public void setCloudIdentifier(String cloudIdentifier) { + this.cloudIdentifier = cloudIdentifier; + } + + + public String getRequestBody() { + return requestBody; + } + + public void setRequestBody(String requestBody) { + this.requestBody = requestBody; + } + + public Date getCreated() { + return created; + } +} 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 a1010a349c..7c58c6171e 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 @@ -23,10 +23,15 @@ package org.onap.so.db.request.beans; import java.net.URI; import java.sql.Timestamp; import java.util.Date; +import java.util.List; import java.util.Objects; +import javax.persistence.CascadeType; import javax.persistence.Column; +import javax.persistence.FetchType; import javax.persistence.Id; +import javax.persistence.JoinColumn; import javax.persistence.MappedSuperclass; +import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Temporal; @@ -34,6 +39,7 @@ import javax.persistence.TemporalType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.commons.lang3.builder.ToStringBuilder; import org.onap.so.requestsdb.TimestampXMLAdapter; +import uk.co.blackpepper.bowman.annotation.LinkedResource; import uk.co.blackpepper.bowman.annotation.ResourceId; @MappedSuperclass @@ -147,6 +153,10 @@ public abstract class InfraRequests implements java.io.Serializable { @Column(name = "REQUEST_URL", length = 500) private String requestUrl; + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "SO_REQUEST_ID", referencedColumnName = "REQUEST_ID") + private List<CloudApiRequests> cloudApiRequests; + @ResourceId public URI getRequestURI() { return URI.create(this.requestId); @@ -458,6 +468,15 @@ public abstract class InfraRequests implements java.io.Serializable { return requestAction; } + @LinkedResource + public List<CloudApiRequests> getCloudApiRequests() { + return cloudApiRequests; + } + + public void setCloudApiRequests(List<CloudApiRequests> cloudApiRequests) { + this.cloudApiRequests = cloudApiRequests; + } + public void setRequestAction(String requestAction) { this.requestAction = requestAction; } 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 f2ff6fac00..103410701c 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 @@ -72,10 +72,10 @@ public class RequestsDbClient { private static final String SERVICE_MODEL_VERSION_ID = "SERVICE_MODEL_VERSION_ID"; - @Value("${mso.adapters.requestDb.endpoint}") + @Value("${mso.adapters.requestDb.endpoint:#{null}}") protected String endpoint; - @Value("${mso.adapters.requestDb.auth}") + @Value("${mso.adapters.requestDb.auth:#{null}}") private String msoAdaptersAuth; private String getOrchestrationFilterURI = "/infraActiveRequests/getOrchestrationFiltersFromInfraActive/"; diff --git a/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/requestsdb/RequestsDBHelperTest.java b/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/requestsdb/RequestsDBHelperTest.java new file mode 100644 index 0000000000..b37ca0af63 --- /dev/null +++ b/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/requestsdb/RequestsDBHelperTest.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 Samsung 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.requestsdb; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; + +@RunWith(MockitoJUnitRunner.class) +public class RequestsDBHelperTest { + + @InjectMocks + private RequestsDBHelper requestsDBHelper; + + @Mock + private RequestsDbClient requestsDbClient; + + @Test + public void updateInfraSuccessCompletion() { + + when(requestsDbClient.getInfraActiveRequestbyRequestId(any())).thenReturn(new InfraActiveRequests()); + + requestsDBHelper.updateInfraSuccessCompletion("messageText", "requestId", "operationalEnvId"); + + ArgumentCaptor<InfraActiveRequests> infraActiveRequests = ArgumentCaptor.forClass(InfraActiveRequests.class); + + verify(requestsDbClient, times(1)).save(infraActiveRequests.capture()); + assertEquals("COMPLETE", infraActiveRequests.getValue().getRequestStatus()); + assertEquals("APIH", infraActiveRequests.getValue().getLastModifiedBy()); + assertEquals(Long.valueOf(100), infraActiveRequests.getValue().getProgress()); + assertEquals("SUCCESSFUL, operationalEnvironmentId - operationalEnvId; Success Message: messageText", + infraActiveRequests.getValue().getStatusMessage()); + assertEquals("operationalEnvId", infraActiveRequests.getValue().getOperationalEnvId()); + } + + @Test + public void updateInfraFailureCompletion() { + + when(requestsDbClient.getInfraActiveRequestbyRequestId(any())).thenReturn(new InfraActiveRequests()); + + requestsDBHelper.updateInfraFailureCompletion("messageText", "requestId", "operationalEnvId"); + + ArgumentCaptor<InfraActiveRequests> infraActiveRequests = ArgumentCaptor.forClass(InfraActiveRequests.class); + verify(requestsDbClient, times(1)).save(infraActiveRequests.capture()); + assertEquals("FAILED", infraActiveRequests.getValue().getRequestStatus()); + assertEquals("APIH", infraActiveRequests.getValue().getLastModifiedBy()); + assertEquals(Long.valueOf(100), infraActiveRequests.getValue().getProgress()); + assertEquals("FAILURE, operationalEnvironmentId - operationalEnvId; Error message: messageText", + infraActiveRequests.getValue().getStatusMessage()); + assertEquals("operationalEnvId", infraActiveRequests.getValue().getOperationalEnvId()); + + } +} 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 00eff8f0c9..9a9564023d 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 @@ -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,6 @@ 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; @@ -22,8 +18,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 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 3518805b0d..f1ee006b60 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 @@ -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; @@ -32,15 +31,11 @@ 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(ActivitySpecActivitySpecCategoriesId.class) 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 f0c9bd99ce..49c5d98943 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 @@ -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; @@ -32,15 +31,11 @@ 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(ActivitySpecActivitySpecParametersId.class) 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 a42a73aac9..56aecc4a98 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 @@ -1,8 +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; import javax.persistence.Entity; @@ -10,20 +8,12 @@ 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; -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/ActivitySpecUserParameters.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ActivitySpecUserParameters.java index be32da379e..6a7b5ba0be 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 @@ -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; @@ -32,15 +31,11 @@ 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(ActivitySpecUserParametersId.class) diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/BuildingBlockDetail.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/BuildingBlockDetail.java index 54e2144c81..f94b8155f8 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/BuildingBlockDetail.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/BuildingBlockDetail.java @@ -21,22 +21,17 @@ package org.onap.so.db.catalog.beans; import java.io.Serializable; -import java.util.List; -import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; -import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; -import javax.persistence.OneToMany; import javax.persistence.Table; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; -import org.onap.so.db.catalog.beans.macro.OrchestrationFlow; import com.openpojo.business.annotation.BusinessKey; @Entity 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 1117648a7f..4599c978ec 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 @@ -22,7 +22,6 @@ package org.onap.so.db.catalog.beans; import java.io.Serializable; import java.util.Date; -import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; @@ -32,8 +31,6 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; -import javax.persistence.MapsId; -import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.PrePersist; import javax.persistence.Table; diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResourceCustomization.java index 9287fbcf84..21b1550cb5 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResourceCustomization.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/NetworkResourceCustomization.java @@ -44,33 +44,6 @@ import uk.co.blackpepper.bowman.annotation.LinkedResource; public class NetworkResourceCustomization implements Serializable { public static final long serialVersionUID = -1322322139926390329L; - @Override - public String toString() { - return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID) - .append("modelInstanceName", modelInstanceName).append("created", created) - .append("networkTechnology", networkTechnology).append("networkType", networkType) - .append("networkScope", networkScope).append("networkRole", networkRole) - .append("networkResource", networkResource).toString(); - } - - @Override - public boolean equals(final Object other) { - if (!(other instanceof NetworkResourceCustomization)) { - return false; - } - NetworkResourceCustomization castOther = (NetworkResourceCustomization) other; - return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode(); - } - - public NetworkResourceCustomization() { - super(); - } - @BusinessKey @Id @Column(name = "MODEL_CUSTOMIZATION_UUID") @@ -102,6 +75,10 @@ public class NetworkResourceCustomization implements Serializable { @JoinColumn(name = "NETWORK_RESOURCE_MODEL_UUID") private NetworkResource networkResource = null; + public NetworkResourceCustomization() { + super(); + } + @PrePersist protected void onCreate() { this.created = new Date(); @@ -175,4 +152,27 @@ public class NetworkResourceCustomization implements Serializable { public void setResourceInput(String resourceInput) { this.resourceInput = resourceInput; } + + @Override + public String toString() { + return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID) + .append("modelInstanceName", modelInstanceName).append("created", created) + .append("networkTechnology", networkTechnology).append("networkType", networkType) + .append("networkScope", networkScope).append("networkRole", networkRole) + .append("networkResource", networkResource).toString(); + } + + @Override + public boolean equals(final Object other) { + if (!(other instanceof NetworkResourceCustomization)) { + return false; + } + NetworkResourceCustomization castOther = (NetworkResourceCustomization) other; + return new EqualsBuilder().append(modelCustomizationUUID, castOther.modelCustomizationUUID).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode(); + } } 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 ffcc8e9717..3b57ae0f72 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 @@ -25,11 +25,9 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; -import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; -import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; @@ -93,6 +91,9 @@ public class Service implements Serializable { @Column(name = "RESOURCE_ORDER") private String resourceOrder; + @Column(name = "OVERALL_DISTRIBUTION_STATUS") + private String distrobutionStatus; + @OneToMany(cascade = CascadeType.ALL) @JoinTable(name = "network_resource_customization_to_service", joinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID"), @@ -135,6 +136,7 @@ public class Service implements Serializable { @JoinColumn(name = "TOSCA_CSAR_ARTIFACT_UUID") private ToscaCsar csar; + @Override public String toString() { return new ToStringBuilder(this).append("modelName", modelName).append("description", description) @@ -367,4 +369,14 @@ public class Service implements Serializable { public void setResourceOrder(String resourceOrder) { this.resourceOrder = resourceOrder; } + + + public String getDistrobutionStatus() { + return distrobutionStatus; + } + + public void setDistrobutionStatus(String distrobutionStatus) { + this.distrobutionStatus = distrobutionStatus; + } + } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResource.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResource.java index 5d9deb6c89..fb54449d5f 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResource.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResource.java @@ -38,9 +38,9 @@ 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 com.openpojo.business.annotation.BusinessKey; import uk.co.blackpepper.bowman.annotation.LinkedResource; @Entity @@ -93,9 +93,6 @@ public class VnfResource implements Serializable { @JoinColumn(name = "HEAT_TEMPLATE_ARTIFACT_UUID") private HeatTemplate heatTemplates; - @OneToMany(fetch = FetchType.LAZY, mappedBy = "vnfResources") - private List<VnfResourceCustomization> vnfResourceCustomizations; - @OneToMany(fetch = FetchType.LAZY, mappedBy = "vnfResource") private List<VnfResourceWorkflow> vnfResourceWorkflow; @@ -111,8 +108,7 @@ public class VnfResource implements Serializable { .append("toscaNodeType", toscaNodeType).append("description", description) .append("orchestrationMode", orchestrationMode).append("aicVersionMin", aicVersionMin) .append("aicVersionMax", aicVersionMax).append("created", created) - .append("heatTemplates", heatTemplates).append("vnfResourceCustomizations", vnfResourceCustomizations) - .append("vnfResourceWorkflow", vnfResourceWorkflow).toString(); + .append("heatTemplates", heatTemplates).append("vnfResourceWorkflow", vnfResourceWorkflow).toString(); } @Override @@ -230,17 +226,6 @@ public class VnfResource implements Serializable { } @LinkedResource - public List<VnfResourceCustomization> getVnfResourceCustomizations() { - if (vnfResourceCustomizations == null) - vnfResourceCustomizations = new ArrayList<>(); - return vnfResourceCustomizations; - } - - public void setVnfResourceCustomizations(List<VnfResourceCustomization> vnfResourceCustomizations) { - this.vnfResourceCustomizations = vnfResourceCustomizations; - } - - @LinkedResource public HeatTemplate getHeatTemplates() { return heatTemplates; } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java index af99aa8c80..36c9251d59 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java @@ -121,6 +121,9 @@ public class VnfResourceCustomization implements Serializable { @Column(name = "SKIP_POST_INSTANTIATION_CONFIGURATION") private Boolean skipPostInstConf; + @Column(name = "VNFCINSTANCEGROUP_ORDER") + private String vnfcInstanceGroupOrder; + @Override public boolean equals(final Object other) { if (!(other instanceof VnfResourceCustomization)) { @@ -148,6 +151,7 @@ public class VnfResourceCustomization implements Serializable { .append("nfType", nfType).append("nfRole", nfRole).append("nfNamingCode", nfNamingCode) .append("multiStageDesign", multiStageDesign).append("vnfResources", vnfResources) .append("vfModuleCustomizations", vfModuleCustomizations) + .append("vnfcInstanceGroupOrder", vnfcInstanceGroupOrder) .append("vnfcInstanceGroupCustomizations", vnfcInstanceGroupCustomizations).toString(); } @@ -324,4 +328,12 @@ public class VnfResourceCustomization implements Serializable { public void setSkipPostInstConf(Boolean skipPostInstConf) { this.skipPostInstConf = skipPostInstConf; } + + public String getVnfcInstanceGroupOrder() { + return vnfcInstanceGroupOrder; + } + + public void setVnfcInstanceGroupOrder(String vnfcInstanceGroupOrder) { + this.vnfcInstanceGroupOrder = vnfcInstanceGroupOrder; + } } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcCustomization.java index f6ae503c61..413efaf12c 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcCustomization.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcCustomization.java @@ -3,6 +3,7 @@ * ONAP - SO * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 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. @@ -20,23 +21,25 @@ package org.onap.so.db.catalog.beans; -import java.io.Serializable; -import java.util.Date; -import java.util.List; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.openpojo.business.annotation.BusinessKey; +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import com.fasterxml.jackson.annotation.JsonFormat; -import com.openpojo.business.annotation.BusinessKey; -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.ToStringBuilder; +import java.io.Serializable; +import java.util.Date; +import java.util.List; @Entity @Table(name = "vnfc_customization") @@ -70,6 +73,9 @@ public class VnfcCustomization implements Serializable { @Column(name = "DESCRIPTION") private String description; + @Column(name = "RESOURCE_INPUT") + private String resourceInput; + @Column(name = "CREATION_TIMESTAMP", updatable = false) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") @Temporal(TemporalType.TIMESTAMP) @@ -78,6 +84,10 @@ public class VnfcCustomization implements Serializable { @OneToMany(cascade = CascadeType.ALL, mappedBy = "vnfcCustomization") private List<CvnfcCustomization> cvnfcCustomization; + @ManyToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "VNFC_INSTANCE_GROUP_CUSTOMIZATION_ID") + private VnfcInstanceGroupCustomization vnfcInstanceGroupCustomization; + @Override public boolean equals(final Object other) { if (!(other instanceof VnfcCustomization)) { @@ -186,4 +196,20 @@ public class VnfcCustomization implements Serializable { public void setCvnfcCustomization(List<CvnfcCustomization> cvnfcCustomization) { this.cvnfcCustomization = cvnfcCustomization; } + + public VnfcInstanceGroupCustomization getVnfcInstanceGroupCustomization() { + return vnfcInstanceGroupCustomization; + } + + public void setVnfcInstanceGroupCustomization(VnfcInstanceGroupCustomization vnfcInstanceGroupCustomization) { + this.vnfcInstanceGroupCustomization = vnfcInstanceGroupCustomization; + } + + public String getResourceInput() { + return resourceInput; + } + + public void setResourceInput(String resourceInput) { + this.resourceInput = resourceInput; + } } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcInstanceGroupCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcInstanceGroupCustomization.java index 695e5bbbb9..8a00ccd261 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcInstanceGroupCustomization.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfcInstanceGroupCustomization.java @@ -3,6 +3,7 @@ * ONAP - SO * ================================================================================ * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 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. @@ -22,6 +23,7 @@ package org.onap.so.db.catalog.beans; import java.io.Serializable; import java.util.Date; +import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; @@ -32,6 +34,7 @@ import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.Table; import javax.persistence.Temporal; @@ -66,6 +69,9 @@ public class VnfcInstanceGroupCustomization implements Serializable { @JoinColumn(name = "INSTANCE_GROUP_MODEL_UUID") private InstanceGroup instanceGroup; + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "vnfcInstanceGroupCustomization") + private List<VnfcCustomization> vnfcCustomizations; + @Column(name = "FUNCTION") private String function; @@ -150,4 +156,12 @@ public class VnfcInstanceGroupCustomization implements Serializable { public void setInstanceGroup(InstanceGroup instanceGroup) { this.instanceGroup = instanceGroup; } + + public List<VnfcCustomization> getVnfcCustomizations() { + return vnfcCustomizations; + } + + public void setVnfcCustomizations(List<VnfcCustomization> vnfcCustomizations) { + this.vnfcCustomizations = vnfcCustomizations; + } } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java index a12edac8a0..1882ad5964 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java @@ -63,6 +63,10 @@ public class RainyDayHandlerStatus implements Serializable { private String errorCode; @BusinessKey + @Column(name = "REG_EX_ERROR_MESSAGE") + private String errorMessage; + + @BusinessKey @Column(name = "WORK_STEP") private String workStep; @@ -77,8 +81,8 @@ public class RainyDayHandlerStatus implements Serializable { public String toString() { return new ToStringBuilder(this).append("id", id).append("flowName", flowName) .append("serviceType", serviceType).append("vnfType", vnfType).append("errorCode", errorCode) - .append("workStep", workStep).append("policy", policy).append("secondaryPolicy", secondaryPolicy) - .toString(); + .append("errorMessage", errorMessage).append("workStep", workStep).append("policy", policy) + .append("secondaryPolicy", secondaryPolicy).toString(); } @Override @@ -161,4 +165,14 @@ public class RainyDayHandlerStatus implements Serializable { public void setSecondaryPolicy(String secondaryPolicy) { this.secondaryPolicy = secondaryPolicy; } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + } 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 19200468ae..a1f926e25f 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 @@ -84,7 +84,6 @@ public class CatalogDbClient { private static final String CLOUD_SITE = "/cloudSite"; private static final String CLOUDIFY_MANAGER = "/cloudifyManager"; - private static final String CVNFC_CUSTOMZIATION = "/cvnfcCustomization"; private static final String RAINY_DAY_HANDLER_MACRO = "/rainy_day_handler_macro"; private static final String NORTHBOUND_REQUEST_REF_LOOKUP = "/northbound_request_ref_lookup"; private static final String NETWORK_RESOURCE_CUSTOMIZATION = "/networkResourceCustomization"; @@ -124,7 +123,6 @@ public class CatalogDbClient { private static final String MODEL_NAME = "modelName"; private static final String MODEL_VERSION = "modelVersion"; private static final String MODEL_INVARIANT_UUID = "modelInvariantUUID"; - private static final String MODEL_INSTANCE_NAME = "modelInstanceName"; private static final String VNF_RESOURCE_MODEL_UUID = "vnfResourceModelUUID"; private static final String NF_ROLE = "nfRole"; private static final String VF_MODULE_MODEL_UUID = "vfModuleModelUUID"; @@ -137,6 +135,7 @@ public class CatalogDbClient { private static final String IS_ALACARTE = "isALaCarte"; private static final String CLOUD_OWNER = "cloudOwner"; private static final String FLOW_NAME = "flowName"; + private static final String ERROR_MESSAGE = "errorMessage"; private static final String SERVICE_TYPE = "serviceType"; private static final String VNF_TYPE = "vnfType"; private static final String ERROR_CODE = "errorCode"; @@ -184,8 +183,8 @@ public class CatalogDbClient { "/findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwner"; private String findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType = "/findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType"; - private String findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep = - "/findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep"; + + private static final String findRainyDayHandler = "/findRainyDayHandler"; private String findByClliAndCloudVersion = "/findByClliAndCloudVersion"; private String findServiceByServiceInstanceId = "/findServiceByServiceInstanceId"; private String findPnfResourceCustomizationByModelUuid = "/findPnfResourceCustomizationByModelUuid"; @@ -196,10 +195,8 @@ public class CatalogDbClient { private String serviceURI; private String vfModuleURI; private String vnfResourceURI; - private String vfModuleCustomizationURI; private String networkCollectionResourceCustomizationURI; private String networkResourceCustomizationURI; - private String vnfResourceCustomizationURI; private String collectionNetworkResourceCustomizationURI; private String instanceGroupURI; private String cloudifyManagerURI; @@ -258,8 +255,6 @@ public class CatalogDbClient { private final Client<CloudifyManager> cloudifyManagerClient; - private final Client<CvnfcCustomization> cvnfcCustomizationClient; - private final Client<ControllerSelectionReference> controllerSelectionReferenceClient; private final Client<PnfResource> pnfResourceClient; @@ -324,8 +319,6 @@ public class CatalogDbClient { findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType = endpoint + NORTHBOUND_REQUEST_REF_LOOKUP + SEARCH + findOneByActionAndRequestScopeAndIsAlacarteAndCloudOwnerAndServiceType; - findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep = endpoint + RAINY_DAY_HANDLER_MACRO + SEARCH - + findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep; findByClliAndCloudVersion = endpoint + CLOUD_SITE + SEARCH + findByClliAndCloudVersion; findPnfResourceCustomizationByModelUuid = @@ -340,12 +333,9 @@ public class CatalogDbClient { serviceURI = endpoint + SERVICE + URI_SEPARATOR; vfModuleURI = endpoint + VFMODULE + URI_SEPARATOR; vnfResourceURI = endpoint + VNF_RESOURCE + URI_SEPARATOR; - vfModuleCustomizationURI = endpoint + VFMODULE_CUSTOMIZATION + URI_SEPARATOR; networkCollectionResourceCustomizationURI = endpoint + NETWORK_COLLECTION_RESOURCE_CUSTOMIZATION + URI_SEPARATOR; networkResourceCustomizationURI = endpoint + NETWORK_RESOURCE_CUSTOMIZATION + URI_SEPARATOR; - cvnfcResourceCustomizationURI = endpoint + CVNFC_CUSTOMZIATION + URI_SEPARATOR; - vnfResourceCustomizationURI = endpoint + VNF_RESOURCE_CUSTOMIZATION + URI_SEPARATOR; collectionNetworkResourceCustomizationURI = endpoint + COLLECTION_NETWORK_RESOURCE_CUSTOMIZATION + URI_SEPARATOR; instanceGroupURI = endpoint + INSTANCE_GROUP + URI_SEPARATOR; @@ -400,7 +390,6 @@ public class CatalogDbClient { homingInstanceClient = clientFactory.create(HomingInstance.class); cloudifyManagerClient = clientFactory.create(CloudifyManager.class); serviceRecipeClient = clientFactory.create(ServiceRecipe.class); - cvnfcCustomizationClient = clientFactory.create(CvnfcCustomization.class); controllerSelectionReferenceClient = clientFactory.create(ControllerSelectionReference.class); externalServiceToInternalServiceClient = clientFactory.create(ExternalServiceToInternalService.class); pnfResourceClient = clientFactory.create(PnfResource.class); @@ -450,7 +439,6 @@ public class CatalogDbClient { homingInstanceClient = clientFactory.create(HomingInstance.class); cloudifyManagerClient = clientFactory.create(CloudifyManager.class); serviceRecipeClient = clientFactory.create(ServiceRecipe.class); - cvnfcCustomizationClient = clientFactory.create(CvnfcCustomization.class); controllerSelectionReferenceClient = clientFactory.create(ControllerSelectionReference.class); externalServiceToInternalServiceClient = clientFactory.create(ExternalServiceToInternalService.class); pnfResourceClient = clientFactory.create(PnfResource.class); @@ -645,13 +633,16 @@ public class CatalogDbClient { .queryParam(SERVICE_TYPE, serviceType).build().toString())); } - public RainyDayHandlerStatus getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep( - String flowName, String serviceType, String vnfType, String errorCode, String workStep) { + public RainyDayHandlerStatus getRainyDayHandlerStatus(String flowName, String serviceType, String vnfType, + String errorCode, String workStep, String errorMessage) { + logger.debug( + "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(findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep) + getUri(UriBuilder.fromUri(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) - .build().toString())); + .queryParam(ERROR_MESSAGE, errorMessage).build().toString())); } public ServiceRecipe getFirstByServiceModelUUIDAndAction(String modelUUID, String action) { diff --git a/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/exception/RestProcessingException.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HeatFilesRepository.java index c84416e245..acefb75b5a 100644 --- a/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/exception/RestProcessingException.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/HeatFilesRepository.java @@ -1,37 +1,30 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * 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. - * - * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ -package org.onap.svnfm.simulator.exception; - -/** - * @author ronan.kenny@est.tech - * - */ -public class RestProcessingException extends RuntimeException { - private static final long serialVersionUID = 16862313537198441L; +package org.onap.so.db.catalog.data.repository; - public RestProcessingException(final String message) { - super(message); - } +import org.onap.so.db.catalog.beans.HeatFiles; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; - public RestProcessingException(final String message, final Throwable cause) { - super(message, cause); - } +@RepositoryRestResource(collectionResourceRel = "heatFiles", path = "heatFiles") +public interface HeatFilesRepository extends JpaRepository<HeatFiles, String> { + HeatFiles findByArtifactUuid(String artifactUUID); } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java index 2c61d91d6b..91ae10236b 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java @@ -22,10 +22,20 @@ package org.onap.so.db.catalog.data.repository; import org.onap.so.db.catalog.beans.macro.RainyDayHandlerStatus; 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 = "rainy_day_handler_macro", path = "rainy_day_handler_macro") public interface RainyDayHandlerStatusRepository extends JpaRepository<RainyDayHandlerStatus, Integer> { - RainyDayHandlerStatus findOneByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(String flowName, - String serviceType, String vnfType, String errorCode, String workStep); + + @Query(value = "SELECT * FROM rainy_day_handler_macro WHERE (FLOW_NAME = :flowName ) AND SERVICE_TYPE IN (:serviceType ,'*') " + + " AND VNF_TYPE IN ( :vnfType , '*') AND ERROR_CODE IN (:errorCode ,'*') AND WORK_STEP IN (:workStep , '*' ) " + + " AND ( :errorMessage REGEXP rainy_day_handler_macro.REG_EX_ERROR_MESSAGE OR REG_EX_ERROR_MESSAGE = '*') " + + " ORDER BY CASE WHEN 'asdf' REGEXP REG_EX_ERROR_MESSAGE THEN 0 WHEN ERROR_CODE != '*' THEN 1 WHEN VNF_TYPE != '*' THEN 2 WHEN SERVICE_TYPE != '*' THEN 3 ELSE 4 END LIMIT 1;", + nativeQuery = true) + RainyDayHandlerStatus findRainyDayHandler(@Param("flowName") String flowName, + @Param("serviceType") String serviceType, @Param("vnfType") String vnfType, + @Param("errorCode") String errorCode, @Param("workStep") String workStep, + @Param("errorMessage") String errorMessage); } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRepository.java index c107192060..b456beaeff 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRepository.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/ServiceRepository.java @@ -30,6 +30,8 @@ import java.util.List; public interface ServiceRepository extends JpaRepository<Service, String> { List<Service> findByModelName(String modelName); + List<Service> findByModelNameAndDistrobutionStatus(String modelName, String distrobutionStatus); + Service findOneByModelName(String modelName); /** diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioning.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioning.java index a7610fec92..98db12c288 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioning.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/utils/MavenLikeVersioning.java @@ -90,8 +90,8 @@ public class MavenLikeVersioning implements Serializable { public boolean isTheSameVersion(String versionToCompare) { if (versionToCompare == null && this.version == null) { return true; - } else if (versionToCompare == null || versionToCompare.trim().equals("") || this.version == null - || this.version.trim().equals("")) { + } else if (versionToCompare == null || "".equals(versionToCompare.trim()) || this.version == null + || "".equals(this.version.trim())) { return false; } String[] currentVersionArray = this.version.split("\\."); diff --git a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/HeatEnvironment.java b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/HeatEnvironment.java new file mode 100644 index 0000000000..97f67a5438 --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/HeatEnvironment.java @@ -0,0 +1,160 @@ +/*- + * ============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.rest.catalog.beans; + +import java.io.Serializable; +import java.text.DateFormat; +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Lob; +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 com.openpojo.business.annotation.BusinessKey; + +@Entity +@Table(name = "heat_environment") +public class HeatEnvironment implements Serializable { + + private static final long serialVersionUID = 768026109321305392L; + + @BusinessKey + @Id + @Column(name = "ARTIFACT_UUID") + private String artifactUuid; + + @Column(name = "NAME") + private String name = null; + + @Column(name = "DESCRIPTION") + private String description = null; + + @Lob + @Column(name = "BODY", columnDefinition = "LONGTEXT") + private String environment = null; + + @Column(name = "ARTIFACT_CHECKSUM") + private String artifactChecksum; + + @Column(name = "CREATION_TIMESTAMP", updatable = false) + @Temporal(TemporalType.TIMESTAMP) + private Date created; + + @BusinessKey + @Column(name = "VERSION") + private String version; + + @PrePersist + protected void onCreate() { + this.created = new Date(); + } + + @Override + public boolean equals(final Object other) { + if (!(other instanceof HeatEnvironment)) { + return false; + } + HeatEnvironment castOther = (HeatEnvironment) other; + return new EqualsBuilder().append(artifactUuid, castOther.artifactUuid).append(version, castOther.version) + .isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(artifactUuid).append(version).toHashCode(); + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getArtifactUuid() { + return this.artifactUuid; + } + + public void setArtifactUuid(String artifactUuid) { + this.artifactUuid = artifactUuid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getEnvironment() { + return this.environment; + } + + public void setEnvironment(String environment) { + this.environment = environment; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public Date getCreated() { + return created; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("Artifact UUID=" + this.artifactUuid); + sb.append(", name="); + sb.append(name); + sb.append(", version="); + sb.append(version); + sb.append(", description="); + sb.append(this.description == null ? "null" : this.description); + sb.append(", body="); + sb.append(this.environment == null ? "null" : this.environment); + if (this.created != null) { + sb.append(",creationTimestamp="); + sb.append(DateFormat.getInstance().format(this.created)); + } + return sb.toString(); + } +} diff --git a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/HeatFile.java b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/HeatFile.java new file mode 100644 index 0000000000..94f61d30e3 --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/HeatFile.java @@ -0,0 +1,115 @@ +/*- + * ============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.rest.catalog.beans; + +import java.io.Serializable; +import java.util.Date; +import org.apache.commons.lang3.builder.ToStringBuilder; + + +public class HeatFile implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3280125018687060890L; + + private String artifactUuid; + + private String description = null; + + private String fileName; + + private String fileBody; + + private Date created; + + private String artifactChecksum; + + private String version; + + @Override + public String toString() { + return new ToStringBuilder(this).append("artifactUuid", artifactUuid).append("description", description) + .append("fileName", fileName).append("fileBody", fileBody).append("created", created) + .append("artifactChecksum", artifactChecksum).toString(); + } + + public String getArtifactUuid() { + return this.artifactUuid; + } + + public void setArtifactUuid(String artifactUuid) { + this.artifactUuid = artifactUuid; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getFileName() { + return this.fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getFileBody() { + return this.fileBody; + } + + public void setFileBody(String fileBody) { + this.fileBody = fileBody; + } + + public Date getCreated() { + return created; + } + + public String getAsdcUuid() { + return this.artifactUuid; + } + + public void setAsdcUuid(String artifactUuid) { + this.artifactUuid = artifactUuid; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } +} diff --git a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/HeatTemplate.java b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/HeatTemplate.java new file mode 100644 index 0000000000..cb346e4167 --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/HeatTemplate.java @@ -0,0 +1,147 @@ +/*- + * ============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.rest.catalog.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.apache.commons.lang3.builder.ToStringBuilder; + + +public class HeatTemplate implements Serializable { + + + private String artifactUuid; + + private String templateName; + + private String templateBody = null; + + private Integer timeoutMinutes; + + private String version; + + private String description; + + private String artifactChecksum; + + private Date created; + + private Set<HeatTemplateParam> parameters; + + private List<HeatTemplate> childTemplates; + + @Override + public String toString() { + return new ToStringBuilder(this).append("artifactUuid", artifactUuid).append("templateName", templateName) + .append("templateBody", templateBody).append("timeoutMinutes", timeoutMinutes) + .append("version", version).append("description", description) + .append("artifactChecksum", artifactChecksum).append("created", created) + .append("parameters", parameters).append("childTemplates", childTemplates).toString(); + } + + public List<HeatTemplate> getChildTemplates() { + if (childTemplates == null) + childTemplates = new ArrayList<>(); + return childTemplates; + } + + public void setChildTemplates(List<HeatTemplate> childTemplates) { + this.childTemplates = childTemplates; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getArtifactUuid() { + return this.artifactUuid; + } + + public void setArtifactUuid(String artifactUuid) { + this.artifactUuid = artifactUuid; + } + + public String getTemplateName() { + return templateName; + } + + public void setTemplateName(String templateName) { + this.templateName = templateName; + } + + public String getTemplateBody() { + return templateBody; + } + + public void setTemplateBody(String templateBody) { + this.templateBody = templateBody; + } + + public Integer getTimeoutMinutes() { + return timeoutMinutes; + } + + public void setTimeoutMinutes(Integer timeout) { + this.timeoutMinutes = timeout; + } + + public Set<HeatTemplateParam> getParameters() { + if (parameters == null) + parameters = new HashSet<>(); + return parameters; + } + + public void setParameters(Set<HeatTemplateParam> parameters) { + this.parameters = parameters; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getHeatTemplate() { + return this.templateBody; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public Date getCreated() { + return created; + } +} diff --git a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/HeatTemplateParam.java b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/HeatTemplateParam.java new file mode 100644 index 0000000000..a79ec962f8 --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/HeatTemplateParam.java @@ -0,0 +1,73 @@ +/*- + * ============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.rest.catalog.beans; + +import java.io.Serializable; +import org.apache.commons.lang3.builder.ToStringBuilder; + + +public class HeatTemplateParam implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -8251042980747916191L; + + private String paramName; + + private Boolean required; + + private String paramType; + + private String paramAlias; + + public String getParamName() { + return paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } + + public Boolean isRequired() { + return required; + } + + public void setRequired(Boolean required) { + this.required = required; + } + + public String getParamAlias() { + return paramAlias; + } + + public void setParamAlias(String paramAlias) { + this.paramAlias = paramAlias; + } + + public String getParamType() { + return paramType; + } + + public void setParamType(String paramType) { + this.paramType = paramType; + } +} diff --git a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Service.java b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Service.java new file mode 100644 index 0000000000..1620058e1e --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Service.java @@ -0,0 +1,165 @@ +/*- + * ============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.rest.catalog.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; + +@JsonInclude(Include.NON_DEFAULT) +public class Service implements Serializable { + + private static final long serialVersionUID = 768026109321305392L; + + private String modelName; + + private String description; + + private String modelVersionId; + + private String modelInvariantId; + + private Date created; + + private String modelVersion; + + private String serviceType; + + private String serviceRole; + + private String environmentContext; + + private String workloadContext; + + private String category; + + private String distrobutionStatus; + + private List<Vnf> vnf = new ArrayList<>(); + + public List<Vnf> getVnf() { + return vnf; + } + + public void setVnf(List<Vnf> vnf) { + this.vnf = vnf; + } + + public String getModelName() { + return modelName; + } + + public void setModelName(String modelName) { + this.modelName = modelName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getModelVersionId() { + return modelVersionId; + } + + public void setModelVersionId(String modelVersionId) { + this.modelVersionId = modelVersionId; + } + + public String getModelInvariantId() { + return modelInvariantId; + } + + public void setModelInvariantId(String modelInvariantId) { + this.modelInvariantId = modelInvariantId; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public String getModelVersion() { + return modelVersion; + } + + public void setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + } + + public String getServiceType() { + return serviceType; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getServiceRole() { + return serviceRole; + } + + public void setServiceRole(String serviceRole) { + this.serviceRole = serviceRole; + } + + public String getEnvironmentContext() { + return environmentContext; + } + + public void setEnvironmentContext(String environmentContext) { + this.environmentContext = environmentContext; + } + + public String getWorkloadContext() { + return workloadContext; + } + + public void setWorkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getDistrobutionStatus() { + return distrobutionStatus; + } + + public void setDistrobutionStatus(String distrobutionStatus) { + this.distrobutionStatus = distrobutionStatus; + } + +} diff --git a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/VfModule.java b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/VfModule.java new file mode 100644 index 0000000000..8e18f94faf --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/VfModule.java @@ -0,0 +1,196 @@ +/*- + * ============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.rest.catalog.beans; + +import java.util.Date; +import java.util.List; +import org.onap.so.db.catalog.beans.HeatEnvironment; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; + +@JsonInclude(Include.NON_DEFAULT) +public class VfModule { + + // VfModule + private String modelVersionId; + private String modelInvariantId; + private String modelName; + private String modelVersion; + private String description; + private Boolean isBase; + private HeatTemplate heatTemplate; + private Date created; + private List<HeatFile> heatFile; + + // Customization + private String modelCustomizationId; + private String label; + private Integer minInstances; + private Integer maxInstances; + private Integer initialCount; + private Integer availabilityZoneCount; + private HeatEnvironment heatEnv; + private Boolean isVolumeGroup; + + + // Add in cvnfcCustomization + + + + public String getModelName() { + return modelName; + } + + public String getModelVersionId() { + return modelVersionId; + } + + public void setModelVersionId(String modelVersionId) { + this.modelVersionId = modelVersionId; + } + + public String getModelInvariantId() { + return modelInvariantId; + } + + public void setModelInvariantId(String modelInvariantId) { + this.modelInvariantId = modelInvariantId; + } + + public String getModelCustomizationId() { + return modelCustomizationId; + } + + public void setModelCustomizationId(String modelCustomizationId) { + this.modelCustomizationId = modelCustomizationId; + } + + public void setModelName(String modelName) { + this.modelName = modelName; + } + + public String getModelVersion() { + return modelVersion; + } + + public void setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Boolean getIsBase() { + return isBase; + } + + public void setIsBase(Boolean isBase) { + this.isBase = isBase; + } + + public HeatTemplate getHeatTemplate() { + return heatTemplate; + } + + public void setHeatTemplate(HeatTemplate heatTemplate) { + this.heatTemplate = heatTemplate; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public List<HeatFile> getHeatFile() { + return heatFile; + } + + public void setHeatFile(List<HeatFile> heatFile) { + this.heatFile = heatFile; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public Integer getMinInstances() { + return minInstances; + } + + public void setMinInstances(Integer minInstances) { + this.minInstances = minInstances; + } + + public Integer getMaxInstances() { + return maxInstances; + } + + public void setMaxInstances(Integer maxInstances) { + this.maxInstances = maxInstances; + } + + public Integer getInitialCount() { + return initialCount; + } + + public void setInitialCount(Integer integer) { + this.initialCount = integer; + } + + public Integer getAvailabilityZoneCount() { + return availabilityZoneCount; + } + + public void setAvailabilityZoneCount(Integer availabilityZoneCount) { + this.availabilityZoneCount = availabilityZoneCount; + } + + public HeatEnvironment getHeatEnv() { + return heatEnv; + } + + public void setHeatEnv(HeatEnvironment heatEnv) { + this.heatEnv = heatEnv; + } + + public Boolean getIsVolumeGroup() { + return isVolumeGroup; + } + + public void setIsVolumeGroup(Boolean isVolumeGroup) { + this.isVolumeGroup = isVolumeGroup; + } + + + +} diff --git a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Vnf.java b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Vnf.java new file mode 100644 index 0000000000..40d701c3c5 --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Vnf.java @@ -0,0 +1,218 @@ +/*- + * ============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.rest.catalog.beans; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; + +@JsonInclude(Include.NON_DEFAULT) +public class Vnf implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 2956199674955504834L; + + private String modelName; + private String modelVersionId; + private String modelInvariantId; + private String modelVersion; + private String modelCustomizationId; + private String modelInstanceName; + private Integer minInstances; + private Integer maxInstances; + private Integer availabilityZoneMaxCount; + private String toscaNodeType; + private String nfFunction; + private String nfRole; + private String nfNamingCode; + private String multiStageDesign; + private String orchestrationMode; + private String cloudVersionMin; + private String cloudVersionMax; + private String category; + private String subCategory; + private List<VfModule> vfModule = new ArrayList<>(); + + public List<VfModule> getVfModule() { + return vfModule; + } + + public void setVfModule(List<VfModule> vfModule) { + this.vfModule = vfModule; + } + + public Integer getAvailabilityZoneMaxCount() { + return availabilityZoneMaxCount; + } + + public void setAvailabilityZoneMaxCount(Integer availabilityZoneMaxCount) { + this.availabilityZoneMaxCount = availabilityZoneMaxCount; + } + + public Integer getMinInstances() { + return minInstances; + } + + public void setMinInstances(Integer minInstances) { + this.minInstances = minInstances; + } + + public Integer getMaxInstances() { + return maxInstances; + } + + public void setMaxInstances(Integer maxInstances) { + this.maxInstances = maxInstances; + } + + public String getCloudVersionMin() { + return cloudVersionMin; + } + + public void setCloudVersionMin(String cloudVersionMin) { + this.cloudVersionMin = cloudVersionMin; + } + + public String getCloudVersionMax() { + return cloudVersionMax; + } + + public void setCloudVersionMax(String cloudVersionMax) { + this.cloudVersionMax = cloudVersionMax; + } + + public String getModelVersionId() { + return modelVersionId; + } + + public void setModelVersionId(String modelVersionId) { + this.modelVersionId = modelVersionId; + } + + public String getModelInvariantId() { + return modelInvariantId; + } + + public void setModelInvariantId(String modelInvariantId) { + this.modelInvariantId = modelInvariantId; + } + + public String getModelCustomizationId() { + return modelCustomizationId; + } + + public void setModelCustomizationId(String modelCustomizationId) { + this.modelCustomizationId = modelCustomizationId; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubCategory() { + return subCategory; + } + + public void setSubCategory(String subCategory) { + this.subCategory = subCategory; + } + + public String getOrchestrationMode() { + return orchestrationMode; + } + + public void setOrchestrationMode(String orchestrationMode) { + this.orchestrationMode = orchestrationMode; + } + + public String getModelName() { + return modelName; + } + + public void setModelName(String modelName) { + this.modelName = modelName; + } + + public String getModelVersion() { + return modelVersion; + } + + public void setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + } + + + public String getModelInstanceName() { + return modelInstanceName; + } + + public void setModelInstanceName(String modelInstanceName) { + this.modelInstanceName = modelInstanceName; + } + + public String getToscaNodeType() { + return toscaNodeType; + } + + public void setToscaNodeType(String toscaNodeType) { + this.toscaNodeType = toscaNodeType; + } + + public String getNfFunction() { + return nfFunction; + } + + public void setNfFunction(String nfFunction) { + this.nfFunction = nfFunction; + } + + public String getNfRole() { + return nfRole; + } + + public void setNfRole(String nfRole) { + this.nfRole = nfRole; + } + + public String getNfNamingCode() { + return nfNamingCode; + } + + public void setNfNamingCode(String nfNamingCode) { + this.nfNamingCode = nfNamingCode; + } + + public String getMultiStageDesign() { + return multiStageDesign; + } + + public void setMultiStageDesign(String multiStepDesign) { + this.multiStageDesign = multiStepDesign; + } +} diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepositoryTest.java index 371a9c13e0..e8addc4aa8 100644 --- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepositoryTest.java +++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepositoryTest.java @@ -74,7 +74,6 @@ public class CvnfcCustomizationRepositoryTest extends BaseTest { List<VnfResourceCustomization> vnfResourceCustomizations = new ArrayList<>(); vnfResourceCustomizations.add(vnfResourceCustomization); - vnfResource.setVnfResourceCustomizations(vnfResourceCustomizations); vnfResourceCustomization.setVnfResources(vnfResource); @@ -123,7 +122,6 @@ public class CvnfcCustomizationRepositoryTest extends BaseTest { List<VnfResourceCustomization> vnfResourceCustomizations = new ArrayList<>(); vnfResourceCustomizations.add(vnfResourceCustomization); - vnfResource.setVnfResourceCustomizations(vnfResourceCustomizations); vnfResourceCustomization.setVnfResources(vnfResource); @@ -177,7 +175,6 @@ public class CvnfcCustomizationRepositoryTest extends BaseTest { List<VnfResourceCustomization> vnfResourceCustomizations = new ArrayList(); vnfResourceCustomizations.add(vnfResourceCustomization); - vnfResource.setVnfResourceCustomizations(vnfResourceCustomizations); vnfResourceCustomization.setVnfResources(vnfResource); diff --git a/mso-catalog-db/src/test/resources/schema.sql b/mso-catalog-db/src/test/resources/schema.sql index f5e7d52ba4..0856a4cbe2 100644 --- a/mso-catalog-db/src/test/resources/schema.sql +++ b/mso-catalog-db/src/test/resources/schema.sql @@ -803,6 +803,7 @@ 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), 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 @@ -1106,6 +1107,7 @@ CREATE TABLE `vnf_resource_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), KEY `fk_vnf_resource_customization__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`), @@ -1132,6 +1134,8 @@ CREATE TABLE `vnfc_customization` ( `MODEL_NAME` varchar(200) NOT NULL, `TOSCA_NODE_TYPE` varchar(200) NOT NULL, `DESCRIPTION` varchar(1200) DEFAULT NULL, + `RESOURCE_INPUT` varchar(20000) DEFAULT NULL, + `VNFC_INSTANCE_GROUP_CUSTOMIZATION_ID` integer DEFAULT NULL, `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.oparent</groupId> <artifactId>oparent</artifactId> - <version>1.2.1</version> + <version>2.0.0</version> <relativePath /> </parent> <groupId>org.onap.so</groupId> @@ -503,7 +503,7 @@ <plugin> <groupId>io.fabric8</groupId> <artifactId>fabric8-maven-plugin</artifactId> - <version>4.0.0-M2</version> + <version>4.1.0</version> <configuration> <skip>${docker.skip}</skip> <skipBuild>${docker.skip.build}</skipBuild> diff --git a/version.properties b/version.properties index 668657e962..99af34261b 100644 --- a/version.properties +++ b/version.properties @@ -3,7 +3,7 @@ # because they are used in Jenkins, whose plug-in doesn't support major=1 -minor=4 +minor=5 patch=0 base_version=${major}.${minor}.${patch} diff --git a/vnfm-simulator/vnf-service/pom.xml b/vnfm-simulator/vnf-service/pom.xml deleted file mode 100644 index 9a6825cf43..0000000000 --- a/vnfm-simulator/vnf-service/pom.xml +++ /dev/null @@ -1,78 +0,0 @@ -<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.vnfm</groupId> - <artifactId>vnfm-simulator</artifactId> - <version>0.0.1-SNAPSHOT</version> - </parent> - <artifactId>vnf-service</artifactId> - - - <properties> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <java.version>1.8</java.version> - </properties> - - <dependencies> - - <dependency> - <groupId>org.onap.vnfm</groupId> - <artifactId>vnfm-api</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-actuator</artifactId> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-test</artifactId> - <scope>test</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> - - </dependencies> -</project>
\ No newline at end of file diff --git a/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmController.java b/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmController.java deleted file mode 100644 index b9703b3a13..0000000000 --- a/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmController.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============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.svnfm.simulator.controller; - -import javax.ws.rs.core.MediaType; - -import org.onap.svnfm.simulator.services.SvnfmService; -import org.onap.vnfm.v1.model.CreateVnfRequest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -/** - * This class contains the VNF life cycle management operations - * - * @author ronan.kenny@est.tech - * - */ - -/** - * TO DO - * - * Implement Exception handling Implement VNFM adaptor call Identify the Create - * VNF response Test itwith the VNFM Adaptor - */ - -@RestController -@RequestMapping("/svnfm") - -public class SvnfmController { - - @Autowired - private SvnfmService svnfmService; - - private static final Logger LOGGER = LoggerFactory.getLogger(SvnfmController.class); - - @RequestMapping(method = RequestMethod.POST, value = "/vnf_instances") - public ResponseEntity<Object> createVNFInstance(@RequestBody final CreateVnfRequest createVNFRequest) { - LOGGER.info("Start createVNFInstance"); - HttpHeaders headers = new HttpHeaders(); - headers.add("Content-Type", MediaType.APPLICATION_JSON); - return new ResponseEntity<>(svnfmService.createVNF(), headers, HttpStatus.CREATED); - } -} diff --git a/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmHealthcheck.java b/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmHealthcheck.java deleted file mode 100644 index e6f55f6c5d..0000000000 --- a/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmHealthcheck.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============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.svnfm.simulator.controller; - -import org.onap.svnfm.simulator.exception.InvalidRestRequestException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - - -/** - * TO DO - * - * Implement Exception handling - * Implement VNFM adaptor call - * Identify the Create VNF response - * Test it with the VNFM Adaptor - */ - -@RestController -@RequestMapping("/svnfm") -public class SvnfmHealthcheck { - - private static final Logger LOGGER = LoggerFactory.getLogger(SvnfmHealthcheck.class); - - @RequestMapping(method = RequestMethod.GET, value = "/healthcheck") - public ResponseEntity<String> healthCheck() { - try { - return new ResponseEntity<>(HttpStatus.OK); - } catch (final InvalidRestRequestException extensions) { - final String message = "Not Found"; - LOGGER.error(message); - return new ResponseEntity<>(message, HttpStatus.NOT_FOUND); - } - } -} diff --git a/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/exception/GlobalExceptionHandler.java b/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/exception/GlobalExceptionHandler.java deleted file mode 100644 index a06f2d22ad..0000000000 --- a/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/exception/GlobalExceptionHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.onap.svnfm.simulator.exception; - -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.web.HttpMediaTypeNotSupportedException; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; - -@ControllerAdvice -public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { - @Override - protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, - HttpHeaders headers, HttpStatus status, WebRequest request) { - String error = "Malformed JSON request"; - return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); - } - - @Override - protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex, - HttpHeaders headers, HttpStatus status, WebRequest request) { - String error = "Media type Not Supported"; - return new ResponseEntity<>(error, HttpStatus.UNSUPPORTED_MEDIA_TYPE); - } -} diff --git a/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/exception/InvalidRestRequestException.java b/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/exception/InvalidRestRequestException.java deleted file mode 100644 index eabd4ec414..0000000000 --- a/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/exception/InvalidRestRequestException.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============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.svnfm.simulator.exception; - -/** - * @author ronan.kenny@est.tech - * - */ -public class InvalidRestRequestException extends RuntimeException { - - private static final long serialVersionUID = 3977807111893986938L; - - public InvalidRestRequestException(final String message) { - super(message); - } - - public InvalidRestRequestException(final String message, final Throwable cause) { - super(message, cause); - } -} diff --git a/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/services/SvnfmService.java b/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/services/SvnfmService.java deleted file mode 100644 index e2dc43a24b..0000000000 --- a/vnfm-simulator/vnf-service/src/main/java/org/onap/svnfm/simulator/services/SvnfmService.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============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.svnfm.simulator.services; - -import java.io.IOException; - -import org.apache.commons.io.IOUtils; -import org.onap.svnfm.simulator.notifications.VnfmAdapterCreationNotification; -import org.onap.vnfm.v1.model.InlineResponse201; -import org.springframework.stereotype.Service; - -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * This class handles the logic of VNF lifecycle - * - * @author Lathishbabu Ganesan (lathishbabu.ganesan@est.tech) - * - */ -@Service -public class SvnfmService { - - /** - * This method read the create VNF response from the json file and return it - * to the VNFM Adaptor - * - * @return - */ - public InlineResponse201 createVNF() { - Thread creationNodtification = new Thread(new VnfmAdapterCreationNotification()); - creationNodtification.start(); - ObjectMapper mapper = new ObjectMapper(); - InlineResponse201 inlineResponse201 = null; - try { - inlineResponse201 = mapper.readValue( - IOUtils.toString(getClass().getClassLoader().getResource("json/createVNFResponse.json")), - InlineResponse201.class); - } catch (IOException e) { - e.printStackTrace(); - } - return inlineResponse201; - } -} diff --git a/vnfm-simulator/vnf-service/src/main/resources/json/createVNFResponse.json b/vnfm-simulator/vnf-service/src/main/resources/json/createVNFResponse.json deleted file mode 100644 index a66bcc1334..0000000000 --- a/vnfm-simulator/vnf-service/src/main/resources/json/createVNFResponse.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "id": "147d9468-4646-11e9-80af-fa163e169afd", - "vnfInstanceName": "MME85_8.EricssonMMEVSPV2_0", - "vnfInstanceDescription": "2f3e21dd-99ba-45b1-b4da-1f71283c46f6", - "vnfdId": "sgsn-mme_onapmme01_cxp9025898_4r85d01", - "vnfProvider": "Ericsson", - "vnfProductName": "SGSN-MME", - "vnfSoftwareVersion": "1.24 (CXS101289_R85D01)", - "vnfdVersion": "onapmme01_cxp9025898_4r85d01", - "vnfPkgId": null, - "vnfConfigurableProperties": null, - "vimConnectionInfo": null, - "instantiationState": "NOT_INSTANTIATED", - "instantiatedVnfInfo": null, - "metadata": null, - "extensions": null, - "links": null - -} diff --git a/vnfm-simulator/vnfm-service/pom.xml b/vnfm-simulator/vnfm-service/pom.xml index 3f4f4512b3..380381f53b 100644 --- a/vnfm-simulator/vnfm-service/pom.xml +++ b/vnfm-simulator/vnfm-service/pom.xml @@ -1,116 +1,149 @@ -<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> - </properties> - <dependencies> - <dependency> - <groupId>org.onap.so.vnfm</groupId> - <artifactId>vnfm-api</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> - </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>
\ No newline at end of file + <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> diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/ApplicationConfig.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/ApplicationConfig.java new file mode 100644 index 0000000000..91b79754a5 --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/ApplicationConfig.java @@ -0,0 +1,43 @@ +package org.onap.svnfm.simulator.config; + +import java.net.InetAddress; +import java.util.Arrays; +import org.onap.svnfm.simulator.constants.Constant; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.concurrent.ConcurrentMapCache; +import org.springframework.cache.support.SimpleCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public class ApplicationConfig implements ApplicationRunner { + + private static final String PORT = "local.server.port"; + + @Autowired + private Environment environment; + + private String baseUrl; + + @Override + public void run(final ApplicationArguments args) throws Exception { + baseUrl = "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + environment.getProperty(PORT); + } + + public String getBaseUrl() { + return baseUrl; + } + + @Bean + public CacheManager cacheManager() { + Cache inlineResponse201 = new ConcurrentMapCache(Constant.IN_LINE_RESPONSE_201_CACHE); + SimpleCacheManager manager = new SimpleCacheManager(); + manager.setCaches(Arrays.asList(inlineResponse201)); + return manager; + } +} diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/SvnfmApplication.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/SvnfmApplication.java index 84b45d0bac..723ae906e6 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/SvnfmApplication.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/SvnfmApplication.java @@ -20,6 +20,7 @@ package org.onap.svnfm.simulator.config; +import org.onap.svnfm.simulator.controller.SvnfmController; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; @@ -27,7 +28,10 @@ import org.springframework.cache.annotation.EnableCaching; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; /** - * + * The spring boot application for the VNF LCM. + * <p> + * The VNFM receives requests through its REST API {@link SvnfmController} + * * @author Lathishbabu Ganesan (lathishbabu.ganesan@est.tech) * @author ronan.kenny@est.tech */ diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/WebSecurityConfigImpl.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/WebSecurityConfigImpl.java new file mode 100644 index 0000000000..18eadd2fc3 --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/WebSecurityConfigImpl.java @@ -0,0 +1,48 @@ +/*- + * ============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.svnfm.simulator.config; + +import org.onap.so.security.MSOSpringFirewall; +import org.onap.so.security.WebSecurityConfig; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.web.firewall.StrictHttpFirewall; + +/** + * Configure the web security for the application. + */ +@EnableWebSecurity +public class WebSecurityConfigImpl extends WebSecurityConfig { + + @Override + protected void configure(final HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().antMatchers("/**").permitAll(); + } + + @Override + public void configure(final WebSecurity web) throws Exception { + super.configure(web); + final StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } + +} diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/constants/Constant.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/constants/Constant.java index bd380903d5..98f47bf455 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/constants/Constant.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/constants/Constant.java @@ -27,9 +27,13 @@ package org.onap.svnfm.simulator.constants; */ public class Constant { + public static final String BASE_URL = "/vnflcm/v1"; public static final String VNF_PROVIDER = "XYZ"; - public static final String VNF_PROVIDER_NAME = "SGSN-MME"; + public static final String VNF_PROVIDER_NAME = "vCPE"; public static final String VNF_SOFTWARE_VERSION = "1.24"; - public static final String VNFD_VERSION = "onapmme01_cxp9025898_4r85d01"; + public static final String VNFD_VERSION = "onapvcpe01_cxp9025898_4r85d01"; public static final String VNF_NOT_INSTANTIATED = "NOT_INSTANTIATED"; + public static final String VNF_CONFIG_PROPERTIES = + "{\"isAutoScaleEnabled\": \"true\",\"isAutoHealingEnabled\": \"true\"}"; + public static final String IN_LINE_RESPONSE_201_CACHE = "inlineResponse201"; } diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmController.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmController.java index 11099a24fc..9c3a02d4e6 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmController.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/controller/SvnfmController.java @@ -22,30 +22,37 @@ package org.onap.svnfm.simulator.controller; import java.util.UUID; import javax.ws.rs.core.MediaType; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.CreateVnfRequest; +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; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InstantiateVnfRequest; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.LccnSubscriptionRequest; +import org.onap.svnfm.simulator.constants.Constant; import org.onap.svnfm.simulator.repository.VnfmCacheRepository; import org.onap.svnfm.simulator.services.SvnfmService; -import org.onap.vnfm.v1.model.CreateVnfRequest; -import org.onap.vnfm.v1.model.InlineResponse201; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** - * + * * @author Lathishbabu Ganesan (lathishbabu.ganesan@est.tech) * @author Ronan Kenny (ronan.kenny@est.tech) */ @RestController -@RequestMapping("/svnfm") +@RequestMapping(path = Constant.BASE_URL, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON) public class SvnfmController { @Autowired @@ -57,25 +64,30 @@ public class SvnfmController { private static final Logger LOGGER = LoggerFactory.getLogger(SvnfmController.class); /** - * - * @param createVNFRequest - * @return + * To create the Vnf and stores the response in cache + * + * @param CreateVnfRequest + * @return InlineResponse201 */ - @RequestMapping(method = RequestMethod.POST, value = "/vnf_instances") + @PostMapping(value = "/vnf_instances") public ResponseEntity<InlineResponse201> createVnf(@RequestBody final CreateVnfRequest createVNFRequest) { - LOGGER.info("Start createVnf------"); + LOGGER.info("Start createVnf {}", createVNFRequest); + final String id = UUID.randomUUID().toString(); final HttpHeaders headers = new HttpHeaders(); - headers.add("Content-Type", MediaType.APPLICATION_JSON); - return new ResponseEntity<>(vnfmCacheRepository.createVnf(createVNFRequest), headers, HttpStatus.CREATED); + headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + final ResponseEntity<InlineResponse201> responseEntity = + new ResponseEntity<>(vnfmCacheRepository.createVnf(createVNFRequest, id), headers, HttpStatus.CREATED); + LOGGER.info("Finished create {}", responseEntity); + return responseEntity; } /** - * + * Get the vnf by id from cache + * * @param vnfId - * @return vnfm cache repository + * @return InlineResponse201 */ - @RequestMapping(method = RequestMethod.GET, value = "/vnf_instances/{vnfInstanceId}", - produces = MediaType.APPLICATION_JSON) + @GetMapping(value = "/vnf_instances/{vnfInstanceId}") @ResponseStatus(code = HttpStatus.OK) public InlineResponse201 getVnf(@PathVariable("vnfInstanceId") final String vnfId) { LOGGER.info("Start getVnf------"); @@ -83,60 +95,79 @@ public class SvnfmController { } /** - * + * To instantiate the vnf and returns the operation id + * * @param vnfId - * @return response entity * @throws InterruptedException */ - @RequestMapping(method = RequestMethod.POST, value = "/vnf_instances/{vnfInstanceId}/instantiate") - public ResponseEntity<Object> instantiateVnf(@PathVariable("vnfInstanceId") final String vnfId) - throws InterruptedException { - LOGGER.info("Start instantiateVNFRequest"); - final String instantiateJobId = UUID.randomUUID().toString(); + @PostMapping(value = "/vnf_instances/{vnfInstanceId}/instantiate") + public ResponseEntity<Void> instantiateVnf(@PathVariable("vnfInstanceId") final String vnfId, + @RequestBody final InstantiateVnfRequest instantiateVNFRequest) { + LOGGER.info("Start instantiateVNFRequest {} ", instantiateVNFRequest); + final HttpHeaders headers = new HttpHeaders(); - headers.add("Content-Type", MediaType.APPLICATION_JSON); - headers.add("Location", instantiateJobId); - return new ResponseEntity<>(svnfmService.instatiateVnf(vnfId, instantiateJobId), headers, HttpStatus.ACCEPTED); + headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + headers.add(HttpHeaders.LOCATION, svnfmService.instantiateVnf(vnfId, instantiateVNFRequest)); + return new ResponseEntity<>(headers, HttpStatus.ACCEPTED); } /** - * - * @param jobId - * @return response entity - * @throws InterruptedException + * To delete the vnf by id + * + * @param vnfId + * @return InlineResponse201 */ - public ResponseEntity<Object> getJobStatus(@PathVariable("jobId") final String jobId) throws InterruptedException { - LOGGER.info("Start getJobStatus"); + @DeleteMapping(value = "/vnf_instances/{vnfInstanceId}") + @ResponseStatus(code = HttpStatus.OK) + public ResponseEntity<Void> deleteVnf(@PathVariable("vnfInstanceId") final String vnfId) { + LOGGER.info("Start deleting Vnf------"); + vnfmCacheRepository.deleteVnf(vnfId); final HttpHeaders headers = new HttpHeaders(); - headers.add("Content-Type", MediaType.APPLICATION_JSON); - return new ResponseEntity<>(svnfmService.getJobStatus(jobId), headers, HttpStatus.ACCEPTED); + headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + return new ResponseEntity<>(headers, HttpStatus.NO_CONTENT); } /** - * + * To terminate the vnf by id + * * @param vnfId - * @return delete VNF + * @throws InterruptedException */ - @RequestMapping(method = RequestMethod.DELETE, value = "/vnf_instances/{vnfInstanceId}", - produces = MediaType.APPLICATION_JSON) - @ResponseStatus(code = HttpStatus.OK) - public InlineResponse201 deleteVnf(@PathVariable("vnfInstanceId") final String vnfId) { - LOGGER.info("Start deleting Vnf------"); - return vnfmCacheRepository.deleteVnf(vnfId); + @PostMapping(value = "/vnf_instances/{vnfInstanceId}/terminate") + public ResponseEntity<Object> terminateVnf(@PathVariable("vnfInstanceId") final String vnfId) { + LOGGER.info("Start terminateVNFRequest {}", vnfId); + final HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + headers.add(HttpHeaders.LOCATION, svnfmService.terminateVnf(vnfId)); + return new ResponseEntity<>(headers, HttpStatus.ACCEPTED); } + /** - * - * @param vnfId + * To get the status of the operation by id + * + * @param operationId * @return response entity * @throws InterruptedException */ - @RequestMapping(method = RequestMethod.POST, value = "/vnf_instances/{vnfInstanceId}/terminate") - public ResponseEntity<Object> terminateVnf(@PathVariable("vnfInstanceId") final String vnfId) - throws InterruptedException { - LOGGER.info("Start terminateVNFRequest"); + @GetMapping(value = "/vnf_lcm_op_occs/{vnfLcmOpOccId}") + public ResponseEntity<InlineResponse200> getOperationStatus( + @PathVariable("vnfLcmOpOccId") final String operationId) { + LOGGER.info("Start getOperationStatus"); final HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", MediaType.APPLICATION_JSON); - return new ResponseEntity<>(svnfmService.terminateVnf(vnfId), headers, HttpStatus.ACCEPTED); + return new ResponseEntity<>(svnfmService.getOperationStatus(operationId), headers, HttpStatus.OK); + } + + @PostMapping(value = "/subscriptions") + public ResponseEntity<InlineResponse2001> subscribeForNotifications( + @RequestBody final LccnSubscriptionRequest lccnSubscriptionRequest) { + LOGGER.info("Subscription request received: {}", lccnSubscriptionRequest); + svnfmService.registerSubscription(lccnSubscriptionRequest); + final InlineResponse2001 response = new InlineResponse2001(); + + final HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + return new ResponseEntity<>(response, headers, HttpStatus.OK); } } diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/model/VnfJob.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/model/VnfOperation.java index 575223c700..c37f433668 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/model/VnfJob.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/model/VnfOperation.java @@ -21,30 +21,37 @@ package org.onap.svnfm.simulator.model; import javax.persistence.Column; import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.Table; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200; /** - * + * * @author Lathishbabu Ganesan (lathishbabu.ganesan@est.tech) * @author Ronan Kenny (ronan.kenny@est.tech) */ @Entity -@Table(name = "VNF_JOB") -public class VnfJob { +@Table(name = "VNF_OPERATION") +public class VnfOperation { @Id - @Column(name = "jobId", nullable = false) - private String jobId; + @Column(name = "operationId", nullable = false) + private String id; private String vnfInstanceId; - private String vnfId; - private String status; - public String getJobId() { - return jobId; + @Enumerated(EnumType.STRING) + private InlineResponse200.OperationEnum operation; + + @Enumerated(EnumType.STRING) + private InlineResponse200.OperationStateEnum operationState; + + public String getId() { + return id; } - public void setJobId(final String jobId) { - this.jobId = jobId; + public void setId(final String id) { + this.id = id; } public String getVnfInstanceId() { @@ -55,19 +62,19 @@ public class VnfJob { this.vnfInstanceId = vnfInstanceId; } - public String getVnfId() { - return vnfId; + public InlineResponse200.OperationEnum getOperation() { + return operation; } - public void setVnfId(final String vnfId) { - this.vnfId = vnfId; + public void setOperation(final InlineResponse200.OperationEnum operation) { + this.operation = operation; } - public String getStatus() { - return status; + public InlineResponse200.OperationStateEnum getOperationState() { + return operationState; } - public void setStatus(final String status) { - this.status = status; + public void setOperationState(final InlineResponse200.OperationStateEnum operationState) { + this.operationState = operationState; } } diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/model/Vnfds.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/model/Vnfds.java new file mode 100644 index 0000000000..ea171f0fce --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/model/Vnfds.java @@ -0,0 +1,97 @@ +package org.onap.svnfm.simulator.model; + +import java.util.List; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@ConfigurationProperties(prefix = "vnfds") +@Component +public class Vnfds { + + private List<Vnfd> vnfdList; + + public static class Vnfd { + + private String vnfdId; + private List<Vnfc> vnfclist; + + + public String getVnfdId() { + return vnfdId; + } + + public void setVnfdId(final String vnfdId) { + this.vnfdId = vnfdId; + } + + public List<Vnfc> getVnfcList() { + return vnfclist; + } + + public void setVnfcList(final List<Vnfc> vnfclist) { + this.vnfclist = vnfclist; + } + } + + + public static class Vnfc { + + private String vnfcId; + private String type; + private String vduId; + private String resourceTemplateId; + private String grantResourceId; + + public String getVnfcId() { + return vnfcId; + } + + public void setVnfcId(final String vnfcId) { + this.vnfcId = vnfcId; + } + + public String getVduId() { + return vduId; + } + + public void setVduId(final String vduId) { + this.vduId = vduId; + } + + public String getType() { + return type; + } + + public void setType(final String type) { + this.type = type; + } + + public String getResourceTemplateId() { + return resourceTemplateId; + } + + public void setResourceTemplateId(final String resourceTemplateId) { + this.resourceTemplateId = resourceTemplateId; + } + + public String getGrantResourceId() { + return grantResourceId; + } + + public void setGrantResourceId(final String grantResourceId) { + this.grantResourceId = grantResourceId; + } + + } + + + public List<Vnfd> getVnfdList() { + return vnfdList; + } + + + public void setVnfdList(final List<Vnfd> vnfdList) { + this.vnfdList = vnfdList; + } + +} diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/notifications/VnfInstantiationNotification.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/notifications/VnfInstantiationNotification.java index 153970b053..9a3cd95bec 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/notifications/VnfInstantiationNotification.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/notifications/VnfInstantiationNotification.java @@ -22,7 +22,8 @@ package org.onap.svnfm.simulator.notifications; -import org.onap.svnfm.simulator.services.SvnfmService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -31,16 +32,16 @@ import org.onap.svnfm.simulator.services.SvnfmService; */ public class VnfInstantiationNotification implements Runnable { - SvnfmService svnfmService = new SvnfmService(); + private static final Logger logger = LoggerFactory.getLogger(VnfInstantiationNotification.class); @Override public void run() { try { Thread.sleep(10000); } catch (final InterruptedException e) { - e.printStackTrace(); + logger.error("Error occured while simulating instantiation ", e); Thread.currentThread().interrupt(); } - System.out.println("Instantiation process finished"); + logger.info("Instantiation process finished"); } } diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/notifications/VnfmAdapterCreationNotification.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/notifications/VnfmAdapterCreationNotification.java index ff299ce12e..39de3444db 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/notifications/VnfmAdapterCreationNotification.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/notifications/VnfmAdapterCreationNotification.java @@ -22,6 +22,9 @@ package org.onap.svnfm.simulator.notifications; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * @author Lathishbabu Ganesan (lathishbabu.ganesan@est.tech) @@ -29,15 +32,17 @@ package org.onap.svnfm.simulator.notifications; */ public class VnfmAdapterCreationNotification implements Runnable { + private static final Logger logger = LoggerFactory.getLogger(VnfmAdapterCreationNotification.class); + @Override public void run() { try { Thread.sleep(10000); } catch (final InterruptedException e) { - e.printStackTrace(); + logger.error("Error occured while simulating creation ", e); Thread.currentThread().interrupt(); } - System.out.println("Call to VNFM Adapter-Create"); + logger.info("Call to VNFM Adapter-Create"); } } diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/notifications/VnfmAdapterDeletionNotification.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/notifications/VnfmAdapterDeletionNotification.java index f7a8eaa2dd..af6064fd6a 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/notifications/VnfmAdapterDeletionNotification.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/notifications/VnfmAdapterDeletionNotification.java @@ -22,6 +22,9 @@ package org.onap.svnfm.simulator.notifications; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * @author Lathishbabu Ganesan (lathishbabu.ganesan@est.tech) @@ -29,15 +32,17 @@ package org.onap.svnfm.simulator.notifications; */ public class VnfmAdapterDeletionNotification implements Runnable { + private static final Logger logger = LoggerFactory.getLogger(VnfmAdapterDeletionNotification.class); + @Override public void run() { try { Thread.sleep(10000); } catch (final InterruptedException e) { - e.printStackTrace(); + logger.error("Error occured while simulating deletion ", e); Thread.currentThread().interrupt(); } - System.out.println("Call to VNFM Adapter-Delete"); + logger.info("Call to VNFM Adapter-Delete"); } } diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/repository/VnfJobRepository.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/repository/VnfOperationRepository.java index b3b39bfdf1..43c201734f 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/repository/VnfJobRepository.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/repository/VnfOperationRepository.java @@ -20,7 +20,7 @@ package org.onap.svnfm.simulator.repository; -import org.onap.svnfm.simulator.model.VnfJob; +import org.onap.svnfm.simulator.model.VnfOperation; import org.springframework.data.repository.CrudRepository; /** @@ -28,6 +28,6 @@ import org.springframework.data.repository.CrudRepository; * @author Lathishbabu Ganesan (lathishbabu.ganesan@est.tech) * @author Ronan Kenny (ronan.kenny@est.tech) */ -public interface VnfJobRepository extends CrudRepository<VnfJob, String> { +public interface VnfOperationRepository extends CrudRepository<VnfOperation, String> { } diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/repository/VnfmCacheRepository.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/repository/VnfmCacheRepository.java index e41cbe1e3a..fbdbf744d0 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/repository/VnfmCacheRepository.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/repository/VnfmCacheRepository.java @@ -20,15 +20,17 @@ package org.onap.svnfm.simulator.repository; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.CreateVnfRequest; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201; +import org.onap.svnfm.simulator.constants.Constant; import org.onap.svnfm.simulator.services.SvnfmService; -import org.onap.vnfm.v1.model.CreateVnfRequest; -import org.onap.vnfm.v1.model.InlineResponse201; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Repository; /** - * + * * @author Lathishbabu Ganesan (lathishbabu.ganesan@est.tech) * @author Ronan Kenny (ronan.kenny@est.tech) */ @@ -38,12 +40,13 @@ public class VnfmCacheRepository { @Autowired private SvnfmService svnfmService; - @Cacheable(value = "inlineResponse201", key = "#createVnfRequest.vnfdId") - public InlineResponse201 createVnf(final CreateVnfRequest createVnfRequest) { - return svnfmService.createVnf(createVnfRequest); + @Cacheable(value = Constant.IN_LINE_RESPONSE_201_CACHE, key = "#id") + public InlineResponse201 createVnf(final CreateVnfRequest createVnfRequest, final String id) { + return svnfmService.createVnf(createVnfRequest, id); } - @Cacheable(value = "inlineResponse201", key = "#id") + + public InlineResponse201 getVnf(final String id) { return svnfmService.getVnf(id); } @@ -52,8 +55,6 @@ public class VnfmCacheRepository { * @param vnfId * @return */ - public InlineResponse201 deleteVnf(String vnfId) { - // TODO - return null; - } + @CacheEvict(value = Constant.IN_LINE_RESPONSE_201_CACHE, key = "#id") + public void deleteVnf(final String id) {} } diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/InstantiateOperationProgressor.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/InstantiateOperationProgressor.java new file mode 100644 index 0000000000..020fa0390d --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/InstantiateOperationProgressor.java @@ -0,0 +1,123 @@ +package org.onap.svnfm.simulator.services; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.modelmapper.ModelMapper; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantsAddResources; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantsAddResources.TypeEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.InlineResponse201; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.InlineResponse201AddResources; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.InlineResponse201VimConnections; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs.ChangeTypeEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201.InstantiationStateEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201InstantiatedVnfInfo; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201InstantiatedVnfInfoResourceHandle; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201InstantiatedVnfInfoVnfcResourceInfo; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201VimConnectionInfo; +import org.onap.svnfm.simulator.config.ApplicationConfig; +import org.onap.svnfm.simulator.model.VnfOperation; +import org.onap.svnfm.simulator.model.Vnfds; +import org.onap.svnfm.simulator.model.Vnfds.Vnfc; +import org.onap.svnfm.simulator.model.Vnfds.Vnfd; +import org.onap.svnfm.simulator.repository.VnfOperationRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class InstantiateOperationProgressor extends OperationProgressor { + + private static final Logger LOGGER = LoggerFactory.getLogger(InstantiateOperationProgressor.class); + + public InstantiateOperationProgressor(final VnfOperation operation, final SvnfmService svnfmService, + final VnfOperationRepository vnfOperationRepository, final ApplicationConfig applicationConfig, + final Vnfds vnfds, final SubscriptionService subscriptionService) { + super(operation, svnfmService, vnfOperationRepository, applicationConfig, vnfds, subscriptionService); + } + + @Override + protected List<GrantsAddResources> getAddResources(final String vnfdId) { + final List<GrantsAddResources> resources = new ArrayList<>(); + + for (final Vnfd vnfd : vnfds.getVnfdList()) { + if (vnfd.getVnfdId().equals(vnfdId)) { + for (final Vnfc vnfc : vnfd.getVnfcList()) { + final GrantsAddResources addResource = new GrantsAddResources(); + vnfc.setGrantResourceId(UUID.randomUUID().toString()); + addResource.setId(vnfc.getGrantResourceId()); + addResource.setType(TypeEnum.fromValue(vnfc.getType())); + addResource.setResourceTemplateId(vnfc.getResourceTemplateId()); + addResource.setVduId(vnfc.getVduId()); + resources.add(addResource); + } + } + } + return resources; + } + + @Override + protected List<GrantsAddResources> getRemoveResources(final String vnfdId) { + return Collections.emptyList(); + } + + @Override + protected List<InlineResponse201InstantiatedVnfInfoVnfcResourceInfo> handleGrantResponse( + final InlineResponse201 grantResponse) { + final InlineResponse201InstantiatedVnfInfo instantiatedVnfInfo = createInstantiatedVnfInfo(grantResponse); + svnfmService.updateVnf(InstantiationStateEnum.INSTANTIATED, instantiatedVnfInfo, operation.getVnfInstanceId(), + getVimConnections(grantResponse)); + return instantiatedVnfInfo.getVnfcResourceInfo(); + } + + private InlineResponse201InstantiatedVnfInfo createInstantiatedVnfInfo(final InlineResponse201 grantResponse) { + final InlineResponse201InstantiatedVnfInfo instantiatedVnfInfo = new InlineResponse201InstantiatedVnfInfo(); + + final Map<String, String> mapOfGrantResourceIdToVimConnectionId = new HashMap<>(); + for (final InlineResponse201AddResources addResource : grantResponse.getAddResources()) { + mapOfGrantResourceIdToVimConnectionId.put(addResource.getResourceDefinitionId(), + addResource.getVimConnectionId()); + } + LOGGER.info("VIM connections in grant response: {}", mapOfGrantResourceIdToVimConnectionId); + + for (final Vnfd vnfd : vnfds.getVnfdList()) { + if (vnfd.getVnfdId().equals(svnfmService.getVnf(operation.getVnfInstanceId()).getVnfdId())) { + for (final Vnfc vnfc : vnfd.getVnfcList()) { + final InlineResponse201InstantiatedVnfInfoVnfcResourceInfo vnfcResourceInfoItem = + new InlineResponse201InstantiatedVnfInfoVnfcResourceInfo(); + vnfcResourceInfoItem.setId(vnfc.getVnfcId()); + vnfcResourceInfoItem.setVduId(vnfc.getVduId()); + final InlineResponse201InstantiatedVnfInfoResourceHandle computeResource = + new InlineResponse201InstantiatedVnfInfoResourceHandle(); + computeResource.setResourceId(UUID.randomUUID().toString()); + LOGGER.info("Checking for VIM connection id for : {}", vnfc.getGrantResourceId()); + computeResource + .setVimConnectionId(mapOfGrantResourceIdToVimConnectionId.get(vnfc.getGrantResourceId())); + + computeResource.setVimLevelResourceType("OS::Nova::Server"); + vnfcResourceInfoItem.setComputeResource(computeResource); + instantiatedVnfInfo.addVnfcResourceInfoItem(vnfcResourceInfoItem); + } + } + } + + return instantiatedVnfInfo; + } + + + private List<InlineResponse201VimConnectionInfo> getVimConnections(final InlineResponse201 grantResponse) { + final List<InlineResponse201VimConnectionInfo> vimConnectionInfo = new ArrayList<>(); + for (final InlineResponse201VimConnections vimConnection : grantResponse.getVimConnections()) { + final ModelMapper modelMapper = new ModelMapper(); + vimConnectionInfo.add(modelMapper.map(vimConnection, InlineResponse201VimConnectionInfo.class)); + } + return vimConnectionInfo; + } + + @Override + protected ChangeTypeEnum getVnfcChangeType() { + return ChangeTypeEnum.ADDED; + } + +} diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/OperationProgressor.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/OperationProgressor.java new file mode 100644 index 0000000000..1e31ab2fdb --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/OperationProgressor.java @@ -0,0 +1,239 @@ +package org.onap.svnfm.simulator.services; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import javax.ws.rs.core.MediaType; +import org.apache.commons.codec.binary.Base64; +import org.modelmapper.ModelMapper; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.ApiResponse; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantRequest; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantsAddResources; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantsLinks; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantsLinksVnfLcmOpOcc; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.InlineResponse201; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.ApiClient; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.ApiException; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.api.DefaultApi; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs.ChangeTypeEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationLinks; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationLinksVnfInstance; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.VnfLcmOperationOccurrenceNotification; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.VnfLcmOperationOccurrenceNotification.NotificationStatusEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.VnfLcmOperationOccurrenceNotification.NotificationTypeEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.VnfLcmOperationOccurrenceNotification.OperationEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.VnfLcmOperationOccurrenceNotification.OperationStateEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201InstantiatedVnfInfoVnfcResourceInfo; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.SubscriptionsAuthenticationParamsBasic; +import org.onap.svnfm.simulator.config.ApplicationConfig; +import org.onap.svnfm.simulator.model.VnfOperation; +import org.onap.svnfm.simulator.model.Vnfds; +import org.onap.svnfm.simulator.repository.VnfOperationRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class OperationProgressor implements Runnable { + + private static final Logger LOGGER = LoggerFactory.getLogger(OperationProgressor.class); + protected final VnfOperation operation; + protected final SvnfmService svnfmService; + private final VnfOperationRepository vnfOperationRepository; + private final ApplicationConfig applicationConfig; + protected final Vnfds vnfds; + private final SubscriptionService subscriptionService; + private final DefaultApi notificationClient; + private final org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.api.DefaultApi grantClient; + + public OperationProgressor(final VnfOperation operation, final SvnfmService svnfmService, + final VnfOperationRepository vnfOperationRepository, final ApplicationConfig applicationConfig, + final Vnfds vnfds, final SubscriptionService subscriptionService) { + this.operation = operation; + this.svnfmService = svnfmService; + this.vnfOperationRepository = vnfOperationRepository; + this.applicationConfig = applicationConfig; + this.vnfds = vnfds; + this.subscriptionService = subscriptionService; + + final ApiClient apiClient = new ApiClient(); + String callBackUrl = subscriptionService.getSubscriptions().iterator().next().getCallbackUri(); + callBackUrl = callBackUrl.substring(0, callBackUrl.indexOf("/lcn/")); + apiClient.setBasePath(callBackUrl); + notificationClient = new DefaultApi(apiClient); + + final org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.ApiClient grantApiClient = + new org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.ApiClient(); + grantApiClient.setBasePath(callBackUrl); + grantClient = new org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.api.DefaultApi(grantApiClient); + } + + @Override + public void run() { + try { + final VnfLcmOperationOccurrenceNotification notificationOfStarting = + buildNotification(NotificationStatusEnum.START, OperationStateEnum.STARTING); + sendNotification(notificationOfStarting); + + sleep(2000); + setState(InlineResponse200.OperationStateEnum.PROCESSING); + final VnfLcmOperationOccurrenceNotification notificationOfProcessing = + buildNotification(NotificationStatusEnum.START, OperationStateEnum.PROCESSING); + sendNotification(notificationOfProcessing); + + + final GrantRequest grantRequest = buildGrantRequest(); + final InlineResponse201 grantResponse = sendGrantRequest(grantRequest); + final List<InlineResponse201InstantiatedVnfInfoVnfcResourceInfo> vnfcs = handleGrantResponse(grantResponse); + + svnfmService.getVnf(operation.getVnfInstanceId()).getInstantiatedVnfInfo(); + + sleep(10000); + setState(InlineResponse200.OperationStateEnum.COMPLETED); + final VnfLcmOperationOccurrenceNotification notificationOfCompleted = + buildNotification(NotificationStatusEnum.RESULT, OperationStateEnum.COMPLETED); + notificationOfCompleted.setAffectedVnfcs(getVnfcs(vnfcs)); + + sendNotification(notificationOfCompleted); + } catch (final Exception exception) { + LOGGER.error("Error in OperationProgressor ", exception); + } + + } + + private void sleep(final long milliSeconds) { + try { + Thread.sleep(milliSeconds); + } catch (final InterruptedException e) { + operation.setOperationState(InlineResponse200.OperationStateEnum.FAILED); + } + } + + private void setState(final InlineResponse200.OperationStateEnum state) { + LOGGER.info("Setting state to {} for operation {}", state, operation.getId()); + operation.setOperationState(state); + vnfOperationRepository.save(operation); + } + + private VnfLcmOperationOccurrenceNotification buildNotification(final NotificationStatusEnum status, + final OperationStateEnum operationState) { + final VnfLcmOperationOccurrenceNotification notification = new VnfLcmOperationOccurrenceNotification(); + notification.setId(UUID.randomUUID().toString()); + notification.setNotificationType(NotificationTypeEnum.VNFLCMOPERATIONOCCURRENCENOTIFICATION); + notification.setNotificationStatus(status); + notification.setOperationState(operationState); + notification.setOperation(OperationEnum.fromValue(operation.getOperation().toString())); + notification.setVnfInstanceId(operation.getVnfInstanceId()); + notification.setVnfLcmOpOccId(operation.getId()); + + final LcnVnfLcmOperationOccurrenceNotificationLinks links = new LcnVnfLcmOperationOccurrenceNotificationLinks(); + final LcnVnfLcmOperationOccurrenceNotificationLinksVnfInstance vnfInstanceLink = + new LcnVnfLcmOperationOccurrenceNotificationLinksVnfInstance(); + vnfInstanceLink.setHref(getVnfLink()); + links.setVnfInstance(vnfInstanceLink); + + + final LcnVnfLcmOperationOccurrenceNotificationLinksVnfInstance operationLink = + new LcnVnfLcmOperationOccurrenceNotificationLinksVnfInstance(); + operationLink.setHref(getOperationLink()); + links.setVnfLcmOpOcc(operationLink); + + notification.setLinks(links); + + return notification; + } + + private List<LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs> getVnfcs( + final List<InlineResponse201InstantiatedVnfInfoVnfcResourceInfo> instantiatedVnfcs) { + final List<LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs> vnfcs = new ArrayList<>(); + if (instantiatedVnfcs != null) { + for (final InlineResponse201InstantiatedVnfInfoVnfcResourceInfo instantiatedVnfc : instantiatedVnfcs) { + LOGGER.info("VNFC TO BE CONVERTED: {}", instantiatedVnfc); + final ModelMapper mapper = new ModelMapper(); + final LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs vnfc = + mapper.map(instantiatedVnfc, LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs.class); + LOGGER.info("VNFC FROM CONVERSION: {}", vnfc); + vnfc.setChangeType(getVnfcChangeType()); + vnfcs.add(vnfc); + } + } + return vnfcs; + } + + private void sendNotification(final VnfLcmOperationOccurrenceNotification notification) { + LOGGER.info("Sending notification: {}", notification); + try { + final SubscriptionsAuthenticationParamsBasic subscriptionAuthentication = + subscriptionService.getSubscriptions().iterator().next().getAuthentication().getParamsBasic(); + final String auth = + subscriptionAuthentication.getUserName() + ":" + subscriptionAuthentication.getPassword(); + final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1)); + final String authHeader = "Basic " + new String(encodedAuth); + notificationClient.lcnVnfLcmOperationOccurrenceNotificationPostWithHttpInfo(notification, + MediaType.APPLICATION_JSON, authHeader); + } catch (final ApiException exception) { + LOGGER.error("Error sending notification: " + notification, exception); + } + } + + + public GrantRequest buildGrantRequest() { + final GrantRequest grantRequest = new GrantRequest(); + grantRequest.setVnfInstanceId(operation.getVnfInstanceId()); + final String vnfdId = svnfmService.getVnf(operation.getVnfInstanceId()).getVnfdId(); + grantRequest.setVnfdId(vnfdId); + grantRequest.setAddResources(getAddResources(vnfdId)); + grantRequest.setRemoveResources(getRemoveResources(vnfdId)); + grantRequest.setVnfLcmOpOccId(operation.getId()); + grantRequest + .setOperation(org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantRequest.OperationEnum + .fromValue(operation.getOperation().getValue())); + grantRequest.setIsAutomaticInvocation(false); + + final GrantsLinksVnfLcmOpOcc vnfInstanceLink = new GrantsLinksVnfLcmOpOcc(); + vnfInstanceLink.setHref(getVnfLink()); + final GrantsLinksVnfLcmOpOcc operationInstanceLink = new GrantsLinksVnfLcmOpOcc(); + operationInstanceLink.setHref(getOperationLink()); + final GrantsLinks links = new GrantsLinks(); + links.setVnfInstance(vnfInstanceLink); + links.setVnfLcmOpOcc(operationInstanceLink); + grantRequest.setLinks(links); + return grantRequest; + } + + protected abstract List<GrantsAddResources> getAddResources(final String vnfdId); + + protected abstract List<GrantsAddResources> getRemoveResources(final String vnfdId); + + protected abstract List<InlineResponse201InstantiatedVnfInfoVnfcResourceInfo> handleGrantResponse( + InlineResponse201 grantResponse); + + protected abstract ChangeTypeEnum getVnfcChangeType(); + + private InlineResponse201 sendGrantRequest(final GrantRequest grantRequest) { + LOGGER.info("Sending grant request: {}", grantRequest); + try { + final ApiResponse<InlineResponse201> response = grantClient.grantsPostWithHttpInfo(grantRequest, + MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, "Basic dm5mbTpwYXNzd29yZDEk"); + LOGGER.info("Grant Response: {}", response); + return response.getData(); + } catch (final org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.ApiException exception) { + LOGGER.error("Error sending notification: " + grantRequest, exception); + return null; + } + } + + private String getVnfLink() { + return getLinkBaseUrl() + "/vnf_instances/" + operation.getVnfInstanceId(); + } + + private String getOperationLink() { + return getLinkBaseUrl() + "/vnf_lcm_op_occs/" + operation.getId(); + } + + private String getLinkBaseUrl() { + return applicationConfig.getBaseUrl() + "/vnflcm/v1"; + } + +} diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/SubscriptionService.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/SubscriptionService.java new file mode 100644 index 0000000000..6a2340bdf6 --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/SubscriptionService.java @@ -0,0 +1,21 @@ +package org.onap.svnfm.simulator.services; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.LccnSubscriptionRequest; +import org.springframework.stereotype.Service; + +@Service +public class SubscriptionService { + + Collection<LccnSubscriptionRequest> subscriptions = new ArrayList<>(); + + public void registerSubscription(final LccnSubscriptionRequest subscription) { + subscriptions.add(subscription); + } + + public Collection<LccnSubscriptionRequest> getSubscriptions() { + return Collections.unmodifiableCollection(subscriptions); + } +} diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/SvnfmService.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/SvnfmService.java index f7f4eaa4a2..21bb00dba7 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/SvnfmService.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/SvnfmService.java @@ -21,22 +21,39 @@ package org.onap.svnfm.simulator.services; import java.lang.reflect.InvocationTargetException; -import java.util.Optional; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import org.modelmapper.ModelMapper; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.CreateVnfRequest; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201.InstantiationStateEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201InstantiatedVnfInfo; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201VimConnectionInfo; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InstantiateVnfRequest; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.LccnSubscriptionRequest; +import org.onap.svnfm.simulator.config.ApplicationConfig; +import org.onap.svnfm.simulator.constants.Constant; import org.onap.svnfm.simulator.model.VnfInstance; -import org.onap.svnfm.simulator.model.VnfJob; +import org.onap.svnfm.simulator.model.VnfOperation; +import org.onap.svnfm.simulator.model.Vnfds; import org.onap.svnfm.simulator.notifications.VnfInstantiationNotification; import org.onap.svnfm.simulator.notifications.VnfmAdapterCreationNotification; -import org.onap.svnfm.simulator.repository.VnfJobRepository; +import org.onap.svnfm.simulator.repository.VnfOperationRepository; import org.onap.svnfm.simulator.repository.VnfmRepository; -import org.onap.vnfm.v1.model.CreateVnfRequest; -import org.onap.vnfm.v1.model.InlineResponse201; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.support.SimpleValueWrapper; import org.springframework.stereotype.Service; /** - * + * * @author Lathishbabu Ganesan (lathishbabu.ganesan@est.tech) * @author Ronan Kenny (ronan.kenny@est.tech) */ @@ -47,122 +64,136 @@ public class SvnfmService { VnfmRepository vnfmRepository; @Autowired - VnfJobRepository vnfJobRepository; + VnfOperationRepository vnfOperationRepository; @Autowired private VnfmHelper vnfmHelper; + @Autowired + ApplicationConfig applicationConfig; + + @Autowired + CacheManager cacheManager; + + @Autowired + Vnfds vnfds; + + @Autowired + SubscriptionService subscriptionService; + + private final ExecutorService executor = Executors.newCachedThreadPool(); + private static final Logger LOGGER = LoggerFactory.getLogger(SvnfmService.class); /** - * + * * @param createVNFRequest * @return inlineResponse201 */ - public InlineResponse201 createVnf(final CreateVnfRequest createVNFRequest) { + public InlineResponse201 createVnf(final CreateVnfRequest createVNFRequest, final String id) { InlineResponse201 inlineResponse201 = null; try { - final VnfInstance vnfInstance = vnfmHelper.createVnfInstance(createVNFRequest); + final VnfInstance vnfInstance = vnfmHelper.createVnfInstance(createVNFRequest, id); vnfmRepository.save(vnfInstance); final Thread creationNotification = new Thread(new VnfmAdapterCreationNotification()); creationNotification.start(); inlineResponse201 = vnfmHelper.getInlineResponse201(vnfInstance); - LOGGER.debug("Response from Create VNF", inlineResponse201); + LOGGER.debug("Response from Create VNF {}", inlineResponse201); } catch (IllegalAccessException | InvocationTargetException e) { LOGGER.error("Failed in Create Vnf", e); } return inlineResponse201; } + @CachePut(value = Constant.IN_LINE_RESPONSE_201_CACHE, key = "#id") + public InlineResponse201 updateVnf(final InstantiationStateEnum instantiationState, + final InlineResponse201InstantiatedVnfInfo instantiatedVnfInfo, final String id, + final List<InlineResponse201VimConnectionInfo> vimConnectionInfo) { + final InlineResponse201 vnf = getVnf(id); + vnf.setInstantiatedVnfInfo(instantiatedVnfInfo); + vnf.setInstantiationState(instantiationState); + vnf.setVimConnectionInfo(vimConnectionInfo); + return vnf; + } + /** - * + * * @param vnfId - * @param instantiateJobId + * @param instantiateVNFRequest + * @param operationId * @throws InterruptedException */ - public Object instatiateVnf(final String vnfId, final String instantiateJobId) throws InterruptedException { - final VnfJob vnfJob = buildVnfInstantiation(vnfId, instantiateJobId); - vnfJobRepository.save(vnfJob); - getJobStatus(vnfJob.getJobId()); - return null; + public String instantiateVnf(final String vnfId, final InstantiateVnfRequest instantiateVNFRequest) { + final VnfOperation vnfOperation = buildVnfOperation(InlineResponse200.OperationEnum.INSTANTIATE, vnfId); + vnfOperationRepository.save(vnfOperation); + executor.submit(new InstantiateOperationProgressor(vnfOperation, this, vnfOperationRepository, + applicationConfig, vnfds, subscriptionService)); + return vnfOperation.getId(); } /** - * + * vnfOperationRepository + * * @param vnfId - * @param instantiateJobId + * @param instantiateOperationId */ - public VnfJob buildVnfInstantiation(final String vnfId, final String instantiateJobId) { - final VnfJob vnfJob = new VnfJob(); - final Optional<VnfInstance> vnfInstance = vnfmRepository.findById(vnfId); - - if (vnfInstance.isPresent()) { - vnfJob.setJobId(instantiateJobId); - for (final VnfInstance instance : vnfmRepository.findAll()) { - if (instance.getId().equals(vnfId)) { - vnfJob.setVnfInstanceId(instance.getVnfInstanceDescription()); - } - } - vnfJob.setVnfId(vnfId); - vnfJob.setStatus("STARTING"); - } - return vnfJob; + public VnfOperation buildVnfOperation(final InlineResponse200.OperationEnum operation, final String vnfId) { + final VnfOperation vnfOperation = new VnfOperation(); + vnfOperation.setId(UUID.randomUUID().toString()); + vnfOperation.setOperation(operation); + vnfOperation.setOperationState(InlineResponse200.OperationStateEnum.STARTING); + vnfOperation.setVnfInstanceId(vnfId); + return vnfOperation; } /** - * - * @param jobId + * + * @param operationId * @throws InterruptedException */ - public Object getJobStatus(final String jobId) throws InterruptedException { - LOGGER.info("Getting job status with id: " + jobId); - for (int i = 0; i < 5; i++) { - LOGGER.info("Instantiation status: RUNNING"); - Thread.sleep(5000); - for (final VnfJob job : vnfJobRepository.findAll()) { - if (job.getJobId().equals(jobId)) { - job.setStatus("RUNNING"); - vnfJobRepository.save(job); - } - } - } + public InlineResponse200 getOperationStatus(final String operationId) { + LOGGER.info("Getting operation status with id: {}", operationId); final Thread instantiationNotification = new Thread(new VnfInstantiationNotification()); instantiationNotification.start(); - for (final VnfJob job : vnfJobRepository.findAll()) { - if (job.getJobId().equals(jobId)) { - job.setStatus("COMPLETE"); - vnfJobRepository.save(job); + for (final VnfOperation operation : vnfOperationRepository.findAll()) { + LOGGER.info("Operation found: {}", operation); + if (operation.getId().equals(operationId)) { + final ModelMapper modelMapper = new ModelMapper(); + return modelMapper.map(operation, InlineResponse200.class); } } return null; } /** - * + * * @param vnfId * @return inlineResponse201 */ public InlineResponse201 getVnf(final String vnfId) { - InlineResponse201 inlineResponse201 = null; - - final Optional<VnfInstance> vnfInstance = vnfmRepository.findById(vnfId); - try { - if (vnfInstance.isPresent()) { - inlineResponse201 = vnfmHelper.getInlineResponse201(vnfInstance.get()); - LOGGER.debug("Response from get VNF", inlineResponse201); - } - } catch (IllegalAccessException | InvocationTargetException e) { - LOGGER.error("Failed in get Vnf", e); + final Cache ca = cacheManager.getCache(Constant.IN_LINE_RESPONSE_201_CACHE); + final SimpleValueWrapper wrapper = (SimpleValueWrapper) ca.get(vnfId); + final InlineResponse201 inlineResponse201 = (InlineResponse201) wrapper.get(); + if (inlineResponse201 != null) { + LOGGER.info("Cache Read Successful"); + return inlineResponse201; } - return inlineResponse201; + return null; } /** * @param vnfId * @return */ - public Object terminateVnf(String vnfId) { - // TODO - return null; + public String terminateVnf(final String vnfId) { + final VnfOperation vnfOperation = buildVnfOperation(InlineResponse200.OperationEnum.TERMINATE, vnfId); + vnfOperationRepository.save(vnfOperation); + executor.submit(new TerminateOperationProgressor(vnfOperation, this, vnfOperationRepository, applicationConfig, + vnfds, subscriptionService)); + return vnfOperation.getId(); + } + + public void registerSubscription(final LccnSubscriptionRequest subscription) { + subscriptionService.registerSubscription(subscription); } } diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/TerminateOperationProgressor.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/TerminateOperationProgressor.java new file mode 100644 index 0000000000..c829be9a4f --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/TerminateOperationProgressor.java @@ -0,0 +1,74 @@ +package org.onap.svnfm.simulator.services; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantsAddResources; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantsAddResources.TypeEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantsResource; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.InlineResponse201; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs.ChangeTypeEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201.InstantiationStateEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201InstantiatedVnfInfoResourceHandle; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201InstantiatedVnfInfoVnfcResourceInfo; +import org.onap.svnfm.simulator.config.ApplicationConfig; +import org.onap.svnfm.simulator.model.VnfOperation; +import org.onap.svnfm.simulator.model.Vnfds; +import org.onap.svnfm.simulator.repository.VnfOperationRepository; + +public class TerminateOperationProgressor extends OperationProgressor { + + public TerminateOperationProgressor(final VnfOperation operation, final SvnfmService svnfmService, + final VnfOperationRepository vnfOperationRepository, final ApplicationConfig applicationConfig, + final Vnfds vnfds, final SubscriptionService subscriptionService) { + super(operation, svnfmService, vnfOperationRepository, applicationConfig, vnfds, subscriptionService); + } + + @Override + protected List<GrantsAddResources> getAddResources(final String vnfdId) { + return Collections.emptyList(); + } + + @Override + protected List<GrantsAddResources> getRemoveResources(final String vnfdId) { + final List<GrantsAddResources> resources = new ArrayList<>(); + + final org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201 vnf = + svnfmService.getVnf(operation.getVnfInstanceId()); + for (final InlineResponse201InstantiatedVnfInfoVnfcResourceInfo vnfc : vnf.getInstantiatedVnfInfo() + .getVnfcResourceInfo()) { + final GrantsAddResources addResource = new GrantsAddResources(); + addResource.setId(UUID.randomUUID().toString()); + addResource.setType(TypeEnum.COMPUTE); + addResource.setVduId(vnfc.getVduId()); + final GrantsResource resource = new GrantsResource(); + + final InlineResponse201InstantiatedVnfInfoResourceHandle computeResource = vnfc.getComputeResource(); + resource.setResourceId(computeResource.getResourceId()); + resource.setVimConnectionId(computeResource.getVimConnectionId()); + resource.setVimLevelResourceType(computeResource.getVimLevelResourceType()); + addResource.setResource(resource); + resources.add(addResource); + + } + return resources; + } + + @Override + protected List<InlineResponse201InstantiatedVnfInfoVnfcResourceInfo> handleGrantResponse( + final InlineResponse201 grantResponse) { + final List<InlineResponse201InstantiatedVnfInfoVnfcResourceInfo> vnfcs = + svnfmService.getVnf(operation.getVnfInstanceId()).getInstantiatedVnfInfo().getVnfcResourceInfo(); + svnfmService.updateVnf(InstantiationStateEnum.NOT_INSTANTIATED, null, operation.getVnfInstanceId(), null); + return vnfcs; + } + + @Override + protected ChangeTypeEnum getVnfcChangeType() { + return ChangeTypeEnum.REMOVED; + } + + + +} diff --git a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/VnfmHelper.java b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/VnfmHelper.java index f35cbf2f49..60b251c4d4 100644 --- a/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/VnfmHelper.java +++ b/vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/VnfmHelper.java @@ -21,31 +21,39 @@ package org.onap.svnfm.simulator.services; import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; import org.apache.commons.beanutils.BeanUtils; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.CreateVnfRequest; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201.InstantiationStateEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201Links; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201LinksSelf; +import org.onap.svnfm.simulator.config.ApplicationConfig; import org.onap.svnfm.simulator.constants.Constant; import org.onap.svnfm.simulator.model.VnfInstance; -import org.onap.vnfm.v1.model.CreateVnfRequest; -import org.onap.vnfm.v1.model.InlineResponse201; -import org.onap.vnfm.v1.model.InlineResponse201.InstantiationStateEnum; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * + * * @author Lathishbabu Ganesan (lathishbabu.ganesan@est.tech) * @author Ronan Kenny (ronan.kenny@est.tech) */ @Component public class VnfmHelper { + @Autowired + private ApplicationConfig applicationConfig; + /** - * + * * @param createVNFRequest * @return vnfInstance */ - public VnfInstance createVnfInstance(final CreateVnfRequest createVNFRequest) { + public VnfInstance createVnfInstance(final CreateVnfRequest createVNFRequest, final String id) { final VnfInstance vnfInstance = new VnfInstance(); - final String vnfId = createVNFRequest.getVnfdId(); - vnfInstance.setId(vnfId); + vnfInstance.setId(id); vnfInstance.setVnfInstanceName(createVNFRequest.getVnfInstanceName()); vnfInstance.setVnfInstanceDescription(createVNFRequest.getVnfInstanceDescription()); vnfInstance.setVnfdId(createVNFRequest.getVnfdId()); @@ -55,7 +63,7 @@ public class VnfmHelper { } /** - * + * * @param vnfInstance * @return inlineResponse201 * @throws IllegalAccessException @@ -68,6 +76,27 @@ public class VnfmHelper { inlineResponse201.setVnfdVersion(Constant.VNFD_VERSION); inlineResponse201.setVnfSoftwareVersion(Constant.VNF_SOFTWARE_VERSION); inlineResponse201.setInstantiationState(InstantiationStateEnum.NOT_INSTANTIATED); + inlineResponse201.setVnfConfigurableProperties(getConfigProperties()); + addAdditionalPRopertyInlineResponse201(inlineResponse201); return inlineResponse201; } + + private Map<String, String> getConfigProperties() { + final Map<String, String> configProperties = new HashMap<>(); + configProperties.put("ipAddress", "10.11.12.13"); + return configProperties; + } + + private void addAdditionalPRopertyInlineResponse201(final InlineResponse201 inlineResponse201) { + final InlineResponse201LinksSelf VnfInstancesLinksSelf = new InlineResponse201LinksSelf(); + VnfInstancesLinksSelf + .setHref(applicationConfig.getBaseUrl() + "/vnflcm/v1/vnf_instances/" + inlineResponse201.getId()); + final InlineResponse201LinksSelf VnfInstancesLinksSelfInstantiate = new InlineResponse201LinksSelf(); + VnfInstancesLinksSelfInstantiate.setHref(applicationConfig.getBaseUrl() + "/vnflcm/v1/vnf_instances/" + + inlineResponse201.getId() + "/instantiate"); + final InlineResponse201Links inlineResponse201Links = new InlineResponse201Links(); + inlineResponse201Links.setSelf(VnfInstancesLinksSelf); + inlineResponse201Links.setInstantiate(VnfInstancesLinksSelfInstantiate); + inlineResponse201.setLinks(inlineResponse201Links); + } } diff --git a/vnfm-simulator/vnfm-service/src/main/resources/application.properties b/vnfm-simulator/vnfm-service/src/main/resources/application.properties deleted file mode 100644 index c5b36d77f4..0000000000 --- a/vnfm-simulator/vnfm-service/src/main/resources/application.properties +++ /dev/null @@ -1,13 +0,0 @@ -# Enabling H2 Console -spring.h2.console.enabled=true -spring.h2.console.path=/console -spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE -spring.datasource.username=admin -spring.datasource.password=admin -spring.datasource.driverClassName=org.h2.Driver -spring.jpa.hibernate.ddl-auto = update -spring.jpa.show-sql=true -logging.level.org.hibernate.SQL=DEBUG -logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE - -server.port=9081
\ No newline at end of file diff --git a/vnfm-simulator/vnfm-service/src/main/resources/application.yaml b/vnfm-simulator/vnfm-service/src/main/resources/application.yaml new file mode 100644 index 0000000000..2ef302ce25 --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/main/resources/application.yaml @@ -0,0 +1,59 @@ +# Copyright © 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. + +spring: + h2: + console: + enabled: true + path: console + datasource: + url: jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE + username: admin + password: admin + http: + converters: + preferred-json-mapper: gson + security: + usercredentials: + - username: vnfm + password: '$2a$10$Fh9ffgPw2vnmsghsRD3ZauBL1aKXebigbq3BB1RPWtE62UDILsjke' + role: BPEL-Client + +server: + port: 9093 + tomcat: + max-threads: 50 + +vnfds: + vnfdlist: + - vnfdid: 1 + vnfclist: + - vnfcid: VNFC1 + resourceTemplateId: vnfd1_vnfc1 + vduId: vnfd1_vduForVnfc1 + type: COMPUTE + - vnfcid: VNFC2 + resourceTemplateId: vnfd1_vnfc2 + vduId: vnfd1_vduForVnfc2 + type: COMPUTE + - vnfdid: 2 + vnfclist: + - vnfcid: VNFC3 + resourceTemplateId: vnfd2_vnfc3 + vduId: vnfd2_vduForVnfc3 + type: COMPUTE + - vnfcid: VNFC4 + resourceTemplateId: vnfd2_vnfc4 + vduId: vnfd2_vduForVnfc4 + type: COMPUTE
\ No newline at end of file diff --git a/vnfm-simulator/vnfm-service/src/test/java/org/onap/svnfm/simulator/controllers/TestSvnfmController.java b/vnfm-simulator/vnfm-service/src/test/java/org/onap/svnfm/simulator/controllers/TestSvnfmController.java index f338b5828e..9cb0702ee0 100644 --- a/vnfm-simulator/vnfm-service/src/test/java/org/onap/svnfm/simulator/controllers/TestSvnfmController.java +++ b/vnfm-simulator/vnfm-service/src/test/java/org/onap/svnfm/simulator/controllers/TestSvnfmController.java @@ -20,10 +20,13 @@ package org.onap.svnfm.simulator.controllers; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -31,15 +34,15 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.CreateVnfRequest; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201; +import org.onap.svnfm.simulator.constants.Constant; import org.onap.svnfm.simulator.controller.SvnfmController; import org.onap.svnfm.simulator.repository.VnfmCacheRepository; import org.onap.svnfm.simulator.services.SvnfmService; -import org.onap.vnfm.v1.model.CreateVnfRequest; -import org.onap.vnfm.v1.model.InlineResponse201; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(MockitoJUnitRunner.class) public class TestSvnfmController { @@ -69,14 +72,12 @@ public class TestSvnfmController { createVnfRequest.setVnfInstanceName("createVnfInstanceTest"); createVnfRequest.setVnfInstanceDescription("createVnfInstanceTest"); - when(vnfmCacheRepository.createVnf(createVnfRequest)).thenReturn(new InlineResponse201()); - - svnfmService.createVnf(createVnfRequest); + when(vnfmCacheRepository.createVnf(eq(createVnfRequest), anyString())).thenReturn(new InlineResponse201()); final String body = (new ObjectMapper()).valueToTree(createVnfRequest).toString(); this.mockMvc - .perform(post("/svnfm/vnf_instances").content(body).contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) + .perform(post(Constant.BASE_URL + "/vnf_instances").content(body) + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()).andExpect(content().contentType(MediaType.APPLICATION_JSON)); } } diff --git a/vnfm-simulator/vnfm-service/src/test/java/org/onap/svnfm/simulator/services/InstantiateOperatorProgressorTest.java b/vnfm-simulator/vnfm-service/src/test/java/org/onap/svnfm/simulator/services/InstantiateOperatorProgressorTest.java new file mode 100644 index 0000000000..ea6c6ef71a --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/test/java/org/onap/svnfm/simulator/services/InstantiateOperatorProgressorTest.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 Nokia. + * ================================================================================ + * 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.svnfm.simulator.services; + +import static org.assertj.core.api.Assertions.assertThat; +import java.util.ArrayList; +import java.util.List; +import org.junit.Before; +import org.junit.Test; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.model.GrantsAddResources; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.LccnSubscriptionRequest; +import org.onap.svnfm.simulator.config.ApplicationConfig; +import org.onap.svnfm.simulator.model.VnfOperation; +import org.onap.svnfm.simulator.model.Vnfds; +import org.onap.svnfm.simulator.model.Vnfds.Vnfc; +import org.onap.svnfm.simulator.model.Vnfds.Vnfd; + +public class InstantiateOperatorProgressorTest { + + private static final String VNF_ID = "vnfTestId"; + private static final String CALLBACK_URI = "/lcn/uritest"; + private static final String VNFC_TYPE = "COMPUTE"; + private static final String RESOURCE_TEMPLATE_ID = "resTempIdTest"; + private static final String VDU_ID = "vduIdTest"; + + private InstantiateOperationProgressor testedObject; + + @Before + public void setup() { + testedObject = new InstantiateOperationProgressor(new VnfOperation(), new SvnfmService(), null, + new ApplicationConfig(), createVnfds(), createSubscriptionService()); + } + + @Test + public void getAddResources_vnfIdFound() { + List<GrantsAddResources> result = testedObject.getAddResources(VNF_ID); + assertThat(result).hasSize(1); + GrantsAddResources grantsAddResourceResult = result.get(0); + assertThat(grantsAddResourceResult.getType()).hasToString(VNFC_TYPE); + assertThat(grantsAddResourceResult.getResourceTemplateId()).isEqualTo(RESOURCE_TEMPLATE_ID); + assertThat(grantsAddResourceResult.getVduId()).isEqualTo(VDU_ID); + } + + @Test + public void getAddResources_vnfIdNotFound() { + List<GrantsAddResources> result = testedObject.getAddResources("otherVnfId"); + assertThat(result).isEmpty(); + } + + private Vnfds createVnfds() { + Vnfd vnfd = new Vnfd(); + vnfd.setVnfdId(VNF_ID); + List<Vnfc> vnfcList = new ArrayList<>(); + vnfcList.add(createVnfc()); + vnfd.setVnfcList(vnfcList); + + List<Vnfd> vnfdList = new ArrayList<>(); + vnfdList.add(vnfd); + + Vnfds vnfds = new Vnfds(); + vnfds.setVnfdList(vnfdList); + return vnfds; + } + + private Vnfc createVnfc() { + Vnfc vnfc = new Vnfc(); + vnfc.setType(VNFC_TYPE); + vnfc.setResourceTemplateId(RESOURCE_TEMPLATE_ID); + vnfc.setVduId(VDU_ID); + return vnfc; + } + + private SubscriptionService createSubscriptionService() { + SubscriptionService subscriptionService = new SubscriptionService(); + LccnSubscriptionRequest lccnSubscriptionRequest = new LccnSubscriptionRequest(); + lccnSubscriptionRequest.setCallbackUri(CALLBACK_URI); + subscriptionService.registerSubscription(lccnSubscriptionRequest); + return subscriptionService; + } + +} |