diff options
148 files changed, 2231 insertions, 1508 deletions
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 8cacf8526a..47ba076e0e 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 @@ -132,14 +132,14 @@ public class MsoHeatEnvironmentEntry { } public boolean hasResources() { - if (this.resources != null && this.resources.size() > 0) { + if (this.resources != null && !this.resources.isEmpty()) { return true; } return false; } public boolean hasParameters() { - if (this.parameters != null && this.parameters.size() > 0) { + if (this.parameters != null && !this.parameters.isEmpty()) { return true; } return false; @@ -147,7 +147,7 @@ public class MsoHeatEnvironmentEntry { public boolean containsParameter(String paramName) { boolean contains = false; - if (this.parameters == null || this.parameters.size() < 1) { + if (this.parameters == null || this.parameters.isEmpty()) { return false; } if (this.parameters.contains(new MsoHeatEnvironmentParameter(paramName))) { @@ -246,22 +246,4 @@ public class MsoHeatEnvironmentEntry { sb.append(this.rawEntry.substring(indexOf)); return sb; } - - public void setHPAParameters(StringBuilder hpasb) { - try { - MsoYamlEditorWithEnvt yaml = new MsoYamlEditorWithEnvt(hpasb.toString().getBytes()); - Set<MsoHeatEnvironmentParameter> hpaParams = yaml.getParameterListFromEnvt(); - for (MsoHeatEnvironmentParameter hpaparam : hpaParams) { - for (MsoHeatEnvironmentParameter param : this.parameters) { - if (param.getName() == hpaparam.getName()) { - param.setValue(hpaparam.getValue()); - } - } - } - } catch (Exception e) { - logger.debug("Exception:", e); - this.errorString = e.getMessage(); - // e.printStackTrace(); - } - } } 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 49ba336e3f..c75aa9a67e 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 @@ -22,10 +22,6 @@ package org.onap.so.openstack.utils; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.woorea.openstack.heat.model.CreateStackParam; -import com.woorea.openstack.heat.model.Stack; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; @@ -52,7 +48,6 @@ import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.HeatStatus; import org.onap.so.openstack.beans.StackInfo; import org.onap.so.openstack.exceptions.MsoAdapterException; -import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.onap.so.openstack.mappers.StackInfoMapper; @@ -62,7 +57,11 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableSet; +import com.woorea.openstack.heat.model.CreateStackParam; +import com.woorea.openstack.heat.model.Stack; @Component public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { @@ -299,7 +298,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { responseBody = getQueryBody((java.io.InputStream) response.getEntity()); if (responseBody != null) { if (logger.isDebugEnabled()) { - logger.debug("Multicloud Create Response Body: " + responseBody.toString()); + logger.debug("Multicloud Create Response Body: {}", responseBody); } Stack workloadStack = getWorkloadStack(responseBody.getWorkloadStatusReason()); if (workloadStack != null && !responseBody.getWorkloadStatus().equals("GET_FAILED") @@ -354,7 +353,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { } } if (workloadStack != null) - logger.debug("Multicloud getWorkloadStack() returning Stack Object: {} ", workloadStack.toString()); + logger.debug("Multicloud getWorkloadStack() returning Stack Object: {} ", workloadStack); return workloadStack; } @@ -457,8 +456,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { Response response = multicloudClient.post(multicloudRequest); if (response.getStatus() != Response.Status.ACCEPTED.getStatusCode()) { if (logger.isDebugEnabled()) - logger.debug( - "Multicloud AAI update request failed: " + response.getStatus() + response.getStatusInfo()); + logger.debug("Multicloud AAI update request failed: {} {}", response.getStatus(), + response.getStatusInfo()); return; } @@ -470,14 +469,14 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { Integer.parseInt(this.environment.getProperty(createPollIntervalProp, CREATE_POLL_INTERVAL_DEFAULT)); int pollTimeout = (timeoutMinutes * 60) + updatePollInterval; boolean updateTimedOut = false; - logger.debug("updatePollInterval=" + updatePollInterval + ", pollTimeout=" + pollTimeout); + logger.debug("updatePollInterval={}, pollTimeout={}", updatePollInterval, pollTimeout); StackInfo stackInfo = null; while (true) { try { stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, workloadId); if (logger.isDebugEnabled()) - logger.debug(stackInfo.getStatus() + " (" + workloadId + ")"); + logger.debug("{} ({})", stackInfo.getStatus(), workloadId); if (HeatStatus.UPDATING.equals(stackInfo.getStatus())) { if (pollTimeout <= 0) { @@ -494,7 +493,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { pollTimeout -= updatePollInterval; if (logger.isDebugEnabled()) - logger.debug("pollTimeout remaining: " + pollTimeout); + logger.debug("pollTimeout remaining: {}", pollTimeout); } else { break; } @@ -508,15 +507,14 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { if (updateTimedOut) { if (logger.isDebugEnabled()) logger.debug("Multicloud AAI update request failed: {} {}", response.getStatus(), - response.getStatusInfo().toString()); + response.getStatusInfo()); } else if (!HeatStatus.UPDATED.equals(stackInfo.getStatus())) { if (logger.isDebugEnabled()) logger.debug("Multicloud AAI update request failed: {} {}", response.getStatus(), - response.getStatusInfo().toString()); + response.getStatusInfo()); } else { if (logger.isDebugEnabled()) - logger.debug("Multicloud AAI update successful: {} {}", response.getStatus(), - response.getStatusInfo().toString()); + logger.debug("Multicloud AAI update successful: {} {}", response.getStatus(), response.getStatusInfo()); } } @@ -543,12 +541,12 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { int deletePollTimeout = pollTimeout; boolean createTimedOut = false; StringBuilder stackErrorStatusReason = new StringBuilder(""); - logger.debug("createPollInterval=" + createPollInterval + ", pollTimeout=" + pollTimeout); + logger.debug("createPollInterval={}, pollTimeout={} ", createPollInterval, pollTimeout); while (true) { try { stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId); - logger.debug(stackInfo.getStatus() + " (" + instanceId + ")"); + logger.debug("{} ({})", stackInfo.getStatus(), instanceId); if (HeatStatus.BUILDING.equals(stackInfo.getStatus())) { // Stack creation is still running. @@ -567,7 +565,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { sleep(createPollInterval * 1000L); pollTimeout -= createPollInterval; - logger.debug("pollTimeout remaining: " + pollTimeout); + logger.debug("pollTimeout remaining: {}", pollTimeout); } else { // save off the status & reason msg before we attempt delete stackErrorStatusReason @@ -596,7 +594,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { while (!deleted) { try { StackInfo queryInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId); - logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus()); + logger.debug("Deleting {}, status: {}", instanceId, queryInfo.getStatus()); if (HeatStatus.DELETING.equals(queryInfo.getStatus())) { if (deletePollTimeout <= 0) { logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", @@ -610,7 +608,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { deletePollTimeout -= deletePollInterval; } } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())) { - logger.debug("DELETE_COMPLETE for " + instanceId); + logger.debug("DELETE_COMPLETE for {}", instanceId); deleted = true; continue; } else { @@ -664,7 +662,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { while (!deleted) { try { StackInfo queryInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId); - logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus()); + logger.debug("Deleting {}, status: {}", instanceId, queryInfo.getStatus()); if (HeatStatus.DELETING.equals(queryInfo.getStatus())) { if (deletePollTimeout <= 0) { logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", @@ -678,7 +676,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { deletePollTimeout -= deletePollInterval; } } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())) { - logger.debug("DELETE_COMPLETE for " + instanceId); + logger.debug("DELETE_COMPLETE for {}", instanceId); deleted = true; continue; } else { @@ -730,7 +728,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { } else { // Get initial status, since it will have been null after the create. stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId); - logger.debug("Multicloud stack query status is: " + stackInfo.getStatus()); + logger.debug("Multicloud stack query status is: {}", stackInfo.getStatus()); } return stackInfo; } @@ -769,7 +767,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { try { return new ObjectMapper().readerFor(MulticloudCreateResponse.class).readValue(body); } catch (Exception e) { - logger.debug("Exception retrieving multicloud vfModule POST response body " + e); + logger.debug("Exception retrieving multicloud vfModule POST response body ", e); } return null; } @@ -786,7 +784,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { try { return new ObjectMapper().readerFor(MulticloudQueryResponse.class).readValue(body); } catch (Exception e) { - logger.debug("Exception retrieving multicloud workload query response body " + e); + logger.debug("Exception retrieving multicloud workload query response body ", e); } return null; } @@ -828,14 +826,11 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { client.addAdditionalHeader("Project", tenantId); } } catch (MalformedURLException e) { - logger.debug( - String.format("Encountered malformed URL error getting multicloud rest client %s", e.getMessage())); + logger.debug("Encountered malformed URL error getting multicloud rest client ", e); } catch (IllegalArgumentException e) { - logger.debug( - String.format("Encountered illegal argument getting multicloud rest client %s", e.getMessage())); + logger.debug("Encountered illegal argument getting multicloud rest client ", e); } catch (UriBuilderException e) { - logger.debug( - String.format("Encountered URI builder error getting multicloud rest client %s", e.getMessage())); + logger.debug("Encountered URI builder error getting multicloud rest client ", e); } return client; } @@ -989,7 +984,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { // There are lots of HeatStatus values, so this is a bit long... HeatStatus heatStatus = stackInfo.getStatus(); String statusMessage = stackInfo.getStatusMessage(); - logger.debug("HeatStatus = " + heatStatus + " msg = " + statusMessage); + logger.debug("HeatStatus = {} msg = {}", heatStatus, statusMessage); if (logger.isDebugEnabled()) { logger.debug(String.format("Stack Status: %s", heatStatus.toString())); 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 069c6c7c5b..44fc620b07 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 @@ -130,13 +130,13 @@ public class MsoNeutronUtils extends MsoCommonUtils { network.setAdminStateUp(true); if (type == NetworkType.PROVIDER) { - if (provider != null && vlans != null && vlans.size() > 0) { + if (provider != null && vlans != null && !vlans.isEmpty()) { network.setProviderPhysicalNetwork(provider); network.setProviderNetworkType("vlan"); network.setProviderSegmentationId(vlans.get(0)); } } else if (type == NetworkType.MULTI_PROVIDER) { - if (provider != null && vlans != null && vlans.size() > 0) { + if (provider != null && vlans != null && !vlans.isEmpty()) { List<Segment> segments = new ArrayList<>(vlans.size()); for (int vlan : vlans) { Segment segment = new Segment(); 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 ad37b39f30..c575304ade 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 @@ -40,7 +40,7 @@ public class MulticloudQueryResponse implements Serializable { @JsonProperty("workload_status") private String workloadStatus; @JsonProperty("workload_status_reason") - private JsonNode workloadStatusReason; + private transient JsonNode workloadStatusReason; @JsonCreator public MulticloudQueryResponse(@JsonProperty("template_type") String templateType, 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 79aad1ad1a..b43447f5c4 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 @@ -25,6 +25,7 @@ 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.adapters.catalogdb.rest.VnfRestImpl; import org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging; import org.springframework.context.annotation.Configuration; import io.swagger.jaxrs.config.BeanConfig; @@ -42,6 +43,7 @@ public class JerseyConfiguration extends ResourceConfig { register(SwaggerSerializers.class); register(JaxRsFilterLogging.class); register(ServiceRestImpl.class); + register(VnfRestImpl.class); BeanConfig beanConfig = new BeanConfig(); beanConfig.setVersion("1.0.2"); beanConfig.setSchemes(new String[] {"https"}); diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundException.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundException.java new file mode 100644 index 0000000000..f8a7ba6da4 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundException.java @@ -0,0 +1,14 @@ +package org.onap.so.adapters.catalogdb.rest; + +public class CatalogEntityNotFoundException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = -300157844846680791L; + + public CatalogEntityNotFoundException(String errorMessage) { + super(errorMessage); + } + +} diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundExceptionMapper.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundExceptionMapper.java new file mode 100644 index 0000000000..c42eaabea7 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundExceptionMapper.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.catalogdb.rest; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Provider +public class CatalogEntityNotFoundExceptionMapper implements ExceptionMapper<CatalogEntityNotFoundException> { + + private static final Logger logger = LoggerFactory.getLogger(CatalogEntityNotFoundExceptionMapper.class); + + @Override + public Response toResponse(CatalogEntityNotFoundException e) { + return Response.status(Response.Status.NOT_FOUND).entity(e).build(); + } +} 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 index dd18767762..e74663dbba 100644 --- 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 @@ -22,9 +22,11 @@ package org.onap.so.adapters.catalogdb.rest; import java.util.ArrayList; import java.util.List; +import org.onap.so.db.catalog.beans.CvnfcCustomization; 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.Cvnfc; import org.onap.so.rest.catalog.beans.Service; import org.onap.so.rest.catalog.beans.VfModule; import org.onap.so.rest.catalog.beans.Vnf; @@ -39,16 +41,23 @@ public class ServiceMapper { public Service mapService(org.onap.so.db.catalog.beans.Service service, int depth) { Service restService = new Service(); - restService.setCategory(service.getCategory()); + if (service.getCategory() != null) { + restService.setCategory(service.getCategory()); + } restService.setCreated(service.getCreated()); restService.setDescription(service.getDescription()); - restService.setDistrobutionStatus(service.getDistrobutionStatus()); + + if (service.getDistrobutionStatus() != null) { + 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()); + if (service.getServiceRole() != null) { + restService.setServiceRole(service.getServiceRole()); + } restService.setServiceType(service.getServiceType()); restService.setWorkloadContext(service.getWorkloadContext()); if (depth > 0) @@ -63,7 +72,7 @@ public class ServiceMapper { return vnfs; } - private Vnf mapVnf(org.onap.so.db.catalog.beans.VnfResourceCustomization vnfResourceCustomization, int depth) { + protected 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()); @@ -81,9 +90,12 @@ public class ServiceMapper { vnf.setNfFunction(vnfResourceCustomization.getNfFunction()); vnf.setNfNamingCode(vnfResourceCustomization.getNfNamingCode()); vnf.setNfRole(vnfResourceCustomization.getNfRole()); + vnf.setNfType(vnfResourceCustomization.getNfType()); + vnf.setNfDataValid(vnfResourceCustomization.getNfDataValid()); vnf.setOrchestrationMode(vnfResourceCustomization.getVnfResources().getOrchestrationMode()); vnf.setSubCategory(vnfResourceCustomization.getVnfResources().getSubCategory()); vnf.setToscaNodeType(vnfResourceCustomization.getVnfResources().getToscaNodeType()); + if (depth > 1) { vnf.setVfModule(mapVfModules(vnfResourceCustomization, depth)); } @@ -93,11 +105,11 @@ public class ServiceMapper { private List<VfModule> mapVfModules(VnfResourceCustomization vnfResourceCustomization, int depth) { List<VfModule> vfModules = new ArrayList<>(); vnfResourceCustomization.getVfModuleCustomizations().parallelStream() - .forEach(vfModule -> vfModules.add(mapVfModule(vfModule))); + .forEach(vfModule -> vfModules.add(mapVfModule(vfModule, depth))); return vfModules; } - private VfModule mapVfModule(VfModuleCustomization vfModuleCust) { + private VfModule mapVfModule(VfModuleCustomization vfModuleCust, int depth) { VfModule vfModule = new VfModule(); vfModule.setAvailabilityZoneCount(vfModuleCust.getAvailabilityZoneCount()); vfModule.setCreated(vfModuleCust.getCreated()); @@ -113,9 +125,34 @@ public class ServiceMapper { vfModule.setModelName(vfModuleCust.getVfModule().getModelName()); vfModule.setModelVersionId(vfModuleCust.getVfModule().getModelUUID()); vfModule.setModelVersion(vfModuleCust.getVfModule().getModelVersion()); + if (depth > 3) { + vfModule.setVnfc(mapCvnfcs(vfModuleCust)); + } return vfModule; } + private List<Cvnfc> mapCvnfcs(VfModuleCustomization vfModuleCustomization) { + List<Cvnfc> cvnfcs = new ArrayList<>(); + vfModuleCustomization.getCvnfcCustomization().parallelStream() + .forEach(cvnfcCust -> cvnfcs.add(mapCvnfcCus(cvnfcCust))); + return cvnfcs; + } + + private Cvnfc mapCvnfcCus(CvnfcCustomization cvnfcCust) { + Cvnfc cvnfc = new Cvnfc(); + cvnfc.setCreated(cvnfcCust.getCreated()); + cvnfc.setDescription(cvnfcCust.getDescription()); + cvnfc.setModelCustomizationId(cvnfcCust.getModelCustomizationUUID()); + cvnfc.setModelInstanceName(cvnfcCust.getModelInstanceName()); + cvnfc.setModelInvariantId(cvnfcCust.getModelInvariantUUID()); + cvnfc.setModelName(cvnfcCust.getModelName()); + cvnfc.setModelVersion(cvnfcCust.getModelVersion()); + cvnfc.setModelVersionId(cvnfcCust.getModelUUID()); + cvnfc.setNfcFunction(cvnfcCust.getNfcFunction()); + cvnfc.setNfcNamingCode(cvnfcCust.getNfcNamingCode()); + return cvnfc; + } + private boolean getIsVolumeGroup(VfModuleCustomization vfModuleCust) { boolean isVolumeGroup = false; HeatEnvironment envt = vfModuleCust.getVolumeHeatEnv(); 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 index 520de4d38c..6f556edfa1 100644 --- 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 @@ -38,7 +38,7 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; -@Api(value = "/v1/services", tags = "model") +@Api(value = "/v1", tags = "model") @Path("/v1/services") @Component public class ServiceRestImpl { @@ -49,18 +49,21 @@ public class ServiceRestImpl { @Autowired private ServiceMapper serviceMapper; + @GET @Path("/{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); + if (service == null) { + new CatalogEntityNotFoundException("Unable to find Service " + modelUUID); + } return serviceMapper.mapService(service, depth); } @GET - @ApiOperation(value = "Find Service Models", response = Service.class, responseContainer = "List", - notes = "If no query parameters are sent an empty list will be returned") + @ApiOperation(value = "Find Service Models", response = Service.class, responseContainer = "List") @Produces({MediaType.APPLICATION_JSON}) @Transactional(readOnly = true) public List<Service> queryServices( @@ -74,6 +77,8 @@ public class ServiceRestImpl { serviceFromDB = serviceRepo.findByModelNameAndDistrobutionStatus(modelName, distributionStatus); } else if (!Strings.isNullOrEmpty(modelName)) { serviceFromDB = serviceRepo.findByModelName(modelName); + } else { + serviceFromDB = serviceRepo.findAll(); } serviceFromDB.stream().forEach(serviceDB -> services.add(serviceMapper.mapService(serviceDB, depth))); return services; diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfMapper.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfMapper.java new file mode 100644 index 0000000000..52a8ccb5a7 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfMapper.java @@ -0,0 +1,37 @@ +package org.onap.so.adapters.catalogdb.rest; + +import org.onap.so.db.catalog.beans.VnfResource; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.rest.catalog.beans.Vnf; +import org.springframework.stereotype.Component; +import com.google.common.base.Strings; + +@Component +public class VnfMapper { + + public VnfResourceCustomization mapVnf(VnfResourceCustomization vnfCust, Vnf vnf) { + + vnfCust.setAvailabilityZoneMaxCount(vnf.getAvailabilityZoneMaxCount()); + vnfCust.setMaxInstances(vnf.getMaxInstances()); + vnfCust.setMinInstances(vnf.getMinInstances()); + vnfCust.setModelCustomizationUUID(vnf.getModelCustomizationId()); + vnfCust.setModelInstanceName(vnf.getModelInstanceName()); + vnfCust.setMultiStageDesign(vnf.getMultiStageDesign()); + vnfCust.setNfDataValid(vnf.getNfDataValid()); + vnfCust.setNfFunction(Strings.nullToEmpty(vnf.getNfFunction())); + vnfCust.setNfNamingCode(Strings.nullToEmpty(vnf.getNfNamingCode())); + vnfCust.setNfRole(Strings.nullToEmpty(vnf.getNfRole())); + vnfCust.setNfType(Strings.nullToEmpty(vnf.getNfType())); + + VnfResource vnfRes = vnfCust.getVnfResources(); + vnfRes.setOrchestrationMode(Strings.nullToEmpty(vnfRes.getOrchestrationMode())); + vnfRes.setSubCategory(Strings.nullToEmpty(vnfRes.getSubCategory())); + vnfRes.setToscaNodeType(Strings.nullToEmpty(vnfRes.getToscaNodeType())); + vnfRes.setModelInvariantUUID(vnfRes.getModelInvariantId()); + vnfRes.setModelName(vnfRes.getModelName()); + vnfRes.setModelUUID(vnfRes.getModelUUID()); + vnfRes.setModelVersion(vnfRes.getModelVersion()); + return vnfCust; + } + +} diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfRestImpl.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfRestImpl.java new file mode 100644 index 0000000000..4353526872 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfRestImpl.java @@ -0,0 +1,107 @@ +/*- + * ============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.List; +import java.util.stream.Collectors; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.db.catalog.data.repository.ServiceRepository; +import org.onap.so.db.catalog.data.repository.VnfCustomizationRepository; +import org.onap.so.rest.catalog.beans.Vnf; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Api(value = "/v1/services/{modelUUID}/vnfs", tags = "model") +@Path("/v1/services/{modelUUID}/vnfs") +@Component +public class VnfRestImpl { + + @Autowired + private ServiceRepository serviceRepo; + + @Autowired + private ServiceMapper serviceMapper; + + @Autowired + private VnfMapper vnfMapper; + + @Autowired + private VnfCustomizationRepository vnfCustRepo; + + @GET + @ApiOperation(value = "Find a VNF model contained within a service", response = Vnf.class) + @Path("/{modelCustomizationUUID}") + @Produces({MediaType.APPLICATION_JSON}) + @Transactional(readOnly = true) + public Vnf findService(@PathParam("modelUUID") String serviceModelUUID, + @PathParam("modelCustomizationUUID") String modelCustomizationUUID, @QueryParam("depth") int depth) { + org.onap.so.db.catalog.beans.Service service = serviceRepo.findOneByModelUUID(serviceModelUUID); + if (service.getVnfCustomizations() == null || service.getVnfCustomizations().isEmpty()) { + throw new WebApplicationException("Vnf Not Found", 404); + } + List<VnfResourceCustomization> vnfCustom = service.getVnfCustomizations().stream() + .filter(vnfCust -> vnfCust.getModelCustomizationUUID().equals(modelCustomizationUUID)) + .collect(Collectors.toList()); + if (vnfCustom.isEmpty() || vnfCustom == null) { + return null; + } else if (vnfCustom.size() > 1) { + throw new RuntimeException( + "More than one Vnf model returned with model Customization UUID: " + modelCustomizationUUID); + } + return serviceMapper.mapVnf(vnfCustom.get(0), depth); + } + + @PUT + @ApiOperation(value = "Update a VNF model contained within a service", response = Vnf.class) + @Path("/{modelCustomizationUUID}") + @Produces({MediaType.APPLICATION_JSON}) + @Transactional + public Response findService(@PathParam("modelUUID") String serviceModelUUID, + @PathParam("modelCustomizationUUID") String modelCustomizationUUID, Vnf vnf) { + org.onap.so.db.catalog.beans.Service service = serviceRepo.findOneByModelUUID(serviceModelUUID); + List<VnfResourceCustomization> vnfCustom = service.getVnfCustomizations().stream() + .filter(vnfCust -> vnfCust.getModelCustomizationUUID().equals(modelCustomizationUUID)) + .collect(Collectors.toList()); + if (vnfCustom.isEmpty() || vnfCustom == null) { + throw new RuntimeException("No Vnf Found"); + } else if (vnfCustom.size() > 1) { + throw new RuntimeException( + "More than one Vnf model returned with model Customization UUID: " + modelCustomizationUUID); + } + VnfResourceCustomization vnfCust = vnfMapper.mapVnf(vnfCustom.get(0), vnf); + vnfCustRepo.save(vnfCust); + return Response.ok().build(); + } + +} + diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.2__AddNfValidData.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.2__AddNfValidData.sql new file mode 100644 index 0000000000..93dde1341e --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.2__AddNfValidData.sql @@ -0,0 +1,5 @@ +USE catalogdb; + +ALTER TABLE vnf_resource_customization +ADD IF NOT EXISTS NF_DATA_VALID tinyint(1) DEFAULT 0; + diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java index 8decd77656..d46fd9c7ba 100644 --- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java @@ -67,6 +67,7 @@ public class ServiceMapperTest { testService.setModelVersion("modelVersion"); testService.setServiceType("serviceType"); testService.setServiceRole("serviceRole"); + testService.getVnfCustomizations().add(getTestVnfCustomization()); return testService; } 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 a955a2c3ce..f82c7acd38 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 @@ -22,15 +22,14 @@ package org.onap.so.db.catalog.client; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.List; import java.util.UUID; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.so.adapters.catalogdb.CatalogDBApplication; import org.onap.so.adapters.catalogdb.CatalogDbAdapterBaseTest; import org.onap.so.db.catalog.beans.AuthenticationType; import org.onap.so.db.catalog.beans.CloudIdentity; @@ -56,10 +55,7 @@ import org.onap.so.db.catalog.beans.macro.NorthBoundRequest; import org.onap.so.db.catalog.beans.macro.RainyDayHandlerStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @@ -74,6 +70,8 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @Autowired CatalogDbClientPortChanger client; + + @Before public void initialize() { client.wiremockPort = String.valueOf(port); @@ -88,7 +86,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { public void testGetRainyDayHandler_Regex() { RainyDayHandlerStatus rainyDayHandlerStatus = client.getRainyDayHandlerStatus("AssignServiceInstanceBB", "*", "*", "*", "*", "The Flavor ID (nd.c6r16d20) could not be found.", "*"); - Assert.assertEquals("Rollback", rainyDayHandlerStatus.getPolicy()); + assertEquals("Rollback", rainyDayHandlerStatus.getPolicy()); } @Test @@ -97,105 +95,105 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { "*", "*", "*", "resources.lba_0_dmz_vmi_0: Unknown id: Error: oper 1 url /fqname-to-id body {\"fq_name\": [\"zrdm6bvota05-dmz_sec_group\"], \"type\": \"security-group\"} response Name ['zrdm6bvota05-dmz_sec_group'] not found", "*"); - Assert.assertEquals("Rollback", rainyDayHandlerStatus.getPolicy()); + assertEquals("Rollback", rainyDayHandlerStatus.getPolicy()); } @Test public void testGetCloudSiteHappyPath() throws Exception { CloudSite cloudSite = client.getCloudSite(MTN13); - Assert.assertNotNull(cloudSite); - Assert.assertNotNull(cloudSite.getIdentityService()); - Assert.assertEquals("MDT13", cloudSite.getClli()); - Assert.assertEquals("mtn13", cloudSite.getRegionId()); - Assert.assertEquals("MTN13", cloudSite.getIdentityServiceId()); + assertNotNull(cloudSite); + assertNotNull(cloudSite.getIdentityService()); + assertEquals("MDT13", cloudSite.getClli()); + assertEquals("mtn13", cloudSite.getRegionId()); + assertEquals("MTN13", cloudSite.getIdentityServiceId()); } @Test public void testGetCloudSiteNotFound() throws Exception { CloudSite cloudSite = client.getCloudSite(UUID.randomUUID().toString()); - Assert.assertNull(cloudSite); + assertNull(cloudSite); } @Test public void testGetCloudifyManagerHappyPath() throws Exception { CloudifyManager cloudifyManager = client.getCloudifyManager("mtn13"); - Assert.assertNotNull(cloudifyManager); - Assert.assertEquals("http://localhost:28090/v2.0", cloudifyManager.getCloudifyUrl()); + assertNotNull(cloudifyManager); + assertEquals("http://localhost:28090/v2.0", cloudifyManager.getCloudifyUrl()); } @Test public void testGetCloudifyManagerNotFound() throws Exception { CloudifyManager cloudifyManager = client.getCloudifyManager(UUID.randomUUID().toString()); - Assert.assertNull(cloudifyManager); + assertNull(cloudifyManager); } @Test public void testGetCloudSiteByClliAndAicVersionHappyPath() throws Exception { CloudSite cloudSite = client.getCloudSiteByClliAndAicVersion("MDT13", "2.5"); - Assert.assertNotNull(cloudSite); + assertNotNull(cloudSite); } @Test public void testGetCloudSiteByClliAndAicVersionNotFound() throws Exception { CloudSite cloudSite = client.getCloudSiteByClliAndAicVersion("MDT13", "232496239746328"); - Assert.assertNull(cloudSite); + assertNull(cloudSite); } @Test public void testGetServiceByID() throws Exception { Service serviceByID = client.getServiceByID("5df8b6de-2083-11e7-93ae-92361f002671"); - Assert.assertNotNull(serviceByID); - Assert.assertEquals("MSOTADevInfra_vSAMP10a_Service", serviceByID.getModelName()); - Assert.assertEquals("NA", serviceByID.getServiceType()); - Assert.assertEquals("NA", serviceByID.getServiceRole()); + assertNotNull(serviceByID); + assertEquals("MSOTADevInfra_vSAMP10a_Service", serviceByID.getModelName()); + assertEquals("NA", serviceByID.getServiceType()); + assertEquals("NA", serviceByID.getServiceRole()); } @Test public void testGetServiceByIDNotFound() throws Exception { Service serviceByID = client.getServiceByID(UUID.randomUUID().toString()); - Assert.assertNull(serviceByID); + assertNull(serviceByID); } @Test public void testGetVfModuleByModelUUID() throws Exception { VfModule vfModule = client.getVfModuleByModelUUID("20c4431c-246d-11e7-93ae-92361f002671"); - Assert.assertNotNull(vfModule); - Assert.assertNotNull(vfModule.getVfModuleCustomization()); - Assert.assertEquals("78ca26d0-246d-11e7-93ae-92361f002671", vfModule.getModelInvariantUUID()); - Assert.assertEquals("vSAMP10aDEV::base::module-0", vfModule.getModelName()); + assertNotNull(vfModule); + assertNotNull(vfModule.getVfModuleCustomization()); + assertEquals("78ca26d0-246d-11e7-93ae-92361f002671", vfModule.getModelInvariantUUID()); + assertEquals("vSAMP10aDEV::base::module-0", vfModule.getModelName()); } @Test public void testGetVfModuleByModelUUIDNotFound() throws Exception { VfModule vfModule = client.getVfModuleByModelUUID(UUID.randomUUID().toString()); - Assert.assertNull(vfModule); + assertNull(vfModule); } @Test public void testGetVnfResourceByModelUUID() throws Exception { VnfResource vnfResource = client.getVnfResourceByModelUUID("ff2ae348-214a-11e7-93ae-92361f002671"); - Assert.assertNotNull(vnfResource); - Assert.assertEquals("vSAMP10a", vnfResource.getModelName()); + assertNotNull(vnfResource); + assertEquals("vSAMP10a", vnfResource.getModelName()); } @Test public void testGetVnfResourceByModelUUIDNotFound() throws Exception { VnfResource vnfResource = client.getVnfResourceByModelUUID(UUID.randomUUID().toString()); - Assert.assertNull(vnfResource); + assertNull(vnfResource); } @Test public void testGetVnfResourceCustomizationByModelCustomizationUUID() { VnfResourceCustomization vnfResourceCustomization = client.getVnfResourceCustomizationByModelCustomizationUUID("68dc9a92-214c-11e7-93ae-92361f002671"); - Assert.assertNotNull(vnfResourceCustomization); - Assert.assertEquals("vSAMP", vnfResourceCustomization.getNfRole()); - Assert.assertNotNull(vnfResourceCustomization.getModelCustomizationUUID()); - Assert.assertNotNull(vnfResourceCustomization.getVnfResources()); - Assert.assertNotNull(vnfResourceCustomization.getVfModuleCustomizations()); - Assert.assertEquals("vSAMP10a", vnfResourceCustomization.getVnfResources().getModelName()); + assertNotNull(vnfResourceCustomization); + assertEquals("vSAMP", vnfResourceCustomization.getNfRole()); + assertNotNull(vnfResourceCustomization.getModelCustomizationUUID()); + assertNotNull(vnfResourceCustomization.getVnfResources()); + assertNotNull(vnfResourceCustomization.getVfModuleCustomizations()); + assertEquals("vSAMP10a", vnfResourceCustomization.getVnfResources().getModelName()); assertTrue("skip post instantiation configuration", vnfResourceCustomization.isSkipPostInstConf()); } @@ -203,15 +201,15 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { public void testGetVnfResourceCustomizationByModelCustomizationUUINotFound() { VnfResourceCustomization vnfResourceCustomization = client.getVnfResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString()); - Assert.assertNull(vnfResourceCustomization); + assertNull(vnfResourceCustomization); } @Test public void testGetInstanceGroupByModelUUID() { InstanceGroup instanceGroup = client.getInstanceGroupByModelUUID("0c8692ef-b9c0-435d-a738-edf31e71f38b"); - Assert.assertNotNull(instanceGroup); - Assert.assertEquals("network_collection_resource_1806..NetworkCollection..0", instanceGroup.getModelName()); - Assert.assertEquals("org.openecomp.resource.cr.NetworkCollectionResource1806", + assertNotNull(instanceGroup); + assertEquals("network_collection_resource_1806..NetworkCollection..0", instanceGroup.getModelName()); + assertEquals("org.openecomp.resource.cr.NetworkCollectionResource1806", instanceGroup.getToscaNodeType().toString()); } @@ -219,33 +217,33 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { public void testGetVfModuleCustomizationByModelCuztomizationUUID() { VfModuleCustomization vfModuleCustomization = client.getVfModuleCustomizationByModelCuztomizationUUID("cb82ffd8-252a-11e7-93ae-92361f002671"); - Assert.assertNotNull(vfModuleCustomization); - Assert.assertNotNull(vfModuleCustomization.getModelCustomizationUUID()); - Assert.assertEquals("base", vfModuleCustomization.getLabel()); + assertNotNull(vfModuleCustomization); + assertNotNull(vfModuleCustomization.getModelCustomizationUUID()); + assertEquals("base", vfModuleCustomization.getLabel()); } @Test public void testGetVfModuleCustomizationByModelCuztomizationUUIDNotFound() { VfModuleCustomization vfModuleCustomization = client.getVfModuleCustomizationByModelCuztomizationUUID(UUID.randomUUID().toString()); - Assert.assertNull(vfModuleCustomization); + assertNull(vfModuleCustomization); } @Test public void testGetNetworkResourceCustomizationByModelCustomizationUUID() { NetworkResourceCustomization networkResourceCustomization = client.getNetworkResourceCustomizationByModelCustomizationUUID("3bdbb104-476c-483e-9f8b-c095b3d308ac"); - Assert.assertNotNull(networkResourceCustomization); - Assert.assertNotNull(networkResourceCustomization.getModelCustomizationUUID()); - Assert.assertEquals("CONTRAIL30_GNDIRECT 9", networkResourceCustomization.getModelInstanceName()); - Assert.assertNotNull(networkResourceCustomization.getNetworkResource()); + assertNotNull(networkResourceCustomization); + assertNotNull(networkResourceCustomization.getModelCustomizationUUID()); + assertEquals("CONTRAIL30_GNDIRECT 9", networkResourceCustomization.getModelInstanceName()); + assertNotNull(networkResourceCustomization.getNetworkResource()); } @Test public void testGetNetworkResourceCustomizationByModelCustomizationUUIDNotFound() { NetworkResourceCustomization networkResourceCustomization = client.getNetworkResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString()); - Assert.assertNull(networkResourceCustomization); + assertNull(networkResourceCustomization); } @Test @@ -253,10 +251,10 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { VfModuleCustomization vfModuleCustomization = client.getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID( "cb82ffd8-252a-11e7-93ae-92361f002672", "20c4431c-246d-11e7-93ae-92361f002672"); - Assert.assertNotNull(vfModuleCustomization); - Assert.assertNotNull(vfModuleCustomization.getModelCustomizationUUID()); - Assert.assertNotNull(vfModuleCustomization.getVfModule()); - Assert.assertEquals("base", vfModuleCustomization.getLabel()); + assertNotNull(vfModuleCustomization); + assertNotNull(vfModuleCustomization.getModelCustomizationUUID()); + assertNotNull(vfModuleCustomization.getVfModule()); + assertEquals("base", vfModuleCustomization.getLabel()); } @Test @@ -264,44 +262,43 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { VfModuleCustomization vfModuleCustomization = client.getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID( "cb82ffd8-252a-11e7-93ae-92361f002672", UUID.randomUUID().toString()); - Assert.assertNull(vfModuleCustomization); + assertNull(vfModuleCustomization); } @Test public void testGetFirstByServiceModelUUIDAndAction() { ServiceRecipe serviceRecipe = client.getFirstByServiceModelUUIDAndAction("4694a55f-58b3-4f17-92a5-796d6f5ffd0d", "createInstance"); - Assert.assertNotNull(serviceRecipe); - Assert.assertNotNull(serviceRecipe.getServiceModelUUID()); - Assert.assertNotNull(serviceRecipe.getAction()); - Assert.assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance", - serviceRecipe.getOrchestrationUri()); - Assert.assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription()); + assertNotNull(serviceRecipe); + assertNotNull(serviceRecipe.getServiceModelUUID()); + assertNotNull(serviceRecipe.getAction()); + assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance", serviceRecipe.getOrchestrationUri()); + assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription()); } @Test public void testGetFirstByServiceModelUUIDAndActionNotFound() { ServiceRecipe serviceRecipe = client.getFirstByServiceModelUUIDAndAction("5df8b6de-2083-11e7-93ae-92361f002671", UUID.randomUUID().toString()); - Assert.assertNull(serviceRecipe); + assertNull(serviceRecipe); } @Test public void testGetFirstVnfResourceByModelInvariantUUIDAndModelVersion() { VnfResource vnfResource = client .getFirstVnfResourceByModelInvariantUUIDAndModelVersion("2fff5b20-214b-11e7-93ae-92361f002671", "2.0"); - Assert.assertNotNull(vnfResource); - Assert.assertNotNull(vnfResource.getModelInvariantId()); - Assert.assertNotNull(vnfResource.getModelVersion()); - Assert.assertNotNull(vnfResource.getHeatTemplates()); - Assert.assertEquals("vSAMP10a", vnfResource.getModelName()); + assertNotNull(vnfResource); + assertNotNull(vnfResource.getModelInvariantId()); + assertNotNull(vnfResource.getModelVersion()); + assertNotNull(vnfResource.getHeatTemplates()); + assertEquals("vSAMP10a", vnfResource.getModelName()); } @Test public void testGetFirstVnfResourceByModelInvariantUUIDAndModelVersionNotFound() { VnfResource vnfResource = client.getFirstVnfResourceByModelInvariantUUIDAndModelVersion( "2fff5b20-214b-11e7-93ae-92361f002671", UUID.randomUUID().toString()); - Assert.assertNull(vnfResource); + assertNull(vnfResource); } @Test @@ -310,29 +307,28 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { vnfr.setModelUUID("ff2ae348-214a-11e7-93ae-92361f002671"); VnfResourceCustomization firstVnfResourceCustomizationByModelInstanceNameAndVnfResources = client.getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources("vSAMP10a 1", vnfr); - Assert.assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources); - Assert.assertEquals("vSAMP", firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getNfRole()); - Assert.assertEquals("vSAMP10a 1", + assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources); + assertEquals("vSAMP", firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getNfRole()); + assertEquals("vSAMP10a 1", firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getModelInstanceName()); - Assert.assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVnfResources()); - Assert.assertNotNull( - firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVfModuleCustomizations()); + assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVnfResources()); + assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVfModuleCustomizations()); } @Test public void testGetFirstVnfRecipeByNfRoleAndAction() { VnfRecipe vnfRecipe = client.getFirstVnfRecipeByNfRoleAndAction("GR-API-DEFAULT", "createInstance"); - Assert.assertNotNull(vnfRecipe); - Assert.assertNotNull(vnfRecipe.getNfRole()); - Assert.assertNotNull(vnfRecipe.getAction()); - Assert.assertEquals("Gr api recipe to create vnf", vnfRecipe.getDescription()); - Assert.assertEquals("/mso/async/services/WorkflowActionBB", vnfRecipe.getOrchestrationUri()); + assertNotNull(vnfRecipe); + assertNotNull(vnfRecipe.getNfRole()); + assertNotNull(vnfRecipe.getAction()); + assertEquals("Gr api recipe to create vnf", vnfRecipe.getDescription()); + assertEquals("/mso/async/services/WorkflowActionBB", vnfRecipe.getOrchestrationUri()); } @Test public void testGetFirstVnfRecipeByNfRoleAndActionNotFound() { VnfRecipe vnfRecipe = client.getFirstVnfRecipeByNfRoleAndAction(UUID.randomUUID().toString(), "createInstance"); - Assert.assertNull(vnfRecipe); + assertNull(vnfRecipe); } @Test @@ -340,12 +336,12 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { VnfComponentsRecipe vnfComponentsRecipe = client.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction( "20c4431c-246d-11e7-93ae-92361f002671", "volumeGroup", "createInstance"); - Assert.assertNotNull(vnfComponentsRecipe); - Assert.assertNotNull(vnfComponentsRecipe.getAction()); - Assert.assertNotNull(vnfComponentsRecipe.getVfModuleModelUUID()); - Assert.assertNotNull(vnfComponentsRecipe.getVnfComponentType()); - Assert.assertEquals("Gr api recipe to create volume-group", vnfComponentsRecipe.getDescription()); - Assert.assertEquals("/mso/async/services/WorkflowActionBB", vnfComponentsRecipe.getOrchestrationUri()); + assertNotNull(vnfComponentsRecipe); + assertNotNull(vnfComponentsRecipe.getAction()); + assertNotNull(vnfComponentsRecipe.getVfModuleModelUUID()); + assertNotNull(vnfComponentsRecipe.getVnfComponentType()); + assertEquals("Gr api recipe to create volume-group", vnfComponentsRecipe.getDescription()); + assertEquals("/mso/async/services/WorkflowActionBB", vnfComponentsRecipe.getOrchestrationUri()); } @@ -355,80 +351,79 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { VnfComponentsRecipe vnfComponentsRecipe = client.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction( UUID.randomUUID().toString(), "volumeGroup", "createInstance"); - Assert.assertNull(vnfComponentsRecipe); + assertNull(vnfComponentsRecipe); } @Test public void testGetFirstVnfComponentsRecipeByVnfComponentTypeAndAction() { VnfComponentsRecipe vnfComponentsRecipe = client.getFirstVnfComponentsRecipeByVnfComponentTypeAndAction("volumeGroup", "createInstance"); - Assert.assertNotNull(vnfComponentsRecipe); - Assert.assertNotNull(vnfComponentsRecipe.getAction()); - Assert.assertNotNull(vnfComponentsRecipe.getVnfComponentType()); - Assert.assertEquals("VID_DEFAULT recipe t", vnfComponentsRecipe.getDescription()); - Assert.assertEquals("/mso/async/services/CreateVfModuleVolumeInfraV1", - vnfComponentsRecipe.getOrchestrationUri()); + assertNotNull(vnfComponentsRecipe); + assertNotNull(vnfComponentsRecipe.getAction()); + assertNotNull(vnfComponentsRecipe.getVnfComponentType()); + assertEquals("VID_DEFAULT recipe t", vnfComponentsRecipe.getDescription()); + assertEquals("/mso/async/services/CreateVfModuleVolumeInfraV1", vnfComponentsRecipe.getOrchestrationUri()); } @Test public void testGetServiceByModelVersionAndModelInvariantUUID() { Service service = client.getServiceByModelVersionAndModelInvariantUUID("2.0", "9647dfc4-2083-11e7-93ae-92361f002671"); - Assert.assertNotNull(service); - Assert.assertNotNull(service.getModelVersion()); - Assert.assertNotNull(service.getModelInvariantUUID()); - Assert.assertEquals("MSOTADevInfra_vSAMP10a_Service", service.getModelName()); - Assert.assertEquals("NA", service.getServiceRole()); + assertNotNull(service); + assertNotNull(service.getModelVersion()); + assertNotNull(service.getModelInvariantUUID()); + assertEquals("MSOTADevInfra_vSAMP10a_Service", service.getModelName()); + assertEquals("NA", service.getServiceRole()); } @Test public void testGetServiceByModelVersionAndModelInvariantUUIDNotFound() { Service service = client.getServiceByModelVersionAndModelInvariantUUID("2.0", UUID.randomUUID().toString()); - Assert.assertNull(service); + assertNull(service); } @Test public void testGetVfModuleByModelInvariantUUIDAndModelVersion() { VfModule vfModule = client.getVfModuleByModelInvariantUUIDAndModelVersion("78ca26d0-246d-11e7-93ae-92361f002671", "2"); - Assert.assertNotNull(vfModule); - Assert.assertNotNull(vfModule.getModelVersion()); - Assert.assertNotNull(vfModule.getModelInvariantUUID()); - Assert.assertEquals("vSAMP10aDEV::base::module-0", vfModule.getModelName()); - Assert.assertEquals("vSAMP10a DEV Base", vfModule.getDescription()); + assertNotNull(vfModule); + assertNotNull(vfModule.getModelVersion()); + assertNotNull(vfModule.getModelInvariantUUID()); + assertEquals("vSAMP10aDEV::base::module-0", vfModule.getModelName()); + assertEquals("vSAMP10a DEV Base", vfModule.getDescription()); } @Test public void testGetVfModuleByModelInvariantUUIDAndModelVersionNotFound() { VfModule vfModule = client.getVfModuleByModelInvariantUUIDAndModelVersion(UUID.randomUUID().toString(), "2"); - Assert.assertNull(vfModule); + assertNull(vfModule); } @Test public void testGetServiceByModelInvariantUUIDOrderByModelVersionDesc() { List<Service> serviceList = client.getServiceByModelInvariantUUIDOrderByModelVersionDesc("9647dfc4-2083-11e7-93ae-92361f002671"); - Assert.assertFalse(serviceList.isEmpty()); - Assert.assertEquals(2, serviceList.size()); + assertFalse(serviceList.isEmpty()); + assertEquals(2, serviceList.size()); Service service = serviceList.get(0); - Assert.assertEquals("2.0", service.getModelVersion()); + assertEquals("2.0", service.getModelVersion()); } @Test public void testGetServiceByModelInvariantUUIDOrderByModelVersionDescNotFound() { List<Service> serviceList = client.getServiceByModelInvariantUUIDOrderByModelVersionDesc(UUID.randomUUID().toString()); - Assert.assertTrue(serviceList.isEmpty()); + assertTrue(serviceList.isEmpty()); } @Test public void testGetVfModuleByModelInvariantUUIDOrderByModelVersionDesc() { List<VfModule> moduleList = client.getVfModuleByModelInvariantUUIDOrderByModelVersionDesc("78ca26d0-246d-11e7-93ae-92361f002671"); - Assert.assertFalse(moduleList.isEmpty()); - Assert.assertEquals(2, moduleList.size()); + assertFalse(moduleList.isEmpty()); + assertEquals(2, moduleList.size()); VfModule module = moduleList.get(0); - Assert.assertEquals("vSAMP10a DEV Base", module.getDescription()); + assertEquals("vSAMP10a DEV Base", module.getDescription()); } @Test @@ -454,20 +449,20 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { cloudSite.setIdentityService(cloudIdentity); localClient.postCloudSite(cloudSite); CloudSite getCloudSite = this.client.getCloudSite("MTN6"); - Assert.assertNotNull(getCloudSite); - Assert.assertNotNull(getCloudSite.getIdentityService()); - Assert.assertEquals("TESTCLLI", getCloudSite.getClli()); - Assert.assertEquals("regionId", getCloudSite.getRegionId()); - Assert.assertEquals("RANDOMID", getCloudSite.getIdentityServiceId()); + assertNotNull(getCloudSite); + assertNotNull(getCloudSite.getIdentityService()); + assertEquals("TESTCLLI", getCloudSite.getClli()); + assertEquals("regionId", getCloudSite.getRegionId()); + assertEquals("RANDOMID", getCloudSite.getIdentityServiceId()); } @Test public void testGetHomingInstance() { HomingInstance homingInstance = client.getHomingInstance("5df8b6de-2083-11e7-93ae-92361f232671"); - Assert.assertNotNull(homingInstance); - Assert.assertNotNull(homingInstance.getCloudOwner()); - Assert.assertNotNull(homingInstance.getCloudRegionId()); - Assert.assertNotNull(homingInstance.getOofDirectives()); + assertNotNull(homingInstance); + assertNotNull(homingInstance.getCloudOwner()); + assertNotNull(homingInstance.getCloudRegionId()); + assertNotNull(homingInstance.getOofDirectives()); } @Test @@ -491,43 +486,43 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { + "\"id\": \"vsink\"\n" + "}\n" + "]\n" + "}"); localClient.postHomingInstance(homingInstance); HomingInstance getHomingInstance = this.client.getHomingInstance("5df8d6be-2083-11e7-93ae-92361f232671"); - Assert.assertNotNull(getHomingInstance); - Assert.assertNotNull(getHomingInstance.getCloudRegionId()); - Assert.assertNotNull(getHomingInstance.getCloudOwner()); - Assert.assertEquals("CloudOwner-1", getHomingInstance.getCloudOwner()); - Assert.assertEquals("CloudRegionOne", getHomingInstance.getCloudRegionId()); + assertNotNull(getHomingInstance); + assertNotNull(getHomingInstance.getCloudRegionId()); + assertNotNull(getHomingInstance.getCloudOwner()); + assertEquals("CloudOwner-1", getHomingInstance.getCloudOwner()); + assertEquals("CloudRegionOne", getHomingInstance.getCloudRegionId()); } @Test public void testGetServiceByModelName() { Service service = client.getServiceByModelName("MSOTADevInfra_Test_Service"); - Assert.assertNotNull(service); - Assert.assertNotNull(service.getModelVersion()); - Assert.assertNotNull(service.getModelInvariantUUID()); - Assert.assertEquals("MSOTADevInfra_Test_Service", service.getModelName()); - Assert.assertEquals("NA", service.getServiceRole()); + assertNotNull(service); + assertNotNull(service.getModelVersion()); + assertNotNull(service.getModelInvariantUUID()); + assertEquals("MSOTADevInfra_Test_Service", service.getModelName()); + assertEquals("NA", service.getServiceRole()); } @Test public void testGetServiceByModelNameNotFound() { Service service = client.getServiceByModelName("Not_Found"); - Assert.assertNull(service); + assertNull(service); } @Test public void testGetServiceByModelUUID() { Service service = client.getServiceByModelUUID("5df8b6de-2083-11e7-93ae-92361f002679"); - Assert.assertNotNull(service); - Assert.assertNotNull(service.getModelVersion()); - Assert.assertNotNull(service.getModelInvariantUUID()); - Assert.assertEquals("5df8b6de-2083-11e7-93ae-92361f002679", service.getModelUUID()); - Assert.assertEquals("NA", service.getServiceRole()); + assertNotNull(service); + assertNotNull(service.getModelVersion()); + assertNotNull(service.getModelInvariantUUID()); + assertEquals("5df8b6de-2083-11e7-93ae-92361f002679", service.getModelUUID()); + assertEquals("NA", service.getServiceRole()); } @Test public void testGetServiceByModelUUIDNotFound() { Service service = client.getServiceByModelUUID("Not_Found"); - Assert.assertNull(service); + assertNull(service); } @Test @@ -539,53 +534,52 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { northBoundRequest.setCloudOwner("my-custom-cloud-owner"); client.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner("createService", "service", true, "my-custom-cloud-owner"); - Assert.assertNotNull(northBoundRequest); - Assert.assertEquals("createService", northBoundRequest.getAction()); - Assert.assertEquals("service", northBoundRequest.getRequestScope()); - Assert.assertEquals(true, northBoundRequest.getIsAlacarte()); - Assert.assertEquals("my-custom-cloud-owner", northBoundRequest.getCloudOwner()); + assertNotNull(northBoundRequest); + assertEquals("createService", northBoundRequest.getAction()); + assertEquals("service", northBoundRequest.getRequestScope()); + assertEquals(true, northBoundRequest.getIsAlacarte()); + assertEquals("my-custom-cloud-owner", northBoundRequest.getCloudOwner()); } @Test public void testFindServiceRecipeByActionAndServiceModelUUID() { ServiceRecipe serviceRecipe = client.findServiceRecipeByActionAndServiceModelUUID("createInstance", "4694a55f-58b3-4f17-92a5-796d6f5ffd0d"); - Assert.assertNotNull(serviceRecipe); - Assert.assertNotNull(serviceRecipe.getServiceModelUUID()); - Assert.assertNotNull(serviceRecipe.getAction()); - Assert.assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance", - serviceRecipe.getOrchestrationUri()); - Assert.assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription()); + assertNotNull(serviceRecipe); + assertNotNull(serviceRecipe.getServiceModelUUID()); + assertNotNull(serviceRecipe.getAction()); + assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance", serviceRecipe.getOrchestrationUri()); + assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription()); } @Test public void testFindServiceRecipeByActionAndServiceModelUUIDNotFound() { ServiceRecipe serviceRecipe = client.findServiceRecipeByActionAndServiceModelUUID("not_found", "5df8b6de-2083-11e7-93ae-test"); - Assert.assertNull(serviceRecipe); + assertNull(serviceRecipe); } @Test public void testFindExternalToInternalServiceByServiceName() { ExternalServiceToInternalService externalServiceToInternalService = client.findExternalToInternalServiceByServiceName("MySpecialServiceName"); - Assert.assertNotNull(externalServiceToInternalService); - Assert.assertNotNull(externalServiceToInternalService.getServiceName()); - Assert.assertNotNull(externalServiceToInternalService.getServiceModelUUID()); - Assert.assertEquals("MySpecialServiceName", externalServiceToInternalService.getServiceName()); + assertNotNull(externalServiceToInternalService); + assertNotNull(externalServiceToInternalService.getServiceName()); + assertNotNull(externalServiceToInternalService.getServiceModelUUID()); + assertEquals("MySpecialServiceName", externalServiceToInternalService.getServiceName()); } @Test public void testFindExternalToInternalServiceByServiceNameNotFound() { ExternalServiceToInternalService externalServiceToInternalService = client.findExternalToInternalServiceByServiceName("Not_Found"); - Assert.assertNull(externalServiceToInternalService); + assertNull(externalServiceToInternalService); } @Test public void getPnfResourceByModelUUID_validUuid_expectedOutput() { PnfResource pnfResource = client.getPnfResourceByModelUUID("ff2ae348-214a-11e7-93ae-92361f002680"); - Assert.assertNotNull(pnfResource); + assertNotNull(pnfResource); assertEquals("PNFResource modelUUID", "ff2ae348-214a-11e7-93ae-92361f002680", pnfResource.getModelUUID()); assertEquals("PNFResource modelInvariantUUID", "2fff5b20-214b-11e7-93ae-92361f002680", pnfResource.getModelInvariantUUID()); @@ -596,7 +590,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @Test public void getPnfResourceByModelUUID_invalidUuid_NullOutput() { PnfResource pnfResource = client.getPnfResourceByModelUUID(UUID.randomUUID().toString()); - Assert.assertNull(pnfResource); + assertNull(pnfResource); } @Test @@ -620,7 +614,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { public void getPnfResourceCustomizationByModelCustomizationUUID_invalidUuid_nullOutput() { PnfResourceCustomization pnfResourceCustomization = client.getPnfResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString()); - Assert.assertNull(pnfResourceCustomization); + assertNull(pnfResourceCustomization); } @Test @@ -651,6 +645,53 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { } @Test + public void testGetServiceTopologyById() throws Exception { + org.onap.so.rest.catalog.beans.Service serviceByID = + client.getServiceModelInformation("5df8b6de-2083-11e7-93ae-92361f002671", "2"); + assertNotNull(serviceByID); + assertEquals("MSOTADevInfra_vSAMP10a_Service", serviceByID.getModelName()); + assertEquals("NA", serviceByID.getServiceType()); + assertEquals("NA", serviceByID.getServiceRole()); + } + + @Test + public void testGetServices() throws Exception { + List<org.onap.so.rest.catalog.beans.Service> services = client.getServices(); + assertEquals(false, services.isEmpty()); + } + + @Test + public void testVnf() throws Exception { + org.onap.so.rest.catalog.beans.Vnf vnf = client.getVnfModelInformation("5df8b6de-2083-11e7-93ae-92361f002671", + "68dc9a92-214c-11e7-93ae-92361f002671", "0"); + assertNotNull(vnf); + assertEquals("vSAMP10a", vnf.getModelName()); + assertEquals(false, vnf.getNfDataValid()); + assertEquals("vSAMP", vnf.getNfFunction()); + assertEquals("vSAMP", vnf.getNfNamingCode()); + assertEquals("vSAMP", vnf.getNfRole()); + assertEquals("vSAMP", vnf.getNfType()); + + vnf.setNfDataValid(true); + vnf.setNfFunction("nfFunction"); + vnf.setNfRole("nfRole"); + vnf.setNfType("nfType"); + vnf.setNfNamingCode("nfNamingCode"); + + client.updateVnf("5df8b6de-2083-11e7-93ae-92361f002671", vnf); + vnf = client.getVnfModelInformation("5df8b6de-2083-11e7-93ae-92361f002671", + "68dc9a92-214c-11e7-93ae-92361f002671", "0"); + assertEquals("vSAMP10a", vnf.getModelName()); + assertEquals(true, vnf.getNfDataValid()); + assertEquals("nfFunction", vnf.getNfFunction()); + assertEquals("nfNamingCode", vnf.getNfNamingCode()); + assertEquals("nfRole", vnf.getNfRole()); + assertEquals("nfType", vnf.getNfType()); + + + } + + @Test public void getWorkflowByArtifactUUID_validUuid_expectedOutput() { Workflow workflow = client.findWorkflowByArtifactUUID("5b0c4322-643d-4c9f-b184-4516049e99b1"); assertEquals("artifactName", "testingWorkflow.bpmn", workflow.getArtifactName()); @@ -659,7 +700,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @Test public void getWorkflowByArtifactUUID_invalidUuid_nullOutput() { Workflow workflow = client.findWorkflowByArtifactUUID(UUID.randomUUID().toString()); - Assert.assertNull(workflow); + assertNull(workflow); } @Test @@ -674,7 +715,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @Test public void getWorkflowByModelUUID_invalidUuid_nullOutput() { Workflow workflow = client.findWorkflowByArtifactUUID(UUID.randomUUID().toString()); - Assert.assertNull(workflow); + assertNull(workflow); } @Test @@ -689,7 +730,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @Test public void getWorkflowBySource_invalidSource_nullOutput() { List<Workflow> workflow = client.findWorkflowBySource("abc"); - Assert.assertNull(workflow); + assertNull(workflow); } } diff --git a/adapters/mso-catalog-db-adapter/src/test/resources/ExpectedService.json b/adapters/mso-catalog-db-adapter/src/test/resources/ExpectedService.json index cc5145f0e3..2dc83c8963 100644 --- a/adapters/mso-catalog-db-adapter/src/test/resources/ExpectedService.json +++ b/adapters/mso-catalog-db-adapter/src/test/resources/ExpectedService.json @@ -23,6 +23,7 @@ "toscaNodeType": "toscaNodeType", "nfFunction": "nfFunction", "nfRole": "nfRole", + "nfType": "nfType", "nfNamingCode": "nfNamingCode", "multiStageDesign": "multiStageDesign", "orchestrationMode": "orchestrationMode", diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java index 4c115271f0..153de2fb12 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java @@ -842,8 +842,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { } else { String error = String.format( "Network Type:%s Version_Min:%s Version_Max:%s not supported on Cloud:%s with AIC_Version:%s", - networkType, networkType, networkResource.getAicVersionMin(), networkResource.getAicVersionMax(), - cloudSiteId, cloudSite.getCloudVersion()); + networkType, networkResource.getAicVersionMin(), networkResource.getAicVersionMax(), cloudSiteId, + cloudSite.getCloudVersion()); logger.error(LoggingAnchor.THREE, MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); throw new NetworkException(error, MsoExceptionCategory.USERDATA); } @@ -1477,13 +1477,19 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { } if (subnet.getAllocationPools() != null) { - curR = curR + " allocation_pools:\n"; + StringBuilder tempBuf = new StringBuilder(); + tempBuf.append(curR); + tempBuf.append(" allocation_pools:\n"); for (Pool pool : subnet.getAllocationPools()) { if (!commonUtils.isNullOrEmpty(pool.getStart()) && !commonUtils.isNullOrEmpty(pool.getEnd())) { - curR = curR + " - start: " + pool.getStart() + "\n"; - curR = curR + " end: " + pool.getEnd() + "\n"; + tempBuf.append(" - start: "); + tempBuf.append(pool.getStart()); + tempBuf.append("\n end: "); + tempBuf.append(pool.getEnd()); + tempBuf.append("\n"); } } + curR = tempBuf.toString(); } resourcesBuf.append(curR); @@ -1492,7 +1498,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { curO = curO.replace("%subnetId%", subnet.getSubnetId()); outputsBuf.append(curO); - } // append resources and outputs in heatTemplate logger.debug("Tempate initial:{}", heatTemplate); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java deleted file mode 100644 index 7786b872ef..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; -import org.onap.so.adapters.vdu.VduArtifact; -import org.onap.so.adapters.vdu.VduArtifact.ArtifactType; -import org.onap.so.adapters.vdu.VduModelInfo; -import org.onap.so.adapters.vnf.exceptions.VnfException; -import com.google.common.io.Files; - -/** - * The purpose of this class is to create a CSAR byte array from Vdu inputs for the purpose of forwarding to a TOSCA - * orchestrator. - * - * @author DeWayne - * - */ -public class CSAR { - private static final String MANIFEST_FILENAME = "MANIFEST.MF"; - private VduModelInfo vduModel; - - public CSAR(VduModelInfo model) { - this.vduModel = model; - } - - /** - * Creates a byte array representation of a CSAR corresponding to the VduBlueprint arg in the constructor. - * - * @return - * @throws VnfException - */ - public byte[] create() { - File dir = Files.createTempDir(); - - /** - * Create subdir - */ - File metadir = new File(dir.getAbsolutePath() + "/TOSCA-Metadata"); - if (!metadir.mkdir()) { - throw new RuntimeException("CSAR TOSCA-Metadata directory create failed"); - } - - /** - * Organize model info for consumption - */ - VduArtifact mainTemplate = null; - List<VduArtifact> extraFiles = new ArrayList<>(); - for (VduArtifact artifact : vduModel.getArtifacts()) { - if (artifact.getType() == ArtifactType.MAIN_TEMPLATE) { - mainTemplate = artifact; - } else { - extraFiles.add(artifact); - } - } - - if (mainTemplate == null) { // make a dummy to avoid null pointers - mainTemplate = new VduArtifact("", new byte[0], null); - } - - /** - * Write template files - */ - try (OutputStream ofs = new FileOutputStream(new File(dir, mainTemplate.getName())); - PrintStream mfstream = - new PrintStream(new File(metadir.getAbsolutePath() + '/' + MANIFEST_FILENAME));) { - ofs.write(mainTemplate.getContent()); - - /** - * Write other files - */ - if (!extraFiles.isEmpty()) { - for (VduArtifact artifact : extraFiles) { - try (OutputStream out = new FileOutputStream(new File(dir, artifact.getName()));) { - out.write(artifact.getContent()); - } - } - } - - - /** - * Create manifest - */ - mfstream.println("TOSCA-Meta-File-Version: 1.0"); - mfstream.println("CSAR-Version: 1.1"); - mfstream.println("Created-by: ONAP"); - mfstream.println("Entry-Definitions: " + mainTemplate.getName()); - - /** - * ZIP it up - */ - ByteArrayOutputStream zipbytes = new ByteArrayOutputStream(); - ZipOutputStream zos = new ZipOutputStream(zipbytes); - compressTree(zos, "", dir, dir); - zos.close(); - return zipbytes.toByteArray(); - - } catch (Exception e) { - throw new RuntimeException("Failed to create CSAR: " + e.getMessage()); - } finally { - /** - * Clean up tmpdir - */ - deleteDirectory(dir); - } - } - - /** - * Private methods - */ - - /** - * Compresses (ZIPs) a directory tree - * - * @param dir - * @throws IOException - */ - private void compressTree(ZipOutputStream zos, String path, File basedir, File dir) throws IOException { - if (!dir.isDirectory()) - return; - - for (File f : dir.listFiles()) { - if (f.isDirectory()) { - String newpath = path + f.getName() + '/'; - ZipEntry entry = new ZipEntry(newpath); - zos.putNextEntry(entry); - zos.closeEntry(); - compressTree(zos, newpath, basedir, f); - } else { - ZipEntry ze = new ZipEntry( - f.getAbsolutePath().substring(basedir.getAbsolutePath().length() + 1).replaceAll("\\\\", "/")); - zos.putNextEntry(ze); - // read the file and write to ZipOutputStream - try (FileInputStream fis = new FileInputStream(f);) { - byte[] buffer = new byte[1024]; - int len; - while ((len = fis.read(buffer)) > 0) { - zos.write(buffer, 0, len); - } - } - zos.closeEntry(); - } - } - } - - private boolean deleteDirectory(File directory) { - if (directory.exists()) { - File[] files = directory.listFiles(); - if (null != files) { - for (int i = 0; i < files.length; i++) { - if (files[i].isDirectory()) { - deleteDirectory(files[i]); - } else { - files[i].delete(); - } - } - } - } - return (directory.delete()); - } -} diff --git a/adapters/mso-openstack-adapters/src/test/resources/schema.sql b/adapters/mso-openstack-adapters/src/test/resources/schema.sql index 7b3ffd7d30..9406bc445d 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/schema.sql +++ b/adapters/mso-openstack-adapters/src/test/resources/schema.sql @@ -1109,6 +1109,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, + `NF_DATA_VALID` tinyint(1) DEFAULT '0', `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java index f45d5a0219..792002354b 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java @@ -40,7 +40,7 @@ public class WebSecurityConfigImpl extends WebSecurityConfig { @Override protected void configure(final HttpSecurity http) throws Exception { - if (clientAuth.equalsIgnoreCase("need")) { + if (("need").equalsIgnoreCase(clientAuth)) { http.csrf().disable().authorizeRequests().anyRequest().permitAll(); } else { http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() 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 e048d4c567..0fc94c8bd6 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 @@ -97,10 +97,8 @@ public class DeployActivitySpecs { } List<String> categoryList = new ArrayList<>(); for (ActivitySpecActivitySpecCategories activitySpecCat : activitySpecActivitySpecCategories) { - if (activitySpecCat != null) { - if (activitySpecCat.getActivitySpecCategories() != null) { - categoryList.add(activitySpecCat.getActivitySpecCategories().getName()); - } + if (activitySpecCat != null && activitySpecCat.getActivitySpecCategories() != null) { + categoryList.add(activitySpecCat.getActivitySpecCategories().getName()); } } activitySpec.setCategoryList(categoryList); 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 3b9406a697..073412133c 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 @@ -37,6 +37,7 @@ import java.nio.file.Paths; import java.util.List; import java.util.Optional; import org.onap.so.logger.LoggingAnchor; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.sdc.api.IDistributionClient; import org.onap.sdc.api.consumer.IDistributionStatusMessage; import org.onap.sdc.api.consumer.IFinalDistrStatusMessage; @@ -71,6 +72,7 @@ import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.springframework.stereotype.Component; @@ -588,6 +590,10 @@ public class ASDCController { logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_RECEIVE_CALLBACK_NOTIF.toString(), String.valueOf(noOfArtifacts), iNotif.getServiceUUID(), "ASDC"); try { + + if (iNotif.getDistributionID() != null && !iNotif.getDistributionID().isEmpty()) { + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, iNotif.getDistributionID()); + } logger.debug(ASDCNotificationLogging.dumpASDCNotification(iNotif)); logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), iNotif.getServiceUUID(), "ASDC", "treatNotification"); diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceStructure.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceStructure.java index 8be3d6ba06..f2c6b2f16a 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceStructure.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceStructure.java @@ -61,7 +61,7 @@ public abstract class ResourceStructure { /** * Number of resources provided by the resource structure. */ - protected int NumberOfResources; + protected int numberOfResources; /** * The list of artifacts existing in this resource hashed by UUID. @@ -142,11 +142,11 @@ public abstract class ResourceStructure { } public int getNumberOfResources() { - return NumberOfResources; + return numberOfResources; } public void setNumberOfResources(int numberOfResources) { - NumberOfResources = numberOfResources; + this.numberOfResources = numberOfResources; } public Map<String, VfModuleArtifact> getArtifactsMapByUUID() { diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/WorkflowResource.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/WorkflowResource.java index a68d98e0b0..ef4dfa24aa 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/WorkflowResource.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/WorkflowResource.java @@ -52,7 +52,7 @@ import org.springframework.stereotype.Component; public class WorkflowResource { protected static final Logger logger = LoggerFactory.getLogger(WorkflowResource.class); - private static final String pattern = ".*\\\"activity:(.*)\\\" .*"; + private static final String PATTERN = ".*\\\"activity:(.*)\\\" .*"; private static final String TARGET_RESOURCE_VNF = "vnf"; private static final String SOURCE_SDC = "sdc"; private static final String BPMN_SUFFIX = ".bpmn"; @@ -176,7 +176,7 @@ public class WorkflowResource { protected List<String> getActivityNameList(String bpmnContent) { List<String> activityNameList = new ArrayList<>(); - Pattern p = Pattern.compile(pattern); + Pattern p = Pattern.compile(PATTERN); Matcher m = p.matcher(bpmnContent); while (m.find()) { activityNameList.add(m.group(1)); 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 276b8183a8..3e6b44226d 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 @@ -47,6 +47,7 @@ import org.onap.sdc.api.notification.IStatusData; import org.onap.sdc.tosca.parser.api.IEntityDetails; import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; import org.onap.sdc.tosca.parser.elements.queries.EntityQuery; +import org.onap.sdc.tosca.parser.elements.queries.EntityQuery.EntityQueryBuilder; import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery; import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery.TopologyTemplateQueryBuilder; import org.onap.sdc.tosca.parser.enums.SdcTypes; @@ -1015,17 +1016,18 @@ public class ToscaResourceInstaller { // Check for VNFC Instance Group info and add it if there is - List<Group> groupList = - toscaResourceStruct.getSdcCsarHelper().getGroupsOfOriginOfNodeTemplateByToscaGroupType( - nodeTemplate, "org.openecomp.groups.VfcInstanceGroup"); + List<IEntityDetails> vfcEntityList = getEntityDetails(toscaResourceStruct, + "org.openecomp.groups.VfcInstanceGroup", + TopologyTemplateQuery.newBuilder(SdcTypes.VF).customizationUUID(vfCustomizationUUID), false); - for (Group group : groupList) { + + for (IEntityDetails groupEntity : vfcEntityList) { VnfcInstanceGroupCustomization vnfcInstanceGroupCustomization = - createVNFCInstanceGroup(nodeTemplate, group, vnfResource, toscaResourceStruct); + createVNFCInstanceGroup(groupEntity, nodeTemplate, vnfResource, toscaResourceStruct); vnfcInstanceGroupCustomizationRepo.saveAndFlush(vnfcInstanceGroupCustomization); } - List<String> seqResult = processVNFCGroupSequence(toscaResourceStruct, groupList); + List<String> seqResult = processVNFCGroupSequence(toscaResourceStruct, vfcEntityList); if (!CollectionUtils.isEmpty(seqResult)) { String resultStr = seqResult.stream().collect(Collectors.joining(",")); vnfResource.setVnfcInstanceGroupOrder(resultStr); @@ -1043,82 +1045,90 @@ public class ToscaResourceInstaller { } private List<String> processVNFCGroupSequence(ToscaResourceStructure toscaResourceStructure, - List<Group> groupList) { - if (CollectionUtils.isEmpty(groupList)) { + List<IEntityDetails> groupEntityDetails) { + if (CollectionUtils.isEmpty(groupEntityDetails)) { 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); + List<String> strSequence = new ArrayList<>(groupEntityDetails.size()); + List<IEntityDetails> tempEntityList = new ArrayList<>(groupEntityDetails.size()); + List<IEntityDetails> entities = new ArrayList<>(); + tempEntityList.addAll(groupEntityDetails); + + for (IEntityDetails vnfcEntityDetails : groupEntityDetails) { + + List<IEntityDetails> vnfcMemberNodes = vnfcEntityDetails.getMemberNodes(); - 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()) { + for (IEntityDetails vnfcDetails : vnfcMemberNodes) { + + Map<String, RequirementAssignment> requirements = vnfcDetails.getRequirements(); + + if (requirements != null && !requirements.isEmpty()) { hasRequirements = true; break; } } if (!hasRequirements) { - strSequence.add(group.getName()); - tempGroupList.remove(group); - nodes.addAll(nodeList); + strSequence.add(vnfcEntityDetails.getName()); + tempEntityList.remove(vnfcEntityDetails); + entities.addAll(vnfcMemberNodes); } } - getVNFCGroupSequenceList(strSequence, tempGroupList, nodes, iSdcCsarHelper); + getVNFCGroupSequenceList(strSequence, tempEntityList, entities, iSdcCsarHelper); return strSequence; } - private void getVNFCGroupSequenceList(List<String> strSequence, List<Group> groupList, List<NodeTemplate> nodes, - ISdcCsarHelper iSdcCsarHelper) { - if (CollectionUtils.isEmpty(groupList)) { + private void getVNFCGroupSequenceList(List<String> strSequence, List<IEntityDetails> vnfcGroupDetails, + List<IEntityDetails> vnfcMemberNodes, ISdcCsarHelper iSdcCsarHelper) { + if (CollectionUtils.isEmpty(vnfcGroupDetails)) { return; } - List<Group> tempGroupList = new ArrayList<>(); - tempGroupList.addAll(groupList); + List<IEntityDetails> tempGroupList = new ArrayList<>(); + tempGroupList.addAll(vnfcGroupDetails); - for (Group group : groupList) { - boolean isAllExists = true; - ArrayList<NodeTemplate> members = group.getMemberNodes(); - for (NodeTemplate memberNode : members) { - RequirementAssignments requirements = iSdcCsarHelper.getRequirementsOf(memberNode); - if (requirements == null || requirements.getAll() == null || requirements.getAll().isEmpty()) { + for (IEntityDetails vnfcGroup : vnfcGroupDetails) { + List<IEntityDetails> members = vnfcGroup.getMemberNodes(); + for (IEntityDetails memberNode : members) { + boolean isAllExists = true; + + + Map<String, RequirementAssignment> requirements = memberNode.getRequirements(); + + if (requirements == null || requirements.isEmpty()) { continue; } - List<RequirementAssignment> rqaList = requirements.getAll(); - for (RequirementAssignment rqa : rqaList) { + + + for (Map.Entry<String, RequirementAssignment> entry : requirements.entrySet()) { + RequirementAssignment rqa = entry.getValue(); String name = rqa.getNodeTemplateName(); - Optional<NodeTemplate> findNode = - nodes.stream().filter(node -> node.getName().equals(name)).findFirst(); - if (!findNode.isPresent()) { - isAllExists = false; - break; + for (IEntityDetails node : vnfcMemberNodes) { + if (name.equals(node.getName())) { + break; + } } - } - if (!isAllExists) { + + isAllExists = false; break; } - } - if (isAllExists) { - strSequence.add(group.getName()); - tempGroupList.remove(group); - nodes.addAll(group.getMemberNodes()); + if (isAllExists) { + strSequence.add(vnfcGroup.getName()); + tempGroupList.remove(vnfcGroupDetails); + vnfcMemberNodes.addAll(vnfcGroupDetails); + } } - } - if (!tempGroupList.isEmpty() && tempGroupList.size() < groupList.size()) { - getVNFCGroupSequenceList(strSequence, tempGroupList, nodes, iSdcCsarHelper); + if (!tempGroupList.isEmpty() && tempGroupList.size() < vnfcGroupDetails.size()) { + getVNFCGroupSequenceList(strSequence, tempGroupList, vnfcMemberNodes, iSdcCsarHelper); + } } } @@ -1822,10 +1832,11 @@ public class ToscaResourceInstaller { return collectionNetworkResourceCustomization; } - protected VnfcInstanceGroupCustomization createVNFCInstanceGroup(NodeTemplate vnfcNodeTemplate, Group group, - VnfResourceCustomization vnfResourceCustomization, ToscaResourceStructure toscaResourceStructure) { + protected VnfcInstanceGroupCustomization createVNFCInstanceGroup(IEntityDetails vfcInstanceEntity, + NodeTemplate vnfcNodeTemplate, VnfResourceCustomization vnfResourceCustomization, + ToscaResourceStructure toscaResourceStructure) { - Metadata instanceMetadata = group.getMetadata(); + Metadata instanceMetadata = vfcInstanceEntity.getMetadata(); InstanceGroup existingInstanceGroup = instanceGroupRepo.findByModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); @@ -1839,7 +1850,7 @@ public class ToscaResourceInstaller { .setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); vfcInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); vfcInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); - vfcInstanceGroup.setToscaNodeType(group.getType()); + vfcInstanceGroup.setToscaNodeType(vfcInstanceEntity.getToscaType()); vfcInstanceGroup.setRole("SUB-INTERFACE"); // Set Role vfcInstanceGroup.setType(InstanceGroupType.VNFC); // Set type } else { @@ -1858,45 +1869,64 @@ public class ToscaResourceInstaller { vfcInstanceGroupCustom.setDescription(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); String getInputName = null; - String groupProperty = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, - "vfc_instance_group_function"); - if (groupProperty != null) { - int getInputIndex = groupProperty.indexOf("{get_input="); - if (getInputIndex > -1) { - getInputName = groupProperty.substring(getInputIndex + 11, groupProperty.length() - 1); + + Map<String, Property> groupProperties = vfcInstanceEntity.getProperties(); + + for (String key : groupProperties.keySet()) { + Property property = groupProperties.get(key); + + String vfcName = property.getName(); + + if (vfcName != null) { + if (vfcName.equals("vfc_instance_group_function")) { + + String vfcValue = property.getValue().toString(); + int getInputIndex = vfcValue.indexOf("{get_input="); + if (getInputIndex > -1) { + getInputName = vfcValue.substring(getInputIndex + 11, vfcValue.length() - 1); + } + + } } + } - vfcInstanceGroupCustom.setFunction(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vnfcNodeTemplate, getInputName)); + + List<IEntityDetails> serviceEntityList = + getEntityDetails(toscaResourceStructure, EntityQuery.newBuilder(SdcTypes.VF).customizationUUID( + vnfResourceCustomization.getModelCustomizationUUID()), SdcTypes.SERVICE, false); + + if (serviceEntityList != null && !serviceEntityList.isEmpty()) { + vfcInstanceGroupCustom.setFunction(getLeafPropertyValue(serviceEntityList.get(0), getInputName)); + } + vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup); ArrayList<Input> inputs = vnfcNodeTemplate.getSubMappingToscaTemplate().getInputs(); - createVFCInstanceGroupMembers(vfcInstanceGroupCustom, group, inputs); + createVFCInstanceGroupMembers(vfcInstanceGroupCustom, vfcInstanceEntity, inputs); return vfcInstanceGroupCustom; - } - private void createVFCInstanceGroupMembers(VnfcInstanceGroupCustomization vfcInstanceGroupCustom, Group group, - List<Input> inputList) { - List<NodeTemplate> members = group.getMemberNodes(); + private void createVFCInstanceGroupMembers(VnfcInstanceGroupCustomization vfcInstanceGroupCustom, + IEntityDetails vfcModuleEntity, List<Input> inputList) { + List<IEntityDetails> members = vfcModuleEntity.getMemberNodes(); if (!CollectionUtils.isEmpty(members)) { - for (NodeTemplate vfcTemplate : members) { + for (IEntityDetails vfcEntity : members) { VnfcCustomization vnfcCustomization = new VnfcCustomization(); - Metadata metadata = vfcTemplate.getMetaData(); + Metadata metadata = vfcEntity.getMetadata(); vnfcCustomization .setModelCustomizationUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - vnfcCustomization.setModelInstanceName(vfcTemplate.getName()); + vnfcCustomization.setModelInstanceName(vfcEntity.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.setToscaNodeType(testNull(vfcEntity.getToscaType())); vnfcCustomization .setDescription(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - vnfcCustomization.setResourceInput(getVnfcResourceInput(vfcTemplate, inputList)); + vnfcCustomization.setResourceInput(getVnfcResourceInput(vfcEntity, inputList)); List<VnfcCustomization> vnfcCustomizations = vfcInstanceGroupCustom.getVnfcCustomizations(); if (vnfcCustomizations == null) { @@ -1908,9 +1938,9 @@ public class ToscaResourceInstaller { } } - public String getVnfcResourceInput(NodeTemplate vfcTemplate, List<Input> inputList) { + public String getVnfcResourceInput(IEntityDetails vfcEntity, List<Input> inputList) { Map<String, String> resouceRequest = new HashMap<>(); - LinkedHashMap<String, Property> vfcTemplateProperties = vfcTemplate.getProperties(); + Map<String, Property> vfcTemplateProperties = vfcEntity.getProperties(); for (String key : vfcTemplateProperties.keySet()) { Property property = vfcTemplateProperties.get(key); String resourceValue = getValue(property.getValue(), inputList); @@ -1918,7 +1948,7 @@ public class ToscaResourceInstaller { } String resourceCustomizationUuid = - vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); + vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); String jsonStr = null; try { @@ -2700,6 +2730,18 @@ public class ToscaResourceInstaller { } + protected List<IEntityDetails> getEntityDetails(ToscaResourceStructure toscaResourceStruct, String entityType, + TopologyTemplateQueryBuilder topologyTemplateBuilder, boolean nestedSearch) { + + EntityQuery entityQuery = EntityQuery.newBuilder(entityType).build(); + TopologyTemplateQuery topologyTemplateQuery = topologyTemplateBuilder.build(); + List<IEntityDetails> entityDetails = + toscaResourceStruct.getSdcCsarHelper().getEntity(entityQuery, topologyTemplateQuery, nestedSearch); + + return entityDetails; + + } + protected List<IEntityDetails> getEntityDetails(ToscaResourceStructure toscaResourceStruct, SdcTypes entityType, TopologyTemplateQueryBuilder topologyTemplateBuilder, boolean nestedSearch) { @@ -2712,6 +2754,18 @@ public class ToscaResourceInstaller { } + protected List<IEntityDetails> getEntityDetails(ToscaResourceStructure toscaResourceStruct, + EntityQueryBuilder entityType, SdcTypes topologyTemplate, boolean nestedSearch) { + + EntityQuery entityQuery = entityType.build(); + TopologyTemplateQuery topologyTemplateQuery = TopologyTemplateQuery.newBuilder(topologyTemplate).build(); + List<IEntityDetails> entityDetails = + toscaResourceStruct.getSdcCsarHelper().getEntity(entityQuery, topologyTemplateQuery, nestedSearch); + + return entityDetails; + + } + protected String getLeafPropertyValue(IEntityDetails entityDetails, String propName) { Property leafProperty = entityDetails.getProperties().get(propName); diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java index 0681cd8aed..055968cc95 100644 --- a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java @@ -33,6 +33,7 @@ import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.asdc.BaseTest; import org.onap.so.asdc.client.exceptions.ASDCControllerException; import org.onap.so.asdc.client.test.emulators.ArtifactInfoImpl; @@ -55,6 +56,7 @@ import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus; import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatusRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @@ -277,6 +279,35 @@ public class ASDCControllerITTest extends BaseTest { } } + /** + * Test to check RequestId is being set using the DistributionID. + */ + @Test + public void treatNotification_verifyRequestID() { + + String serviceUuid = "efaea486-561f-4159-9191-a8d3cb346728"; + String serviceInvariantUuid = "f2edfbf4-bb0a-4fe7-a57a-71362d4b0b23"; + distributionId = "bb15de12-166d-4e45-9e5f-4b3f25200d7b"; + + initMockAaiServer(serviceUuid, serviceInvariantUuid); + + NotificationDataImpl notificationData = new NotificationDataImpl(); + notificationData.setServiceUUID(serviceUuid); + notificationData.setDistributionID(distributionId); + notificationData.setServiceInvariantUUID(serviceInvariantUuid); + notificationData.setServiceVersion("1.0"); + + try { + asdcController.treatNotification(notificationData); + logger.info("Verify RequestId : {}", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + assertEquals("bb15de12-166d-4e45-9e5f-4b3f25200d7b", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + + } catch (Exception e) { + logger.info(e.getMessage(), e); + fail(e.getMessage()); + } + } + private ArtifactInfoImpl constructPnfServiceArtifact() { ArtifactInfoImpl artifactInfo = new ArtifactInfoImpl(); artifactInfo.setArtifactType(ASDCConfiguration.TOSCA_CSAR); 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 846eaf47e2..da99efadea 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 @@ -24,6 +24,7 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; +import org.onap.sdc.tosca.parser.api.IEntityDetails; import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; import org.onap.sdc.toscaparser.api.NodeTemplate; import org.onap.sdc.toscaparser.api.Property; @@ -49,6 +50,9 @@ public class ToscaResourceInputTest { NodeTemplate nodeTemplate; @Mock + IEntityDetails entityDetails; + + @Mock Property property; @Mock @@ -65,16 +69,16 @@ public class ToscaResourceInputTest { 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(entityDetails.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); + when(entityDetails.getMetadata()).thenReturn(metadata); List<Input> inputs = new ArrayList<>(); inputs.add(input); - String resourceInput = toscaResourceInstaller.getVnfcResourceInput(nodeTemplate, inputs); + String resourceInput = toscaResourceInstaller.getVnfcResourceInput(entityDetails, inputs); assertEquals("{\\\"key1\\\":\\\"[sites,INDEX,role]|defaultValue\\\"}", resourceInput); } diff --git a/asdc-controller/src/test/resources/schema.sql b/asdc-controller/src/test/resources/schema.sql index 652fc8f0de..ad6b156956 100644 --- a/asdc-controller/src/test/resources/schema.sql +++ b/asdc-controller/src/test/resources/schema.sql @@ -1113,6 +1113,7 @@ CREATE TABLE `vnf_resource_customization` ( `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, `SERVICE_MODEL_UUID` varchar(200) NOT NULL, `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, + `NF_DATA_VALID` tinyint(1) DEFAULT '0', 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`), diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtil.groovy index 64567a349e..5525c2642b 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtil.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtil.groovy @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -40,11 +40,11 @@ class ExternalAPIUtil { String Prefix="EXTAPI_" - private static final Logger logger = LoggerFactory.getLogger( ExternalAPIUtil.class); + private static final Logger logger = LoggerFactory.getLogger( ExternalAPIUtil.class) - private final HttpClientFactory httpClientFactory; - private final MsoUtils utils; - private final ExceptionUtil exceptionUtil; + private final HttpClientFactory httpClientFactory + private final MsoUtils utils + private final ExceptionUtil exceptionUtil public static final String PostServiceOrderRequestsTemplate = "{\n" + @@ -107,22 +107,22 @@ class ExternalAPIUtil { // } public String setTemplate(String template, Map<String, String> valueMap) { - logger.debug("ExternalAPIUtil setTemplate", true); - StringBuffer result = new StringBuffer(); + logger.debug("ExternalAPIUtil setTemplate", true) + StringBuffer result = new StringBuffer() - String pattern = "<.*>"; - Pattern r = Pattern.compile(pattern); - Matcher m = r.matcher(template); + String pattern = "<.*>" + Pattern r = Pattern.compile(pattern) + Matcher m = r.matcher(template) - logger.debug("ExternalAPIUtil template:" + template, true); + logger.debug("ExternalAPIUtil template:" + template, true) while (m.find()) { - String key = template.substring(m.start() + 1, m.end() - 1); - logger.debug("ExternalAPIUtil key:" + key + " contains key? " + valueMap.containsKey(key), true); - m.appendReplacement(result, valueMap.getOrDefault(key, "\"TBD\"")); + String key = template.substring(m.start() + 1, m.end() - 1) + logger.debug("ExternalAPIUtil key:" + key + " contains key? " + valueMap.containsKey(key), true) + m.appendReplacement(result, valueMap.getOrDefault(key, "\"TBD\"")) } - m.appendTail(result); - logger.debug("ExternalAPIUtil return:" + result.toString(), true); - return result.toString(); + m.appendTail(result) + logger.debug("ExternalAPIUtil return:" + result.toString(), true) + return result.toString() } /** diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtilFactory.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtilFactory.groovy index e7f46464ee..549267eec1 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtilFactory.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtilFactory.groovy @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2018 Nokia. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy index f013fa8698..db39358ccd 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * @@ -22,9 +22,9 @@ package org.onap.so.bpmn.common.scripts -import org.onap.so.logger.LoggingAnchor; +import org.onap.so.logger.LoggingAnchor import org.onap.so.bpmn.core.UrnPropertiesReader -import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.ErrorCode import java.text.SimpleDateFormat @@ -39,7 +39,7 @@ import static org.apache.commons.lang3.StringUtils.* // SDNC Adapter Request/Response processing public class SDNCAdapter extends AbstractServiceTaskProcessor { - private static final Logger logger = LoggerFactory.getLogger( SDNCAdapter.class); + private static final Logger logger = LoggerFactory.getLogger( SDNCAdapter.class) def Prefix="SDNCA_" @@ -77,7 +77,7 @@ public class SDNCAdapter extends AbstractServiceTaskProcessor { } catch (IOException ex) { logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Unable to encode username password string", "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) } // TODO Use variables instead of passing xml request - Huh? @@ -238,9 +238,9 @@ public class SDNCAdapter extends AbstractServiceTaskProcessor { def sdnccallbackreq=execution.getVariable("sdncAdapterCallbackRequest") logger.debug("sdncAdapterCallbackRequest :" + sdnccallbackreq) if (sdnccallbackreq==null){ - execution.setVariable("callbackResponseReceived",false); + execution.setVariable("callbackResponseReceived",false) }else{ - execution.setVariable("callbackResponseReceived",true); + execution.setVariable("callbackResponseReceived",true) } } @@ -303,10 +303,10 @@ public class SDNCAdapter extends AbstractServiceTaskProcessor { } public String generateCurrentTimeInUtc(){ - final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - sdf.setTimeZone(TimeZone.getTimeZone("UTC")); - final String utcTime = sdf.format(new Date()); - return utcTime; + final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + sdf.setTimeZone(TimeZone.getTimeZone("UTC")) + final String utcTime = sdf.format(new Date()) + return utcTime } public void toggleSuccessIndicator(DelegateExecution execution){ diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy index 449f4e3222..c30d807bf3 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -53,7 +53,7 @@ import org.onap.so.utils.TargetEntity class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { - private static final Logger logger = LoggerFactory.getLogger( SDNCAdapterRestV1.class); + private static final Logger logger = LoggerFactory.getLogger( SDNCAdapterRestV1.class) ExceptionUtil exceptionUtil = new ExceptionUtil() @@ -88,7 +88,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { String msg = getProcessKey(execution) + ': mso:adapters:sdnc:rest:endpoint URN mapping is not defined' logger.debug(msg) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -109,7 +109,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { String msg = getProcessKey(execution) + ': no sdncRequestId in ' + requestType logger.debug(msg) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -124,7 +124,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { String msg = getProcessKey(execution) + ': no bpNotificationUrl in ' + requestType logger.debug(msg) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -141,7 +141,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType logger.debug(msg) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -157,7 +157,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { logger.debug(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined") logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) } else { try { def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution)) @@ -166,7 +166,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { logger.debug(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter") logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter", - "BPMN", ErrorCode.UnknownError.getValue(), ex); + "BPMN", ErrorCode.UnknownError.getValue(), ex) } } @@ -176,7 +176,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { String timeout = jsonUtil.getJsonValue(request, requestType + ".bpTimeout") // in addition to null/empty, also need to verify that the timer value is a valid duration "P[n]T[n]H|M|S" - String timerRegex = "PT[0-9]+[HMS]"; + String timerRegex = "PT[0-9]+[HMS]" if (timeout == null || timeout.isEmpty() || !timeout.matches(timerRegex)) { logger.debug(getProcessKey(execution) + ': preProcessRequest(): null/empty/invalid bpTimeout value. Using "mso.adapters.sdnc.timeout"') timeout = UrnPropertiesReader.getVariable("mso.adapters.sdnc.timeout", execution) @@ -197,7 +197,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { String msg = 'Caught exception in ' + method + ": " + e logger.debug(msg) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } } @@ -221,7 +221,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { String sdncAdapterRequest = execution.getVariable(prefix + 'sdncAdapterRequest') logger.debug("SDNC Rest Request is: " + sdncAdapterRequest) - URL url = new URL(sdncAdapterUrl); + URL url = new URL(sdncAdapterUrl) HttpClient httpClient = new HttpClientFactory().newJsonClient(url, TargetEntity.SDNC_ADAPTER) httpClient.addAdditionalHeader("X-ONAP-RequestID", execution.getVariable("mso-request-id")) @@ -245,7 +245,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { String msg = 'Unsupported HTTP method "' + sdncAdapterMethod + '" in ' + method + ": " + e logger.debug(msg) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -259,7 +259,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { String msg = 'Caught exception in ' + method + ": " + e logger.debug(msg, e) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } } @@ -330,7 +330,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { } // Note: the mapping function handles a null or empty responseCode - int mappedResponseCode = Integer.parseInt(exceptionUtil.MapSDNCResponseCodeToErrorCode(responseCode)); + int mappedResponseCode = Integer.parseInt(exceptionUtil.MapSDNCResponseCodeToErrorCode(responseCode)) exceptionUtil.buildWorkflowException(execution, mappedResponseCode, "Received " + responseType + " from SDNCAdapter:" + info) } catch (Exception e) { @@ -370,7 +370,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { String msg = 'Caught exception in ' + method + ": " + e logger.debug(msg) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } } @@ -396,12 +396,12 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { String msg = 'Caught exception in ' + method + ": " + e logger.debug(msg) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } } public Logger getLogger() { - return logger; + return logger } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy index 62c7bb5adf..ba5145d19b 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -51,7 +51,7 @@ import org.slf4j.LoggerFactory * any non-final response received from SDNC. */ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { - private static final Logger logger = LoggerFactory.getLogger( SDNCAdapterRestV2.class); + private static final Logger logger = LoggerFactory.getLogger( SDNCAdapterRestV2.class) ExceptionUtil exceptionUtil = new ExceptionUtil() @@ -87,7 +87,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { String msg = getProcessKey(execution) + ': mso:adapters:sdnc:rest:endpoint URN mapping is not defined' logger.debug(msg) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -108,7 +108,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { String msg = getProcessKey(execution) + ': no sdncRequestId in ' + requestType logger.debug(msg) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -123,7 +123,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { String msg = getProcessKey(execution) + ': no bpNotificationUrl in ' + requestType logger.debug(msg) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -134,7 +134,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType logger.debug(msg) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } @@ -153,7 +153,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { logger.debug(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined") logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) } else { try { def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution)) @@ -162,7 +162,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { logger.debug(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter") logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter", - "BPMN", ErrorCode.UnknownError.getValue(), ex); + "BPMN", ErrorCode.UnknownError.getValue(), ex) } } @@ -172,7 +172,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { String timeout = jsonUtil.getJsonValue(request, requestType + ".bpTimeout") // in addition to null/empty, also need to verify that the timer value is a valid duration "P[n]T[n]H|M|S" - String timerRegex = "PT[0-9]+[HMS]"; + String timerRegex = "PT[0-9]+[HMS]" if (timeout == null || timeout.isEmpty() || !timeout.matches(timerRegex)) { logger.debug(getProcessKey(execution) + ': preProcessRequest(): null/empty/invalid bpTimeout value. Using "mso.adapters.sdnc.timeout"') timeout = UrnPropertiesReader.getVariable("mso.adapters.sdnc.timeout", execution) @@ -193,7 +193,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { String msg = 'Caught exception in ' + method + ": " + e logger.debug(msg) logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + ErrorCode.UnknownError.getValue()) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } } @@ -297,6 +297,6 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { } public Logger getLogger() { - return logger; + return logger } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/db/RequestsDbListenerRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/db/RequestsDbListenerRunner.java index 68cda5c22b..69151ff74f 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/db/RequestsDbListenerRunner.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/db/RequestsDbListenerRunner.java @@ -27,9 +27,9 @@ import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import org.onap.so.bpmn.common.BuildingBlockExecution; -import org.onap.so.bpmn.common.listener.ListenerRunner; import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulatorListenerRunner; import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.listener.ListenerRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulatorListenerRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulatorListenerRunner.java index 5f4dc871fb..ea7de687ee 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulatorListenerRunner.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulatorListenerRunner.java @@ -27,8 +27,8 @@ import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import org.onap.so.bpmn.common.BuildingBlockExecution; -import org.onap.so.bpmn.common.listener.ListenerRunner; import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; +import org.onap.so.listener.ListenerRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/FlowValidatorRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/FlowValidatorRunner.java index 040522b576..02cddf3655 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/FlowValidatorRunner.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/FlowValidatorRunner.java @@ -28,9 +28,11 @@ import org.camunda.bpm.engine.delegate.DelegateExecution; import org.javatuples.Pair; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.common.DelegateExecutionImpl; -import org.onap.so.bpmn.common.listener.ListenerRunner; +import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.listener.ListenerRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -47,6 +49,9 @@ public abstract class FlowValidatorRunner<S extends FlowValidator, E extends Flo private static Logger logger = LoggerFactory.getLogger(FlowValidatorRunner.class); + @Autowired + protected ExceptionBuilder exceptionBuilder; + protected List<S> preFlowValidators; protected List<E> postFlowValidators; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/InstanceResourceList.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/InstanceResourceList.java index b1173bbf95..3a4df68f02 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/InstanceResourceList.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/InstanceResourceList.java @@ -68,7 +68,7 @@ public class InstanceResourceList { public static List<Resource> getInstanceResourceList(final VnfResource vnfResource, final String uuiRequest) { - List<Resource> sequencedResourceList = new ArrayList<Resource>(); + List<Resource> sequencedResourceList = new ArrayList<>(); Gson gson = new Gson(); JsonObject servJsonObject = gson.fromJson(uuiRequest, JsonObject.class); JsonObject reqInputJsonObj = servJsonObject.getAsJsonObject("service").getAsJsonObject("parameters") @@ -108,11 +108,16 @@ public class InstanceResourceList { sequencedResourceList.add(vnfResource); } + // check if the resource contains vf-module + if (vnfResource != null && vnfResource.getVfModules() != null) { + sequencedResourceList.addAll(vnfResource.getVfModules()); + } + return sequencedResourceList; } private static List<Resource> getGroupResourceInstanceList(VnfResource vnfResource, JsonObject vfObj) { - List<Resource> sequencedResourceList = new ArrayList<Resource>(); + List<Resource> sequencedResourceList = new ArrayList<>(); if (vnfResource.getGroupOrder() != null && !StringUtils.isEmpty(vnfResource.getGroupOrder())) { String[] grpSequence = vnfResource.getGroupOrder().split(","); for (String grpType : grpSequence) { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/CryptoHandler.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/CryptoHandler.java deleted file mode 100644 index 5c0406cc9e..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/CryptoHandler.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.bpmn.common.util; - -import java.io.IOException; -import java.io.InputStream; -import java.security.GeneralSecurityException; -import java.util.Properties; -import org.onap.so.utils.CryptoUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class CryptoHandler implements ICryptoHandler { - private static final Logger logger = LoggerFactory.getLogger(CryptoHandler.class); - private static final String GENERAL_SECURITY_EXCEPTION_PREFIX = "GeneralSecurityException :"; - private static final String MSO_KEY = "aa3871669d893c7fb8abbcda31b88b4f"; - private static final String PROPERTY_KEY = "mso.AaiEncrypted.Pwd"; - - @Override - public String getMsoAaiPassword() { - Properties keyProp = new Properties(); - try { - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - InputStream rs = cl.getResourceAsStream("urn.properties"); - keyProp.load(rs); - rs.close(); - return CryptoUtils.decrypt((String) keyProp.get(PROPERTY_KEY), MSO_KEY); - } catch (GeneralSecurityException | IOException e) { - logger.error(GENERAL_SECURITY_EXCEPTION_PREFIX + e.getMessage(), e); - return null; - } - } - - - @Override - public String encryptMsoPassword(String plainMsoPwd) { - try { - return CryptoUtils.encrypt(plainMsoPwd, MSO_KEY); - } catch (GeneralSecurityException e) { - logger.error(GENERAL_SECURITY_EXCEPTION_PREFIX + e.getMessage(), e); - return null; - } - } - - @Override - public String decryptMsoPassword(String encryptedPwd) { - try { - return CryptoUtils.decrypt(encryptedPwd, MSO_KEY); - } catch (GeneralSecurityException e) { - logger.error(GENERAL_SECURITY_EXCEPTION_PREFIX + e.getMessage(), e); - return null; - } - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/Metadata.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/Metadata.java index f56fad3bcf..84b162e1a2 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/Metadata.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/Metadata.java @@ -31,7 +31,7 @@ public class Metadata implements Serializable { private static final long serialVersionUID = 4981393122007858950L; @JsonProperty("metadatum") - private List<Metadatum> metadatum = new ArrayList<Metadatum>(); + private List<Metadatum> metadatum = new ArrayList<>(); public List<Metadatum> getMetadatum() { return metadatum; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java index a5eb9d86a7..96a6ab7bd2 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java @@ -36,8 +36,6 @@ public class AggregateRoute implements Serializable, ShallowCopy<AggregateRoute> @Id @JsonProperty("route-id") private String routeId; - @JsonProperty("route-name") - private String routeName; @JsonProperty("network-start-address") private String networkStartAddress; @JsonProperty("cidr-mask") @@ -54,14 +52,6 @@ public class AggregateRoute implements Serializable, ShallowCopy<AggregateRoute> this.routeId = routeId; } - public String getRouteName() { - return routeName; - } - - public void setRouteName(String routeName) { - this.routeName = routeName; - } - public String getNetworkStartAddress() { return networkStartAddress; } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java index 841546b3b1..ebf722ef74 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java @@ -133,7 +133,7 @@ public class GenericVnf implements Serializable, ShallowCopy<GenericVnf> { @JsonProperty("model-info-generic-vnf") private ModelInfoGenericVnf modelInfoGenericVnf; @JsonProperty("instance-groups") - private List<InstanceGroup> instanceGroups = new ArrayList<InstanceGroup>(); + private List<InstanceGroup> instanceGroups = new ArrayList<>(); @JsonProperty("call-homing") private Boolean callHoming; @JsonProperty("nf-function") diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LInterface.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LInterface.java index 387d191409..db2785902a 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LInterface.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LInterface.java @@ -65,15 +65,15 @@ public class LInterface implements Serializable, ShallowCopy<LInterface> { @JsonProperty("allowed-address-pairs") private String allowedAddressPairs; @JsonProperty("vlans") - private List<Vlan> vlans = new ArrayList<Vlan>(); + private List<Vlan> vlans = new ArrayList<>(); @JsonProperty("sriov-vfs") - private List<SriovVf> sriovVfs = new ArrayList<SriovVf>(); + private List<SriovVf> sriovVfs = new ArrayList<>(); @JsonProperty("l-interfaces") - private List<LInterface> lInterfaces = new ArrayList<LInterface>(); + private List<LInterface> lInterfaces = new ArrayList<>(); @JsonProperty("l3-interface-ipv4-address-list") - private List<L3InterfaceIpv4AddressList> l3InterfaceIpv4AddressList = new ArrayList<L3InterfaceIpv4AddressList>(); + private List<L3InterfaceIpv4AddressList> l3InterfaceIpv4AddressList = new ArrayList<>(); @JsonProperty("l3-interface-ipv6-address-list") - private List<L3InterfaceIpv6AddressList> l3InterfaceIpv6AddressList = new ArrayList<L3InterfaceIpv6AddressList>(); + private List<L3InterfaceIpv6AddressList> l3InterfaceIpv6AddressList = new ArrayList<>(); public String getInterfaceName() { return interfaceName; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PServer.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PServer.java index d0bf1f588b..f3e28faf44 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PServer.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PServer.java @@ -41,9 +41,9 @@ public class PServer implements Serializable, ShallowCopy<PServer> { @JsonProperty("hostname") private String hostname; @JsonProperty("physical-links") - private List<PhysicalLink> physicalLinks = new ArrayList<PhysicalLink>(); // TODO techincally there is a pInterface - // between (pserver <--> physical-link) - // but dont really need that pojo + private List<PhysicalLink> physicalLinks = new ArrayList<>(); // TODO techincally there is a pInterface + // between (pserver <--> physical-link) + // but dont really need that pojo public String getPserverId() { return pserverId; 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 0803bed574..6cc8aa368c 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 @@ -79,7 +79,7 @@ public class ServiceInstance implements Serializable, ShallowCopy<ServiceInstanc @JsonProperty("instance-groups") private List<InstanceGroup> instanceGroups = new ArrayList<>(); @JsonProperty("service-proxies") - private List<ServiceProxy> serviceProxies = new ArrayList<ServiceProxy>(); + private List<ServiceProxy> serviceProxies = new ArrayList<>(); public void setServiceProxies(List<ServiceProxy> serviceProxies) { this.serviceProxies = serviceProxies; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceSubscription.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceSubscription.java index 05199b7f37..b677b1efd0 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceSubscription.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceSubscription.java @@ -41,7 +41,7 @@ public class ServiceSubscription implements Serializable, ShallowCopy<ServiceSub @JsonProperty("temp-ub-sub-account-id") private String tempUbSubAccountId; @JsonProperty("service-instances") - private List<ServiceInstance> serviceInstances = new ArrayList<ServiceInstance>(); + private List<ServiceInstance> serviceInstances = new ArrayList<>(); public String getServiceType() { return serviceType; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vlan.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vlan.java index 6951a23630..8c0db18d80 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vlan.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vlan.java @@ -62,9 +62,9 @@ public class Vlan implements Serializable, ShallowCopy<Vlan> { @JsonProperty("is-ip-unnumbered") private Boolean isIpUnnumbered; @JsonProperty("l3-interface-ipv4-address-list") - private List<L3InterfaceIpv4AddressList> l3InterfaceIpv4AddressList = new ArrayList<L3InterfaceIpv4AddressList>(); + private List<L3InterfaceIpv4AddressList> l3InterfaceIpv4AddressList = new ArrayList<>(); @JsonProperty("l3-interface-ipv6-address-list") - private List<L3InterfaceIpv6AddressList> l3InterfaceIpv6AddressList = new ArrayList<L3InterfaceIpv6AddressList>(); + private List<L3InterfaceIpv6AddressList> l3InterfaceIpv6AddressList = new ArrayList<>(); public String getVlanInterface() { return vlanInterface; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBondingLink.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBondingLink.java index 4ee8213e59..4e5b3557d8 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBondingLink.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBondingLink.java @@ -41,10 +41,10 @@ public class VpnBondingLink implements Serializable, ShallowCopy<VpnBondingLink> private String vpnBondingLinkId; @JsonProperty("configurations") - private List<Configuration> configurations = new ArrayList<Configuration>(); + private List<Configuration> configurations = new ArrayList<>(); @JsonProperty("service-proxies") - private List<ServiceProxy> serviceProxies = new ArrayList<ServiceProxy>(); + private List<ServiceProxy> serviceProxies = new ArrayList<>(); public String getVpnBondingLinkId() { return vpnBondingLinkId; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/License.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/License.java index c9f7e5e948..93d85daad1 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/License.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/License.java @@ -34,9 +34,9 @@ public class License implements Serializable { private static final long serialVersionUID = 2345786874755685318L; @JsonProperty("entitlement-pool-uuids") - private List<String> entitlementPoolUuids = new ArrayList<String>(); + private List<String> entitlementPoolUuids = new ArrayList<>(); @JsonProperty("license-key-group-uuids") - private List<String> licenseKeyGroupUuids = new ArrayList<String>(); + private List<String> licenseKeyGroupUuids = new ArrayList<>(); public List<String> getEntitlementPoolUuids() { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java index 573925ff3f..ea48c78dc0 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java @@ -30,6 +30,7 @@ import java.util.Map; import java.util.Optional; import org.modelmapper.ModelMapper; import org.modelmapper.convention.MatchingStrategies; +import org.onap.so.bpmn.servicedecomposition.bbobjects.AggregateRoute; import org.onap.so.bpmn.servicedecomposition.bbobjects.AllottedResource; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.bpmn.servicedecomposition.bbobjects.Collection; @@ -131,6 +132,10 @@ public class BBInputSetupMapperLayer { return modelMapper.map(aaiSegmentationAssignment, SegmentationAssignment.class); } + protected AggregateRoute mapAAIAggregateRoute(org.onap.aai.domain.yang.AggregateRoute aaiAggregateRoute) { + return modelMapper.map(aaiAggregateRoute, AggregateRoute.class); + } + protected CtagAssignment mapAAICtagAssignment(org.onap.aai.domain.yang.CtagAssignment aaiCtagAssignment) { return modelMapper.map(aaiCtagAssignment, CtagAssignment.class); } @@ -262,10 +267,21 @@ public class BBInputSetupMapperLayer { mapAllSubnetsIntoL3Network(aaiL3Network, network); mapAllCtagAssignmentsIntoL3Network(aaiL3Network, network); mapAllSegmentationAssignmentsIntoL3Network(aaiL3Network, network); + mapAllAggregateRoutesIntoL3Network(aaiL3Network, network); network.setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(aaiL3Network.getOrchestrationStatus())); return network; } + protected void mapAllAggregateRoutesIntoL3Network(org.onap.aai.domain.yang.L3Network aaiL3Network, + L3Network network) { + if (aaiL3Network.getAggregateRoutes() != null) { + for (org.onap.aai.domain.yang.AggregateRoute aaiAggregateRoute : aaiL3Network.getAggregateRoutes() + .getAggregateRoute()) { + network.getAggregateRoutes().add(mapAAIAggregateRoute(aaiAggregateRoute)); + } + } + } + protected void mapAllSegmentationAssignmentsIntoL3Network(org.onap.aai.domain.yang.L3Network aaiL3Network, L3Network network) { if (aaiL3Network.getSegmentationAssignments() != null) { 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 09a5424d47..be53e505ac 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 @@ -104,6 +104,7 @@ public class ExecuteBuildingBlockRainyDay { } } catch (Exception ex) { // keep default serviceType value + logger.error("Exception in serviceType retrivel", ex); } String vnfType = ASTERISK; try { @@ -115,6 +116,7 @@ public class ExecuteBuildingBlockRainyDay { } } catch (Exception ex) { // keep default vnfType value + logger.error("Exception in vnfType retrivel", ex); } String errorCode = ASTERISK; @@ -122,12 +124,14 @@ public class ExecuteBuildingBlockRainyDay { errorCode = "" + workflowException.getErrorCode(); } catch (Exception ex) { // keep default errorCode value + logger.error("Exception in errorCode retrivel", ex); } try { errorCode = "" + (String) execution.getVariable("WorkflowExceptionCode"); } catch (Exception ex) { // keep default errorCode value + logger.error("Exception in errorCode retrivel", ex); } String workStep = ASTERISK; @@ -135,6 +139,7 @@ public class ExecuteBuildingBlockRainyDay { workStep = workflowException.getWorkStep(); } catch (Exception ex) { // keep default workStep value + logger.error("Exception in workStep retrivel", ex); } String errorMessage = ASTERISK; @@ -142,6 +147,7 @@ public class ExecuteBuildingBlockRainyDay { errorMessage = workflowException.getErrorMessage(); } catch (Exception ex) { // keep default workStep value + logger.error("Exception in errorMessage retrivel", ex); } String serviceRole = ASTERISK; @@ -177,14 +183,14 @@ public class ExecuteBuildingBlockRainyDay { logger.error("Failed to update Request Db Infra Active Requests with Retry Status", ex); } } - if (handlingCode.equals("RollbackToAssigned") && !aLaCarte) { + if ("RollbackToAssigned".equals(handlingCode) && !aLaCarte) { handlingCode = "Rollback"; } if (handlingCode.startsWith("Rollback")) { String targetState = ""; - if (handlingCode.equalsIgnoreCase("RollbackToAssigned")) { + if ("RollbackToAssigned".equalsIgnoreCase(handlingCode)) { targetState = Status.ROLLED_BACK_TO_ASSIGNED.toString(); - } else if (handlingCode.equalsIgnoreCase("RollbackToCreated")) { + } else if ("RollbackToCreated".equalsIgnoreCase(handlingCode)) { targetState = Status.ROLLED_BACK_TO_CREATED.toString(); } else { targetState = Status.ROLLED_BACK.toString(); @@ -204,7 +210,7 @@ public class ExecuteBuildingBlockRainyDay { int envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries)); execution.setVariable("maxRetries", envMaxRetries); } catch (Exception ex) { - logger.error("Could not read maxRetries from config file. Setting max to 5 retries"); + logger.error("Could not read maxRetries from config file. Setting max to 5 retries", ex); execution.setVariable("maxRetries", 5); } } @@ -247,8 +253,7 @@ public class ExecuteBuildingBlockRainyDay { request.setLastModifiedBy("CamundaBPMN"); requestDbclient.updateInfraActiveRequests(request); } catch (Exception e) { - logger.error("Failed to update Request db with extSystemErrorSource or rollbackExtSystemErrorSource: " - + e.getMessage()); + logger.error("Failed to update Request db with extSystemErrorSource or rollbackExtSystemErrorSource: ", e); } } 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 b2dbd97bfc..aee28cae00 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 @@ -90,7 +90,6 @@ public class ExtractPojosForBB { result = lookupObjectInList(serviceInstance.getConfigurations(), value); break; case VPN_ID: - serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); result = lookupObjectInList(gBBInput.getCustomer().getVpnBindings(), value); break; case VPN_BONDING_LINK_ID: @@ -107,8 +106,9 @@ public class ExtractPojosForBB { } catch (BBObjectNotFoundException e) { // re-throw parent object not found throw e; } catch (Exception e) { // convert all other exceptions to object not found - logger.warn("BBObjectNotFoundException in ExtractPojosForBB", - "BBObject " + key + " was not found in " + "gBBInput using reference value: " + value); + logger.warn( + "BBObjectNotFoundException in ExtractPojosForBB, BBObject {} was not found in gBBInput using reference value: {} {}", + key, value, e); throw new BBObjectNotFoundException(key, value); } @@ -119,13 +119,8 @@ public class ExtractPojosForBB { } } - protected <T> Optional<T> lookupObject(Object obj, String value) throws IllegalAccessException, - IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - return findValue(obj, value); - } - - protected <T> Optional<T> lookupObjectInList(List<?> list, String value) throws IllegalAccessException, - IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { + protected <T> Optional<T> lookupObjectInList(List<?> list, String value) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Optional<T> result = Optional.empty(); for (Object obj : list) { result = findValue(obj, value); @@ -137,8 +132,8 @@ public class ExtractPojosForBB { } - protected <T> Optional<T> findValue(Object obj, String value) throws IllegalAccessException, - IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { + protected <T> Optional<T> findValue(Object obj, String value) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { for (Field field : obj.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(Id.class)) { String fieldName = field.getName(); diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnf.java index b2e6ead36b..ad94421e5a 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnf.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnf.java @@ -48,7 +48,7 @@ public class ConfigAssignPropertiesForPnf { private String pnfCustomizationUuid; @JsonIgnore - private Map<String, Object> userParam = new HashMap<String, Object>(); + private Map<String, Object> userParam = new HashMap<>(); public String getServiceInstanceId() { return serviceInstanceId; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnf.java index 592b349215..acd60a4004 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnf.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnf.java @@ -48,7 +48,7 @@ public class ConfigAssignPropertiesForVnf { private String vnfCustomizationUuid; @JsonIgnore - private Map<String, Object> userParam = new HashMap<String, Object>(); + private Map<String, Object> userParam = new HashMap<>(); public String getServiceInstanceId() { return serviceInstanceId; diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/BuildingBlockValidatorRunnerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/BuildingBlockValidatorRunnerTest.java index 2c0377d11c..f4fe6d7158 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/BuildingBlockValidatorRunnerTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/BuildingBlockValidatorRunnerTest.java @@ -47,7 +47,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {ValidationConfig.class}) -public class BuildingBlockValidatorRunnerTest { +public class BuildingBlockValidatorRunnerTest extends BuildingBlockValidatorRunner { @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/WorkflowValidatorRunnerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/WorkflowValidatorRunnerTest.java index 0143e567af..596eced1d1 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/WorkflowValidatorRunnerTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/WorkflowValidatorRunnerTest.java @@ -45,7 +45,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {ValidationConfig.class}) -public class WorkflowValidatorRunnerTest { +public class WorkflowValidatorRunnerTest extends WorkflowValidatorRunner { @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyDisabledValidator.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyDisabledValidator.java index af64ed2de6..544d370a3c 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyDisabledValidator.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyDisabledValidator.java @@ -23,8 +23,8 @@ package org.onap.so.bpmn.common.listener.validation; import java.util.Collections; import java.util.Optional; import org.onap.so.bpmn.common.BuildingBlockExecution; -import org.onap.so.bpmn.common.listener.Skip; import org.onap.so.bpmn.common.listener.validation.PreBuildingBlockValidator; +import org.onap.so.listener.Skip; import org.springframework.stereotype.Component; @Component diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/ValidationConfig.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/ValidationConfig.java index 068f433dd5..a3692a50b7 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/ValidationConfig.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/ValidationConfig.java @@ -21,13 +21,13 @@ package org.onap.so.bpmn.common.listener.validation; import org.onap.so.bpmn.common.DefaultToShortClassNameBeanNameGenerator; -import org.onap.so.bpmn.common.listener.ListenerRunner; import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.listener.ListenerRunner; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan(basePackageClasses = {ExceptionBuilder.class, ListenerRunner.class}, +@ComponentScan(basePackageClasses = {ExceptionBuilder.class, ListenerRunner.class, WorkflowValidatorRunner.class}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class) public class ValidationConfig { diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java deleted file mode 100644 index 273e9f0e3c..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.bpmn.common.util; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class CryptoHandlerTest { - private static final String plainPswd = "mso0206"; - private CryptoHandler cryptoHandler; - private static String encryptPwd; - - - @Before - public void setup() { - cryptoHandler = new CryptoHandler(); - encryptPwd = cryptoHandler.encryptMsoPassword(plainPswd); - } - - @Test - @Ignore // ignored until we can mock the properties file. - public void getMsoAaiPasswordTest() { - assertEquals(plainPswd, cryptoHandler.getMsoAaiPassword()); - } - - @Test - public void encryptMsoPasswordTest() { - assertEquals(plainPswd, cryptoHandler.decryptMsoPassword(cryptoHandler.encryptMsoPassword(plainPswd))); - } - - @Test - public void decryptMsoPasswordTest() { - assertEquals(plainPswd, cryptoHandler.decryptMsoPassword(encryptPwd)); - } -} diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/aaiL3NetworkInputWithSubnets.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/aaiL3NetworkInputWithSubnets.json index 418396f290..9b32a4c446 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/aaiL3NetworkInputWithSubnets.json +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/aaiL3NetworkInputWithSubnets.json @@ -69,5 +69,15 @@ } ] }, + "aggregateRoutes": { + "aggregateRoute": [ + { + "routeId": "routeId", + "networkStartAddress": "10.80.12.0", + "cidrMask": "23", + "ipVersion": "4" + } + ] + }, "relationshipList": null }
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/l3NetworkExpectedWithSubnet.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/l3NetworkExpectedWithSubnet.json index ccefe195c9..f65fe17a2e 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/l3NetworkExpectedWithSubnet.json +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/l3NetworkExpectedWithSubnet.json @@ -52,5 +52,13 @@ "segmentation-id": "segmentationId" } ], + "aggregate-routes": [ + { + "route-id": "routeId", + "network-start-address": "10.80.12.0", + "cidr-mask": "23", + "ip-version": "4" + } + ], "model-info-network": null } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java index 21847e1c4e..7d5bb0dcf1 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java @@ -33,7 +33,7 @@ public class WorkflowException implements Serializable { private final int errorCode; private final String errorMessage; private final String workStep; - private transient TargetEntities extSystemErrorSource; + private TargetEntities extSystemErrorSource; /** * Constructor diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java index 093fba089d..050a2af06a 100644 --- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java +++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java @@ -136,8 +136,8 @@ public class MSOInfrastructureApplication { deploymentBuilder.addString(workflowName, workflowBody); } deploymentBuilder.enableDuplicateFiltering(true); - deploymentBuilder.deploy(); } + deploymentBuilder.deploy(); } } catch (Exception e) { logger.warn("Unable to deploy custom workflows, " + e.getMessage()); diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSDNCNetworkResource.groovy index 573cd0a533..b855e936d0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSDNCNetworkResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSDNCNetworkResource.groovy @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -45,7 +45,7 @@ import org.slf4j.LoggerFactory * flow for SDNC Network Resource Activate */ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor { - private static final Logger logger = LoggerFactory.getLogger( ActivateSDNCNetworkResource.class); + private static final Logger logger = LoggerFactory.getLogger( ActivateSDNCNetworkResource.class) String Prefix = "ACTSDNCRES_" @@ -135,7 +135,7 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor { <statusDescription>${msoUtils.xmlEscape(statusDescription)}</statusDescription> </ns:updateResourceOperationStatus> </soapenv:Body> - </soapenv:Envelope>"""; + </soapenv:Envelope>""" setProgressUpdateVariables(execution, body) } @@ -148,12 +148,12 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor { String customizeResourceParam(String networkInputParametersJson) { List<Map<String, Object>> paramList = new ArrayList() - JSONObject jsonObject = new JSONObject(networkInputParametersJson); + JSONObject jsonObject = new JSONObject(networkInputParametersJson) Iterator iterator = jsonObject.keys() while (iterator.hasNext()) { String key = iterator.next() HashMap<String, String> hashMap = new HashMap() - hashMap.put("name", key); + hashMap.put("name", key) hashMap.put("value", jsonObject.get(key)) paramList.add(hashMap) } @@ -186,7 +186,7 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor { String serviceModelVersion = resourceInputObj.getServiceModelInfo().getModelVersion() String serviceModelName = resourceInputObj.getServiceModelInfo().getModelName() String globalCustomerId = resourceInputObj.getGlobalSubscriberId() - String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid(); + String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid() String modelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() String modelUuid = resourceInputObj.getResourceModelInfo().getModelUuid() String modelName = resourceInputObj.getResourceModelInfo().getModelName() @@ -478,4 +478,4 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor { } logger.info("exited send sync Resp") } -}
\ No newline at end of file +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CompareModelofE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CompareModelofE2EServiceInstance.groovy index 608bf66da9..df11549ff4 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CompareModelofE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CompareModelofE2EServiceInstance.groovy @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -19,9 +19,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.infrastructure.scripts; +package org.onap.so.bpmn.infrastructure.scripts -import static org.apache.commons.lang3.StringUtils.*; +import static org.apache.commons.lang3.StringUtils.* import org.apache.commons.lang3.* import org.camunda.bpm.engine.delegate.BpmnError @@ -55,7 +55,7 @@ import groovy.json.* * @param - WorkflowException */ public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcessor { - private static final Logger logger = LoggerFactory.getLogger( CompareModelofE2EServiceInstance.class); + private static final Logger logger = LoggerFactory.getLogger( CompareModelofE2EServiceInstance.class) String Prefix="CMPMDSI_" private static final String DebugFlag = "isDebugEnabled" @@ -64,7 +64,7 @@ public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcess JsonUtils jsonUtil = new JsonUtils() VidUtils vidUtils = new VidUtils() - public void preProcessRequest (DelegateExecution execution) { + void preProcessRequest (DelegateExecution execution) { execution.setVariable("prefix",Prefix) String msg = "" @@ -128,7 +128,7 @@ public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcess execution.setVariable("operationType", "CompareModel") } catch (BpmnError e) { - throw e; + throw e } catch (Exception ex){ msg = "Exception in preProcessRequest " + ex.getMessage() logger.info(msg) @@ -137,7 +137,7 @@ public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcess logger.trace("Exit preProcessRequest ") } - public void sendSyncResponse (DelegateExecution execution) { + void sendSyncResponse (DelegateExecution execution) { logger.trace("sendSyncResponse ") try { @@ -155,7 +155,7 @@ public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcess logger.trace("Exit sendSyncResopnse ") } - public void sendSyncError (DelegateExecution execution) { + void sendSyncError (DelegateExecution execution) { logger.trace("sendSyncError ") try { @@ -182,7 +182,7 @@ public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcess } - public void prepareCompletionRequest (DelegateExecution execution) { + void prepareCompletionRequest (DelegateExecution execution) { logger.trace("prepareCompletion ") try { @@ -214,7 +214,7 @@ public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcess logger.trace("Exit prepareCompletionRequest ") } - public void prepareFalloutRequest(DelegateExecution execution){ + void prepareFalloutRequest(DelegateExecution execution){ logger.trace("prepareFalloutRequest ") try { diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy index 8bb48a203b..ced1b928fc 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -72,7 +72,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso JsonUtils jsonUtil = new JsonUtils() - private static final Logger logger = LoggerFactory.getLogger( Create3rdONAPE2EServiceInstance.class); + private static final Logger logger = LoggerFactory.getLogger( Create3rdONAPE2EServiceInstance.class) public void checkSPPartnerInfo (DelegateExecution execution) { logger.info(" ***** Started checkSPPartnerInfo *****") @@ -312,7 +312,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso // Put TP Link info into serviceParameters JSONObject inputParameters = new JSONObject(execution.getVariable(Prefix + "ServiceParameters")) if(inputParameters.has("remote-access-provider-id")) { - Map<String, Object> crossTPs = new HashMap<String, Object>(); + Map<String, Object> crossTPs = new HashMap<String, Object>() crossTPs.put("local-access-provider-id", inputParameters.get("remote-access-provider-id")) crossTPs.put("local-access-client-id", inputParameters.get("remote-access-client-id")) crossTPs.put("local-access-topology-id", inputParameters.get("remote-access-topology-id")) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy index 2abee7caaa..cae629fdf0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy @@ -7,7 +7,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -39,7 +39,7 @@ import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.AAIResourcesClient import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory -import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.ErrorCode import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.MessageEnum import org.slf4j.Logger @@ -56,7 +56,7 @@ public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor String Prefix="CRESI_" ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() - private static final Logger logger = LoggerFactory.getLogger( CreateCustomE2EServiceInstance.class); + private static final Logger logger = LoggerFactory.getLogger( CreateCustomE2EServiceInstance.class) public void preProcessRequest (DelegateExecution execution) { @@ -154,7 +154,7 @@ public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor //execution.setVariable("serviceInputParams", jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.userParams")) //execution.setVariable("failExists", true) } catch (BpmnError e) { - throw e; + throw e } catch (Exception ex){ msg = "Exception in preProcessRequest " + ex.getMessage() logger.debug(msg) @@ -332,7 +332,7 @@ public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor }catch(Exception e){ logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing prepareInitServiceOperationStatus.", "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); + ErrorCode.UnknownError.getValue(), "Exception is:\n" + e) execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage()) } logger.trace("finished prepareInitServiceOperationStatus") 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 bcd33530b1..4b3c1aa7b4 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 @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -55,7 +55,7 @@ import org.slf4j.LoggerFactory */ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { - private static final Logger logger = LoggerFactory.getLogger( CreateSDNCNetworkResource.class); + private static final Logger logger = LoggerFactory.getLogger( CreateSDNCNetworkResource.class) String Prefix="CRESDNCRES_" ExceptionUtil exceptionUtil = new ExceptionUtil() @@ -120,20 +120,20 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { } String customizeResourceParam(String networkInputParametersJson) { - List<Map<String, Object>> paramList = new ArrayList(); - JSONObject jsonObject = new JSONObject(networkInputParametersJson); - Iterator iterator = jsonObject.keys(); + List<Map<String, Object>> paramList = new ArrayList() + JSONObject jsonObject = new JSONObject(networkInputParametersJson) + Iterator iterator = jsonObject.keys() while (iterator.hasNext()) { - String key = iterator.next(); - HashMap<String, String> hashMap = new HashMap(); - hashMap.put("name", key); + String key = iterator.next() + HashMap<String, String> hashMap = new HashMap() + hashMap.put("name", key) hashMap.put("value", jsonObject.get(key)) paramList.add(hashMap) } - Map<String, List<Map<String, Object>>> paramMap = new HashMap(); - paramMap.put("param", paramList); + Map<String, List<Map<String, Object>>> paramMap = new HashMap() + paramMap.put("param", paramList) - return new JSONObject(paramMap).toString(); + return new JSONObject(paramMap).toString() } private List<Metadatum> getMetaDatum(String customerId, @@ -347,7 +347,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { String serviceModelVersion = resourceInputObj.getServiceModelInfo().getModelVersion() String serviceModelName = resourceInputObj.getServiceModelInfo().getModelName() String globalCustomerId = resourceInputObj.getGlobalSubscriberId() - String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid(); + String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid() String modelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() String modelUuid = resourceInputObj.getResourceModelInfo().getModelUuid() String modelName = resourceInputObj.getResourceModelInfo().getModelName() @@ -357,7 +357,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { //here convert json string to xml string String netowrkInputParameters = XML.toString(new JSONObject(customizeResourceParam(networkInputParametersJson))) // 1. prepare assign topology via SDNC Adapter SUBFLOW call - String sdncTopologyCreateRequest = ""; + String sdncTopologyCreateRequest = "" String modelType = resourceInputObj.getResourceModelInfo().getModelType() @@ -641,7 +641,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { <statusDescription>${msoUtils.xmlEscape(statusDescription)}</statusDescription> </ns:updateResourceOperationStatus> </soapenv:Body> - </soapenv:Envelope>"""; + </soapenv:Envelope>""" setProgressUpdateVariables(execution, body) @@ -674,7 +674,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { <statusDescription>${msoUtils.xmlEscape(statusDescription)}</statusDescription> </ns:updateResourceOperationStatus> </soapenv:Body> - </soapenv:Envelope>"""; + </soapenv:Envelope>""" setProgressUpdateVariables(execution, body) } @@ -724,7 +724,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { try { String operationStatus = "finished" // RESTResponse for main flow - String vnfid=execution.getVariable("resourceInstanceId"); + String vnfid=execution.getVariable("resourceInstanceId") String resourceOperationResp = """{"operationStatus":"${operationStatus}","vnf-id":"${vnfid}"}""".trim() logger.debug(" sendSyncResponse to APIH:" + "\n" + resourceOperationResp) sendWorkflowResponse(execution, 202, resourceOperationResp) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy index 433a8d0bb9..901964f465 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * @@ -25,7 +25,7 @@ package org.onap.so.bpmn.infrastructure.scripts import org.onap.so.client.HttpClientFactory 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.aai.entities.uri.AAIUriFactory import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor @@ -44,7 +44,7 @@ import org.onap.so.utils.TargetEntity * flow for VFC Network Service Create */ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { - private static final Logger logger = LoggerFactory.getLogger( CreateVFCNSResource.class); + private static final Logger logger = LoggerFactory.getLogger( CreateVFCNSResource.class) ExceptionUtil exceptionUtil = new ExceptionUtil() @@ -77,7 +77,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { String globalSubscriberId = jsonUtil.getJsonValue(resourceInput, "globalSubscriberId") logger.info("globalSubscriberId:" + globalSubscriberId) //set local globalSubscriberId variable - execution.setVariable("globalSubscriberId", globalSubscriberId); + execution.setVariable("globalSubscriberId", globalSubscriberId) String serviceType = execution.getVariable("serviceType") logger.info("serviceType:" + serviceType) @@ -110,9 +110,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { "operationId":"${operationId}", "nodeTemplateUUID":"${nodeTemplateUUID}" }""" - execution.setVariable("nsOperationKey", nsOperationKey); + execution.setVariable("nsOperationKey", nsOperationKey) execution.setVariable("nsParameters", nsParameters) - execution.setVariable("nsServiceModelUUID", nsServiceModelUUID); + execution.setVariable("nsServiceModelUUID", nsServiceModelUUID) String vfcAdapterUrl = UrnPropertiesReader.getVariable("mso.adapters.vfc.rest.endpoint", execution) @@ -128,7 +128,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { execution.setVariable("vfcAdapterUrl", vfcAdapterUrl) } catch (BpmnError e) { - throw e; + throw e } catch (Exception ex){ msg = "Exception in preProcessRequest " + ex.getMessage() logger.info(msg) @@ -143,9 +143,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { public void createNetworkService(DelegateExecution execution) { logger.trace("createNetworkService ") String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl") - String nsOperationKey = execution.getVariable("nsOperationKey"); - String nsServiceModelUUID = execution.getVariable("nsServiceModelUUID"); - String nsParameters = execution.getVariable("nsParameters"); + String nsOperationKey = execution.getVariable("nsOperationKey") + String nsServiceModelUUID = execution.getVariable("nsServiceModelUUID") + String nsParameters = execution.getVariable("nsParameters") String nsServiceName = execution.getVariable("nsServiceName") String nsServiceDescription = execution.getVariable("nsServiceDescription") String locationConstraints = jsonUtil.getJsonValue(nsParameters, "locationConstraints") @@ -163,7 +163,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { Response apiResponse = postRequest(execution, vfcAdapterUrl + "/ns", reqBody) String returnCode = apiResponse.getStatus () String aaiResponseAsString = apiResponse.readEntity(String.class) - String nsInstanceId = ""; + String nsInstanceId = "" if(returnCode== "200" || returnCode == "201"){ nsInstanceId = jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId") } @@ -177,8 +177,8 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { public void instantiateNetworkService(DelegateExecution execution) { logger.trace("instantiateNetworkService ") String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl") - String nsOperationKey = execution.getVariable("nsOperationKey"); - String nsParameters = execution.getVariable("nsParameters"); + String nsOperationKey = execution.getVariable("nsOperationKey") + String nsParameters = execution.getVariable("nsParameters") String nsServiceName = execution.getVariable("nsServiceName") String nsServiceDescription = execution.getVariable("nsServiceDescription") String reqBody ="""{ @@ -192,7 +192,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { Response apiResponse = postRequest(execution, url, reqBody) String returnCode = apiResponse.getStatus() String aaiResponseAsString = apiResponse.readEntity(String.class) - String jobId = ""; + String jobId = "" if(returnCode== "200"|| returnCode == "201"){ jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId") } @@ -207,7 +207,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { logger.trace("queryNSProgress ") String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl") String jobId = execution.getVariable("jobId") - String nsOperationKey = execution.getVariable("nsOperationKey"); + String nsOperationKey = execution.getVariable("nsOperationKey") String url = vfcAdapterUrl + "/jobs/" + jobId Response apiResponse = postRequest(execution, url, nsOperationKey) String returnCode = apiResponse.getStatus() @@ -225,9 +225,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { */ public void timeDelay(DelegateExecution execution) { try { - Thread.sleep(5000); + Thread.sleep(5000) } catch(InterruptedException e) { - logger.error("Time Delay exception" + e.getMessage()); + logger.error("Time Delay exception" + e.getMessage()) } } @@ -252,7 +252,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { getAAIClient().connect(nsUri,relatedServiceUri) logger.info("NS relationship to Service added successfully") }catch(Exception e){ - logger.error("Exception occured while Creating NS relationship."+ e.getMessage()); + logger.error("Exception occured while Creating NS relationship."+ e.getMessage()) throw new BpmnError("MSOWorkflowException") } } @@ -268,7 +268,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { Response apiResponse = null try{ - URL url = new URL(urlString); + URL url = new URL(urlString) // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7' // user 'bepl' authHeader is the same with mso.db.auth @@ -282,7 +282,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { logger.debug("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class)) }catch(Exception e){ - logger.error("VFC Aatpter Post Call Exception:" + e.getMessage()); + logger.error("VFC Aatpter Post Call Exception:" + e.getMessage()) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "VFC Aatpter Post Call Exception") } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeActivateSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeActivateSDNCNetworkResource.groovy index 097a1be291..1a689d426c 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeActivateSDNCNetworkResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeActivateSDNCNetworkResource.groovy @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -42,7 +42,7 @@ import org.slf4j.LoggerFactory * flow for SDNC Network Resource Activate */ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor { - private static final Logger logger = LoggerFactory.getLogger( DeActivateSDNCNetworkResource.class); + private static final Logger logger = LoggerFactory.getLogger( DeActivateSDNCNetworkResource.class) String Prefix = "DEACTSDNCRES_" ExceptionUtil exceptionUtil = new ExceptionUtil() @@ -53,7 +53,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor MsoUtils msoUtils = new MsoUtils() - public void preProcessRequest(DelegateExecution execution) { + void preProcessRequest(DelegateExecution execution) { logger.info(" ***** Started preProcessRequest *****") @@ -96,7 +96,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor execution.setVariable("mso-request-id", requestId) execution.setVariable("mso-service-instance-id", resourceInputObj.getServiceInstanceId()) } catch (BpmnError e) { - throw e; + throw e } catch (Exception ex){ msg = "Exception in preProcessRequest " + ex.getMessage() logger.debug(msg) @@ -104,7 +104,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor } } - public void prepareSDNCRequest(DelegateExecution execution) { + void prepareSDNCRequest(DelegateExecution execution) { logger.info(" ***** Started prepareSDNCRequest *****") try { @@ -127,7 +127,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor String serviceModelVersion = resourceInputObj.getServiceModelInfo().getModelVersion() String serviceModelName = resourceInputObj.getServiceModelInfo().getModelName() String globalCustomerId = resourceInputObj.getGlobalSubscriberId() - String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid(); + String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid() String modelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() String modelUuid = resourceInputObj.getResourceModelInfo().getModelUuid() String modelName = resourceInputObj.getResourceModelInfo().getModelName() @@ -390,7 +390,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor logger.info(" ***** Exit prepareSDNCRequest *****") } - public void prepareUpdateAfterDeActivateSDNCResource(DelegateExecution execution) { + void prepareUpdateAfterDeActivateSDNCResource(DelegateExecution execution) { String resourceInput = execution.getVariable("resourceInput") ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) String operType = resourceInputObj.getOperationType() @@ -418,7 +418,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor <statusDescription>${msoUtils.xmlEscape(statusDescription)}</statusDescription> </ns:updateResourceOperationStatus> </soapenv:Body> - </soapenv:Envelope>"""; + </soapenv:Envelope>""" setProgressUpdateVariables(execution, body) } @@ -429,7 +429,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor execution.setVariable("CVFMI_updateResOperStatusRequest", body) } - public void postDeactivateSDNCCall(DelegateExecution execution) { + void postDeactivateSDNCCall(DelegateExecution execution) { logger.info(" ***** Started prepareSDNCRequest *****") String responseCode = execution.getVariable(Prefix + "sdncDeleteReturnCode") String responseObj = execution.getVariable(Prefix + "SuccessIndicator") @@ -438,7 +438,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor logger.info(" ***** Exit prepareSDNCRequest *****") } - public void sendSyncResponse(DelegateExecution execution) { + void sendSyncResponse(DelegateExecution execution) { logger.debug(" *** sendSyncResponse *** ") try { diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy index 64ae3dfbef..da486bb1c3 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -60,7 +60,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso JsonUtils jsonUtil = new JsonUtils() - private static final Logger logger = LoggerFactory.getLogger( Delete3rdONAPE2EServiceInstance.class); + private static final Logger logger = LoggerFactory.getLogger( Delete3rdONAPE2EServiceInstance.class) public void checkSPPartnerInfoFromAAI (DelegateExecution execution) { logger.info(" ***** Started checkSPPartnerInfo *****") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCustomE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCustomE2EServiceInstance.groovy index a9b1fdaac3..2a65ae97a2 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCustomE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCustomE2EServiceInstance.groovy @@ -8,7 +8,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * @@ -22,9 +22,9 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.infrastructure.scripts; +package org.onap.so.bpmn.infrastructure.scripts -import static org.apache.commons.lang3.StringUtils.*; +import static org.apache.commons.lang3.StringUtils.* import org.apache.commons.lang3.* import org.camunda.bpm.engine.delegate.BpmnError @@ -38,7 +38,7 @@ import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.bpmn.core.UrnPropertiesReader import org.slf4j.Logger import org.slf4j.LoggerFactory -import org.springframework.web.util.UriUtils; +import org.springframework.web.util.UriUtils import groovy.json.* @@ -52,7 +52,7 @@ public class DeleteCustomE2EServiceInstance extends AbstractServiceTaskProcessor ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() VidUtils vidUtils = new VidUtils() - private static final Logger logger = LoggerFactory.getLogger( DeleteCustomE2EServiceInstance.class); + private static final Logger logger = LoggerFactory.getLogger( DeleteCustomE2EServiceInstance.class) public void preProcessRequest (DelegateExecution execution) { execution.setVariable("prefix",Prefix) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy index 7c8b7eb7cc..61b1250522 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy @@ -67,7 +67,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { MsoUtils msoUtils = new MsoUtils() - public void preProcessRequest(DelegateExecution execution){ + void preProcessRequest(DelegateExecution execution){ logger.info(" ***** Started preProcessRequest *****") try { @@ -184,7 +184,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { * generate the nsOperationKey * generate the nsParameters */ - public void prepareSDNCRequest (DelegateExecution execution) { + void prepareSDNCRequest (DelegateExecution execution) { logger.info(" ***** Started prepareSDNCRequest *****") try { @@ -475,7 +475,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { execution.setVariable("CVFMI_updateResOperStatusRequest", body) } - public void prepareUpdateBeforeDeleteSDNCResource(DelegateExecution execution) { + void prepareUpdateBeforeDeleteSDNCResource(DelegateExecution execution) { logger.debug(" *** prepareUpdateBeforeDeleteSDNCResource *** ") String resourceInput = execution.getVariable(Prefix + "resourceInput"); ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) @@ -511,7 +511,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { } - public void prepareUpdateAfterDeleteSDNCResource(DelegateExecution execution) { + void prepareUpdateAfterDeleteSDNCResource(DelegateExecution execution) { logger.debug(" *** prepareUpdateAfterDeleteSDNCResource *** ") String resourceInput = execution.getVariable(Prefix + "resourceInput"); ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) @@ -546,7 +546,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { logger.debug(" ***** Exit prepareUpdateAfterDeleteSDNCResource *****") } - public void postDeleteSDNCCall(DelegateExecution execution){ + void postDeleteSDNCCall(DelegateExecution execution){ logger.info(" ***** Started postDeleteSDNCCall *****") String responseCode = execution.getVariable(Prefix + "sdncDeleteReturnCode") String responseObj = execution.getVariable(Prefix + "SuccessIndicator") @@ -555,7 +555,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { logger.info(" ***** Exit postDeleteSDNCCall *****") } - public void sendSyncResponse (DelegateExecution execution) { + void sendSyncResponse (DelegateExecution execution) { logger.debug( " *** sendSyncResponse *** ") try { diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVFCNSResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVFCNSResource.groovy index 9b269c734f..642609a970 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVFCNSResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVFCNSResource.groovy @@ -63,14 +63,14 @@ public class DeleteVFCNSResource extends AbstractServiceTaskProcessor { logger.info(" ***** end preProcessRequest *****") } - public void postProcessRequest (DelegateExecution execution) { + void postProcessRequest (DelegateExecution execution) { def isDebugEnabled = execution.getVariable("isDebugLogEnabled") logger.info(" ***** start postProcessRequest *****") logger.info(" ***** end postProcessRequest *****") } - public void sendSyncResponse (DelegateExecution execution) { + void sendSyncResponse (DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") logger.debug( " *** sendSyncResponse *** ") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy index fff2503308..324e6b42ba 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -19,9 +19,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.infrastructure.scripts; +package org.onap.so.bpmn.infrastructure.scripts -import static org.apache.commons.lang3.StringUtils.*; +import static org.apache.commons.lang3.StringUtils.* import org.onap.so.bpmn.core.domain.ServiceDecomposition import org.onap.so.bpmn.core.domain.Resource @@ -52,7 +52,7 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { String Prefix="DCMPMDV_" ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() - private static final Logger logger = LoggerFactory.getLogger( DoCompareModelVersions.class); + private static final Logger logger = LoggerFactory.getLogger( DoCompareModelVersions.class) public void preProcessRequest (DelegateExecution execution) { def isDebugEnabled = execution.getVariable("isDebugLogEnabled") @@ -196,8 +196,8 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { ServiceDecomposition serviceDecomposition_Target = execution.getVariable("serviceDecomposition_Target") ServiceDecomposition serviceDecomposition_Original = execution.getVariable("serviceDecomposition_Original") - List<Resource> allSR_target = serviceDecomposition_Target.getServiceResources(); - List<Resource> allSR_original = serviceDecomposition_Original.getServiceResources(); + List<Resource> allSR_target = serviceDecomposition_Target.getServiceResources() + List<Resource> allSR_original = serviceDecomposition_Original.getServiceResources() List<Resource> addResourceList = new ArrayList<String>() List<Resource> delResourceList = new ArrayList<String>() @@ -214,8 +214,8 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { if(rc_o.getModelInfo().getModelUuid() == muuid && rc_o.getModelInfo().getModelInvariantUuid() == mIuuid && rc_o.getModelInfo().getModelCustomizationUuid() == mCuuid) { - addResourceList.remove(rc_t); - delResourceList.remove(rc_o); + addResourceList.remove(rc_t) + delResourceList.remove(rc_o) } } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy index 0191439dac..9d8b953f0e 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy @@ -7,7 +7,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -26,9 +26,9 @@ import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import org.onap.so.logger.LoggingAnchor -import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.ErrorCode -import static org.apache.commons.lang3.StringUtils.*; +import static org.apache.commons.lang3.StringUtils.* import javax.ws.rs.NotFoundException @@ -83,7 +83,7 @@ import org.onap.so.bpmn.core.UrnPropertiesReader * */ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { - private static final Logger logger = LoggerFactory.getLogger( DoCreateE2EServiceInstance.class); + private static final Logger logger = LoggerFactory.getLogger( DoCreateE2EServiceInstance.class) String Prefix="DCRESI_" @@ -165,7 +165,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { execution.setVariable("serviceInstanceData", si) } catch (BpmnError e) { - throw e; + throw e } catch (Exception ex){ msg = "Exception in preProcessRequest " + ex.getMessage() logger.info(msg) @@ -210,7 +210,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { //we need a service plugin platform here. ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") String uuiRequest = execution.getVariable("uuiRequest") - String newUuiRequest = ServicePluginFactory.getInstance().preProcessService(serviceDecomposition, uuiRequest); + String newUuiRequest = ServicePluginFactory.getInstance().preProcessService(serviceDecomposition, uuiRequest) execution.setVariable("uuiRequest", newUuiRequest) } @@ -218,7 +218,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { //we need a service plugin platform here. ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") String uuiRequest = execution.getVariable("uuiRequest") - String newUuiRequest = ServicePluginFactory.getInstance().doServiceHoming(serviceDecomposition, uuiRequest); + String newUuiRequest = ServicePluginFactory.getInstance().doServiceHoming(serviceDecomposition, uuiRequest) execution.setVariable("uuiRequest", newUuiRequest) } @@ -254,7 +254,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { } } } catch (BpmnError e) { - throw e; + throw e } catch (Exception ex) { msg = "Exception in DoCreateServiceInstance.postProcessAAIGET. " + ex.getMessage() logger.info(msg) @@ -276,7 +276,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { client.create(uri, si) } catch (BpmnError e) { - throw e; + throw e } catch (Exception ex) { //start rollback set up RollbackData rollbackData = new RollbackData() @@ -310,11 +310,11 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { AAIResultWrapper aaiResult = client.get(uri,NotFoundException.class) Map<String, Object> result = aaiResult.asMap() List<Object> resources = - (List<Object>) result.getOrDefault("result-data", Collections.emptyList()); + (List<Object>) result.getOrDefault("result-data", Collections.emptyList()) if(resources.size()>0) { String relationshipUrl = ((Map<String, Object>) resources.get(0)).get("resource-link") - final Relationship body = new Relationship(); + final Relationship body = new Relationship() body.setRelatedLink(relationshipUrl) createRelationShipInAAI(execution, body) @@ -329,7 +329,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { } catch (BpmnError e) { - throw e; + throw e } catch (Exception ex) { msg = "Exception in DoCreateE2EServiceInstance.createCustomRelationship. " + ex.getMessage() @@ -349,7 +349,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { client.create(uri, relationship) } catch (BpmnError e) { - throw e; + throw e } catch (Exception ex) { msg = "Exception in DoCreateE2EServiceInstance.createRelationShipInAAI. " + ex.getMessage() @@ -362,9 +362,9 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { private String isNeedProcessCustomRelationship(String uuiRequest) { String requestInput = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs") - Map<String, String> requestInputObject = getJsonObject(requestInput, Map.class); + Map<String, String> requestInputObject = getJsonObject(requestInput, Map.class) if (requestInputObject == null) { - return null; + return null } Optional<Map.Entry> firstKey = @@ -380,15 +380,15 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { } private static <T> T getJsonObject(String jsonstr, Class<T> type) { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); + ObjectMapper mapper = new ObjectMapper() + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true) try { - return mapper.readValue(jsonstr, type); + return mapper.readValue(jsonstr, type) } catch (IOException e) { logger.error("{} {} fail to unMarshal json", MessageEnum.RA_NS_EXC.toString(), - ErrorCode.BusinessProcesssError.getValue(), e); + ErrorCode.BusinessProcesssError.getValue(), e) } - return null; + return null } @@ -409,7 +409,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { execution.setVariable("serviceInstanceName", si.get().getServiceInstanceName()) }catch(BpmnError e) { - throw e; + throw e }catch(Exception ex) { String msg = "Internal Error in getServiceInstance: " + ex.getMessage() exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) @@ -449,7 +449,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { } } } catch (BpmnError e) { - throw e; + throw e } catch (Exception ex) { msg = "Exception in DoCreateServiceInstance.postProcessAAIGET2 " + ex.getMessage() logger.info(msg) @@ -462,12 +462,12 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { logger.trace("preProcessRollback ") try { - Object workflowException = execution.getVariable("WorkflowException"); + Object workflowException = execution.getVariable("WorkflowException") if (workflowException instanceof WorkflowException) { logger.info("Prev workflowException: " + workflowException.getErrorMessage()) - execution.setVariable("prevWorkflowException", workflowException); - //execution.setVariable("WorkflowException", null); + execution.setVariable("prevWorkflowException", workflowException) + //execution.setVariable("WorkflowException", null) } } catch (BpmnError e) { logger.info("BPMN Error during preProcessRollback") @@ -482,15 +482,15 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { logger.trace("postProcessRollback ") String msg = "" try { - Object workflowException = execution.getVariable("prevWorkflowException"); + Object workflowException = execution.getVariable("prevWorkflowException") if (workflowException instanceof WorkflowException) { logger.info("Setting prevException to WorkflowException: ") - execution.setVariable("WorkflowException", workflowException); + execution.setVariable("WorkflowException", workflowException) } execution.setVariable("rollbackData", null) } catch (BpmnError b) { logger.info("BPMN Error during postProcessRollback") - throw b; + throw b } catch(Exception ex) { msg = "Exception in postProcessRollback. " + ex.getMessage() logger.info(msg) @@ -547,19 +547,19 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { }catch(Exception e){ logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preInitResourcesOperStatus.", "BPMN", - ErrorCode.UnknownError.getValue(), e); + ErrorCode.UnknownError.getValue(), e) execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage()) } logger.trace("COMPLETED preInitResourcesOperStatus Process ") } - // if site location is in local Operator, create all resources in local ONAP; + // if site location is in local Operator, create all resources in local ONAP // if site location is in 3rd Operator, only process sp-partner to create all resources in 3rd ONAP public void doProcessSiteLocation(DelegateExecution execution){ logger.trace("======== Start doProcessSiteLocation Process ======== ") ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") String uuiRequest = execution.getVariable("uuiRequest") - uuiRequest = ServicePluginFactory.getInstance().doProcessSiteLocation(serviceDecomposition, uuiRequest); + uuiRequest = ServicePluginFactory.getInstance().doProcessSiteLocation(serviceDecomposition, uuiRequest) execution.setVariable("uuiRequest", uuiRequest) execution.setVariable("serviceDecomposition", serviceDecomposition) @@ -571,7 +571,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { logger.trace("======== Start doTPResourcesAllocation Process ======== ") ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") String uuiRequest = execution.getVariable("uuiRequest") - uuiRequest = ServicePluginFactory.getInstance().doTPResourcesAllocation(execution, uuiRequest); + uuiRequest = ServicePluginFactory.getInstance().doTPResourcesAllocation(execution, uuiRequest) execution.setVariable("uuiRequest", uuiRequest) logger.trace("======== COMPLETED doTPResourcesAllocation Process ======== ") } 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 b1356b9fb6..bc26aa10ec 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 @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -72,13 +72,13 @@ import java.lang.reflect.Type * @param - WorkflowException */ public class DoCreateResources extends AbstractServiceTaskProcessor{ - private static final Logger logger = LoggerFactory.getLogger( DoCreateResources.class); + private static final Logger logger = LoggerFactory.getLogger( DoCreateResources.class) ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create() - public void preProcessRequest(DelegateExecution execution) { + void preProcessRequest(DelegateExecution execution) { logger.trace("preProcessRequest ") String msg = "" @@ -95,7 +95,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ logger.trace("Exit preProcessRequest ") } - public void sequenceResoure(DelegateExecution execution) { + void sequenceResoure(DelegateExecution execution) { logger.trace("Start sequenceResoure Process ") String incomingRequest = execution.getVariable("uuiRequest") @@ -170,7 +170,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ String isContainsWanResource = networkResourceList.isEmpty() ? "false" : "true" //if no networkResource, get SDNC config from properties file if( "false".equals(isContainsWanResource)) { - String serviceNeedSDNC = "mso.workflow.custom." + serviceModelName + ".sdnc.need"; + String serviceNeedSDNC = "mso.workflow.custom." + serviceModelName + ".sdnc.need" isContainsWanResource = BPMNProperties.getProperty(serviceNeedSDNC, isContainsWanResource) } @@ -181,7 +181,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ logger.trace("COMPLETED sequenceResoure Process ") } - public prepareServiceTopologyRequest(DelegateExecution execution) { + void prepareServiceTopologyRequest(DelegateExecution execution) { logger.trace("======== Start prepareServiceTopologyRequest Process ======== ") @@ -201,7 +201,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ logger.trace("======== End prepareServiceTopologyRequest Process ======== ") } - public void getCurrentResoure(DelegateExecution execution){ + void getCurrentResoure(DelegateExecution execution){ logger.trace("Start getCurrentResoure Process ") def currentIndex = execution.getVariable("currentResourceIndex") List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList") @@ -211,7 +211,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ logger.trace("COMPLETED getCurrentResource Process ") } - public void parseNextResource(DelegateExecution execution){ + void parseNextResource(DelegateExecution execution){ logger.trace("Start parseNextResource Process ") def currentIndex = execution.getVariable("currentResourceIndex") def nextIndex = currentIndex + 1 @@ -225,7 +225,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ logger.trace("COMPLETED parseNextResource Process ") } - public void prepareResourceRecipeRequest(DelegateExecution execution){ + void prepareResourceRecipeRequest(DelegateExecution execution){ logger.trace("Start prepareResourceRecipeRequest Process ") ResourceInput resourceInput = new ResourceInput() String serviceInstanceName = execution.getVariable("serviceInstanceName") @@ -242,7 +242,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ resourceInput.setServiceType(serviceType) resourceInput.setServiceInstanceId(serviceInstanceId) resourceInput.setOperationId(operationId) - resourceInput.setOperationType(operationType); + resourceInput.setOperationType(operationType) def currentIndex = execution.getVariable("currentResourceIndex") List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList") Resource currentResource = sequencedResourceList.get(currentIndex) @@ -284,7 +284,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ logger.trace("COMPLETED prepareResourceRecipeRequest Process ") } - public void executeResourceRecipe(DelegateExecution execution){ + void executeResourceRecipe(DelegateExecution execution){ logger.trace("Start executeResourceRecipe Process ") try { @@ -338,7 +338,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ } } - public void postConfigRequest(DelegateExecution execution){ + void postConfigRequest(DelegateExecution execution){ //now do noting ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") for (VnfResource resource : serviceDecomposition.vnfResources) { @@ -346,4 +346,4 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ } execution.setVariable("serviceDecomposition", serviceDecomposition) } -}
\ No newline at end of file +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy index bf52b11de2..64d9827c7c 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy @@ -83,7 +83,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { JsonUtils jsonUtil = new JsonUtils() CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create() - public void preProcessRequest (DelegateExecution execution) { + void preProcessRequest (DelegateExecution execution) { def isDebugEnabled = execution.getVariable("isDebugLogEnabled") String msg = "" logger.trace("preProcessRequest") @@ -286,7 +286,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { logger.trace("Exit preProcessRequest") } - public void getAAICustomerById (DelegateExecution execution) { + void getAAICustomerById (DelegateExecution execution) { // https://{aaiEP}/aai/v8/business/customers/customer/{globalCustomerId} try { @@ -306,7 +306,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { } - public void putServiceInstance(DelegateExecution execution) { + void putServiceInstance(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") logger.trace("putServiceInstance") String msg = "" @@ -380,7 +380,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { logger.trace("Exit putServiceInstance") } - public void preProcessSDNCAssignRequest(DelegateExecution execution) { + void preProcessSDNCAssignRequest(DelegateExecution execution) { def isDebugEnabled = execution.getVariable("isDebugLogEnabled") String msg = "" logger.trace("preProcessSDNCAssignRequest") @@ -479,7 +479,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { logger.trace("Exit preProcessSDNCAssignRequest") } - public void postProcessSDNCAssign (DelegateExecution execution) { + void postProcessSDNCAssign (DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") logger.trace("postProcessSDNCAssign") try { @@ -518,7 +518,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { logger.trace("Exit postProcessSDNCAssign") } - public void postProcessAAIGET2(DelegateExecution execution) { + void postProcessAAIGET2(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") logger.trace("postProcessAAIGET2") String msg = "" @@ -561,7 +561,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { logger.trace("Exit postProcessAAIGET2") } - public void preProcessRollback (DelegateExecution execution) { + void preProcessRollback (DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") logger.trace("preProcessRollback") try { @@ -582,7 +582,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { logger.trace("Exit preProcessRollback") } - public void postProcessRollback (DelegateExecution execution) { + void postProcessRollback (DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") logger.trace("postProcessRollback") String msg = "" @@ -603,7 +603,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { logger.trace("Exit postProcessRollback") } - public void createProject(DelegateExecution execution) { + void createProject(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") logger.trace("createProject") @@ -631,7 +631,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { logger.trace("Exit createProject") } - public void createOwningEntity(DelegateExecution execution) { + void createOwningEntity(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") logger.trace("createOwningEntity") String msg = ""; @@ -679,7 +679,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { // Build Error Section // ******************************* - public void processJavaException(DelegateExecution execution){ + void processJavaException(DelegateExecution execution){ def isDebugEnabled=execution.getVariable("isDebugLogEnabled") try{ diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy index 1eeba493f4..af82bf091a 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy @@ -69,7 +69,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso String Prefix="DCRESIRB_" - public void preProcessRequest(DelegateExecution execution) { + void preProcessRequest(DelegateExecution execution) { def isDebugEnabled = execution.getVariable("isDebugLogEnabled") execution.setVariable("prefix",Prefix) String msg = "" @@ -139,7 +139,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso logger.trace("Exit preProcessRequest") } - public void validateSDNCResponse(DelegateExecution execution, String response, String method) { + void validateSDNCResponse(DelegateExecution execution, String response, String method) { logger.trace("validateSDNCResponse") String msg = "" @@ -172,7 +172,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso logger.trace("Exit validateSDNCResponse") } - public void postProcessRequest(DelegateExecution execution) { + void postProcessRequest(DelegateExecution execution) { logger.trace("postProcessRequest") String msg = "" @@ -206,7 +206,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso } - public void processRollbackException(DelegateExecution execution){ + void processRollbackException(DelegateExecution execution){ logger.trace("processRollbackException") try{ @@ -224,7 +224,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso logger.debug("Exit processRollbackException") } - public void processRollbackJavaException(DelegateExecution execution){ + void processRollbackJavaException(DelegateExecution execution){ logger.trace("processRollbackJavaException") try{ diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy index eab99df9b2..1517a335d9 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy @@ -61,7 +61,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces * generate the nsOperationKey * generate the nsParameters */ - public void preProcessRequest (DelegateExecution execution) { + void preProcessRequest (DelegateExecution execution) { String msg = "" logger.trace("preProcessRequest()") try { @@ -130,7 +130,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces /** * create NS task */ - public void createNetworkService(DelegateExecution execution) { + void createNetworkService(DelegateExecution execution) { logger.trace("createNetworkService") String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl") String nsOperationKey = execution.getVariable("nsOperationKey"); @@ -157,7 +157,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces /** * instantiate NS task */ - public void instantiateNetworkService(DelegateExecution execution) { + void instantiateNetworkService(DelegateExecution execution) { logger.trace("instantiateNetworkService") String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl") String nsOperationKey = execution.getVariable("nsOperationKey"); @@ -186,7 +186,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces /** * query NS task */ - public void queryNSProgress(DelegateExecution execution) { + void queryNSProgress(DelegateExecution execution) { logger.trace("queryNSProgress") String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl") String jobId = execution.getVariable("jobId") @@ -206,7 +206,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces /** * delay 5 sec */ - public void timeDelay(DelegateExecution execution) { + void timeDelay(DelegateExecution execution) { try { Thread.sleep(5000); } catch(InterruptedException e) { @@ -217,7 +217,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces /** * finish NS task */ - public void addNSRelationship(DelegateExecution execution) { + void addNSRelationship(DelegateExecution execution) { logger.trace("addNSRelationship") String nsInstanceId = execution.getVariable("nsInstanceId") if(nsInstanceId == null || nsInstanceId == ""){ diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy index cf3a0ef56f..a88becad1a 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy @@ -7,7 +7,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * @@ -25,7 +25,7 @@ package org.onap.so.bpmn.infrastructure.scripts import org.onap.so.logger.LoggingAnchor import org.onap.so.logger.ErrorCode -import static org.apache.commons.lang3.StringUtils.*; +import static org.apache.commons.lang3.StringUtils.* import javax.xml.parsers.DocumentBuilder import javax.xml.parsers.DocumentBuilderFactory @@ -33,8 +33,8 @@ import javax.xml.parsers.DocumentBuilderFactory import org.apache.commons.lang3.* import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.json.JSONArray; -import org.json.JSONObject; +import org.json.JSONArray +import org.json.JSONObject import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils @@ -44,7 +44,7 @@ import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.logger.MessageEnum import org.slf4j.Logger import org.slf4j.LoggerFactory -import org.springframework.web.util.UriUtils; +import org.springframework.web.util.UriUtils import org.w3c.dom.Document import org.w3c.dom.Element import org.w3c.dom.Node @@ -79,7 +79,7 @@ import groovy.json.* * Rollback - Deferred */ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { - private static final Logger logger = LoggerFactory.getLogger( DoCustomDeleteE2EServiceInstance.class); + private static final Logger logger = LoggerFactory.getLogger( DoCustomDeleteE2EServiceInstance.class) String Prefix="DDELSI_" @@ -151,7 +151,7 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess execution.setVariable("siParamsXml", siParamsXml) } catch (BpmnError e) { - throw e; + throw e } catch (Exception ex){ msg = "Exception in preProcessRequest " + ex.getMessage() logger.info(msg) @@ -271,7 +271,7 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess logger.info("sdncDelete:\n" + sdncDelete) } catch (BpmnError e) { - throw e; + throw e } catch(Exception ex) { msg = "Exception in preProcessSDNCDelete. " + ex.getMessage() logger.info(msg) @@ -302,7 +302,7 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess exceptionUtil.buildAndThrowWorkflowException(execution, 3500, msg) } } catch (BpmnError e) { - throw e; + throw e } catch(Exception ex) { msg = "Exception in postProcessSDNC " + method + " Exception:" + ex.getMessage() logger.info(msg) @@ -337,8 +337,8 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess //Confirm there are no related service instances (vnf/network or volume) if (utils.nodeExists(siData, "relationship-list")) { logger.info("SI Data relationship-list exists:") - InputSource source = new InputSource(new StringReader(siData)); - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + InputSource source = new InputSource(new StringReader(siData)) + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance() DocumentBuilder docBuilder = docFactory.newDocumentBuilder() Document serviceXml = docBuilder.parse(source) serviceXml.getDocumentElement().normalize() @@ -433,7 +433,7 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess logger.info("Service-instance NOT found in AAI. Silent Success") } }catch (BpmnError e) { - throw e; + throw e } catch (Exception ex) { msg = "Exception in DoDeleteE2EServiceInstance.postProcessAAIGET. " + ex.getMessage() logger.info(msg) @@ -452,7 +452,7 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess String serviceType = execution.getVariable("serviceType") String serviceInstanceId = execution.getVariable("serviceInstanceId") - AAIResourcesClient resourceClient = new AAIResourcesClient(); + AAIResourcesClient resourceClient = new AAIResourcesClient() AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustId, serviceType, serviceInstanceId) resourceClient.delete(serviceInstanceUri) @@ -535,7 +535,7 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess }catch(Exception e){ logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception Occured Processing preInitResourcesOperStatus.", "BPMN", - ErrorCode.UnknownError.getValue(), e); + ErrorCode.UnknownError.getValue(), e) execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage()) } logger.trace("COMPLETED preInitResourcesOperStatus Process ") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy index 481a79a7ef..34ea20ba62 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy @@ -6,7 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -90,7 +90,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { String Prefix="DDEESI_" ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() - private static final Logger logger = LoggerFactory.getLogger( DoDeleteE2EServiceInstance.class); + private static final Logger logger = LoggerFactory.getLogger( DoDeleteE2EServiceInstance.class) public void preProcessRequest (DelegateExecution execution) { @@ -158,7 +158,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { execution.setVariable("siParamsXml", siParamsXml) } catch (BpmnError e) { - throw e; + throw e } catch (Exception ex){ msg = "Exception in preProcessRequest " + ex.getMessage() logger.error(msg) @@ -243,7 +243,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { // for sp-partner and others else if (eKey.endsWith("-id")) { jObj.put("resourceInstanceId", eValue) - String resourceName = rt + eValue; + String resourceName = rt + eValue jObj.put("resourceType", resourceName) } jObj.put("resourceLinkUrl", rl) @@ -520,12 +520,12 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { if (StringUtils.containsIgnoreCase(obj.get("resourceType"), modelName)) { resource.setResourceId(obj.get("resourceInstanceId")) //deleteRealResourceList.add(resource) - matches = true; + matches = true } else if (modelCustomizationUuid.equals(obj.get("modelCustomizationId")) || modelUuid.equals(obj.get("model-version-id")) ) { resource.setResourceId(obj.get("resourceInstanceId")) resource.setResourceInstanceName(obj.get("resourceType")) //deleteRealResourceList.add(resource) - matches = true; + matches = true } return matches } @@ -646,7 +646,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { String serviceType = execution.getVariable("serviceType") String serviceInstanceId = execution.getVariable("serviceInstanceId") - AAIResourcesClient resourceClient = new AAIResourcesClient(); + AAIResourcesClient resourceClient = new AAIResourcesClient() AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustId, serviceType, serviceInstanceId) resourceClient.delete(serviceInstanceUri) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/HandlePNF.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/HandlePNF.groovy index cbeb1d3d69..97eb3b3960 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/HandlePNF.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/HandlePNF.groovy @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2017 - 2019 Huawei Intellectual Property. All rights reserved. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -34,7 +34,7 @@ import org.slf4j.Logger import org.slf4j.LoggerFactory public class HandlePNF extends AbstractServiceTaskProcessor{ - private static final Logger logger = LoggerFactory.getLogger( HandlePNF.class); + private static final Logger logger = LoggerFactory.getLogger( HandlePNF.class) ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() @@ -95,7 +95,7 @@ public class HandlePNF extends AbstractServiceTaskProcessor{ <statusDescription>${msoUtils.xmlEscape(statusDescription)}</statusDescription> </ns:updateResourceOperationStatus> </soapenv:Body> - </soapenv:Envelope>"""; + </soapenv:Envelope>""" logger.debug("body: "+body) setProgressUpdateVariables(execution, body) logger.debug("exit postProcess for HandlePNF") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegate.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegate.java index d67e6ef0db..a011346756 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegate.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegate.java @@ -45,7 +45,7 @@ public class ConfigCheckerDelegate implements JavaDelegate { private Logger logger = LoggerFactory.getLogger(ConfigCheckerDelegate.class); // ERROR CODE for variable not found in the delegation Context - private static int ERROR_CODE = 601; + private static final int ERROR_CODE = 601; @Autowired protected ExceptionBuilder exceptionUtil; 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 357b571a5c..48061db887 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 @@ -90,7 +90,7 @@ 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 = runnable = pnfCorrelationIdToThreadMap.remove(pnfCorrelationId); + Runnable runnable = pnfCorrelationIdToThreadMap.remove(pnfCorrelationId); synchronized (updateInfoMap) { for (int i = updateInfoMap.size() - 1; i >= 0; i--) { if (!updateInfoMap.get(i).containsKey("pnfCorrelationId")) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java index 579e7b72df..2f05eb5f2d 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java @@ -863,23 +863,23 @@ public class ServicePluginFactory { HttpClient client = HttpClientBuilder.create().build(); - if ("POST".equals(methodType.toUpperCase())) { + if ("POST".equalsIgnoreCase(methodType)) { HttpPost httpPost = new HttpPost(msbUrl); httpPost.setConfig(requestConfig); httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON)); method = httpPost; - } else if ("PUT".equals(methodType.toUpperCase())) { + } else if ("PUT".equalsIgnoreCase(methodType)) { HttpPut httpPut = new HttpPut(msbUrl); httpPut.setConfig(requestConfig); httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON)); method = httpPut; - } else if ("GET".equals(methodType.toUpperCase())) { + } else if ("GET".equalsIgnoreCase(methodType)) { HttpGet httpGet = new HttpGet(msbUrl); httpGet.setConfig(requestConfig); httpGet.addHeader("X-FromAppId", "MSO"); httpGet.addHeader("Accept", "application/json"); method = httpGet; - } else if ("DELETE".equals(methodType.toUpperCase())) { + } else if ("DELETE".equalsIgnoreCase(methodType)) { HttpDelete httpDelete = new HttpDelete(msbUrl); httpDelete.setConfig(requestConfig); method = httpDelete; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java index 68cfd487b3..bd60fbe38c 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java @@ -71,6 +71,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import com.google.common.base.Strings; @Component public class AAICreateTasks { @@ -184,24 +185,35 @@ public class AAICreateTasks { ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); OwningEntity owningEntity = serviceInstance.getOwningEntity(); - String owningEntityId = owningEntity.getOwningEntityId(); - String owningEntityName = owningEntity.getOwningEntityName(); - if (owningEntityId == null || "".equals(owningEntityId)) { - String msg = "Exception in AAICreateOwningEntity. OwningEntityId is null."; + if (Strings.isNullOrEmpty(owningEntity.getOwningEntityId()) + && Strings.isNullOrEmpty(owningEntity.getOwningEntityName())) { + String msg = "Exception in AAICreateOwningEntity. OwningEntityId and Name are null."; execution.setVariable("ErrorCreateOEAAI", msg); exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg); + } else if (Strings.isNullOrEmpty(owningEntity.getOwningEntityId()) + && !Strings.isNullOrEmpty(owningEntity.getOwningEntityName())) { + if (aaiSIResources.existsOwningEntityName(owningEntity.getOwningEntityName())) { + org.onap.aai.domain.yang.OwningEntity aaiEntity = + aaiSIResources.getOwningEntityByName(owningEntity.getOwningEntityName()); + owningEntity.setOwningEntityId(aaiEntity.getOwningEntityId()); + owningEntity.setOwningEntityName(owningEntity.getOwningEntityName()); + aaiSIResources.connectOwningEntityandServiceInstance(owningEntity, serviceInstance); + } else { + owningEntity.setOwningEntityId(UUID.randomUUID().toString()); + aaiSIResources.createOwningEntityandConnectServiceInstance(owningEntity, serviceInstance); + } } else { if (aaiSIResources.existsOwningEntity(owningEntity)) { aaiSIResources.connectOwningEntityandServiceInstance(owningEntity, serviceInstance); } else { - if (owningEntityName == null || "".equals(owningEntityName)) { + if (Strings.isNullOrEmpty(owningEntity.getOwningEntityName())) { String msg = "Exception in AAICreateOwningEntity. Can't create an owningEntity with no owningEntityName."; logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue(), msg); exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg); } else { - if (aaiSIResources.existsOwningEntityName(owningEntityName)) { + if (aaiSIResources.existsOwningEntityName(owningEntity.getOwningEntityName())) { String msg = "Exception in AAICreateOwningEntity. Can't create OwningEntity as name already exists in AAI associated with a different owning-entity-id (name must be unique)"; logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java index fc3f2aec7a..52d294955a 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java @@ -23,10 +23,10 @@ package org.onap.so.bpmn.infrastructure.validations; import java.util.Optional; import java.util.regex.Pattern; import org.onap.so.bpmn.common.BuildingBlockExecution; -import org.onap.so.bpmn.common.listener.Skip; import org.onap.so.bpmn.common.listener.validation.PreBuildingBlockValidator; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.listener.Skip; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java index f23e5cdb5a..5c69987a54 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java @@ -33,6 +33,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Optional; import javax.annotation.PostConstruct; import org.apache.commons.lang3.StringUtils; @@ -210,23 +211,25 @@ public class VnfAdapterVfModuleObjectMapper { protected void buildDirectivesParamFromMap(Map<String, Object> paramsMap, String directive, Map<String, Object> srcMap) throws MissingValueTagException { StringBuilder directives = new StringBuilder(); - int no_directives_size = 0; + int noOfDirectivesSize = 0; if (directive.equals(MsoMulticloudUtils.USER_DIRECTIVES) && srcMap.containsKey(MsoMulticloudUtils.OOF_DIRECTIVES)) { - no_directives_size = 1; + noOfDirectivesSize = 1; } - if (srcMap.size() > no_directives_size) { + if (srcMap.size() > noOfDirectivesSize) { directives.append("{ \"attributes\": [ "); int i = 0; - for (String attributeName : srcMap.keySet()) { + for (Map.Entry<String, Object> attributeEntry : srcMap.entrySet()) { + String attributeName = attributeEntry.getKey(); + Object attributeValue = attributeEntry.getValue(); if (!(MsoMulticloudUtils.USER_DIRECTIVES.equals(directive) && attributeName.equals(MsoMulticloudUtils.OOF_DIRECTIVES))) { - if (srcMap.get(attributeName) == null) { + if (attributeValue == null) { logger.error("No value tag found for attribute: {}", attributeName); throw new MissingValueTagException("No value tag found for " + attributeName); } - directives.append(new AttributeNameValue(attributeName, srcMap.get(attributeName).toString())); - if (i < (srcMap.size() - 1 + no_directives_size)) + directives.append(new AttributeNameValue(attributeName, attributeValue.toString())); + if (i < (srcMap.size() - 1 + noOfDirectivesSize)) directives.append(", "); i++; } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIEntityNotFoundException.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIEntityNotFoundException.java new file mode 100644 index 0000000000..5f65e5d76d --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIEntityNotFoundException.java @@ -0,0 +1,16 @@ +package org.onap.so.client.orchestration; + +public class AAIEntityNotFoundException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -107868951852460677L; + + public AAIEntityNotFoundException(String error) { + super(error); + } + + + +} 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 c41f3fa56c..fc1528526c 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 @@ -22,7 +22,9 @@ package org.onap.so.client.orchestration; +import java.util.List; import java.util.Optional; +import org.onap.aai.domain.yang.OwningEntities; import org.onap.so.bpmn.common.InjectionHelper; import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer; import org.onap.so.bpmn.servicedecomposition.bbobjects.OwningEntity; @@ -120,6 +122,25 @@ public class AAIServiceInstanceResources { return aaiRC.exists(owningEntityUri); } + public org.onap.aai.domain.yang.OwningEntity getOwningEntityByName(String owningEntityName) + throws AAIEntityNotFoundException { + AAIResourceUri owningEntityUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.OWNING_ENTITY) + .queryParam("owning-entity-name", owningEntityName); + AAIResourcesClient aaiRC = injectionHelper.getAaiClient(); + Optional<OwningEntities> owningEntities = aaiRC.get(OwningEntities.class, owningEntityUri); + if (owningEntities.isPresent()) { + List<org.onap.aai.domain.yang.OwningEntity> owningEntityList = owningEntities.get().getOwningEntity(); + if (owningEntityList.size() > 1) { + throw new AAIEntityNotFoundException( + "Non unique result returned for owning entity name: " + owningEntityName); + } else { + return owningEntityList.get(0); + } + } else { + throw new AAIEntityNotFoundException("No result returned for owning entity name: " + owningEntityName); + } + } + public void connectOwningEntityandServiceInstance(OwningEntity owningEntity, ServiceInstance serviceInstance) { AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntity.getOwningEntityId()); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java index 12d1b0be95..b8146b5504 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java @@ -36,7 +36,7 @@ public class SDNCRequest implements Serializable { private SDNCTopology topology; private String correlationValue = UUID.randomUUID().toString(); private String correlationName = "SDNCCallback"; - private Object SDNCPayload; + private Object sdncPayload; public String getTimeOut() { @@ -72,11 +72,11 @@ public class SDNCRequest implements Serializable { } public Object getSDNCPayload() { - return SDNCPayload; + return sdncPayload; } public void setSDNCPayload(Object sDNCPayload) { - SDNCPayload = sDNCPayload; + this.sdncPayload = sDNCPayload; } @Override diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java index ed3ec759c3..a8550d8df9 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java @@ -54,16 +54,16 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup; import org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network; import org.onap.so.bpmn.servicedecomposition.bbobjects.LineOfBusiness; import org.onap.so.bpmn.servicedecomposition.bbobjects.NetworkPolicy; +import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; import org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoGenericVnf; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.exception.BBObjectNotFoundException; import org.onap.so.db.catalog.beans.OrchestrationStatus; -import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform; public class AAICreateTasksTest extends BaseTaskTest { @@ -272,24 +272,6 @@ public class AAICreateTasksTest extends BaseTaskTest { } @Test - public void createOwningEntityNullOwningEntityIdTest() throws Exception { - expectedException.expect(BpmnError.class); - - serviceInstance.getOwningEntity().setOwningEntityId(null); - - aaiCreateTasks.createOwningEntity(execution); - } - - @Test - public void createOwningEntityEmptyOwningEntityIdTest() throws Exception { - expectedException.expect(BpmnError.class); - - serviceInstance.getOwningEntity().setOwningEntityId(""); - - aaiCreateTasks.createOwningEntity(execution); - } - - @Test public void createOwningEntityNullOwningEntityNameTest() throws Exception { expectedException.expect(BpmnError.class); diff --git a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClient.java b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClient.java index 3bd646fada..d15fbf9322 100644 --- a/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClient.java +++ b/cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClient.java @@ -135,7 +135,7 @@ public class CloudifyClient { * @return An object of Class <R> */ public <R> CloudifyRequest<R> get(String path, Class<R> returnType) { - return new CloudifyRequest<R>(this, HttpMethod.GET, path, null, returnType); + return new CloudifyRequest<>(this, HttpMethod.GET, path, null, returnType); } } 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 df63bd18d3..006768f2f1 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 @@ -37,7 +37,7 @@ public class CloudifyRequest<R> { private StringBuilder path = new StringBuilder(); - private Map<String, List<Object>> headers = new HashMap<String, List<Object>>(); + private Map<String, List<Object>> headers = new HashMap<>(); private Entity<?> entity; @@ -100,7 +100,7 @@ public class CloudifyRequest<R> { } public <T> Entity<T> entity(T entity, String contentType) { - return new Entity<T>(entity, contentType); + return new Entity<>(entity, contentType); } public Entity<?> entity() { @@ -160,7 +160,7 @@ public class CloudifyRequest<R> { + headers + ", entity=" + entity + ", returnType=" + returnType + "]"; } - private Map<String, List<Object>> queryParams = new LinkedHashMap<String, List<Object>>(); + private Map<String, List<Object>> queryParams = new LinkedHashMap<>(); public Map<String, List<Object>> queryParams() { return queryParams; @@ -171,7 +171,7 @@ public class CloudifyRequest<R> { List<Object> values = queryParams.get(key); values.add(value); } else { - List<Object> values = new ArrayList<Object>(); + List<Object> values = new ArrayList<>(); values.add(value); queryParams.put(key, values); } diff --git a/common/pom.xml b/common/pom.xml index a52897170a..2553038e6b 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -186,6 +186,11 @@ <version>${grpc.version}</version> <scope>test</scope> </dependency> + <dependency> + <groupId>org.javatuples</groupId> + <artifactId>javatuples</artifactId> + <version>1.2</version> + </dependency> </dependencies> <dependencyManagement> 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 f7f5d78604..e301edb0fd 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 @@ -32,9 +32,9 @@ public class DSLNodeKey implements QueryStep { private boolean not = false; private final StringBuilder query = new StringBuilder(); private final String keyName; - private final List<String> values; + private final List<Object> values; - public DSLNodeKey(String keyName, String... value) { + public DSLNodeKey(String keyName, Object... value) { this.keyName = keyName; this.values = Arrays.asList(value); @@ -54,14 +54,18 @@ public class DSLNodeKey implements QueryStep { result.append(" !"); } result.append("('").append(keyName).append("', "); - List<String> temp = new ArrayList<>(); - for (String item : values) { + List<Object> temp = new ArrayList<>(); + for (Object item : values) { if ("null".equals(item)) { temp.add(String.format("' %s '", item)); } else if ("".equals(item)) { temp.add("' '"); } else { - temp.add(String.format("'%s'", item)); + if (item instanceof String) { + temp.add(String.format("'%s'", item)); + } else { + temp.add(item); + } } } result.append(Joiner.on(", ").join(temp)).append(")"); diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java index 2fdd6574e5..87d4d84cac 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java @@ -45,7 +45,7 @@ public class __ { return __.<DSLNode>start(new DSLNode(name, key)); } - public static DSLNodeKey key(String keyName, String... value) { + public static DSLNodeKey key(String keyName, Object... value) { return new DSLNodeKey(keyName, value); } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/ListenerRunner.java b/common/src/main/java/org/onap/so/listener/ListenerRunner.java index 3c36052dca..a489be6070 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/ListenerRunner.java +++ b/common/src/main/java/org/onap/so/listener/ListenerRunner.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.listener; +package org.onap.so.listener; import java.lang.annotation.Annotation; import java.util.Comparator; @@ -27,7 +27,6 @@ import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.annotation.Priority; -import org.onap.so.client.exception.ExceptionBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; @@ -36,10 +35,7 @@ public abstract class ListenerRunner { @Autowired protected ApplicationContext context; - @Autowired - protected ExceptionBuilder exceptionBuilder; - - protected <T> List<T> filterListeners(List<T> validators, Predicate<T> predicate) { + public <T> List<T> filterListeners(List<T> validators, Predicate<T> predicate) { return validators.stream().filter(item -> { return !item.getClass().isAnnotationPresent(Skip.class) && predicate.test(item); }).sorted(Comparator.comparing(item -> { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/Skip.java b/common/src/main/java/org/onap/so/listener/Skip.java index a0543fd3cc..aa3ec2a204 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/Skip.java +++ b/common/src/main/java/org/onap/so/listener/Skip.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.listener; +package org.onap.so.listener; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java index 9fceed1641..a72229a25c 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java @@ -57,6 +57,9 @@ public class RequestParameters implements Serializable { @JsonProperty("rebuildVolumeGroups") private Boolean rebuildVolumeGroups; + @JsonProperty("enforceValidNfValues") + private Boolean enforceValidNfValues = false; + @Override public String toString() { return new ToStringBuilder(this).append("subscriptionServiceType", subscriptionServiceType) @@ -64,7 +67,15 @@ public class RequestParameters implements Serializable { .append("usePreload", usePreload).append("autoBuildVfModules", autoBuildVfModules) .append("cascadeDelete", cascadeDelete).append("testApi", testApi) .append("retainAssignments", retainAssignments).append("rebuildVolumeGroups", rebuildVolumeGroups) - .toString(); + .append("enforceValidNfValues", enforceValidNfValues).toString(); + } + + public Boolean getEnforceValidNfValues() { + return enforceValidNfValues; + } + + public void setEnforceValidNfValues(Boolean enforceValidNfValues) { + this.enforceValidNfValues = enforceValidNfValues; } public String getSubscriptionServiceType() { diff --git a/common/src/main/java/org/onap/so/utils/TargetEntities.java b/common/src/main/java/org/onap/so/utils/TargetEntities.java index 94385ec8ea..67016a1fa9 100644 --- a/common/src/main/java/org/onap/so/utils/TargetEntities.java +++ b/common/src/main/java/org/onap/so/utils/TargetEntities.java @@ -20,6 +20,8 @@ package org.onap.so.utils; -public interface TargetEntities { +import java.io.Serializable; + +public interface TargetEntities extends Serializable { } diff --git a/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java b/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java index 6e55fe17fa..590e83827b 100644 --- a/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java +++ b/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java @@ -108,4 +108,14 @@ public class DSLQueryBuilderTest { builder.equals("pserver*('hostname', 'my-hostname') > p-interface > sriov-pf('pf-pci-id', 'my-id')")); assertTrue(builder.equals(builder)); } + + + @Test + public void mixedTypeTest() { + DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.CLOUD_REGION, + __.key("cloud-owner", "owner"), __.key("cloud-region-id", "id"))); + builder.to(__.node(AAIObjectType.VLAN_TAG, __.key("vlan-id-outer", 167), __.key("my-boolean", true)).output()); + assertTrue(builder.equals( + "cloud-region('cloud-owner', 'owner')('cloud-region-id', 'id') > vlan-tag*('vlan-id-outer', 167)('my-boolean', true)")); + } } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Actions.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Actions.java index 5dbe44f58b..5ae0cea549 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Actions.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Actions.java @@ -20,6 +20,8 @@ package org.onap.so.apihandlerinfra; -public interface Actions { +import java.io.Serializable; + +public interface Actions extends Serializable { } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java index c7f6459482..ab2ce10690 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java @@ -29,7 +29,7 @@ public abstract class ApiException extends Exception { * */ private static final long serialVersionUID = 683162058616691134L; - private int httpResponseCode; + private int httpResponseCode = 500; private String messageID; private ErrorLoggerInfo errorLoggerInfo; @@ -49,6 +49,15 @@ public abstract class ApiException extends Exception { super(message, cause); } + public ApiException(String message, int httpResponseCode) { + super(message); + this.httpResponseCode = httpResponseCode; + } + + public ApiException(String message) { + super(message); + } + public String getMessageID() { return messageID; } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java index 66b86a6961..6a56b58f04 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java @@ -70,7 +70,7 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> { @Override public Response toResponse(ApiException exception) { - + logger.error("Error During API Call", exception); return Response.status(exception.getHttpResponseCode()).entity(buildErrorString(exception)).build(); } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java index 42198e2d0c..cbbfa16eaa 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java @@ -22,7 +22,7 @@ package org.onap.so.apihandlerinfra.exceptions; public class DuplicateRequestException extends ApiException { - private static final String duplicateFailMessage = "Error: Locked instance - This %s (%s) " + private static final String DUPLICATE_FAIL_MESSAGE = "Error: Locked instance - This %s (%s) " + "already has a request being worked with a status of %s (RequestId - %s). The existing request must finish or be cleaned up before proceeding."; private DuplicateRequestException(Builder builder) { @@ -36,7 +36,7 @@ public class DuplicateRequestException extends ApiException { public Builder(String requestScope, String instance, String requestStatus, String requestID, int httpResponseCode, String messageID) { - super(String.format(duplicateFailMessage, requestScope, instance, requestStatus, requestID), + super(String.format(DUPLICATE_FAIL_MESSAGE, requestScope, instance, requestStatus, requestID), httpResponseCode, messageID); } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RequestDbFailureException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RequestDbFailureException.java index 577a14674b..a8f868da05 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RequestDbFailureException.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RequestDbFailureException.java @@ -22,7 +22,7 @@ package org.onap.so.apihandlerinfra.exceptions; public class RequestDbFailureException extends ApiException { - private static final String requestDbFailMessage = "Unable to %s due to error contacting requestDb: %s"; + private static final String REQUEST_DB_FAIL_MESSAGE = "Unable to %s due to error contacting requestDb: %s"; private RequestDbFailureException(Builder builder) { super(builder); @@ -32,7 +32,7 @@ public class RequestDbFailureException extends ApiException { public Builder(String action, String error, int httpResponseCode, String messageID) { - super(requestDbFailMessage.format(requestDbFailMessage, action, error), httpResponseCode, messageID); + super(REQUEST_DB_FAIL_MESSAGE.format(REQUEST_DB_FAIL_MESSAGE, action, error), httpResponseCode, messageID); } public RequestDbFailureException build() { diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java index 372ed30d8e..ae8256e64f 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java @@ -28,6 +28,11 @@ public class ValidateException extends ApiException { } + public ValidateException(String errorMessage, int httpResponseCode) { + super(errorMessage, httpResponseCode); + } + + public static class Builder extends ApiException.Builder<Builder> { public Builder(String message, int httpResponseCode, String messageID) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java index 451fa64585..e56eb422d8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java @@ -115,7 +115,7 @@ public class CamundaRequestHandler { List<HistoricProcessInstanceEntity> historicProcessInstanceList = response.getBody(); - if (historicProcessInstanceList != null) { + if (historicProcessInstanceList != null && !historicProcessInstanceList.isEmpty()) { Collections.reverse(historicProcessInstanceList); processInstanceId = historicProcessInstanceList.get(0).getId(); } else { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GenericStringConverter.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GenericStringConverter.java new file mode 100644 index 0000000000..80144d8ca1 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GenericStringConverter.java @@ -0,0 +1,33 @@ +package org.onap.so.apihandlerinfra; + +import java.net.URI; +import java.util.Set; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.ConfigurationPropertiesBinding; +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.core.convert.converter.GenericConverter; +import org.springframework.stereotype.Component; +import com.google.common.collect.ImmutableSet; + +@Component +@ConfigurationPropertiesBinding +public class GenericStringConverter implements GenericConverter { + + @Autowired + private HealthCheckConverter converter; + + @Override + public Set<ConvertiblePair> getConvertibleTypes() { + + ConvertiblePair[] pairs = new ConvertiblePair[] {new ConvertiblePair(String.class, Subsystem.class), + new ConvertiblePair(String.class, URI.class)}; + return ImmutableSet.copyOf(pairs); + } + + @Override + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + + return converter.convert(source, sourceType, targetType); + + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java index 3d4b2c76fb..0379ae3578 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java @@ -25,11 +25,8 @@ package org.onap.so.apihandlerinfra; import java.net.URI; import java.util.Collections; -import org.onap.so.logger.LoggingAnchor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; +import java.util.List; +import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.transaction.Transactional; import javax.ws.rs.DefaultValue; @@ -42,14 +39,20 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import org.apache.http.HttpStatus; +import org.onap.so.apihandlerinfra.HealthCheckConfig.Endpoint; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; -import org.springframework.http.HttpMethod; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @@ -59,45 +62,38 @@ import io.swagger.annotations.ApiOperation; @Api(value = "/globalhealthcheck", description = "APIH Infra Global Health Check") public class GlobalHealthcheckHandler { private static Logger logger = LoggerFactory.getLogger(GlobalHealthcheckHandler.class); - private static final String CONTEXTPATH_PROPERTY = "management.context-path"; - private static final String PROPERTY_DOMAIN = "mso.health.endpoints"; - private static final String CATALOGDB_PROPERTY = PROPERTY_DOMAIN + ".catalogdb"; - private static final String REQUESTDB_PROPERTY = PROPERTY_DOMAIN + ".requestdb"; - private static final String SDNC_PROPERTY = PROPERTY_DOMAIN + ".sdnc"; - private static final String OPENSTACK_PROPERTY = PROPERTY_DOMAIN + ".openstack"; - private static final String BPMN_PROPERTY = PROPERTY_DOMAIN + ".bpmn"; - private static final String ASDC_PROPERTY = PROPERTY_DOMAIN + ".asdc"; - private static final String REQUESTDBATTSVC_PROPERTY = PROPERTY_DOMAIN + ".requestdbattsvc"; - private static final String DEFAULT_PROPERTY_VALUE = ""; + protected static final String CONTEXTPATH_PROPERTY = "management.endpoints.web.base-path"; + protected static final String PROPERTY_DOMAIN = "mso.health"; + protected static final String CATALOGDB_PROPERTY = PROPERTY_DOMAIN + ".endpoints.catalogdb"; + protected static final String REQUESTDB_PROPERTY = PROPERTY_DOMAIN + ".endpoints.requestdb"; + protected static final String SDNC_PROPERTY = PROPERTY_DOMAIN + ".endpoints.sdnc"; + protected static final String OPENSTACK_PROPERTY = PROPERTY_DOMAIN + ".endpoints.openstack"; + protected static final String BPMN_PROPERTY = PROPERTY_DOMAIN + ".endpoints.bpmn"; + protected static final String ASDC_PROPERTY = PROPERTY_DOMAIN + ".endpoints.asdc"; + protected static final String REQUESTDBATTSVC_PROPERTY = PROPERTY_DOMAIN + ".endpoints.requestdbattsvc"; + protected static final String MSO_AUTH_PROPERTY = PROPERTY_DOMAIN + ".auth"; + protected static final String DEFAULT_PROPERTY_VALUE = ""; // e.g. /manage private String actuatorContextPath; - private String endpointCatalogdb; - private String endpointRequestdb; - private String endpointSdnc; - private String endpointOpenstack; - private String endpointBpmn; - private String endpointAsdc; - private String endpointRequestdbAttsvc; @Autowired private Environment env; @Autowired private RestTemplate restTemplate; - private final String health = "/health"; + @Autowired + private HealthCheckConfig config; + + private static final String HEALTH = "/health"; + + private String msoAuth; @PostConstruct protected void init() { actuatorContextPath = env.getProperty(CONTEXTPATH_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointCatalogdb = env.getProperty(CATALOGDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointRequestdb = env.getProperty(REQUESTDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointSdnc = env.getProperty(SDNC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointOpenstack = env.getProperty(OPENSTACK_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointBpmn = env.getProperty(BPMN_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointAsdc = env.getProperty(ASDC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointRequestdbAttsvc = env.getProperty(REQUESTDBATTSVC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + msoAuth = env.getProperty(MSO_AUTH_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); } @GET @@ -108,29 +104,25 @@ public class GlobalHealthcheckHandler { @Context ContainerRequestContext requestContext) { Response HEALTH_CHECK_RESPONSE = null; // Build internal response object - HealthcheckResponse rsp = new HealthcheckResponse(); + HealthCheckResponse rsp = new HealthCheckResponse(); try { // Generated RequestId String requestId = requestContext.getProperty("requestId").toString(); logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); - // set APIH status, this is the main entry point - rsp.setApih(HealthcheckStatus.UP.toString()); - // set BPMN - rsp.setBpmn(querySubsystemHealth(MsoSubsystems.BPMN)); - // set SDNCAdapter - rsp.setSdncAdapter(querySubsystemHealth(MsoSubsystems.SDNC)); - // set ASDCController - rsp.setAsdcController(querySubsystemHealth(MsoSubsystems.ASDC)); - // set CatalogDbAdapter - rsp.setCatalogdbAdapter(querySubsystemHealth(MsoSubsystems.CATALOGDB)); - // set RequestDbAdapter - rsp.setRequestdbAdapter(querySubsystemHealth(MsoSubsystems.REQUESTDB)); - // set OpenStackAdapter - rsp.setOpenstackAdapter(querySubsystemHealth(MsoSubsystems.OPENSTACK)); - // set RequestDbAdapterAttSvc - rsp.setRequestdbAdapterAttsvc(querySubsystemHealth(MsoSubsystems.REQUESTDBATT)); + List<Endpoint> endpoints = config.getEndpoints().stream().filter(item -> { + if (!enableBpmn && SoSubsystems.BPMN.equals(item.getSubsystem())) { + return false; + } else { + return true; + } + }).collect(Collectors.toList()); + + for (Endpoint endpoint : endpoints) { + rsp.getSubsystems().add(querySubsystemHealth(endpoint)); + } + // set Message rsp.setMessage(String.format("HttpStatus: %s", HttpStatus.SC_OK)); logger.info(rsp.toString()); @@ -149,70 +141,51 @@ public class GlobalHealthcheckHandler { protected HttpEntity<String> buildHttpEntityForRequest() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - headers.set("Content-Type", "application/json"); + headers.set(HttpHeaders.CONTENT_TYPE, "application/json"); + headers.set(HttpHeaders.AUTHORIZATION, msoAuth); HttpEntity<String> entity = new HttpEntity<>("parameters", headers); return entity; } - protected String querySubsystemHealth(MsoSubsystems subsystem) { + protected HealthCheckSubsystem querySubsystemHealth(Endpoint subsystem) { + HealthCheckStatus status = HealthCheckStatus.DOWN; + URI uri = subsystem.getUri(); try { // get port number for the subsystem - String ept = getEndpointUrlForSubsystemEnum(subsystem); - // build final endpoint url - UriBuilder builder = UriBuilder.fromPath(ept).path(actuatorContextPath).path(health); - URI uri = builder.build(); - logger.info("Calculated URL: {}", uri.toString()); + uri = UriBuilder.fromUri(subsystem.getUri()).path(actuatorContextPath).path(HEALTH).build(); + logger.info("Calculated URL: {}", uri); ResponseEntity<SubsystemHealthcheckResponse> result = restTemplate.exchange(uri, HttpMethod.GET, buildHttpEntityForRequest(), SubsystemHealthcheckResponse.class); - return processResponseFromSubsystem(result, subsystem); + status = processResponseFromSubsystem(result, subsystem); + } catch (Exception ex) { logger.error("Exception occured in GlobalHealthcheckHandler.querySubsystemHealth() ", ex); - return HealthcheckStatus.DOWN.toString(); } + + return new HealthCheckSubsystem(subsystem.getSubsystem(), uri, status); } - protected String processResponseFromSubsystem(ResponseEntity<SubsystemHealthcheckResponse> result, - MsoSubsystems subsystem) { + protected HealthCheckStatus processResponseFromSubsystem(ResponseEntity<SubsystemHealthcheckResponse> result, + Endpoint endpoint) { if (result == null || result.getStatusCodeValue() != HttpStatus.SC_OK) { logger.error(String.format("Globalhealthcheck: checking subsystem: %s failed ! result object is: %s", - subsystem, result == null ? "NULL" : result)); - return HealthcheckStatus.DOWN.toString(); + endpoint.getSubsystem(), result == null ? "NULL" : result)); + return HealthCheckStatus.DOWN; } SubsystemHealthcheckResponse body = result.getBody(); String status = body.getStatus(); if ("UP".equalsIgnoreCase(status)) { - return HealthcheckStatus.UP.toString(); + return HealthCheckStatus.UP; } else { - logger.error("{}, query health endpoint did not return UP status!", subsystem); - return HealthcheckStatus.DOWN.toString(); + logger.error("{}, query health endpoint did not return UP status!", endpoint.getSubsystem()); + return HealthCheckStatus.DOWN; } } - - protected String getEndpointUrlForSubsystemEnum(MsoSubsystems subsystem) { - switch (subsystem) { - case SDNC: - return this.endpointSdnc; - case ASDC: - return this.endpointAsdc; - case BPMN: - return this.endpointBpmn; - case CATALOGDB: - return this.endpointCatalogdb; - case OPENSTACK: - return this.endpointOpenstack; - case REQUESTDB: - return this.endpointRequestdb; - case REQUESTDBATT: - return this.endpointRequestdbAttsvc; - default: - return ""; - } - } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheck.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheck.java new file mode 100644 index 0000000000..1899cdd765 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheck.java @@ -0,0 +1,84 @@ +package org.onap.so.apihandlerinfra; + +import java.net.URI; +import javax.ws.rs.core.UriBuilder; +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "mso.health.enpoints") +public class HealthCheck { + + private Subsystem subsystem; + private URI uri; + private HealthCheckStatus status = HealthCheckStatus.DOWN; + + public HealthCheck() { + + } + + public HealthCheck(String subsystem, String uri) { + this.subsystem = SoSubsystems.valueOf(subsystem.toUpperCase()); + this.uri = UriBuilder.fromUri(uri).build(); + } + + public HealthCheck(Subsystem subsystem, URI uri) { + this.subsystem = subsystem; + this.uri = uri; + } + + public HealthCheck(Subsystem subsystem, URI uri, HealthCheckStatus status) { + this.subsystem = subsystem; + this.uri = uri; + this.status = status; + } + + public Subsystem getSubsystem() { + return subsystem; + } + + public void setSubsystem(Subsystem component) { + this.subsystem = component; + } + + public URI getUri() { + return uri; + } + + public void setUri(URI uri) { + this.uri = uri; + } + + public HealthCheckStatus getStatus() { + return status; + } + + public void setStatus(HealthCheckStatus status) { + this.status = status; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("subsystem", subsystem).append("uri", uri).append("status", status) + .toString(); + } + + @Override + public boolean equals(final Object other) { + if (!(other instanceof HealthCheck)) { + return false; + } + HealthCheck castOther = (HealthCheck) other; + return new EqualsBuilder().append(subsystem, castOther.subsystem).append(uri, castOther.uri) + .append(status, castOther.status).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(subsystem).append(uri).append(status).toHashCode(); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConfig.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConfig.java new file mode 100644 index 0000000000..11fd94bc91 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConfig.java @@ -0,0 +1,83 @@ +/*- + * ============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.apihandlerinfra; + +import java.net.URI; +import java.util.List; +import javax.validation.constraints.NotNull; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.validation.annotation.Validated; + +@Configuration +@ConfigurationProperties(prefix = "mso.health") +@Validated +public class HealthCheckConfig { + + @NotNull + private List<Endpoint> endpoints; + + public List<Endpoint> getEndpoints() { + return endpoints; + } + + public void setEndpoints(List<Endpoint> endpoints) { + this.endpoints = endpoints; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("endpoints", this.endpoints).toString(); + } + + @Validated + public static class Endpoint { + @NotNull + private Subsystem subsystem; + @NotNull + private URI uri; + + public Endpoint() { + + } + + public Endpoint(Subsystem subsystem, URI uri) { + this.subsystem = subsystem; + this.uri = uri; + } + + public Subsystem getSubsystem() { + return subsystem; + } + + public void setSubsystem(Subsystem subsystem) { + this.subsystem = subsystem; + } + + public URI getUri() { + return uri; + } + + public void setUri(URI uri) { + this.uri = uri; + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConverter.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConverter.java new file mode 100644 index 0000000000..ed06018e7b --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConverter.java @@ -0,0 +1,22 @@ +package org.onap.so.apihandlerinfra; + +import java.net.URI; +import javax.ws.rs.core.UriBuilder; +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.stereotype.Component; + +@Component +public class HealthCheckConverter { + + + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + if (sourceType.getType() == String.class && targetType.getType() == Subsystem.class) { + return SoSubsystems.valueOf(((String) source).toUpperCase()); + } else if (sourceType.getType() == String.class && targetType.getType() == URI.class) { + return UriBuilder.fromUri((String) source).build(); + } else { + return source; + } + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/ICryptoHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckResponse.java index 479d2e82bd..5400249c65 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/ICryptoHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckResponse.java @@ -17,13 +17,33 @@ * limitations under the License. * ============LICENSE_END========================================================= */ +package org.onap.so.apihandlerinfra; -package org.onap.so.bpmn.common.util; +import java.util.ArrayList; +import java.util.List; -public interface ICryptoHandler { - public String getMsoAaiPassword(); +public class HealthCheckResponse { + + + private List<HealthCheckSubsystem> subsystems = new ArrayList<>(); + private String message; + + + public List<HealthCheckSubsystem> getSubsystems() { + return subsystems; + } + + public void setSubsystems(List<HealthCheckSubsystem> subsystems) { + this.subsystems = subsystems; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } - public String encryptMsoPassword(String plainPwd); - public String decryptMsoPassword(String encryptedPwd); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckStatus.java index 077a3c2d60..6b31c1f1ed 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckStatus.java @@ -19,12 +19,12 @@ */ package org.onap.so.apihandlerinfra; -public enum HealthcheckStatus { +public enum HealthCheckStatus { UP("UP"), DOWN("DOWN"); private String status; - private HealthcheckStatus(String status) { + private HealthCheckStatus(String status) { this.status = status; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckSubsystem.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckSubsystem.java new file mode 100644 index 0000000000..e1335b952c --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckSubsystem.java @@ -0,0 +1,40 @@ +package org.onap.so.apihandlerinfra; + +import java.net.URI; + +public class HealthCheckSubsystem { + + private Subsystem subsystem; + private URI uri; + private HealthCheckStatus status; + + public HealthCheckSubsystem(Subsystem subsystem, URI uri, HealthCheckStatus status) { + this.subsystem = subsystem; + this.uri = uri; + this.status = status; + } + + public Subsystem getSubsystem() { + return subsystem; + } + + public void setSubsystem(Subsystem subsystem) { + this.subsystem = subsystem; + } + + public URI getUri() { + return uri; + } + + public void setUri(URI uri) { + this.uri = uri; + } + + public HealthCheckStatus getStatus() { + return status; + } + + public void setStatus(HealthCheckStatus status) { + this.status = status; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java deleted file mode 100644 index fad3dd4055..0000000000 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java +++ /dev/null @@ -1,116 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.so.apihandlerinfra; - -import org.apache.commons.lang3.builder.ToStringBuilder; - -public class HealthcheckResponse { - private String apih; - private String bpmn; - private String sdncAdapter; - private String asdcController; - private String catalogdbAdapter; - private String requestdbAdapter; - private String openstackAdapter; - private String requestdbAdapterAttsvc; - private String message = ""; - - public String getApih() { - return apih; - } - - public void setApih(String apih) { - this.apih = apih; - } - - public String getBpmn() { - return bpmn; - } - - public void setBpmn(String bpmn) { - this.bpmn = bpmn; - } - - public String getSdncAdapter() { - return sdncAdapter; - } - - public void setSdncAdapter(String sdncAdapter) { - this.sdncAdapter = sdncAdapter; - } - - public String getAsdcController() { - return asdcController; - } - - public void setAsdcController(String asdcController) { - this.asdcController = asdcController; - } - - public String getCatalogdbAdapter() { - return catalogdbAdapter; - } - - public void setCatalogdbAdapter(String catalogdbAdapter) { - this.catalogdbAdapter = catalogdbAdapter; - } - - public String getRequestdbAdapter() { - return requestdbAdapter; - } - - public void setRequestdbAdapter(String requestdbAdapter) { - this.requestdbAdapter = requestdbAdapter; - } - - public String getOpenstackAdapter() { - return openstackAdapter; - } - - public void setOpenstackAdapter(String openstackAdapter) { - this.openstackAdapter = openstackAdapter; - } - - public String getRequestdbAdapterAttsvc() { - return requestdbAdapterAttsvc; - } - - public void setRequestdbAdapterAttsvc(String requestdbAdapterAttsvc) { - this.requestdbAdapterAttsvc = requestdbAdapterAttsvc; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - @Override - public String toString() { - return new ToStringBuilder(this).append("apih", this.apih).append("pbmn", this.bpmn) - .append("sdncAdapter", this.sdncAdapter).append("asdcController", this.asdcController) - .append("catalogdbAdapter", this.catalogdbAdapter).append("requestdbAdapter", this.requestdbAdapter) - .append("openstackAdapter", this.openstackAdapter) - .append("requestdbAdapterAttsvc", this.requestdbAdapterAttsvc).append("message", this.message) - .toString(); - } -} 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 6f36fb2aff..a5ccb1b29b 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 @@ -42,6 +42,7 @@ import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.EnumUtils; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandler.common.ResponseBuilder; @@ -411,7 +412,11 @@ public class OrchestrationRequests { protected String mapRequestStatusToRequest(InfraActiveRequests iar, String format) { if (iar.getRequestStatus() != null) { - if (!StringUtils.isBlank(format) && OrchestrationRequestFormat.DETAIL.toString().equalsIgnoreCase(format)) { + boolean requestFormat = false; + if (format != null) { + requestFormat = EnumUtils.isValidEnum(OrchestrationRequestFormat.class, format.toUpperCase()); + } + if (requestFormat) { return iar.getRequestStatus(); } else { if (Status.ABORTED.toString().equalsIgnoreCase(iar.getRequestStatus()) 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 9ab95a2319..2fddfd9a95 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 @@ -295,7 +295,7 @@ public class RequestHandlerUtils extends AbstractRestHandler { String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { InfraActiveRequests dup = null; try { - if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance + if (!(instanceName == null && "service".equals(requestScope) && (action == Action.createInstance || action == Action.activateInstance || action == Action.assignInstance))) { dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope); } @@ -334,7 +334,7 @@ public class RequestHandlerUtils extends AbstractRestHandler { updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); } for (HistoricProcessInstance instance : response.getBody()) { - if (instance.getState().equals("ACTIVE")) { + if (("ACTIVE").equals(instance.getState())) { return true; } else { updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); @@ -479,24 +479,11 @@ public class RequestHandlerUtils extends AbstractRestHandler { boolean isAlaCarte, Actions action) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); - if (msoRawRequest != null) { - ServiceInstancesRequest sir = mapper.readValue(msoRawRequest, ServiceInstancesRequest.class); - if (serviceInstRequest != null && serviceInstRequest.getRequestDetails() != null - && serviceInstRequest.getRequestDetails().getRequestParameters() != null) { - if (!isAlaCarte && Action.createInstance.equals(action)) { - sir.getRequestDetails() - .setCloudConfiguration(serviceInstRequest.getRequestDetails().getCloudConfiguration()); - sir.getRequestDetails().getRequestParameters().setUserParams( - serviceInstRequest.getRequestDetails().getRequestParameters().getUserParams()); - } - sir.getRequestDetails().getRequestParameters() - .setUsePreload(serviceInstRequest.getRequestDetails().getRequestParameters().getUsePreload()); - } - - logger.debug("Value as string: {}", mapper.writeValueAsString(sir)); - return mapper.writeValueAsString(sir); + if (serviceInstRequest != null) { + return mapper.writeValueAsString(serviceInstRequest); + } else { + return msoRawRequest; } - return null; } public Optional<String> retrieveModelName(RequestParameters requestParams) { 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 5b827d9cf8..b1d38983ec 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 @@ -51,6 +51,7 @@ import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException; import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.apihandlerinfra.infra.rest.handler.AbstractRestHandler; +import org.onap.so.apihandlerinfra.infra.rest.validators.RequestValidatorListenerRunner; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.constants.Status; import org.onap.so.db.catalog.beans.NetworkResource; @@ -124,6 +125,9 @@ public class ServiceInstances extends AbstractRestHandler { @Autowired private RequestHandlerUtils requestHandlerUtils; + @Autowired + private RequestValidatorListenerRunner requestValidatorListenerRunner; + @POST @Path("/{version:[vV][5-7]}/serviceInstances") @Consumes(MediaType.APPLICATION_JSON) @@ -764,6 +768,13 @@ public class ServiceInstances extends AbstractRestHandler { public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException { + return serviceInstances(requestJSON, action, instanceIdMap, version, requestId, requestUri, null); + + } + + public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, + String version, String requestId, String requestUri, HashMap<String, String> queryParams) + throws ApiException { String serviceInstanceId; Boolean aLaCarte = null; ServiceInstancesRequest sir; @@ -771,6 +782,8 @@ public class ServiceInstances extends AbstractRestHandler { sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); action = handleReplaceInstance(action, sir); + requestValidatorListenerRunner.runValidations(requestUri, instanceIdMap, sir, queryParams); + String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SoSubsystems.java index 13f1e52068..5842531dc3 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SoSubsystems.java @@ -19,18 +19,18 @@ */ package org.onap.so.apihandlerinfra; -public enum MsoSubsystems { +public enum SoSubsystems implements Subsystem { APIH("API Handler"), ASDC("ASDC Controller"), BPMN("BPMN Infra"), CATALOGDB("CatalogDb Adapter"), OPENSTACK("Openstack Adapter"), REQUESTDB("RequestDB Adapter"), - REQUESTDBATT("RequestDB Adapter ATT Svc"), SDNC("SDNC Adapter"); + private String subsystem; - private MsoSubsystems(String subsystem) { + private SoSubsystems(String subsystem) { this.subsystem = subsystem; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Subsystem.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Subsystem.java new file mode 100644 index 0000000000..88626f3168 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Subsystem.java @@ -0,0 +1,5 @@ +package org.onap.so.apihandlerinfra; + +public interface Subsystem { + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java new file mode 100644 index 0000000000..344e5438c9 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java @@ -0,0 +1,85 @@ +package org.onap.so.apihandlerinfra.infra.rest; + +import java.util.Optional; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.L3Network; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aai.domain.yang.VfModule; +import org.onap.aai.domain.yang.VolumeGroup; +import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class AAIDataRetrieval { + + private static final String VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID = "VF Module Not Found In Inventory, VnfId: "; + + private AAIResourcesClient aaiResourcesClient; + + private static final Logger logger = LoggerFactory.getLogger(AAIDataRetrieval.class); + + public ServiceInstance getServiceInstance(String serviceInstanceId) { + return this.getAaiResourcesClient() + .get(ServiceInstance.class, + AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)) + .orElseGet(() -> { + logger.debug("No Service Instance found in A&AI ServiceInstanceId: {}", serviceInstanceId); + return null; + }); + } + + + public VfModule getAAIVfModule(String vnfId, String vfModuleId) { + return this.getAaiResourcesClient() + .get(VfModule.class, AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)) + .orElseGet(() -> { + logger.debug("No Vf Module found in A&AI VnfId: {}" + ", VfModuleId: {}", vnfId, vfModuleId); + return null; + }); + } + + public GenericVnf getGenericVnf(String vnfId) { + return this.getAaiResourcesClient() + .get(GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)) + .orElseGet(() -> { + logger.debug("No Generic VNF found in A&AI VnfId: {}", vnfId); + return null; + }); + } + + public VolumeGroup getVolumeGroup(String vnfId, String volumeGroupId) throws AAIEntityNotFound { + AAIResultWrapper wrapper = + this.getAaiResourcesClient().get(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + .relatedTo(AAIObjectType.VOLUME_GROUP, volumeGroupId)); + Optional<VolumeGroup> volume = wrapper.asBean(VolumeGroup.class); + if (volume.isPresent()) { + return volume.get(); + } else { + logger.debug("No VolumeGroup in A&AI found: {}", vnfId); + return null; + } + } + + public L3Network getNetwork(String networkId) { + return this.getAaiResourcesClient() + .get(L3Network.class, AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId)) + .orElseGet(() -> { + logger.debug("No Network found in A&AI NetworkId: {}", networkId); + return null; + }); + } + + protected AAIResourcesClient getAaiResourcesClient() { + if (aaiResourcesClient == null) { + aaiResourcesClient = new AAIResourcesClient(); + } + return aaiResourcesClient; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java index bb5b4edfe4..ee2bb586cf 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java @@ -33,10 +33,7 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound; import org.onap.so.apihandlerinfra.infra.rest.exception.CloudConfigurationNotFoundException; import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.client.aai.entities.AAIResultWrapper; -import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.constants.Status; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; @@ -75,17 +72,19 @@ public class BpmnRequestBuilder { @Autowired private RequestsDbClient infraActiveRequestsClient; + @Autowired + private AAIDataRetrieval aaiDataRet; + private ObjectMapper mapper = new ObjectMapper(); - private AAIResourcesClient aaiResourcesClient; public ServiceInstancesRequest buildVFModuleDeleteRequest(String vnfId, String vfModuleId, ModelType modelType) throws AAIEntityNotFound { - GenericVnf vnf = getGenericVnf(vnfId); + GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId); if (vnf == null) { throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId); } - VfModule vfModule = getAAIVfModule(vnfId, vfModuleId); + VfModule vfModule = aaiDataRet.getAAIVfModule(vnfId, vfModuleId); if (vfModule == null) { throw new AAIEntityNotFound(VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " vfModuleId: " + vfModuleId); } @@ -94,11 +93,11 @@ public class BpmnRequestBuilder { public ServiceInstancesRequest buildVolumeGroupDeleteRequest(String vnfId, String volumeGroupId) throws AAIEntityNotFound { - GenericVnf vnf = getGenericVnf(vnfId); + GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId); if (vnf == null) { throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId); } - VolumeGroup volumeGroup = getVolumeGroup(vnfId, volumeGroupId); + VolumeGroup volumeGroup = aaiDataRet.getVolumeGroup(vnfId, volumeGroupId); if (volumeGroup == null) { throw new AAIEntityNotFound( VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " volumeGroupId: " + volumeGroupId); @@ -107,7 +106,7 @@ public class BpmnRequestBuilder { } public ServiceInstancesRequest buildServiceDeleteRequest(String serviceInstanceId) throws AAIEntityNotFound { - ServiceInstance serviceInstance = getServiceInstance(serviceInstanceId); + ServiceInstance serviceInstance = aaiDataRet.getServiceInstance(serviceInstanceId); if (serviceInstance == null) { throw new AAIEntityNotFound( "ServiceInstance Not Found In Inventory, ServiceInstanceId: " + serviceInstanceId); @@ -116,7 +115,7 @@ public class BpmnRequestBuilder { } public ServiceInstancesRequest buildVnfDeleteRequest(String vnfId) throws AAIEntityNotFound { - GenericVnf vnf = getGenericVnf(vnfId); + GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId); if (vnf == null) { throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId); } @@ -124,7 +123,7 @@ public class BpmnRequestBuilder { } public ServiceInstancesRequest buildNetworkDeleteRequest(String networkId) throws AAIEntityNotFound { - L3Network network = getNetwork(networkId); + L3Network network = aaiDataRet.getNetwork(networkId); if (network == null) { throw new AAIEntityNotFound("Network Not Found In Inventory, NetworkId: " + networkId); } @@ -407,72 +406,5 @@ public class BpmnRequestBuilder { return requestParams; } - public VfModule getAAIVfModule(String vnfId, String vfModuleId) { - return this.getAaiResourcesClient() - .get(VfModule.class, AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)) - .orElseGet(() -> { - logger.debug("No Vf Module found in A&AI VnfId: {}" + ", VfModuleId: {}", vnfId, vfModuleId); - return null; - }); - } - - public GenericVnf getGenericVnf(String vnfId) { - return this.getAaiResourcesClient() - .get(GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)) - .orElseGet(() -> { - logger.debug("No Generic VNF found in A&AI VnfId: {}", vnfId); - return null; - }); - } - - public VolumeGroup getVolumeGroup(String vnfId, String volumeGroupId) throws AAIEntityNotFound { - GenericVnf vnf = getGenericVnf(vnfId); - AAIResultWrapper wrapper = new AAIResultWrapper(vnf); - List<AAIResourceUri> listVserverWrapper; - Optional<AAIResourceUri> volumeGroupURI; - if (wrapper.getRelationships().isPresent()) { - listVserverWrapper = wrapper.getRelationships().get().getRelatedUris(AAIObjectType.VOLUME_GROUP); - volumeGroupURI = listVserverWrapper.stream() - .filter(resourceURI -> resourceURI.getURIKeys().get("volume-group-id").equals(volumeGroupId)) - .findFirst(); - } else { - throw new AAIEntityNotFound( - VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " volumeGroupId: " + volumeGroupId); - } - return this.getAaiResourcesClient().get(VolumeGroup.class, volumeGroupURI.get()).orElseGet(() -> { - logger.debug("No VolumeGroup in A&AI found: {}", vnfId); - return null; - }); - } - - public ServiceInstance getServiceInstance(String serviceInstanceId) { - return this.getAaiResourcesClient() - .get(ServiceInstance.class, - AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)) - .orElseGet(() -> { - logger.debug("No Service Instance found in A&AI ServiceInstanceId: {}", serviceInstanceId); - return null; - }); - } - - public L3Network getNetwork(String networkId) { - return this.getAaiResourcesClient() - .get(L3Network.class, AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId)) - .orElseGet(() -> { - logger.debug("No Network found in A&AI NetworkId: {}", networkId); - return null; - }); - } - - public AAIResourcesClient getAaiResourcesClient() { - if (aaiResourcesClient == null) { - aaiResourcesClient = new AAIResourcesClient(); - } - return aaiResourcesClient; - } - - public void setAaiResourcesClient(AAIResourcesClient aaiResourcesClient) { - this.aaiResourcesClient = aaiResourcesClient; - } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java new file mode 100644 index 0000000000..4aa60152dd --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java @@ -0,0 +1,40 @@ +/*- + * ============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.apihandlerinfra.infra.rest.validators; + +import java.util.Map; +import java.util.Optional; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; + +public interface RequestValidator { + + + /** + * Should this validator run for given request + * + * @return + */ + public boolean shouldRunFor(String uri, ServiceInstancesRequest request); + + + public Optional<String> validate(Map<String, String> instanceIdMap, ServiceInstancesRequest request, + Map<String, String> queryParams); +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidatorListenerRunner.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidatorListenerRunner.java new file mode 100644 index 0000000000..d689c6b7a5 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidatorListenerRunner.java @@ -0,0 +1,80 @@ +/*- + * ============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.apihandlerinfra.infra.rest.validators; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; +import org.javatuples.Pair; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.listener.ListenerRunner; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class RequestValidatorListenerRunner extends ListenerRunner { + + private static Logger logger = LoggerFactory.getLogger(RequestValidatorListenerRunner.class); + + protected List<RequestValidator> requestValidators; + + @PostConstruct + protected void init() { + requestValidators = new ArrayList<>( + Optional.ofNullable(context.getBeansOfType(RequestValidator.class)).orElse(new HashMap<>()).values()); + } + + public boolean runValidations(String requestURI, Map<String, String> instanceIdMap, ServiceInstancesRequest request, + Map<String, String> queryParams) throws ApiException { + logger.info("Running local validations"); + List<Pair<String, Optional<String>>> results = + runValidations(requestValidators, instanceIdMap, request, queryParams, requestURI); + if (!results.isEmpty()) { + throw new ValidateException("Failed Validations:\n" + + results.stream().map(item -> String.format("%s: %s", item.getValue0(), item.getValue1().get())) + .collect(Collectors.joining("\n")), + 400); + } + + return true; + } + + protected List<Pair<String, Optional<String>>> runValidations(List<? extends RequestValidator> validators, + Map<String, String> instanceIdMap, ServiceInstancesRequest request, Map<String, String> queryParams, + String requestURI) { + + List<? extends RequestValidator> filtered = + filterListeners(validators, (item -> item.shouldRunFor(requestURI, request))); + + List<Pair<String, Optional<String>>> results = new ArrayList<>(); + filtered.forEach(item -> results + .add(new Pair<>(item.getClass().getName(), item.validate(instanceIdMap, request, queryParams)))); + + return results.stream().filter(item -> item.getValue1().isPresent()).collect(Collectors.toList()); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java index 216588432b..ef5abe9f74 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java @@ -137,10 +137,8 @@ public class ModelDistributionRequest { se.setMessageId(messageId); se.setText(text); if (variables != null) { - if (variables != null) { - for (String variable : variables) { - se.getVariables().add(variable); - } + for (String variable : variables) { + se.getVariables().add(variable); } } re.setServiceException(se); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java index 71405b0f63..20be2b5a8b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java @@ -43,7 +43,8 @@ public class PlatformLOBValidation implements ValidationRule { platform = info.getSir().getRequestDetails().getPlatform(); lineOfBusiness = info.getSir().getRequestDetails().getLineOfBusiness(); - if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance) { + if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance + && !info.getReqParameters().getEnforceValidNfValues()) { if (reqVersion > 5 && platform == null) { throw new ValidationException("platform"); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java index 584269715a..cebbd6389c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java @@ -41,10 +41,12 @@ public class ProjectOwningEntityValidation implements ValidationRule { String requestScope = info.getRequestScope(); Actions action = info.getAction(); + project = info.getSir().getRequestDetails().getProject(); owningEntity = info.getSir().getRequestDetails().getOwningEntity(); if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.service.name()) - && action == Action.createInstance || action == Action.assignInstance) { + && !info.getReqParameters().getEnforceValidNfValues() && action == Action.createInstance + || action == Action.assignInstance) { if (reqVersion > 5 && owningEntity == null) { throw new ValidationException("owningEntity"); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java index e6b5163f59..830f38f98b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java @@ -30,6 +30,7 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import org.camunda.bpm.engine.impl.persistence.entity.HistoricActivityInstanceEntity; import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; @@ -119,7 +120,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getActivityNameTest() throws IOException { + public void getActivityNameTest() { String expectedActivityName = "Last task executed: BB to Execute"; String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); @@ -127,7 +128,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getActivityNameNullActivityNameTest() throws IOException { + public void getActivityNameNullActivityNameTest() { String expectedActivityName = "Task name is null."; HistoricActivityInstanceEntity activityInstance = new HistoricActivityInstanceEntity(); List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>(); @@ -139,7 +140,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getActivityNameNullListTest() throws IOException { + public void getActivityNameNullListTest() { String expectedActivityName = "No results returned on activityInstance history lookup."; List<HistoricActivityInstanceEntity> activityInstanceList = null; String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); @@ -148,7 +149,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getActivityNameEmptyListTest() throws IOException { + public void getActivityNameEmptyListTest() { String expectedActivityName = "No results returned on activityInstance history lookup."; List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>(); String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); @@ -157,7 +158,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getTaskNameTest() throws IOException, ContactCamundaException { + public void getTaskNameTest() throws ContactCamundaException { doReturn(processInstanceResponse).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID); doReturn(activityInstanceResponse).when(camundaRequestHandler) .getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b", REQUEST_ID); @@ -170,7 +171,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getTaskNameNullProcessInstanceListTest() throws IOException, ContactCamundaException { + public void getTaskNameNullProcessInstanceListTest() throws ContactCamundaException { ResponseEntity<List<HistoricProcessInstanceEntity>> response = new ResponseEntity<>(null, HttpStatus.OK); doReturn(response).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID); String expected = "No processInstances returned for requestId: " + REQUEST_ID; @@ -181,7 +182,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getTaskNameNullProcessInstanceIdTest() throws IOException, ContactCamundaException { + public void getTaskNameNullProcessInstanceIdTest() throws ContactCamundaException { HistoricProcessInstanceEntity processInstance = new HistoricProcessInstanceEntity(); List<HistoricProcessInstanceEntity> processInstanceList = new ArrayList<>(); processInstanceList.add(processInstance); @@ -196,7 +197,19 @@ public class CamundaRequestHandlerTest { } @Test - public void getTaskNameProcessInstanceLookupFailureTest() throws IOException, ContactCamundaException { + public void getTaskNameEmptyProcessInstanceListTest() throws ContactCamundaException { + ResponseEntity<List<HistoricProcessInstanceEntity>> response = + new ResponseEntity<>(Collections.emptyList(), HttpStatus.OK); + doReturn(response).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID); + String expected = "No processInstances returned for requestId: " + REQUEST_ID; + + String actual = camundaRequestHandler.getTaskName(REQUEST_ID); + + assertEquals(expected, actual); + } + + @Test + public void getTaskNameProcessInstanceLookupFailureTest() throws ContactCamundaException { doThrow(HttpClientErrorException.class).when(camundaRequestHandler) .getCamundaProcessInstanceHistory(REQUEST_ID); @@ -205,7 +218,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getCamundaActivityHistoryTest() throws IOException, ContactCamundaException { + public void getCamundaActivityHistoryTest() throws ContactCamundaException { HttpHeaders headers = setHeaders(); HttpEntity<?> requestEntity = new HttpEntity<>(headers); String targetUrl = "http://localhost:8089/sobpmnengine/history/activity-instance?processInstanceId=" @@ -239,7 +252,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getCamundaProccesInstanceHistoryTest() throws IOException, ContactCamundaException { + public void getCamundaProccesInstanceHistoryTest() { HttpHeaders headers = setHeaders(); HttpEntity<?> requestEntity = new HttpEntity<>(headers); String targetUrl = @@ -292,7 +305,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getCamundaProccesInstanceHistoryFailThenSuccessTest() throws IOException, ContactCamundaException { + public void getCamundaProccesInstanceHistoryFailThenSuccessTest() { HttpHeaders headers = setHeaders(); HttpEntity<?> requestEntity = new HttpEntity<>(headers); String targetUrl = @@ -310,7 +323,7 @@ public class CamundaRequestHandlerTest { } @Test - public void setCamundaHeadersTest() throws ContactCamundaException, RequestDbFailureException { + public void setCamundaHeadersTest() { String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password String key = "07a7159d3bf51a0e53be7a8f89699be7"; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java index 928b488f6a..0291cfd2ea 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java @@ -20,70 +20,67 @@ package org.onap.so.apihandlerinfra; -import static org.junit.Assert.assertArrayEquals; +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.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyObject; +import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import java.net.URI; -import java.util.Collections; -import java.util.List; -import org.springframework.test.util.ReflectionTestUtils; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; import org.json.JSONException; -import org.junit.Rule; import org.junit.Test; -import org.mockito.InjectMocks; +import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; -import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.onap.so.apihandlerinfra.HealthCheckConfig.Endpoint; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.client.RestTemplate; +import com.fasterxml.jackson.core.JsonProcessingException; +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {GenericStringConverter.class, HealthCheckConverter.class}, + initializers = {ConfigFileApplicationContextInitializer.class}) +@ActiveProfiles("test") +@EnableConfigurationProperties({HealthCheckConfig.class}) public class GlobalHealthcheckHandlerTest { - @Mock - RestTemplate restTemplate; + @MockBean + private RestTemplate restTemplate; - @Mock - ContainerRequestContext requestContext; + @MockBean + private ContainerRequestContext requestContext; - @InjectMocks - @Spy - GlobalHealthcheckHandler globalhealth; - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); + @SpyBean + private GlobalHealthcheckHandler globalhealth; @Test public void testQuerySubsystemHealthNullResult() { ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); - ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8080"); Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), ArgumentMatchers.any(HttpMethod.class), ArgumentMatchers.<HttpEntity<?>>any(), ArgumentMatchers.<Class<Object>>any())).thenReturn(null); - String result = globalhealth.querySubsystemHealth(MsoSubsystems.BPMN); - System.out.println(result); - assertEquals(HealthcheckStatus.DOWN.toString(), result); + HealthCheckSubsystem result = globalhealth + .querySubsystemHealth(new Endpoint(SoSubsystems.BPMN, UriBuilder.fromPath("http://localhost").build())); + assertEquals(HealthCheckStatus.DOWN, result.getStatus()); } @Test public void testQuerySubsystemHealthNotNullResult() { ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); - ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); subSystemResponse.setStatus("UP"); @@ -92,20 +89,13 @@ public class GlobalHealthcheckHandlerTest { Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), ArgumentMatchers.any(HttpMethod.class), ArgumentMatchers.<HttpEntity<?>>any(), ArgumentMatchers.<Class<Object>>any())).thenReturn(r); - String result = globalhealth.querySubsystemHealth(MsoSubsystems.ASDC); - System.out.println(result); - assertEquals(HealthcheckStatus.UP.toString(), result); + HealthCheckSubsystem result = globalhealth + .querySubsystemHealth(new Endpoint(SoSubsystems.ASDC, UriBuilder.fromPath("http://localhost").build())); + assertEquals(HealthCheckStatus.UP, result.getStatus()); } private Response globalHealthcheck(String status) { ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); - ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); - ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081"); - ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082"); - ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083"); - ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084"); - ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085"); - ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086"); SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); @@ -116,70 +106,41 @@ public class GlobalHealthcheckHandlerTest { Mockito.when(requestContext.getProperty(anyString())).thenReturn("1234567890"); Response response = globalhealth.globalHealthcheck(true, requestContext); - return response; } @Test - public void globalHealthcheckAllUPTest() throws JSONException { - Response response = globalHealthcheck("UP"); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - HealthcheckResponse root; - root = (HealthcheckResponse) response.getEntity(); - String apistatus = root.getApih(); - assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String bpmnstatus = root.getBpmn(); - assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String sdncstatus = root.getSdncAdapter(); - assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + public void globalHealthcheckAllUPTest() throws JSONException, JsonProcessingException { - String asdcstatus = root.getAsdcController(); - assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + HealthCheckResponse expected = new HealthCheckResponse(); - String catastatus = root.getCatalogdbAdapter(); - assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String reqdbstatus = root.getRequestdbAdapter(); - assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String openstatus = root.getOpenstackAdapter(); - assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + for (Subsystem system : SoSubsystems.values()) { + expected.getSubsystems().add(new HealthCheckSubsystem(system, + UriBuilder.fromUri("http://localhost").build(), HealthCheckStatus.UP)); + } + expected.setMessage("HttpStatus: 200"); + Response response = globalHealthcheck("UP"); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + HealthCheckResponse root; + root = (HealthCheckResponse) response.getEntity(); + assertThat(root, sameBeanAs(expected).ignoring("subsystems.uri").ignoring("subsystems.subsystem")); - String reqdbattstatus = root.getRequestdbAdapterAttsvc(); - assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); } @Test public void globalHealthcheckAllDOWNTest() throws JSONException { + HealthCheckResponse expected = new HealthCheckResponse(); + + for (Subsystem system : SoSubsystems.values()) { + expected.getSubsystems().add(new HealthCheckSubsystem(system, + UriBuilder.fromUri("http://localhost").build(), HealthCheckStatus.DOWN)); + } + expected.setMessage("HttpStatus: 200"); Response response = globalHealthcheck("DOWN"); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - HealthcheckResponse root; - root = (HealthcheckResponse) response.getEntity(); - String apistatus = root.getApih(); - assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String bpmnstatus = root.getBpmn(); - assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String sdncstatus = root.getSdncAdapter(); - assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String asdcstatus = root.getAsdcController(); - assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String catastatus = root.getCatalogdbAdapter(); - assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String reqdbstatus = root.getRequestdbAdapter(); - assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String openstatus = root.getOpenstackAdapter(); - assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String reqdbattstatus = root.getRequestdbAdapterAttsvc(); - assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + HealthCheckResponse root; + root = (HealthCheckResponse) response.getEntity(); + assertThat(root, sameBeanAs(expected).ignoring("subsystems.uri").ignoring("subsystems.subsystem")); } @Test @@ -189,40 +150,15 @@ public class GlobalHealthcheckHandlerTest { assertEquals(MediaType.APPLICATION_JSON, he.getHeaders().getContentType()); } - @Test - public void getEndpointUrlForSubsystemEnumTest() { - ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); - ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); - ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081"); - ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082"); - ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083"); - ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084"); - ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085"); - ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086"); - - String result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.ASDC); - assertEquals("http://localhost:8080", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.SDNC); - assertEquals("http://localhost:8081", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.BPMN); - assertEquals("http://localhost:8082", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.CATALOGDB); - assertEquals("http://localhost:8083", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.OPENSTACK); - assertEquals("http://localhost:8084", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDB); - assertEquals("http://localhost:8085", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDBATT); - assertEquals("http://localhost:8086", result); - } @Test public void processResponseFromSubsystemTest() { SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); subSystemResponse.setStatus("UP"); ResponseEntity<SubsystemHealthcheckResponse> r = new ResponseEntity<>(subSystemResponse, HttpStatus.OK); - String result = globalhealth.processResponseFromSubsystem(r, MsoSubsystems.BPMN); - assertEquals("UP", result); + Endpoint endpoint = new Endpoint(SoSubsystems.BPMN, UriBuilder.fromUri("http://localhost").build()); + HealthCheckStatus result = globalhealth.processResponseFromSubsystem(r, endpoint); + assertEquals(HealthCheckStatus.UP, result); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java index 5023155768..f672648a6b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java @@ -295,6 +295,14 @@ public class OrchestrationRequestsUnitTest { assertEquals(Status.ABORTED.toString(), result); } + @Test + public void mapRequestStatusToRequestForFormatStatusDetailTest() throws ApiException { + iar.setRequestStatus(Status.ABORTED.toString()); + String result = orchestrationRequests.mapRequestStatusToRequest(iar, "statusDetail"); + + assertEquals(Status.ABORTED.toString(), result); + } + @Test public void mapRequestStatusToRequestForFormatEmptyStringTest() throws ApiException { diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java index e28e36d307..a79aeb2bd7 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java @@ -2934,15 +2934,5 @@ public class ServiceInstancesTest extends BaseTest { Actions action = servInstances.handleReplaceInstance(Action.replaceInstance, sir); assertEquals(Action.replaceInstanceRetainAssignments, action); } - /* - * @Test public void buildSelfLinkUrlTest() throws Exception { // v - version String incomingUrl = - * "http://localhost:8080/onap/infra/so/serviceInstantiation/v7/serviceInstances"; String expectedSelfLink = - * "http://localhost:8080/orchestrationRequests/v7/efce3167-5e45-4666-9d4d-22e23648e5d1"; String requestId = - * "efce3167-5e45-4666-9d4d-22e23648e5d1"; Optional<URL> actualSelfLinkUrl = buildSelfLinkUrl(incomingUrl, - * requestId); assertEquals(expectedSelfLink, actualSelfLinkUrl.get().toString()); // V - Version String - * incomingUrlV = "http://localhost:8080/onap/infra/so/serviceInstantiation/V7/serviceInstances"; String - * expectedSelfLinkV = "http://localhost:8080/orchestrationRequests/V7/efce3167-5e45-4666-9d4d-22e23648e5d1"; - * Optional<URL> actualSelfLinkUrlV = buildSelfLinkUrl(incomingUrlV, requestId); assertEquals(expectedSelfLinkV, - * actualSelfLinkUrlV.get().toString()); } - */ } + diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java index 3644dd8e7f..f73da49e0d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java @@ -23,6 +23,7 @@ package org.onap.so.apihandlerinfra.infra.rest; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; import java.io.File; import java.util.Optional; import org.junit.Before; @@ -32,7 +33,6 @@ 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.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.ServiceInstance; @@ -40,6 +40,7 @@ import org.onap.aai.domain.yang.VfModule; import org.onap.aai.domain.yang.VolumeGroup; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; import org.onap.so.db.request.client.RequestsDbClient; @@ -55,15 +56,19 @@ public class BpmnRequestBuilderTest { @Rule public ExpectedException exceptionRule = ExpectedException.none(); + + @Mock + private AAIResourcesClient aaiResourcesClient; + @InjectMocks - @Spy - BpmnRequestBuilder reqBuilder; + private AAIDataRetrieval aaiData = spy(AAIDataRetrieval.class); @Mock private RequestsDbClient requestDBClient; - @Mock - private AAIResourcesClient aaiResourcesClient; + @InjectMocks + private BpmnRequestBuilder reqBuilder = spy(BpmnRequestBuilder.class); + private ObjectMapper mapper = new ObjectMapper(); @@ -71,8 +76,7 @@ public class BpmnRequestBuilderTest { @Before public void setup() { - reqBuilder.setAaiResourcesClient(aaiResourcesClient); - + // aaiData.setAaiResourcesClient(aaiResourcesClient); } @Test @@ -80,11 +84,11 @@ public class BpmnRequestBuilderTest { ServiceInstance service = provider.getMapper().readValue(new File(RESOURCE_PATH + "ServiceInstance.json"), ServiceInstance.class); - doReturn(service).when(reqBuilder).getServiceInstance("serviceId"); + doReturn(service).when(aaiData).getServiceInstance("serviceId"); ServiceInstancesRequest expectedRequest = mapper .readValue(new File(RESOURCE_PATH + "ExpectedServiceRequest.json"), ServiceInstancesRequest.class); - expectedRequest.getRequestDetails().getModelInfo().setModelId(null); - // bad getter/setter setting multiple fields + expectedRequest.getRequestDetails().getModelInfo().setModelId(null); // bad getter/setter setting multiple + // fields ServiceInstancesRequest actualRequest = reqBuilder.buildServiceDeleteRequest("serviceId"); assertThat(actualRequest, sameBeanAs(expectedRequest)); } @@ -128,13 +132,16 @@ public class BpmnRequestBuilderTest { AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId")); VolumeGroup volumeGroup = provider.getMapper().readValue(new File(RESOURCE_PATH + "VolumeGroup.json"), VolumeGroup.class); - - doReturn(Optional.of(volumeGroup)).when(aaiResourcesClient).get(VolumeGroup.class, AAIUriFactory - .createResourceUri(AAIObjectType.VOLUME_GROUP, "cloudOwner", "regionOne", "volumeGroupId")); + AAIResultWrapper wrapper = new AAIResultWrapper(volumeGroup); + doReturn(wrapper).when(aaiResourcesClient) + .get(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId") + .relatedTo(AAIObjectType.VOLUME_GROUP, "volumeGroupId")); ServiceInstancesRequest expectedRequest = mapper .readValue(new File(RESOURCE_PATH + "ExpectedVolumeGroupRequest.json"), ServiceInstancesRequest.class); ServiceInstancesRequest actualRequest = reqBuilder.buildVolumeGroupDeleteRequest("vnfId", "volumeGroupId"); assertThat(actualRequest, sameBeanAs(expectedRequest)); } + } + diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceNoOE.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceNoOE.json new file mode 100644 index 0000000000..a6aa3e1c25 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceNoOE.json @@ -0,0 +1,33 @@ +{ + "serviceInstanceId":"1882939", + "vnfInstanceId":"1882938", + "networkInstanceId":"1882937", + "volumeGroupInstanceId":"1882935", + "vfModuleInstanceId":"1882934", + "requestDetails": { + "requestInfo": { + "source": "VID", + "requestorId": "xxxxxx", + "instanceName": "testService9" + }, + "requestParameters": { + "aLaCarte": true, + "autoBuildVfModules": false, + "subscriptionServiceType": "test", + "disableOwningEntityProject": true + }, + "modelInfo":{ + "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7965", + "modelVersion":"1", + "modelVersionId":"10", + "modelType":"service", + "modelName":"serviceModel", + "modelInstanceName":"modelInstanceName", + "modelCustomizationId":"f7ce78bb-423b-11e7-93f8-0050569a796" + }, + "subscriberInfo": { + "globalSubscriberId": "someTestId", + "subscriberName": "someTestId" + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json index 09f6d81da3..0b03f56caa 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json @@ -101,7 +101,7 @@ }, { "relationship-key": "volume-group.volume-group-id", - "relationship-value": "18b220c8-af84-4b82-a8c0-41bbea6328a6" + "relationship-value": "volumeGroupId" } ] }, 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 2e1c6a9bdc..27e1ae90d2 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 @@ -9,14 +9,20 @@ server: mso: health: endpoints: - catalogdb: http://localhost:${wiremock.server.port} - requestdb: http://localhost:${wiremock.server.port} - sdnc: http://localhost:${wiremock.server.port} - openstack: http://localhost:${wiremock.server.port} - bpmn: http://localhost:${wiremock.server.port} - asdc: http://localhost:${wiremock.server.port} - requestdbattsvc: http://localhost:${wiremock.server.port} - + - subsystem: apih + uri: http://localhost:${wiremock.server.port} + - subsystem: asdc + uri: http://localhost:${wiremock.server.port} + - subsystem: bpmn + uri: http://localhost:${wiremock.server.port} + - subsystem: catalogdb + uri: http://localhost:${wiremock.server.port} + - subsystem: openstack + uri: http://localhost:${wiremock.server.port} + - subsystem: requestdb + uri: http://localhost:${wiremock.server.port} + - subsystem: sdnc + uri: http://localhost:${wiremock.server.port} infra-requests: archived: period: 180 @@ -118,7 +124,13 @@ mariaDB4j: port: 3307 databaseName: catalogdb databaseName2: requestdb - +#Actuator +management: + endpoints: + web: + base-path: /manage + exposure: + include: "*" org: onap: 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 731d2bec4d..ee53e491a4 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 @@ -1111,6 +1111,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, + `NF_DATA_VALID` tinyint(1) DEFAULT '0', `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), 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 13ca33c2cf..9cf71538b1 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 @@ -117,14 +117,11 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep final long startTime = System.currentTimeMillis(); logger.debug("Execute query on infra active request table"); - List<InfraActiveRequests> results = new ArrayList<InfraActiveRequests>(); - final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); crit.where(cb.and(predicates.toArray(new Predicate[0]))); crit.orderBy(order); - results = entityManager.createQuery(crit).getResultList(); - return results; + return entityManager.createQuery(crit).getResultList(); } /* 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 36c9251d59..aec1c7fb22 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 @@ -23,9 +23,7 @@ package org.onap.so.db.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 javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; @@ -34,7 +32,6 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PrePersist; @@ -124,6 +121,9 @@ public class VnfResourceCustomization implements Serializable { @Column(name = "VNFCINSTANCEGROUP_ORDER") private String vnfcInstanceGroupOrder; + @Column(name = "NF_DATA_VALID") + private Boolean nfDataValid; + @Override public boolean equals(final Object other) { if (!(other instanceof VnfResourceCustomization)) { @@ -336,4 +336,14 @@ public class VnfResourceCustomization implements Serializable { public void setVnfcInstanceGroupOrder(String vnfcInstanceGroupOrder) { this.vnfcInstanceGroupOrder = vnfcInstanceGroupOrder; } + + public Boolean getNfDataValid() { + return nfDataValid; + } + + public void setNfDataValid(Boolean nfDataValid) { + this.nfDataValid = nfDataValid; + } + + } 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 a959f2f5a1..23539b074d 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 @@ -27,7 +27,9 @@ import java.util.List; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.persistence.EntityNotFoundException; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; +import org.apache.http.HttpStatus; import org.onap.so.db.catalog.beans.BuildingBlockDetail; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.CloudifyManager; @@ -67,13 +69,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; import org.springframework.http.client.BufferingClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; +import com.google.common.base.Strings; import uk.co.blackpepper.bowman.Client; import uk.co.blackpepper.bowman.ClientFactory; import uk.co.blackpepper.bowman.Configuration; @@ -888,6 +895,90 @@ public class CatalogDbClient { "Unable to find CvnfcConfigurationCustomization ModelCustomizationUUID:" + cvnfcCustomizationUuid); } + public org.onap.so.rest.catalog.beans.Service getServiceModelInformation(String serviceModelUUID, String depth) { + if (Strings.isNullOrEmpty(serviceModelUUID)) { + throw new EntityNotFoundException("Service Model UUID passed as Null or Empty String"); + } + try { + HttpEntity<?> entity = getHttpEntity(); + return restTemplate.exchange( + UriComponentsBuilder.fromUriString(endpoint + "/ecomp/mso/catalog/v1/services/" + serviceModelUUID) + .queryParam("depth", depth).build().encode().toString(), + HttpMethod.GET, entity, org.onap.so.rest.catalog.beans.Service.class).getBody(); + } catch (HttpClientErrorException e) { + logger.warn("Entity Not found in DLP", e); + if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) { + throw new EntityNotFoundException("Unable to find Service with ServiceModelUUID:" + serviceModelUUID); + } + throw e; + } + } + + public List<org.onap.so.rest.catalog.beans.Service> getServices() { + try { + HttpEntity<?> entity = getHttpEntity(); + return restTemplate + .exchange( + UriComponentsBuilder.fromUriString(endpoint + "/ecomp/mso/catalog/v1/services").build() + .encode().toString(), + HttpMethod.GET, entity, + new ParameterizedTypeReference<List<org.onap.so.rest.catalog.beans.Service>>() {}) + .getBody(); + } catch (HttpClientErrorException e) { + logger.error("Error Calling catalog database", e); + throw e; + } + } + + public org.onap.so.rest.catalog.beans.Vnf getVnfModelInformation(String serviceModelUUID, + String vnfCustomizationUUID, String depth) { + if (Strings.isNullOrEmpty(serviceModelUUID)) { + throw new EntityNotFoundException("Service Model UUID passed as Null or Empty String"); + } + if (Strings.isNullOrEmpty(vnfCustomizationUUID)) { + throw new EntityNotFoundException("Vnf Customization UUID passed as Null or Empty String"); + } + try { + HttpEntity<?> entity = getHttpEntity(); + return restTemplate + .exchange( + UriComponentsBuilder + .fromUriString(endpoint + "/ecomp/mso/catalog/v1/services/" + serviceModelUUID + + "/vnfs/" + vnfCustomizationUUID) + .queryParam("depth", depth).build().encode().toString(), + HttpMethod.GET, entity, org.onap.so.rest.catalog.beans.Vnf.class) + .getBody(); + } catch (HttpClientErrorException e) { + if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) { + throw new EntityNotFoundException( + "Unable to find Vnf with Vnf Customization UUID:" + vnfCustomizationUUID); + } + throw e; + } + } + + public void updateVnf(String serviceModelUUID, org.onap.so.rest.catalog.beans.Vnf vnf) { + if (vnf == null) { + throw new EntityNotFoundException("Vnf passed as null"); + } + try { + HttpHeaders headers = getHttpHeaders(); + HttpEntity<org.onap.so.rest.catalog.beans.Vnf> entity = new HttpEntity<>(vnf, headers); + + restTemplate.exchange( + UriComponentsBuilder.fromUriString(endpoint + "/ecomp/mso/catalog/v1/services/" + serviceModelUUID + + "/vnfs/" + vnf.getModelCustomizationId()).build().encode().toString(), + HttpMethod.PUT, entity, org.onap.so.rest.catalog.beans.Vnf.class).getBody(); + } catch (HttpClientErrorException e) { + if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) { + throw new EntityNotFoundException( + "Unable to find Vnf with Vnf Customization UUID:" + vnf.getModelCustomizationId()); + } + throw e; + } + } + + public Workflow findWorkflowByArtifactUUID(String artifactUUID) { return this.getSingleResource(workflowClient, getUri(UriBuilder.fromUri(findWorkflowByArtifactUUID) .queryParam(ARTIFACT_UUID, artifactUUID).build().toString())); @@ -910,4 +1001,18 @@ public class CatalogDbClient { public void setEndpoint(String endpoint) { this.endpoint = endpoint; } + + private HttpHeaders getHttpHeaders() { + HttpHeaders headers = new HttpHeaders(); + headers.set(HttpHeaders.AUTHORIZATION, msoAdaptersAuth); + headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + headers.set(LogConstants.TARGET_ENTITY_HEADER, TARGET_ENTITY); + return headers; + } + + private HttpEntity<?> getHttpEntity() { + HttpHeaders headers = getHttpHeaders(); + return new HttpEntity<>(headers); + } } diff --git a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Cvnfc.java b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Cvnfc.java new file mode 100644 index 0000000000..e22f366ddf --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Cvnfc.java @@ -0,0 +1,136 @@ +/*- + * ============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 com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import org.apache.commons.lang3.builder.ToStringBuilder; + +@JsonInclude(Include.NON_DEFAULT) +public class Cvnfc { + + private String modelCustomizationId; + private String modelInstanceName; + private String modelVersionId; + private String modelInvariantId; + private String modelVersion; + private String modelName; + private String description; + private String nfcFunction; + private String nfcNamingCode; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") + private Date created; + + public String getModelCustomizationId() { + return modelCustomizationId; + } + + public void setModelCustomizationId(String modelCustomizationId) { + this.modelCustomizationId = modelCustomizationId; + } + + public String getModelInstanceName() { + return modelInstanceName; + } + + public void setModelInstanceName(String modelInstanceName) { + this.modelInstanceName = modelInstanceName; + } + + 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 getModelVersion() { + return modelVersion; + } + + public void setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + } + + 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 getNfcFunction() { + return nfcFunction; + } + + public void setNfcFunction(String nfcFunction) { + this.nfcFunction = nfcFunction; + } + + public String getNfcNamingCode() { + return nfcNamingCode; + } + + public void setNfcNamingCode(String nfcNamingCode) { + this.nfcNamingCode = nfcNamingCode; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + + + @Override + public String toString() { + return new ToStringBuilder(this).append("modelCustomizationId", modelCustomizationId) + .append("modelInstanceName", modelInstanceName).append("modelVersionId", modelVersionId) + .append("modelInvariantId", modelInvariantId).append("modelVersion", modelVersion) + .append("modelName", modelName).append("description", description).append("nfcFunction", nfcFunction) + .append("nfcNamingCode", nfcNamingCode).append("created", created).toString(); + } + +} 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 index 1620058e1e..11089046fd 100644 --- 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 @@ -24,6 +24,7 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; +import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @@ -40,6 +41,7 @@ public class Service implements Serializable { private String modelInvariantId; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") private Date created; private String modelVersion; 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 index 8e18f94faf..f2a2c77aca 100644 --- 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 @@ -20,9 +20,11 @@ package org.onap.so.rest.catalog.beans; +import java.util.ArrayList; import java.util.Date; import java.util.List; import org.onap.so.db.catalog.beans.HeatEnvironment; +import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @@ -37,6 +39,7 @@ public class VfModule { private String description; private Boolean isBase; private HeatTemplate heatTemplate; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") private Date created; private List<HeatFile> heatFile; @@ -50,9 +53,7 @@ public class VfModule { private HeatEnvironment heatEnv; private Boolean isVolumeGroup; - - // Add in cvnfcCustomization - + private List<Cvnfc> vnfc = new ArrayList<>(); public String getModelName() { @@ -191,6 +192,12 @@ public class VfModule { this.isVolumeGroup = isVolumeGroup; } + public List<Cvnfc> getVnfc() { + return vnfc; + } + public void setVnfc(List<Cvnfc> vnfc) { + this.vnfc = vnfc; + } } 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 index 40d701c3c5..febf69baf1 100644 --- 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 @@ -47,12 +47,14 @@ public class Vnf implements Serializable { private String nfFunction; private String nfRole; private String nfNamingCode; + private String nfType; private String multiStageDesign; private String orchestrationMode; private String cloudVersionMin; private String cloudVersionMax; private String category; private String subCategory; + private Boolean nfDataValid; private List<VfModule> vfModule = new ArrayList<>(); public List<VfModule> getVfModule() { @@ -215,4 +217,21 @@ public class Vnf implements Serializable { public void setMultiStageDesign(String multiStepDesign) { this.multiStageDesign = multiStepDesign; } + + public String getNfType() { + return nfType; + } + + public void setNfType(String nfType) { + this.nfType = nfType; + } + + public Boolean getNfDataValid() { + return nfDataValid; + } + + public void setNfDataValid(Boolean nfDataValid) { + this.nfDataValid = nfDataValid; + } + } diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java index 612963d35b..8bf47e71d3 100644 --- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java +++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java @@ -37,6 +37,7 @@ public class VnfcCustomizationRepositoryTest extends BaseTest { private VnfcCustomizationRepository vnfcCustomizationRepository; @Test + @Transactional public void findAllTest() throws Exception { List<VnfcCustomization> vnfcCustomizationList = vnfcCustomizationRepository.findAll(); Assert.assertFalse(CollectionUtils.isEmpty(vnfcCustomizationList)); diff --git a/mso-catalog-db/src/test/resources/schema.sql b/mso-catalog-db/src/test/resources/schema.sql index 7cd13a3780..7468f62ecb 100644 --- a/mso-catalog-db/src/test/resources/schema.sql +++ b/mso-catalog-db/src/test/resources/schema.sql @@ -1109,6 +1109,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, + `NF_DATA_VALID` tinyint(1) DEFAULT '0', `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), diff --git a/version.properties b/version.properties index 99af34261b..f78f30b18d 100644 --- a/version.properties +++ b/version.properties @@ -4,7 +4,7 @@ major=1 minor=5 -patch=0 +patch=1 base_version=${major}.${minor}.${patch} |