diff options
author | 2018-07-10 14:20:54 +0300 | |
---|---|---|
committer | 2018-07-10 14:20:54 +0300 | |
commit | c72d565bb58226b20625b2bce5f0019046bee649 (patch) | |
tree | 8658e49595705b02e47ddc14afa20d6bb7123547 /vid-app-common/src/main/java/org/onap/vid/services | |
parent | ef8a6b47847012fd59ea20da21d8d3d7c4a301ed (diff) |
Merge 1806 code of vid-common
Change-Id: I75d52abed4a24dfe3827d79edc4a2938726aa87a
Issue-ID: VID-208
Signed-off-by: Sonsino, Ofir (os0695) <os0695@intl.att.com>
Diffstat (limited to 'vid-app-common/src/main/java/org/onap/vid/services')
18 files changed, 994 insertions, 187 deletions
diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AaiService.java b/vid-app-common/src/main/java/org/onap/vid/services/AaiService.java index 4e86281c..f3e0bfda 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/AaiService.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/AaiService.java @@ -1,23 +1,19 @@ package org.onap.vid.services; -import org.codehaus.jackson.JsonParseException; -import org.codehaus.jackson.map.JsonMappingException; import org.onap.vid.aai.AaiResponse; +import org.onap.vid.aai.AaiResponseTranslator; import org.onap.vid.aai.SubscriberFilteredResults; -import org.onap.vid.aai.model.AaiGetPnfs.Pnf; -import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList; +import org.onap.vid.aai.model.AaiGetInstanceGroupsByCloudRegion; import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList; +import org.onap.vid.aai.model.AaiGetPnfs.Pnf; import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; +import org.onap.vid.aai.model.PortDetailsTranslator; import org.onap.vid.asdc.beans.Service; -import org.onap.vid.model.ServiceInstanceSearchResult; import org.onap.vid.model.SubscriberList; import org.onap.vid.roles.RoleValidator; import javax.ws.rs.core.Response; - -import java.io.IOException; import java.util.Collection; -import java.util.ArrayList; import java.util.List; /** @@ -38,6 +34,10 @@ public interface AaiService { AaiResponse getAaiZones(); + AaiResponse getNetworkCollectionDetails(String serviceInstanceId); + + AaiResponse<AaiGetInstanceGroupsByCloudRegion> getInstanceGroupsByCloudRegion(String cloudOwner, String cloudRegionId, String networkFunction); + AaiResponse<OperationalEnvironmentList> getOperationalEnvironments(String operationalEnvironmentType, String operationalEnvironmentStatus); AaiResponse getAicZoneForPnf(String globalCustomerId , String serviceType , String serviceId); @@ -60,4 +60,9 @@ public interface AaiService { AaiResponse getPNFData(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion, String equipVendor, String equipModel); + AaiResponseTranslator.PortMirroringConfigData getPortMirroringConfigData(String configurationId); + + List<PortDetailsTranslator.PortDetails> getPortMirroringSourcePorts(String configurationId); + + AaiResponse getInstanceGroupsByVnfInstanceId(String vnfInstanceId); } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java index 92ce0c26..4de2cc74 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java @@ -1,12 +1,14 @@ package org.onap.vid.services; import org.apache.http.HttpStatus; -import org.onap.vid.aai.model.AaiGetAicZone.AicZones; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.codehaus.jackson.JsonNode; import org.onap.vid.aai.*; import org.onap.vid.aai.ServiceInstance; import org.onap.vid.aai.ServiceSubscription; import org.onap.vid.aai.Services; +import org.onap.vid.aai.model.AaiGetAicZone.AicZones; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.AaiGetNetworkCollectionDetails; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.AaiGetRelatedInstanceGroupsByVnfId; import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList; import org.onap.vid.aai.model.AaiGetPnfs.Pnf; import org.onap.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone; @@ -17,6 +19,7 @@ import org.onap.vid.model.ServiceInstanceSearchResult; import org.onap.vid.model.SubscriberList; import org.onap.vid.roles.RoleValidator; import org.onap.vid.utils.Intersection; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import javax.ws.rs.core.Response; @@ -24,6 +27,7 @@ import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -31,55 +35,53 @@ import java.util.stream.Collectors; * Created by Oren on 7/4/17. */ public class AaiServiceImpl implements AaiService { - private String serviceInstanceId = "service-instance.service-instance-id"; - private String serviceType = "service-subscription.service-type"; - private String customerId = "customer.global-customer-id"; - private String serviceInstanceName = "service-instance.service-instance-name"; + private static final String SERVICE_INSTANCE_ID = "service-instance.service-instance-id"; + private static final String SERVICE_TYPE = "service-subscription.service-type"; + private static final String CUSTOMER_ID = "customer.global-customer-id"; + private static final String SERVICE_INSTANCE_NAME = "service-instance.service-instance-name"; private int indexOfSubscriberName = 6; @Autowired private AaiClientInterface aaiClient; - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiServiceImpl.class); + @Autowired + private AaiResponseTranslator aaiResponseTranslator; + + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(AaiServiceImpl.class); private List<Service> convertModelToService(Model model) { List<Service> services = new ArrayList<>(); String category = ""; if(validateModel(model)){ - if(model.getModelType() != null) + if(model.getModelType() != null) { category = model.getModelType(); + } for (ModelVer modelVer: model.getModelVers().getModelVer()) { - Service service = new Service(); - if (modelVer.getModelVersionId() != null) - service.setUuid(modelVer.getModelVersionId()); - if(model.getModelInvariantId() != null) - service.setInvariantUUID(model.getModelInvariantId()); - if(modelVer.getModelVersion() != null) - service.setVersion(modelVer.getModelVersion()); - if(modelVer.getModelName() != null) - service.setName(modelVer.getModelName()); - if(modelVer.getDistributionStatus() != null) - service.setDistributionStatus(Service.DistributionStatus.valueOf(modelVer.getDistributionStatus())); - service.setCategory(category); + Service service = new Service( + modelVer.getModelVersionId(), + model.getModelInvariantId(), + category, modelVer.getModelVersion(), modelVer.getModelName(), + modelVer.getDistributionStatus(), + null, null, null, null + ); services.add(service); } } else { - return null; + return Collections.emptyList(); } return services; } private boolean validateModel(Model model){ - if(model != null){ - if(model.getModelVers() != null && model.getModelVers().getModelVer() != null && model.getModelVers().getModelVer().get(0).getModelVersionId() != null){ - return true; - } + if (model == null) { + return false; + } else { + return model.getModelVers() != null && model.getModelVers().getModelVer() != null && model.getModelVers().getModelVer().get(0).getModelVersionId() != null; } - return false; } private List<ServiceInstanceSearchResult> getServicesByOwningEntityId(List<String> owningEntities, RoleValidator roleValidator) { @@ -100,8 +102,9 @@ public class AaiServiceImpl implements AaiService { List<ServiceInstanceSearchResult> serviceInstanceSearchResultList = new ArrayList<>(); if (projectByIdResponse.getT() != null) { for (Project project : projectByIdResponse.getT().getProject()) { - if (project.getRelationshipList() != null) + if (project.getRelationshipList() != null) { serviceInstanceSearchResultList = convertRelationshipToSearchResult(project, serviceInstanceSearchResultList, roleValidator); + } } } return serviceInstanceSearchResultList; @@ -126,11 +129,11 @@ public class AaiServiceImpl implements AaiService { setSubscriberName(relationship, serviceInstanceSearchResult); for (RelationshipData relationshipData : relationshipDataList) { String key = relationshipData.getRelationshipKey(); - if (key.equals(serviceInstanceId)) { + if (key.equals(SERVICE_INSTANCE_ID)) { serviceInstanceSearchResult.setServiceInstanceId(relationshipData.getRelationshipValue()); - } else if (key.equals(serviceType)) { + } else if (key.equals(SERVICE_TYPE)) { serviceInstanceSearchResult.setServiceType(relationshipData.getRelationshipValue()); - } else if (key.equals(customerId)) { + } else if (key.equals(CUSTOMER_ID)) { serviceInstanceSearchResult.setGlobalCustomerId(relationshipData.getRelationshipValue()); } } @@ -150,7 +153,7 @@ public class AaiServiceImpl implements AaiService { List<RelatedToProperty> relatedToPropertyList = relationship.getRelatedToPropertyList(); if (relatedToPropertyList != null) { for (RelatedToProperty relatedToProperty : relatedToPropertyList) { - if (relatedToProperty.getPropertyKey().equals(serviceInstanceName)) { + if (relatedToProperty.getPropertyKey().equals(SERVICE_INSTANCE_NAME)) { serviceInstanceSearchResult.setServiceInstanceName(relatedToProperty.getPropertyValue()); } } @@ -160,24 +163,20 @@ public class AaiServiceImpl implements AaiService { @Override public SubscriberFilteredResults getFullSubscriberList(RoleValidator roleValidator) { AaiResponse<SubscriberList> subscriberResponse = aaiClient.getAllSubscribers(); - SubscriberFilteredResults subscriberFilteredResults = - new SubscriberFilteredResults(roleValidator, subscriberResponse.getT(), - subscriberResponse.getErrorMessage(), - subscriberResponse.getHttpCode()); - return subscriberFilteredResults; + return new SubscriberFilteredResults(roleValidator, subscriberResponse.getT(), + subscriberResponse.getErrorMessage(), + subscriberResponse.getHttpCode()); } @Override public AaiResponse<OperationalEnvironmentList> getOperationalEnvironments(String operationalEnvironmentType, String operationalEnvironmentStatus) { - AaiResponse<OperationalEnvironmentList> subscriberResponse = aaiClient.getOperationalEnvironments(operationalEnvironmentType, operationalEnvironmentStatus); - return subscriberResponse; + return aaiClient.getOperationalEnvironments(operationalEnvironmentType, operationalEnvironmentStatus); } @Override public AaiResponse<SubscriberList> getFullSubscriberList() { - AaiResponse<SubscriberList> subscriberResponse = aaiClient.getAllSubscribers(); - return subscriberResponse; + return aaiClient.getAllSubscribers(); } @Override @@ -206,7 +205,7 @@ public class AaiServiceImpl implements AaiService { if (projects != null) { resultList.add(getServicesByProjectNames(projects, roleValidator)); } - if (resultList.size() > 0) { + if (!resultList.isEmpty()) { Intersection<ServiceInstanceSearchResult> intersection = new Intersection<>(); serviceInstancesSearchResults.serviceInstances = intersection.intersectMultipileArray(resultList); } @@ -270,7 +269,7 @@ public class AaiServiceImpl implements AaiService { try { return aaiClient.getVersionByInvariantId(modelInvariantId); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to getVersionByInvariantId from A&AI", e); } return null; } @@ -290,10 +289,11 @@ public class AaiServiceImpl implements AaiService { @Override public AaiResponse getServices(RoleValidator roleValidator) { AaiResponse<GetServicesAAIRespone> subscriberResponse = aaiClient.getServices(); - if (subscriberResponse.getT() != null) + if (subscriberResponse.getT() != null) { for (org.onap.vid.aai.model.AaiGetServicesRequestModel.Service service : subscriberResponse.getT().service) { service.isPermitted = true; } + } return subscriberResponse; } @@ -323,8 +323,7 @@ public class AaiServiceImpl implements AaiService { @Override public AaiResponse getAaiZones() { - AaiResponse<AicZones> response = aaiClient.getAllAicZones(); - return response; + return (AaiResponse<AicZones>) aaiClient.getAllAicZones(); } @Override @@ -334,17 +333,17 @@ public class AaiServiceImpl implements AaiService { AaiResponse<ServiceRelationships> serviceInstanceResp = aaiClient.getServiceInstance(globalCustomerId, serviceType, serviceId); if (serviceInstanceResp.getT() != null) { List<String> aicZoneList = getRelationshipDataByType(serviceInstanceResp.getT().getRelationshipList(), "zone", "zone.zone-id"); - if (aicZoneList.size() > 0) { + if (!aicZoneList.isEmpty()) { aicZone = aicZoneList.get(0); } else { - logger.warn("aic zone not found for service instance " + serviceId); + LOGGER.warn("aic zone not found for service instance " + serviceId); } } else { if (serviceInstanceResp.getErrorMessage() != null) { - logger.error("get service instance " + serviceId + " return error", serviceInstanceResp.getErrorMessage()); + LOGGER.error("get service instance {} return error {}", serviceId, serviceInstanceResp.getErrorMessage()); return new AaiResponse(aicZone , serviceInstanceResp.getErrorMessage() ,serviceInstanceResp.getHttpCode()); } else { - logger.warn("get service instance " + serviceId + " return empty body"); + LOGGER.warn("get service instance {} return empty body", serviceId); return new AaiResponse(aicZone , "get service instance " + serviceId + " return empty body" ,serviceInstanceResp.getHttpCode()); } } @@ -358,6 +357,18 @@ public class AaiServiceImpl implements AaiService { } @Override + public AaiResponse getNetworkCollectionDetails(String serviceInstanceId){ + AaiResponse<AaiGetNetworkCollectionDetails> getNetworkCollectionDetailsAaiResponse = aaiClient.getNetworkCollectionDetails(serviceInstanceId); + return getNetworkCollectionDetailsAaiResponse; + } + + @Override + public AaiResponse<AaiGetInstanceGroupsByCloudRegion> getInstanceGroupsByCloudRegion(String cloudOwner, String cloudRegionId, String networkFunction){ + AaiResponse<AaiGetInstanceGroupsByCloudRegion> getInstanceGroupsByCloudRegionResponse = aaiClient.getInstanceGroupsByCloudRegion(cloudOwner, cloudRegionId, networkFunction); + return getInstanceGroupsByCloudRegionResponse; + } + + @Override public Collection<Service> getServicesByDistributionStatus() { AaiResponse<GetServiceModelsByDistributionStatusResponse> serviceModelsByDistributionStatusResponse = aaiClient.getServiceModelsByDistributionStatus(); Collection<Service> services = new ArrayList<>(); @@ -366,9 +377,7 @@ public class AaiServiceImpl implements AaiService { for (Result result : results) { if(result.getModel() != null) { List<Service> service = convertModelToService(result.getModel()); - if (service != null) { - services.addAll(service); - } + services.addAll(service); } } } @@ -381,42 +390,97 @@ public class AaiServiceImpl implements AaiService { AaiResponse<ServiceRelationships> serviceInstanceResp = aaiClient.getServiceInstance(globalCustomerId, serviceType, serviceInstanceId); if (serviceInstanceResp.getT() != null) { - List<String> logicalLinks = getRelationshipDataByType(serviceInstanceResp.getT().getRelationshipList(), "logical-link", "logical-link.link-name"); - for (String logicalLink : logicalLinks) { - String link = ""; - try { - link = URLEncoder.encode(logicalLink, "UTF-8"); - AaiResponse<LogicalLinkResponse> logicalLinkResp = aaiClient.getLogicalLink(link); - if (logicalLinkResp.getT() != null) { - //lag-interface is the key for pnf - approved by Bracha - List<String> linkPnfs = getRelationshipDataByType(logicalLinkResp.getT().getRelationshipList(), "lag-interface", "pnf.pnf-name"); - if (linkPnfs.size() > 0) { - pnfs.addAll(linkPnfs); - } else { - logger.warn("no pnf found for logical link " + logicalLink); - } - } else { - if (logicalLinkResp.getErrorMessage() != null) { - logger.error("get logical link " + logicalLink + " return error", logicalLinkResp.getErrorMessage()); - } else { - logger.warn("get logical link " + logicalLink + " return empty body"); - } - } - } catch (UnsupportedEncodingException e) { - logger.error("Failed to encode logical link: " + logicalLink, e.getMessage()); - } + + addPnfsToListViaLogicalLinks(pnfs, serviceInstanceResp); + addPnfsToListViaDirectRelations(pnfs, serviceInstanceResp); + + if (pnfs.isEmpty()) { + LOGGER.warn("no pnf direct relation found for service id:" + serviceInstanceId+ + " name: "+serviceInstanceResp.getT().getServiceInstanceName()); } } else { if (serviceInstanceResp.getErrorMessage() != null) { - logger.error("get service instance " + serviceInstanceId + " return error", serviceInstanceResp.getErrorMessage()); + LOGGER.error("get service instance {} return error {}", serviceInstanceId, serviceInstanceResp.getErrorMessage()); } else { - logger.warn("get service instance " + serviceInstanceId + " return empty body"); + LOGGER.warn("get service instance {} return empty body", serviceInstanceId); } } return pnfs.stream().distinct().collect(Collectors.toList()); } + @Override + public AaiResponseTranslator.PortMirroringConfigData getPortMirroringConfigData(String configurationId) { + AaiResponse<JsonNode> aaiResponse = aaiClient.getCloudRegionAndSourceByPortMirroringConfigurationId(configurationId); + return aaiResponseTranslator.extractPortMirroringConfigData(aaiResponse); + } + + @Override + public AaiResponse getInstanceGroupsByVnfInstanceId(String vnfInstanceId){ + AaiResponse<AaiGetRelatedInstanceGroupsByVnfId> aaiResponse = aaiClient.getInstanceGroupsByVnfInstanceId(vnfInstanceId); + if(aaiResponse.getHttpCode() == HttpStatus.SC_OK){ + return new AaiResponse(convertGetInstanceGroupsResponseToSimpleResponse(aaiResponse.getT()), aaiResponse.getErrorMessage(), aaiResponse.getHttpCode()); + } + return aaiClient.getInstanceGroupsByVnfInstanceId(vnfInstanceId); + } + + private List<InstanceGroupInfo> convertGetInstanceGroupsResponseToSimpleResponse(AaiGetRelatedInstanceGroupsByVnfId response) { + List<InstanceGroupInfo> instanceGroupInfoList = new ArrayList<>(); + for(org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship relationship: response.getRelationshipList().getRelationship()){ + getInstanceGroupInfoFromRelationship(relationship, instanceGroupInfoList); + } + return instanceGroupInfoList; + } + + private void getInstanceGroupInfoFromRelationship(org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship relationship, List<InstanceGroupInfo> instanceGroupInfoList) { + if(relationship.getRelatedTo().equals("instance-group")){ + for(org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelatedToProperty relatedToProperty: relationship.getRelatedToPropertyList()){ + if(relatedToProperty.getPropertyKey().equals("instance-group.instance-group-name")){ + instanceGroupInfoList.add(new InstanceGroupInfo(relatedToProperty.getPropertyValue())); + } + } + } + } + + @Override + public List<PortDetailsTranslator.PortDetails> getPortMirroringSourcePorts(String configurationId){ + return aaiClient.getPortMirroringSourcePorts(configurationId); + } + + private void addPnfsToListViaDirectRelations(List<String> pnfs, AaiResponse<ServiceRelationships> serviceInstanceResp) { + pnfs.addAll(getRelationshipDataByType(serviceInstanceResp.getT().getRelationshipList(), "pnf", "pnf.pnf-name")); + } + + private void addPnfsToListViaLogicalLinks(List<String> pnfs, AaiResponse<ServiceRelationships> serviceInstanceResp) { + List<String> logicalLinks = getRelationshipDataByType(serviceInstanceResp.getT().getRelationshipList(), "logical-link", "logical-link.link-name"); + for (String logicalLink : logicalLinks) { + String link; + try { + link = URLEncoder.encode(logicalLink, "UTF-8"); + } catch (UnsupportedEncodingException e) { + LOGGER.error("Failed to encode logical link: " + logicalLink, e); + continue; + } + + AaiResponse<LogicalLinkResponse> logicalLinkResp = aaiClient.getLogicalLink(link); + if (logicalLinkResp.getT() != null) { + //lag-interface is the key for pnf - approved by Bracha + List<String> linkPnfs = getRelationshipDataByType(logicalLinkResp.getT().getRelationshipList(), "lag-interface", "pnf.pnf-name"); + if (!linkPnfs.isEmpty()) { + pnfs.addAll(linkPnfs); + } else { + LOGGER.warn("no pnf found for logical link " + logicalLink); + } + } else { + if (logicalLinkResp.getErrorMessage() != null) { + LOGGER.error("get logical link " + logicalLink + " return error", logicalLinkResp.getErrorMessage()); + } else { + LOGGER.warn("get logical link " + logicalLink + " return empty body"); + } + } + } + } + private List<String> getRelationshipDataByType(RelationshipList relationshipList, String relationshipType, String relationshipDataKey) { List<String> relationshipValues = new ArrayList<>(); for (Relationship relationship : relationshipList.getRelationship()) { diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogic.java b/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogic.java new file mode 100644 index 00000000..90eb0d2b --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogic.java @@ -0,0 +1,60 @@ +package org.onap.vid.services; + +import org.onap.vid.aai.model.ResourceType; +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.job.Job; +import org.onap.vid.model.JobAuditStatus; +import org.onap.vid.model.ServiceInfo; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; +import org.onap.vid.mso.rest.AsyncRequestStatus; + +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.function.Consumer; + +public interface AsyncInstantiationBusinessLogic { + + List<String> PARAMS_TO_IGNORE = Arrays.asList("vnf_name", "vf_module_name"); + + List<ServiceInfo> getAllServicesInfo(); + + List<UUID> pushBulkJob(ServiceInstantiation request, String userId); + + RequestDetailsWrapper<ServiceInstantiationRequestDetails> generateServiceInstantiationRequest(UUID uuid, ServiceInstantiation details, String userId); + + String getServiceInstantiationPath(ServiceInstantiation serviceInstantiationRequest); + + String getOrchestrationRequestsPath(); + + ServiceInfo getServiceInfoByJobId(UUID jobUUID); + + List<JobAuditStatus> getAuditStatuses(UUID jobUUID, JobAuditStatus.SourceStatus source); + + ServiceInfo updateServiceInfo(UUID jobUUID, Consumer<ServiceInfo> serviceUpdater); + + ServiceInfo updateServiceInfoAndAuditStatus(UUID jobUuid, Job.JobStatus jobStatus); + + void auditVidStatus(UUID jobUUID, Job.JobStatus jobStatus); + + void auditMsoStatus(UUID jobUUID, AsyncRequestStatus.Request msoRequestStatus); + + void auditMsoStatus(UUID jobUUID, String jobStatus, String requestId, String additionalInfo); + + Job.JobStatus calcStatus(AsyncRequestStatus asyncRequestStatus); + + void handleFailedInstantiation(UUID jobUUID); + + void deleteJob(UUID jobId); + + void hideServiceInfo(UUID jobUUID); + + int getCounterForName(String name); + + int getMaxRetriesGettingFreeNameFromAai(); + + void setMaxRetriesGettingFreeNameFromAai(int maxRetriesGettingFreeNameFromAai); + + String getUniqueName(String name, ResourceType resourceType); +} diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogicImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogicImpl.java new file mode 100644 index 00000000..7259301a --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogicImpl.java @@ -0,0 +1,486 @@ +package org.onap.vid.services; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.AaiResponse; +import org.onap.vid.aai.exceptions.InvalidAAIResponseException; +import org.onap.vid.aai.model.AaiNodeQueryResponse; +import org.onap.vid.aai.model.ResourceType; +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.domain.mso.CloudConfiguration; +import org.onap.vid.domain.mso.SubscriberInfo; +import org.onap.vid.exceptions.DbFailureUncheckedException; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.exceptions.MaxRetriesException; +import org.onap.vid.exceptions.OperationNotAllowedException; +import org.onap.vid.job.Job; +import org.onap.vid.job.Job.JobStatus; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobType; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.model.JobAuditStatus; +import org.onap.vid.model.NameCounter; +import org.onap.vid.model.ServiceInfo; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.model.serviceInstantiation.VfModule; +import org.onap.vid.model.serviceInstantiation.Vnf; +import org.onap.vid.mso.MsoBusinessLogicImpl; +import org.onap.vid.mso.MsoProperties; +import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.utils.DaoUtils; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.*; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +import static org.onap.vid.utils.Logging.debugRequestDetails; + +@Service +public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBusinessLogic { + + private static final int MAX_RETRIES_GETTING_COUNTER = 100; + private static final int MAX_RETRIES_GETTING_FREE_NAME_FROM_AAI = 10000; + public static final String NAME_FOR_CHECK_AAI_STATUS = "NAME_FOR_CHECK_AAI_STATUS"; + + private final DataAccessService dataAccessService; + + private final JobAdapter jobAdapter; + + private final JobsBrokerService jobService; + + private SessionFactory sessionFactory; + + private AaiClientInterface aaiClient; + + private int maxRetriesGettingFreeNameFromAai = MAX_RETRIES_GETTING_FREE_NAME_FROM_AAI; + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AsyncInstantiationBusinessLogicImpl.class); + private Map<String, JobStatus> msoStateToJobStatusMap = ImmutableMap.<String, JobStatus>builder() + .put("inprogress", JobStatus.IN_PROGRESS) + .put("failed", JobStatus.FAILED) + .put("pause", JobStatus.PAUSE) + .put("paused", JobStatus.PAUSE) + .put("complete", JobStatus.COMPLETED) + .put("pending", JobStatus.IN_PROGRESS) + .put("pendingmanualtask", JobStatus.PAUSE) + .put("unlocked", JobStatus.IN_PROGRESS) + .build(); + + + @Autowired + public AsyncInstantiationBusinessLogicImpl(DataAccessService dataAccessService, + JobAdapter jobAdapter, + JobsBrokerService jobService, + SessionFactory sessionFactory, + AaiClientInterface aaiClient) { + this.dataAccessService = dataAccessService; + this.jobAdapter = jobAdapter; + this.jobService = jobService; + this.sessionFactory = sessionFactory; + this.aaiClient = aaiClient; + } + + @Override + public List<ServiceInfo> getAllServicesInfo() { + return dataAccessService.getList(ServiceInfo.class, filterByCreationDateAndNotDeleted(), orderByCreatedDateAndStatus(), null); + } + + private String filterByCreationDateAndNotDeleted() { + LocalDateTime minus3Months = LocalDateTime.now().minusMonths(3); + Timestamp filterDate = Timestamp.valueOf(minus3Months); + return " where" + + " hidden = false" + + " and deleted_at is null" + // don't fetch deleted + " and created >= '" + filterDate + "' "; + } + + private String orderByCreatedDateAndStatus() { + return " createdBulkDate DESC ,\n" + + " (CASE jobStatus\n" + + " WHEN 'COMPLETED' THEN 0\n" + + " WHEN 'FAILED' THEN 0\n" + + " WHEN 'IN_PROGRESS' THEN 1\n" + + " WHEN 'PAUSE' THEN 2\n" + + " WHEN 'PENDING' THEN 3\n" + + " WHEN 'STOPPED' THEN 3 END),\n" + + " statusModifiedDate "; + } + + @Override + public List<UUID> pushBulkJob(ServiceInstantiation request, String userId) { + List<UUID> uuids = new ArrayList<>(); + Date createdBulkDate = Calendar.getInstance().getTime(); + int bulkSize = request.getBulkSize(); + UUID templateId = UUID.randomUUID(); + for (int i = 0; i < bulkSize; i++) { + Job job = jobAdapter.createJob(JobType.ServiceInstantiation, request, templateId, userId, i); + UUID jobId = jobService.add(job); + auditVidStatus(jobId,job.getStatus()); + uuids.add(jobId); + dataAccessService.saveDomainObject(createServiceInfo(userId, request, jobId, templateId, createdBulkDate), DaoUtils.getPropsMap()); + } + return uuids; + } + + private ServiceInfo createServiceInfo(String userId, ServiceInstantiation serviceInstantiation, UUID jobId, UUID templateId, Date createdBulkDate) { + return new ServiceInfo( + userId, Job.JobStatus.PENDING, serviceInstantiation.isPause(), jobId, templateId, + serviceInstantiation.getOwningEntityId(), + serviceInstantiation.getOwningEntityName(), + serviceInstantiation.getProjectName(), + serviceInstantiation.getAicZoneId(), + serviceInstantiation.getAicZoneName(), + serviceInstantiation.getTenantId(), + serviceInstantiation.getTenantName(), + serviceInstantiation.getLcpCloudRegionId(), + null, + serviceInstantiation.getSubscriptionServiceType(), + serviceInstantiation.getSubscriberName(), + null, + serviceInstantiation.getInstanceName(), + serviceInstantiation.getModelInfo().getModelInvariantId(), + serviceInstantiation.getModelInfo().getModelName(), + serviceInstantiation.getModelInfo().getModelVersion(), + createdBulkDate + ); + } + + + @Override + public RequestDetailsWrapper<ServiceInstantiationRequestDetails> generateServiceInstantiationRequest(UUID jobId, ServiceInstantiation payload, String userId) { + + ServiceInstantiationRequestDetails.ServiceInstantiationOwningEntity owningEntity = new ServiceInstantiationRequestDetails.ServiceInstantiationOwningEntity(payload.getOwningEntityId(), payload.getOwningEntityName()); + + SubscriberInfo subscriberInfo = new SubscriberInfo(); + subscriberInfo.setGlobalSubscriberId(payload.getGlobalSubscriberId()); + + String serviceInstanceName = null; + if(payload.isUserProvidedNaming()) { + serviceInstanceName = getUniqueName(payload.getInstanceName(), ResourceType.SERVICE_INSTANCE); + String finalServiceInstanceName = serviceInstanceName; + updateServiceInfo(jobId, x -> x.setServiceInstanceName(finalServiceInstanceName)); + } + ServiceInstantiationRequestDetails.RequestInfo requestInfo = new ServiceInstantiationRequestDetails.RequestInfo( + serviceInstanceName, + payload.getProductFamilyId(), + "VID", + payload.isRollbackOnFailure(), + userId); + + List<ServiceInstantiationRequestDetails.ServiceInstantiationService> serviceInstantiationService = new LinkedList<>(); + List<Map<String, String>> unFilteredInstanceParams = payload.getInstanceParams() != null ? payload.getInstanceParams() : new LinkedList<>(); + List<Map<String, String>> filteredInstanceParams = removeUnNeededParams(unFilteredInstanceParams); + ServiceInstantiationRequestDetails.ServiceInstantiationService serviceInstantiationService1 = new ServiceInstantiationRequestDetails.ServiceInstantiationService( + payload.getModelInfo(), + serviceInstanceName, + filteredInstanceParams, + createServiceInstantiationVnfList(payload) + ); + serviceInstantiationService.add(serviceInstantiationService1); + + ServiceInstantiationRequestDetails.RequestParameters requestParameters = new ServiceInstantiationRequestDetails.RequestParameters(payload.getSubscriptionServiceType(), false, serviceInstantiationService); + + ServiceInstantiationRequestDetails.Project project = payload.getProjectName() != null ? new ServiceInstantiationRequestDetails.Project(payload.getProjectName()) : null; + + ServiceInstantiationRequestDetails requestDetails = new ServiceInstantiationRequestDetails(payload.getModelInfo(), owningEntity, subscriberInfo, + project, requestInfo, requestParameters); + + RequestDetailsWrapper<ServiceInstantiationRequestDetails> requestDetailsWrapper = new RequestDetailsWrapper(requestDetails); + debugRequestDetails(requestDetailsWrapper, logger); + return requestDetailsWrapper; + } + + private List<Map<String, String>> removeUnNeededParams(List<Map<String, String>> instanceParams) { + List<String> keysToRemove = new ArrayList<>(); + if (instanceParams != null && !instanceParams.isEmpty()) { + for (String key : instanceParams.get(0).keySet()) { + for (String paramToIgnore : PARAMS_TO_IGNORE) + if ((key.equalsIgnoreCase(paramToIgnore))) { + keysToRemove.add(key); + } + } + for (String key : keysToRemove) { + instanceParams.get(0).remove(key); + } + //TODO will be removed on once we stop using List<Map<String, String>> + if (instanceParams.get(0).isEmpty()) { + return Collections.emptyList(); + } + } + return instanceParams; + } + + private ServiceInstantiationRequestDetails.ServiceInstantiationVnfList createServiceInstantiationVnfList(ServiceInstantiation payload) { + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + cloudConfiguration.setTenantId(payload.getTenantId()); + cloudConfiguration.setLcpCloudRegionId(payload.getLcpCloudRegionId()); + + Map<String, Vnf> vnfs = payload.getVnfs(); + List<ServiceInstantiationRequestDetails.ServiceInstantiationVnf> vnfList = new ArrayList<>(); + for (Vnf vnf : vnfs.values()) { + Map<String, Map<String, VfModule>> vfModules = vnf.getVfModules(); + List<VfModule> convertedUnFilteredVfModules = convertVfModuleMapToList(vfModules); + List<VfModule> filteredVfModules = filterInstanceParamsFromVfModuleAndUniqueNames(convertedUnFilteredVfModules, vnf.isUserProvidedNaming()); + ServiceInstantiationRequestDetails.ServiceInstantiationVnf serviceInstantiationVnf = new ServiceInstantiationRequestDetails.ServiceInstantiationVnf( + vnf.getModelInfo(), + cloudConfiguration, + vnf.getPlatformName(), + vnf.getLineOfBusiness(), + payload.getProductFamilyId(), + removeUnNeededParams(vnf.getInstanceParams()), + filteredVfModules, + vnf.isUserProvidedNaming() ? getUniqueName(vnf.getInstanceName(), ResourceType.GENERIC_VNF) : null + ); + vnfList.add(serviceInstantiationVnf); + } + + return new ServiceInstantiationRequestDetails.ServiceInstantiationVnfList(vnfList); + } + + private List<VfModule> convertVfModuleMapToList(Map<String, Map<String, VfModule>> vfModules) { + return vfModules.values().stream().flatMap(vfModule -> vfModule.values().stream()).collect(Collectors.toList()); + } + + private List<VfModule> filterInstanceParamsFromVfModuleAndUniqueNames(List<VfModule> unFilteredVfModules, boolean isUserProvidedNaming) { + return unFilteredVfModules.stream().map(vfModule -> + new VfModule( + vfModule.getModelInfo(), + getUniqueNameIfNeeded(isUserProvidedNaming, vfModule.getInstanceName(), ResourceType.VF_MODULE), + getUniqueNameIfNeeded(isUserProvidedNaming, vfModule.getVolumeGroupInstanceName(), ResourceType.VOLUME_GROUP), + removeUnNeededParams(vfModule.getInstanceParams()))) + .collect(Collectors.toList()); + } + + private String getUniqueNameIfNeeded(boolean isUserProvidedNaming, String name, ResourceType resourceType) { + return isUserProvidedNaming && !StringUtils.isEmpty(name) ? + getUniqueName(name, resourceType) : null; + } + + @Override + public String getServiceInstantiationPath(ServiceInstantiation serviceInstantiationRequest) { + //in case pause flag is true - use assign , else - use create. + return MsoBusinessLogicImpl.validateEndpointPath( + serviceInstantiationRequest.isPause() ? + "mso.restapi.serviceInstanceAssign" : "mso.restapi.serviceInstanceCreate" + ); + } + + @Override + public String getOrchestrationRequestsPath() { + return MsoBusinessLogicImpl.validateEndpointPath(MsoProperties.MSO_REST_API_GET_ORC_REQ); + } + + @Override + public ServiceInfo updateServiceInfo(UUID jobUUID, Consumer<ServiceInfo> serviceUpdater) { + ServiceInfo serviceInfo = getServiceInfoByJobId(jobUUID); + serviceUpdater.accept(serviceInfo); + dataAccessService.saveDomainObject(serviceInfo, DaoUtils.getPropsMap()); + return serviceInfo; + } + + @Override + public ServiceInfo updateServiceInfoAndAuditStatus(UUID jobUuid, JobStatus jobStatus) { + auditVidStatus(jobUuid,jobStatus); + return updateServiceInfo(jobUuid, x -> setServiceInfoStatus(x, jobStatus)); + } + + private void setServiceInfoStatus(ServiceInfo serviceInfo, JobStatus jobStatus) { + serviceInfo.setJobStatus(jobStatus); + serviceInfo.setStatusModifiedDate(new Date()); + } + + public ServiceInfo getServiceInfoByJobId(UUID jobUUID) { + List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, String.format(" where jobId = '%s' ", jobUUID), null, null); + if (serviceInfoList.size() != 1) { + throw new GenericUncheckedException("Failed to retrieve job with uuid " + jobUUID + " from ServiceInfo table. Instances found: " + serviceInfoList.size()); + } + return serviceInfoList.get(0); + } + + public List<JobAuditStatus> getAuditStatuses(UUID jobUUID, JobAuditStatus.SourceStatus source) { + return dataAccessService.getList( + JobAuditStatus.class, + String.format(" where SOURCE = '%s' and JOB_ID = '%s'",source, jobUUID), + " CREATED_DATE ", null); + } + + private JobAuditStatus getLatestAuditStatus(UUID jobUUID, JobAuditStatus.SourceStatus source){ + List<JobAuditStatus> list = getAuditStatuses(jobUUID,source); + return !list.isEmpty() ? list.get(list.size()-1) : null; + } + + @Override + public void auditVidStatus(UUID jobUUID, JobStatus jobStatus){ + JobAuditStatus vidStatus = new JobAuditStatus(jobUUID, jobStatus.toString(), JobAuditStatus.SourceStatus.VID); + auditStatus(vidStatus); + } + + @Override + public void auditMsoStatus(UUID jobUUID, AsyncRequestStatus.Request msoRequestStatus){ + auditMsoStatus(jobUUID, msoRequestStatus.requestStatus.getRequestState(), msoRequestStatus.requestId, msoRequestStatus.requestStatus.getStatusMessage()); + } + + @Override + public void auditMsoStatus(UUID jobUUID, String jobStatus, String requestId, String additionalInfo){ + JobAuditStatus msoStatus = new JobAuditStatus(jobUUID, jobStatus, JobAuditStatus.SourceStatus.MSO, + requestId != null ? UUID.fromString(requestId) : null, + additionalInfo); + auditStatus(msoStatus); + } + + private void auditStatus(JobAuditStatus jobAuditStatus){ + JobAuditStatus latestStatus = getLatestAuditStatus(jobAuditStatus.getJobId(),jobAuditStatus.getSource()); + if (latestStatus == null || !latestStatus.equals(jobAuditStatus)) + dataAccessService.saveDomainObject(jobAuditStatus, DaoUtils.getPropsMap()); + + } + + public Job.JobStatus calcStatus(AsyncRequestStatus asyncRequestStatus) { + String msoRequestState = asyncRequestStatus.request.requestStatus.getRequestState().toLowerCase().replaceAll("[^a-z]+", ""); + JobStatus jobStatus = msoStateToJobStatusMap.get(msoRequestState); + return (jobStatus != null ? jobStatus : JobStatus.IN_PROGRESS); + } + + @Override + public void handleFailedInstantiation(UUID jobUUID) { + ServiceInfo serviceInfo = updateServiceInfoAndAuditStatus(jobUUID, JobStatus.FAILED); + List<ServiceInfo> serviceInfoList = dataAccessService.getList( + ServiceInfo.class, + String.format(" where templateId = '%s' and jobStatus = '%s'", + serviceInfo.getTemplateId(), + JobStatus.PENDING), + null, null); + serviceInfoList.forEach(si -> updateServiceInfoAndAuditStatus(si.getJobId(), JobStatus.STOPPED)); + } + + @Override + public void deleteJob(UUID jobId) { + jobService.delete(jobId); + Date now = new Date(); + updateServiceInfo(jobId, x -> x.setDeletedAt(now)); + } + + @Override + public void hideServiceInfo(UUID jobUUID) { + ServiceInfo serviceInfo = getServiceInfoByJobId(jobUUID); + if (!serviceInfo.getJobStatus().isFinal()) { + String message = String.format( "jobId %s: Service status does not allow hide service, status = %s", + serviceInfo.getJobId(), + serviceInfo.getJobStatus()); + logger.error(EELFLoggerDelegate.errorLogger, message); + throw new OperationNotAllowedException(message); + } + serviceInfo.setHidden(true); + dataAccessService.saveDomainObject(serviceInfo, DaoUtils.getPropsMap()); + } + + @Override + public int + + + getCounterForName(String name) { + + String hqlSelectNC = "from NameCounter where name = :name"; + String hqlUpdateCounter = "update NameCounter set counter = :newCounter " + + "where name= :name " + + "and counter= :prevCounter"; + + Integer counter = null; + GenericUncheckedException lastException = null; + for (int i = 0; i< MAX_RETRIES_GETTING_COUNTER && counter==null; i++) { + try { + counter = calcCounter(name, hqlSelectNC, hqlUpdateCounter); + } + catch (GenericUncheckedException exception) { + lastException = exception; //do nothing, we will try again in the loop + } + } + + if (counter!=null) { + return counter; + } + + throw lastException!=null ? new DbFailureUncheckedException(lastException) : + new DbFailureUncheckedException("Failed to get counter for "+name+" due to unknown error"); + + } + + private Integer calcCounter(String name, String hqlSelectNC, String hqlUpdateCounter) { + Integer counter; + counter = DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> { + NameCounter nameCounter = (NameCounter) session.createQuery(hqlSelectNC) + .setText("name", name) + .uniqueResult(); + if (nameCounter != null) { + int updatedRows = session.createQuery(hqlUpdateCounter) + .setText("name", nameCounter.getName()) + .setInteger("prevCounter", nameCounter.getCounter()) + .setInteger("newCounter", nameCounter.getCounter() + 1) + .executeUpdate(); + if (updatedRows == 1) { + return nameCounter.getCounter() + 1; + } + } else { + Object nameAsId = session.save(new NameCounter(name)); + //if save success + if (nameAsId != null) { + return 1; + } + } + //in case of failure return null, in order to continue the loop + return null; + }); + return counter; + } + + @Override + public int getMaxRetriesGettingFreeNameFromAai() { + return maxRetriesGettingFreeNameFromAai; + } + + @Override + public void setMaxRetriesGettingFreeNameFromAai(int maxRetriesGettingFreeNameFromAai) { + this.maxRetriesGettingFreeNameFromAai = maxRetriesGettingFreeNameFromAai; + } + + @Override + public String getUniqueName(String name, ResourceType resourceType) { + //check that name aai response well before increasing counter from DB + //Prevents unnecessary increasing of the counter while AAI doesn't response + isNameFreeInAai(NAME_FOR_CHECK_AAI_STATUS, resourceType); + + for (int i=0; i<getMaxRetriesGettingFreeNameFromAai(); i++) { + int counter = getCounterForName(name); + String newName = formatNameAndCounter(name, counter); + if (isNameFreeInAai(newName, resourceType)) { + return newName; + } + } + + throw new MaxRetriesException("find unused name for "+name, getMaxRetriesGettingFreeNameFromAai()); + } + + //the method is protected so we can call it in the UT + protected String formatNameAndCounter(String name, int counter) { + return name + "_" + String.format("%03d", counter); + } + + private boolean isNameFreeInAai(String name, ResourceType resourceType) throws InvalidAAIResponseException { + AaiResponse<AaiNodeQueryResponse> aaiResponse = aaiClient.searchNodeTypeByName(name, resourceType); + if (aaiResponse.getHttpCode() > 399 || aaiResponse.getT() == null) { + throw new InvalidAAIResponseException(aaiResponse); + } + return CollectionUtils.isEmpty(aaiResponse.getT().resultData); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AuditService.java b/vid-app-common/src/main/java/org/onap/vid/services/AuditService.java new file mode 100644 index 00000000..19569a7f --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/services/AuditService.java @@ -0,0 +1,11 @@ +package org.onap.vid.services; + +import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.mso.RestObject; + +import java.util.UUID; + +public interface AuditService { + + void setFailedAuditStatusFromMso(UUID jobUuid, String requestId, int statusCode, String msoResponse); +} diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AuditServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/AuditServiceImpl.java new file mode 100644 index 00000000..13db1ae9 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/services/AuditServiceImpl.java @@ -0,0 +1,47 @@ +package org.onap.vid.services; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.StringUtils; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.springframework.stereotype.Service; + +import javax.inject.Inject; +import java.io.IOException; +import java.util.UUID; + + +@Service +public class AuditServiceImpl implements AuditService{ + + @Inject + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Override + public void setFailedAuditStatusFromMso(UUID jobUuid, String requestId, int statusCode, String msoResponse){ + final String failedMsoRequestStatus = "FAILED"; + String additionalInfo = formatExceptionAdditionalInfo(statusCode, msoResponse); + asyncInstantiationBL.auditMsoStatus(jobUuid, failedMsoRequestStatus, requestId, additionalInfo); + } + + private String formatExceptionAdditionalInfo(int statusCode, String msoResponse) { + String errorMsg = "Http Code:" + statusCode; + if (!StringUtils.isEmpty(msoResponse)) { + String filteredJson; + try { + ObjectMapper objectMapper = new ObjectMapper(); + filteredJson = StringUtils.defaultIfEmpty( + objectMapper.readTree(msoResponse).path("serviceException").toString().replaceAll("[\\{\\}]","") , + msoResponse + ); + } catch (JsonParseException e) { + filteredJson = msoResponse; + } catch (IOException e) { + throw new GenericUncheckedException(e); + } + + errorMsg = errorMsg + ", " + filteredJson; + } + return errorMsg; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationService.java b/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationService.java new file mode 100644 index 00000000..387edc12 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationService.java @@ -0,0 +1,15 @@ +package org.onap.vid.services; + +import org.onap.vid.model.JobBulk; +import org.onap.vid.model.JobModel; + +import java.util.Map; +import java.util.UUID; + +public interface BulkInstantiationService { + + JobBulk saveBulk(Map<String, Object> bulkRequest); + + JobModel getJob(UUID uuid); + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationServiceImpl.java new file mode 100644 index 00000000..2a868f13 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationServiceImpl.java @@ -0,0 +1,46 @@ +package org.onap.vid.services; + +import org.onap.vid.job.Job; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.model.JobBulk; +import org.onap.vid.model.JobModel; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.ws.rs.NotFoundException; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +@Service +public class BulkInstantiationServiceImpl implements BulkInstantiationService { + + private JobsBrokerService jobsBrokerService; + private JobAdapter jobAdapter; + + @Autowired + public BulkInstantiationServiceImpl(JobsBrokerService jobsBrokerService, JobAdapter jobAdapter) { + this.jobsBrokerService = jobsBrokerService; + this.jobAdapter = jobAdapter; + } + + @Override + public JobBulk saveBulk(Map<String, Object> bulkRequest) { + List<Job> jobList = jobAdapter.createBulkOfJobs(bulkRequest); + jobList.forEach(jobsBrokerService::add); + return jobAdapter.toModelBulk(jobList); + } + + @Override + public JobModel getJob(UUID uuid) { + Job job = jobsBrokerService.peek(uuid); + + if (job == null || job.getUuid() == null) { + throw new NotFoundException("Job with uuid " + uuid + " not found"); + } + return jobAdapter.toModel(job); + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/services/CategoryParameterService.java b/vid-app-common/src/main/java/org/onap/vid/services/CategoryParameterService.java index a140007b..044c4bb0 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/CategoryParameterService.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/CategoryParameterService.java @@ -1,18 +1,16 @@ package org.onap.vid.services; -import java.io.IOException; - import org.onap.vid.category.AddCategoryOptionResponse; +import org.onap.vid.category.AddCategoryOptionsRequest; import org.onap.vid.category.CategoryParameterOptionRep; import org.onap.vid.category.CategoryParametersResponse; -import org.onap.vid.category.AddCategoryOptionsRequest; -import org.onap.vid.model.CategoryParameterOption; import org.onap.vid.model.CategoryParameter.Family; +import org.onap.vid.model.CategoryParameterOption; public interface CategoryParameterService { - CategoryParametersResponse getCategoryParameters(Family familyName) throws IOException; - AddCategoryOptionResponse createCategoryParameterOptions(String categoryName, AddCategoryOptionsRequest option) throws IOException; + CategoryParametersResponse getCategoryParameters(Family familyName); + AddCategoryOptionResponse createCategoryParameterOptions(String categoryName, AddCategoryOptionsRequest option); AddCategoryOptionResponse updateCategoryParameterOption(String categoryName, CategoryParameterOptionRep option); - void deleteCategoryOption(String categoryName, CategoryParameterOption option) throws IOException; + void deleteCategoryOption(String categoryName, CategoryParameterOption option); } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/CategoryParameterServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/CategoryParameterServiceImpl.java index 3887fdfc..fa531ffc 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/CategoryParameterServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/CategoryParameterServiceImpl.java @@ -1,22 +1,20 @@ package org.onap.vid.services; -import java.io.IOException; -import java.util.*; -import java.util.stream.Collectors; - -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.service.DataAccessService; import org.onap.vid.category.AddCategoryOptionResponse; +import org.onap.vid.category.AddCategoryOptionsRequest; import org.onap.vid.category.CategoryParameterOptionRep; +import org.onap.vid.category.CategoryParametersResponse; import org.onap.vid.model.CategoryParameter; +import org.onap.vid.model.CategoryParameter.Family; import org.onap.vid.model.CategoryParameterOption; -import org.onap.vid.category.AddCategoryOptionsRequest; -import org.onap.vid.category.CategoryParametersResponse; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.service.DataAccessService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.onap.vid.model.CategoryParameter.Family; import javax.ws.rs.ForbiddenException; +import java.util.*; +import java.util.stream.Collectors; @Service @@ -49,7 +47,7 @@ public class CategoryParameterServiceImpl implements CategoryParameterService { } @Override - public CategoryParametersResponse getCategoryParameters(Family familyName) throws IOException { + public CategoryParametersResponse getCategoryParameters(Family familyName) { List<CategoryParameter> categoryParameters = dataAccessService.getList(CategoryParameter.class, String.format(" where family = '%s' ",familyName), null, null); return convertToCategoryParametersResponse(categoryParameters); } @@ -63,7 +61,7 @@ public class CategoryParameterServiceImpl implements CategoryParameterService { } @Override - public AddCategoryOptionResponse createCategoryParameterOptions(String categoryName, AddCategoryOptionsRequest optionsRequest) throws IOException, UnfoundedCategoryException { + public AddCategoryOptionResponse createCategoryParameterOptions(String categoryName, AddCategoryOptionsRequest optionsRequest) { AddCategoryOptionResponse response = new AddCategoryOptionResponse(new ArrayList<>()); CategoryParameter categoryParameter = getCategoryParameter(categoryName); @@ -123,7 +121,7 @@ public class CategoryParameterServiceImpl implements CategoryParameterService { } @Override - public void deleteCategoryOption(String categoryName, CategoryParameterOption option) throws IOException { + public void deleteCategoryOption(String categoryName, CategoryParameterOption option) { List<CategoryParameter> categoryParameters = dataAccessService.getList(CategoryParameter.class, String.format(" where name = '%s'", categoryName), null, null); if (categoryParameters.size() != 1) { String msg = "There is no category parameter with name " + categoryName; diff --git a/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementService.java b/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementService.java index bf083318..ab6239fd 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementService.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementService.java @@ -1,10 +1,8 @@ package org.onap.vid.services; -import fj.data.Either; import org.apache.commons.lang3.tuple.Pair; -import org.json.JSONObject; -import org.onap.vid.changeManagement.*; import org.json.simple.JSONArray; +import org.onap.vid.changeManagement.*; import org.onap.vid.mso.rest.Request; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; @@ -13,8 +11,8 @@ import java.util.Collection; import java.util.List; public interface ChangeManagementService { - Collection<Request> getMSOChangeManagements() throws Exception; - ResponseEntity<String> doChangeManagement(ChangeManagementRequest request, String vnfName) throws Exception; + Collection<Request> getMSOChangeManagements(); + ResponseEntity<String> doChangeManagement(ChangeManagementRequest request, String vnfName); JSONArray getSchedulerChangeManagements(); /** @@ -27,6 +25,6 @@ public interface ChangeManagementService { List<String> getWorkflowsForVnf(GetVnfWorkflowRelationRequest getVnfWorkflowRelationRequest); VnfWorkflowRelationResponse deleteVnfWorkflowRelation(VnfWorkflowRelationRequest vnfWorkflowRelationRequest); VnfWorkflowRelationAllResponse getAllVnfWorkflowRelations(); - String uploadConfigUpdateFile(MultipartFile file) throws Exception; + String uploadConfigUpdateFile(MultipartFile file); } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementServiceImpl.java index ca5fe44d..90d1c33e 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementServiceImpl.java @@ -17,7 +17,6 @@ import org.onap.vid.mso.MsoBusinessLogic; import org.onap.vid.mso.MsoResponseWrapperInterface; import org.onap.vid.mso.rest.Request; import org.onap.vid.scheduler.SchedulerProperties; -import org.onap.vid.scheduler.SchedulerRestInterfaceFactory; import org.onap.vid.scheduler.SchedulerRestInterfaceIfc; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; @@ -27,6 +26,7 @@ import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import javax.ws.rs.BadRequestException; +import java.io.IOException; import java.util.*; import java.util.stream.Collectors; @@ -34,27 +34,30 @@ import java.util.stream.Collectors; @Service public class ChangeManagementServiceImpl implements ChangeManagementService { - private final static String primaryKey = "payload"; - private final static Set<String> requiredKeys = new HashSet<>(Arrays.asList("request-parameters", "configuration-parameters")); + private final static String PRIMARY_KEY = "payload"; + private final static Set<String> REQUIRED_KEYS = new HashSet<>(Arrays.asList("request-parameters", "configuration-parameters")); private final DataAccessService dataAccessService; private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ChangeManagementServiceImpl.class); private MsoBusinessLogic msoBusinessLogic; + private final SchedulerRestInterfaceIfc restClient; + @Autowired private CsvService csvService; @Autowired - public ChangeManagementServiceImpl(DataAccessService dataAccessService, MsoBusinessLogic msoBusinessLogic) { + public ChangeManagementServiceImpl(DataAccessService dataAccessService, MsoBusinessLogic msoBusinessLogic, SchedulerRestInterfaceIfc schedulerRestInterface) { this.dataAccessService = dataAccessService; this.msoBusinessLogic = msoBusinessLogic; + this.restClient = schedulerRestInterface; } @Override - public Collection<Request> getMSOChangeManagements() throws Exception { + public Collection<Request> getMSOChangeManagements() { Collection<Request> result = null; return msoBusinessLogic.getOrchestrationRequestsForDashboard(); } - private RequestDetails findRequestByVnfName(List<RequestDetails> requests, String vnfName) { + protected RequestDetails findRequestByVnfName(List<RequestDetails> requests, String vnfName) { if (requests == null) return null; @@ -69,7 +72,7 @@ public class ChangeManagementServiceImpl implements ChangeManagementService { } @Override - public ResponseEntity<String> doChangeManagement(ChangeManagementRequest request, String vnfName) throws Exception { + public ResponseEntity<String> doChangeManagement(ChangeManagementRequest request, String vnfName) { if (request == null) return null; ResponseEntity<String> response; @@ -102,6 +105,8 @@ public class ChangeManagementServiceImpl implements ChangeManagementService { msoResponseWrapperObject = msoBusinessLogic.createVfModuleInstance(currentRequestDetails, serviceInstanceId, vnfInstanceId); break; } + default: + logger.error("Failure during doChangeManagement with request " + request.toString()); } response = new ResponseEntity<String>(msoResponseWrapperObject.getResponse(), HttpStatus.OK); return response; @@ -124,7 +129,7 @@ public class ChangeManagementServiceImpl implements ChangeManagementService { return currentRequestDetails.getVnfInstanceId(); } - private String extractServiceInstanceId(RequestDetails currentRequestDetails, String requestType) { + protected String extractServiceInstanceId(RequestDetails currentRequestDetails, String requestType) { try { String serviceInstanceId = currentRequestDetails.getRelatedInstList().get(0).getRelatedInstance().getInstanceId(); serviceInstanceId.toString(); //throw exception in case that serviceInstanceId is null... @@ -141,7 +146,6 @@ public class ChangeManagementServiceImpl implements ChangeManagementService { try { String path = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_GET_SCHEDULES); org.onap.vid.scheduler.RestObject<String> restObject = new org.onap.vid.scheduler.RestObject<>(); - SchedulerRestInterfaceIfc restClient = SchedulerRestInterfaceFactory.getInstance(); String str = new String(); restObject.set(str); @@ -162,7 +166,6 @@ public class ChangeManagementServiceImpl implements ChangeManagementService { try { String path = String.format(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_DELETE_SCHEDULE), scheduleId); org.onap.vid.scheduler.RestObject<String> restObject = new org.onap.vid.scheduler.RestObject<>(); - SchedulerRestInterfaceIfc restClient = SchedulerRestInterfaceFactory.getInstance(); String str = new String(); restObject.set(str); restClient.Delete(str, "", path, restObject); @@ -289,18 +292,22 @@ public class ChangeManagementServiceImpl implements ChangeManagementService { } @Override - public String uploadConfigUpdateFile(MultipartFile file) - throws Exception { - JSONObject json = csvService.convertCsvToJson(csvService.readCsv(file)); + public String uploadConfigUpdateFile(MultipartFile file) { + JSONObject json = null; + try { + json = csvService.convertCsvToJson(csvService.readCsv(file)); + } catch (InstantiationException | IllegalAccessException | IOException e) { + throw new BadRequestException("Invalid csv file", e); + } if (!validateJsonOutput(json)) throw new BadRequestException("Invalid csv file"); - json = json.getJSONObject(primaryKey); - json = new JSONObject().put(primaryKey, json.toString()); + json = json.getJSONObject(PRIMARY_KEY); + json = new JSONObject().put(PRIMARY_KEY, json.toString()); return json.toString(); } private boolean validateJsonOutput(org.json.JSONObject json) { - if (!json.has(primaryKey) || !json.getJSONObject(primaryKey).keySet().containsAll(requiredKeys)) + if (!json.has(PRIMARY_KEY) || !json.getJSONObject(PRIMARY_KEY).keySet().containsAll(REQUIRED_KEYS)) return false; return true; } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/CsvServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/CsvServiceImpl.java index e0100e5b..6f5f4f73 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/CsvServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/CsvServiceImpl.java @@ -8,7 +8,6 @@ import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.ws.rs.BadRequestException; -import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; @@ -25,7 +24,7 @@ public class CsvServiceImpl implements CsvService{ /** The logger. */ static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CsvServiceImpl.class); - private static final String arrayRegex = "\\[(.*?)\\]"; + private static final String ARRAY_REGEX = "\\[(.*?)\\]"; /** @@ -216,33 +215,37 @@ public class CsvServiceImpl implements CsvService{ String key = currentRow[j]; if (j == length-1) { json = putJson(json,currentRow[j],null); + } + else + { + json = buildJsonRow(myEntries, i, j, json, currentRow, length, currentDuplicateRows, key); + } + i += currentDuplicateRows; + } + logger.debug(EELFLoggerDelegate.debugLogger, "end {} json = {}", getMethodName(), json); + return json; + } + private <T> T buildJsonRow(List<String[]> myEntries, int i, int j, T json, String[] currentRow, int length, int currentDuplicateRows, String key) throws IllegalAccessException, InstantiationException { + if (key.matches(ARRAY_REGEX)){ + JSONArray arrayObjects = buildJSON(myEntries, i, j + 1, currentDuplicateRows, JSONArray.class); + json = putJson(json,key.replaceAll("\\[","").replaceAll("]",""),arrayObjects); + } + else { + if (j < length - 2) { + json = putJson(json, currentRow[j], buildJSON(myEntries, i, j + 1, currentDuplicateRows, JSONObject.class)); } else { - if (key.matches(arrayRegex)){ - JSONArray arrayObjects = buildJSON(myEntries, i, j + 1, currentDuplicateRows, JSONArray.class); - json = putJson(json,key.replaceAll("\\[","").replaceAll("]",""),arrayObjects); - } - else { - if (j < length - 2) { - json = putJson(json, currentRow[j], buildJSON(myEntries, i, j + 1, currentDuplicateRows, JSONObject.class)); - } - else - { - if (j == length - 2)//last object - { - if(currentDuplicateRows > 1) { - throw new BadRequestException("Invalid csv file"); - } - json = putJson(json, currentRow[j], currentRow[j + 1]); - } + if (j == length - 2)//last object + { + if(currentDuplicateRows > 1) { + throw new BadRequestException("Invalid csv file"); } + json = putJson(json, currentRow[j], currentRow[j + 1]); } } - i += currentDuplicateRows; } - logger.debug(EELFLoggerDelegate.debugLogger, "end {} json = {}", getMethodName(), json); return json; } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/PombaService.java b/vid-app-common/src/main/java/org/onap/vid/services/PombaService.java new file mode 100644 index 00000000..28c947b6 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/services/PombaService.java @@ -0,0 +1,7 @@ +package org.onap.vid.services; + +import org.onap.vid.model.PombaInstance.PombaRequest; + +public interface PombaService { + void verify(PombaRequest request); +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/services/PombaServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/PombaServiceImpl.java new file mode 100644 index 00000000..21b1ec1c --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/services/PombaServiceImpl.java @@ -0,0 +1,17 @@ +package org.onap.vid.services; + +import org.onap.vid.aai.PombaClientInterface; +import org.onap.vid.model.PombaInstance.PombaRequest; +import org.springframework.beans.factory.annotation.Autowired; + +public class PombaServiceImpl implements PombaService { + + @Autowired + private PombaClientInterface pombaClientInterface; + + + @Override + public void verify(PombaRequest request) { + pombaClientInterface.verify(request); + } +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/services/RoleGenaratorServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/RoleGenaratorServiceImpl.java index ea2cea57..635cb485 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/RoleGenaratorServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/RoleGenaratorServiceImpl.java @@ -1,8 +1,10 @@ package org.onap.vid.services; import jline.internal.Log; -import org.junit.Test; -import org.onap.vid.aai.*; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.AaiResponse; +import org.onap.vid.aai.ServiceSubscription; +import org.onap.vid.aai.Services; import org.onap.vid.model.ModelConstants; import org.onap.vid.model.Subscriber; import org.onap.vid.model.SubscriberList; @@ -14,17 +16,18 @@ import java.util.HashMap; @Service public class RoleGenaratorServiceImpl implements RoleGeneratorService { + public static final String ROLE_ID_COLUMN = "ROLE_ID"; @Autowired AaiClientInterface client; - public static final String dbName = "vid_portal"; - public static final String tblName = "fn_role"; - public static final String tempDelimiter ="***"; - public static final String oldDelimiter = "_"; + public static final String DB_NAME = "vid_portal"; + public static final String TBL_NAME = "fn_role"; + public static final String TEMP_DELIMITER ="***"; + public static final String OLD_DELIMITER = "_"; @Override public String generateRoleScript(Boolean firstRun) { - String query = "USE " + dbName + ";\r\n" + + String query = "USE " + DB_NAME + ";\r\n" + "SET SQL_SAFE_UPDATES = 0;\r\n"; try { AaiResponse<SubscriberList> subscribers = client.getAllSubscribers(); @@ -69,7 +72,7 @@ public class RoleGenaratorServiceImpl implements RoleGeneratorService { private String buildSubscribersValuesForMappingsTable(SubscriberList subscribers){ String query=""; for (Subscriber subscriber : subscribers.customer) { - String subscriberName = subscriber.subscriberName.contains(oldDelimiter) ? subscriber.subscriberName.replace(oldDelimiter, tempDelimiter) : subscriber.subscriberName; + String subscriberName = subscriber.subscriberName.contains(OLD_DELIMITER) ? subscriber.subscriberName.replace(OLD_DELIMITER, TEMP_DELIMITER) : subscriber.subscriberName; query = query + "('" + subscriber.globalCustomerId + "','" + subscriberName + "') ,"; } if(query.length() > 0) @@ -80,8 +83,8 @@ public class RoleGenaratorServiceImpl implements RoleGeneratorService { private String buildServicesValuesForMappingsTable(HashMap<String,String> servicesNames){ final String[] query = {""}; servicesNames.forEach((k,v)->{ - if (k.contains(oldDelimiter)) { - query[0] += "('" + k + "' ,'" + k.replace(oldDelimiter, tempDelimiter) +"'),"; + if (k.contains(OLD_DELIMITER)) { + query[0] += "('" + k + "' ,'" + k.replace(OLD_DELIMITER, TEMP_DELIMITER) +"'),"; } }); if(query[0].length() > 0) @@ -97,7 +100,7 @@ public class RoleGenaratorServiceImpl implements RoleGeneratorService { query = "CREATE TEMPORARY TABLE IF NOT EXISTS " + entityName + "Mappings(mapKey VARCHAR(255),mapValue VARCHAR(255));\r\n" + "INSERT INTO " + entityName + "Mappings VALUES "; query += valuesForMappingsTable; - query += "UPDATE " + tblName + "\r\n" + + query += "UPDATE " + TBL_NAME + "\r\n" + "INNER JOIN " + entityName + "Mappings ON role_name LIKE concat('%',mapKey, '%')\r\n" + "SET ROLE_NAME = REPLACE(ROLE_NAME, mapKey, mapValue) ; \r\n" + dropTemporaryTable(entityName + "Mappings"); @@ -106,10 +109,10 @@ public class RoleGenaratorServiceImpl implements RoleGeneratorService { } private String replaceToNewDelimiter(){ - String query = "UPDATE " + tblName + "\r\n" + - "SET ROLE_NAME = REPLACE(ROLE_NAME, '" + oldDelimiter + "', '" + ModelConstants.ROLE_DELIMITER + "');\r\n" ; + String query = "UPDATE " + TBL_NAME + "\r\n" + + "SET ROLE_NAME = REPLACE(ROLE_NAME, '" + OLD_DELIMITER + "', '" + ModelConstants.ROLE_DELIMITER + "');\r\n" ; query += "UPDATE fn_role\r\n" + - "SET ROLE_NAME = REPLACE(ROLE_NAME, '" + tempDelimiter + "', '" + oldDelimiter + "');\r\n" ; + "SET ROLE_NAME = REPLACE(ROLE_NAME, '" + TEMP_DELIMITER + "', '" + OLD_DELIMITER + "');\r\n" ; return query; } @@ -145,9 +148,9 @@ public class RoleGenaratorServiceImpl implements RoleGeneratorService { String query = deleteFromTableByRoles("fn_role_composite", "PARENT_ROLE_ID"); query = query.substring(0, query.length()-1); query += " OR wrong_roles.ROLEID = fn_role_composite.CHILD_ROLE_ID;\r\n"; - query += deleteFromTableByRoles("fn_role_function", "ROLE_ID")+ "\r\n"; - query += deleteFromTableByRoles("fn_user_role", "ROLE_ID")+ "\r\n"; - query += deleteFromTableByRoles("fn_role", "ROLE_ID")+ "\r\n"; + query += deleteFromTableByRoles("fn_role_function", ROLE_ID_COLUMN)+ "\r\n"; + query += deleteFromTableByRoles("fn_user_role", ROLE_ID_COLUMN)+ "\r\n"; + query += deleteFromTableByRoles(TBL_NAME, ROLE_ID_COLUMN)+ "\r\n"; return query; } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/VidService.java b/vid-app-common/src/main/java/org/onap/vid/services/VidService.java index 328fad01..ae1765f0 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/VidService.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/VidService.java @@ -1,17 +1,11 @@ package org.onap.vid.services; import org.onap.vid.asdc.AsdcCatalogException; -import org.onap.vid.asdc.beans.Service; import org.onap.vid.model.ServiceModel; -import java.util.Collection; -import java.util.Map; - public interface VidService { - Collection<Service> getServices(Map<String, String[]> requestParams) - throws AsdcCatalogException; - ServiceModel getService(String uuid) throws AsdcCatalogException; + void invalidateServiceCache(); }
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/services/VidServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/VidServiceImpl.java index 55243019..dc2541b3 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/VidServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/VidServiceImpl.java @@ -1,5 +1,8 @@ package org.onap.vid.services; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; import org.onap.vid.asdc.AsdcCatalogException; @@ -8,13 +11,17 @@ import org.onap.vid.asdc.beans.Service; import org.onap.vid.asdc.parser.ToscaParser; import org.onap.vid.asdc.parser.ToscaParserImpl; import org.onap.vid.asdc.parser.ToscaParserImpl2; +import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.ServiceModel; import org.springframework.beans.factory.annotation.Autowired; +import org.togglz.core.manager.FeatureManager; import java.nio.file.Path; -import java.util.Collection; -import java.util.Map; import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +import static org.onap.vid.properties.Features.FLAG_SERVICE_MODEL_CACHE; /** * The Class VidController. @@ -29,22 +36,37 @@ public class VidServiceImpl implements VidService { * The Constant dateFormat. */ protected final AsdcClient asdcClient; + private final FeatureManager featureManager; + @Autowired private ToscaParserImpl2 toscaParser; + private final LoadingCache<String, ServiceModel> serviceModelCache; - public VidServiceImpl(AsdcClient asdcClient) { - this.asdcClient = asdcClient; + + private class NullServiceModelException extends Exception { + NullServiceModelException(String modelUuid) { + super("Could not create service model for UUID " + modelUuid); + } } - /* - * (non-Javadoc) - * - * @see org.onap.vid.controller.VidService#getServices(java.util.Map) - */ - @Override - public Collection<Service> getServices(Map<String, String[]> requestParams) - throws AsdcCatalogException { - return asdcClient.getServices(requestParams); + public VidServiceImpl(AsdcClient asdcClient, FeatureManager featureManager) { + this.asdcClient = asdcClient; + this.featureManager = featureManager; + + this.serviceModelCache = CacheBuilder.newBuilder() + .maximumSize(1000) + .expireAfterAccess(7, TimeUnit.DAYS) + .build(new CacheLoader<String, ServiceModel>() { + @Override + public ServiceModel load(String modelUuid) throws AsdcCatalogException, NullServiceModelException { + ServiceModel serviceModel = getServiceFromSdc(modelUuid); + if (serviceModel != null) { + return serviceModel; + } else { + throw new NullServiceModelException(modelUuid); + } + } + }); } /* @@ -54,6 +76,28 @@ public class VidServiceImpl implements VidService { */ @Override public ServiceModel getService(String uuid) throws AsdcCatalogException { + if (featureManager.isActive(FLAG_SERVICE_MODEL_CACHE)) { + return getServiceFromCache(uuid); + }else { + return getServiceFromSdc(uuid); + } + } + + private ServiceModel getServiceFromCache(String uuid) throws AsdcCatalogException { + try { + return serviceModelCache.get(uuid); + } catch (ExecutionException e) { + if (e.getCause() instanceof AsdcCatalogException) { + throw (AsdcCatalogException) e.getCause(); + } else if (e.getCause() instanceof NullServiceModelException) { + return null; + } else { + throw new GenericUncheckedException(e); + } + } + } + + private ServiceModel getServiceFromSdc(String uuid) throws AsdcCatalogException { final Path serviceCsar = asdcClient.getServiceToscaModel(UUID.fromString(uuid)); ToscaParser tosca = new ToscaParserImpl(); serviceCsar.toFile().getAbsolutePath(); @@ -67,13 +111,17 @@ public class VidServiceImpl implements VidService { return serviceModel; } - private ServiceModel getServiceModel(String uuid, Path serviceCsar, ToscaParser tosca, Service asdcServiceMetadata) throws Exception { + private ServiceModel getServiceModel(String uuid, Path serviceCsar, ToscaParser tosca, Service asdcServiceMetadata) throws AsdcCatalogException { try { return toscaParser.makeServiceModel(serviceCsar, asdcServiceMetadata); } catch (SdcToscaParserException e) { return tosca.makeServiceModel(uuid, serviceCsar, asdcServiceMetadata); } } - + + @Override + public void invalidateServiceCache(){ + serviceModelCache.invalidateAll(); + } }
\ No newline at end of file |