diff options
Diffstat (limited to 'vid-app-common/src/main')
202 files changed, 8804 insertions, 4615 deletions
diff --git a/vid-app-common/src/main/java/org/onap/vid/RelatedTo.java b/vid-app-common/src/main/java/org/onap/vid/RelatedTo.java index 738f6203..08e02816 100644 --- a/vid-app-common/src/main/java/org/onap/vid/RelatedTo.java +++ b/vid-app-common/src/main/java/org/onap/vid/RelatedTo.java @@ -24,7 +24,7 @@ public class RelatedTo { @JsonProperty("url") public String url; @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + private Map<String, Object> additionalProperties = new HashMap<>(); @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiClient.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiClient.java index 6ed34590..c1964c16 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/AaiClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiClient.java @@ -1,37 +1,46 @@ package org.onap.vid.aai; +import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.apache.http.client.utils.URIBuilder; +import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; -import org.onap.vid.aai.util.AAIRestInterface; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.vid.aai.model.AaiGetAicZone.AicZones; -import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList; import org.onap.vid.aai.model.*; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.*; +import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList; import org.onap.vid.aai.model.AaiGetPnfs.Pnf; import org.onap.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone; import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; +import org.onap.vid.aai.model.Relationship; +import org.onap.vid.aai.model.RelationshipData; +import org.onap.vid.aai.model.RelationshipList; +import org.onap.vid.aai.util.AAIRestInterface; +import org.onap.vid.aai.util.VidObjectMapperType; +import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.SubscriberList; -import org.springframework.beans.factory.annotation.Autowired; +import org.onap.vid.model.probes.ErrorMetadata; +import org.onap.vid.model.probes.ExternalComponentStatus; +import org.onap.vid.model.probes.HttpRequestMetadata; +import org.onap.vid.utils.Logging; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.web.util.UriUtils; -import javax.servlet.ServletContext; -import javax.ws.rs.BadRequestException; +import javax.inject.Inject; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; -import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.UUID; +import java.util.*; + +import static java.util.Collections.emptyList; +import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; /** @@ -39,27 +48,37 @@ import java.util.UUID; */ public class AaiClient implements AaiClientInterface { - /** - * The Constant dateFormat. - */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + public static final String QUERY_FORMAT_RESOURCE = "query?format=resource"; + public static final String SERVICE_SUBSCRIPTIONS_PATH = "/service-subscriptions/service-subscription/"; + public static final String MODEL_INVARIANT_ID = "&model-invariant-id="; + public static final String QUERY_FORMAT_SIMPLE = "query?format=simple"; + public static final String BUSINESS_CUSTOMER = "/business/customers/customer/"; + public static final String SERVICE_INSTANCE = "/service-instances/service-instance/"; + public static final String BUSINESS_CUSTOMERS_CUSTOMER = "business/customers/customer/"; + protected String fromAppId = "VidAaiController"; - @Autowired - ServletContext servletContext; + + private PortDetailsTranslator portDetailsTranslator; + + private final AAIRestInterface restController; + /** * The logger */ - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class); - private final String getServiceModelsResponseBody = "{\"start\" : \"service-design-and-creation/models/\", \"query\" : \"query/serviceModels-byDistributionStatus?distributionStatus=DISTRIBUTION_COMPLETE_OK\"}"; - public AaiClient() { - // certiPath = getCertificatesFile().getAbsolutePath(); - // depth = "0"; - } + /** + * The Constant dateFormat. + */ + static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + static final String GET_SERVICE_MODELS_RESPONSE_BODY = "{\"start\" : \"service-design-and-creation/models/\", \"query\" : \"query/serviceModels-byDistributionStatus?distributionStatus=DISTRIBUTION_COMPLETE_OK\"}"; - public AaiClient(ServletContext context) { - servletContext = context; + @Inject + public AaiClient(AAIRestInterface restController, PortDetailsTranslator portDetailsTranslator) { + this.restController = restController; + this.portDetailsTranslator = portDetailsTranslator; } @@ -73,67 +92,131 @@ public class AaiClient implements AaiClientInterface { @Override public AaiResponse getServicesByOwningEntityId(List<String> owningEntityIds){ - File certiPath = getCertificatesFile(); - Response resp = doAaiGet(certiPath.getAbsolutePath(), getUrlFromLIst("business/owning-entities?", "owning-entity-id=", owningEntityIds), false); - AaiResponse aaiResponse = proccessAaiResponse(resp, OwningEntityResponse.class, null); - - return aaiResponse; + Response resp = doAaiGet(getUrlFromLIst("business/owning-entities?", "owning-entity-id=", owningEntityIds), false); + return processAaiResponse(resp, OwningEntityResponse.class, null); } @Override public AaiResponse getServicesByProjectNames(List<String> projectNames){ - File certiPath = getCertificatesFile(); - Response resp = doAaiGet(certiPath.getAbsolutePath(), getUrlFromLIst("business/projects?", "project-name=", projectNames), false); - AaiResponse aaiResponse = proccessAaiResponse(resp, ProjectResponse.class, null); - - return aaiResponse; + Response resp = doAaiGet(getUrlFromLIst("business/projects?", "project-name=", projectNames), false); + return processAaiResponse(resp, ProjectResponse.class, null); } @Override public AaiResponse getServiceModelsByDistributionStatus() { - File certiPath = getCertificatesFile(); - Response resp = doAaiPut(certiPath.getAbsolutePath(), "query?format=resource", getServiceModelsResponseBody, false); - AaiResponse aaiResponse = proccessAaiResponse(resp, GetServiceModelsByDistributionStatusResponse.class, null); + Response resp = doAaiPut(QUERY_FORMAT_RESOURCE, GET_SERVICE_MODELS_RESPONSE_BODY, false); + return processAaiResponse(resp, GetServiceModelsByDistributionStatusResponse.class, null); + } + + @Override + public AaiResponse getNetworkCollectionDetails(String serviceInstanceId) { + Response resp = doAaiPut(QUERY_FORMAT_RESOURCE, "{\"start\": [\"nodes/service-instances/service-instance/" + serviceInstanceId + "\"],\"query\": \"query/network-collection-ByServiceInstance\"}\n", false); + AaiResponse<AaiGetNetworkCollectionDetailsHelper> aaiResponse = processAaiResponse(resp, AaiGetNetworkCollectionDetailsHelper.class, null, VidObjectMapperType.FASTERXML); + return getNetworkCollectionDetailsResponse(aaiResponse); + } + + @Override + public AaiResponse getInstanceGroupsByCloudRegion(String cloudOwner, String cloudRegionId, String networkFunction) { + Response resp = doAaiPut(QUERY_FORMAT_RESOURCE, + "{\"start\": [\"cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner + "/" + cloudRegionId + "\"]," + + "\"query\": \"query/instance-group-byCloudRegion?type=L3-NETWORK&role=SUB-INTERFACE&function=" + networkFunction + "\"}\n", false); + return processAaiResponse(resp, AaiGetInstanceGroupsByCloudRegion.class, null, VidObjectMapperType.FASTERXML); + } + private AaiResponse getNetworkCollectionDetailsResponse(AaiResponse<AaiGetNetworkCollectionDetailsHelper> aaiResponse){ + if(aaiResponse.getHttpCode() == 200) { + com.fasterxml.jackson.databind.ObjectMapper om = new com.fasterxml.jackson.databind.ObjectMapper(); + AaiGetNetworkCollectionDetails aaiGetNetworkCollectionDetails = new AaiGetNetworkCollectionDetails(); + try { + for (int i = 0; i < aaiResponse.getT().getResults().size(); i++) { + LinkedHashMap<String, Object> temp = ((LinkedHashMap) aaiResponse.getT().getResults().get(i)); + if (temp.get("service-instance") != null) + aaiGetNetworkCollectionDetails.getResults().setServiceInstance(om.readValue(om.writeValueAsString(temp.get("service-instance")), org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.ServiceInstance.class)); + else if (temp.get("collection") != null) + aaiGetNetworkCollectionDetails.getResults().setCollection(om.readValue(om.writeValueAsString(temp.get("collection")), org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Collection.class)); + else if (temp.get("instance-group") != null) + aaiGetNetworkCollectionDetails.getResults().setInstanceGroup(om.readValue(om.writeValueAsString(temp.get("instance-group")), InstanceGroup.class)); + else if (temp.get("l3-network") != null) + aaiGetNetworkCollectionDetails.getResults().getNetworks().add(om.readValue(om.writeValueAsString(temp.get("l3-network")), Network.class)); + } + return new AaiResponse(aaiGetNetworkCollectionDetails, null, HttpStatus.SC_OK); + } + catch (com.fasterxml.jackson.databind.JsonMappingException e) { + return new AaiResponse(e.getCause(), "AAI response parsing Error" , aaiResponse.getHttpCode()); + } + catch (Exception e) { + return new AaiResponse(e.getCause(), "Got " + aaiResponse.getHttpCode() + " from a&ai" , aaiResponse.getHttpCode()); + } + } return aaiResponse; } @Override public AaiResponse getPNFData(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion, String equipVendor, String equipModel) { - String certiPath = getCertificatesFile().getAbsolutePath(); - String siQuery = "/business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + "&model-invariant-id=" + modelInvariantId; + String siQuery = BUSINESS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + MODEL_INVARIANT_ID + modelInvariantId; String pnfQuery = "query/pnf-fromModel-byRegion?cloudRegionId=" + encodePathSegment(cloudRegion) + "&equipVendor=" + encodePathSegment(equipVendor) + "&equipModel=" + encodePathSegment(equipModel); String payload = "{\"start\":\"" + siQuery + "\",\"query\":\"" + pnfQuery + "\"}"; - Response resp = doAaiPut(certiPath, "query?format=simple", payload, false); - return proccessAaiResponse(resp, AaiGetPnfResponse.class, null); + Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false); + return processAaiResponse(resp, AaiGetPnfResponse.class, null); } @Override public AaiResponse<Pnf> getSpecificPnf(String pnfId) { - File certiPath = getCertificatesFile(); - Response resp = doAaiGet(certiPath.getAbsolutePath(), "network/pnfs/pnf/"+pnfId, false); - AaiResponse aaiResponse = proccessAaiResponse(resp, Pnf.class, null); + Response resp = doAaiGet("network/pnfs/pnf/"+pnfId, false); + return processAaiResponse(resp, Pnf.class, null); + } - return aaiResponse; + + public AaiResponse getInstanceGroupsByVnfInstanceId(String vnfInstanceId){ + Response resp = doAaiGet("network/generic-vnfs/generic-vnf/" + vnfInstanceId + "?depth=0", false); + return processAaiResponse(resp, AaiGetRelatedInstanceGroupsByVnfId.class , null, null); + } + + + @Override + public List<PortDetailsTranslator.PortDetails> getPortMirroringSourcePorts(String configurationID) { + String payload = "{\"start\":\"/network/configurations/configuration/" + configurationID + "\",\"query\":\"query/pserver-fromConfiguration\"}"; + Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false); + resp.bufferEntity(); // avoid later "Entity input stream has already been closed" problems + String rawPayload = resp.readEntity(String.class); + AaiResponse<AaiGetPortMirroringSourcePorts> aaiResponse = processAaiResponse(resp, AaiGetPortMirroringSourcePorts.class, rawPayload); + return portDetailsTranslator.extractPortDetails(aaiResponse, rawPayload); } + + public AaiResponse getServiceInstance(String globalCustomerId, String serviceType, String serviceInstanceId) { - String certiPath = getCertificatesFile().getAbsolutePath(); - String getServiceInstancePath = "business/customers/customer/"+globalCustomerId+"/service-subscriptions/service-subscription/"+serviceType+"/service-instances/service-instance/"+serviceInstanceId; - Response resp = doAaiGet(certiPath , getServiceInstancePath , false); - return proccessAaiResponse(resp, ServiceRelationships.class, null); + String getServiceInstancePath = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId+ SERVICE_SUBSCRIPTIONS_PATH +serviceType+ SERVICE_INSTANCE +serviceInstanceId; + Response resp = doAaiGet(getServiceInstancePath , false); + return processAaiResponse(resp, ServiceRelationships.class, null); } @Override public AaiResponse getLogicalLink(String link) { - String certiPath = getCertificatesFile().getAbsolutePath(); - Response resp = doAaiGet(certiPath , "network/logical-links/logical-link/" + link , false); - return proccessAaiResponse(resp, LogicalLinkResponse.class, null); + Response resp = doAaiGet("network/logical-links/logical-link/" + link , false); + return processAaiResponse(resp, LogicalLinkResponse.class, null); + } + + @Override + public AaiResponse<AaiNodeQueryResponse> searchNodeTypeByName(String name, ResourceType type) { + String path = String.format( + "search/nodes-query?search-node-type=%s&filter=%s:EQUALS:%s", + type.getAaiFormat(), + type.getNameFilter(), + name + ); + return typedAaiGet(path, AaiNodeQueryResponse.class); } + private <T> AaiResponse<T> typedAaiGet(String path, Class<T> clz) { + Response resp = doAaiGet(path , false); + return processAaiResponse(resp, clz, null, VidObjectMapperType.FASTERXML); + } + + + private String getUrlFromLIst(String url, String paramKey, List<String> params){ - url.concat(paramKey); int i = 0; for(String param: params){ i ++; @@ -157,99 +240,89 @@ public class AaiClient implements AaiClientInterface { @Override public AaiResponse<SubscriberList> getAllSubscribers() { - String certiPath = getCertificatesFile().getAbsolutePath(); + return getAllSubscribers(false).getAaiResponse(); + } + + AaiResponseWithRequestInfo<SubscriberList> getAllSubscribers(boolean propagateExceptions){ String depth = "0"; - Response resp = doAaiGet(certiPath, "business/customers?subscriber-type=INFRA&depth=" + depth, false); - return proccessAaiResponse(resp, SubscriberList.class, null); + ResponseWithRequestInfo aaiGetResult = doAaiGet("business/customers?subscriber-type=INFRA&depth=" + depth, false, propagateExceptions); + AaiResponseWithRequestInfo<SubscriberList> responseWithRequestInfo = processAaiResponse(aaiGetResult, SubscriberList.class, propagateExceptions); + responseWithRequestInfo.setRequestedUrl(aaiGetResult.getRequestUrl()); + responseWithRequestInfo.setHttpMethod(aaiGetResult.getRequestHttpMethod()); + return responseWithRequestInfo; } @Override public AaiResponse getAllAicZones() { - String certiPath = getCertificatesFile().getAbsolutePath(); - Response resp = doAaiGet(certiPath, "network/zones", false); - AaiResponse aaiAicZones = proccessAaiResponse(resp, AicZones.class, null); - return aaiAicZones; + Response resp = doAaiGet("network/zones", false); + return processAaiResponse(resp, AicZones.class, null); } @Override public AaiResponse<String> getAicZoneForPnf(String globalCustomerId , String serviceType , String serviceId) { - String certiPath = getCertificatesFile().getAbsolutePath(); - String aicZonePath = "business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId; - Response resp = doAaiGet(certiPath , aicZonePath , false); - AaiResponse<ServiceRelationships> aaiResponse = proccessAaiResponse(resp , ServiceRelationships.class , null); - ServiceRelationships serviceRelationships = (ServiceRelationships)aaiResponse.getT(); + String aicZonePath = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + serviceType + SERVICE_INSTANCE + serviceId; + Response resp = doAaiGet(aicZonePath , false); + AaiResponse<ServiceRelationships> aaiResponse = processAaiResponse(resp , ServiceRelationships.class , null); + ServiceRelationships serviceRelationships = aaiResponse.getT(); RelationshipList relationshipList = serviceRelationships.getRelationshipList(); Relationship relationship = relationshipList.getRelationship().get(0); RelationshipData relationshipData= relationship.getRelationDataList().get(0); String aicZone = relationshipData.getRelationshipValue(); - AaiResponse<String> aaiAicZonaForPnfResponse = new AaiResponse(aicZone , null ,HttpStatus.SC_OK); - return aaiAicZonaForPnfResponse; + return new AaiResponse(aicZone , null ,HttpStatus.SC_OK); } @Override public AaiResponse getVNFData() { - String certiPath = getCertificatesFile().getAbsolutePath(); String payload = "{\"start\": [\"/business/customers/customer/e433710f-9217-458d-a79d-1c7aff376d89/service-subscriptions/service-subscription/VIRTUAL%20USP/service-instances/service-instance/3f93c7cb-2fd0-4557-9514-e189b7b04f9d\"], \"query\": \"query/vnf-topology-fromServiceInstance\"}"; - Response resp = doAaiPut(certiPath, "query?format=simple", payload, false); - return proccessAaiResponse(resp, AaiGetVnfResponse.class, null); - + Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false); + return processAaiResponse(resp, AaiGetVnfResponse.class, null); } @Override public Response getVNFData(String globalSubscriberId, String serviceType) { - String certiPath = getCertificatesFile().getAbsolutePath(); - String payload = "{\"start\": [\"business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/"+ encodePathSegment(serviceType) +"/service-instances\"]," + + String payload = "{\"start\": [\"business/customers/customer/" + globalSubscriberId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) +"/service-instances\"]," + "\"query\": \"query/vnf-topology-fromServiceInstance\"}"; - return doAaiPut(certiPath, "query?format=simple", payload, false); - + return doAaiPut(QUERY_FORMAT_SIMPLE, payload, false); } @Override public AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId) { - String certiPath = getCertificatesFile().getAbsolutePath(); - String payload = "{\"start\": [\"/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + encodePathSegment(serviceType) + "/service-instances/service-instance/" + serviceInstanceId + "\"], \"query\": \"query/vnf-topology-fromServiceInstance\"}"; - Response resp = doAaiPut(certiPath, "query?format=simple", payload, false); - return proccessAaiResponse(resp, AaiGetVnfResponse.class, null); + String payload = "{\"start\": [\"/business/customers/customer/" + globalSubscriberId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + SERVICE_INSTANCE + serviceInstanceId + "\"], \"query\": \"query/vnf-topology-fromServiceInstance\"}"; + Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false); + return processAaiResponse(resp, AaiGetVnfResponse.class, null); } @Override public Response getVersionByInvariantId(List<String> modelInvariantId) { - File certiPath = getCertificatesFile(); StringBuilder sb = new StringBuilder(); for (String id : modelInvariantId){ - sb.append("&model-invariant-id="); + sb.append(MODEL_INVARIANT_ID); sb.append(id); } - Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/models?depth=2"+ sb.toString(), false); - return resp; + return doAaiGet("service-design-and-creation/models?depth=2"+ sb.toString(), false); } @Override public AaiResponse getSubscriberData(String subscriberId) { - File certiPath = getCertificatesFile(); String depth = "2"; AaiResponse subscriberDataResponse; - Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId + "?depth=" + depth, false); - subscriberDataResponse = proccessAaiResponse(resp, Services.class, null); + Response resp = doAaiGet(BUSINESS_CUSTOMERS_CUSTOMER + subscriberId + "?depth=" + depth, false); + subscriberDataResponse = processAaiResponse(resp, Services.class, null); return subscriberDataResponse; } @Override public AaiResponse getServices() { - File certiPath = getCertificatesFile(); - Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/services", false); - AaiResponse<GetServicesAAIRespone> getServicesResponse = proccessAaiResponse(resp, GetServicesAAIRespone.class, null); - - return getServicesResponse; + Response resp = doAaiGet("service-design-and-creation/services", false); + return processAaiResponse(resp, GetServicesAAIRespone.class, null); } @Override public AaiResponse getOperationalEnvironments(String operationalEnvironmentType, String operationalEnvironmentStatus) { - File certiPath = getCertificatesFile(); String url = "cloud-infrastructure/operational-environments"; URIBuilder urlBuilder = new URIBuilder(); if (operationalEnvironmentType != null) @@ -257,47 +330,83 @@ public class AaiClient implements AaiClientInterface { if (operationalEnvironmentStatus != null) urlBuilder.addParameter("operational-environment-status", operationalEnvironmentStatus); url += urlBuilder.toString(); - Response resp = doAaiGet(certiPath.getAbsolutePath(), url, false); - AaiResponse<OperationalEnvironmentList> getOperationalEnvironmentsResponse = proccessAaiResponse(resp, OperationalEnvironmentList.class, null); - return getOperationalEnvironmentsResponse; - + Response resp = doAaiGet(url, false); + return processAaiResponse(resp, OperationalEnvironmentList.class, null); } @Override public AaiResponse getTenants(String globalCustomerId, String serviceType) { - File certiPath = getCertificatesFile(); - String url = "business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceType; + AaiResponse aaiResponse; - Response resp = doAaiGet(certiPath.getAbsolutePath(), url, false); + if ((globalCustomerId == null || globalCustomerId.isEmpty()) || ((serviceType == null) || (serviceType.isEmpty())) ){ + aaiResponse = new AaiResponse<>(null, "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}", HttpStatus.SC_INTERNAL_SERVER_ERROR); + return aaiResponse; + } + + String url = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + serviceType; + + Response resp = doAaiGet(url, false); String responseAsString = parseForTenantsByServiceSubscription(resp.readEntity(String.class)); if (responseAsString.equals("")){ - AaiResponse aaiResponse = new AaiResponse<>(null, String.format("{\"statusText\":\" A&AI has no LCP Region & Tenants associated to subscriber '%s' and service type '%s'\"}", globalCustomerId, serviceType), HttpStatus.SC_INTERNAL_SERVER_ERROR); - return aaiResponse; + return new AaiResponse<>(null, String.format("{\"statusText\":\" A&AI has no LCP Region & Tenants associated to subscriber '%s' and service type '%s'\"}", globalCustomerId, serviceType), HttpStatus.SC_INTERNAL_SERVER_ERROR); } else { - AaiResponse<GetTenantsResponse[]> getTenantsResponse = proccessAaiResponse(resp, GetTenantsResponse[].class, responseAsString); - return getTenantsResponse; + return processAaiResponse(resp, GetTenantsResponse[].class, responseAsString); } - } @Override public AaiResponse getNodeTemplateInstances(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion) { - String certiPath = getCertificatesFile().getAbsolutePath(); - - String siQuery = "/business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + "&model-invariant-id=" + modelInvariantId; + String siQuery = BUSINESS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + MODEL_INVARIANT_ID + modelInvariantId; String vnfQuery = "query/queryvnfFromModelbyRegion?cloudRegionId=" + encodePathSegment(cloudRegion); String payload1 = "{\"start\":\"" + siQuery + "\",\"query\":\"" + vnfQuery + "\"}"; - Response resp1 = doAaiPut(certiPath, "query?format=simple", payload1, false); - AaiResponse aaiResponse1 = proccessAaiResponse(resp1, AaiGetVnfResponse.class, null); + Response resp1 = doAaiPut(QUERY_FORMAT_SIMPLE, payload1, false); + AaiResponse aaiResponse1 = processAaiResponse(resp1, AaiGetVnfResponse.class, null); logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse1); return aaiResponse1; } - private AaiResponse proccessAaiResponse(Response resp, Class classType, String responseBody) { - AaiResponse subscriberDataResponse = null; + @Override + public AaiResponse<JsonNode> getCloudRegionAndSourceByPortMirroringConfigurationId(String configurationId) { + final String start = "[\"network/configurations/configuration/" + configurationId + "\"]"; + final String query = "\"query/cloud-region-and-source-FromConfiguration\""; + String payload = "{\"start\":" + start + ",\"query\":" + query + "}"; + + Response response = doAaiPut("query?format=simple&nodesOnly=true", payload, false); + AaiResponse<JsonNode> aaiResponse = processAaiResponse(response, JsonNode.class, null); + + logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse); + return aaiResponse; + } + + private <T> AaiResponseWithRequestInfo<T> processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class<? extends T> classType, boolean propagateExceptions) { + String responseBody = null; + Integer responseHttpCode = null; + try { + Response response = responseWithRequestInfo.getResponse(); + responseHttpCode = (response != null) ? response.getStatus() : null; + responseBody = (response != null) ? response.readEntity(String.class) : null; + AaiResponse<T> processedAaiResponse = processAaiResponse(response, classType, responseBody, VidObjectMapperType.CODEHAUS, propagateExceptions); + return new AaiResponseWithRequestInfo<>(responseWithRequestInfo.getRequestHttpMethod(), responseWithRequestInfo.getRequestUrl(), processedAaiResponse, + responseBody); + } catch (Exception e) { + throw new ExceptionWithRequestInfo(responseWithRequestInfo.getRequestHttpMethod(), + responseWithRequestInfo.getRequestUrl(), responseBody, responseHttpCode, e); + } + } + + private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody) { + return processAaiResponse(resp, classType, responseBody, VidObjectMapperType.CODEHAUS); + } + + private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody, VidObjectMapperType omType) { + return processAaiResponse(resp, classType, responseBody, omType, false); + } + + private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) { + AaiResponse subscriberDataResponse; if (resp == null) { subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI"); @@ -305,54 +414,81 @@ public class AaiClient implements AaiClientInterface { logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString()); if (resp.getStatus() != HttpStatus.SC_OK) { logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI"); - subscriberDataResponse = new AaiResponse<>(null, resp.readEntity(String.class), resp.getStatus()); + String rawData = resp.readEntity(String.class); + subscriberDataResponse = new AaiResponse<>(null, rawData, resp.getStatus()); } else { - String finalResponse = null; - try { - if (responseBody != null) { - finalResponse = responseBody; - } else { - finalResponse = resp.readEntity(String.class); - } + subscriberDataResponse = processOkResponse(resp, classType, responseBody, omType, propagateExceptions); + } + } + return subscriberDataResponse; + } - subscriberDataResponse = new AaiResponse<>((new ObjectMapper().readValue(finalResponse, classType)), null, HttpStatus.SC_OK); + private AaiResponse processOkResponse(Response resp, Class classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) { + AaiResponse subscriberDataResponse; + String finalResponse = null; + try { + if (responseBody != null) { + finalResponse = responseBody; + } else { + finalResponse = resp.readEntity(String.class); + } - } catch(Exception e){ - subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR); - logger.error("Failed to parse aai response: \"{}\" to class {}", finalResponse, classType, e); - } + if(omType == VidObjectMapperType.CODEHAUS) + subscriberDataResponse = parseCodeHausObject(classType, finalResponse); + else + subscriberDataResponse = parseFasterXmlObject(classType, finalResponse); + + } catch(Exception e){ + if (propagateExceptions) { + throw new GenericUncheckedException(e); + } else { + subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR); + logger.error("Failed to parse aai response: \"{}\" to class {}", finalResponse, classType, e); } } return subscriberDataResponse; } - private File getCertificatesFile() { - if (servletContext != null) - return new File(servletContext.getRealPath("/WEB-INF/cert/")); - return null; + private AaiResponse parseFasterXmlObject(Class classType, String finalResponse) throws IOException { + com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); + return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK); + } + + private AaiResponse parseCodeHausObject(Class classType, String finalResponse) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK); } - @SuppressWarnings("all") - public Response doAaiGet(String certiPath, String uri, boolean xml) { + public Response doAaiGet(String uri, boolean xml) { + return doAaiGet(uri, xml, false).getResponse(); + } + + + public ResponseWithRequestInfo doAaiGet(String uri, boolean xml, boolean propagateExceptions) { String methodName = "doAaiGet"; String transId = UUID.randomUUID().toString(); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - Response resp = null; + ResponseWithRequestInfo resp; try { + resp = restController.RestGet(fromAppId, transId, uri, xml, propagateExceptions); - AAIRestInterface restContrller = new AAIRestInterface(certiPath); - resp = restContrller.RestGet(fromAppId, transId, uri, xml); - - } catch (WebApplicationException e) { - final String message = ((BadRequestException) e).getResponse().readEntity(String.class); - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); } catch (Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - } + if (propagateExceptions) { + throw (e instanceof RuntimeException) ? (RuntimeException)e : new GenericUncheckedException(e); + } else { + final Exception actual = + e instanceof ExceptionWithRequestInfo ? (Exception) e.getCause() : e; + + final String message = + actual instanceof WebApplicationException ? ((WebApplicationException) actual).getResponse().readEntity(String.class) : e.toString(); + //ToDo: change parameter of requestUrl to real url from RestGet function + resp = new ResponseWithRequestInfo(null, null, org.springframework.http.HttpMethod.GET); + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); + } + } return resp; } @@ -366,13 +502,12 @@ public class AaiClient implements AaiClientInterface { return parseServiceSubscriptionObjectForTenants(jsonObject); } catch (Exception ex) { - + logger.debug(EELFLoggerDelegate.debugLogger, "parseForTenantsByServiceSubscription error while parsing tenants by service subscription", ex); } - return tenantList; } - protected Response doAaiPut(String certiPath, String uri, String payload, boolean xml) { + protected Response doAaiPut(String uri, String payload, boolean xml) { String methodName = "doAaiPut"; String transId = UUID.randomUUID().toString(); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -380,95 +515,31 @@ public class AaiClient implements AaiClientInterface { Response resp = null; try { - AAIRestInterface restContrller = new AAIRestInterface(certiPath); - resp = restContrller.RestPut(fromAppId, transId, uri, payload, xml); + resp = restController.RestPut(fromAppId, uri, payload, xml); } catch (Exception e) { logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); } - return resp; } - public static String parseServiceSubscriptionObjectForTenants(JSONObject jsonObject) { - + private String parseServiceSubscriptionObjectForTenants(JSONObject jsonObject) { JSONArray tenantArray = new JSONArray(); boolean bconvert = false; - try { JSONObject relationShipListsObj = (JSONObject) jsonObject.get("relationship-list"); if (relationShipListsObj != null) { JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship"); - if (rShipArray != null) { - Iterator i1 = rShipArray.iterator(); - - while (i1.hasNext()) { - - JSONObject inner1Obj = (JSONObject) i1.next(); - - if (inner1Obj == null) - continue; - - String relatedTo = checkForNull((String) inner1Obj.get("related-to")); - if (relatedTo.equalsIgnoreCase("tenant")) { - JSONObject tenantNewObj = new JSONObject(); - - String relatedLink = checkForNull((String) inner1Obj.get("related-link")); - tenantNewObj.put("link", relatedLink); - - JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data"); - if (rDataArray != null) { - Iterator i2 = rDataArray.iterator(); - - while (i2.hasNext()) { - JSONObject inner2Obj = (JSONObject) i2.next(); - - if (inner2Obj == null) - continue; - - String rShipKey = checkForNull((String) inner2Obj.get("relationship-key")); - String rShipVal = checkForNull((String) inner2Obj.get("relationship-value")); - if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) { - tenantNewObj.put("cloudOwner", rShipVal); - } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) { - tenantNewObj.put("cloudRegionID", rShipVal); - } - - if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) { - tenantNewObj.put("tenantID", rShipVal); - } - } - } - - JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property"); - if (relatedTPropArray != null) { - Iterator i3 = relatedTPropArray.iterator(); - - while (i3.hasNext()) { - JSONObject inner3Obj = (JSONObject) i3.next(); - - if (inner3Obj == null) - continue; - - String propKey = checkForNull((String) inner3Obj.get("property-key")); - String propVal = checkForNull((String) inner3Obj.get("property-value")); - if (propKey.equalsIgnoreCase("tenant.tenant-name")) { - tenantNewObj.put("tenantName", propVal); - } - } - } - bconvert = true; - tenantArray.add(tenantNewObj); - } + for (Object innerObj : defaultIfNull(rShipArray, emptyList())) { + if (innerObj != null) { + bconvert = parseTenant(tenantArray, bconvert, (JSONObject) innerObj); } - } } } catch (NullPointerException ex) { - - + logger.debug(EELFLoggerDelegate.debugLogger, "parseServiceSubscriptionObjectForTenants. error while parsing service subscription object for tenants", ex); } if (bconvert) @@ -478,12 +549,99 @@ public class AaiClient implements AaiClientInterface { } + private static boolean parseTenant(JSONArray tenantArray, boolean bconvert, JSONObject inner1Obj) { + String relatedTo = checkForNull((String) inner1Obj.get("related-to")); + if (relatedTo.equalsIgnoreCase("tenant")) { + JSONObject tenantNewObj = new JSONObject(); + + String relatedLink = checkForNull((String) inner1Obj.get("related-link")); + tenantNewObj.put("link", relatedLink); + + JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data"); + for (Object innerObj : defaultIfNull(rDataArray, emptyList())) { + parseRelationShip(tenantNewObj, (JSONObject) innerObj); + } + + JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property"); + for (Object innerObj : defaultIfNull(relatedTPropArray, emptyList())) { + parseRelatedTProp(tenantNewObj, (JSONObject) innerObj); + } + bconvert = true; + tenantArray.add(tenantNewObj); + } + return bconvert; + } + + private static void parseRelatedTProp(JSONObject tenantNewObj, JSONObject innerObj) { + if (innerObj == null) + return; + + String propKey = checkForNull((String) innerObj.get("property-key")); + String propVal = checkForNull((String) innerObj.get("property-value")); + if (propKey.equalsIgnoreCase("tenant.tenant-name")) { + tenantNewObj.put("tenantName", propVal); + } + } + + private static void parseRelationShip(JSONObject tenantNewObj, JSONObject inner2Obj) { + if (inner2Obj == null) + return; + + String rShipKey = checkForNull((String) inner2Obj.get("relationship-key")); + String rShipVal = checkForNull((String) inner2Obj.get("relationship-value")); + if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) { + tenantNewObj.put("cloudOwner", rShipVal); + } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) { + tenantNewObj.put("cloudRegionID", rShipVal); + } + + if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) { + tenantNewObj.put("tenantID", rShipVal); + } + } + private static String encodePathSegment(String segmentToEncode) { try { return UriUtils.encodePathSegment(segmentToEncode, "UTF-8"); } catch (UnsupportedEncodingException e) { - throw new RuntimeException("URI encoding failed unexpectedly", e); + throw new GenericUncheckedException("URI encoding failed unexpectedly", e); } } + @Override + public ExternalComponentStatus probeAaiGetAllSubscribers(){ + long startTime = System.currentTimeMillis(); + try { + AaiResponseWithRequestInfo<SubscriberList> responseWithRequestInfo = getAllSubscribers(true); + AaiResponse<SubscriberList> aaiResponse = responseWithRequestInfo.getAaiResponse(); + long duration = System.currentTimeMillis() - startTime; + + SubscriberList subscribersList = (aaiResponse != null) ? aaiResponse.getT() : null; + boolean isAvailable = subscribersList != null && subscribersList.customer != null && !subscribersList.customer.isEmpty(); + + HttpRequestMetadata metadata = new HttpRequestMetadata( + responseWithRequestInfo.getHttpMethod(), + (aaiResponse != null) ? aaiResponse.getHttpCode() : 0, + responseWithRequestInfo.getRequestedUrl(), + StringUtils.substring(responseWithRequestInfo.getRawData(), 0, 500), + isAvailable ? "OK" : "No subscriber received", + duration + ); + return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, isAvailable, metadata); + + } catch (ExceptionWithRequestInfo e) { + long duration = System.currentTimeMillis() - startTime; + return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false, + new HttpRequestMetadata( + e.getHttpMethod(), + defaultIfNull(e.getHttpCode(), 0), + e.getRequestedUrl(), + e.getRawData(), + Logging.exceptionToDescription(e.getCause()), duration)); + } catch (Exception e) { + long duration = System.currentTimeMillis() - startTime; + return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false, + new ErrorMetadata(Logging.exceptionToDescription(e), duration)); + } + } }
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiClientInterface.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiClientInterface.java index 5095f48b..901591a8 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/AaiClientInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiClientInterface.java @@ -1,16 +1,16 @@ package org.onap.vid.aai; -import org.codehaus.jackson.JsonParseException; -import org.codehaus.jackson.map.JsonMappingException; -import org.onap.vid.aai.model.AaiGetPnfs.Pnf; +import org.codehaus.jackson.JsonNode; import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList; -import org.onap.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone; +import org.onap.vid.aai.model.AaiGetPnfs.Pnf; import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; +import org.onap.vid.aai.model.AaiNodeQueryResponse; +import org.onap.vid.aai.model.PortDetailsTranslator; +import org.onap.vid.aai.model.ResourceType; import org.onap.vid.model.SubscriberList; +import org.onap.vid.model.probes.ExternalComponentStatus; import javax.ws.rs.core.Response; - -import java.io.IOException; import java.util.List; /** @@ -18,6 +18,8 @@ import java.util.List; */ public interface AaiClientInterface { + AaiResponse<AaiNodeQueryResponse> searchNodeTypeByName(String name, ResourceType type); + AaiResponse<SubscriberList> getAllSubscribers(); AaiResponse getSubscriberData(String subscriberId); @@ -36,6 +38,10 @@ public interface AaiClientInterface { AaiResponse getVNFData(); + AaiResponse getNetworkCollectionDetails(String serviceInstanceId); + + AaiResponse getInstanceGroupsByCloudRegion(String cloudOwner, String cloudRegionId, String networkFunction); + Response getVNFData(String globalSubscriberId, String serviceType); AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId); @@ -55,4 +61,12 @@ public interface AaiClientInterface { AaiResponse getServiceInstance(String globalCustomerId, String serviceType, String serviceInstanceId); AaiResponse getLogicalLink(String link); + + AaiResponse<JsonNode> getCloudRegionAndSourceByPortMirroringConfigurationId(String configurationId); + + List<PortDetailsTranslator.PortDetails> getPortMirroringSourcePorts(String configurationID); + + AaiResponse getInstanceGroupsByVnfInstanceId(String vnfInstanceId); + + ExternalComponentStatus probeAaiGetAllSubscribers(); } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiGetVnfResponse.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiGetVnfResponse.java index 14e8e5dc..08585206 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/AaiGetVnfResponse.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiGetVnfResponse.java @@ -17,7 +17,7 @@ public class AaiGetVnfResponse { @JsonProperty("results") public List<VnfResult> results = null; @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + private Map<String, Object> additionalProperties = new HashMap<>(); @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseTranslator.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseTranslator.java new file mode 100644 index 00000000..6f503799 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseTranslator.java @@ -0,0 +1,103 @@ +package org.onap.vid.aai; + +import org.apache.commons.lang3.StringUtils; +import org.codehaus.jackson.JsonNode; +import org.springframework.stereotype.Component; + +import java.util.Optional; + +@Component +public class AaiResponseTranslator { + + public PortMirroringConfigData extractPortMirroringConfigData(AaiResponse<JsonNode> aaiResponse) { + return extractErrorResponseIfHttpError(aaiResponse).orElseGet(() -> extractPortMirroringConfigData(aaiResponse.getT())); + } + + public PortMirroringConfigData extractPortMirroringConfigData(JsonNode cloudRegionAndSourceFromConfigurationResponse) { + final JsonNode payload = cloudRegionAndSourceFromConfigurationResponse; + if (payload == null) { + return new PortMirroringConfigDataError("Response payload is null", null); + } + + final JsonNode results = payload.path("results"); + if (results.isMissingNode()) { + return new PortMirroringConfigDataError("Root node 'results' is missing", payload.toString()); + } + + for (JsonNode resultNode : results) { + final JsonNode nodeType = resultNode.path("node-type"); + if (nodeType.isTextual() && "cloud-region".equals(nodeType.getTextValue())) { + return getPortMirroringConfigData(payload, resultNode); + } + } + return new PortMirroringConfigDataError("Root node 'results' has no node where 'node-TYPE' is 'cloud-region'", payload.toString()); + } + + private PortMirroringConfigData getPortMirroringConfigData(JsonNode payload, JsonNode resultNode) { + final JsonNode properties = resultNode.path("properties"); + if (properties.isMissingNode()) { + final String message = "The node-type 'cloud-region' does not contain a 'properties' node"; + return new PortMirroringConfigDataError(message, payload.toString()); + } + + final JsonNode cloudRegionIdNode = properties.path("cloud-region-id"); + if (cloudRegionIdNode.isMissingNode()) { + return new PortMirroringConfigDataError("The node-type 'cloud-region' does not contain the property 'cloud-region-id'", payload.toString()); + } + if (!cloudRegionIdNode.isTextual()) { + return new PortMirroringConfigDataError("The node-type 'cloud-region' contains a non-textual value for the property 'cloud-region-id'", payload.toString()); + } + + final String cloudRegionId = cloudRegionIdNode.asText(); + if (StringUtils.isBlank(cloudRegionId)) { + return new PortMirroringConfigDataError("Node 'properties.cloud-region-id' of node-type 'cloud-region' is blank", payload.toString()); + } + + return new PortMirroringConfigDataOk(cloudRegionId); + } + + private Optional<PortMirroringConfigData> extractErrorResponseIfHttpError(AaiResponse aaiResponse) { + if (aaiResponse.getHttpCode() != org.springframework.http.HttpStatus.OK.value()) { + final String errorMessage = aaiResponse.getErrorMessage(); + return Optional.of(new PortMirroringConfigDataError( + "Got " + aaiResponse.getHttpCode() + " from aai", + errorMessage != null ? errorMessage.toString() : null) + ); + } else { + return Optional.empty(); + } + } + + public abstract static class PortMirroringConfigData { + } + + public static class PortMirroringConfigDataOk extends PortMirroringConfigData { + private final String cloudRegionId; + + public PortMirroringConfigDataOk(String cloudRegionId) { + this.cloudRegionId = cloudRegionId; + } + + public String getCloudRegionId() { + return cloudRegionId; + } + } + + public static class PortMirroringConfigDataError extends PortMirroringConfigData { + private final String errorDescription; + private final String rawAaiResponse; + + public PortMirroringConfigDataError(String errorDescription, String rawAaiResponse) { + this.errorDescription = errorDescription; + this.rawAaiResponse = rawAaiResponse; + } + + public String getErrorDescription() { + return errorDescription; + } + + public String getRawAaiResponse() { + return rawAaiResponse; + } + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseWithRequestInfo.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseWithRequestInfo.java new file mode 100644 index 00000000..cd1f9044 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseWithRequestInfo.java @@ -0,0 +1,44 @@ +package org.onap.vid.aai; + + +import org.springframework.http.HttpMethod; + +import java.io.Serializable; + +public class AaiResponseWithRequestInfo<T> implements Serializable { + private AaiResponse<T> aaiResponse; + private String requestedUrl; + private String rawData; + private HttpMethod httpMethod; + + public AaiResponseWithRequestInfo(HttpMethod httpMethod, String requestedUrl, AaiResponse<T> aaiResponse, String rawData) { + this.aaiResponse = aaiResponse; + this.requestedUrl = requestedUrl; + this.rawData = rawData; + this.httpMethod = httpMethod; + } + + public void setRequestedUrl(String requestedUrl) { + this.requestedUrl = requestedUrl; + } + + public void setHttpMethod(HttpMethod httpMethod) { + this.httpMethod = httpMethod; + } + + public AaiResponse<T> getAaiResponse() { + return aaiResponse; + } + + public String getRequestedUrl() { + return requestedUrl; + } + + public String getRawData() { + return rawData; + } + + public HttpMethod getHttpMethod() { + return httpMethod; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/ExceptionWithRequestInfo.java b/vid-app-common/src/main/java/org/onap/vid/aai/ExceptionWithRequestInfo.java new file mode 100644 index 00000000..dcca3ec4 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/ExceptionWithRequestInfo.java @@ -0,0 +1,54 @@ +package org.onap.vid.aai; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.http.HttpMethod; + +import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; + +public class ExceptionWithRequestInfo extends RuntimeException { + + private final HttpMethod httpMethod; + private final String requestedUrl; + private final Integer httpCode; + private final String rawData; + + public ExceptionWithRequestInfo(HttpMethod httpMethod, String requestedUrl, String rawData, Integer httpCode, Throwable cause) { + super(toMessage(httpMethod, requestedUrl, cause), cause); + this.httpMethod = httpMethod; + this.requestedUrl = requestedUrl; + this.rawData = rawData; + this.httpCode = httpCode; + } + + public ExceptionWithRequestInfo(HttpMethod httpMethod, String requestedUrl, Throwable cause) { + this(httpMethod, requestedUrl, null, null, cause); + } + + public String getRequestedUrl() { + return requestedUrl; + } + + public String getRawData() { + return rawData; + } + + public HttpMethod getHttpMethod() { + return httpMethod; + } + + public Integer getHttpCode() { + return httpCode; + } + + private static String toMessage(HttpMethod httpMethod, String requestedUrl, Throwable cause) { + if (StringUtils.isEmpty(requestedUrl)) { + return cause.toString(); + } else { + return "" + + "Exception while handling " + + defaultIfNull(httpMethod, "request").toString() + + " " + requestedUrl + + ": " + cause.toString(); + } + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/PombaClientImpl.java b/vid-app-common/src/main/java/org/onap/vid/aai/PombaClientImpl.java new file mode 100644 index 00000000..28b6f542 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/PombaClientImpl.java @@ -0,0 +1,50 @@ +package org.onap.vid.aai; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.onap.vid.model.PombaInstance.PombaRequest; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.ServletContext; +import javax.ws.rs.core.Response; +import java.io.File; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class PombaClientImpl implements PombaClientInterface { + + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + protected String fromAppId = "VidAaiController"; + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class); + + @Autowired + ServletContext servletContext; + + @Autowired + PombaRestInterface pombaRestInterface; + + + @Override + public void verify(PombaRequest request) { + String methodName = "doAaiPost"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + String uri = SystemProperties.getProperty("pomba.server.url"); + + + try { + Response response = pombaRestInterface.RestPost(fromAppId, uri, new ObjectMapper().writeValueAsString(request)); + } catch (Exception e) { + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + } + } + + + private File getCertificatesFile() { + if (servletContext != null) + return new File(servletContext.getRealPath("/WEB-INF/cert/")); + return null; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/PombaClientInterface.java b/vid-app-common/src/main/java/org/onap/vid/aai/PombaClientInterface.java new file mode 100644 index 00000000..328f31ac --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/PombaClientInterface.java @@ -0,0 +1,7 @@ +package org.onap.vid.aai; + +import org.onap.vid.model.PombaInstance.PombaRequest; + +public interface PombaClientInterface { + void verify(PombaRequest request); +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/PombaRestInterface.java b/vid-app-common/src/main/java/org/onap/vid/aai/PombaRestInterface.java new file mode 100644 index 00000000..73ebf69d --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/PombaRestInterface.java @@ -0,0 +1,73 @@ +package org.onap.vid.aai; + +import org.onap.vid.aai.util.AAIRestInterface; +import org.onap.vid.aai.util.HttpClientMode; +import org.onap.vid.aai.util.HttpsAuthClient; +import org.onap.vid.utils.Logging; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.http.HttpMethod; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Date; +import java.util.UUID; + +import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; + +public class PombaRestInterface extends AAIRestInterface { + + public PombaRestInterface (HttpsAuthClient httpsAuthClientFactory) { + super(httpsAuthClientFactory); + } + + private Client client = null; + + private void initRestClient() + { + if (client == null) { + try { + client = httpsAuthClientFactory.getClient(HttpClientMode.UNSECURE); + } + catch (Exception e) { + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== Exception in REST call to DB in initRestClient" + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== Exception in REST call to DB : " + e.toString()); + } + } + } + + + public Response RestPost(String fromAppId, String url, String payload) { + String methodName = "RestPost"; + String transId = UUID.randomUUID().toString(); + try { + String responseType = MediaType.APPLICATION_JSON; + initRestClient(); + + Logging.logRequest(outgoingRequestsLogger, HttpMethod.POST, url, payload); + final Response cres = client.target(url) + .request() + .accept(responseType) + .header(TRANSACTION_ID_HEADER, transId) + .header(FROM_APP_ID_HEADER, fromAppId) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) + .post(Entity.entity(payload, MediaType.APPLICATION_JSON)); + Logging.logResponse(outgoingRequestsLogger, HttpMethod.POST, url, cres); + + if (cres.getStatus() == 200 && cres.getStatus() <= 299) { + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " with status="+cres.getStatus()+ URL_DECLARATION +url); + } + return cres; + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION +url+ ", Exception: " + e.toString()); + } + return null; + } + +} + + diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/ResponseWithRequestInfo.java b/vid-app-common/src/main/java/org/onap/vid/aai/ResponseWithRequestInfo.java new file mode 100644 index 00000000..eb57b34f --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/ResponseWithRequestInfo.java @@ -0,0 +1,29 @@ +package org.onap.vid.aai; + +import org.springframework.http.HttpMethod; + +import javax.ws.rs.core.Response; + +public class ResponseWithRequestInfo { + private String requestUrl; + private HttpMethod requestHttpMethod; + private Response response; + + public ResponseWithRequestInfo(Response response, String requestUrl, HttpMethod requestHttpMethod) { + this.response = response; + this.requestUrl = requestUrl; + this.requestHttpMethod = requestHttpMethod; + } + + public String getRequestUrl() { + return requestUrl; + } + + public HttpMethod getRequestHttpMethod() { + return requestHttpMethod; + } + + public Response getResponse() { + return response; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/exceptions/InvalidAAIResponseException.java b/vid-app-common/src/main/java/org/onap/vid/aai/exceptions/InvalidAAIResponseException.java index e6296488..f80cae50 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/exceptions/InvalidAAIResponseException.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/exceptions/InvalidAAIResponseException.java @@ -1,7 +1,13 @@ package org.onap.vid.aai.exceptions; +import org.onap.vid.aai.AaiResponse; +import org.onap.vid.exceptions.GenericUncheckedException; + /** * Created by Oren on 7/4/17. */ -public class InvalidAAIResponseException extends Exception { +public class InvalidAAIResponseException extends GenericUncheckedException { + public InvalidAAIResponseException(AaiResponse aaiResponse) { + super(String.format("errorCode: %d, raw: %s", aaiResponse.getHttpCode(), aaiResponse.getErrorMessage())); + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetInstanceGroupsByCloudRegion.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetInstanceGroupsByCloudRegion.java new file mode 100644 index 00000000..a1fec6b8 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetInstanceGroupsByCloudRegion.java @@ -0,0 +1,20 @@ +package org.onap.vid.aai.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class AaiGetInstanceGroupsByCloudRegion { + + private final List<InstanceGroupWrapper> results; + + public AaiGetInstanceGroupsByCloudRegion(@JsonProperty("results") List<InstanceGroupWrapper> results) { + this.results = results; + } + + public List<InstanceGroupWrapper> getResults() { + return results; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/AaiGetNetworkCollectionDetails.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/AaiGetNetworkCollectionDetails.java new file mode 100644 index 00000000..a1047862 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/AaiGetNetworkCollectionDetails.java @@ -0,0 +1,23 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class AaiGetNetworkCollectionDetails { + + public AaiGetNetworkCollectionDetails(){ + results = new Result(); + } + @JsonProperty("results") + private Result results = null; + + @JsonProperty("results") + public Result getResults() { + return results; + } + + @JsonProperty("results") + public void setResults(Result results) { + this.results = results; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/AaiGetNetworkCollectionDetailsHelper.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/AaiGetNetworkCollectionDetailsHelper.java new file mode 100644 index 00000000..2d3cfb91 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/AaiGetNetworkCollectionDetailsHelper.java @@ -0,0 +1,38 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AaiGetNetworkCollectionDetailsHelper { + @JsonProperty("results") + private List<Object> results = null; + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + + @JsonProperty("results") + public List<Object> getResults() { + return results; + } + + @JsonProperty("results") + public void setResults(List<Object> results) { + this.results = results; + } + + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/AaiGetRelatedInstanceGroupsByVnfId.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/AaiGetRelatedInstanceGroupsByVnfId.java new file mode 100644 index 00000000..d5556511 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/AaiGetRelatedInstanceGroupsByVnfId.java @@ -0,0 +1,181 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@JsonIgnoreProperties(ignoreUnknown = true) +public class AaiGetRelatedInstanceGroupsByVnfId { + + @JsonProperty("vnf-id") + private String vnfId; + @JsonProperty("vnf-name") + private String vnfName; + @JsonProperty("vnf-type") + private String vnfType; + @JsonProperty("prov-status") + private String provStatus; + @JsonProperty("operational-status") + private String operationalStatus; + @JsonProperty("equipment-role") + private String equipmentRole; + @JsonProperty("in-maint") + private Boolean inMaint; + @JsonProperty("is-closed-loop-disabled") + private Boolean isClosedLoopDisabled; + @JsonProperty("resource-version") + private String resourceVersion; + @JsonProperty("model-invariant-id") + private String modelInvariantId; + @JsonProperty("model-version-id") + private String modelVersionId; + @JsonProperty("model-customization-id") + private String modelCustomizationId; + @JsonProperty("selflink") + private String selflink; + @JsonProperty("relationship-list") + private RelationshipList relationshipList; + + + @JsonProperty("vnf-id") + public String getVnfId() { + return vnfId; + } + + @JsonProperty("vnf-id") + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + @JsonProperty("vnf-name") + public String getVnfName() { + return vnfName; + } + + @JsonProperty("vnf-name") + public void setVnfName(String vnfName) { + this.vnfName = vnfName; + } + + @JsonProperty("vnf-type") + public String getVnfType() { + return vnfType; + } + + @JsonProperty("vnf-type") + public void setVnfType(String vnfType) { + this.vnfType = vnfType; + } + + @JsonProperty("prov-status") + public String getProvStatus() { + return provStatus; + } + + @JsonProperty("prov-status") + public void setProvStatus(String provStatus) { + this.provStatus = provStatus; + } + + @JsonProperty("operational-status") + public String getOperationalStatus() { + return operationalStatus; + } + + @JsonProperty("operational-status") + public void setOperationalStatus(String operationalStatus) { + this.operationalStatus = operationalStatus; + } + + @JsonProperty("equipment-role") + public String getEquipmentRole() { + return equipmentRole; + } + + @JsonProperty("equipment-role") + public void setEquipmentRole(String equipmentRole) { + this.equipmentRole = equipmentRole; + } + + @JsonProperty("in-maint") + public Boolean getInMaint() { + return inMaint; + } + + @JsonProperty("in-maint") + public void setInMaint(Boolean inMaint) { + this.inMaint = inMaint; + } + + @JsonProperty("is-closed-loop-disabled") + public Boolean getIsClosedLoopDisabled() { + return isClosedLoopDisabled; + } + + @JsonProperty("is-closed-loop-disabled") + public void setIsClosedLoopDisabled(Boolean isClosedLoopDisabled) { + this.isClosedLoopDisabled = isClosedLoopDisabled; + } + + @JsonProperty("resource-version") + public String getResourceVersion() { + return resourceVersion; + } + + @JsonProperty("resource-version") + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + @JsonProperty("model-invariant-id") + public String getModelInvariantId() { + return modelInvariantId; + } + + @JsonProperty("model-invariant-id") + public void setModelInvariantId(String modelInvariantId) { + this.modelInvariantId = modelInvariantId; + } + + @JsonProperty("model-version-id") + public String getModelVersionId() { + return modelVersionId; + } + + @JsonProperty("model-version-id") + public void setModelVersionId(String modelVersionId) { + this.modelVersionId = modelVersionId; + } + + @JsonProperty("model-customization-id") + public String getModelCustomizationId() { + return modelCustomizationId; + } + + @JsonProperty("model-customization-id") + public void setModelCustomizationId(String modelCustomizationId) { + this.modelCustomizationId = modelCustomizationId; + } + + @JsonProperty("selflink") + public String getSelflink() { + return selflink; + } + + @JsonProperty("selflink") + public void setSelflink(String selflink) { + this.selflink = selflink; + } + + @JsonProperty("relationship-list") + public RelationshipList getRelationshipList() { + return relationshipList; + } + + @JsonProperty("relationship-list") + public void setRelationshipList(RelationshipList relationshipList) { + this.relationshipList = relationshipList; + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Collection.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Collection.java new file mode 100644 index 00000000..7badaa29 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Collection.java @@ -0,0 +1,130 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Collection { + @JsonProperty("collection-id") + private String collectionId; + @JsonProperty("model-invariant-id") + private String modelInvariantId; + @JsonProperty("model-version-id") + private String modelVersionId; + @JsonProperty("collection-name") + private String collectionName; + @JsonProperty("collection-type") + private String collectionType; + @JsonProperty("collection-role") + private String collectionRole; + @JsonProperty("collection-function") + private String collectionFunction; + @JsonProperty("collection-customization-id") + private String collectionCustomizationId; + @JsonProperty("relationship-list") + private RelationshipList relationshipList; + @JsonProperty("resource-version") + private String resourceVersion; + + @JsonProperty("collection-id") + public String getCollectionId() { + return collectionId; + } + + @JsonProperty("collection-id") + public void setCollectionId(String collectionId) { + this.collectionId = collectionId; + } + + @JsonProperty("model-invariant-id") + public String getModelInvariantId() { + return modelInvariantId; + } + + @JsonProperty("model-invariant-id") + public void setModelInvariantId(String modelInvariantId) { + this.modelInvariantId = modelInvariantId; + } + + @JsonProperty("model-version-id") + public String getModelVersionId() { + return modelVersionId; + } + + @JsonProperty("model-version-id") + public void setModelVersionId(String modelVersionId) { + this.modelVersionId = modelVersionId; + } + + @JsonProperty("collection-name") + public String getCollectionName() { + return collectionName; + } + + @JsonProperty("collection-name") + public void setCollectionName(String collectionName) { + this.collectionName = collectionName; + } + + @JsonProperty("collection-type") + public String getCollectionType() { + return collectionType; + } + + @JsonProperty("collection-type") + public void setCollectionType(String collectionType) { + this.collectionType = collectionType; + } + + @JsonProperty("collection-role") + public String getCollectionRole() { + return collectionRole; + } + + @JsonProperty("collection-role") + public void setCollectionRole(String collectionRole) { + this.collectionRole = collectionRole; + } + + @JsonProperty("collection-function") + public String getCollectionFunction() { + return collectionFunction; + } + + @JsonProperty("collection-function") + public void setCollectionFunction(String collectionFunction) { + this.collectionFunction = collectionFunction; + } + + @JsonProperty("collection-customization-id") + public String getCollectionCustomizationId() { + return collectionCustomizationId; + } + + @JsonProperty("collection-customization-id") + public void setCollectionCustomizationId(String collectionCustomizationId) { + this.collectionCustomizationId = collectionCustomizationId; + } + + @JsonProperty("relationship-list") + public RelationshipList getRelationshipList() { + return relationshipList; + } + + @JsonProperty("relationship-list") + public void setRelationshipList(RelationshipList relationshipList) { + this.relationshipList = relationshipList; + } + + @JsonProperty("resource-version") + public String getResourceVersion() { + return resourceVersion; + } + + @JsonProperty("resource-version") + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/InstanceGroup.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/InstanceGroup.java new file mode 100644 index 00000000..b540fa40 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/InstanceGroup.java @@ -0,0 +1,105 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class InstanceGroup { + @JsonProperty("instance-group-role") + private String instanceGroupRole; + @JsonProperty("model-invariant-id") + private String modelInvariantId; + @JsonProperty("model-version-id") + private String modelVersionId; + private String id; + private String description; + @JsonProperty("instance-group-type") + private String instanceGroupType; + @JsonProperty("resource-version") + private String resourceVersion; + @JsonProperty("instance-group-name") + private String instanceGroupName; + @JsonProperty("instance-group-function") + private String instanceGroupFunction; + @JsonProperty("relationship-list") + private RelationshipList relationshipList; + + public InstanceGroup(){ + super(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public InstanceGroup( + @JsonProperty("instance-group-role") + String instanceGroupRole, + @JsonProperty("model-invariant-id") + String modelInvariantId, + @JsonProperty("model-version-id") + String modelVersionId, + @JsonProperty(value = "id", required = true) + String id, + @JsonProperty(value = "description", required = true) + String description, + @JsonProperty(value = "instance-group-type", required = true) + String instanceGroupType, + @JsonProperty("resource-version") + String resourceVersion, + @JsonProperty("instance-group-name") + String instanceGroupName, + @JsonProperty("instance-group-function") + String instanceGroupFunction, + @JsonProperty("relationship-list") + RelationshipList relationshipList) { + this.instanceGroupRole = instanceGroupRole; + this.modelInvariantId = modelInvariantId; + this.modelVersionId = modelVersionId; + this.id = id; + this.description = description; + this.instanceGroupType = instanceGroupType; + this.resourceVersion = resourceVersion; + this.instanceGroupName = instanceGroupName; + this.instanceGroupFunction = instanceGroupFunction; + this.relationshipList = relationshipList; + } + + public String getInstanceGroupRole() { + return instanceGroupRole; + } + + public String getModelInvariantId() { + return modelInvariantId; + } + + public String getModelVersionId() { + return modelVersionId; + } + + public String getId() { + return id; + } + + public String getDescription() { + return description; + } + + public String getInstanceGroupType() { + return instanceGroupType; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public String getInstanceGroupName() { + return instanceGroupName; + } + + public String getInstanceGroupFunction() { + return instanceGroupFunction; + } + + public RelationshipList getRelationshipList() { + return relationshipList; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Network.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Network.java new file mode 100644 index 00000000..29450a8f --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Network.java @@ -0,0 +1,142 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Network { + @JsonProperty("network-id") + private String networkId; + @JsonProperty("network-name") + private String networkName; + @JsonProperty("network-type") + private String networkType; + @JsonProperty("network-role") + private String networkRole; + @JsonProperty("network-technology") + private String networkTechnology; + @JsonProperty("is-bound-to-vpn") + private Boolean isBoundToVpn; + @JsonProperty("resource-version") + private String resourceVersion; + @JsonProperty("is-provider-network") + private Boolean isProviderNetwork; + @JsonProperty("is-shared-network") + private Boolean isSharedNetwork; + @JsonProperty("is-external-network") + private Boolean isExternalNetwork; + @JsonProperty("relationship-list") + private RelationshipList relationshipList; + + + @JsonProperty("network-id") + public String getNetworkId() { + return networkId; + } + + @JsonProperty("network-id") + public void setNetworkId(String networkId) { + this.networkId = networkId; + } + + @JsonProperty("network-name") + public String getNetworkName() { + return networkName; + } + + @JsonProperty("network-name") + public void setNetworkName(String networkName) { + this.networkName = networkName; + } + + @JsonProperty("network-type") + public String getNetworkType() { + return networkType; + } + + @JsonProperty("network-type") + public void setNetworkType(String networkType) { + this.networkType = networkType; + } + + @JsonProperty("network-role") + public String getNetworkRole() { + return networkRole; + } + + @JsonProperty("network-role") + public void setNetworkRole(String networkRole) { + this.networkRole = networkRole; + } + + @JsonProperty("network-technology") + public String getNetworkTechnology() { + return networkTechnology; + } + + @JsonProperty("network-technology") + public void setNetworkTechnology(String networkTechnology) { + this.networkTechnology = networkTechnology; + } + + @JsonProperty("is-bound-to-vpn") + public Boolean getIsBoundToVpn() { + return isBoundToVpn; + } + + @JsonProperty("is-bound-to-vpn") + public void setIsBoundToVpn(Boolean isBoundToVpn) { + this.isBoundToVpn = isBoundToVpn; + } + + @JsonProperty("resource-version") + public String getResourceVersion() { + return resourceVersion; + } + + @JsonProperty("resource-version") + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + @JsonProperty("is-provider-network") + public Boolean getIsProviderNetwork() { + return isProviderNetwork; + } + + @JsonProperty("is-provider-network") + public void setIsProviderNetwork(Boolean isProviderNetwork) { + this.isProviderNetwork = isProviderNetwork; + } + + @JsonProperty("is-shared-network") + public Boolean getIsSharedNetwork() { + return isSharedNetwork; + } + + @JsonProperty("is-shared-network") + public void setIsSharedNetwork(Boolean isSharedNetwork) { + this.isSharedNetwork = isSharedNetwork; + } + + @JsonProperty("is-external-network") + public Boolean getIsExternalNetwork() { + return isExternalNetwork; + } + + @JsonProperty("is-external-network") + public void setIsExternalNetwork(Boolean isExternalNetwork) { + this.isExternalNetwork = isExternalNetwork; + } + + @JsonProperty("relationship-list") + public RelationshipList getRelationshipList() { + return relationshipList; + } + + @JsonProperty("relationship-list") + public void setRelationshipList(RelationshipList relationshipList) { + this.relationshipList = relationshipList; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/RelatedToProperty.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/RelatedToProperty.java new file mode 100644 index 00000000..1c10500a --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/RelatedToProperty.java @@ -0,0 +1,37 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class RelatedToProperty { + + public String getPropertyKey() { + return propertyKey; + } + + + public void setPropertyKey(String propertyKey) { + this.propertyKey = propertyKey; + } + + + public String getPropertyValue() { + return propertyValue; + } + + + public void setPropertyValue(String propertyValue) { + this.propertyValue = propertyValue; + } + + + @JsonProperty("property-key") + public String propertyKey; + + + @JsonProperty("property-value") + public String propertyValue; + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Relationship.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Relationship.java new file mode 100644 index 00000000..56c08ed0 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Relationship.java @@ -0,0 +1,67 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Relationship { + + @JsonProperty("related-to") + public String relatedTo; + + @JsonProperty("related-link") + public String relatedLink; + + @JsonProperty("relationship-label") + public String relationshipLabel; + + @JsonProperty("relationship-data") + public List<RelationshipData> relationshipData; + + @JsonProperty("related-to-property") + public List<RelatedToProperty> relatedToProperty; + + + public String getRelatedTo() { + return relatedTo; + } + + public void setRelatedTo(String relatedTo) { + this.relatedTo = relatedTo; + } + + public String getRelatedLink() { + return relatedLink; + } + + public void setRelatedLink(String relatedLink) { + this.relatedLink = relatedLink; + } + + public List<RelationshipData> getRelationDataList() { + return relationshipData; + } + + public void setRelationDataList(List<RelationshipData> relationDataList) { + this.relationshipData = relationDataList; + } + + public List<RelatedToProperty> getRelatedToPropertyList() { + return relatedToProperty; + } + + public void setRelatedToPropertyList(List<RelatedToProperty> relatedToPropertyList) { + this.relatedToProperty = relatedToPropertyList; + } + + public String getRelationshipLabel() { + return relationshipLabel; + } + + public void setRelationshipLabel(String relationshipLabel) { + this.relationshipLabel = relationshipLabel; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/RelationshipData.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/RelationshipData.java new file mode 100644 index 00000000..48cc000e --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/RelationshipData.java @@ -0,0 +1,29 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class RelationshipData { + @JsonProperty("relationship-key") + public String getRelationshipKey() { + return relationshipKey; + } + @JsonProperty("relationship-key") + public void setRelationshipKey(String relationshipKey) { + this.relationshipKey = relationshipKey; + } + @JsonProperty("relationship-value") + public String getRelationshipValue() { + return relationshipValue; + } + @JsonProperty("relationship-value") + public void setRelationshipValue(String relationshipValue) { + this.relationshipValue = relationshipValue; + } + + public String relationshipKey; + + public String relationshipValue; + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/RelationshipList.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/RelationshipList.java new file mode 100644 index 00000000..df1e03a0 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/RelationshipList.java @@ -0,0 +1,25 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class RelationshipList { + + @JsonProperty("relationship") + public List<Relationship> getRelationship() { + return relationship; + } + + @JsonProperty("relationship") + public void setRelationship(List<Relationship> relationship) { + this.relationship = relationship; + } + + public List<Relationship> relationship; + + + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Result.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Result.java new file mode 100644 index 00000000..776493a5 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Result.java @@ -0,0 +1,64 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.ArrayList; +import java.util.List; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Result { + + @JsonProperty("service-instance") + private ServiceInstance serviceInstance; + @JsonProperty("collection") + private Collection collection; + @JsonProperty("instance-group") + private InstanceGroup instanceGroup; + @JsonProperty("networks") + private List<Network> networks; + + public Result(){ + this.networks = new ArrayList<>(); + } + + + @JsonProperty("service-instance") + public ServiceInstance getServiceInstance() { + return serviceInstance; + } + + @JsonProperty("service-instance") + public void setServiceInstance(ServiceInstance serviceInstance) { + this.serviceInstance = serviceInstance; + } + + @JsonProperty("collection") + public Collection getCollection() { + return collection; + } + + @JsonProperty("collection") + public void setCollection(Collection collection) { + this.collection = collection; + } + + @JsonProperty("instance-group") + public InstanceGroup getInstanceGroup() { + return instanceGroup; + } + + @JsonProperty("instance-group") + public void setInstanceGroup(InstanceGroup instanceGroup) { + this.instanceGroup = instanceGroup; + } + + @JsonProperty("networks") + public List<Network> getNetworks() { return networks; } + + @JsonProperty("networks") + public void setNetworks(List<Network> networks) { this.networks = networks; } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/ServiceInstance.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/ServiceInstance.java new file mode 100644 index 00000000..c366402e --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/ServiceInstance.java @@ -0,0 +1,17 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceInstance { + + @JsonProperty("service-instance-id") + public String serviceInstanceId; + + @JsonProperty("resource-version") + public String resourceVersion; + + @JsonProperty("relationship-list") + public RelationshipList relationshipList; +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPortMirroringSourcePorts.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPortMirroringSourcePorts.java new file mode 100644 index 00000000..47a57daf --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPortMirroringSourcePorts.java @@ -0,0 +1,18 @@ +package org.onap.vid.aai.model; + +import org.codehaus.jackson.annotate.JsonProperty; + +import java.util.List; + +public class AaiGetPortMirroringSourcePorts { + + private final List<SimpleResult> results; + + public AaiGetPortMirroringSourcePorts(@JsonProperty("results") List<SimpleResult> results) { + this.results = results; + } + + public List<SimpleResult> getResults() { + return results; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiNodeQueryResponse.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiNodeQueryResponse.java new file mode 100644 index 00000000..18bf1619 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiNodeQueryResponse.java @@ -0,0 +1,26 @@ +package org.onap.vid.aai.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +public class AaiNodeQueryResponse { + + public static class ResultData { + + public final ResourceType resourceType; + public final String resourceLink; + + public ResultData(@JsonProperty("resource-type") ResourceType resourceType, + @JsonProperty("resource-link") String resourceLink) { + this.resourceType = resourceType; + this.resourceLink = resourceLink; + } + } + + public final List<ResultData> resultData; + + public AaiNodeQueryResponse(@JsonProperty("result-data") List<ResultData> resultData) { + this.resultData = resultData; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/InstanceGroupInfo.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/InstanceGroupInfo.java new file mode 100644 index 00000000..c2eb7094 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/InstanceGroupInfo.java @@ -0,0 +1,32 @@ +package org.onap.vid.aai.model; + +public class InstanceGroupInfo { + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + private String type; + private String name; + + public InstanceGroupInfo(String name){ + this.name = name; + this.type = "instance-group"; + } + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/InstanceGroupWrapper.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/InstanceGroupWrapper.java new file mode 100644 index 00000000..879fa63a --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/InstanceGroupWrapper.java @@ -0,0 +1,20 @@ +package org.onap.vid.aai.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.InstanceGroup; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class InstanceGroupWrapper { + + private InstanceGroup instanceGroup; + + @JsonProperty("instance-group") + public InstanceGroup getInstanceGroup() { + return instanceGroup; + } + @JsonProperty("instance-group") + public void setInstanceGroup(InstanceGroup instanceGroup) { + this.instanceGroup = instanceGroup; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/PortDetailsTranslator.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/PortDetailsTranslator.java new file mode 100644 index 00000000..f8980457 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/PortDetailsTranslator.java @@ -0,0 +1,138 @@ +package org.onap.vid.aai.model; + + +import com.google.common.collect.ImmutableList; +import org.onap.vid.aai.AaiResponse; +import org.onap.vid.properties.Features; +import org.togglz.core.manager.FeatureManager; + +import javax.inject.Inject; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +public class PortDetailsTranslator { + + @Inject + FeatureManager featureManager; + + public static class PortDetailsOk extends PortDetails { + + private final String interfaceId; + private final String interfaceName; + private final boolean isPortMirrored; + + public PortDetailsOk(String interfaceId, String interfaceName, boolean isPortMirrored) { + this.interfaceId = interfaceId; + this.interfaceName = interfaceName; + this.isPortMirrored = isPortMirrored; + } + + public String getInterfaceId() { + return interfaceId; + } + + public String getInterfaceName() { + return interfaceName; + } + + public boolean getIsPortMirrored() { + return isPortMirrored; + } + } + + public abstract static class PortDetails { + } + + public static class PortDetailsError extends PortDetails { + private final String errorDescription; + private final String rawAaiResponse; + + public PortDetailsError(String errorDescription, String rawAaiResponse){ + this.errorDescription = errorDescription; + this.rawAaiResponse = rawAaiResponse; + } + + public String getErrorDescription() { + return errorDescription; + } + + public String getRawAaiResponse() { + return rawAaiResponse; + } + } + + public static PortDetails extractPortDetailsFromProperties(Properties properties, String rawPayload){ + List<String> errorDescriptions = new LinkedList<>(); + describeIfNullOrEmpty("interface-id", properties.getInterfaceId(), errorDescriptions); + describeIfNullOrEmpty("interface-name", properties.getInterfaceName(), errorDescriptions); + describeIfNullOrEmpty("is-port-mirrored", properties.getIsPortMirrored(), errorDescriptions); + + if(errorDescriptions.isEmpty()){ + return new PortDetailsOk(properties.getInterfaceId(), properties.getInterfaceName(), properties.getIsPortMirrored()); + } else { + return new PortDetailsError(String.join(" ", errorDescriptions), rawPayload); + } + } + + private static void describeIfNullOrEmpty(String name, Object value, List<String> errorDescriptions) { + if (value == null) { + errorDescriptions.add("Value of '" + name + "' is missing."); + } else if (value.toString().isEmpty()) { + errorDescriptions.add("Value of '" + name + "' is empty."); + } + } + + private static Optional<List<PortDetails>> extractErrorResponseIfHttpError(AaiResponse aaiResponse, String rawPayload) { + if (aaiResponse.getHttpCode() != org.springframework.http.HttpStatus.OK.value()) { + final String errorMessage = aaiResponse.getErrorMessage(); + return Optional.of(ImmutableList.of(new PortDetailsError( + "Got " + aaiResponse.getHttpCode() + " from aai", + errorMessage != null ? errorMessage.toString() : rawPayload) + )); + } else { + return Optional.empty(); + } + } + + public List<PortDetails> extractPortDetailsInternal(AaiGetPortMirroringSourcePorts aaiGetPortsResponse, String rawPayload){ + List<SimpleResult> filteredResult = getFilteredPortList(aaiGetPortsResponse.getResults()); + + return filteredResult.stream() + .map(SimpleResult::getProperties) + .map(p -> extractPortDetailsFromProperties(p, rawPayload)) + .collect(Collectors.toList()); + } + + public List<SimpleResult> getFilteredPortList(List<SimpleResult> results) { + String LINTERFACE = "l-interface"; + + final Predicate<SimpleResult> ifIsPort = (SimpleResult r) -> LINTERFACE.equals(r.getNodeType()); + Predicate<SimpleResult> ifIsSource = getIsSourcePredicate(); + + return results.stream() + .filter(ifIsPort) + .filter(ifIsSource) + .collect(Collectors.toList()); + } + + private Predicate<SimpleResult> getIsSourcePredicate() { + boolean FLAG_ADVANCED_PORTS_FILTER = featureManager.isActive(Features.FLAG_ADVANCED_PORTS_FILTER); + + if (FLAG_ADVANCED_PORTS_FILTER) { + String PORT_LABEL = "org.onap.relationships.inventory.Source"; + return (SimpleResult r) -> r.getRelatedTo().stream() + .anyMatch(relatedTo -> PORT_LABEL.equalsIgnoreCase(relatedTo.getRelationshipLabel())); + } else { + return (SimpleResult r) -> true; + } + } + + public List<PortDetails> extractPortDetails(AaiResponse<AaiGetPortMirroringSourcePorts> aaiGetPortsResponse, String rawPayload){ + return extractErrorResponseIfHttpError(aaiGetPortsResponse, rawPayload).orElseGet(() -> extractPortDetailsInternal(aaiGetPortsResponse.getT(), rawPayload)); + + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/Properties.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/Properties.java new file mode 100644 index 00000000..6fecbed5 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/Properties.java @@ -0,0 +1,33 @@ +package org.onap.vid.aai.model; + +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Properties { + + private final String interfaceName; + private final String interfaceId; + private final Boolean isPortMirrored; + + public Properties( + @JsonProperty("interface-name") String interfaceName, + @JsonProperty("interface-id") String interfaceId, + @JsonProperty("is-port-mirrored") Boolean isPortMirrored) { + this.interfaceName = interfaceName; + this.interfaceId = interfaceId; + this.isPortMirrored = isPortMirrored; + } + + public String getInterfaceName() { + return interfaceName; + } + + public String getInterfaceId() { + return interfaceId; + } + + public Boolean getIsPortMirrored() { + return isPortMirrored; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedTo.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedTo.java new file mode 100644 index 00000000..f14a445f --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedTo.java @@ -0,0 +1,39 @@ +package org.onap.vid.aai.model; + +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class RelatedTo { + private final String id; + private final String relationshipLabel; + private final String nodeType; + private final String url; + + public RelatedTo( + @JsonProperty("id") String id, + @JsonProperty("relationship-label") String relationshipLabel, + @JsonProperty("node-type") String nodeType, + @JsonProperty("url") String url) { + this.id = id; + this.relationshipLabel = relationshipLabel; + this.nodeType = nodeType; + this.url = url; + } + + public String getId() { + return id; + } + + public String getRelationshipLabel() { + return relationshipLabel; + } + + public String getNodeType() { + return nodeType; + } + + public String getUrl() { + return url; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedToProperty.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedToProperty.java index 38003aec..a2a98fc2 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedToProperty.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedToProperty.java @@ -1,8 +1,10 @@ package org.onap.vid.aai.model; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; +@JsonIgnoreProperties(ignoreUnknown = true) public class RelatedToProperty { public String getPropertyKey() { @@ -27,8 +29,8 @@ public class RelatedToProperty { @JsonProperty("property-key") public String propertyKey; - - + + @JsonProperty("property-value") public String propertyValue; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/Relationship.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/Relationship.java index c80d5b6b..6bf63c43 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/Relationship.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/Relationship.java @@ -1,14 +1,14 @@ package org.onap.vid.aai.model; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; - import java.util.List; - +@JsonIgnoreProperties(ignoreUnknown = true) public class Relationship { - + @JsonProperty("related-to") public String relatedTo; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipData.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipData.java index 5d2d4091..41536651 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipData.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipData.java @@ -1,8 +1,9 @@ package org.onap.vid.aai.model; - +import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; +@JsonIgnoreProperties(ignoreUnknown = true) public class RelationshipData { @JsonProperty("relationship-key") public String getRelationshipKey() { @@ -21,10 +22,8 @@ public class RelationshipData { this.relationshipValue = relationshipValue; } - @JsonProperty("relationship-key") public String relationshipKey; - @JsonProperty("relationship-value") public String relationshipValue; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipList.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipList.java index 43194fc7..b16ddd01 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipList.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipList.java @@ -1,10 +1,11 @@ package org.onap.vid.aai.model; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; import java.util.List; - +@JsonIgnoreProperties(ignoreUnknown = true) public class RelationshipList { @JsonProperty("relationship") @@ -17,7 +18,6 @@ public class RelationshipList { this.relationship = relationship; } - @JsonProperty("relationship") public List<Relationship> relationship; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/ResourceType.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/ResourceType.java new file mode 100644 index 00000000..736a1aa9 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/ResourceType.java @@ -0,0 +1,44 @@ +package org.onap.vid.aai.model; + +import com.fasterxml.jackson.annotation.JsonCreator; + +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public enum ResourceType { + + SERVICE_INSTANCE("service-instance", "service-instance-name"), + GENERIC_VNF("generic-vnf", "vnf-name"), + VF_MODULE("vf-module", "vf-module-name"), + VOLUME_GROUP("volume-group", "volume-group-name"); + + private static Map<String, ResourceType> AAI_FORMAT_MAP = Stream + .of(ResourceType.values()) + .collect(Collectors.toMap(s -> s.aaiFormat, Function.identity())); + + private final String aaiFormat; + private final String nameFilter; + + ResourceType(String formatted, String nameFilter) { + this.aaiFormat = formatted; + this.nameFilter = nameFilter; + } + + public String getAaiFormat() { + return aaiFormat; + } + + public String getNameFilter() { + return nameFilter; + } + + @JsonCreator + public static ResourceType fromString(String string) { + return Optional + .ofNullable(AAI_FORMAT_MAP.get(string)) + .orElseThrow(() -> new IllegalArgumentException(string)); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/SimpleResult.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/SimpleResult.java new file mode 100644 index 00000000..b2edfc17 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/SimpleResult.java @@ -0,0 +1,85 @@ +package org.onap.vid.aai.model; + +import org.codehaus.jackson.annotate.JsonAnyGetter; +import org.codehaus.jackson.annotate.JsonAnySetter; +import org.codehaus.jackson.annotate.JsonIgnore; +import org.codehaus.jackson.annotate.JsonProperty; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class SimpleResult { + @JsonProperty("id") + private String id; + @JsonProperty("node-type") + private String nodeType; + @JsonProperty("url") + private String url; + @JsonProperty("properties") + private Properties properties; + @JsonProperty("related-to") + private List<RelatedTo> relatedTo = null; + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + + @JsonProperty("id") + public String getId() { + return id; + } + + @JsonProperty("id") + public void setId(String id) { + this.id = id; + } + + @JsonProperty("node-type") + public String getNodeType() { + return nodeType; + } + + @JsonProperty("node-type") + public void setNodeType(String nodeType) { + this.nodeType = nodeType; + } + + @JsonProperty("url") + public String getUrl() { + return url; + } + + @JsonProperty("url") + public void setUrl(String url) { + this.url = url; + } + + @JsonProperty("properties") + public Properties getProperties() { + return properties; + } + + @JsonProperty("properties") + public void setProperties(Properties properties) { + this.properties = properties; + } + + @JsonProperty("related-to") + public List<RelatedTo> getRelatedTo() { + return relatedTo; + } + + @JsonProperty("related-to") + public void setRelatedTo(List<RelatedTo> relatedTo) { + this.relatedTo = relatedTo; + } + + @JsonAnyGetter + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/AAIRestInterface.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/AAIRestInterface.java index 226850d2..ac38b505 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/AAIRestInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/AAIRestInterface.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,28 +20,31 @@ package org.onap.vid.aai.util; +import com.att.eelf.configuration.EELFLogger; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.eclipse.jetty.util.security.Password; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.aai.ResponseWithRequestInfo; +import org.onap.vid.utils.Logging; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpMethod; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; -import java.security.KeyManagementException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Base64; import java.util.Date; import java.util.UUID; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import com.att.eelf.configuration.EELFLogger; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; -import org.eclipse.jetty.util.security.Password; -import org.onap.vid.utils.Logging; -import org.springframework.http.HttpMethod; -import static org.onap.vid.utils.Logging.getHttpServletRequest; -import static org.onap.vid.utils.Logging.requestIdHeaderKey; +import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; +import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; /** @@ -49,43 +52,32 @@ import static org.onap.vid.utils.Logging.requestIdHeaderKey; */ public class AAIRestInterface { + public static final String WITH_STATUS = " with status="; /** The logger. */ - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AAIRestInterface.class); + protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AAIRestInterface.class); - final private EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("aai"); + protected final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("aai"); /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + protected final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); /** The client. */ - private static Client client = null; + private Client client = null; /** The rest srvr base URL. */ private String restSrvrBaseURL; - /** The certificate path. */ - public String certificatePath = ""; + @Autowired + protected HttpsAuthClient httpsAuthClientFactory; private String START_STRING = " start"; - - private String TRANSACTION_ID_HEADER = "X-TransactionId"; - private String FROM_APP_ID_HEADER = "X-FromAppId"; + protected String TRANSACTION_ID_HEADER = "X-TransactionId"; + protected String FROM_APP_ID_HEADER = "X-FromAppId"; private String SUCCESSFUL_API_MESSAGE=" REST api POST was successful!"; - private String URL_DECLERATION = ", url="; - - - - + protected String URL_DECLARATION = ", url="; - - /** - * Instantiates a new AAI rest interface. - * - * @param certPath the cert path - */ - public AAIRestInterface(String certPath) - { - certificatePath = certPath; + public AAIRestInterface(HttpsAuthClient httpsAuthClientFactory) { + this.httpsAuthClientFactory = httpsAuthClientFactory; } /** @@ -99,27 +91,28 @@ public class AAIRestInterface { return URLEncoder.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20"); } - /** - * Inits the rest client. - */ - private void initRestClient() - { - String methodName = "initRestClient"; + private void initRestClient() { + initRestClient(false); + } + + private void initRestClient(boolean propagateExceptions) + { if (client == null) { try { - client = HttpsAuthClient.getClient(certificatePath); - } - catch (KeyManagementException e){ - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== KeyManagementException in " + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== KeyManagementException in " + methodName + e.toString()); + client = httpsAuthClientFactory.getClient(HttpClientMode.WITHOUT_KEYSTORE); } catch (Exception e) { logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== Exception in REST call to DB in initRestClient" + e.toString()); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== Exception in REST call to DB : " + e.toString()); + if (propagateExceptions) { + ExceptionUtils.rethrow(e); + } } } } + + /** * Sets the rest srvr base URL. * @@ -155,70 +148,82 @@ public class AAIRestInterface { * @param requestUri the request uri * @param xml the xml * @return the string - * @throws UnsupportedEncodingException */ - public Response RestGet(String fromAppId, String transId, String requestUri, boolean xml) throws UnsupportedEncodingException { - String methodName = "RestGet"; - - String responseType = MediaType.APPLICATION_JSON; - if (xml) - responseType = MediaType.APPLICATION_XML; - initRestClient(); + public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml) { + return RestGet(fromAppId, transId, requestUri, xml, false); + } - String clientCert = SystemProperties.getProperty(AAIProperties.AAI_USE_CLIENT_CERT); + public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml, boolean propagateExceptions) { + String url = null; + try { + String methodName = "RestGet"; + url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + requestUri; - boolean useClientCert = false; - if (clientCert != null && - SystemProperties.getProperty(AAIProperties.AAI_USE_CLIENT_CERT).equalsIgnoreCase("true")) { - useClientCert = true; - } - String url = ""; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START_STRING); + String responseType = MediaType.APPLICATION_JSON; + if (xml) + responseType = MediaType.APPLICATION_XML; - url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + requestUri; + initRestClient(propagateExceptions); + String clientCert = SystemProperties.getProperty(AAIProperties.AAI_USE_CLIENT_CERT); - logger.debug(dateFormat.format(new Date()) + "<== " + url + " for the get REST API"); - Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); + boolean useClientCert = false; + if (clientCert != null && + SystemProperties.getProperty(AAIProperties.AAI_USE_CLIENT_CERT).equalsIgnoreCase("true")) { + useClientCert = true; + } - final Response cres; - if (useClientCert == true) { - cres = client.target(url) - .request() - .accept(responseType) - .header(TRANSACTION_ID_HEADER, transId) - .header(FROM_APP_ID_HEADER, fromAppId) - .header("Content-Type", MediaType.APPLICATION_JSON) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .get(); - } else { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START_STRING); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + url + " for the get REST API"); + + Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); + + final Response cres; + if (useClientCert == true) { + cres = client.target(url) + .request() + .accept(responseType) + .header(TRANSACTION_ID_HEADER, transId) + .header(FROM_APP_ID_HEADER, fromAppId) + .header("Content-Type", MediaType.APPLICATION_JSON) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) + .get(); + } else { - String vidUsername = SystemProperties.getProperty(AAIProperties.AAI_VID_USERNAME); - String vidPassword = Password.deobfuscate(SystemProperties.getProperty(AAIProperties.AAI_VID_PASSWD_X)); - String encodeThis = vidUsername + ":" + vidPassword; + String vidUsername = SystemProperties.getProperty(AAIProperties.AAI_VID_USERNAME); + String vidPassword = Password.deobfuscate(SystemProperties.getProperty(AAIProperties.AAI_VID_PASSWD_X)); + String encodeThis = vidUsername + ":" + vidPassword; + + cres = client.target(url) + .request() + .accept(responseType) + .header(TRANSACTION_ID_HEADER, transId) + .header(FROM_APP_ID_HEADER, fromAppId) + .header("Content-Type", "application/json") + .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8"))) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) + .get(); + } + Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres); - cres = client.target(url) - .request() - .accept(responseType) - .header(TRANSACTION_ID_HEADER, transId) - .header(FROM_APP_ID_HEADER, fromAppId) - .header("Content-Type", "application/json") - .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8"))) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .get(); - } - Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres); -// String r = cres.readEntity(String.class); - if (cres.getStatus() == 200) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + SUCCESSFUL_API_MESSAGE); - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + SUCCESSFUL_API_MESSAGE); - } else { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName +" with status="+cres.getStatus()+URL_DECLERATION+url); + if (cres.getStatus() == 200) { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + SUCCESSFUL_API_MESSAGE); + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + SUCCESSFUL_API_MESSAGE); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS + cres.getStatus() + URL_DECLARATION + url); + } + return new ResponseWithRequestInfo(cres, url, HttpMethod.GET); + } catch (Exception e) { + // no need to ask if "propagateExceptions" because any exception + // at this point should have already obey to the + // "propagateExceptions" flag + throw new ExceptionWithRequestInfo(HttpMethod.GET, defaultIfNull(url, requestUri), e); } - return cres; -// logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName +" resp=" + r ); -// return r; + } + + protected String extractOrGenerateRequestId() { + return Logging.extractOrGenerateRequestId(); } @@ -237,7 +242,6 @@ public class AAIRestInterface { logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START_STRING); initRestClient(); - String request = "{}"; url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + path; Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url); final Response cres = client.target(url) @@ -245,8 +249,7 @@ public class AAIRestInterface { .accept(MediaType.APPLICATION_JSON) .header(TRANSACTION_ID_HEADER, transId) .header(FROM_APP_ID_HEADER, sourceID) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - //.entity(request) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) .delete(); Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres); if (cres.getStatus() == 404) { // resource not found @@ -271,16 +274,15 @@ public class AAIRestInterface { * Rest put. * * @param fromAppId the from app id - * @param transId the trans id * @param path the path * @param payload the payload * @param xml the xml * @return the string */ - public Response RestPut(String fromAppId, String transId, String path, String payload, boolean xml) { + public Response RestPut(String fromAppId, String path, String payload, boolean xml) { String methodName = "RestPut"; String url=""; - transId = UUID.randomUUID().toString(); + String transId = UUID.randomUUID().toString(); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START_STRING); try { @@ -303,19 +305,19 @@ public class AAIRestInterface { .header(TRANSACTION_ID_HEADER, transId) .header(FROM_APP_ID_HEADER, fromAppId) .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8"))) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) .put(Entity.entity(payload, MediaType.APPLICATION_JSON)); Logging.logResponse(outgoingRequestsLogger, HttpMethod.PUT, url, cres); if (cres.getStatus() == 200 && cres.getStatus() <= 299) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION); + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION); } else { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName +" with status="+cres.getStatus()+URL_DECLERATION+url); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS +cres.getStatus()+ URL_DECLARATION +url); } return cres; } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION+url+ ", Exception: " + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION +url+ ", Exception: " + e.toString()); } return null; } @@ -326,16 +328,15 @@ public class AAIRestInterface { * Rest post. * * @param fromAppId the from app id - * @param transId the trans id * @param path the path * @param payload the payload * @param xml the xml * @return the string */ - public Response RestPost(String fromAppId, String transId, String path, String payload, boolean xml) { + public Response RestPost(String fromAppId, String path, String payload, boolean xml) { String methodName = "RestPost"; String url=""; - transId = UUID.randomUUID().toString(); + String transId = UUID.randomUUID().toString(); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START_STRING); try { @@ -358,19 +359,19 @@ public class AAIRestInterface { .header(TRANSACTION_ID_HEADER, transId) .header(FROM_APP_ID_HEADER, fromAppId) .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8"))) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) .post(Entity.entity(payload, MediaType.APPLICATION_JSON)); Logging.logResponse(outgoingRequestsLogger, HttpMethod.POST, url, cres); if (cres.getStatus() == 200 && cres.getStatus() <= 299) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION); + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION); } else { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " with status="+cres.getStatus()+URL_DECLERATION+url); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS +cres.getStatus()+ URL_DECLARATION +url); } return cres; } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION+url+ ", Exception: " + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION +url+ ", Exception: " + e.toString()); } return null; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/CustomJacksonJaxBJsonProvider.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/CustomJacksonJaxBJsonProvider.java index 996341a9..375f0b2d 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/CustomJacksonJaxBJsonProvider.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/CustomJacksonJaxBJsonProvider.java @@ -21,8 +21,6 @@ package org.onap.vid.aai.util; -import javax.ws.rs.ext.Provider; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; @@ -30,6 +28,8 @@ import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; +import javax.ws.rs.ext.Provider; + /** * The Class CustomJacksonJaxBJsonProvider. */ diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpClientMode.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpClientMode.java new file mode 100644 index 00000000..e1992826 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpClientMode.java @@ -0,0 +1,9 @@ +package org.onap.vid.aai.util; + +public enum HttpClientMode { + + WITH_KEYSTORE, + WITHOUT_KEYSTORE(), + UNSECURE, + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsAuthClient.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsAuthClient.java index 3bc8e4a3..f1eafe42 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsAuthClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsAuthClient.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,120 +21,151 @@ package org.onap.vid.aai.util; -import java.io.FileInputStream; -import java.security.KeyManagementException; -import java.security.KeyStore; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; - import org.eclipse.jetty.util.security.Password; import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.HttpUrlConnectorProvider; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; + +import javax.net.ssl.*; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import java.io.FileInputStream; +import java.io.IOException; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + /** * The Class HttpsAuthClient. */ -public class HttpsAuthClient{ - /** The logger. */ - static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsAuthClient.class); - - /** - * Gets the client. - * - * @param certFilePath the cert file path - * @return the client - * @throws KeyManagementException the key management exception - */ - public static Client getClient(String certFilePath) throws KeyManagementException { - - ClientConfig config = new ClientConfig(); - //config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - //config.getClasses().add(org.onap.aai.util.CustomJacksonJaxBJsonProvider.class); - - try { - - config.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, Boolean.TRUE ); - - config.connectorProvider(new HttpUrlConnectorProvider().useSetMethodWorkaround()); - String truststore_path = certFilePath + org.onap.vid.aai.util.AAIProperties.FILESEPARTOR + SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_TRUSTSTORE_FILENAME); - String truststore_password = SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_TRUSTSTORE_PASSWD_X); - String decrypted_truststore_password = Password.deobfuscate(truststore_password); - - boolean useClientCert = false; - - String keystore_path = certFilePath + org.onap.vid.aai.util.AAIProperties.FILESEPARTOR + SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_KEYSTORE_FILENAME); - String keystore_password = SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_KEYSTORE_PASSWD_X); - String decrypted_keystore_password = Password.deobfuscate(keystore_password); - - String clientCert = SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_USE_CLIENT_CERT); - - if (clientCert != null && - SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_USE_CLIENT_CERT).equalsIgnoreCase("true")) { - useClientCert = true; - } - - System.setProperty("javax.net.ssl.trustStore", truststore_path); - System.setProperty("javax.net.ssl.trustStorePassword", decrypted_truststore_password); - HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){ - public boolean verify(String string,SSLSession ssls) { - return true; - } - }); - - final SSLContext ctx = SSLContext.getInstance("TLS"); - - KeyManagerFactory kmf = null; - if (useClientCert) { - - try { - kmf = KeyManagerFactory.getInstance("SunX509"); - FileInputStream fin = new FileInputStream(keystore_path); - KeyStore ks = KeyStore.getInstance("PKCS12"); - char[] pwd = decrypted_keystore_password.toCharArray(); - ks.load(fin, pwd); - kmf.init(ks, pwd); - } catch (Exception e) { - //System.out.println("Error setting up kmf: exiting"); - logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up kmf: exiting"); - e.printStackTrace(); - return null; - } - ctx.init(kmf.getKeyManagers(), null, null); - - return ClientBuilder.newBuilder() - .sslContext(ctx) - .hostnameVerifier(new HostnameVerifier() { - @Override - public boolean verify( String s, SSLSession sslSession ) { - return true; - } - }).withConfig(config) - .build() - .register(org.onap.vid.aai.util.CustomJacksonJaxBJsonProvider.class); - } else { - return ClientBuilder.newBuilder() - .hostnameVerifier(new HostnameVerifier() { - @Override - public boolean verify( String s, SSLSession sslSession ) { - return true; - } - }).withConfig(config) - .build() - .register(org.onap.vid.aai.util.CustomJacksonJaxBJsonProvider.class); - } - } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up config: exiting"); - //System.out.println("Error setting up config: exiting"); - e.printStackTrace(); - System.exit(1); - return null; - } - } -} +public class HttpsAuthClient { + + + public HttpsAuthClient(String certFilePath) { + this.certFilePath = certFilePath; + } + + private final String certFilePath; + + /** The logger. */ + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsAuthClient.class); + + /** + * Gets the client. + * + * @return the client + * @throws KeyManagementException the key management exception + */ + public Client getClient(HttpClientMode mode) throws GeneralSecurityException, IOException { + ClientConfig config = new ClientConfig(); + SSLContext ctx; + + try { + String truststorePath = getCertificatesPath() + org.onap.vid.aai.util.AAIProperties.FILESEPARTOR + SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_TRUSTSTORE_FILENAME); + String truststorePassword = SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_TRUSTSTORE_PASSWD_X); + String decryptedTruststorePassword = Password.deobfuscate(truststorePassword); + + System.setProperty("javax.net.ssl.trustStore", truststorePath); + System.setProperty("javax.net.ssl.trustStorePassword", decryptedTruststorePassword); + + HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { + public boolean verify(String string, SSLSession ssls) { + return true; + } + }); + ctx = SSLContext.getInstance("TLSv1.2"); + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = getTrustManager(mode); + + switch (mode) { + case WITH_KEYSTORE: + String aaiKeystorePath = getCertificatesPath() + org.onap.vid.aai.util.AAIProperties.FILESEPARTOR + SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_KEYSTORE_FILENAME); + String aaiKeystorePassword = SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_KEYSTORE_PASSWD_X); + config.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, Boolean.TRUE); + config.connectorProvider(new HttpUrlConnectorProvider().useSetMethodWorkaround()); + KeyManagerFactory kmf = getKeyManagerFactory(aaiKeystorePath, aaiKeystorePassword); + keyManagers = kmf.getKeyManagers(); + break; + + case WITHOUT_KEYSTORE: + config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); + break; + + default: + logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up config. HttpClientMode is " + mode); + } + + ctx.init(keyManagers, trustManagers, null); + return ClientBuilder.newBuilder() + .sslContext(ctx) + .hostnameVerifier(new HostnameVerifier() { + @Override + public boolean verify(String s, SSLSession sslSession) { + return true; + } + }).withConfig(config) + .build() + .register(org.onap.vid.aai.util.CustomJacksonJaxBJsonProvider.class); + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up config", e); + throw e; + } + + } + + /** + * @param aaiKeystorePath + * @param aaiKeystorePassword - in OBF format + * @return + * @throws NoSuchAlgorithmException + * @throws KeyStoreException + * @throws IOException + * @throws CertificateException + * @throws UnrecoverableKeyException + */ + private KeyManagerFactory getKeyManagerFactory(String aaiKeystorePath, String aaiKeystorePassword) throws IOException, GeneralSecurityException { + String aaiDecryptedKeystorePassword = Password.deobfuscate(aaiKeystorePassword); + KeyManagerFactory kmf = null; + try (FileInputStream fin = new FileInputStream(aaiKeystorePath)) { + kmf = KeyManagerFactory.getInstance("SunX509"); + KeyStore ks = KeyStore.getInstance("PKCS12"); + char[] pwd = aaiDecryptedKeystorePassword.toCharArray(); + ks.load(fin, pwd); + kmf.init(ks, pwd); + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up kmf"); + logger.error(EELFLoggerDelegate.errorLogger, "Error setting up kmf (keystore path: {}, obfuascated keystore password: {})", aaiKeystorePath, aaiKeystorePassword, e); + throw e; + } + return kmf; + } + + private String getCertificatesPath() { + return certFilePath; + } + + private TrustManager[] getTrustManager(HttpClientMode httpClientMode) { + //Creating a trustManager that will accept all certificates. + //TODO - remove this one the POMBA certificate is added to the tomcat_keystore file + TrustManager[] trustAllCerts = null; + if (httpClientMode == HttpClientMode.UNSECURE) { + + trustAllCerts = new TrustManager[]{new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted(X509Certificate[] certs, String authType) { + } + + public void checkServerTrusted(X509Certificate[] certs, String authType) { + } + }}; + } + return trustAllCerts; + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsComponentsClient.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsComponentsClient.java index 10022219..d1f1cfc8 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsComponentsClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsComponentsClient.java @@ -20,25 +20,29 @@ package org.onap.vid.aai.util; -import java.io.FileInputStream; -import java.security.KeyManagementException; -import java.security.KeyStore; - -import javax.net.ssl.SSLContext; - +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; import org.eclipse.jetty.util.security.Password; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; +import javax.net.ssl.SSLContext; +import java.io.FileInputStream; +import java.security.GeneralSecurityException; +import java.security.KeyManagementException; +import java.security.KeyStore; + /** * The Class HttpsComponentsClient. */ public class HttpsComponentsClient{ - + + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsComponentsClient.class); + /** * Gets the client. * @@ -46,10 +50,10 @@ public class HttpsComponentsClient{ * @return the client * @throws KeyManagementException the key management exception */ - public static CloseableHttpClient getClient(String certFilePath) throws Exception { + public static CloseableHttpClient getClient(String certFilePath) { CloseableHttpClient httpclient = null; try { - + String truststore_path = certFilePath + AAIProperties.FILESEPARTOR + SystemProperties.getProperty(AAIProperties.AAI_TRUSTSTORE_FILENAME); String truststore_password = SystemProperties.getProperty(AAIProperties.AAI_TRUSTSTORE_PASSWD_X); String decrypted_truststore_password = Password.deobfuscate(truststore_password); @@ -60,17 +64,31 @@ public class HttpsComponentsClient{ SSLContextBuilder sslContextB = new SSLContextBuilder(); KeyStore ks = KeyStore.getInstance("PKCS12"); - FileInputStream fin = new FileInputStream(keystore_path); char[] pwd = decrypted_keystore_password.toCharArray(); - ks.load(fin, pwd); - + + try(FileInputStream fin = new FileInputStream(keystore_path)) { + ks.load(fin, pwd); + } + catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up keystore"); + logger.error(EELFLoggerDelegate.errorLogger, "Error loading keystore materials: (keystore path: {}, obfuascated keystore password: {})", keystore_path, keystore_password); + throw new GenericUncheckedException(e); + } + sslContextB.loadKeyMaterial(ks, pwd); KeyStore ts = KeyStore.getInstance("JKS"); - FileInputStream fin1 = new FileInputStream(truststore_path); char[] pwd1 = decrypted_truststore_password.toCharArray(); - ts.load(fin1, pwd1); - + + try(FileInputStream fin1 = new FileInputStream(truststore_path)) { + ts.load(fin1, pwd1); + } + catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up truststore"); + logger.error(EELFLoggerDelegate.errorLogger, "Error loading truststore materials: (truststore path: {}, obfuascated truststore password: {})", truststore_path, truststore_password); + throw new GenericUncheckedException(e); + } + sslContextB.loadTrustMaterial(ts); sslContextB.loadKeyMaterial(ks, pwd); sslContextB.useTLS(); @@ -88,8 +106,8 @@ public class HttpsComponentsClient{ .build(); - } catch (Exception e) { - throw e; + } catch (GeneralSecurityException e) { + throw new GenericUncheckedException(e); } return httpclient; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/JettyObfuscationConversionCommandLineUtil.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/JettyObfuscationConversionCommandLineUtil.java index 8a3ba88f..cfc56d18 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/JettyObfuscationConversionCommandLineUtil.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/JettyObfuscationConversionCommandLineUtil.java @@ -21,11 +21,7 @@ package org.onap.vid.aai.util; -import org.apache.commons.cli.BasicParser; -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; +import org.apache.commons.cli.*; import org.eclipse.jetty.util.security.Password; @@ -70,7 +66,7 @@ public class JettyObfuscationConversionCommandLineUtil { * Usage. */ private static void usage(){ - System.out.println("usage:");; + System.out.println("usage:"); System.out.println("-e [string] to obfuscate"); System.out.println("-d [string] to deobfuscate"); System.out.println("-h help"); diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/VidObjectMapperType.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/VidObjectMapperType.java new file mode 100644 index 00000000..931987ae --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/VidObjectMapperType.java @@ -0,0 +1,6 @@ +package org.onap.vid.aai.util; + +public enum VidObjectMapperType { + CODEHAUS, + FASTERXML +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/AsdcClient.java b/vid-app-common/src/main/java/org/onap/vid/asdc/AsdcClient.java index 970ec954..4e0254cd 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/AsdcClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/AsdcClient.java @@ -20,66 +20,16 @@ package org.onap.vid.asdc; -import java.io.IOException; +import org.onap.vid.asdc.beans.Service; + import java.nio.file.Path; -import java.util.Collection; -import java.util.Map; import java.util.UUID; -import org.onap.vid.asdc.beans.Artifact; -import org.onap.vid.asdc.beans.Resource; -import org.onap.vid.asdc.beans.Service; - /** * The Interface AsdcClient. */ public interface AsdcClient { - - /** - * Gets the resource. - * - * @param uuid the uuid - * @return the resource - * @throws AsdcCatalogException the sdc catalog exception - */ - public Resource getResource(UUID uuid) throws AsdcCatalogException; - - /** - * Gets the resources. - * - * @return the resources - * @throws AsdcCatalogException the sdc catalog exception - */ - public Collection<Resource> getResources() throws AsdcCatalogException; - - /** - * Gets the resources. - * - * @param filter the filter - * @return the resources - * @throws AsdcCatalogException the sdc catalog exception - */ - public Collection<Resource> getResources(Map<String, String[]> filter) throws AsdcCatalogException; - - /** - * Gets the resource artifact. - * - * @param resourceUuid the resource uuid - * @param artifactUuid the artifact uuid - * @return the resource artifact - * @throws AsdcCatalogException the sdc catalog exception - */ - public Artifact getResourceArtifact(UUID resourceUuid, UUID artifactUuid) throws AsdcCatalogException; - - /** - * Gets the resource tosca model. - * - * @param uuid the uuid - * @return the resource tosca model - * @throws AsdcCatalogException the sdc catalog exception - */ - public Path getResourceToscaModel(UUID uuid) throws AsdcCatalogException; - + /** * Gets the service. * @@ -87,35 +37,8 @@ public interface AsdcClient { * @return the service * @throws AsdcCatalogException the sdc catalog exception */ - public Service getService(UUID uuid) throws AsdcCatalogException; - - /** - * Gets the services. - * - * @return the services - * @throws AsdcCatalogException the sdc catalog exception - */ - public Collection<Service> getServices() throws AsdcCatalogException; - - /** - * Gets the services. - * - * @param filter the filter - * @return the services - * @throws AsdcCatalogException the asdc catalog exception - */ - public Collection<Service> getServices(Map<String, String[]> filter) throws AsdcCatalogException; - - /** - * Gets the service artifact. - * - * @param serviceUuid the service uuid - * @param artifactUuid the artifact uuid - * @return the service artifact - * @throws AsdcCatalogException the asdc catalog exception - */ - public Artifact getServiceArtifact(UUID serviceUuid, UUID artifactUuid) throws AsdcCatalogException; - + Service getService(UUID uuid) throws AsdcCatalogException; + /** * Gets the service tosca model. * @@ -123,7 +46,5 @@ public interface AsdcClient { * @return the service tosca model * @throws AsdcCatalogException the asdc catalog exception */ - public Path getServiceToscaModel(UUID uuid) throws AsdcCatalogException; - - //TODO: Collect TOSCA information from CSAR + Path getServiceToscaModel(UUID uuid) throws AsdcCatalogException; } diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/Resource.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/Resource.java deleted file mode 100644 index 6b5aa532..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/Resource.java +++ /dev/null @@ -1,429 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.asdc.beans; - -import java.util.Collection; -import java.util.UUID; - -/** - * The Class Resource. - */ -public class Resource { - - /** - * The Enum Type. - */ - public enum Type { - - /** The vf. */ - VF, - - /** The vfc. */ - VFC, - - /** The cp. */ - CP, - - /** The vl. */ - VL, - - /** The vfcmt. */ - VFCMT - } - - /** - * The Enum LifecycleState. - */ - public enum LifecycleState { - - /** The not certified checkout. */ - NOT_CERTIFIED_CHECKOUT, - - /** The not certified checkin. */ - NOT_CERTIFIED_CHECKIN, - - /** The ready for certification. */ - READY_FOR_CERTIFICATION, - - /** The certification in progress. */ - CERTIFICATION_IN_PROGRESS, - - /** The certified. */ - CERTIFIED - } - - /** The uuid. */ - private String uuid; - - /** The invariant UUID. */ - private String invariantUUID; - - /** The name. */ - private String name; - - /** The description. */ - private String description; - - /** The version. */ - private String version; - - /** The tosca model URL. */ - private String toscaModelURL; - - /** The category. */ - private String category; - - /** The sub category. */ - private String subCategory; - - /** The resource type. */ - private Resource.Type resourceType; - - /** The lifecycle state. */ - private Resource.LifecycleState lifecycleState; - - /** The last updater user ID. */ - private String lastUpdaterUserId; - - /** The last updater full name. */ - private String lastUpdaterFullName; - - /** The tosca model. */ - private String toscaModel; - - /** The tosca resource name. */ - private String toscaResourceName; - - /** The artifacts. */ - private Collection<Artifact> artifacts; - - /** The resources. */ - private Collection<SubResource> resources; - - /** - * Gets the uuid. - * - * @return the uuid - */ - public String getUuid() { - return uuid; - } - - /** - * Gets the invariant UUID. - * - * @return the invariant UUID - */ - public String getInvariantUUID() { - return invariantUUID; - } - - /** - * Gets the name. - * - * @return the name - */ - public String getName() { - return name; - } - - /** - * Gets the description. - * - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * Gets the version. - * - * @return the version - */ - public String getVersion() { - return version; - } - - /** - * Gets the tosca model URL. - * - * @return the tosca model URL - */ - public String getToscaModelURL() { - return toscaModelURL; - } - - /** - * Gets the category. - * - * @return the category - */ - public String getCategory() { - return category; - } - - /** - * Gets the sub category. - * - * @return the sub category - */ - public String getSubCategory() { - return subCategory; - } - - /** - * Gets the resource type. - * - * @return the resource type - */ - public Resource.Type getResourceType() { - return resourceType; - } - - /** - * Gets the lifecycle state. - * - * @return the lifecycle state - */ - public Resource.LifecycleState getLifecycleState() { - return lifecycleState; - } - - /** - * Gets the last updater user ID. - * - * @return the last updater user ID - */ - public String getLastUpdaterUserId() { - return lastUpdaterUserId; - } - - /** - * Gets the last updater full name. - * - * @return the last updater full name - */ - public String getLastUpdaterFullName() { - return lastUpdaterFullName; - } - - /** - * Gets the tosca model. - * - * @return the tosca model - */ - public String getToscaModel() { - return toscaModel; - } - - /** - * Gets the tosca resource name. - * - * @return the tosca resource name - */ - public String getToscaResourceName() { - return toscaResourceName; - } - - /** - * Gets the artifacts. - * - * @return the artifacts - */ - public Collection<Artifact> getArtifacts() { - return artifacts; - } - - /** - * Gets the resources. - * - * @return the resources - */ - public Collection<SubResource> getResources() { - return resources; - } - - /** - * Sets the uuid. - * - * @param uuid the new uuid - */ - public void setUuid(String uuid) { - this.uuid = uuid; - } - - /** - * Sets the invariant UUID. - * - * @param invariantUUID the new invariant UUID - */ - public void setInvariantUUID(String invariantUUID) { - this.invariantUUID = invariantUUID; - } - - /** - * Sets the name. - * - * @param name the new name - */ - public void setName(String name) { - this.name = name; - } - /** - * Sets the description. - * - * @param name the new description - */ - public void setDescription(String description) { - this.description = description; - } - /** - * Sets the version. - * - * @param version the new version - */ - public void setVersion(String version) { - this.version = version; - } - - /** - * Sets the tosca model URL. - * - * @param toscaModelURL the new tosca model URL - */ - public void setToscaModelURL(String toscaModelURL) { - this.toscaModelURL = toscaModelURL; - } - - /** - * Sets the category. - * - * @param category the new category - */ - public void setCategory(String category) { - this.category = category; - } - - /** - * Sets the sub category. - * - * @param subCategory the new sub category - */ - public void setSubCategory(String subCategory) { - this.subCategory = subCategory; - } - - /** - * Sets the resource type. - * - * @param resourceType the new resource type - */ - public void setResourceType(Resource.Type resourceType) { - this.resourceType = resourceType; - } - - /** - * Sets the lifecycle state. - * - * @param lifecycleState the new lifecycle state - */ - public void setLifecycleState(Resource.LifecycleState lifecycleState) { - this.lifecycleState = lifecycleState; - } - - /** - * Sets the last updater user ID. - * - * @param lastUpdaterUserId the new last updater user ID - */ - public void setLastUpdaterUserId(String lastUpdaterUserId) { - this.lastUpdaterUserId = lastUpdaterUserId; - } - - /** - * Sets the last updater full name. - * - * @param lastUpdaterFullName the new last updater full name - */ - public void setLastUpdaterFullName(String lastUpdaterFullName) { - this.lastUpdaterFullName = lastUpdaterFullName; - } - - /** - * Sets the tosca model. - * - * @param toscaModel the new tosca model - */ - public void setToscaModel(String toscaModel) { - this.toscaModel = toscaModel; - } - - /** - * Sets the tosca resource name. - * - * @param toscaResourceName the new tosca resource name - */ - public void setToscaResourceName(String toscaResourceName) { - this.toscaResourceName = toscaResourceName; - } - - /** - * Sets the artifacts. - * - * @param artifacts the new artifacts - */ - public void setArtifacts(Collection<Artifact> artifacts) { - this.artifacts = artifacts; - } - - /** - * Sets the resources. - * - * @param resources the new resources - */ - public void setResources(Collection<SubResource> resources) { - this.resources = resources; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final UUID uuid = UUID.fromString(getUuid()); - - return uuid.hashCode(); - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof Resource)) return false; - - final Resource resource = (Resource) o; - - return (resource.getUuid().equals(getUuid())); - } -} diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/SecureService.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/SecureService.java deleted file mode 100644 index b81a4389..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/SecureService.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.onap.vid.asdc.beans; - -/** - * Created by Oren on 6/27/17. - */ -public class SecureService extends Service{ - - public boolean isPermmited = true; -} diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/Service.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/Service.java index 5f59b89e..cb16f144 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/Service.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/Service.java @@ -97,7 +97,7 @@ public class Service { private String lastUpdaterFullName; /** The distribution status. */ - private Service.DistributionStatus distributionStatus; + private String distributionStatus; /** The artifacts. */ private Collection<Artifact> artifacts; @@ -191,7 +191,7 @@ public class Service { * * @return the distribution status */ - public Service.DistributionStatus getDistributionStatus() { + public String getDistributionStatus() { return distributionStatus; } @@ -299,7 +299,7 @@ public class Service { * * @param distributionStatus the new distribution status */ - public void setDistributionStatus(Service.DistributionStatus distributionStatus) { + public void setDistributionStatus(String distributionStatus) { this.distributionStatus = distributionStatus; } @@ -334,9 +334,7 @@ public class Service { */ @Override public int hashCode() { - final UUID uuid = UUID.fromString(getUuid()); - - return uuid.hashCode(); + return UUID.fromString(getUuid()).hashCode(); } /* (non-Javadoc) @@ -351,4 +349,20 @@ public class Service { return (service.getUuid().equals(getUuid())); } + + public Service(String uuid, String invariantUUID, String category, String version, String name, String distributionStatus, String toscaModelURL, LifecycleState lifecycleState, Collection<Artifact> artifacts, Collection<SubResource> resources) { + this.uuid = uuid; + this.invariantUUID = invariantUUID; + this.name = name; + this.version = version; + this.toscaModelURL = toscaModelURL; + this.category = category; + this.lifecycleState = lifecycleState; + this.distributionStatus = distributionStatus; + this.artifacts = artifacts; + this.resources = resources; + } + + public Service() { + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Capability.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Capability.java deleted file mode 100644 index 7aa13435..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Capability.java +++ /dev/null @@ -1,140 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.asdc.beans.tosca; - -import java.util.Collection; -import java.util.Map; - -/** - * The Class Capability. - */ -public class Capability { - - /** The type. */ - private String type; //FIXME: Make an enumeration? - - /** The description. */ - private String description; - - /** The occurrences. */ - private Collection<String> occurrences; //FIXME: Make an enumeration? - - /** The properties. */ - private Map<String, Property> properties; - - /** The valid source types. */ - private Collection<String> valid_source_types; //FIXME: Make an enumeration? - - /** - * Instantiates a new capability. - */ - public Capability() {} - - /** - * Gets the type. - * - * @return the type - */ - public String getType() { - return type; - } - - /** - * Gets the description. - * - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * Gets the occurrences. - * - * @return the occurrences - */ - public Collection<String> getOccurrences() { - return occurrences; - } - - /** - * Gets the properties. - * - * @return the properties - */ - public Map<String, Property> getProperties() { - return properties; - } - - /** - * Gets the valid source types. - * - * @return the valid source types - */ - public Collection<String> getValid_source_types() { - return valid_source_types; - } - - /** - * Sets the type. - * - * @param type the new type - */ - public void setType(String type) { - this.type = type; - } - - /** - * Sets the description. - * - * @param description the new description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Sets the occurrences. - * - * @param occurrences the new occurrences - */ - public void setOccurrences(Collection<String> occurrences) { - this.occurrences = occurrences; - } - - /** - * Sets the properties. - * - * @param properties the properties - */ - public void setProperties(Map<String, Property> properties) { - this.properties = properties; - } - - /** - * Sets the valid source types. - * - * @param valid_source_types the new valid source types - */ - public void setValid_source_types(Collection<String> valid_source_types) { - this.valid_source_types = valid_source_types; - } -} diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Constraint.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Constraint.java deleted file mode 100644 index 118776ca..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Constraint.java +++ /dev/null @@ -1,199 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.asdc.beans.tosca; -import java.util.List; -import java.util.ArrayList; - -/** - * The Class Constraint. - */ - -public class Constraint { - private List<Object> valid_values; - private Object equal; - private Object greater_than; - private Object greater_or_equal; - private Object less_than; - private Object less_or_equal; - private List<Object> in_range; - private Object length; - private Object min_length; - private Object max_length; - - /** - * Instantiates a new Constraint. - */ - public Constraint() { - valid_values = new ArrayList<Object>(); - in_range = new ArrayList<Object>(); - } - - /** - * Gets the valid_values. - * - * @return the valid_values - */ - public List<Object> getvalid_values() { - return valid_values; - } - /** - * Gets equal. - * - * @return equal - */ - public Object getEqual() { - return equal; - } - /** - * Gets greater_than. - * - * @return greater_than - */ - public Object getGreater_than() { - return greater_than; - } - /** - * Gets greater_or_equal. - * - * @return greater_or_equal - */ - public Object getGreater_or_equal() { - return greater_or_equal; - } - /** - * Gets less_than. - * - * @return less_than - */ - public Object getLess_than() { - return less_than; - } - /** - * Gets less_or_equal. - * - * @return less_or_equal - */ - public Object getLess_or_equal() { - return less_or_equal; - } - /** - * Gets in_range. - * - * @return in_range - */ - public List<Object> getIn_range() { - return in_range; - } - /** - * Gets length. - * - * @return length - */ - public Object getLength() { - return length; - } - /** - * Gets min_length. - * - * @return min_length - */ - public Object getMin_length() { - return min_length; - } - /** - * Gets max_length. - * - * @return max_length - */ - public Object getMax_length() { - return max_length; - } - /** - * Sets the valid_values. - * - * @param op the new valid_values - */ - public void setvalid_values(List<Object> vlist) { - this.valid_values = vlist; - } - /** - * Sets equal. - * - * @param e the new equal - */ - public void setEqual(Object e) { - this.equal = e; - } - /** - * Sets greater_than. - * - * @param e the new greater_than - */ - public void setGreater_than(Object e) { - this.greater_than = e; - } - /** - * Sets less_than. - * - * @param e the new less_than - */ - public void setLess_than(Object e) { - this.less_than = e; - } - /** - * Sets in_range. - * - * @param e the new in_range - */ - public void setIn_range(List<Object> e) { - this.in_range = e; - } - /** - * Sets length. - * - * @param e the length - */ - public void setLength(Object e) { - this.length = e; - } - /** - * Sets min_length. - * - * @param e the min_length - */ - public void setMin_length(Object e) { - this.min_length = e; - } - /** - * Sets max_length. - * - * @param e the max_length - */ - public void setMax_length(Object e) { - this.max_length = e; - } - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "valid_values=" + valid_values; - } -} diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Input.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Input.java index 6b2f39ec..59028492 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Input.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Input.java @@ -20,7 +20,7 @@ package org.onap.vid.asdc.beans.tosca; -import org.onap.sdc.toscaparser.api.elements.constraints.*; +import org.onap.sdc.toscaparser.api.Property; import java.util.List; import java.util.ArrayList; @@ -31,6 +31,13 @@ import java.util.ArrayList; */ public class Input { + public Input(org.onap.sdc.toscaparser.api.parameters.Input input, List<Property> properties){ + this.type = input.getType(); + this.description = input.getDescription(); + this._default = input.getDefault(); + this.inputProperties = new InputProperties(properties); + } + /** The type. */ private String type; @@ -42,6 +49,8 @@ public class Input { /** The entry schema. */ private Input entry_schema; + + private InputProperties inputProperties; /** The constraints */ private List<org.onap.sdc.toscaparser.api.elements.constraints.Constraint> constraints; @@ -142,11 +151,18 @@ public class Input { /** * Sets the entry schema. * - * @param the entry schema */ public void setentry_schema(Input s) { this.entry_schema = s; } + + public InputProperties getInputProperties() { + return inputProperties; + } + + public void setInputProperties(InputProperties inputProperties) { + this.inputProperties = inputProperties; + } /** * Sets the constraints. * diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/InputProperties.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/InputProperties.java new file mode 100644 index 00000000..bc2513ea --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/InputProperties.java @@ -0,0 +1,63 @@ +package org.onap.vid.asdc.beans.tosca; + +import org.onap.sdc.toscaparser.api.Property; + +import java.util.List; + +public class InputProperties { + private String sourceType; + private String vfModuleLabel; + private String paramName; + + public InputProperties(){ + + } + + public InputProperties(List<Property> properties) { + for(Property property: properties) { + if (property.getName().equals("source_type")) { + this.sourceType = (String)property.getValue(); + continue; + } else if (property.getName().equals("param_name")) { + this.paramName = (String)property.getValue(); + continue; + } else if (property.getName().equals("vf_module_label")) { + this.vfModuleLabel = getPropertyValueAsString(property); + continue; + } + } + } + + public String getSourceType() { + return sourceType; + } + + public void setSourceType(String sourceType) { + this.sourceType = sourceType; + } + + public String getVfModuleLabel() { + return vfModuleLabel; + } + + public void setVfModuleLabel(String vfModuleLabel) { + this.vfModuleLabel = vfModuleLabel; + } + + public String getParamName() { + return paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } + + private String getPropertyValueAsString(Property property) { + return property.getValue().toString().substring(1, property.getValue().toString().length()-1); + } + + + + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Property.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Property.java index 4bebe8b8..74b00bdf 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Property.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Property.java @@ -73,15 +73,6 @@ public class Property { } /** - * Gets the default. - * - * @return the default - */ - public String get_default() { - return _default; - } - - /** * Sets the type. * * @param type the new type @@ -109,15 +100,6 @@ public class Property { } /** - * Sets the default. - * - * @param _default the new default - */ - public void set_default(String _default) { - this._default = _default; - } - - /** * Gets the default. * * @return the default @@ -125,7 +107,7 @@ public class Property { public String getDefault() { return _default; } - + /** * Checks if is required. * diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Requirement.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Requirement.java deleted file mode 100644 index 202e88f1..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Requirement.java +++ /dev/null @@ -1,120 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.asdc.beans.tosca; - -import java.util.Collection; - -/** - * The Class Requirement. - */ -public class Requirement { - - /** The occurrences. */ - private Collection<String> occurrences; - - /** The capability. */ - private String capability; - - /** The node. */ - private String node; - - /** The relationship. */ - private String relationship; - - /** - * Instantiates a new requirement. - */ - Requirement() {} - - /** - * Gets the occurrences. - * - * @return the occurrences - */ - public Collection<String> getOccurrences() { - return occurrences; - } - - /** - * Gets the capability. - * - * @return the capability - */ - public String getCapability() { - return capability; - } - - /** - * Gets the node. - * - * @return the node - */ - public String getNode() { - return node; - } - - /** - * Gets the relationship. - * - * @return the relationship - */ - public String getRelationship() { - return relationship; - } - - /** - * Sets the occurrences. - * - * @param occurrences the new occurrences - */ - public void setOccurrences(Collection<String> occurrences) { - this.occurrences = occurrences; - } - - /** - * Sets the capability. - * - * @param capability the new capability - */ - public void setCapability(String capability) { - this.capability = capability; - } - - /** - * Sets the node. - * - * @param node the new node - */ - public void setNode(String node) { - this.node = node; - } - - /** - * Sets the relationship. - * - * @param relationship the new relationship - */ - public void setRelationship(String relationship) { - this.relationship = relationship; - } - - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/local/LocalAsdcClient.java b/vid-app-common/src/main/java/org/onap/vid/asdc/local/LocalAsdcClient.java index 7671b730..108d9c06 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/local/LocalAsdcClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/local/LocalAsdcClient.java @@ -7,23 +7,22 @@ import org.json.JSONArray; import org.json.JSONObject; import org.onap.vid.asdc.AsdcCatalogException; import org.onap.vid.asdc.AsdcClient; -import org.onap.vid.asdc.beans.Artifact; -import org.onap.vid.asdc.beans.Resource; import org.onap.vid.asdc.beans.Service; import org.onap.vid.asdc.beans.tosca.ToscaCsar; import org.onap.vid.asdc.beans.tosca.ToscaMeta; import org.onap.vid.asdc.beans.tosca.ToscaModel; +import org.onap.vid.exceptions.GenericUncheckedException; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; -import java.util.Collection; -import java.util.LinkedList; import java.util.Map; import java.util.UUID; import java.util.zip.ZipFile; @@ -34,6 +33,7 @@ import java.util.zip.ZipFile; public class LocalAsdcClient implements AsdcClient { + public static final String SERVICES = "services"; /** * The catalog. */ @@ -94,62 +94,12 @@ public class LocalAsdcClient implements AsdcClient { } /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResource(java.util.UUID) - */ - public Resource getResource(UUID uuid) throws AsdcCatalogException { - final JSONObject resource = getCatalog().getJSONObject("resources") - .getJSONObject(uuid.toString()); - return convert(resource, Resource.class); - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResources() - */ - public Collection<Resource> getResources() throws AsdcCatalogException { - final Collection<Resource> resources = new LinkedList<Resource>(); - - for (String key : getCatalog().getJSONObject("resources").keySet()) { - final JSONObject json = getCatalog().getJSONObject("resources").getJSONObject(key); - final Resource resource = convert(json, Resource.class); - resources.add(resource); - } - - return resources; - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResources(java.util.Map) - */ - public Collection<Resource> getResources(Map<String, String[]> filter) throws AsdcCatalogException { - final Collection<Resource> resources = new LinkedList<Resource>(); - - for (String key : getCatalog().getJSONObject("resources").keySet()) { - final JSONObject json = getCatalog().getJSONObject("resources").getJSONObject(key); - - boolean filterMatch = true; - - for (Map.Entry<String, String[]> entry : filter.entrySet()) { - for (int i = 0; i < entry.getValue().length; i++) { - if (!json.getString(entry.getKey()).equals(entry.getValue()[i])) { - filterMatch = false; - break; - } - } - } - - if (filterMatch) resources.add(convert(json, Resource.class)); - } - - return resources; - } - - /* (non-Javadoc) * @see org.onap.vid.asdc.AsdcClient#getService(java.util.UUID) */ public Service getService(UUID uuid) throws AsdcCatalogException { JSONObject serviceJsonObject = null; - final JSONArray categoryJsonArray = getCatalog().getJSONArray("services"); + final JSONArray categoryJsonArray = getCatalog().getJSONArray(SERVICES); for (int i = 0; i < categoryJsonArray.length(); i++) { JSONObject jsonServiceObject = categoryJsonArray.getJSONObject(i); @@ -165,132 +115,34 @@ public class LocalAsdcClient implements AsdcClient { } /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getServices() - */ - public Collection<Service> getServices() throws AsdcCatalogException { - final Collection<Service> services = new LinkedList<Service>(); - - JSONArray servicesArr = getCatalog().getJSONArray("services"); - - for (Object objService : servicesArr) { - JSONObject jsonServiceItem = (JSONObject) objService; - final Service service = convert(jsonServiceItem, Service.class); - services.add(service); - } - - return services; - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getServices(java.util.Map) - */ - public Collection<Service> getServices(Map<String, String[]> filter) throws AsdcCatalogException { - final Collection<Service> services = new LinkedList<Service>(); - - JSONArray catalogServices = catalog.getJSONArray("services"); - - for (int i = 0; i < catalogServices.length(); i++) { - - JSONObject serviceJson = catalogServices.getJSONObject(i); - - boolean filterMatch = true; - - for (Map.Entry<String, String[]> entry : filter.entrySet()) { - for (int j = 0; j < entry.getValue().length; j++) { - if (!serviceJson.getString(entry.getKey()).equals(entry.getValue()[j])) { - filterMatch = false; - break; - } - } - } - if (filterMatch) services.add(convert(serviceJson, Service.class)); - } - return services; - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResourceArtifact(java.util.UUID, java.util.UUID) - */ - public Artifact getResourceArtifact(UUID resourceUuid, UUID artifactUuid) throws AsdcCatalogException { - final JSONArray artifacts = getCatalog().getJSONObject("resources") - .getJSONObject(resourceUuid.toString()) - .getJSONArray("artifacts"); - - for (int i = 0; i < artifacts.length(); i++) { - final JSONObject artifact = artifacts.getJSONObject(i); - - if (artifact.getString("artifactUUID").equals(artifactUuid.toString())) { - return convert(artifact, Artifact.class); - } - } - - return null; - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getServiceArtifact(java.util.UUID, java.util.UUID) - */ - public Artifact getServiceArtifact(UUID serviceUuid, UUID artifactUuid) throws AsdcCatalogException { - final JSONArray artifacts = getCatalog().getJSONObject("services") - .getJSONObject(serviceUuid.toString()) - .getJSONArray("artifacts"); - - for (int i = 0; i < artifacts.length(); i++) { - final JSONObject artifact = artifacts.getJSONObject(i); - - if (artifact.getString("artifactUUID").equals(artifactUuid.toString())) { - return convert(artifact, Artifact.class); - } - } - - return null; - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResourceToscaModel(java.util.UUID) - */ - public Path getResourceToscaModel(UUID resourceUuid) throws AsdcCatalogException { - final String toscaModelURL = getCatalog().getJSONObject("resources") - .getJSONObject(resourceUuid.toString()) - .getString("toscaModelURL"); - - - final InputStream toscaModelStream = getClass().getClassLoader().getResourceAsStream(toscaModelURL); - - if (toscaModelStream == null) return null; - - return null;//getToscaModel(toscaModelStream); - } - - /* (non-Javadoc) * @see org.onap.vid.asdc.AsdcClient#getServiceToscaModel(java.util.UUID) */ public Path getServiceToscaModel(UUID serviceUuid) throws AsdcCatalogException { String toscaModelURL = null; - final JSONArray categoryJsonArray = getCatalog().getJSONArray("services"); + final JSONArray categoryJsonArray = getCatalog().getJSONArray(SERVICES); for (int i = 0; i < categoryJsonArray.length(); i++) { JSONObject jsonServiceObject = categoryJsonArray.getJSONObject(i); if (jsonServiceObject.get("uuid").equals(serviceUuid.toString())) { toscaModelURL = jsonServiceObject.getString("toscaModelURL"); - break; } } if (toscaModelURL == null) { return null; } - final InputStream toscaModelStream = getClass().getClassLoader().getResourceAsStream(toscaModelURL); - ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource(toscaModelURL).getFile()); - Path path = Paths.get(file.getPath()); - - if (toscaModelStream == null) return null; - return path; + try { + //using URLDecoder.decode to convert special characters from %XX to real character + //see https://stackoverflow.com/questions/32251251/java-classloader-getresource-with-special-characters-in-path + return Paths.get(URLDecoder.decode(file.getPath(), "UTF-8")); + } catch (UnsupportedEncodingException e) { + throw new GenericUncheckedException(e); + } } /** @@ -346,7 +198,7 @@ public class LocalAsdcClient implements AsdcClient { */ private JSONObject catalog = new JSONObject() .put("resources", new JSONObject()) - .put("services", new JSONObject()); + .put(SERVICES, new JSONObject()); /** * The mapper. diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/memory/InMemoryAsdcClient.java b/vid-app-common/src/main/java/org/onap/vid/asdc/memory/InMemoryAsdcClient.java deleted file mode 100644 index 780e82a6..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/memory/InMemoryAsdcClient.java +++ /dev/null @@ -1,372 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.asdc.memory; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.util.Collection; -import java.util.LinkedList; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; -import java.util.zip.ZipFile; - -import org.codehaus.jackson.JsonParseException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.json.JSONArray; -import org.json.JSONObject; -import org.yaml.snakeyaml.Yaml; - -import org.onap.vid.asdc.AsdcCatalogException; -import org.onap.vid.asdc.AsdcClient; -import org.onap.vid.asdc.beans.Artifact; -import org.onap.vid.asdc.beans.Resource; -import org.onap.vid.asdc.beans.Service; -import org.onap.vid.asdc.beans.tosca.ToscaCsar; -import org.onap.vid.asdc.beans.tosca.ToscaMeta; -import org.onap.vid.asdc.beans.tosca.ToscaModel; - -/** - * The Class InMemoryAsdcClient. - */ -public class InMemoryAsdcClient implements AsdcClient { - - /** The catalog. */ - private final JSONObject catalog; - - /** The mapper. */ - private final ObjectMapper mapper; - - /** - * The Class Builder. - */ - public static class Builder { - - /** The catalog. */ - private JSONObject catalog = new JSONObject() - .put("resources", new JSONObject()) - .put("services", new JSONObject()); - - /** The mapper. */ - private ObjectMapper mapper = new ObjectMapper(); - - /** - * Instantiates a new builder. - */ - public Builder() {} - - /** - * Catalog. - * - * @param catalog the catalog - * @return the builder - */ - public Builder catalog(JSONObject catalog) { - this.catalog = catalog; - return this; - } - - /** - * Mapper. - * - * @param mapper the mapper - * @return the builder - */ - public Builder mapper(ObjectMapper mapper) { - this.mapper = mapper; - return this; - } - - /** - * Builds the. - * - * @return the in memory sdc client - */ - public InMemoryAsdcClient build() { - return new InMemoryAsdcClient(this); - } - } - - /** - * Instantiates a new in memory sdc client. - * - * @param builder the builder - */ - private InMemoryAsdcClient(Builder builder) { - catalog = builder.catalog; - mapper = builder.mapper; - } - - /** - * Gets the catalog. - * - * @return the catalog - */ - private JSONObject getCatalog() { - return catalog; - } - - /** - * Gets the mapper. - * - * @return the mapper - */ - private ObjectMapper getMapper() { - return mapper; - } - - /** - * Convert. - * - * @param <T> the generic type - * @param json the json - * @param clazz the clazz - * @return the t - * @throws AsdcCatalogException the sdc catalog exception - */ - private <T> T convert(JSONObject json, Class<T> clazz) throws AsdcCatalogException { - try { - return getMapper().readValue(json.toString(), clazz); - } catch (JsonParseException e) { - throw new AsdcCatalogException("Failed to parse SDC response (bad data)", e); - } catch (JsonMappingException e) { - throw new AsdcCatalogException("Failed to map SDC response to internal VID data structure(s)", e); - } catch (IOException e) { - throw new AsdcCatalogException("Failed to get a response from SDC", e); - } - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResource(java.util.UUID) - */ - public Resource getResource(UUID uuid) throws AsdcCatalogException { - final JSONObject resource = getCatalog().getJSONObject("resources") - .getJSONObject(uuid.toString()); - return convert(resource, Resource.class); - } - - /* (non-Javadoc) - */ - public Collection<Resource> getResources() throws AsdcCatalogException { - final Collection<Resource> resources = new LinkedList<Resource> (); - - for (String key : getCatalog().getJSONObject("resources").keySet()) { - final JSONObject json = getCatalog().getJSONObject("resources").getJSONObject(key); - final Resource resource = convert(json, Resource.class); - resources.add(resource); - } - - return resources; - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResources(java.util.Map) - */ - public Collection<Resource> getResources(Map<String, String[]> filter) throws AsdcCatalogException { - final Collection<Resource> resources = new LinkedList<Resource> (); - - for (String key : getCatalog().getJSONObject("resources").keySet()) { - final JSONObject json = getCatalog().getJSONObject("resources").getJSONObject(key); - - boolean filterMatch = true; - - for (Entry<String, String[]> entry : filter.entrySet()) { - for (int i = 0; i < entry.getValue().length; i++) { - if (!json.getString(entry.getKey()).equals(entry.getValue()[i])) { - filterMatch = false; - break; - } - } - } - - if (filterMatch) resources.add(convert(json, Resource.class)); - } - - return resources; - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getService(java.util.UUID) - */ - public Service getService(UUID uuid) throws AsdcCatalogException { - final JSONObject service = getCatalog().getJSONObject("services") - .getJSONObject(uuid.toString()); - return convert(service, Service.class); - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getServices() - */ - public Collection<Service> getServices() throws AsdcCatalogException { - final Collection<Service> services = new LinkedList<Service> (); - - for (String key : getCatalog().getJSONObject("services").keySet()) { - final JSONObject json = getCatalog().getJSONObject("services").getJSONObject(key); - final Service service = convert(json, Service.class); - services.add(service); - } - - return services; - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getServices(java.util.Map) - */ - public Collection<Service> getServices(Map<String, String[]> filter) throws AsdcCatalogException { - final Collection<Service> services = new LinkedList<Service> (); - - for (String key : getCatalog().getJSONObject("services").keySet()) { - final JSONObject json = getCatalog().getJSONObject("services").getJSONObject(key); - - boolean filterMatch = true; - - for (Entry<String, String[]> entry : filter.entrySet()) { - for (int i = 0; i < entry.getValue().length; i++) { - if (!json.getString(entry.getKey()).equals(entry.getValue()[i])) { - filterMatch = false; - break; - } - } - } - - if (filterMatch) services.add(convert(json, Service.class)); - } - - return services; - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResourceArtifact(java.util.UUID, java.util.UUID) - */ - public Artifact getResourceArtifact(UUID resourceUuid, UUID artifactUuid) throws AsdcCatalogException { - final JSONArray artifacts = getCatalog().getJSONObject("resources") - .getJSONObject(resourceUuid.toString()) - .getJSONArray("artifacts"); - - for (int i = 0; i < artifacts.length(); i++) { - final JSONObject artifact = artifacts.getJSONObject(i); - - if (artifact.getString("artifactUUID").equals(artifactUuid.toString())) { - return convert(artifact, Artifact.class); - } - } - - return null; - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getServiceArtifact(java.util.UUID, java.util.UUID) - */ - public Artifact getServiceArtifact(UUID serviceUuid, UUID artifactUuid) throws AsdcCatalogException { - final JSONArray artifacts = getCatalog().getJSONObject("services") - .getJSONObject(serviceUuid.toString()) - .getJSONArray("artifacts"); - - for (int i = 0; i < artifacts.length(); i++) { - final JSONObject artifact = artifacts.getJSONObject(i); - - if (artifact.getString("artifactUUID").equals(artifactUuid.toString())) { - return convert(artifact, Artifact.class); - } - } - - return null; - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResourceToscaModel(java.util.UUID) - */ - public Path getResourceToscaModel(UUID resourceUuid) throws AsdcCatalogException { - final String toscaModelURL = getCatalog().getJSONObject("resources") - .getJSONObject(resourceUuid.toString()) - .getString("toscaModelURL"); - - - final InputStream toscaModelStream = getClass().getClassLoader().getResourceAsStream(toscaModelURL); - - if (toscaModelStream == null) return null; - - return null;//getToscaModel(toscaModelStream); - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getServiceToscaModel(java.util.UUID) - */ - public Path getServiceToscaModel(UUID serviceUuid) throws AsdcCatalogException { - final String toscaModelURL = getCatalog().getJSONObject("services") - .getJSONObject(serviceUuid.toString()) - .getString("toscaModelURL"); - - final InputStream toscaModelStream = getClass().getClassLoader().getResourceAsStream(toscaModelURL); - - if (toscaModelStream == null) return null; - - return null;//getToscaModel(toscaModelStream); - } - - /** - * Gets the tosca model. - * - * @param csarInputStream the csar input stream - * @return the tosca model - * @throws AsdcCatalogException the asdc catalog exception - */ - private ToscaCsar getToscaModel(InputStream csarInputStream) throws AsdcCatalogException { - final Path csarFile; - - try { - csarFile = Files.createTempFile("csar", ".zip"); - Files.copy(csarInputStream, csarFile, StandardCopyOption.REPLACE_EXISTING); - } catch (IOException e) { - throw new AsdcCatalogException("Caught IOException while creating CSAR", e); - } - - try (final ZipFile csar = new ZipFile(csarFile.toFile())) { - - final InputStream toscaMetaStream = csar.getInputStream(csar.getEntry("TOSCA-Metadata/TOSCA.meta")); - final ToscaMeta toscaMeta = new ToscaMeta.Builder(toscaMetaStream).build(); - final String entryDefinitions = toscaMeta.get("Entry-Definitions"); - final InputStream toscaParentEntryYamlStream = csar.getInputStream(csar.getEntry(entryDefinitions)); - - final Yaml yaml = new Yaml(); - final ToscaModel parentModel = yaml.loadAs(toscaParentEntryYamlStream, ToscaModel.class); - - final ToscaCsar.Builder csarBuilder = new ToscaCsar.Builder(parentModel); - - for (Map<String, Map<String, String>> imports : parentModel.getImports()) { - for (Entry<String, Map<String, String>> entry : imports.entrySet()) { - final InputStream toscaChildEntryYamlStream = csar.getInputStream(csar.getEntry("Definitions/" + entry.getValue().get("file"))); - final ToscaModel childModel = yaml.loadAs(toscaChildEntryYamlStream, ToscaModel.class); - csarBuilder.addVnf(childModel); - } - } - - return csarBuilder.build(); - } catch (IOException e) { - throw new AsdcCatalogException("Caught IOException while processing CSAR", e); - } - } - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParser.java b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParser.java index 6da1738a..8af1f7b0 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParser.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParser.java @@ -1,15 +1,14 @@ package org.onap.vid.asdc.parser; -import java.nio.file.Path; - -import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; import org.onap.vid.asdc.AsdcCatalogException; -import org.onap.vid.asdc.beans.tosca.ToscaCsar; import org.onap.vid.asdc.beans.Service; +import org.onap.vid.asdc.beans.tosca.ToscaCsar; import org.onap.vid.model.ServiceModel; +import java.nio.file.Path; + public interface ToscaParser{ ToscaCsar parse(Path path) throws AsdcCatalogException; - ServiceModel makeServiceModel(String uuid,Path path,Service asdcServiceMetadata) throws Exception; + ServiceModel makeServiceModel(String uuid,Path path,Service asdcServiceMetadata) throws AsdcCatalogException; }
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl.java b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl.java index 37f4b0ab..27445c0f 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl.java @@ -1,49 +1,34 @@ package org.onap.vid.asdc.parser; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Path; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.Map.Entry; -import java.util.zip.ZipFile; - import org.apache.commons.lang3.mutable.MutableBoolean; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; import org.onap.vid.asdc.AsdcCatalogException; import org.onap.vid.asdc.beans.Service; import org.onap.vid.asdc.beans.tosca.NodeTemplate; import org.onap.vid.asdc.beans.tosca.ToscaCsar; import org.onap.vid.asdc.beans.tosca.ToscaMeta; import org.onap.vid.asdc.beans.tosca.ToscaModel; -import org.onap.vid.model.ModelConstants; -import org.onap.vid.model.Network; -import org.onap.vid.model.Node; -import org.onap.vid.model.ServiceModel; -import org.onap.vid.model.VNF; +import org.onap.vid.model.*; import org.onap.vid.properties.VidProperties; -import org.springframework.beans.factory.annotation.Autowired; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.error.YAMLException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.zip.ZipFile; + public class ToscaParserImpl implements ToscaParser { /** The Constant LOG. */ static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(ToscaParserImpl.class); - @Autowired - private final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - - private static final String asdcModelNamespace = VidProperties.getAsdcModelNamespace(); - private static final String vnfTag = asdcModelNamespace + ModelConstants.VNF; - private static final String networkTag = asdcModelNamespace + ModelConstants.NETWORK; - private static final String vfModuleTag = asdcModelNamespace + ModelConstants.VF_MODULE; + private static final String ASDC_MODEL_NAMESPACE = VidProperties.getAsdcModelNamespace(); + private static final String VNF_TAG = ASDC_MODEL_NAMESPACE + ModelConstants.VNF; + private static final String NETWORK_TAG = ASDC_MODEL_NAMESPACE + ModelConstants.NETWORK; @Override @@ -60,29 +45,7 @@ public class ToscaParserImpl implements ToscaParser { final InputStream toscaParentEntryYamlStream = csar.getInputStream(csar.getEntry(entryDefinitions)); try { - final Yaml yaml = new Yaml(); - final ToscaModel parentModel = yaml.loadAs(toscaParentEntryYamlStream, ToscaModel.class); - - final ToscaCsar.Builder csarBuilder = new ToscaCsar.Builder(parentModel); - - for (Map<String, Map<String, String>> imports : parentModel.getImports()) { - LOG.debug("imports = " + imports.toString()); - for (Entry<String, Map<String, String>> entry : imports.entrySet()) { - if (entry.getValue() != null) { - String fname = entry.getValue().get("file"); - if ((fname != null) && (fname.startsWith("service") || fname.startsWith("resource"))) { - LOG.debug("fname = " + fname); - final InputStream toscaChildEntryYamlStream = csar - .getInputStream(csar.getEntry("Definitions/" + fname)); - - final ToscaModel childModel = yaml.loadAs(toscaChildEntryYamlStream, ToscaModel.class); - csarBuilder.addVnf(childModel); - } - } - } - } - - return csarBuilder.build(); + return createToscaCsar(csar, toscaParentEntryYamlStream); } catch (YAMLException e) { throw new AsdcCatalogException("Caught exception while processing TOSCA YAML", e); } @@ -91,22 +54,49 @@ public class ToscaParserImpl implements ToscaParser { } } - public ServiceModel makeServiceModel(String uuid, final Path serviceCsar,Service service ) throws AsdcCatalogException, SdcToscaParserException { + private ToscaCsar createToscaCsar(ZipFile csar, InputStream toscaParentEntryYamlStream) throws IOException { + final Yaml yaml = new Yaml(); + final ToscaModel parentModel = yaml.loadAs(toscaParentEntryYamlStream, ToscaModel.class); + + final ToscaCsar.Builder csarBuilder = new ToscaCsar.Builder(parentModel); + + for (Map<String, Map<String, String>> imports : parentModel.getImports()) { + LOG.debug("imports = " + imports.toString()); + for (Entry<String, Map<String, String>> entry : imports.entrySet()) { + if (entry.getValue() != null) { + String fname = entry.getValue().get("file"); + if ((fname != null) && (fname.startsWith("service") || fname.startsWith("resource"))) { + LOG.debug("fname = " + fname); + final InputStream toscaChildEntryYamlStream = csar + .getInputStream(csar.getEntry("Definitions/" + fname)); + + final ToscaModel childModel = yaml.loadAs(toscaChildEntryYamlStream, ToscaModel.class); + csarBuilder.addVnf(childModel); + } + } + } + } + + return csarBuilder.build(); + } + + public ServiceModel makeServiceModel(String uuid, final Path serviceCsar,Service service ) throws AsdcCatalogException { final ServiceModel serviceModel = new ServiceModel(); ToscaCsar toscaCsar = getToscaCsar(serviceCsar); String methodName = "getServices"; - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " start"); MutableBoolean isNewFlow = new MutableBoolean(false); - final Map<String, VNF> vnfs = new HashMap<String, VNF>(); - final Map<String, Network> networks = new HashMap<String, Network>(); + final Map<String, VNF> vnfs = new HashMap<>(); + final Map<String, Network> networks = new HashMap<>(); final ToscaModel asdcServiceToscaModel = toscaCsar.getParent(); serviceModel.setService(ServiceModel.extractService(asdcServiceToscaModel, service)); + populateVnfsAndNetwork(methodName, isNewFlow, vnfs, networks, asdcServiceToscaModel, serviceModel); + // If we see customization uuid under vnf or network, follow 1702 flow if (isNewFlow.getValue()) { return (getCustomizedServices(asdcServiceToscaModel, serviceModel)); @@ -147,33 +137,30 @@ public class ToscaParserImpl implements ToscaParser { } private static void populateVnfsAndNetwork(String methodName, MutableBoolean isNewFlow, final Map<String, VNF> vnfs, - final Map<String, Network> networks, final ToscaModel asdcServiceToscaModel, ServiceModel serviceModel) - throws AsdcCatalogException, SdcToscaParserException { + final Map<String, Network> networks, final ToscaModel asdcServiceToscaModel, ServiceModel serviceModel) { for (Entry<String, NodeTemplate> component : extractNodeTemplates(asdcServiceToscaModel)) { final String modelCustomizationName = component.getKey(); - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + LOG.debug(EELFLoggerDelegate.debugLogger, methodName + " model customization name: " + modelCustomizationName); final NodeTemplate nodeTemplate = component.getValue(); final String type = nodeTemplate.getType(); - if (type.startsWith(vnfTag)) { + if (type.startsWith(VNF_TAG)) { LOG.debug(EELFLoggerDelegate.debugLogger, - dateFormat.format(new Date()) + methodName + " found node template type: " + type); + methodName + " found node template type: " + type); final VNF vnf = new VNF(); vnf.extractVnf(modelCustomizationName, nodeTemplate); -// populateNodeVersionIfMissing(nodeTemplate, vnf,service); LOG.debug(EELFLoggerDelegate.debugLogger, - dateFormat.format(new Date()) + methodName + " VNF commands: " + vnf.getCommands()); + methodName + " VNF commands: " + vnf.getCommands()); vnfs.put(modelCustomizationName, vnf); isNewFlow.setValue(isNewFlow(vnf)); } // Networks - if (type.startsWith(networkTag)) { + if (type.startsWith(NETWORK_TAG)) { LOG.debug(EELFLoggerDelegate.debugLogger, - dateFormat.format(new Date()) + methodName + " found node template type: " + type); + methodName + " found node template type: " + type); final Network network = new Network(); network.extractNetwork(modelCustomizationName, nodeTemplate); -// populateNodeVersionIfMissing(nodeTemplate, network, service); isNewFlow.setValue(isNewFlow(network)); networks.put(modelCustomizationName, network); @@ -192,20 +179,8 @@ public class ToscaParserImpl implements ToscaParser { return (node.getCustomizationUuid() != null) && (node.getCustomizationUuid().length() > 0); } - private static boolean isNodeVersionMissing(Node Node) { - return Node.getVersion() == null; - } - - private static void populateNodeVersionIfMissing(final NodeTemplate nodeTemplate, final Node node, Service service) - throws AsdcCatalogException { - if (isNodeVersionMissing(node)) { - node.setVersion(service.getVersion()); - } - } - private ServiceModel getCustomizedServices(ToscaModel asdcServiceToscaModel, ServiceModel serviceModel) { String methodName = "asdcServiceToscaModel"; - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " start"); // asdcServiceToscaModel should have vf modules and vol groups populated // at this point but @@ -217,10 +192,4 @@ public class ToscaParserImpl implements ToscaParser { return (serviceModel); } - - private UUID extractUUIDFromNodeTemplate(final NodeTemplate nodeTemplate) { - return UUID.fromString(nodeTemplate.getMetadata().getUUID()); - } - - }
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl2.java b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl2.java index e75bb306..17fb29b5 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl2.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl2.java @@ -7,6 +7,7 @@ import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; import org.onap.sdc.tosca.parser.impl.FilterType; import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory; import org.onap.sdc.tosca.parser.impl.SdcTypes; +import org.onap.sdc.toscaparser.api.Group; import org.onap.sdc.toscaparser.api.*; import org.onap.sdc.toscaparser.api.elements.Metadata; import org.onap.sdc.toscaparser.api.parameters.Input; @@ -16,98 +17,208 @@ import java.util.*; import java.util.stream.Collectors; import static java.util.stream.Collectors.toMap; +import static org.onap.vid.asdc.parser.ToscaParserImpl2.Constants.VF_MODULE_LABEL; public class ToscaParserImpl2 { public class Constants { - public final static String uuid = "UUID"; - public final static String description = "description"; - public final static String serviceType = "serviceType"; - public final static String serviceRole = "serviceRole"; - public final static String ecompGeneratedNaming = "ecompGeneratedNaming"; - - public final static String customizationUUID = "customizationUUID"; - public final static String vfModuleModelVersion = "vfModuleModelVersion"; - public final static String vfModuleModelCustomizationUUID = "vfModuleModelCustomizationUUID"; - public final static String volume_group = "volume_group"; - public final static String vfModuleModelInvariantUUID = "vfModuleModelInvariantUUID"; - public final static String vfModuleModelUUID = "vfModuleModelUUID"; - public final static String invariantUUID = "invariantUUID"; - public final static String version = "version"; - public final static String name = "name"; - public final static String category = "category"; - public final static String vfModuleModelName = "vfModuleModelName"; - public final static String getInput = "get_input"; - - public final static String instantiationType = "instantiationType"; - //Instantiation Types - public final static String both = "Both"; - public final static String macro = "Macro"; - public final static String aLaCarte = "A-La-Carte"; - public final static String clientConfig = "ClientConfig"; - - - } - - public ToscaParserImpl2() { - + public final static String UUID = "UUID"; + public final static String DESCRIPTION = "description"; + public final static String SERVICE_TYPE = "serviceType"; + public final static String SERVICE_ROLE = "serviceRole"; + public final static String ECOMP_GENERATED_NAMING = "ecompGeneratedNaming"; + + public final static String CUSTOMIZATION_UUID = "customizationUUID"; + public final static String VF_MODULE_MODEL_VERSION = "vfModuleModelVersion"; + public final static String VF_MODULE_MODEL_CUSTOMIZATION_UUID = "vfModuleModelCustomizationUUID"; + public final static String VOLUME_GROUP = "volume_group"; + public final static String VF_MODULE_MODEL_INVARIANT_UUID = "vfModuleModelInvariantUUID"; + public final static String VF_MODULE_MODEL_UUID = "vfModuleModelUUID"; + public final static String INVARIANT_UUID = "invariantUUID"; + public final static String VERSION = "version"; + public final static String NAME = "name"; + public final static String CATEGORY = "category"; + public final static String VF_MODULE_MODEL_NAME = "vfModuleModelName"; + public final static String GET_INPUT = "get_input"; + public final static String TYPE = "type"; + + public final static String INSTANTIATION_TYPE = "instantiationType"; + //instantiation type + public final static String BOTH = "Both"; + public final static String MACRO = "Macro"; + public final static String A_LA_CARTE = "A-La-Carte"; + public final static String CLIENT_CONFIG = "ClientConfig"; + + //group properties + public final static String MIN_VF_MODULE_INSTANCES = "min_vf_module_instances"; + public final static String MAX_VF_MODULE_INSTANCES = "max_vf_module_instances"; + public final static String INITIAL_COUNT = "initial_count"; + public final static String VF_MODULE_LABEL = "vf_module_label"; + + //collection resource properties + public final static String SUBCATEGORY = "subcategory"; + public final static String RESOURCE_VENDOR = "resourceVendor"; + public final static String RESOURCE_VENDOR_RELEASE = "resourceVendorRelease"; + public final static String RESOURCE_VENDOR_MODEL_NUMBER = "resourceVendorModelNumber"; + public final static String ORG_OPENECOMP_GROUPS_NETWORK_COLLECTION = "org.openecomp.groups.NetworkCollection"; + public final static String NETWORK_COLLECTION_FUNCTION = "network_collection_function"; + public final static String NETWORK_COLLECTION_DESCRIPTION = "network_collection_description"; + + //vfc instance group properties + public final static String VFC_INSTANCE_GROUP_TYPE = "org.openecomp.groups.VfcInstanceGroup"; + public final static String VFC_PARENT_PORT_ROLE = "vfc_parent_port_role"; + public final static String SUBINTERFACE_ROLE = "subinterface_role"; + public final static String VFC_INSTANCE_GROUP_FUNCTION = "vfc_instance_group_function"; } + + public ToscaParserImpl2() {} - public ServiceModel makeServiceModel(Path path, Service asdcServiceMetadata) throws Exception { + public ServiceModel makeServiceModel(Path path, Service asdcServiceMetadata) throws SdcToscaParserException { ServiceModel serviceModel = new ServiceModel(); SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); ISdcCsarHelper sdcCsarHelper = factory.getSdcCsarHelper(path.toFile().getAbsolutePath(),false); - serviceModel.setService(extractServiceFromCsar(asdcServiceMetadata, sdcCsarHelper)); + serviceModel.setService(extractServiceFromCsar(asdcServiceMetadata, sdcCsarHelper)); serviceModel.setVolumeGroups(extractVolumeGroups(sdcCsarHelper)); serviceModel.setVfModules(extractVfModuleFromCsar(sdcCsarHelper)); - serviceModel.setVnfs(extractVnfsFromCsar(serviceModel,sdcCsarHelper)); + serviceModel.setVnfs(extractVnfsFromCsar(sdcCsarHelper)); serviceModel.setConfigurations(extractPortMirroringConfigFromCsar(sdcCsarHelper)); serviceModel.setServiceProxies(extractServiceProxyFromCsar(sdcCsarHelper)); serviceModel.setNetworks(extractNetworksFromCsar(sdcCsarHelper)); serviceModel.setPnfs(extractPnfsFromCsar(sdcCsarHelper)); + serviceModel.setCollectionResource(extractCRFromCsar(sdcCsarHelper)); return serviceModel; } + + private org.onap.vid.model.Service extractServiceFromCsar(Service asdcServiceMetadata, ISdcCsarHelper csarHelper) throws SdcToscaParserException { org.onap.vid.model.Service service = new org.onap.vid.model.Service(); - service.setName(csarHelper.getServiceMetadata().getValue(Constants.name)); - service.setCategory(csarHelper.getServiceMetadata().getValue(Constants.category)); - service.setInvariantUuid(csarHelper.getServiceMetadata().getValue(Constants.invariantUUID)); - service.setUuid(csarHelper.getServiceMetadata().getValue(Constants.uuid)); + service.setName(csarHelper.getServiceMetadata().getValue(Constants.NAME)); + service.setCategory(csarHelper.getServiceMetadata().getValue(Constants.CATEGORY)); + service.setInvariantUuid(csarHelper.getServiceMetadata().getValue(Constants.INVARIANT_UUID)); + service.setUuid(csarHelper.getServiceMetadata().getValue(Constants.UUID)); service.setVersion(asdcServiceMetadata.getVersion()); - service.setDescription(csarHelper.getServiceMetadata().getValue(Constants.description)); - service.setInputs(inputsListToInputsMap(csarHelper.getServiceInputs())); - service.setServiceEcompNaming(csarHelper.getServiceMetadata().getValue(Constants.ecompGeneratedNaming)); - service.setServiceType(csarHelper.getServiceMetadata().getValue(Constants.serviceType)); - service.setServiceRole(csarHelper.getServiceMetadata().getValue(Constants.serviceRole)); + service.setDescription(csarHelper.getServiceMetadata().getValue(Constants.DESCRIPTION)); + service.setInputs(inputsListToInputsMap(csarHelper.getInputsWithAnnotations())); + service.setServiceEcompNaming(csarHelper.getServiceMetadata().getValue(Constants.ECOMP_GENERATED_NAMING)); + service.setServiceType(csarHelper.getServiceMetadata().getValue(Constants.SERVICE_TYPE)); + service.setServiceRole(csarHelper.getServiceMetadata().getValue(Constants.SERVICE_ROLE)); service.setInstantiationType(validateInstantiationType(csarHelper)); return service; } - - private Map<String, VNF> extractVnfsFromCsar(ServiceModel serviceModel,ISdcCsarHelper csarHelper) { + private Map<String,CR> extractCRFromCsar(ISdcCsarHelper sdcCsarHelper) { + List<NodeTemplate> nodeTemplates = sdcCsarHelper.getServiceNodeTemplates(); + Map<String, CR> collectionResourceMap = new HashMap<>(); + + for(NodeTemplate nodeTemplate: nodeTemplates){ + if(nodeTemplate.getMetaData().getValue(Constants.TYPE).equals(SdcTypes.CR.getValue())) { + CR cr = new CR(); + populateCrFromNodeTemplate(nodeTemplate, sdcCsarHelper, cr); + collectionResourceMap.put(nodeTemplate.getName(), cr); + } + } + + return collectionResourceMap; + } + + private void populateCrFromNodeTemplate(NodeTemplate nodeTemplate, ISdcCsarHelper sdcCsarHelper, CR cr) { + populateNodeFromNodeTemplate(nodeTemplate, sdcCsarHelper, cr); + cr.setCustomizationUUID(nodeTemplate.getMetaData().getValue(Constants.CUSTOMIZATION_UUID)); + cr.setCategory(nodeTemplate.getMetaData().getValue(Constants.CATEGORY)); + cr.setSubcategory(nodeTemplate.getMetaData().getValue(Constants.SUBCATEGORY)); + cr.setResourceVendor(nodeTemplate.getMetaData().getValue(Constants.RESOURCE_VENDOR)); + cr.setResourceVendorRelease(nodeTemplate.getMetaData().getValue(Constants.RESOURCE_VENDOR_RELEASE)); + cr.setResourceVendorModelNumber(nodeTemplate.getMetaData().getValue(Constants.RESOURCE_VENDOR_MODEL_NUMBER)); + cr.setNetworksCollection(getNetworksCollectionMapFromGroupsList(sdcCsarHelper, nodeTemplate)); + } + + private Map<String, NetworkCollection> getNetworksCollectionMapFromGroupsList(ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate) { + List<Group> groups = sdcCsarHelper.getGroupsOfOriginOfNodeTemplateByToscaGroupType(nodeTemplate, Constants.ORG_OPENECOMP_GROUPS_NETWORK_COLLECTION); + Map<String, NetworkCollection> networksCollectionMap = new HashMap<String, NetworkCollection>(); + for(Group group: groups){ + networksCollectionMap.put(group.getName(), populateCollectionNetworkFromGroup(group, nodeTemplate)); + } + return networksCollectionMap; + } + + private NetworkCollection populateCollectionNetworkFromGroup(Group group, NodeTemplate nodeTemplate) { + NetworkCollection networkCollection = new NetworkCollection(); + networkCollection.setUuid(group.getMetadata().getValue(Constants.UUID)); + networkCollection.setInvariantUuid(group.getMetadata().getValue(Constants.INVARIANT_UUID)); + networkCollection.setVersion(group.getMetadata().getValue(Constants.VERSION)); + networkCollection.setName(group.getMetadata().getValue(Constants.NAME)); + extractPropertiesOfCollectionNetworkFromCsar(group, nodeTemplate, networkCollection); + + return networkCollection; + } + + private void extractPropertiesOfCollectionNetworkFromCsar(Group group, NodeTemplate nodeTemplate, NetworkCollection networkCollection) { + LinkedHashMap<String, Property> properties = group.getProperties(); + Map<String, Property> nodeTemplateProperties = nodeTemplate.getProperties(); + + String networkCollectionFunction = (String)((Map)(properties.get(Constants.NETWORK_COLLECTION_FUNCTION).getValue())).get(Constants.GET_INPUT); + String networkCollectionDescription = (String)((Map)(properties.get(Constants.NETWORK_COLLECTION_DESCRIPTION).getValue())).get(Constants.GET_INPUT); + + networkCollection.getNetworkCollectionProperties().setNetworkCollectionDescription((String)nodeTemplateProperties.get(networkCollectionDescription).getValue()); + networkCollection.getNetworkCollectionProperties().setNetworkCollectionFunction((String)nodeTemplateProperties.get(networkCollectionFunction).getValue()); + } + + + private Map<String, VNF> extractVnfsFromCsar(ISdcCsarHelper csarHelper) { List<NodeTemplate> nodeTemplates = csarHelper.getServiceVfList(); Map<String, VNF> vnfsMaps = new HashMap<String, VNF>(); for (NodeTemplate nodeTemplate : nodeTemplates) { VNF vnf = new VNF(); populateNodeFromNodeTemplate(nodeTemplate, csarHelper, vnf); - vnf.setModelCustomizationName(nodeTemplate.getName()); - Map<String, VfModule> vfModuleHashMap = getVfModulesFromVF(csarHelper, vnf.getCustomizationUuid()); - vnf.setVfModules(vfModuleHashMap); - - Map<String, VolumeGroup> volumeGroupMap = getVolumeGroupsFromVF(csarHelper, vnf.getCustomizationUuid()); - vnf.setVolumeGroups(volumeGroupMap); + vnf.setVfModules(getVfModulesFromVF(csarHelper, vnf.getCustomizationUuid())); + vnf.setVolumeGroups(getVolumeGroupsFromVF(csarHelper, vnf.getCustomizationUuid())); + vnf.setVfcInstanceGroups(getVfcInstanceGroup(csarHelper, nodeTemplate)); vnfsMaps.put(nodeTemplate.getName(), vnf); } return vnfsMaps; } + private Map<String,VfcInstanceGroup> getVfcInstanceGroup(ISdcCsarHelper csarHelper, NodeTemplate nodeTemplate) { + List<Group> vfcList = csarHelper.getGroupsOfOriginOfNodeTemplateByToscaGroupType(nodeTemplate, Constants.VFC_INSTANCE_GROUP_TYPE); + return vfcList.stream() + .collect(toMap(Group::getName, group -> populateVfcInstanceGroupFromGroup(group, csarHelper, nodeTemplate))); + } + + private VfcInstanceGroup populateVfcInstanceGroupFromGroup(Group group, ISdcCsarHelper csarHelper, NodeTemplate nodeTemplate) { + VfcInstanceGroup vfcInstanceGroup = new VfcInstanceGroup(); + vfcInstanceGroup.setUuid(group.getMetadata().getValue(Constants.UUID)); + vfcInstanceGroup.setInvariantUuid(group.getMetadata().getValue(Constants.INVARIANT_UUID)); + vfcInstanceGroup.setVersion(group.getMetadata().getValue(Constants.VERSION)); + vfcInstanceGroup.setName(group.getMetadata().getValue(Constants.NAME)); + vfcInstanceGroup.setVfcInstanceGroupProperties(getVfcPropertiesFromGroup(nodeTemplate, group)); + + return vfcInstanceGroup; + + } + + private VfcInstanceGroupProperties getVfcPropertiesFromGroup(NodeTemplate nodeTemplate, Group group) { + VfcInstanceGroupProperties vfcInstanceGroupProperties = new VfcInstanceGroupProperties(); + vfcInstanceGroupProperties.setVfcParentPortRole((String) group.getProperties().get(Constants.VFC_PARENT_PORT_ROLE).getValue()); + vfcInstanceGroupProperties.setSubinterfaceRole((String) group.getProperties().get(Constants.SUBINTERFACE_ROLE).getValue()); + + String networkCollectionFunction = (String)((Map)(group.getProperties().get(Constants.NETWORK_COLLECTION_FUNCTION).getValue())).get(Constants.GET_INPUT); + String vfcInstanceGroupFunction = (String)((Map)(group.getProperties().get(Constants.VFC_INSTANCE_GROUP_FUNCTION).getValue())).get(Constants.GET_INPUT); + + if(nodeTemplate.getProperties().get(networkCollectionFunction) != null) + vfcInstanceGroupProperties.setNetworkCollectionFunction((String) nodeTemplate.getProperties().get(networkCollectionFunction).getValue()); + if(nodeTemplate.getProperties().get(vfcInstanceGroupFunction) != null) + vfcInstanceGroupProperties.setVfcInstanceGroupFunction((String) nodeTemplate.getProperties().get(vfcInstanceGroupFunction).getValue()); + + return vfcInstanceGroupProperties; + } + private Map<String, PortMirroringConfig> extractPortMirroringConfigFromCsar(ISdcCsarHelper csarHelper) { List<NodeTemplate> nodeTemplates = csarHelper.getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION); Map<String, PortMirroringConfig> configMaps = new HashMap<>(); @@ -175,18 +286,18 @@ public class ToscaParserImpl2 { Map<String, VfModule> getVfModulesFromVF(ISdcCsarHelper csarHelper, String vfUuid) { List<Group> vfModulesByVf = csarHelper.getVfModulesByVf(vfUuid); return vfModulesByVf.stream() - .collect(toMap(Group::getName, this::populateVfModuleFromGroup)); + .collect(toMap(Group::getName, group -> populateVfModuleFromGroup(group, csarHelper))); } Map<String, VolumeGroup> getVolumeGroupsFromVF(ISdcCsarHelper csarHelper, String vfCustomizationUuid) { List<Group> vfModulesByVf = csarHelper.getVfModulesByVf(vfCustomizationUuid); return vfModulesByVf.stream() .filter((group -> isVolumeGroup(group))) - .collect(toMap(Group::getName, this::populateVolumeGroupFromGroup)); + .collect(toMap(Group::getName, group -> populateVolumeGroupFromGroup(group, csarHelper))); } private static Boolean isVolumeGroup(Group group) { - return Boolean.valueOf(group.getPropertyValue(Constants.volume_group).toString()); + return Boolean.valueOf(group.getPropertyValue(Constants.VOLUME_GROUP).toString()); } private Map<String, Network> extractNetworksFromCsar(ISdcCsarHelper csarHelper) { @@ -220,7 +331,7 @@ public class ToscaParserImpl2 { for (NodeTemplate nodeTemplate : serviceVfList) { Map<String, VfModule> nodeTemplateVfModule = - getVfModulesFromVF(csarHelper, nodeTemplate.getMetaData().getValue(Constants.customizationUUID)); + getVfModulesFromVF(csarHelper, nodeTemplate.getMetaData().getValue(Constants.CUSTOMIZATION_UUID)); vfModuleHashMap.putAll(nodeTemplateVfModule); } return vfModuleHashMap; @@ -239,60 +350,109 @@ public class ToscaParserImpl2 { private Map<String, org.onap.vid.asdc.beans.tosca.Input> inputsListToInputsMap(List<org.onap.sdc.toscaparser.api.parameters.Input> inputList) { Map<String, org.onap.vid.asdc.beans.tosca.Input> inputs = new HashMap<>(); for (org.onap.sdc.toscaparser.api.parameters.Input input : inputList) { - inputs.put(input.getName(), convertInput(input, new org.onap.vid.asdc.beans.tosca.Input(), null)); + //Set only inputs without annotation to the service level + if(input.getAnnotations() == null) + inputs.put(input.getName(), convertInput(input, new org.onap.vid.asdc.beans.tosca.Input(), null)); } return inputs; } private Node populateNodeFromNodeTemplate(NodeTemplate nodeTemplate, ISdcCsarHelper csarHelper, Node newNode) { newNode.setCustomizationUuid(csarHelper.getNodeTemplateCustomizationUuid(nodeTemplate)); - newNode.setDescription(nodeTemplate.getMetaData().getValue(Constants.description)); - newNode.setInvariantUuid(nodeTemplate.getMetaData().getValue(Constants.invariantUUID)); - newNode.setUuid(nodeTemplate.getMetaData().getValue(Constants.uuid)); - newNode.setName(nodeTemplate.getMetaData().getValue(Constants.name)); - newNode.setVersion(nodeTemplate.getMetaData().getValue(Constants.version)); + newNode.setDescription(nodeTemplate.getMetaData().getValue(Constants.DESCRIPTION)); + newNode.setInvariantUuid(nodeTemplate.getMetaData().getValue(Constants.INVARIANT_UUID)); + newNode.setUuid(nodeTemplate.getMetaData().getValue(Constants.UUID)); + newNode.setName(nodeTemplate.getMetaData().getValue(Constants.NAME)); + newNode.setVersion(nodeTemplate.getMetaData().getValue(Constants.VERSION)); newNode.setInputs(extractInputsAndCommandsForNodeTemplate(nodeTemplate, csarHelper, newNode)); - newNode.setType(nodeTemplate.getMetaData().getValue("type")); + newNode.setType(nodeTemplate.getMetaData().getValue(Constants.TYPE)); Map<String, String> propertiesMap = setPropertiesOfVnf(nodeTemplate.getPropertiesObjects()); newNode.setProperties(propertiesMap); return newNode; } - private VfModule populateVfModuleFromGroup(Group group){ + private VfModule populateVfModuleFromGroup(Group group, ISdcCsarHelper csarHelper){ VfModule vfModule = new VfModule(); - - vfModule.setVersion(group.getMetadata().getValue(Constants.vfModuleModelVersion)); - vfModule.setCustomizationUuid(group.getMetadata().getValue(Constants.vfModuleModelCustomizationUUID)); - vfModule.setModelCustomizationName(group.getMetadata().getValue(Constants.vfModuleModelName)); - vfModule.setName(group.getMetadata().getValue(Constants.vfModuleModelName)); + extractBasicPropertiesForGroup(vfModule, group, csarHelper); vfModule.setVolumeGroupAllowed(isVolumeGroup(group)); - vfModule.setDescription(group.getDescription()); - vfModule.setInvariantUuid(group.getMetadata().getValue(Constants.vfModuleModelInvariantUUID)); - vfModule.setUuid(group.getMetadata().getValue(Constants.vfModuleModelUUID)); - vfModule.setProperties(group.getProperties()); return vfModule; } - private VolumeGroup populateVolumeGroupFromGroup(Group group){ + private VolumeGroup populateVolumeGroupFromGroup(Group group, ISdcCsarHelper csarHelper){ VolumeGroup volumeGroup = new VolumeGroup(); - volumeGroup.setDescription(group.getDescription()); - volumeGroup.setInvariantUuid(group.getMetadata().getValue(Constants.vfModuleModelInvariantUUID)); - volumeGroup.setName(group.getMetadata().getValue(Constants.vfModuleModelName)); - volumeGroup.setModelCustomizationName(group.getMetadata().getValue(Constants.vfModuleModelName)); - volumeGroup.setVersion(group.getMetadata().getValue(Constants.vfModuleModelVersion)); - volumeGroup.setUuid(group.getMetadata().getValue(Constants.vfModuleModelUUID)); - volumeGroup.setCustomizationUuid(group.getMetadata().getValue(Constants.vfModuleModelCustomizationUUID)); - + extractBasicPropertiesForGroup(volumeGroup, group, csarHelper); return volumeGroup; } + private void extractBasicPropertiesForGroup(org.onap.vid.model.Group newGroup, Group group, ISdcCsarHelper csarHelper) { + newGroup.setDescription(group.getDescription()); + newGroup.setVersion(group.getMetadata().getValue(Constants.VF_MODULE_MODEL_VERSION)); + newGroup.setCustomizationUuid(group.getMetadata().getValue(Constants.VF_MODULE_MODEL_CUSTOMIZATION_UUID)); + newGroup.setModelCustomizationName(group.getMetadata().getValue(Constants.VF_MODULE_MODEL_NAME)); + newGroup.setName(group.getMetadata().getValue(Constants.VF_MODULE_MODEL_NAME)); + newGroup.setUuid(group.getMetadata().getValue(Constants.VF_MODULE_MODEL_UUID)); + newGroup.setInvariantUuid(group.getMetadata().getValue(Constants.VF_MODULE_MODEL_INVARIANT_UUID)); + newGroup.setProperties(extractVfModuleProperties(group, csarHelper)); + newGroup.setInputs(extractVfInputsFromCsarByAnnotation(csarHelper, newGroup)); + } + + + private Map<String,org.onap.vid.asdc.beans.tosca.Input> extractVfInputsFromCsarByAnnotation(ISdcCsarHelper csarHelper, org.onap.vid.model.Group group) { + Map<String, org.onap.vid.asdc.beans.tosca.Input> inputMap = new HashMap<>(); + if(group.getProperties().getVfModuleLabel() != null){ + List<Input> inputsList = csarHelper.getInputsWithAnnotations(); + for(Input input: inputsList){ + if(input.getAnnotations() != null){ + List<Property> annotationProperties = input.getAnnotations().get("source").getProperties(); + if(isInputMatchesToGroup(annotationProperties, group)){ + inputMap.put(input.getName(), new org.onap.vid.asdc.beans.tosca.Input(input ,annotationProperties)); + } + } + } + } + return inputMap; + } + + + private boolean isInputMatchesToGroup(List<Property> annotationProperties, org.onap.vid.model.Group group){ + for(Property property: annotationProperties){ + if(property.getName().equals(VF_MODULE_LABEL)){ + return getPropertyValueAsString(property).equals(group.getProperties().getVfModuleLabel()); + } + } + return false; + } + + public String getPropertyValueAsString(Property property) { + return removeSquareBrackets(property.getValue().toString()); + } + + private String removeSquareBrackets(String stringWithSquareBrackets){ + return stringWithSquareBrackets.substring(1, stringWithSquareBrackets.length()-1); + } + + private GroupProperties extractVfModuleProperties(Group group, ISdcCsarHelper csarHelper){ + GroupProperties vfModuleProperties = new GroupProperties(); + if(csarHelper.getGroupPropertyAsObject(group, Constants.MIN_VF_MODULE_INSTANCES) != null) + vfModuleProperties.setMinCountInstances((Integer)csarHelper.getGroupPropertyAsObject(group, Constants.MIN_VF_MODULE_INSTANCES)); + if(csarHelper.getGroupPropertyAsObject(group, Constants.MAX_VF_MODULE_INSTANCES) != null) + vfModuleProperties.setMaxCountInstances((Integer)csarHelper.getGroupPropertyAsObject(group, Constants.MAX_VF_MODULE_INSTANCES)); + if(csarHelper.getGroupPropertyAsObject(group, Constants.INITIAL_COUNT) != null) + vfModuleProperties.setInitialCount((Integer)csarHelper.getGroupPropertyAsObject(group, Constants.INITIAL_COUNT)); + if(csarHelper.getGroupPropertyAsObject(group, VF_MODULE_LABEL) != null) + vfModuleProperties.setVfModuleLabel((String) csarHelper.getGroupPropertyAsObject(group, VF_MODULE_LABEL)); + return vfModuleProperties; + } + + + private Map<String, org.onap.vid.asdc.beans.tosca.Input> extractInputsAndCommandsForNodeTemplate(NodeTemplate nodeTemplate, ISdcCsarHelper csarHelper, Node newNode){ Map<String, org.onap.vid.asdc.beans.tosca.Input> inputMap = new HashMap<>(); Map<String, CommandProperty> commandPropertyMap = new HashMap<>(); List<Input> inputs = csarHelper.getServiceInputs(); - Map<String, String> properties = csarHelper.filterNodeTemplatePropertiesByValue(nodeTemplate, FilterType.CONTAINS, Constants.getInput); + Map<String, String> properties = csarHelper.filterNodeTemplatePropertiesByValue(nodeTemplate, FilterType.CONTAINS, Constants.GET_INPUT); for (Map.Entry<String, String> property : properties.entrySet()) { String inputKey = property.getValue(); String key = extractInputValue(inputKey); @@ -337,7 +497,7 @@ public class ToscaParserImpl2 { private CommandProperty extractCommands(String displayName, String inputName){ CommandProperty commandProperty = new CommandProperty(); commandProperty.setDisplayName(displayName); - commandProperty.setCommand(Constants.getInput); + commandProperty.setCommand(Constants.GET_INPUT); commandProperty.setInputName(inputName); return commandProperty; } @@ -345,19 +505,23 @@ public class ToscaParserImpl2 { private Map<String, String> setPropertiesOfVnf(List<Property> properties) { Map<String, String> propertiesMap = new HashMap<String, String>(); for (Property property : properties) { + //special handling to necessary sub-property "ecomp_generated_naming" + if(property.getName().equals("nf_naming")){ + propertiesMap.put(removeSquareBrackets(((LinkedHashMap)(property.getValue())).keySet().toString()) ,((LinkedHashMap)(property.getValue())).get("ecomp_generated_naming").toString()); + } propertiesMap.put(property.getName(), property.getValue().toString()); } return propertiesMap; } private String validateInstantiationType(ISdcCsarHelper csarHelper){ - String instantiationType = csarHelper.getServiceMetadata().getValue(Constants.instantiationType); - String validatedInstantiationType = Constants.clientConfig; + String instantiationType = csarHelper.getServiceMetadata().getValue(Constants.INSTANTIATION_TYPE); + String validatedInstantiationType = Constants.CLIENT_CONFIG; if(instantiationType != null && !instantiationType.isEmpty()){ - if(instantiationType.equalsIgnoreCase(Constants.macro) || instantiationType.equalsIgnoreCase(Constants.both)) - validatedInstantiationType = Constants.macro; - else if(instantiationType.equalsIgnoreCase(Constants.aLaCarte)) - validatedInstantiationType = Constants.aLaCarte; + if(instantiationType.equalsIgnoreCase(Constants.MACRO) || instantiationType.equalsIgnoreCase(Constants.BOTH)) + validatedInstantiationType = Constants.MACRO; + else if(instantiationType.equalsIgnoreCase(Constants.A_LA_CARTE)) + validatedInstantiationType = Constants.A_LA_CARTE; } return validatedInstantiationType; } diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/rest/RestfulAsdcClient.java b/vid-app-common/src/main/java/org/onap/vid/asdc/rest/RestfulAsdcClient.java index 7ac0fa39..5dd0f4cc 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/rest/RestfulAsdcClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/rest/RestfulAsdcClient.java @@ -20,43 +20,35 @@ package org.onap.vid.asdc.rest; +import com.att.eelf.configuration.EELFLogger; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.asdc.AsdcCatalogException; import org.onap.vid.asdc.AsdcClient; -import org.onap.vid.asdc.beans.Artifact; -import org.onap.vid.asdc.beans.Resource; import org.onap.vid.asdc.beans.Service; -import org.onap.vid.asdc.parser.ToscaParserImpl; import org.onap.vid.model.ModelConstants; import org.onap.vid.properties.VidProperties; +import org.onap.vid.utils.Logging; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.http.HttpMethod; -import javax.ws.rs.NotFoundException; import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ResponseProcessingException; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.Response; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Collection; import java.util.Collections; -import java.util.Map; -import java.util.Map.Entry; import java.util.UUID; -import static org.onap.vid.utils.Logging.getHttpServletRequest; -import static org.onap.vid.utils.Logging.requestIdHeaderKey; +import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; /** * The Class RestfulAsdcClient. */ @@ -122,10 +114,7 @@ public class RestfulAsdcClient implements AsdcClient { */ static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(RestfulAsdcClient.class); - /** - * The Constant dateFormat. - */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + final private static EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("asdc"); /** * The client. @@ -147,8 +136,6 @@ public class RestfulAsdcClient implements AsdcClient { */ private final String auth; - ToscaParserImpl p = new ToscaParserImpl(); - /** * Instantiates a new restful asdc client. * @@ -160,8 +147,8 @@ public class RestfulAsdcClient implements AsdcClient { auth = builder.auth; commonHeaders = new MultivaluedHashMap<String, Object>(); - commonHeaders.put("Authorization", Collections.singletonList((Object) (auth))); commonHeaders.put("X-ECOMP-InstanceID", Collections.singletonList((Object) (SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME)))); + commonHeaders.put("Authorization", Collections.singletonList((Object) (auth))); } private Path createTmpFile(InputStream csarInputStream) throws AsdcCatalogException { @@ -185,252 +172,32 @@ public class RestfulAsdcClient implements AsdcClient { } /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResource(java.util.UUID) - */ - public Resource getResource(UUID uuid) throws AsdcCatalogException { - - String path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_RESOURCE_API_PATH, ModelConstants.DEFAULT_ASDC_RESOURCE_API_PATH); - try { - return getClient() - .target(uri) - .path(path + "/" + uuid.toString() + "/metadata") - .request(MediaType.APPLICATION_JSON_TYPE) - .headers(commonHeaders) - .header("Content-Type", MediaType.APPLICATION_JSON) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .get(Resource.class); - } catch (ResponseProcessingException e) { - //Couldn't convert response to Java type - throw new AsdcCatalogException("SDC response could not be processed", e); - } catch (ProcessingException e) { - //IO problems during request - throw new AsdcCatalogException("Failed to get a response from SDC service", e); - } catch (WebApplicationException e) { - //Web service returned data, but the response status wasn't a good one (i.e. non 2xx) - throw new AsdcCatalogException(e); - } - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResourceArtifact(java.util.UUID, java.util.UUID) - */ - public Artifact getResourceArtifact(UUID resourceUuid, UUID artifactUuid) throws AsdcCatalogException { - String path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_RESOURCE_API_PATH, ModelConstants.DEFAULT_ASDC_RESOURCE_API_PATH); - try { - return getClient() - .target(uri) - .path(path + "/" + resourceUuid + "/artifacts/" + artifactUuid) - .request(MediaType.APPLICATION_JSON_TYPE) - .headers(commonHeaders) - .header("Content-Type", MediaType.APPLICATION_JSON) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .get(Artifact.class); - } catch (ResponseProcessingException e) { - //Couldn't convert response to Java type - throw new AsdcCatalogException("SDC response could not be processed", e); - } catch (ProcessingException e) { - //IO problems during request - throw new AsdcCatalogException("Failed to get a response from SDC service", e); - } catch (WebApplicationException e) { - //Web service returned data, but the response status wasn't a good one (i.e. non 2xx) - throw new AsdcCatalogException(e); - } - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResources() - */ - public Collection<Resource> getResources() throws AsdcCatalogException { - String path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_RESOURCE_API_PATH, ModelConstants.DEFAULT_ASDC_RESOURCE_API_PATH); - try { - return getClient() - .target(uri) - .path(path) - .request(MediaType.APPLICATION_JSON_TYPE) - .headers(commonHeaders) - .header("Content-Type", MediaType.APPLICATION_JSON) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .get(new GenericType<Collection<Resource>>() { - }); - } catch (ResponseProcessingException e) { - //Couldn't convert response to Java type - throw new AsdcCatalogException("SDC response could not be processed", e); - } catch (ProcessingException e) { - //IO problems during request - throw new AsdcCatalogException("Failed to get a response from SDC service", e); - } catch (WebApplicationException e) { - //Web service returned data, but the response status wasn't a good one (i.e. non 2xx) - throw new AsdcCatalogException(e); - } - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResources(java.util.Map) - */ - public Collection<Resource> getResources(Map<String, String[]> filter) throws AsdcCatalogException { - String path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_RESOURCE_API_PATH, ModelConstants.DEFAULT_ASDC_RESOURCE_API_PATH); - WebTarget target = getClient() - .target(uri) - .path(path); - - for (Entry<String, String[]> filterEntry : filter.entrySet()) { - target = target.queryParam(filterEntry.getKey(), (Object[]) filterEntry.getValue()); - } - - try { - return target.request() - .accept(MediaType.APPLICATION_JSON_TYPE) - .headers(commonHeaders) - .header("Content-Type", MediaType.APPLICATION_JSON) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .get(new GenericType<Collection<Resource>>() { - }); - } catch (ResponseProcessingException e) { - //Couldn't convert response to Java type - throw new AsdcCatalogException("SDC response could not be processed", e); - } catch (ProcessingException e) { - //IO problems during request - throw new AsdcCatalogException("Failed to get a response from SDC service", e); - } catch (NotFoundException e) { - throw e; - } catch (WebApplicationException e) { - //Web service returned data, but the response status wasn't a good one (i.e. non 2xx) - throw new AsdcCatalogException(e); - } - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getResourceToscaModel(java.util.UUID) - */ - public Path getResourceToscaModel(UUID resourceUuid) throws AsdcCatalogException { - String path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_RESOURCE_API_PATH, ModelConstants.DEFAULT_ASDC_RESOURCE_API_PATH); - try (final InputStream csarInputStream = (InputStream) getClient() - .target(uri) - .path(path + "/" + resourceUuid + "/toscaModel") - .request(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .headers(commonHeaders) - .header("Content-Type", MediaType.APPLICATION_OCTET_STREAM) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .get(InputStream.class)) { - - return getToscaCsar(csarInputStream); - } catch (IOException e) { - throw new AsdcCatalogException("Failed to retrieve resource TOSCA model from SDC", e); - } - } - - /* (non-Javadoc) * @see org.onap.vid.asdc.AsdcClient#getService(java.util.UUID) */ public Service getService(UUID uuid) throws AsdcCatalogException { - String path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_SVC_API_PATH, ModelConstants.DEFAULT_ASDC_SVC_API_PATH); + String path = VidProperties.getPropertyWithDefault( + ModelConstants.ASDC_SVC_API_PATH, + ModelConstants.DEFAULT_ASDC_SVC_API_PATH); + + String url = uri+path + "/" + uuid.toString() + "/metadata"; + Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); try { - return getClient() + Response response = getClient() .target(uri) .path(path + "/" + uuid.toString() + "/metadata") .request(MediaType.APPLICATION_JSON) .headers(commonHeaders) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .get(Service.class); - } catch (ResponseProcessingException e) { - //Couldn't convert response to Java type - throw new AsdcCatalogException("SDC response could not be processed", e); - } catch (ProcessingException e) { - //IO problems during request - throw new AsdcCatalogException("Failed to get a response from SDC service", e); - } catch (WebApplicationException e) { - //Web service returned data, but the response status wasn't a good one (i.e. non 2xx) - throw new AsdcCatalogException(e); - } - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getServiceArtifact(java.util.UUID, java.util.UUID) - */ - public Artifact getServiceArtifact(UUID serviceUuid, UUID artifactUuid) throws AsdcCatalogException { - String path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_SVC_API_PATH, ModelConstants.DEFAULT_ASDC_SVC_API_PATH); - - try { - return getClient() - .target(uri) - .path(path + "/" + serviceUuid + "/artifacts/" + artifactUuid) - .request(MediaType.APPLICATION_JSON_TYPE) - .headers(commonHeaders) - .header("Content-Type", MediaType.APPLICATION_JSON) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .get(Artifact.class); - } catch (ResponseProcessingException e) { - //Couldn't convert response to Java type - throw new AsdcCatalogException("SDC response could not be processed", e); - } catch (ProcessingException e) { - //IO problems during request - throw new AsdcCatalogException("Failed to get a response from SDC service", e); - } catch (WebApplicationException e) { - //Web service returned data, but the response status wasn't a good one (i.e. non 2xx) - throw new AsdcCatalogException(e); - } - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getServices() - */ - public Collection<Service> getServices() throws AsdcCatalogException { - String path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_SVC_API_PATH, ModelConstants.DEFAULT_ASDC_SVC_API_PATH); - try { - return getClient() - .target(uri) - .path(path) - .request() - .accept(MediaType.APPLICATION_JSON_TYPE) - .headers(commonHeaders) - .header("Content-Type", MediaType.APPLICATION_JSON) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .get(new GenericType<Collection<Service>>() { - }); - } catch (ResponseProcessingException e) { - //Couldn't convert response to Java type - throw new AsdcCatalogException("SDC response could not be processed", e); - } catch (ProcessingException e) { - //IO problems during request - throw new AsdcCatalogException("Failed to get a response from SDC service", e); - } catch (WebApplicationException e) { - //Web service returned data, but the response status wasn't a good one (i.e. non 2xx) - throw new AsdcCatalogException(e); - } - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getServices(java.util.Map) - */ - public Collection<Service> getServices(Map<String, String[]> filter) throws AsdcCatalogException { - - String path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_SVC_API_PATH, ModelConstants.DEFAULT_ASDC_SVC_API_PATH); - WebTarget target = getClient() - .target(uri) - .path(path); - - - for (Entry<String, String[]> filterEntry : filter.entrySet()) { - target = target.queryParam(filterEntry.getKey(), (Object[]) filterEntry.getValue()); - } - - try { - return target.request() - .accept(MediaType.APPLICATION_JSON_TYPE) - .headers(commonHeaders) - .header("Content-Type", MediaType.APPLICATION_JSON) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .get(new GenericType<Collection<Service>>() { - }); + .header(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()) + .get(); + Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, response); + return response.readEntity(Service.class); } catch (ResponseProcessingException e) { //Couldn't convert response to Java type throw new AsdcCatalogException("SDC response could not be processed", e); } catch (ProcessingException e) { //IO problems during request throw new AsdcCatalogException("Failed to get a response from SDC service", e); - } catch (NotFoundException e) { - throw e; } catch (WebApplicationException e) { //Web service returned data, but the response status wasn't a good one (i.e. non 2xx) throw new AsdcCatalogException(e); @@ -442,41 +209,34 @@ public class RestfulAsdcClient implements AsdcClient { * @see org.onap.vid.asdc.AsdcClient#getServiceToscaModel(java.util.UUID) */ public Path getServiceToscaModel(UUID serviceUuid) throws AsdcCatalogException { - String path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_SVC_API_PATH, ModelConstants.DEFAULT_ASDC_SVC_API_PATH); + String path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_SVC_API_PATH, + ModelConstants.DEFAULT_ASDC_SVC_API_PATH); + + String url = uri+path + "/" + serviceUuid + "/toscaModel"; + Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); try { - final InputStream csarInputStream = (InputStream) getClient() + final InputStream csarInputStream = getClient() .target(uri) .path(path + "/" + serviceUuid + "/toscaModel") .request(MediaType.APPLICATION_OCTET_STREAM_TYPE) .headers(commonHeaders) .header("Content-Type", MediaType.APPLICATION_OCTET_STREAM) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) + .header(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()) .get(InputStream.class); - - - return getToscaCsar(csarInputStream); + Path toscaFilePath = createTmpFile(csarInputStream); + outgoingRequestsLogger.debug("Received {} {} . Tosca file was saved at: {}", HttpMethod.GET.name(), url, toscaFilePath.toAbsolutePath()); + return toscaFilePath; } catch (ResponseProcessingException e) { //Couldn't convert response to Java type throw new AsdcCatalogException("SDC response could not be processed", e); } catch (ProcessingException e) { //IO problems during request - throw new AsdcCatalogException("Failed to get a response from SDC service", e); + throw new AsdcCatalogException("Failed to get a response from SDC service. Cause: "+e.getMessage(), e); } catch (WebApplicationException e) { //Web service returned data, but the response status wasn't a good one (i.e. non 2xx) throw new AsdcCatalogException(e); } } - - /** - * Gets the tosca model. - * - * @param csarInputStream the csar input stream - * @return the tosca model - * @throws AsdcCatalogException the asdc catalog exception - */ - private Path getToscaCsar(InputStream csarInputStream) throws AsdcCatalogException { - return createTmpFile(csarInputStream); - } } diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/RequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/RequestDetails.java index 36452f67..8e1a4083 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/RequestDetails.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/RequestDetails.java @@ -53,4 +53,8 @@ public class RequestDetails extends org.onap.vid.mso.rest.RequestDetails{ this.relatedInstList = relatedInstList; } + @Override + public boolean equals(Object other) { + return super.equals(other); + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/VnfDetailsWithWorkflows.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/VnfDetailsWithWorkflows.java index db162999..4e172a10 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/VnfDetailsWithWorkflows.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/VnfDetailsWithWorkflows.java @@ -13,7 +13,6 @@ public class VnfDetailsWithWorkflows extends VnfDetails { public VnfDetailsWithWorkflows() { } - @SuppressWarnings("WeakerAccess") public VnfDetailsWithWorkflows(String UUID, String invariantUUID, List<String> workflows) { super(UUID, invariantUUID); @@ -33,4 +32,8 @@ public class VnfDetailsWithWorkflows extends VnfDetails { public void setWorkflows(List<String> workflows) { this.workflows = workflows; } + + public boolean equals(VnfDetailsWithWorkflows vnfDetailsWithWorkflows){ + return this.workflows.equals(vnfDetailsWithWorkflows.getWorkflows()); + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/client/FakeHttpSession.java b/vid-app-common/src/main/java/org/onap/vid/client/FakeHttpSession.java deleted file mode 100644 index 69ce11f4..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/client/FakeHttpSession.java +++ /dev/null @@ -1,224 +0,0 @@ -package org.onap.vid.client; - -import org.apache.commons.io.IOUtils; -import org.json.JSONArray; -import org.json.JSONObject; -import org.json.JSONTokener; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpSession; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; - -/** - * Created by pickjonathan on 03/07/2017. - */ -public class FakeHttpSession implements HttpSession { - - /** - * Setup the creation time - */ - public FakeHttpSession() { - File file = new File("resources/roles.json"); - - String rolesInputStream = null; - try { - rolesInputStream = IOUtils.toString(FakeHttpSession.class.getClassLoader().getResourceAsStream("roles.json"),"UTF8"); - } catch (IOException e) { - e.printStackTrace(); - } - JSONTokener tokener = new JSONTokener(rolesInputStream); - JSONObject roles = new JSONObject(tokener); - - JSONArray rolesArray = roles.getJSONArray("roles"); - - //set permissions to the roles from file. - this.setAttribute("role", rolesArray); - - creationTime = System.currentTimeMillis(); - } - - - /** - * Setup the creation time - * @param id The new session id - */ - public FakeHttpSession(String id) - { - this.id = id; - creationTime = System.currentTimeMillis(); - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#getCreationTime() - */ - public long getCreationTime() - { - return creationTime; - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#getId() - */ - public String getId() - { - if (id == null) - { - System.out.println("Inventing data in FakeHttpSession.getId() to remain plausible."); - id = "fake"; - } - - return id; - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#getLastAccessedTime() - */ - public long getLastAccessedTime() - { - return creationTime; - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#getServletContext() - */ - public ServletContext getServletContext() - { - return null; - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#setMaxInactiveInterval(int) - */ - public void setMaxInactiveInterval(int maxInactiveInterval) - { - this.maxInactiveInterval = maxInactiveInterval; - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#getMaxInactiveInterval() - */ - public int getMaxInactiveInterval() - { - return maxInactiveInterval; - } - - /** - * @see javax.servlet.http.HttpSession#getSessionContext() - * @deprecated - */ - @SuppressWarnings({"UnnecessaryFullyQualifiedName"}) - @Deprecated - public javax.servlet.http.HttpSessionContext getSessionContext() - { - return null; - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#getAttribute(java.lang.String) - */ - public Object getAttribute(String name) - { - return attributes.get(name); - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#getValue(java.lang.String) - */ - @Deprecated - public Object getValue(String name) - { - return attributes.get(name); - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#getAttributeNames() - */ - public Enumeration<String> getAttributeNames() - { - return Collections.enumeration(attributes.keySet()); - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#getValueNames() - */ - @Deprecated - public String[] getValueNames() - { - return attributes.keySet().toArray(new String[attributes.keySet().size()]); - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#setAttribute(java.lang.String, java.lang.Object) - */ - public void setAttribute(String name, Object value) - { - attributes.put(name, value); - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#putValue(java.lang.String, java.lang.Object) - */ - @Deprecated - public void putValue(String name, Object value) - { - attributes.put(name, value); - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#removeAttribute(java.lang.String) - */ - public void removeAttribute(String name) - { - attributes.remove(name); - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#removeValue(java.lang.String) - */ - @Deprecated - public void removeValue(String name) - { - attributes.remove(name); - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#invalidate() - */ - public void invalidate() - { - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpSession#isNew() - */ - public boolean isNew() - { - return true; - } - - /** - * The session id - */ - private String id = null; - - /** - * The list of attributes - */ - private Map<String, Object> attributes = new HashMap<String, Object>(); - - /** - * When were we created - */ - private long creationTime; - - /** - * How long before we timeout? - */ - private int maxInactiveInterval = 30 * 60 * 1000; -} diff --git a/vid-app-common/src/main/java/org/onap/vid/client/HttpBasicClient.java b/vid-app-common/src/main/java/org/onap/vid/client/HttpBasicClient.java index ac057a87..8f0d59fd 100644 --- a/vid-app-common/src/main/java/org/onap/vid/client/HttpBasicClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/client/HttpBasicClient.java @@ -21,18 +21,16 @@ package org.onap.vid.client; -import java.text.DateFormat; -import java.text.SimpleDateFormat; - -import javax.servlet.ServletContext; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; - import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import javax.servlet.ServletContext; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import java.text.DateFormat; +import java.text.SimpleDateFormat; /** * General HTTP client. @@ -56,7 +54,7 @@ public class HttpBasicClient{ * @return Client client object * @throws Exception the exception */ - public static Client getClient() throws Exception { + public static Client getClient() { ClientConfig config = new ClientConfig(); config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); diff --git a/vid-app-common/src/main/java/org/onap/vid/client/HttpsBasicClient.java b/vid-app-common/src/main/java/org/onap/vid/client/HttpsBasicClient.java index 0f8c028b..5afa0359 100644 --- a/vid-app-common/src/main/java/org/onap/vid/client/HttpsBasicClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/client/HttpsBasicClient.java @@ -20,10 +20,12 @@ package org.onap.vid.client; -import java.io.File; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; +import org.eclipse.jetty.util.security.Password; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.onap.vid.properties.VidProperties; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; @@ -31,13 +33,10 @@ import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; - -import org.eclipse.jetty.util.security.Password; -import org.glassfish.jersey.client.ClientConfig; -import org.glassfish.jersey.client.ClientProperties; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.properties.VidProperties; +import java.io.File; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; /** * General SSL client using the VID tomcat keystore. It doesn't use client certificates. @@ -57,12 +56,10 @@ public class HttpsBasicClient{ * @return Client The SSL client * @throws Exception the exception */ - public static Client getClient() throws Exception { + public static Client getClient() { String methodName = "getClient"; ClientConfig config = new ClientConfig(); - //config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - //config.getClasses().add(org.onap.aai.util.CustomJacksonJaxBJsonProvider.class); - + SSLContext ctx = null; try { @@ -80,10 +77,6 @@ public class HttpsBasicClient{ File tr = new File (truststore_path); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " absolute truststore path=" + tr.getAbsolutePath()); - //String keystore_path = certFilePath + AAIProperties.FILESEPARTOR + SystemProperties.getProperty(AAIProperties.AAI_KEYSTORE_FILENAME); - //String keystore_password = SystemProperties.getProperty(AAIProperties.AAI_KEYSTORE_PASSWD_X); - //String decrypted_keystore_password = EncryptedPropValue.decryptTriple(keystore_password); - System.setProperty("javax.net.ssl.trustStore", truststore_path); System.setProperty("javax.net.ssl.trustStorePassword", decrypted_truststore_password); HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){ @@ -94,24 +87,7 @@ public class HttpsBasicClient{ //May need to make the algorithm a parameter. MSO requires TLSv1.1 or TLSv1.2 ctx = SSLContext.getInstance("TLSv1.2"); - - /* - KeyManagerFactory kmf = null; - try { - kmf = KeyManagerFactory.getInstance("SunX509"); - FileInputStream fin = new FileInputStream(keystore_path); - KeyStore ks = KeyStore.getInstance("PKCS12"); - char[] pwd = decrypted_keystore_password.toCharArray(); - ks.load(fin, pwd); - kmf.init(ks, pwd); - } catch (Exception e) { - System.out.println("Error setting up kmf: exiting"); - e.printStackTrace(); - System.exit(1); - } - ctx.init(kmf.getKeyManagers(), null, null); - */ ctx.init(null, null, null); //config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, // new HTTPSProperties( , ctx)); @@ -128,16 +104,8 @@ public class HttpsBasicClient{ .register(org.onap.vid.aai.util.CustomJacksonJaxBJsonProvider.class); } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up config: exiting"); - //System.out.println("Error setting up config: exiting"); - e.printStackTrace(); + logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up config: exiting", e); return null; } - - //Client client = ClientBuilder.newClient(config); - // uncomment this line to get more logging for the request/response - // client.addFilter(new LoggingFilter(System.out)); - - //return client; } } diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/filter/ClientCredentialsFilter.java b/vid-app-common/src/main/java/org/onap/vid/controller/filter/ClientCredentialsFilter.java new file mode 100644 index 00000000..d4c7e3c5 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/filter/ClientCredentialsFilter.java @@ -0,0 +1,62 @@ +package org.onap.vid.controller.filter; + +import org.apache.commons.lang3.StringUtils; +import org.onap.vid.scheduler.SchedulerProperties; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.web.filter.GenericFilterBean; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * Created by amichai on 13/05/2018. + */ +@WebFilter(urlPatterns = "/change-management/workflow/*") +public class ClientCredentialsFilter extends GenericFilterBean { + + private final static EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(ClientCredentialsFilter.class); + + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + + if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) + return; + + String expectedAuthorization = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_BASIC_AUTH); + String actualAuthorization = ((HttpServletRequest)request).getHeader("Authorization"); + + if (verifyClientCredentials(actualAuthorization, expectedAuthorization)) { + LOGGER.warn(EELFLoggerDelegate.debugLogger,"Client credentials authenticated."); + chain.doFilter(request, response); + return; + } + + LOGGER.warn(EELFLoggerDelegate.debugLogger,"Client did not provide the expected credentials."); + ((HttpServletResponse) response).sendError(401); + } + + public boolean verifyClientCredentials(String actualAuthorization, String expectedAuthorization) + { + if (StringUtils.isEmpty(expectedAuthorization)) + { + LOGGER.warn(EELFLoggerDelegate.debugLogger,String.format("Expected Authorization is not configured (key: %s)", SchedulerProperties.SCHEDULER_BASIC_AUTH)); + return true; + } + + if (StringUtils.isEmpty(actualAuthorization)) + { + LOGGER.warn(EELFLoggerDelegate.debugLogger,"Authorization header is missing."); + return false; + } + + return actualAuthorization.equals(expectedAuthorization); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/AaiController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/AaiController.java index b7dfd37c..1a426ed2 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/AaiController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/AaiController.java @@ -20,13 +20,15 @@ package org.onap.vid.controllers; -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.JsonMappingException; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; import org.codehaus.jackson.map.ObjectMapper; import org.onap.vid.aai.AaiResponse; +import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigData; import org.onap.vid.aai.ServiceInstancesSearchResults; import org.onap.vid.aai.SubscriberData; import org.onap.vid.aai.SubscriberFilteredResults; +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; @@ -49,16 +51,15 @@ import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.BadRequestException; import javax.ws.rs.DefaultValue; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; -import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; +import java.util.stream.Collectors; import static org.onap.vid.utils.Logging.getMethodName; @@ -67,8 +68,7 @@ import static org.onap.vid.utils.Logging.getMethodName; */ @RestController -public class -AaiController extends RestrictedBaseController { +public class AaiController extends RestrictedBaseController { /** * The Constant dateFormat. */ @@ -98,14 +98,8 @@ AaiController extends RestrictedBaseController { @Autowired private RoleProvider roleProvider; - public AaiController() { - - } - - public AaiController(ServletContext servletContext) { - this.servletContext = servletContext; - - } + @Autowired + private AAIRestInterface aaiRestInterface; /** * Welcome method. @@ -120,28 +114,32 @@ AaiController extends RestrictedBaseController { } @RequestMapping(value = {"/aai_get_aic_zones"}, method = RequestMethod.GET) - public ResponseEntity<String> getAicZones(HttpServletRequest request) throws JsonGenerationException, JsonMappingException, IOException { + public ResponseEntity<String> getAicZones(HttpServletRequest request) throws IOException { LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== getAicZones controller start"); AaiResponse response = aaiService.getAaiZones(); return aaiResponseToResponseEntity(response); } @RequestMapping(value = {"/aai_get_aic_zone_for_pnf/{globalCustomerId}/{serviceType}/{serviceId}"}, method = RequestMethod.GET) - public ResponseEntity<String> getAicZoneForPnf(@PathVariable("globalCustomerId") String globalCustomerId ,@PathVariable("serviceType") String serviceType , @PathVariable("serviceId") String serviceId ,HttpServletRequest request) throws JsonGenerationException, JsonMappingException, IOException { + public ResponseEntity<String> getAicZoneForPnf(@PathVariable("globalCustomerId") String globalCustomerId ,@PathVariable("serviceType") String serviceType , @PathVariable("serviceId") String serviceId ,HttpServletRequest request) throws IOException { LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== getAicZoneForPnf controller start"); AaiResponse response = aaiService.getAicZoneForPnf(globalCustomerId , serviceType , serviceId); return aaiResponseToResponseEntity(response); } + @RequestMapping(value = {"/aai_get_instance_groups_by_vnf_instance_id/{vnfInstanceId}"}, method = RequestMethod.GET) + public ResponseEntity<String> getInstanceGroupsByVnfInstanceId(@PathVariable("vnfInstanceId") String vnfInstanceId ,HttpServletRequest request) throws IOException { + AaiResponse response = aaiService.getInstanceGroupsByVnfInstanceId(vnfInstanceId); + return aaiResponseToResponseEntity(response); + } /** * Get services from a&ai. * * @return ResponseEntity<String> The response entity with the logged in user uuid. * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException the interrupted exception */ @RequestMapping(value = {"/getuserID"}, method = RequestMethod.GET) - public ResponseEntity<String> getUserID(HttpServletRequest request) throws IOException, InterruptedException { + public ResponseEntity<String> getUserID(HttpServletRequest request) { String userId = ControllersUtils.extractUserId(request); @@ -153,10 +151,9 @@ AaiController extends RestrictedBaseController { * * @return ResponseEntity<String> The response entity * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException the interrupted exception */ @RequestMapping(value = "/aai_get_services", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity<String> doGetServices(HttpServletRequest request) throws IOException, InterruptedException { + public ResponseEntity<String> doGetServices(HttpServletRequest request) throws IOException { RoleValidator roleValidator = new RoleValidator(roleProvider.getUserRoles(request)); AaiResponse subscriberList = aaiService.getServices(roleValidator); @@ -167,7 +164,7 @@ AaiController extends RestrictedBaseController { @RequestMapping(value = {"/aai_get_version_by_invariant_id"}, method = RequestMethod.POST) - public ResponseEntity<String> getVersionByInvariantId(HttpServletRequest request, @RequestBody VersionByInvariantIdsRequest versions) throws IOException { + public ResponseEntity<String> getVersionByInvariantId(HttpServletRequest request, @RequestBody VersionByInvariantIdsRequest versions) { ResponseEntity<String> responseEntity; ObjectMapper objectMapper = new ObjectMapper(); @@ -178,7 +175,7 @@ AaiController extends RestrictedBaseController { private ResponseEntity<String> aaiResponseToResponseEntity(AaiResponse aaiResponseData) - throws IOException, JsonGenerationException, JsonMappingException { + throws IOException { ResponseEntity<String> responseEntity; ObjectMapper objectMapper = new ObjectMapper(); if (aaiResponseData.getHttpCode() == 200) { @@ -195,19 +192,17 @@ AaiController extends RestrictedBaseController { * @param serviceInstanceId the service instance Id * @return ResponseEntity The response entity * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException the interrupted exception */ @RequestMapping(value = "/aai_get_service_instance/{service-instance-id}/{service-instance-type}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity<String> doGetServiceInstance(@PathVariable("service-instance-id") String serviceInstanceId, @PathVariable("service-instance-type") String serviceInstanceType) throws IOException, InterruptedException { - File certiPath = GetCertificatesPath(); + public ResponseEntity<String> doGetServiceInstance(@PathVariable("service-instance-id") String serviceInstanceId, @PathVariable("service-instance-type") String serviceInstanceType) { Response resp = null; if (serviceInstanceType.equalsIgnoreCase("Service Instance Id")) { - resp = doAaiGet(certiPath.getAbsolutePath(), + resp = doAaiGet( "search/nodes-query?search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId, false); } else { - resp = doAaiGet(certiPath.getAbsolutePath(), + resp = doAaiGet( "search/nodes-query?search-node-type=service-instance&filter=service-instance-name:EQUALS:" + serviceInstanceId, false); } @@ -221,13 +216,11 @@ AaiController extends RestrictedBaseController { * @param serviceSubscriptionId the service subscription id * @return ResponseEntity The response entity * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException the interrupted exception */ @RequestMapping(value = "/aai_get_service_subscription/{global-customer-id}/{service-subscription-id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> doGetServices(@PathVariable("global-customer-id") String globalCustomerId, - @PathVariable("service-subscription-id") String serviceSubscriptionId) throws IOException, InterruptedException { - File certiPath = GetCertificatesPath(); - Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + globalCustomerId + @PathVariable("service-subscription-id") String serviceSubscriptionId) { + Response resp = doAaiGet("business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceSubscriptionId + "?depth=0", false); return convertResponseToResponseEntity(resp); } @@ -238,10 +231,9 @@ AaiController extends RestrictedBaseController { * @param fullSet the full set * @return ResponseEntity The response entity * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException the interrupted exception */ @RequestMapping(value = "/aai_get_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity<String> doGetSubscriberList(HttpServletRequest request, @DefaultValue("n") @QueryParam("fullSet") String fullSet) throws IOException, InterruptedException { + public ResponseEntity<String> doGetSubscriberList(HttpServletRequest request, @DefaultValue("n") @QueryParam("fullSet") String fullSet) throws IOException { return getFullSubscriberList(request); } @@ -250,10 +242,9 @@ AaiController extends RestrictedBaseController { * * @return ResponseEntity The response entity * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException the interrupted exception */ @RequestMapping(value = "/get_system_prop_vnf_prov_status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity<String> getTargetProvStatus() throws IOException, InterruptedException { + public ResponseEntity<String> getTargetProvStatus() { String p = SystemProperties.getProperty("aai.vnf.provstatus"); return new ResponseEntity<String>(p, HttpStatus.OK); } @@ -264,11 +255,10 @@ AaiController extends RestrictedBaseController { * * @return ResponseEntity The response entity * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException the interrupted exception */ @RequestMapping(value = "/get_operational_environments", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public AaiResponse<OperationalEnvironmentList> getOperationalEnvironments(@RequestParam(value="operationalEnvironmentType", required = false) String operationalEnvironmentType, - @RequestParam(value="operationalEnvironmentStatus", required = false) String operationalEnvironmentStatus) throws IOException, InterruptedException { + @RequestParam(value="operationalEnvironmentStatus", required = false) String operationalEnvironmentStatus) { LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({}, {})", getMethodName(), operationalEnvironmentType, operationalEnvironmentStatus); AaiResponse<OperationalEnvironmentList> response = aaiService.getOperationalEnvironments(operationalEnvironmentType,operationalEnvironmentStatus); if (response.getHttpCode() != 200) { @@ -288,10 +278,9 @@ AaiController extends RestrictedBaseController { * g @return ResponseEntity The response entity * * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException the interrupted exception */ @RequestMapping(value = "/aai_get_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity<String> getFullSubscriberList(HttpServletRequest request) throws IOException, InterruptedException { + public ResponseEntity<String> getFullSubscriberList(HttpServletRequest request) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); ResponseEntity<String> responseEntity; RoleValidator roleValidator = new RoleValidator(roleProvider.getUserRoles(request)); @@ -312,7 +301,7 @@ AaiController extends RestrictedBaseController { produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> getVnfDataByGlobalIdAndServiceType(HttpServletRequest request, @PathVariable("globalCustomerId") String globalCustomerId, - @PathVariable("serviceType") String serviceType) throws IOException { + @PathVariable("serviceType") String serviceType) { Response resp = aaiService.getVNFData(globalCustomerId, serviceType); return convertResponseToResponseEntity(resp); @@ -326,7 +315,7 @@ AaiController extends RestrictedBaseController { * @throws IOException Signals that an I/O exception has occurred. */ @RequestMapping(value = "/aai_refresh_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity<String> doRefreshSubscriberList() throws IOException { + public ResponseEntity<String> doRefreshSubscriberList() { Response resp = getSubscribers(false); return convertResponseToResponseEntity(resp); } @@ -338,7 +327,7 @@ AaiController extends RestrictedBaseController { * @throws IOException Signals that an I/O exception has occurred. */ @RequestMapping(value = "/aai_refresh_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity<String> doRefreshFullSubscriberList() throws IOException { + public ResponseEntity<String> doRefreshFullSubscriberList() { Response resp = getSubscribers(false); return convertResponseToResponseEntity(resp); } @@ -421,9 +410,8 @@ AaiController extends RestrictedBaseController { @PathVariable("serviceInstance") String serviceInstance) { String componentListPayload = getComponentListPutPayload(namedQueryId, globalCustomerId, serviceType, serviceInstance); - File certiPath = GetCertificatesPath(); - Response resp = doAaiPost(certiPath.getAbsolutePath(), "search/named-query", componentListPayload, false); + Response resp = doAaiPost("search/named-query", componentListPayload, false); return convertResponseToResponseEntity(resp); } @@ -453,9 +441,8 @@ AaiController extends RestrictedBaseController { @PathVariable("serviceType") String serviceType) { String componentListPayload = getModelsByServiceTypePayload(namedQueryId, globalCustomerId, serviceType); - File certiPath = GetCertificatesPath(); - Response resp = doAaiPost(certiPath.getAbsolutePath(), "search/named-query", componentListPayload, false); + Response resp = doAaiPost("search/named-query", componentListPayload, false); return convertResponseToResponseEntity(resp); } @@ -471,24 +458,48 @@ AaiController extends RestrictedBaseController { return new ResponseEntity<String>(resp.getT(), HttpStatus.valueOf(resp.getHttpCode())); } + @RequestMapping(value = "/aai_get_network_collection_details/{serviceInstanceId}", method = RequestMethod.GET) + public ResponseEntity<String> getNetworkCollectionDetails(@PathVariable("serviceInstanceId") String serviceInstanceId) throws IOException { + com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); + AaiResponse<String> resp = aaiService.getNetworkCollectionDetails(serviceInstanceId); + + String httpMessage = resp.getT() != null ? + objectMapper.writeValueAsString(resp.getT()) : + resp.getErrorMessage(); + return new ResponseEntity<String>(httpMessage, HttpStatus.valueOf(resp.getHttpCode())); + } + + @RequestMapping(value = "/aai_get_instance_groups_by_cloudregion/{cloudOwner}/{cloudRegionId}/{networkFunction}", method = RequestMethod.GET) + public ResponseEntity<String> getInstanceGroupsByCloudRegion(@PathVariable("cloudOwner") String cloudOwner, + @PathVariable("cloudRegionId") String cloudRegionId, + @PathVariable("networkFunction") String networkFunction) throws IOException { + com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); + AaiResponse<AaiGetInstanceGroupsByCloudRegion> resp = aaiService.getInstanceGroupsByCloudRegion(cloudOwner, cloudRegionId, networkFunction); + + String httpMessage = resp.getT() != null ? + objectMapper.writeValueAsString(resp.getT()) : + resp.getErrorMessage(); + return new ResponseEntity<String>(httpMessage, HttpStatus.valueOf(resp.getHttpCode())); + } + @RequestMapping(value = "/aai_get_by_uri/**", method = RequestMethod.GET) public ResponseEntity<String> getByUri(HttpServletRequest request) { - File certiPath = GetCertificatesPath(); String restOfTheUrl = (String) request.getAttribute( HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); String formattedUri = restOfTheUrl.replaceFirst("/aai_get_by_uri/", "").replaceFirst("^aai/v[\\d]+/", ""); - Response resp = doAaiGet(certiPath.getAbsolutePath(), formattedUri, false); + Response resp = doAaiGet(formattedUri, false); return convertResponseToResponseEntity(resp); } + + @RequestMapping(value = "/aai_get_configuration/{configuration_id}", method = RequestMethod.GET) public ResponseEntity<String> getSpecificConfiguration(@PathVariable("configuration_id") String configurationId) { - File certiPath = GetCertificatesPath(); - Response resp = doAaiGet(certiPath.getAbsolutePath(), "network/configurations/configuration/"+configurationId, false); + Response resp = doAaiGet("network/configurations/configuration/"+configurationId, false); return convertResponseToResponseEntity(resp); } @@ -563,6 +574,24 @@ AaiController extends RestrictedBaseController { return new ResponseEntity<String>(resp.getT(), HttpStatus.valueOf(resp.getHttpCode())); } + @RequestMapping(value = "/aai_getPortMirroringConfigsData", method = RequestMethod.GET) + public Map<String, PortMirroringConfigData> getPortMirroringConfigsData( + @RequestParam ("configurationIds") List<String> configurationIds) { + + return configurationIds.stream() + .map(id -> ImmutablePair.of(id, aaiService.getPortMirroringConfigData(id))) + .collect(Collectors.toMap(Pair::getKey, Pair::getValue)); + } + + @RequestMapping(value = "/aai_getPortMirroringSourcePorts", method = RequestMethod.GET) + public Map<String, Object> getPortMirroringSourcePorts( + @RequestParam ("configurationIds") List<String> configurationIds) { + + return configurationIds.stream() + .map(id -> ImmutablePair.of(id, aaiService.getPortMirroringSourcePorts(id))) + .collect(Collectors.toMap(Pair::getKey, Pair::getValue)); + } + private ResponseEntity<String> convertResponseToResponseEntity(Response resp) { ResponseEntity<String> respEnt; ObjectMapper objectMapper = new ObjectMapper(); @@ -582,10 +611,9 @@ AaiController extends RestrictedBaseController { */ private Response getSubscribers(boolean isFullSet) { - File certiPath = GetCertificatesPath(); String depth = "0"; - Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers?subscriber-type=INFRA&depth=" + depth, false); + Response resp = doAaiGet("business/customers?subscriber-type=INFRA&depth=" + depth, false); if (resp != null) { LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString()); } @@ -599,33 +627,20 @@ AaiController extends RestrictedBaseController { * @return the subscriber details */ private Response getSubscriberDetails(String subscriberId) { - File certiPath = GetCertificatesPath(); - Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId + "?depth=2", false); + Response resp = doAaiGet("business/customers/customer/" + subscriberId + "?depth=2", false); //String resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId, false); LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscriberDetails() resp=" + resp.getStatusInfo().toString()); return resp; } /** - * Gets the certificates path. - * - * @return the file - */ - private File GetCertificatesPath() { - if (servletContext != null) - return new File(servletContext.getRealPath("/WEB-INF/cert/")); - return null; - } - - /** * Send a GET request to a&ai. * - * @param certiPath the certi path * @param uri the uri * @param xml the xml * @return String The response */ - protected Response doAaiGet(String certiPath, String uri, boolean xml) { + protected Response doAaiGet(String uri, boolean xml) { String methodName = "getSubscriberList"; String transId = UUID.randomUUID().toString(); LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -633,11 +648,11 @@ AaiController extends RestrictedBaseController { Response resp = null; try { - AAIRestInterface restContrller = new AAIRestInterface(certiPath); - resp = restContrller.RestGet(fromAppId, transId, uri, xml); + + resp = aaiRestInterface.RestGet(fromAppId, transId, uri, xml).getResponse(); } catch (WebApplicationException e) { - final String message = ((BadRequestException) e).getResponse().readEntity(String.class); + final String message = e.getResponse().readEntity(String.class); LOGGER.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); } catch (Exception e) { @@ -651,13 +666,12 @@ AaiController extends RestrictedBaseController { /** * Send a POST request to a&ai. * - * @param certiPath the certi path * @param uri the uri * @param payload the payload * @param xml the xml * @return String The response */ - protected Response doAaiPost(String certiPath, String uri, String payload, boolean xml) { + protected Response doAaiPost(String uri, String payload, boolean xml) { String methodName = "getSubscriberList"; String transId = UUID.randomUUID().toString(); LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -665,8 +679,7 @@ AaiController extends RestrictedBaseController { Response resp = null; try { - AAIRestInterface restContrller = new AAIRestInterface(certiPath); - resp = restContrller.RestPost(fromAppId, transId, uri, payload, xml); + resp = aaiRestInterface.RestPost(fromAppId, uri, payload, xml); } catch (Exception e) { LOGGER.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/AsyncControllerForTests.java b/vid-app-common/src/main/java/org/onap/vid/controllers/AsyncControllerForTests.java new file mode 100644 index 00000000..c4d82932 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/AsyncControllerForTests.java @@ -0,0 +1,56 @@ +package org.onap.vid.controllers; + +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.model.ExceptionResponse; +import org.onap.vid.model.JobBulk; +import org.onap.vid.model.JobModel; +import org.onap.vid.services.BulkInstantiationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; + +import javax.ws.rs.WebApplicationException; +import java.util.Map; +import java.util.UUID; + +import static org.springframework.http.HttpStatus.BAD_REQUEST; + +@RestController +@RequestMapping("asyncForTests") +public class AsyncControllerForTests extends VidRestrictedBaseController { + + private BulkInstantiationService bulkInstantiationService; + + @Autowired + public AsyncControllerForTests(BulkInstantiationService bulkInstantiationService) { + this.bulkInstantiationService = bulkInstantiationService; + } + + @RequestMapping(method = RequestMethod.POST) + public JobBulk createAsyncJob(@RequestBody Map<String, Object> body) { + return bulkInstantiationService.saveBulk(body); + } + + @RequestMapping(value = "/job/{uuid}", method = RequestMethod.GET) + public JobModel getJob(@PathVariable UUID uuid) { + return bulkInstantiationService.getJob(uuid); + } + + @RequestMapping(value = "/error", method = RequestMethod.GET) + public void throwError() { + throw new GenericUncheckedException("dummy error"); + } + + @ExceptionHandler({IllegalArgumentException.class}) + @ResponseStatus(value=BAD_REQUEST) + private ExceptionResponse exceptionHandlerBadRequest(Exception e) { + return ControllersUtils.handleException(e, LOGGER); + } + + @ExceptionHandler(WebApplicationException.class) + private ResponseEntity webApplicationExceptionHandler(WebApplicationException e) { + return ControllersUtils.handleWebApplicationException(e, LOGGER); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/AsyncInstantiationController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/AsyncInstantiationController.java new file mode 100644 index 00000000..c5621a30 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/AsyncInstantiationController.java @@ -0,0 +1,78 @@ +package org.onap.vid.controllers; + + +import org.onap.vid.exceptions.OperationNotAllowedException; +import org.onap.vid.model.ExceptionResponse; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.exception.ExceptionUtils; + +import org.onap.vid.model.JobAuditStatus; +import org.onap.vid.model.ServiceInfo; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.mso.MsoResponseWrapper2; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.UUID; +import static org.springframework.http.HttpStatus.METHOD_NOT_ALLOWED; + + +@RestController +@RequestMapping(AsyncInstantiationController.ASYNC_INSTANTIATION) +public class AsyncInstantiationController extends VidRestrictedBaseController { + + public static final String ASYNC_INSTANTIATION = "asyncInstantiation"; + + protected final AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Autowired + public AsyncInstantiationController(AsyncInstantiationBusinessLogic asyncInstantiationBL) { + this.asyncInstantiationBL = asyncInstantiationBL; + } + + @ExceptionHandler(OperationNotAllowedException.class) + @ResponseStatus(value=METHOD_NOT_ALLOWED) + public ExceptionResponse illegalStateExceptionHandler(Exception e) { + return ControllersUtils.handleException(e, LOGGER); + } + + /** + * Gets the new services status. + * @param request the request + * @return the services list + */ + @RequestMapping(method = RequestMethod.GET) + public List<ServiceInfo> getServicesInfo(HttpServletRequest request) { + return asyncInstantiationBL.getAllServicesInfo(); + } + + @RequestMapping(value = "bulk", method = RequestMethod.POST) + public MsoResponseWrapper2<List<String>> createBulkOfServices(@RequestBody ServiceInstantiation request, HttpServletRequest httpServletRequest) { + //Push to DB according the model + + String userId = ControllersUtils.extractUserId(httpServletRequest); + List<UUID> uuids = asyncInstantiationBL.pushBulkJob(request, userId); + + return new MsoResponseWrapper2(200, uuids); + } + + @RequestMapping(value = "job/{jobId}", method = RequestMethod.DELETE) + public void deleteServiceInfo(@PathVariable("jobId") UUID jobId) { + asyncInstantiationBL.deleteJob(jobId); + } + + @RequestMapping(value = "hide/{jobId}", method = RequestMethod.POST) + public void hideServiceInfo(@PathVariable("jobId") UUID jobId) { + asyncInstantiationBL.hideServiceInfo(jobId); + } + + @RequestMapping(value = "auditStatus/{jobId}", method = RequestMethod.GET) + public List<JobAuditStatus> getJobAuditStatus(HttpServletRequest request, @PathVariable(value="jobId") UUID jobId, @RequestParam(value="source") JobAuditStatus.SourceStatus source){ + return asyncInstantiationBL.getAuditStatuses(jobId, source); + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/ChangeManagementController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/ChangeManagementController.java index fc5bc0b2..59fe61fd 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/ChangeManagementController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/ChangeManagementController.java @@ -23,7 +23,6 @@ import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.WebApplicationException; -import java.io.IOException; import java.util.Collection; import java.util.Collections; @@ -36,7 +35,6 @@ import static org.springframework.http.HttpStatus.*; @RestController @RequestMapping(ChangeManagementController.CHANGE_MANAGEMENT) public class ChangeManagementController extends UnRestrictedBaseController { - private static final String GetWorkflowsResponse = null; public static final String VNF_WORKFLOW_RELATION = "vnf_workflow_relation"; public static final String CHANGE_MANAGEMENT = "change-management"; public static final String GET_VNF_WORKFLOW_RELATION = "get_vnf_workflow_relation"; @@ -57,13 +55,13 @@ public class ChangeManagementController extends UnRestrictedBaseController { } @RequestMapping(value = {"/workflow"}, method = RequestMethod.GET) - public ResponseEntity<Collection<String>> getWorkflow(@RequestParam("vnfs") Collection<String> vnfs) throws IOException, InterruptedException { + public ResponseEntity<Collection<String>> getWorkflow(@RequestParam("vnfs") Collection<String> vnfs) { Collection<String> result = this.workflowService.getWorkflowsForVNFs(vnfs); return new ResponseEntity<>(result, OK); } @RequestMapping(value = {"/mso"}, method = RequestMethod.GET) - public ResponseEntity<Collection<Request>> getMSOChangeManagements() throws Exception, IOException, InterruptedException { + public ResponseEntity<Collection<Request>> getMSOChangeManagements() { Collection<Request> result = this.changeManagementService.getMSOChangeManagements(); return new ResponseEntity<>(result, OK); @@ -94,20 +92,20 @@ public class ChangeManagementController extends UnRestrictedBaseController { @RequestMapping(value = {"/scheduler"}, method = RequestMethod.GET) - public ResponseEntity<JSONArray> getSchedulerChangeManagements() throws IOException, InterruptedException { + public ResponseEntity<JSONArray> getSchedulerChangeManagements() { JSONArray result = this.changeManagementService.getSchedulerChangeManagements(); return new ResponseEntity<>(result, OK); } @RequestMapping(value = {SCHEDULER_BY_SCHEDULE_ID}, method = RequestMethod.DELETE) - public ResponseEntity deleteSchedule(@PathVariable("scheduleId") String scheduleId) throws IOException, InterruptedException { + public ResponseEntity deleteSchedule(@PathVariable("scheduleId") String scheduleId) { Pair<String, Integer> result = this.changeManagementService.deleteSchedule(scheduleId); return ResponseEntity.status(result.getRight()).build(); } @RequestMapping(value = {GET_VNF_WORKFLOW_RELATION}, method = RequestMethod.POST) - public ResponseEntity getWorkflows(@RequestBody GetVnfWorkflowRelationRequest getVnfWorkflowRelationRequest) throws IOException, InterruptedException { + public ResponseEntity getWorkflows(@RequestBody GetVnfWorkflowRelationRequest getVnfWorkflowRelationRequest) { try { GetWorkflowsResponse response = new GetWorkflowsResponse(changeManagementService.getWorkflowsForVnf(getVnfWorkflowRelationRequest)); return ResponseEntity.status(OK).body(response); @@ -122,7 +120,7 @@ public class ChangeManagementController extends UnRestrictedBaseController { } @RequestMapping(value = {VNF_WORKFLOW_RELATION}, method = RequestMethod.POST) - public ResponseEntity createWorkflowRelation(@RequestBody VnfWorkflowRelationRequest vnfWorkflowRelationRequest) throws IOException, InterruptedException { + public ResponseEntity createWorkflowRelation(@RequestBody VnfWorkflowRelationRequest vnfWorkflowRelationRequest) { VnfWorkflowRelationResponse vnfWorkflowRelationResponse; try { vnfWorkflowRelationResponse = changeManagementService.addVnfWorkflowRelation(vnfWorkflowRelationRequest); @@ -135,7 +133,7 @@ public class ChangeManagementController extends UnRestrictedBaseController { } @RequestMapping(value = {VNF_WORKFLOW_RELATION}, method = RequestMethod.GET) - public ResponseEntity getAllWorkflowRelation() throws IOException, InterruptedException { + public ResponseEntity getAllWorkflowRelation() { try { VnfWorkflowRelationAllResponse vnfWorkflowRelationAllResponse = changeManagementService.getAllVnfWorkflowRelations(); @@ -147,7 +145,7 @@ public class ChangeManagementController extends UnRestrictedBaseController { } @RequestMapping(value = {VNF_WORKFLOW_RELATION}, method = RequestMethod.DELETE) - public ResponseEntity deleteWorkflowRelation(@RequestBody VnfWorkflowRelationRequest vnfWorkflowRelationRequest) throws IOException, InterruptedException { + public ResponseEntity deleteWorkflowRelation(@RequestBody VnfWorkflowRelationRequest vnfWorkflowRelationRequest) { VnfWorkflowRelationResponse vnfWorkflowRelationResponse; try { vnfWorkflowRelationResponse = changeManagementService.deleteVnfWorkflowRelation(vnfWorkflowRelationRequest); diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/ControllersUtils.java b/vid-app-common/src/main/java/org/onap/vid/controllers/ControllersUtils.java index 3f8cfa6a..1abe300e 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/ControllersUtils.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/ControllersUtils.java @@ -6,9 +6,11 @@ import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.model.ExceptionResponse; import org.slf4j.MDC; +import org.springframework.http.ResponseEntity; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; +import javax.ws.rs.WebApplicationException; import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; import static org.onap.vid.utils.Logging.getMethodName; @@ -37,4 +39,9 @@ public class ControllersUtils { ExceptionResponse exceptionResponse = new ExceptionResponse(e); return exceptionResponse; } + + public static ResponseEntity handleWebApplicationException(WebApplicationException e, EELFLoggerDelegate logger) { + return ResponseEntity.status(e.getResponse().getStatus()).body(ControllersUtils.handleException(e, logger)); + } + } diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/FeatureTogglingController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/FeatureTogglingController.java new file mode 100644 index 00000000..36dfdaa0 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/FeatureTogglingController.java @@ -0,0 +1,29 @@ +package org.onap.vid.controllers; + +import org.onap.vid.properties.Features; +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("flags") +public class FeatureTogglingController extends RestrictedBaseController { + + @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public @ResponseBody Map<String,Boolean> getFeatureToggles() + { + HashMap<String,Boolean> flags = new HashMap <String, Boolean>(); + for(Features flag : Features.values()){ + flags.put(flag.name(), flag.isActive()); + } + return flags; + + + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java index 149c5bda..c3871da9 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java @@ -116,10 +116,9 @@ public class HealthCheckController extends UnRestrictedBaseController { * Used by IDNS for redundancy * @return ResponseEntity The response entity * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException the interrupted exception - */ + */ @RequestMapping(value="/healthCheck",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public HealthStatus gethealthCheckStatusforIDNS() throws IOException, InterruptedException { + public HealthStatus gethealthCheckStatusforIDNS() { String driver = SystemProperties.getProperty("db.driver"); String URL = SystemProperties.getProperty("db.connectionURL"); @@ -151,13 +150,12 @@ public class HealthCheckController extends UnRestrictedBaseController { * * @return ResponseEntity The response entity * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException the interrupted exception * Project : */ @RequestMapping(value="rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public HealthStatus getHealthCheck( @PathVariable("User-Agent") String UserAgent, - @PathVariable("X-ECOMP-RequestID") String ECOMPRequestID) throws IOException, InterruptedException { + @PathVariable("X-ECOMP-RequestID") String ECOMPRequestID) { String driver = SystemProperties.getProperty("db.driver"); String URL = SystemProperties.getProperty("db.connectionURL"); diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/MaintenanceController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/MaintenanceController.java index c961f593..0976f403 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/MaintenanceController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/MaintenanceController.java @@ -21,17 +21,17 @@ import javax.ws.rs.ForbiddenException; import java.util.Arrays; import java.util.Collections; -import static org.onap.vid.utils.Logging.getMethodName; +import static org.onap.vid.utils.Logging.getMethodCallerName; /** * Controler for APIs that are used only by vid operators */ @RestController -@RequestMapping(MaintenanceController.Maintenance) +@RequestMapping(MaintenanceController.MAINTENANCE) public class MaintenanceController extends UnRestrictedBaseController { - public static final String Maintenance = "maintenance"; + public static final String MAINTENANCE = "maintenance"; @Autowired protected CategoryParameterService categoryParameterService; @@ -45,12 +45,12 @@ public class MaintenanceController extends UnRestrictedBaseController { */ @RequestMapping(value = "/category_parameter/{categoryName}", method = RequestMethod.POST) public ResponseEntity addCategoryOptions ( - HttpServletRequest request, @PathVariable String categoryName, @RequestBody AddCategoryOptionsRequest option) throws Exception { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName()); + HttpServletRequest request, @PathVariable String categoryName, @RequestBody AddCategoryOptionsRequest option) { + debugStartLog(); try { AddCategoryOptionResponse response = categoryParameterService.createCategoryParameterOptions(categoryName, option); HttpStatus httpStatus = response.getErrors().size()>0 ? HttpStatus.MULTI_STATUS : HttpStatus.OK; - LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), response); + debugEndLog(response); return new ResponseEntity<>(response, httpStatus); } catch (CategoryParameterServiceImpl.UnfoundedCategoryException exception) { @@ -64,12 +64,12 @@ public class MaintenanceController extends UnRestrictedBaseController { @RequestMapping(value = "/category_parameter/{categoryName}", method = RequestMethod.PUT) public ResponseEntity updateNameForOption ( - HttpServletRequest request, @PathVariable String categoryName, @RequestBody CategoryParameterOptionRep option) throws Exception { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName()); + HttpServletRequest request, @PathVariable String categoryName, @RequestBody CategoryParameterOptionRep option) { + debugStartLog(); try { AddCategoryOptionResponse response = categoryParameterService.updateCategoryParameterOption(categoryName, option); HttpStatus httpStatus = response.getErrors().size()>0 ? HttpStatus.MULTI_STATUS : HttpStatus.OK; - LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), response); + debugEndLog(response); return new ResponseEntity<>(response, httpStatus); } catch (ForbiddenException exception) { @@ -94,11 +94,11 @@ public class MaintenanceController extends UnRestrictedBaseController { * @throws Exception the exception */ @RequestMapping(value = "/category_parameter", method = RequestMethod.GET) - public ResponseEntity getCategoryParameter(HttpServletRequest request, @RequestParam(value="familyName", required = true) Family familyName) throws Exception { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName()); + public ResponseEntity getCategoryParameter(HttpServletRequest request, @RequestParam(value="familyName", required = true) Family familyName) { + debugStartLog(); try { CategoryParametersResponse response = categoryParameterService.getCategoryParameters(familyName); - LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), response); + debugEndLog(response); return new ResponseEntity<>(response, HttpStatus.OK); } catch (Exception exception) { @@ -115,12 +115,12 @@ public class MaintenanceController extends UnRestrictedBaseController { */ @RequestMapping(value = "/delete_category_parameter/{categoryName}", method = RequestMethod.POST) public ResponseEntity deleteCategoryOption ( - HttpServletRequest request, @PathVariable String categoryName, @RequestBody CategoryParameterOption option) throws Exception { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName()); + HttpServletRequest request, @PathVariable String categoryName, @RequestBody CategoryParameterOption option) { + debugStartLog(); try { categoryParameterService.deleteCategoryOption(categoryName, option); - LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), HttpStatus.OK); + debugEndLog(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK); } catch (CategoryParameterServiceImpl.UnfoundedCategoryException exception) { @@ -132,4 +132,11 @@ public class MaintenanceController extends UnRestrictedBaseController { } } + private void debugStartLog() { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodCallerName()); + } + + private void debugEndLog(Object response) { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodCallerName(), response); + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/MsoConfig.java b/vid-app-common/src/main/java/org/onap/vid/controllers/MsoConfig.java index f3dbf5df..aa0b1ad3 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/MsoConfig.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/MsoConfig.java @@ -8,6 +8,7 @@ import org.onap.vid.mso.MsoInterface; import org.onap.vid.mso.rest.MsoRestClientNew; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.togglz.core.manager.FeatureManager; @Configuration @@ -34,8 +35,8 @@ public class MsoConfig { } @Bean - public MsoBusinessLogic getMsoBusinessLogic(){ - return new MsoBusinessLogicImpl(getMsoClient()); + public MsoBusinessLogic getMsoBusinessLogic(MsoInterface msoClient, FeatureManager featureManager){ + return new MsoBusinessLogicImpl(msoClient, featureManager); } diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/MsoController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/MsoController.java index deebb2b7..62c64b75 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/MsoController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/MsoController.java @@ -27,6 +27,7 @@ import org.onap.vid.mso.MsoBusinessLogic; import org.onap.vid.mso.MsoResponseWrapper; import org.onap.vid.mso.rest.Request; import org.onap.vid.mso.rest.RequestDetails; +import org.onap.vid.mso.rest.RequestDetailsWrapper; import org.onap.vid.mso.rest.Task; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -46,6 +47,8 @@ import java.util.Date; import java.util.LinkedHashMap; import java.util.List; +import static org.onap.vid.utils.Logging.getMethodName; + //import java.util.UUID; //import org.springframework.http.ResponseEntity; //import org.springframework.http.RequestEntity; @@ -65,7 +68,7 @@ public class MsoController extends RestrictedBaseController { /** * The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + private final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); /** * The Constant SVC_INSTANCE_ID. @@ -98,7 +101,7 @@ public class MsoController extends RestrictedBaseController { * @throws Exception the exception */ @RequestMapping(value = "/mso_create_svc_instance", method = RequestMethod.POST) - public ResponseEntity<String> createSvcInstance(HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + public ResponseEntity<String> createSvcInstance(HttpServletRequest request, @RequestBody RequestDetails mso_request) { String methodName = "createSvcInstance"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -119,7 +122,7 @@ public class MsoController extends RestrictedBaseController { * @throws Exception the exception */ @RequestMapping(value = "/mso_create_e2e_svc_instance", method = RequestMethod.POST) - public ResponseEntity<String> createE2eSvcInstance(HttpServletRequest request, @RequestBody LinkedHashMap<String, Object> mso_request) throws Exception { + public ResponseEntity<String> createE2eSvcInstance(HttpServletRequest request, @RequestBody LinkedHashMap<String, Object> mso_request) { String methodName = "createE2eSvcInstance"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -141,7 +144,7 @@ public class MsoController extends RestrictedBaseController { * @throws Exception the exception */ @RequestMapping(value = "/mso_create_vnf_instance/{serviceInstanceId}", method = RequestMethod.POST) - public ResponseEntity<String> createVnf(@PathVariable("serviceInstanceId") String serviceInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + public ResponseEntity<String> createVnf(@PathVariable("serviceInstanceId") String serviceInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) { MsoResponseWrapper w = msoBusinessLogic.createVnf(mso_request, serviceInstanceId); @@ -160,7 +163,7 @@ public class MsoController extends RestrictedBaseController { * @throws Exception the exception */ @RequestMapping(value = "/mso_create_nw_instance/{serviceInstanceId}", method = RequestMethod.POST) - public ResponseEntity<String> createNwInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + public ResponseEntity<String> createNwInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) { String methodName = "createNwInstance"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start, serviceInstanceId = " + serviceInstanceId); @@ -181,7 +184,7 @@ public class MsoController extends RestrictedBaseController { */ @RequestMapping(value = "/mso_create_volumegroup_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) public ResponseEntity<String> createVolumeGroupInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, - HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + HttpServletRequest request, @RequestBody RequestDetails mso_request) { String methodName = "createVolumeGroupInstance"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -202,7 +205,7 @@ public class MsoController extends RestrictedBaseController { */ @RequestMapping(value = "/mso_create_vfmodule_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) public ResponseEntity<String> createVfModuleInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, - @PathVariable("vnfInstanceId") String vnfInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + @PathVariable("vnfInstanceId") String vnfInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) { String methodName = "createVfModuleInstance"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -224,7 +227,7 @@ public class MsoController extends RestrictedBaseController { */ @RequestMapping(value = "/mso_create_configuration_instance/{serviceInstanceId}/configurations/", method = RequestMethod.POST) public ResponseEntity<String> createConfigurationInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, - HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + HttpServletRequest request, @RequestBody RequestDetailsWrapper mso_request) { String methodName = "createConfigurationInstance"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -245,10 +248,10 @@ public class MsoController extends RestrictedBaseController { */ @RequestMapping(value = "/mso_delete_e2e_svc_instance/{serviceInstanceId}", method = RequestMethod.POST) public ResponseEntity<String> deleteE2eSvcInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, - HttpServletRequest request, @RequestBody LinkedHashMap<String, Object> mso_request) throws Exception { + HttpServletRequest request, @RequestBody LinkedHashMap<String, Object> mso_request) { String methodName = "deleteE2eSvcInstance"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName(), mso_request); MsoResponseWrapper w = msoBusinessLogic.deleteE2eSvcInstance(mso_request.get("requestDetails"), serviceInstanceId); @@ -267,20 +270,18 @@ public class MsoController extends RestrictedBaseController { * @return the response entity * @throws Exception the exception */ + @RequestMapping(value = "/mso_delete_svc_instance/{serviceInstanceId}", method = RequestMethod.POST) - public ResponseEntity<String> deleteSvcInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, - HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + public String deleteSvcInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + HttpServletRequest request, @RequestBody RequestDetails mso_request, + @RequestParam(value = "serviceStatus") String serviceStatus) { String methodName = "deleteSvcInstance"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w = msoBusinessLogic.deleteSvcInstance(mso_request, serviceInstanceId); - - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); + LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName(), mso_request); + MsoResponseWrapper w = msoBusinessLogic.deleteSvcInstance(mso_request, serviceInstanceId, serviceStatus); // always return OK, the MSO status code is embedded in the body - return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK)); - + return w.getResponse(); } /** @@ -295,7 +296,7 @@ public class MsoController extends RestrictedBaseController { @RequestMapping(value = "/mso_delete_vnf_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) public ResponseEntity<String> deleteVnf(@PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, - HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + HttpServletRequest request, @RequestBody RequestDetails mso_request) { String methodName = "deleteVnf"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -320,7 +321,7 @@ public class MsoController extends RestrictedBaseController { public ResponseEntity<String> deleteConfiguration( @PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable ("configurationId") String configurationId, - @RequestBody RequestDetails mso_request) throws Exception { + @RequestBody RequestDetailsWrapper mso_request) { String methodName = "deleteConfiguration"; LOGGER.debug(EELFLoggerDelegate.debugLogger, @@ -345,7 +346,7 @@ public class MsoController extends RestrictedBaseController { public ResponseEntity<String> activateConfiguration( @PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("configurationId") String configurationId, - @RequestBody RequestDetails mso_request) throws Exception { + @RequestBody RequestDetails mso_request) { MsoResponseWrapper w = msoBusinessLogic.setConfigurationActiveStatus(mso_request, serviceInstanceId, configurationId, true); @@ -366,7 +367,7 @@ public class MsoController extends RestrictedBaseController { public ResponseEntity<String> deactivateConfiguration( @PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("configurationId") String configurationId, - @RequestBody RequestDetails mso_request) throws Exception { + @RequestBody RequestDetails mso_request) { MsoResponseWrapper w = msoBusinessLogic.setConfigurationActiveStatus(mso_request, serviceInstanceId, configurationId, false); @@ -387,7 +388,7 @@ public class MsoController extends RestrictedBaseController { public ResponseEntity<String> disablePortOnConfiguration( @PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("configurationId") String configurationId, - @RequestBody RequestDetails mso_request) throws Exception { + @RequestBody RequestDetails mso_request) { MsoResponseWrapper w = msoBusinessLogic.setPortOnConfigurationStatus(mso_request, serviceInstanceId, configurationId, false); @@ -408,7 +409,7 @@ public class MsoController extends RestrictedBaseController { public ResponseEntity<String> enablePortOnConfiguration( @PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("configurationId") String configurationId, - @RequestBody RequestDetails mso_request) throws Exception { + @RequestBody RequestDetails mso_request) { MsoResponseWrapper w = msoBusinessLogic.setPortOnConfigurationStatus(mso_request, serviceInstanceId, configurationId, true); @@ -430,7 +431,7 @@ public class MsoController extends RestrictedBaseController { @RequestMapping(value = "/mso_delete_vfmodule_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfModuleId}", method = RequestMethod.POST) public ResponseEntity<String> deleteVfModule( @PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, - @PathVariable("vfModuleId") String vfModuleId, HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + @PathVariable("vfModuleId") String vfModuleId, HttpServletRequest request, @RequestBody RequestDetails mso_request) { String methodName = "deleteVfModule"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -439,7 +440,6 @@ public class MsoController extends RestrictedBaseController { // always return OK, the MSO status code is embedded in the body return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK)); - } /** @@ -455,7 +455,7 @@ public class MsoController extends RestrictedBaseController { @RequestMapping(value = "/mso_delete_volumegroup_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupId}", method = RequestMethod.POST) public ResponseEntity<String> deleteVolumeGroupInstance( @PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, @PathVariable("volumeGroupId") String volumeGroupId, - HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + HttpServletRequest request, @RequestBody RequestDetails mso_request) { String methodName = "deleteVolumeGroupInstance"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -476,7 +476,7 @@ public class MsoController extends RestrictedBaseController { */ @RequestMapping(value = "/mso_delete_nw_instance/{serviceInstanceId}/networks/{networkInstanceId}", method = RequestMethod.POST) public ResponseEntity<String> deleteNwInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, - @PathVariable("networkInstanceId") String networkInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) throws Exception { + @PathVariable("networkInstanceId") String networkInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) { String methodName = "deleteNwInstance"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -484,7 +484,6 @@ public class MsoController extends RestrictedBaseController { // always return OK, the MSO status code is embedded in the body return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK)); - } /** @@ -497,7 +496,7 @@ public class MsoController extends RestrictedBaseController { */ @RequestMapping(value = "/mso_get_orch_req/{requestId}", method = RequestMethod.GET) public ResponseEntity<String> getOrchestrationRequest(@PathVariable("requestId") String requestId, - HttpServletRequest request) throws Exception { + HttpServletRequest request) { String methodName = "getOrchestrationRequest"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -509,7 +508,6 @@ public class MsoController extends RestrictedBaseController { return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK)); } - /** * Gets the orchestration requests. * @@ -520,7 +518,7 @@ public class MsoController extends RestrictedBaseController { */ @RequestMapping(value = "/mso_get_orch_reqs/{filterString}", method = RequestMethod.GET) public ResponseEntity<String> getOrchestrationRequests(@PathVariable("filterString") String filterString, - HttpServletRequest request) throws Exception { + HttpServletRequest request) { String methodName = "getOrchestrationRequests"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -532,7 +530,6 @@ public class MsoController extends RestrictedBaseController { return (new ResponseEntity<String>(w.getResponse(), HttpStatus.OK)); } - /** * activate to a pnf instance. * @@ -542,7 +539,7 @@ public class MsoController extends RestrictedBaseController { * @throws Exception the exception */ @RequestMapping(value = "/mso_activate_service_instance/{serviceInstanceId}", method = RequestMethod.POST) - public ResponseEntity<String> activateServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @RequestBody RequestDetails requestDetails) throws Exception { + public ResponseEntity<String> activateServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @RequestBody RequestDetails requestDetails) { String methodName = "activateServiceInstance"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -559,7 +556,7 @@ public class MsoController extends RestrictedBaseController { * @throws Exception the exception */ @RequestMapping(value = "/mso_deactivate_service_instance/{serviceInstanceId}", method = RequestMethod.POST) - public ResponseEntity<String> deactivateServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @RequestBody RequestDetails requestDetails) throws Exception { + public ResponseEntity<String> deactivateServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @RequestBody RequestDetails requestDetails) { String methodName = "deactivateServiceInstance"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -567,7 +564,6 @@ public class MsoController extends RestrictedBaseController { return new ResponseEntity<>(w.getResponse(), HttpStatus.OK); } - /** * Gets the orchestration requests for the dashboard. * currently its all the orchestration requests with RequestType updateInstance or replaceInstance. @@ -575,7 +571,7 @@ public class MsoController extends RestrictedBaseController { * @throws Exception the exception */ @RequestMapping(value = "/mso_get_orch_reqs/dashboard", method = RequestMethod.GET) - public List<Request> getOrchestrationRequestsForDashboard() throws Exception { + public List<Request> getOrchestrationRequestsForDashboard() { String methodName = "getOrchestrationRequestsForDashboard"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -592,7 +588,7 @@ public class MsoController extends RestrictedBaseController { * @throws Exception the exception */ @RequestMapping(value = "/mso_get_man_task/{originalRequestId}", method = RequestMethod.GET) - public List<Task> getManualTasksByRequestId(@PathVariable("originalRequestId") String originalRequestId) throws Exception { + public List<Task> getManualTasksByRequestId(@PathVariable("originalRequestId") String originalRequestId) { String methodName = "getManualTasksByRequestId"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -600,8 +596,6 @@ public class MsoController extends RestrictedBaseController { return msoBusinessLogic.getManualTasksByRequestId(originalRequestId); } - - /** * Complete the manual task. * @@ -611,7 +605,7 @@ public class MsoController extends RestrictedBaseController { * @throws Exception the exception */ @RequestMapping(value = "/mso_post_man_task/{taskId}", method = RequestMethod.POST) - public ResponseEntity<String> manualTaskComplete(@PathVariable("taskId") String taskId , @RequestBody RequestDetails requestDetails) throws Exception { + public ResponseEntity<String> manualTaskComplete(@PathVariable("taskId") String taskId , @RequestBody RequestDetails requestDetails) { String methodName = "manualTaskComplete"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -622,7 +616,7 @@ public class MsoController extends RestrictedBaseController { @RequestMapping(value = "/mso_remove_relationship/{serviceInstanceId}", method = RequestMethod.POST) public ResponseEntity<String> removeRelationshipFromServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId , - @RequestBody RequestDetails requestDetails) throws Exception { + @RequestBody RequestDetails requestDetails) { String methodName = "removeRelationshipFromServiceInstance"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -639,7 +633,7 @@ public class MsoController extends RestrictedBaseController { @RequestMapping(value = "/mso_add_relationship/{serviceInstanceId}", method = RequestMethod.POST) public ResponseEntity<String> addRelationshipToServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId , - @RequestBody RequestDetails requestDetails) throws Exception { + @RequestBody RequestDetails requestDetails) { String methodName = "addRelationshipToServiceInstance"; LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); @@ -654,7 +648,6 @@ public class MsoController extends RestrictedBaseController { return new ResponseEntity<>(w.getResponse(), HttpStatus.OK); } - /** * Exception handler. * @@ -697,5 +690,4 @@ public class MsoController extends RestrictedBaseController { response.flushBuffer(); } - } diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/OperationalEnvironmentController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/OperationalEnvironmentController.java index fd8ae140..3b6a3f78 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/OperationalEnvironmentController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/OperationalEnvironmentController.java @@ -5,8 +5,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.MoreObjects; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.model.ExceptionResponse; import org.onap.vid.model.RequestReferencesContainer; @@ -19,6 +17,7 @@ import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo; import org.onap.vid.mso.rest.MsoRestClientNew; import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails; import org.onap.vid.mso.rest.RequestDetails; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.MissingServletRequestParameterException; @@ -35,13 +34,11 @@ import java.util.stream.Stream; import static org.onap.vid.utils.Logging.getMethodCallerName; import static org.onap.vid.utils.Logging.getMethodName; -import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; @RestController @RequestMapping("operationalEnvironment") -public class OperationalEnvironmentController extends RestrictedBaseController { +public class OperationalEnvironmentController extends VidRestrictedBaseController { - private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(OperationalEnvironmentController.class); private final RestMsoImplementation restMso; private final MsoBusinessLogic msoBusinessLogic; @@ -55,8 +52,8 @@ public class OperationalEnvironmentController extends RestrictedBaseController { } @RequestMapping(value = "/create", method = RequestMethod.POST) - public MsoResponseWrapper2 createOperationalEnvironment(HttpServletRequest request, @RequestBody OperationalEnvironmentCreateBody operationalEnvironment) throws Exception { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName(), operationalEnvironment); + public MsoResponseWrapper2 createOperationalEnvironment(HttpServletRequest request, @RequestBody OperationalEnvironmentCreateBody operationalEnvironment) { + debugStart(operationalEnvironment); String userId = ControllersUtils.extractUserId(request); RequestDetailsWrapper<OperationEnvironmentRequestDetails> requestDetailsWrapper = msoBusinessLogic.convertParametersToRequestDetails(operationalEnvironment, userId); String path = msoBusinessLogic.getOperationalEnvironmentCreationPath(); @@ -69,7 +66,7 @@ public class OperationalEnvironmentController extends RestrictedBaseController { @RequestMapping(value = "/activate", method = RequestMethod.POST) public MsoResponseWrapper2 activate(HttpServletRequest request, @RequestParam("operationalEnvironment") String operationalEnvironmentId, - @RequestBody OperationalEnvironmentActivateBody activateRequest) throws Exception { + @RequestBody OperationalEnvironmentActivateBody activateRequest) throws MissingServletRequestParameterException { verifyIsNotEmpty(operationalEnvironmentId, "operationalEnvironment"); @@ -96,7 +93,7 @@ public class OperationalEnvironmentController extends RestrictedBaseController { @RequestMapping(value = "/deactivate", method = RequestMethod.POST) public MsoResponseWrapper2 deactivate(HttpServletRequest request, @RequestParam("operationalEnvironment") String operationalEnvironmentId, - @RequestBody Map deactivationRequest) throws Exception { + @RequestBody Map deactivationRequest) throws MissingServletRequestParameterException { verifyIsNotEmpty(operationalEnvironmentId, "operationalEnvironment"); @@ -116,9 +113,9 @@ public class OperationalEnvironmentController extends RestrictedBaseController { } @RequestMapping(value = "/requestStatus", method = RequestMethod.GET) - public MsoResponseWrapper2 status(HttpServletRequest request, @RequestParam("requestId") String requestId) throws Exception { + public MsoResponseWrapper2 status(HttpServletRequest request, @RequestParam("requestId") String requestId) throws MissingServletRequestParameterException { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName(), requestId); + debugStart(requestId); verifyIsNotEmpty(requestId, "requestId"); String path = msoBusinessLogic.getCloudResourcesRequestsStatusPath(requestId); @@ -129,12 +126,6 @@ public class OperationalEnvironmentController extends RestrictedBaseController { return new MsoResponseWrapper2<>(msoResponse); } - @ExceptionHandler(Exception.class) - @ResponseStatus(value=INTERNAL_SERVER_ERROR) - private ExceptionResponse exceptionHandler(Exception e) { - return ControllersUtils.handleException(e, LOGGER); - } - @ExceptionHandler({ org.springframework.web.bind.MissingServletRequestParameterException.class, BadManifestException.class diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/PolicyController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/PolicyController.java index 7519053a..80b4739d 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/PolicyController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/PolicyController.java @@ -21,9 +21,9 @@ package org.onap.vid.controllers; import org.json.simple.JSONObject; +import org.onap.vid.policy.*; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.vid.policy.*; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; @@ -45,7 +45,7 @@ public class PolicyController extends RestrictedBaseController{ private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(PolicyController.class); @RequestMapping(value="/get_policy",method = RequestMethod.POST) - public ResponseEntity<String> getPolicyInfo( HttpServletRequest request, @RequestBody JSONObject policy_request) throws Exception { + public ResponseEntity<String> getPolicyInfo( HttpServletRequest request, @RequestBody JSONObject policy_request) { LOGGER.debug("#####################POLICY API CALL STARTED ###############"+ PolicyProperties.POLICY_GET_CONFIG_VAL); LOGGER.debug("#####################Policy Request ###############"+policy_request.toString()); @@ -58,7 +58,7 @@ public class PolicyController extends RestrictedBaseController{ return ( new ResponseEntity<String>(policyResWrapper.getResponse(), HttpStatus.valueOf(policyResWrapper.getStatus())) ); } - protected static PolicyResponseWrapper getPolicyConfig(JSONObject request, String path) throws Exception { + protected static PolicyResponseWrapper getPolicyConfig(JSONObject request, String path) { String methodName = "getPolicyConfig"; String uuid = UUID.randomUUID().toString(); LOGGER.debug( "starting getPolicyConfig "); diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/ProbeController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/ProbeController.java new file mode 100644 index 00000000..a2145de3 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/ProbeController.java @@ -0,0 +1,27 @@ +package org.onap.vid.controllers; + +import org.onap.vid.aai.AaiClient; +import org.onap.vid.model.probes.ExternalComponentStatus; +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import java.util.ArrayList; +import java.util.List; + +@RestController +@RequestMapping("probe") +public class ProbeController extends RestrictedBaseController { + @Autowired + private AaiClient aaiClient; + + @RequestMapping(method= RequestMethod.GET) + public List<ExternalComponentStatus> getProbe(){ + List<ExternalComponentStatus> componentStatuses = new ArrayList<>(); + componentStatuses.add(aaiClient.probeAaiGetAllSubscribers()); + return componentStatuses; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/PropertyController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/PropertyController.java index 8066507a..2c823863 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/PropertyController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/PropertyController.java @@ -20,12 +20,12 @@ package org.onap.vid.controllers; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.category.CategoryParametersResponse; import org.onap.vid.model.CategoryParameter.Family; import org.onap.vid.services.CategoryParameterService; +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -79,7 +79,7 @@ public class PropertyController extends RestrictedBaseController{ */ @RequestMapping(value = "/get_property/{name}/{defaultvalue}", method = RequestMethod.GET) public ResponseEntity<String> getProperty (@PathVariable("name") String name, @PathVariable("defaultvalue") String defaultvalue, - HttpServletRequest request) throws Exception { + HttpServletRequest request) { String methodName = "getProperty"; ResponseEntity<String> resp = null; @@ -115,7 +115,7 @@ public class PropertyController extends RestrictedBaseController{ * @throws Exception the exception */ @RequestMapping(value = "/category_parameter", method = RequestMethod.GET) - public ResponseEntity getCategoryParameter(HttpServletRequest request, @RequestParam(value="familyName", required = true) Family familyName) throws Exception { + public ResponseEntity getCategoryParameter(HttpServletRequest request, @RequestParam(value="familyName", required = true) Family familyName) { LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName()); try { CategoryParametersResponse response = categoryParameterService.getCategoryParameters(familyName); diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/RoleGeneratorController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/RoleGeneratorController.java index 2dbb4d11..dd6388d8 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/RoleGeneratorController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/RoleGeneratorController.java @@ -1,27 +1,22 @@ package org.onap.vid.controllers; -import fj.test.Bool; -import org.json.JSONObject; -import org.onap.portalsdk.core.controller.UnRestrictedBaseController; import org.onap.vid.services.RoleGeneratorService; +import org.onap.portalsdk.core.controller.UnRestrictedBaseController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import javax.servlet.http.HttpServletRequest; - @RestController public class RoleGeneratorController extends UnRestrictedBaseController { @Autowired private RoleGeneratorService roleGeneratorService; public static final String GENERATE_ROLE_SCRIPT = "generateRoleScript"; @RequestMapping(value = GENERATE_ROLE_SCRIPT +"/{firstRun}", method = RequestMethod.GET ) - public ResponseEntity<String> generateRoleScript (@PathVariable("firstRun") boolean firstRun) throws Exception { + public ResponseEntity<String> generateRoleScript (@PathVariable("firstRun") boolean firstRun) { ResponseEntity<String> response = null; String query = roleGeneratorService.generateRoleScript(firstRun); response = new ResponseEntity<String>(query, HttpStatus.OK); diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/VidController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/VidController.java index 41abdee5..6d6ffb31 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/VidController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/VidController.java @@ -20,22 +20,21 @@ package org.onap.vid.controllers; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; import org.onap.vid.asdc.AsdcCatalogException; import org.onap.vid.asdc.beans.SecureServices; import org.onap.vid.exceptions.VidServiceUnavailableException; +import org.onap.vid.model.PombaInstance.PombaRequest; import org.onap.vid.model.ServiceModel; import org.onap.vid.roles.Role; import org.onap.vid.roles.RoleProvider; import org.onap.vid.services.AaiService; +import org.onap.vid.services.PombaService; import org.onap.vid.services.VidService; +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; @@ -51,8 +50,7 @@ public class VidController extends RestrictedBaseController { private final VidService service; @Autowired - public VidController(VidService vidService) throws SdcToscaParserException{ - + public VidController(VidService vidService) { service = vidService; } @@ -62,6 +60,9 @@ public class VidController extends RestrictedBaseController { @Autowired RoleProvider roleProvider; + @Autowired + private PombaService pombaService; + // /** // * Gets the services. // * @@ -112,7 +113,6 @@ public class VidController extends RestrictedBaseController { } catch (Exception t) { LOG.debug("Unexpected error while retrieving service definitions from A&AI: " + t.getMessage() + ":", t); - t.printStackTrace(); throw new VidServiceUnavailableException("Unexpected error while retrieving service definitions from A&AI: " + t.getMessage(), t); } } @@ -131,11 +131,16 @@ public class VidController extends RestrictedBaseController { try { return service.getService(uuid); } catch (AsdcCatalogException e) { - LOG.error("Failed to retrieve service definitions from SDC", e); + LOG.error("Failed to retrieve service definitions from SDC. Error: "+e.getMessage() , e); throw new VidServiceUnavailableException("Failed to retrieve service definitions from SDC", e); } } + @RequestMapping(value = "/rest/models/reset", method = RequestMethod.POST) + @ResponseStatus(HttpStatus.ACCEPTED) + public void invalidateServiceModelCache(HttpServletRequest request) { + service.invalidateServiceCache(); + } /** * Gets the services view. @@ -145,7 +150,12 @@ public class VidController extends RestrictedBaseController { * @throws VidServiceUnavailableException the vid service unavailable exception */ @RequestMapping(value={"/serviceModels"}, method=RequestMethod.GET) - public ModelAndView getServicesView(HttpServletRequest request) throws VidServiceUnavailableException { - return new ModelAndView("serviceModels"); - } + public ModelAndView getServicesView(HttpServletRequest request) { + return new ModelAndView("serviceModels"); + } + + @RequestMapping(value = {"/rest/models/services/verifyService"}, method = RequestMethod.POST) + public void verifyServiceInstance(HttpServletRequest request, @RequestBody PombaRequest pombaRequest) { + pombaService.verify(pombaRequest); + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/VidRestrictedBaseController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/VidRestrictedBaseController.java new file mode 100644 index 00000000..b520bc02 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/VidRestrictedBaseController.java @@ -0,0 +1,43 @@ +package org.onap.vid.controllers; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.exception.ExceptionUtils; +import org.onap.vid.model.ExceptionResponse; +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; + +import static org.onap.vid.utils.Logging.getMethodCallerName; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; + +public abstract class VidRestrictedBaseController extends RestrictedBaseController { + + protected final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(this.getClass().getName()); + + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + @ResponseBody + public ResponseEntity handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "{}: {}", getMethodCallerName(), ExceptionUtils.getMessage(e), e); + Class<?> type = e.getRequiredType(); + String message; + if (type.isEnum()) { + message = "The parameter " + e.getName() + " must have a value among : " + StringUtils.join(type.getEnumConstants(), ", "); + } + else { + message = "The parameter " + e.getName() + " must be of type " + type.getTypeName(); + } + ResponseEntity response = new ResponseEntity<String>(message, HttpStatus.BAD_REQUEST); + return response; + } + + @ExceptionHandler(Exception.class) + @ResponseStatus(value=INTERNAL_SERVER_ERROR) + public ExceptionResponse exceptionHandler(Exception e) { + return ControllersUtils.handleException(e, LOGGER); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/WebConfig.java b/vid-app-common/src/main/java/org/onap/vid/controllers/WebConfig.java index 295a5fce..22e47600 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/WebConfig.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/WebConfig.java @@ -1,36 +1,30 @@ package org.onap.vid.controllers; import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.io.IOUtils; -import org.json.JSONObject; -import org.json.JSONTokener; -import org.onap.vid.aai.AaiClient; -import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.*; +import org.onap.vid.aai.model.PortDetailsTranslator; +import org.onap.vid.aai.util.AAIRestInterface; +import org.onap.vid.aai.util.HttpsAuthClient; import org.onap.vid.asdc.AsdcClient; -import org.onap.vid.asdc.local.LocalAsdcClient; -import org.onap.vid.asdc.memory.InMemoryAsdcClient; import org.onap.vid.asdc.parser.ToscaParserImpl2; import org.onap.vid.asdc.rest.RestfulAsdcClient; -import org.onap.vid.controllers.VidController; +import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.properties.AsdcClientConfiguration; -import org.onap.vid.properties.AsdcClientConfiguration.AsdcClientType; -import org.onap.vid.services.AaiService; -import org.onap.vid.services.AaiServiceImpl; -import org.onap.vid.services.VidService; -import org.onap.vid.services.VidServiceImpl; +import org.onap.vid.services.*; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.togglz.core.manager.FeatureManager; import javax.net.ssl.SSLContext; +import javax.servlet.ServletContext; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; -import java.io.IOException; -import java.io.InputStream; +import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; -import java.util.Arrays; @Configuration public class WebConfig { @@ -46,73 +40,76 @@ public class WebConfig { } + @Bean + public VidService vidService(AsdcClient asdcClient, FeatureManager featureManager) { + return new VidServiceImpl(asdcClient, featureManager); + } + @Bean + public AaiService getAaiService() { + return new AaiServiceImpl(); + } @Bean - public VidService vidService(AsdcClient asdcClient) { - return new VidServiceImpl(asdcClient); + public AaiResponseTranslator aaiResponseTranslator() { + return new AaiResponseTranslator(); } @Bean - public AaiService getAaiService(){ - return new AaiServiceImpl(); + public PortDetailsTranslator portDetailsTranslator() { + return new PortDetailsTranslator(); + } + + @Bean + public AaiClientInterface getAaiRestInterface(@Qualifier("aaiRestInterface") AAIRestInterface restController, PortDetailsTranslator portsDetailsTranslator) { + return new AaiClient(restController, portsDetailsTranslator); + } + + @Bean(name = "aaiRestInterface") + public AAIRestInterface aaiRestInterface(HttpsAuthClient httpsAuthClientFactory) { + return new AAIRestInterface(httpsAuthClientFactory); } @Bean - public AaiClientInterface getAaiClientInterface(){ - return new AaiClient(); + public PombaRestInterface getPombaRestInterface(HttpsAuthClient httpsAuthClientFactory) { + return new PombaRestInterface(httpsAuthClientFactory); } @Bean - public AsdcClient asdcClient(AsdcClientConfiguration asdcClientConfig) throws IOException { - switch (asdcClientConfig.getAsdcClientType()) { - case IN_MEMORY: - final InputStream asdcCatalogFile = VidController.class.getClassLoader().getResourceAsStream("catalog.json"); - final JSONTokener tokener = new JSONTokener(asdcCatalogFile); - final JSONObject catalog = new JSONObject(tokener); - - return new InMemoryAsdcClient.Builder().catalog(catalog).build(); - case REST: - - final String protocol = asdcClientConfig.getAsdcClientProtocol(); - final String host = asdcClientConfig.getAsdcClientHost(); - final int port = asdcClientConfig.getAsdcClientPort(); - final String auth = asdcClientConfig.getAsdcClientAuth(); - Client cl = null; - if (protocol.equalsIgnoreCase("https")) { - try { - SSLContext ctx = SSLContext.getInstance("TLSv1.2"); - ctx.init(null, null, null); - cl = ClientBuilder.newBuilder().sslContext(ctx).build(); - } catch (NoSuchAlgorithmException n) { - throw new RuntimeException("SDC Client could not be instantiated due to unsupported protocol TLSv1.2", n); - } catch (KeyManagementException k) { - throw new RuntimeException("SDC Client could not be instantiated due to a key management exception", k); - } - } else { - cl = ClientBuilder.newBuilder().build(); - } - - try { - final URI uri = new URI(protocol + "://" + host + ":" + port + "/"); - return new RestfulAsdcClient.Builder(cl, uri) - .auth(auth) - .build(); - } catch (URISyntaxException e) { - throw new RuntimeException("SDC Client could not be instantiated due to a syntax error in the URI", e); - } - - case LOCAL: - - final InputStream asdcServicesFile = VidController.class.getClassLoader().getResourceAsStream("sdcservices.json"); - - final JSONTokener jsonTokener = new JSONTokener(IOUtils.toString(asdcServicesFile)); - final JSONObject sdcServicesCatalog = new JSONObject(jsonTokener); - - return new LocalAsdcClient.Builder().catalog(sdcServicesCatalog).build(); - - default: - throw new RuntimeException(asdcClientConfig.getAsdcClientType() + " is invalid; must be one of " + Arrays.toString(AsdcClientType.values())); + public HttpsAuthClient httpsAuthClientFactory(ServletContext servletContext) { + final String certFilePath = new File(servletContext.getRealPath("/WEB-INF/cert/")).getAbsolutePath(); + return new HttpsAuthClient(certFilePath); + } + + @Bean + public AsdcClient asdcClient(AsdcClientConfiguration asdcClientConfig) { + + final String protocol = asdcClientConfig.getAsdcClientProtocol(); + final String host = asdcClientConfig.getAsdcClientHost(); + final int port = asdcClientConfig.getAsdcClientPort(); + final String auth = asdcClientConfig.getAsdcClientAuth(); + Client cl = null; + if (protocol.equalsIgnoreCase("https")) { + try { + SSLContext ctx = SSLContext.getInstance("TLSv1.2"); + ctx.init(null, null, null); + cl = ClientBuilder.newBuilder().sslContext(ctx).build(); + } catch (NoSuchAlgorithmException n) { + throw new GenericUncheckedException("SDC Client could not be instantiated due to unsupported protocol TLSv1.2", n); + } catch (KeyManagementException k) { + throw new GenericUncheckedException("SDC Client could not be instantiated due to a key management exception", k); + } + } else { + cl = ClientBuilder.newBuilder().build(); + } + + try { + final URI uri = new URI(protocol + "://" + host + ":" + port + "/"); + return new RestfulAsdcClient.Builder(cl, uri) + .auth(auth) + .build(); + } catch (URISyntaxException e) { + throw new GenericUncheckedException("SDC Client could not be instantiated due to a syntax error in the URI", e); } } @@ -121,4 +118,13 @@ public class WebConfig { return new ToscaParserImpl2(); } + @Bean + public PombaService getVerifyServiceInstanceService() { + return new PombaServiceImpl(); + } + + @Bean + public PombaClientInterface getVerifyServiceInstanceClientInterface() { + return new PombaClientImpl(); + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java b/vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java index d21cc5fb..964c7e13 100644 --- a/vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java @@ -20,21 +20,10 @@ package org.onap.vid.dao; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URL; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Properties; - import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import java.sql.*; + public class FnAppDoaImpl { @@ -48,7 +37,7 @@ public class FnAppDoaImpl { String q = null; int count = 0; try { - dbc = getConnection(driver,URL,username,password); + dbc = getConnection(URL,username,password); logger.debug(EELFLoggerDelegate.debugLogger, "getConnection:::"+ dbc); q = "select count(*) from fn_app"; pst = dbc.prepareStatement(q); @@ -65,7 +54,7 @@ public class FnAppDoaImpl { return count; } - public static Connection getConnection(String driver2, String url, String username, String password) throws IOException, SQLException, ClassNotFoundException{ + public static Connection getConnection(String url, String username, String password) throws SQLException { java.sql.Connection con=null; if( url!=null && username!=null && password!=null ){ @@ -79,34 +68,46 @@ public class FnAppDoaImpl { public static void cleanup(ResultSet rs, PreparedStatement st, Connection c) { if (rs != null) { - try { - rs.close(); - } catch (Exception e) { - if (logger != null) - logger.error("Error when trying to close result set", e); - } + closeResultSet(rs); } if (st != null) { - try { - st.close(); - } catch (Exception e) { - if (logger != null) - logger.error("Error when trying to close statement", e); - } + closePreparedStatement(st); } if (c != null) { - try { - c.rollback(); - } catch (Exception e) { - if (logger != null) - logger.error("Error when trying to rollback connection", e); - } - try { - c.close(); - } catch (Exception e) { - if (logger != null) - logger.error("Error when trying to close connection", e); - } + rollbackAndCloseConnection(c); } } + + private static void rollbackAndCloseConnection(Connection c) { + try { + c.rollback(); + } catch (Exception e) { + if (logger != null) + logger.error("Error when trying to rollback connection", e); + } + try { + c.close(); + } catch (Exception e) { + if (logger != null) + logger.error("Error when trying to close connection", e); + } + } + + private static void closePreparedStatement(PreparedStatement st) { + try { + st.close(); + } catch (Exception e) { + if (logger != null) + logger.error("Error when trying to close statement", e); + } + } + + private static void closeResultSet(ResultSet rs) { + try { + rs.close(); + } catch (Exception e) { + if (logger != null) + logger.error("Error when trying to close result set", e); + } + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/exceptions/DbFailureUncheckedException.java b/vid-app-common/src/main/java/org/onap/vid/exceptions/DbFailureUncheckedException.java new file mode 100644 index 00000000..63d63ef2 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/exceptions/DbFailureUncheckedException.java @@ -0,0 +1,17 @@ +package org.onap.vid.exceptions; + +public class DbFailureUncheckedException extends GenericUncheckedException { + + + public DbFailureUncheckedException(String message) { + super(message); + } + + public DbFailureUncheckedException(String message, Throwable cause) { + super(message, cause); + } + + public DbFailureUncheckedException(Throwable cause) { + super(cause); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/exceptions/GenericUncheckedException.java b/vid-app-common/src/main/java/org/onap/vid/exceptions/GenericUncheckedException.java new file mode 100644 index 00000000..dbfa5889 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/exceptions/GenericUncheckedException.java @@ -0,0 +1,15 @@ +package org.onap.vid.exceptions; + +public class GenericUncheckedException extends RuntimeException { + public GenericUncheckedException(String message) { + super(message); + } + + public GenericUncheckedException(String message, Throwable cause) { + super(message, cause); + } + + public GenericUncheckedException(Throwable cause) { + super(cause); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/exceptions/MaxRetriesException.java b/vid-app-common/src/main/java/org/onap/vid/exceptions/MaxRetriesException.java new file mode 100644 index 00000000..74edd315 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/exceptions/MaxRetriesException.java @@ -0,0 +1,8 @@ +package org.onap.vid.exceptions; + +public class MaxRetriesException extends GenericUncheckedException { + + public MaxRetriesException(String operationDetails, int numberOfRetries) { + super(String.format("Max retries for %s, retries: %d", operationDetails, numberOfRetries)); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/exceptions/OperationNotAllowedException.java b/vid-app-common/src/main/java/org/onap/vid/exceptions/OperationNotAllowedException.java new file mode 100644 index 00000000..bbd6549f --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/exceptions/OperationNotAllowedException.java @@ -0,0 +1,7 @@ +package org.onap.vid.exceptions; + +public class OperationNotAllowedException extends GenericUncheckedException { + public OperationNotAllowedException(String message) { + super(message); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/Job.java b/vid-app-common/src/main/java/org/onap/vid/job/Job.java new file mode 100644 index 00000000..77f348dc --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/Job.java @@ -0,0 +1,47 @@ +package org.onap.vid.job; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import java.util.Map; +import java.util.UUID; + +public interface Job { + + UUID getUuid(); + + void setUuid(UUID uuid); + + JobStatus getStatus(); + + void setStatus(JobStatus status); + + @JsonIgnore + Map<String, Object> getData(); + + void setTypeAndData(JobType jobType, Map<String, Object> data); + + UUID getTemplateId(); + + void setTemplateId(UUID templateId); + + void setIndexInBulk(Integer indexInBulk); + + JobType getType(); + + enum JobStatus { + COMPLETED(true), + FAILED(true), + IN_PROGRESS(false), + PAUSE(false), + PENDING(false), + STOPPED(true); + + private final Boolean finalStatus; + public Boolean isFinal(){return finalStatus;} + + JobStatus(Boolean finalStatus) + { + this.finalStatus = finalStatus ; + } + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/JobAdapter.java b/vid-app-common/src/main/java/org/onap/vid/job/JobAdapter.java new file mode 100644 index 00000000..1701092b --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/JobAdapter.java @@ -0,0 +1,26 @@ +package org.onap.vid.job; + +import org.onap.vid.model.JobBulk; +import org.onap.vid.model.JobModel; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * kind of factory for creating jobs and converting them to Job Model + */ +public interface JobAdapter { + JobModel toModel(Job job); + + JobBulk toModelBulk(List<Job> jobList); + + List<Job> createBulkOfJobs(Map<String, Object> bulkRequest); + + Job createJob(JobType jobType, AsyncJobRequest request, UUID templateId, String userId, Integer indexInBulk); + + // Marks types that are an AsyncJob payload + public interface AsyncJobRequest { + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/JobCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/JobCommand.java new file mode 100644 index 00000000..c32645ca --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/JobCommand.java @@ -0,0 +1,41 @@ +package org.onap.vid.job; + +import java.util.Map; +import java.util.UUID; + + +/** + * A callable instance, with serializable characteristics. + * Represents a step in a chain of steps, which eventualy + * resides into a packing Job. + */ +public interface JobCommand { + + /** + * Initialize the command state + * @param jobUuid Parent job's uuid + * @param data An input to be set into the command. Each implementation may expect different keys in the map. + * @return Returns itself + */ + default JobCommand init(UUID jobUuid, Map<String, Object> data) { + return this; + } + + /** + * @return Returns the inner state of the command. This state, once passed into init(), should + * bring the command back to it's state. + */ + Map<String, Object> getData(); + + /** + * Execute the command represented by this instance. Assumes the instance is already init(). + * @return A NextCommand containing the next command in chain of commands, or null if chain + * should be terminated. Might return itself (packed in a NextCommand). + */ + NextCommand call(); + + default JobType getType() { + return JobType.jobTypeOf(this.getClass()); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/JobType.java b/vid-app-common/src/main/java/org/onap/vid/job/JobType.java new file mode 100644 index 00000000..9846d277 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/JobType.java @@ -0,0 +1,31 @@ +package org.onap.vid.job; + +import org.onap.vid.job.command.*; + +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public enum JobType { + + HttpCall(HttpCallCommand.class), + AggregateState(AggregateStateCommand.class), + ServiceInstantiation(ServiceInstantiationCommand.class), + InProgressStatus(InProgressStatusCommand.class), + NoOp(NoOpCommand.class); + + private static final Map<Class, JobType> REVERSE_MAP = Stream.of(values()).collect(Collectors.toMap(t -> t.getCommandClass(), t -> t)); + + private final Class commandClass; + + <T extends JobCommand> JobType(Class<T> commandClass) { + this.commandClass = commandClass; + } + + public Class getCommandClass() { + return commandClass; + } + static JobType jobTypeOf(Class commandClass) { + return REVERSE_MAP.get(commandClass); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/JobsBrokerService.java b/vid-app-common/src/main/java/org/onap/vid/job/JobsBrokerService.java new file mode 100644 index 00000000..856f50b2 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/JobsBrokerService.java @@ -0,0 +1,21 @@ +package org.onap.vid.job; + +import java.util.Collection; +import java.util.Optional; +import java.util.UUID; + +public interface JobsBrokerService { + + UUID add(Job job); + + Optional<Job> pull(Job.JobStatus topic, String ownerId); + + void pushBack(Job job); + + Collection<Job> peek(); + + Job peek(UUID jobId); + + void delete(UUID jobId); + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/NextCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/NextCommand.java new file mode 100644 index 00000000..55f375bb --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/NextCommand.java @@ -0,0 +1,25 @@ +package org.onap.vid.job; + +public class NextCommand { + private final Job.JobStatus status; + private final JobCommand command; + + public NextCommand(Job.JobStatus nextStatus, JobCommand nextCommand) { + this.status = nextStatus; + this.command = nextCommand; + } + + public NextCommand(Job.JobStatus nextStatus) { + this.status = nextStatus; + this.command = null; + } + + public Job.JobStatus getStatus() { + return status; + } + + public JobCommand getCommand() { + return command; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/AggregateStateCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/AggregateStateCommand.java new file mode 100644 index 00000000..65aadf3b --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/AggregateStateCommand.java @@ -0,0 +1,26 @@ +package org.onap.vid.job.command; + +import org.onap.vid.job.JobCommand; +import org.onap.vid.job.NextCommand; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.Collections; +import java.util.Map; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class AggregateStateCommand implements JobCommand { + + @Override + public NextCommand call() { + return null; + } + + @Override + public Map<String, Object> getData() { + return Collections.emptyMap(); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/HttpCallCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/HttpCallCommand.java new file mode 100644 index 00000000..5951d7c8 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/HttpCallCommand.java @@ -0,0 +1,52 @@ +package org.onap.vid.job.command; + +import com.google.common.collect.ImmutableMap; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobCommand; +import org.onap.vid.job.NextCommand; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Response; +import java.util.Map; +import java.util.UUID; + + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class HttpCallCommand implements JobCommand { + private String url; + private UUID uuid; + + public HttpCallCommand() { + } + + public HttpCallCommand(String url, UUID uuid) { + init(url, uuid); + } + + @Override + public NextCommand call() { + final Response response = ClientBuilder.newClient().target(url).request().post(Entity.text(uuid.toString())); + return new NextCommand(Job.JobStatus.COMPLETED); + } + + @Override + public HttpCallCommand init(UUID jobUuid, Map<String, Object> data) { + return init((String) data.get("url"), jobUuid); + } + + private HttpCallCommand init(String url, UUID jobUuid) { + this.url = url; + this.uuid = jobUuid; + return this; + } + + @Override + public Map<String, Object> getData() { + return ImmutableMap.of("url", url); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusCommand.java new file mode 100644 index 00000000..64c782c0 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusCommand.java @@ -0,0 +1,110 @@ +package org.onap.vid.job.command; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import org.onap.vid.job.Job.JobStatus; +import org.onap.vid.job.JobCommand; +import org.onap.vid.job.NextCommand; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; +import java.util.Map; +import java.util.UUID; + + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class InProgressStatusCommand implements JobCommand { + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(InProgressStatusCommand.class); + + @Inject + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Inject + private RestMsoImplementation restMso; + + @Inject + private AuditService auditService; + + private String requestId; + + private UUID jobUuid; + + public InProgressStatusCommand() { + } + + InProgressStatusCommand(UUID jobUuid, String requestId) { + init(jobUuid, requestId); + } + + @Override + public NextCommand call() { + + try { + String path = asyncInstantiationBL.getOrchestrationRequestsPath()+"/"+requestId; + RestObject<AsyncRequestStatus> msoResponse = restMso.GetForObject("", path, AsyncRequestStatus.class); + JobStatus jobStatus; + if (msoResponse.getStatusCode() >= 400 || msoResponse.get() == null) { + auditService.setFailedAuditStatusFromMso(jobUuid, requestId, msoResponse.getStatusCode(), msoResponse.getRaw()); + LOGGER.error(EELFLoggerDelegate.errorLogger, + "Failed to get orchestration status for {}. Status code: {}, Body: {}", + requestId, msoResponse.getStatusCode(), msoResponse.getRaw()); + return new NextCommand(JobStatus.IN_PROGRESS, this); + } + else { + jobStatus = asyncInstantiationBL.calcStatus(msoResponse.get()); + } + + asyncInstantiationBL.auditMsoStatus(jobUuid,msoResponse.get().request); + + + if (jobStatus == JobStatus.FAILED) { + asyncInstantiationBL.handleFailedInstantiation(jobUuid); + } + else { + asyncInstantiationBL.updateServiceInfoAndAuditStatus(jobUuid, jobStatus); + } + //in case of JobStatus.PAUSE we leave the job itself as IN_PROGRESS, for keep tracking job progress + if (jobStatus == JobStatus.PAUSE) { + return new NextCommand(JobStatus.IN_PROGRESS, this); + } + return new NextCommand(jobStatus, this); + } catch (javax.ws.rs.ProcessingException e) { + // Retry when we can't connect MSO during getStatus + LOGGER.error(EELFLoggerDelegate.errorLogger, "Cannot get orchestration status for {}, will retry: {}", requestId, e, e); + return new NextCommand(JobStatus.IN_PROGRESS, this); + } catch (RuntimeException e) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "Cannot get orchestration status for {}, stopping: {}", requestId, e, e); + return new NextCommand(JobStatus.STOPPED, this); + } + } + + @Override + public InProgressStatusCommand init(UUID jobUuid, Map<String, Object> data) { + return init(jobUuid, (String) data.get("requestId")); + } + + private InProgressStatusCommand init(UUID jobUuid, String requestId) { + this.requestId = requestId; + this.jobUuid = jobUuid; + return this; + } + + @Override + public Map<String, Object> getData() { + return ImmutableMap.of("requestId", requestId); + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/JobCommandFactory.java b/vid-app-common/src/main/java/org/onap/vid/job/command/JobCommandFactory.java new file mode 100644 index 00000000..1e613c58 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/JobCommandFactory.java @@ -0,0 +1,43 @@ +package org.onap.vid.job.command; + +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobCommand; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; +import java.util.function.Function; + +@Component +public class JobCommandFactory { + + final Function<Class<? extends JobCommand>, JobCommand> jobFactory; + + @Inject + public JobCommandFactory(ApplicationContext applicationContext) { + this.jobFactory = (jobType -> { + final Object commandBean = applicationContext.getBean(jobType); + + if (!(commandBean instanceof JobCommand)) { + throw new GenericUncheckedException(commandBean.getClass() + " is not a JobCommand"); + } + + return (JobCommand) commandBean; + }); + } + + public JobCommandFactory(Function<Class<? extends JobCommand>, JobCommand> jobFactory) { + this.jobFactory = jobFactory; + } + + public JobCommand toCommand(Job job) { + + final JobCommand command = jobFactory.apply(job.getType().getCommandClass()); + command.init(job.getUuid(), job.getData()); + + return command; + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/NoOpCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/NoOpCommand.java new file mode 100644 index 00000000..37636fca --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/NoOpCommand.java @@ -0,0 +1,25 @@ +package org.onap.vid.job.command; + +import org.onap.vid.job.JobCommand; +import org.onap.vid.job.NextCommand; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.Collections; +import java.util.Map; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NoOpCommand implements JobCommand { + + @Override + public NextCommand call() { + return null; + } + + @Override + public Map<String, Object> getData() { + return Collections.emptyMap(); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInstantiationCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInstantiationCommand.java new file mode 100644 index 00000000..6afacf23 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInstantiationCommand.java @@ -0,0 +1,140 @@ +package org.onap.vid.job.command; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import org.onap.vid.aai.exceptions.InvalidAAIResponseException; +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.exceptions.MaxRetriesException; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobCommand; +import org.onap.vid.job.NextCommand; +import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; +import java.util.Map; +import java.util.UUID; + + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ServiceInstantiationCommand implements JobCommand { + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(ServiceInstantiationCommand.class); + + @Inject + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Inject + private AuditService auditService; + + @Inject + private RestMsoImplementation restMso; + + private UUID uuid; + private ServiceInstantiation serviceInstantiationRequest; + private String userId; + + public ServiceInstantiationCommand() { + } + + public ServiceInstantiationCommand(UUID uuid, ServiceInstantiation serviceInstantiationRequest, String userId) { + init(uuid, serviceInstantiationRequest, userId); + } + + @Override + public NextCommand call() { + RequestDetailsWrapper<ServiceInstantiationRequestDetails> requestDetailsWrapper ; + try { + requestDetailsWrapper = asyncInstantiationBL.generateServiceInstantiationRequest( + uuid, serviceInstantiationRequest, userId + ); + } + + //Aai return bad response while checking names uniqueness + catch (InvalidAAIResponseException exception) { + LOGGER.error("Failed to check name uniqueness in AAI. VID will try again later", exception); + //put the job in_progress so we will keep trying to check name uniqueness in AAI + //And then send the request to MSO + return new NextCommand(Job.JobStatus.IN_PROGRESS, this); + } + + //Vid reached to max retries while trying to find unique name in AAI + catch (MaxRetriesException exception) { + LOGGER.error("Failed to find unused name in AAI. Set the job to FAILED ", exception); + return handleCommandFailed(); + } + + String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationRequest); + + RestObject<RequestReferencesContainer> msoResponse = restMso.PostForObject(requestDetailsWrapper, "", + path, RequestReferencesContainer.class); + + if (msoResponse.getStatusCode() >= 200 && msoResponse.getStatusCode() < 400) { + final Job.JobStatus jobStatus = Job.JobStatus.IN_PROGRESS; + final String requestId = msoResponse.get().getRequestReferences().getRequestId(); + final String instanceId = msoResponse.get().getRequestReferences().getInstanceId(); + asyncInstantiationBL.auditVidStatus(uuid, jobStatus); + setInitialRequestAuditStatusFromMso(requestId); + asyncInstantiationBL.updateServiceInfo(uuid, x-> { + x.setJobStatus(jobStatus); + x.setServiceInstanceId(instanceId); + }); + + return new NextCommand(jobStatus, new InProgressStatusCommand(uuid, requestId)); + } else { + auditService.setFailedAuditStatusFromMso(uuid,null, msoResponse.getStatusCode(),msoResponse.getRaw()); + return handleCommandFailed(); + } + + } + + private void setInitialRequestAuditStatusFromMso(String requestId){ + final String initialMsoRequestStatus = "REQUESTED"; + asyncInstantiationBL.auditMsoStatus(uuid,initialMsoRequestStatus,requestId,null); + } + + protected NextCommand handleCommandFailed() { + asyncInstantiationBL.handleFailedInstantiation(uuid); + return new NextCommand(Job.JobStatus.FAILED); + } + + @Override + public ServiceInstantiationCommand init(UUID jobUuid, Map<String, Object> data) { + final Object request = data.get("request"); + + return init( + jobUuid, + OBJECT_MAPPER.convertValue(request, ServiceInstantiation.class), + (String) data.get("userId") + ); + } + + private ServiceInstantiationCommand init(UUID jobUuid, ServiceInstantiation serviceInstantiationRequest, String userId) { + this.uuid = jobUuid; + this.serviceInstantiationRequest = serviceInstantiationRequest; + this.userId = userId; + + return this; + } + + @Override + public Map<String, Object> getData() { + return ImmutableMap.of( + "uuid", uuid, + "request", serviceInstantiationRequest, + "userId", userId + ); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobAdapterImpl.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobAdapterImpl.java new file mode 100644 index 00000000..77e1dd2c --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobAdapterImpl.java @@ -0,0 +1,72 @@ +package org.onap.vid.job.impl; + +import com.google.common.collect.ImmutableMap; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobType; +import org.onap.vid.model.JobBulk; +import org.onap.vid.model.JobModel; +import org.springframework.stereotype.Component; + +import javax.ws.rs.BadRequestException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +@Component +public class JobAdapterImpl implements JobAdapter { + + @Override + public JobModel toModel(Job job) { + JobModel jobModel = new JobModel(); + jobModel.setUuid(job.getUuid()); + jobModel.setStatus(job.getStatus()); + jobModel.setTemplateId(job.getTemplateId()); + return jobModel; + } + + @Override + public JobBulk toModelBulk(List<Job> jobList) { + return new JobBulk(jobList.stream().map(this::toModel).collect(Collectors.toList())); + } + + @Override + public Job createJob(JobType jobType, AsyncJobRequest request, UUID templateId, String userId, Integer indexInBulk){ + JobDaoImpl job = new JobDaoImpl(); + job.setStatus(Job.JobStatus.PENDING); + job.setTypeAndData(jobType, ImmutableMap.of( + "request", request, + "userId", userId)); + job.setTemplateId(templateId); + job.setIndexInBulk(indexInBulk); + job.setUserId(userId); + return job; + } + + @Override + public List<Job> createBulkOfJobs(Map<String, Object> bulkRequest) { + int count; + JobType jobType; + + try { + count = (Integer) bulkRequest.get("count"); + jobType = JobType.valueOf((String) bulkRequest.get("type")); + } catch (Exception exception) { + throw new BadRequestException(exception); + } + List<Job> jobList = new ArrayList<>(count + 1); + UUID templateId = UUID.randomUUID(); + for (int i = 0; i < count; i++) { + Job child = new JobDaoImpl(); + child.setTypeAndData(jobType, bulkRequest); + child.setStatus(Job.JobStatus.PENDING); + child.setTemplateId(templateId); + child.setIndexInBulk(i); + jobList.add(child); + } + return jobList; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobDaoImpl.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobDaoImpl.java new file mode 100644 index 00000000..1ff1296c --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobDaoImpl.java @@ -0,0 +1,192 @@ +package org.onap.vid.job.impl; + + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.MoreObjects; +import org.hibernate.annotations.Type; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobType; +import org.onap.vid.model.VidBaseEntity; + +import javax.persistence.*; +import java.io.IOException; +import java.util.*; + +@Entity +@Table(name = "vid_job") +public class JobDaoImpl extends VidBaseEntity implements Job { + + private static ObjectMapper objectMapper = new ObjectMapper(); + private Job.JobStatus status; + private JobType type; + private Map<JobType, Map<String, Object>> data = new TreeMap<>(); + private UUID templateId; + private UUID uuid; + private String takenBy; + private String userId; + private Integer age = 0; + private Integer indexInBulk = 0; + private Date deletedAt; + + @Id + @Column(name = "JOB_ID", columnDefinition = "CHAR(36)") + @Type(type="org.hibernate.type.UUIDCharType") + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + //we use uuid instead id. So making id Transient + @Override + @Transient + @JsonIgnore + public Long getId() { + return this.getUuid().getLeastSignificantBits(); + } + + @Column(name = "JOB_STATUS") + @Enumerated(EnumType.STRING) + public Job.JobStatus getStatus() { + return status; + } + + public void setStatus(Job.JobStatus status) { + this.status = status; + } + + @Enumerated(EnumType.STRING) + @Column(name = "JOB_TYPE") + public JobType getType() { + return type; + } + + public void setType(JobType type) { + this.type = type; + } + + //the columnDefinition is relevant only for UT + @Column(name = "JOB_DATA", columnDefinition = "VARCHAR(30000)") + public String getDataRaw() { + try { + return objectMapper.writeValueAsString(data); + } catch (JsonProcessingException e) { + throw new GenericUncheckedException(e); + } + } + + public void setDataRaw(String data) { + try { + this.data = objectMapper.readValue(data, new TypeReference<Map<JobType, Map<String, Object>>>() { + }); + } catch (IOException e) { + throw new GenericUncheckedException(e); + } + } + + @Transient + public Map<String, Object> getData() { + return data.get(getType()); + } + + @Override + public void setTypeAndData(JobType jobType, Map<String, Object> data) { + // *add* the data to map, + // then change state to given type + this.type = jobType; + this.data.put(jobType, data); + } + + @Column(name = "TAKEN_BY") + public String getTakenBy() { + return takenBy; + } + + public void setTakenBy(String takenBy) { + this.takenBy = takenBy; + } + + @Type(type="org.hibernate.type.UUIDCharType") + @Column(name = "TEMPLATE_ID", columnDefinition = "CHAR(36)") + public UUID getTemplateId() { + return templateId; + } + + @Override + public void setTemplateId(UUID templateId) { + this.templateId = templateId; + } + + @Column(name="INDEX_IN_BULK") + public Integer getIndexInBulk() { + return indexInBulk; + } + + @Override + public void setIndexInBulk(Integer indexInBulk) { + this.indexInBulk = indexInBulk; + } + + @Column(name="USER_ID") + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + @Column(name="AGE") + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + @Column(name="DELETED_AT") + public Date getDeletedAt() { + return deletedAt; + } + + public void setDeletedAt(Date deletedAt) { + this.deletedAt = deletedAt; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof JobDaoImpl)) return false; + JobDaoImpl daoJob = (JobDaoImpl) o; + return Objects.equals(getUuid(), daoJob.getUuid()); + } + + @Override + public int hashCode() { + return Objects.hash(getUuid()); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("status", status) + .add("type", type) + .add("templateId", templateId) + .add("uuid", uuid) + .add("takenBy", takenBy) + .add("userId", userId) + .add("age", age) + .add("created", created) + .add("modified", modified) + .add("deletedAt", deletedAt) + .add("data", data) + .toString(); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobSchedulerInitializer.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobSchedulerInitializer.java new file mode 100644 index 00000000..a5070fbd --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobSchedulerInitializer.java @@ -0,0 +1,76 @@ +package org.onap.vid.job.impl; + +import com.google.common.collect.ImmutableMap; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.command.JobCommandFactory; +import org.onap.vid.properties.Features; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.quartz.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; +import org.springframework.stereotype.Component; +import org.togglz.core.manager.FeatureManager; + +import javax.annotation.PostConstruct; + +import static org.quartz.SimpleScheduleBuilder.simpleSchedule; + +@Component +public class JobSchedulerInitializer { + + private JobsBrokerService jobsBrokerService; + private SchedulerFactoryBean schedulerFactoryBean; + private FeatureManager featureManager; + private JobCommandFactory jobCommandFactory; + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JobSchedulerInitializer.class); + + @Autowired + public JobSchedulerInitializer( + JobsBrokerService jobsBrokerService, + SchedulerFactoryBean schedulerFactoryBean, + FeatureManager featureManager, + JobCommandFactory JobCommandFactory + ) { + this.jobsBrokerService = jobsBrokerService; + this.schedulerFactoryBean = schedulerFactoryBean; + this.featureManager = featureManager; + this.jobCommandFactory = JobCommandFactory; + + } + + @PostConstruct + public void init() { + if (!featureManager.isActive(Features.FLAG_ASYNC_JOBS)) { + return; + } + scheduleJobWorker(Job.JobStatus.PENDING, 1); + scheduleJobWorker(Job.JobStatus.IN_PROGRESS, 1); + } + + private void scheduleJobWorker(Job.JobStatus topic, int intervalInSeconds) { + Scheduler scheduler = schedulerFactoryBean.getScheduler(); + JobDetail jobDetail = JobBuilder.newJob().ofType(JobWorker.class) + .withIdentity("AsyncWorkersJob" + topic) + .withDescription("Job that run async worker for " + topic) + .setJobData(new JobDataMap(ImmutableMap.of( + "jobsBrokerService", jobsBrokerService, + "jobCommandFactory", jobCommandFactory, + "featureManager", featureManager, + "topic", topic + ))) + .build(); + Trigger asyncWorkerTrigger = TriggerBuilder.newTrigger().forJob(jobDetail) + .withIdentity("AsyncWorkersTrigger" + topic) + .withDescription("Trigger to run async worker for " + topic) + .withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(intervalInSeconds)) + .build(); + try { + scheduler.scheduleJob(jobDetail, asyncWorkerTrigger); + } catch (SchedulerException e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to schedule trigger for async worker jobs: {}", e.getMessage()); + throw new GenericUncheckedException(e); + } + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobWorker.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobWorker.java new file mode 100644 index 00000000..aa94a2aa --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobWorker.java @@ -0,0 +1,135 @@ +package org.onap.vid.job.impl; + +import org.apache.commons.lang3.StringUtils; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobCommand; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.NextCommand; +import org.onap.vid.job.command.JobCommandFactory; +import org.onap.vid.properties.Features; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.quartz.JobExecutionContext; +import org.springframework.scheduling.quartz.QuartzJobBean; +import org.springframework.stereotype.Component; +import org.togglz.core.manager.FeatureManager; + +import java.util.Optional; +import java.util.UUID; + +import static org.onap.vid.job.Job.JobStatus.FAILED; +import static org.onap.vid.job.Job.JobStatus.STOPPED; + +@Component +public class JobWorker extends QuartzJobBean { + + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(JobWorker.class); + + private JobsBrokerService jobsBrokerService; + private FeatureManager featureManager; + private JobCommandFactory jobCommandFactory; + private Job.JobStatus topic; + + @Override + protected void executeInternal(JobExecutionContext context) { + Optional<Job> job; + + if (!isMsoNewApiActive()) { + return; + } + + job = pullJob(); + + while (job.isPresent()) { + Job nextJob = executeJobAndGetNext(job.get()); + pushBack(nextJob); + + job = pullJob(); + } + } + + private Optional<Job> pullJob() { + try { + return jobsBrokerService.pull(topic, UUID.randomUUID().toString()); + } catch (Exception e) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "failed to pull job from queue, breaking: {}", e, e); + return Optional.empty(); + } + } + + private void pushBack(Job nextJob) { + try { + jobsBrokerService.pushBack(nextJob); + } catch (Exception e) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "failed pushing back job to queue: {}", e, e); + } + } + + protected Job executeJobAndGetNext(Job job) { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "going to execute job {} of {}: {}/{}", + StringUtils.substring(String.valueOf(job.getUuid()), 0, 8), + StringUtils.substring(String.valueOf(job.getTemplateId()), 0, 8), + job.getStatus(), job.getType()); + + NextCommand nextCommand = executeCommandAndGetNext(job); + + Job nextJob = setNextCommandInJob(nextCommand, job); + + return nextJob; + } + + private NextCommand executeCommandAndGetNext(Job job) { + NextCommand nextCommand; + try { + final JobCommand jobCommand = jobCommandFactory.toCommand(job); + nextCommand = jobCommand.call(); + } catch (Exception e) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "error while executing job from queue: {}", e, e); + nextCommand = new NextCommand(FAILED); + } + + if (nextCommand == null) { + nextCommand = new NextCommand(STOPPED); + } + return nextCommand; + } + + private Job setNextCommandInJob(NextCommand nextCommand, Job job) { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "transforming job {} of {}: {}/{} -> {}{}", + StringUtils.substring(String.valueOf(job.getUuid()), 0, 8), + StringUtils.substring(String.valueOf(job.getTemplateId()), 0, 8), + job.getStatus(), job.getType(), + nextCommand.getStatus(), + nextCommand.getCommand() != null ? ("/" + nextCommand.getCommand().getType()) : ""); + + job.setStatus(nextCommand.getStatus()); + + if (nextCommand.getCommand() != null) { + job.setTypeAndData(nextCommand.getCommand().getType(), nextCommand.getCommand().getData()); + } + + return job; + } + + private boolean isMsoNewApiActive() { + return featureManager.isActive(Features.FLAG_ASYNC_INSTANTIATION); + } + + + //used by quartz to inject JobsBrokerService into the job + //see JobSchedulerInitializer + public void setJobsBrokerService(JobsBrokerService jobsBrokerService) { + this.jobsBrokerService = jobsBrokerService; + } + + public void setFeatureManager(FeatureManager featureManager) { + this.featureManager = featureManager; + } + + public void setJobCommandFactory(JobCommandFactory jobCommandFactory) { + this.jobCommandFactory = jobCommandFactory; + } + + public void setTopic(Job.JobStatus topic) { + this.topic = topic; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobsBrokerServiceInDatabaseImpl.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobsBrokerServiceInDatabaseImpl.java new file mode 100644 index 00000000..e286cc4a --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobsBrokerServiceInDatabaseImpl.java @@ -0,0 +1,236 @@ +package org.onap.vid.job.impl; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.exceptions.OperationNotAllowedException; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.properties.VidProperties; +import org.onap.vid.utils.DaoUtils; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.nio.ByteBuffer; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.*; + +@Service +public class JobsBrokerServiceInDatabaseImpl implements JobsBrokerService { + + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JobsBrokerServiceInDatabaseImpl.class); + + private final DataAccessService dataAccessService; + + private final SessionFactory sessionFactory; + private int maxOpenedInstantiationRequestsToMso; + private int pollingIntervalSeconds; + + @Autowired + public JobsBrokerServiceInDatabaseImpl(DataAccessService dataAccessService, SessionFactory sessionFactory, + @Value("0") int maxOpenedInstantiationRequestsToMso, + @Value("10") int pollingIntervalSeconds) { + // tha @Value will inject conservative defaults; overridden in @PostConstruct from configuration + this.dataAccessService = dataAccessService; + this.sessionFactory = sessionFactory; + this.maxOpenedInstantiationRequestsToMso = maxOpenedInstantiationRequestsToMso; + this.pollingIntervalSeconds = pollingIntervalSeconds; + } + + @PostConstruct + public void configure() { + maxOpenedInstantiationRequestsToMso = Integer.parseInt(SystemProperties.getProperty(VidProperties.MSO_MAX_OPENED_INSTANTIATION_REQUESTS)); + pollingIntervalSeconds = Integer.parseInt(SystemProperties.getProperty(VidProperties.MSO_ASYNC_POLLING_INTERVAL_SECONDS)); + } + + public void deleteAll() { + dataAccessService.deleteDomainObjects(JobDaoImpl.class, "1=1", null); + } + + @Override + public UUID add(Job job) { + final JobDaoImpl jobDao = castToJobDaoImpl(job); + jobDao.setUuid(UUID.randomUUID()); + dataAccessService.saveDomainObject(jobDao, DaoUtils.getPropsMap()); + return job.getUuid(); + } + + @Override + public Optional<Job> pull(Job.JobStatus topic, String ownerId) { + JobDaoImpl daoJob; + int updatedEntities; + do { + String query = sqlQueryForTopic(topic); + List<JobDaoImpl> jobs = dataAccessService.executeSQLQuery(query, JobDaoImpl.class, null); + if (jobs.isEmpty()) { + return Optional.empty(); + } + + daoJob = jobs.get(0); + + final UUID uuid = daoJob.getUuid(); + final Integer age = daoJob.getAge(); + + daoJob.setTakenBy(ownerId); + + // It might become that daoJob was taken and pushed-back already, before we + // arrived here, so we're verifying the age was not pushed forward. + // Age is actually forwarded upon pushBack(). + String hqlUpdate = "update JobDaoImpl job set job.takenBy = :takenBy where " + + " job.id = :id" + + " and job.age = :age" + + " and takenBy is null"; + updatedEntities = DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> + session.createQuery(hqlUpdate) + .setText("id", uuid.toString()) + .setInteger("age", age) + .setText("takenBy", ownerId) + .executeUpdate()); + + } while (updatedEntities == 0); + + return Optional.ofNullable(daoJob); + } + + private java.sql.Timestamp nowMinusInterval() { + return Timestamp.valueOf(LocalDateTime.now().minusSeconds(pollingIntervalSeconds)); + } + + private String sqlQueryForTopic(Job.JobStatus topic) { + switch (topic) { + case IN_PROGRESS: + return "" + + "select * from VID_JOB" + + " where" + + // select only non-deleted in-progress jobs + " JOB_STATUS = 'IN_PROGRESS'" + + " and TAKEN_BY is null" + + " and DELETED_AT is null" + + // give some breath, don't select jos that were recently reached + " and MODIFIED_DATE <= '" + nowMinusInterval() + + // take the oldest handled one + "' order by MODIFIED_DATE ASC" + + // select only one result + " limit 1"; + + case PENDING: + return "" + + // select only pending jobs + "select vid_job.* from VID_JOB " + + // select users have in_progress jobs + "left join \n" + + " (select user_Id, 1 as has_any_in_progress_job from VID_JOB where JOB_STATUS = 'IN_PROGRESS' or TAKEN_BY IS NOT NULL \n" + + "group by user_id) users_have_any_in_progress_job_tbl\n" + + "on vid_job.user_id = users_have_any_in_progress_job_tbl.user_id " + + "where JOB_STATUS = 'PENDING' and TAKEN_BY is null" + + // job is not deleted + " AND DELETED_AT is null and (\n" + + // limit in-progress to some amount + "select sum(CASE WHEN JOB_STATUS='IN_PROGRESS' or (JOB_STATUS='PENDING' and TAKEN_BY IS NOT NULL) THEN 1 ELSE 0 END) as in_progress\n" + + "from VID_JOB ) <" + maxOpenedInstantiationRequestsToMso + " \n " + + // don't take jobs from templates that already in-progress/failed + "and TEMPLATE_Id not in \n" + + "(select TEMPLATE_Id from vid_job where" + + " (JOB_STATUS='FAILED' and DELETED_AT is null)" + // failed but not deleted + " or JOB_STATUS='IN_PROGRESS'" + + " or TAKEN_BY IS NOT NULL)" + " \n " + + // prefer older jobs, but the earlier in each bulk + "order by has_any_in_progress_job, CREATED_DATE, INDEX_IN_BULK " + + // select only one result + "limit 1"; + default: + throw new GenericUncheckedException("Unsupported topic to pull from: " + topic); + } + } + + + private byte[] getUuidAsByteArray(UUID owner) { + ByteBuffer bb = ByteBuffer.wrap(new byte[16]); + bb.putLong(owner.getMostSignificantBits()); + bb.putLong(owner.getLeastSignificantBits()); + return bb.array(); + } + + @Override + public void pushBack(Job job) { + final JobDaoImpl remoteDaoJob = (JobDaoImpl) dataAccessService.getDomainObject(JobDaoImpl.class, job.getUuid(), null); + + if (remoteDaoJob == null) { + throw new IllegalStateException("Can push back only pulled jobs. Add new jobs using add()"); + } + + if (remoteDaoJob.getTakenBy() == null) { + throw new IllegalStateException("Can push back only pulled jobs. This one already pushed back."); + } + + final JobDaoImpl jobDao = castToJobDaoImpl(job); + + jobDao.setTakenBy(null); + + Integer age = jobDao.getAge(); + jobDao.setAge(age + 1); + + logger.debug(EELFLoggerDelegate.debugLogger, "{}/{}", jobDao.getStatus(), jobDao.getType()); + + dataAccessService.saveDomainObject(jobDao, DaoUtils.getPropsMap()); + } + + private JobDaoImpl castToJobDaoImpl(Job job) { + if (!(job instanceof JobDaoImpl)) { + throw new UnsupportedOperationException("Can't add " + job.getClass() + " to " + this.getClass()); + } + return (JobDaoImpl) job; + } + + @Override + public Collection<Job> peek() { + return dataAccessService.getList(JobDaoImpl.class, null); + } + + @Override + public Job peek(UUID jobId) { + return (JobDaoImpl) dataAccessService.getDomainObject(JobDaoImpl.class, jobId, null); + } + + @Override + public void delete(UUID jobId) { + int updatedEntities; + Date now = new Date(); + + String hqlUpdate = "update JobDaoImpl job set job.deletedAt = :now where " + + " job.id = :id" + + " and job.status in(:pending, :stopped)" + + " and takenBy is null"; + + updatedEntities = DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> + session.createQuery(hqlUpdate) + .setTimestamp("now", now) + .setText("id", jobId.toString()) + .setText("pending", Job.JobStatus.PENDING.toString()) + .setText("stopped", Job.JobStatus.STOPPED.toString()) + .executeUpdate()); + + if (updatedEntities == 0) { + final JobDaoImpl remoteDaoJob = (JobDaoImpl) dataAccessService.getDomainObject(JobDaoImpl.class, jobId, null); + + if (remoteDaoJob == null || remoteDaoJob.getUuid() == null) { + logger.debug(EELFLoggerDelegate.debugLogger,"jobId {}: Service does not exist", jobId); + throw new OperationNotAllowedException("Service does not exist"); + } + + if (!remoteDaoJob.getStatus().equals(Job.JobStatus.PENDING) && !remoteDaoJob.getStatus().equals(Job.JobStatus.STOPPED) || !StringUtils.isEmpty(remoteDaoJob.getTakenBy()) ) { + logger.debug(EELFLoggerDelegate.debugLogger,"jobId {}: Service status does not allow deletion from the queue, status = {}", jobId, remoteDaoJob.getStatus() + + ", takenBy " + remoteDaoJob.getTakenBy()); + throw new OperationNotAllowedException("Service status does not allow deletion from the queue"); + } + + throw new OperationNotAllowedException("Service deletion failed"); + } + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/CR.java b/vid-app-common/src/main/java/org/onap/vid/model/CR.java new file mode 100644 index 00000000..f8c046e7 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/CR.java @@ -0,0 +1,80 @@ +package org.onap.vid.model; + +import java.util.HashMap; +import java.util.Map; + +public class CR extends Node{ + + private String category; + + private String subcategory; + + private String resourceVendor; + + private String resourceVendorRelease; + + private String resourceVendorModelNumber; + + private String customizationUUID; + + private Map<String, NetworkCollection> networksCollection = new HashMap<String, NetworkCollection>(); + + + + public Map<String, NetworkCollection> getNetworksCollection() { + return networksCollection; + } + + public void setNetworksCollection(Map<String, NetworkCollection> networksCollection) { + this.networksCollection = networksCollection; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubcategory() { + return subcategory; + } + + public void setSubcategory(String subcategory) { + this.subcategory = subcategory; + } + + public String getResourceVendor() { + return resourceVendor; + } + + public void setResourceVendor(String resourceVendor) { + this.resourceVendor = resourceVendor; + } + + public String getResourceVendorRelease() { + return resourceVendorRelease; + } + + public void setResourceVendorRelease(String resourceVendorRelease) { + this.resourceVendorRelease = resourceVendorRelease; + } + + public String getResourceVendorModelNumber() { + return resourceVendorModelNumber; + } + + public void setResourceVendorModelNumber(String resourceVendorModelNumber) { + this.resourceVendorModelNumber = resourceVendorModelNumber; + } + + public String getCustomizationUUID() { + return customizationUUID; + } + + public void setCustomizationUUID(String customizationUUID) { + this.customizationUUID = customizationUUID; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/CategoryParameter.java b/vid-app-common/src/main/java/org/onap/vid/model/CategoryParameter.java index a98a71bc..99824e72 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/CategoryParameter.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/CategoryParameter.java @@ -1,19 +1,16 @@ package org.onap.vid.model; //import org.hibernate.annotations.Table; -import org.onap.portalsdk.core.domain.support.DomainVo; -import org.onap.vid.controllers.MaintenanceController; -//import javax.persistence.*; import javax.persistence.*; -import java.io.Serializable; -import java.util.Date; import java.util.HashSet; import java.util.Set; +//import javax.persistence.*; + @Entity @Table(name = "vid_category_parameter", uniqueConstraints = @UniqueConstraint(columnNames = "name")) -public class CategoryParameter extends DomainVo { +public class CategoryParameter extends VidBaseEntity { public enum Family { PARAMETER_STANDARDIZATION, @@ -45,30 +42,6 @@ public class CategoryParameter extends DomainVo { return super.getId(); } - @Override - @Column(name = "CREATED_DATE") - public Date getCreated() { - return super.getCreated(); - } - - @Override - @Column(name = "MODIFIED_DATE") - public Date getModified() { - return super.getModified(); - } - - @Override - @Transient - public Long getCreatedId() { - return super.getCreatedId(); - } - - @Override - @Transient - public Long getModifiedId() { - return super.getModifiedId(); - } - @Column(name = "NAME", unique = true, nullable = false, length=50) public String getName() { return name; @@ -78,24 +51,6 @@ public class CategoryParameter extends DomainVo { this.name = name; } - @Override - @Transient - public Serializable getAuditUserId() { - return super.getAuditUserId(); - } - - @Override - @Transient - public Long getRowNum() { - return super.getRowNum(); - } - - @Override - @Transient - public Set getAuditTrail() { - return super.getAuditTrail(); - } - @OneToMany(fetch = FetchType.EAGER, mappedBy = "categoryParameter") public Set<CategoryParameterOption> getOptions() { return options; diff --git a/vid-app-common/src/main/java/org/onap/vid/model/CategoryParameterOption.java b/vid-app-common/src/main/java/org/onap/vid/model/CategoryParameterOption.java index 141d2c14..5cccc835 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/CategoryParameterOption.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/CategoryParameterOption.java @@ -11,7 +11,6 @@ import java.util.Set; @Table(name = "vid_category_parameter_option") public class CategoryParameterOption extends DomainVo { - private Long id; private String appId; private String name; @@ -33,10 +32,6 @@ public class CategoryParameterOption extends DomainVo { return id; } - public void setId(Long id) { - this.id = id; - } - @Column(name = "CATEGORY_OPT_APP_ID") public String getAppId() { return appId; diff --git a/vid-app-common/src/main/java/org/onap/vid/model/Group.java b/vid-app-common/src/main/java/org/onap/vid/model/Group.java new file mode 100644 index 00000000..5f98341d --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/Group.java @@ -0,0 +1,212 @@ +package org.onap.vid.model; + +import org.onap.vid.asdc.beans.tosca.Input; +import org.onap.vid.asdc.parser.ToscaParserImpl2; + +import java.util.Map; + +public class Group { + + + /** The uuid. */ + private String uuid; + + /** The invariant uuid. */ + private String invariantUuid; + + /** The customization uuid. */ + private String customizationUuid; + + /** The description. */ + private String description; + + /** The name. */ + private String name; + + /** The version. */ + private String version; + + /** The model customization name. */ + private String modelCustomizationName; + + /** The group properties. */ + private GroupProperties properties; + + private Map<String, Input> inputs; + + + /** + * Gets the model customization name. + * + * @return the model customization name + */ + public String getModelCustomizationName() { + return modelCustomizationName; + } + /** + * Gets the uuid. + * + * @return the uuid + */ + public String getUuid() { + return uuid; + } + + /** + * Gets the invariant uuid. + * + * @return the invariant uuid + */ + public String getInvariantUuid() { + return invariantUuid; + } + /** + * Gets the customization uuid. + * + * @return the invariant uuid + */ + public String getCustomizationUuid() { + return customizationUuid; + } + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + return description; + } + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Gets the version. + * + * @return the version + */ + public String getVersion() { + return version; + } + + /** + * Gets the properties. + * + * @return the properties + */ + public GroupProperties getProperties() { + return properties; + } + /** + * Sets the uuid. + * + * @param uuid the new uuid + */ + public void setUuid(String uuid) { + this.uuid = uuid; + } + + /** + * Sets the invariant uuid. + * + * @param invariantUuid the new invariant uuid + */ + public void setInvariantUuid(String invariantUuid) { + this.invariantUuid = invariantUuid; + } + /** + * Sets the customization uuid. + * + * @param customizationUuid the new customization uuid + */ + public void setCustomizationUuid(String customizationUuid) { + this.customizationUuid = customizationUuid; + } + /** + * Sets the description. + * + * @param description the new description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Sets the name. + * + * @param name the new name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Sets the version. + * + * @param version the new version + */ + public void setVersion(String version) { + this.version = version; + } + + public Map<String, Input> getInputs() { + return inputs; + } + + public void setInputs(Map<String, Input> inputs) { + this.inputs = inputs; + } + + /** + * Sets the model customization name. + * + * @param modelCustomizationName the new model customization name + */ + public void setModelCustomizationName(String modelCustomizationName) { + this.modelCustomizationName = modelCustomizationName; + } + /** + * Sets the group properties. + * + * @param properties the new model customization name + */ + public void setProperties(GroupProperties properties) { + this.properties = properties; + } + + + + protected static GroupProperties extractPropertiesForGroup(org.onap.vid.asdc.beans.tosca.Group group){ + String [] propertyKeys = {ToscaParserImpl2.Constants.MIN_VF_MODULE_INSTANCES, ToscaParserImpl2.Constants.MAX_VF_MODULE_INSTANCES, ToscaParserImpl2.Constants.INITIAL_COUNT}; + GroupProperties groupProperties = new GroupProperties(); + + for(String propertyKey : propertyKeys){ + Object val = group.getProperties().get(propertyKey); + if (val != null && val instanceof Integer) { + setInGroupProperties(groupProperties, propertyKey, (Integer) val); + } + } + return groupProperties; + } + + private static void setInGroupProperties(GroupProperties groupProperties, String propertyKey, Integer propertyValue){ + switch (propertyKey) { + case ToscaParserImpl2.Constants.MIN_VF_MODULE_INSTANCES: + groupProperties.setMinCountInstances(propertyValue); + break; + case ToscaParserImpl2.Constants.MAX_VF_MODULE_INSTANCES: + groupProperties.setMaxCountInstances(propertyValue); + break; + case ToscaParserImpl2.Constants.INITIAL_COUNT: + groupProperties.setInitialCount(propertyValue); + break; + default: + // do noting + } + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/GroupProperties.java b/vid-app-common/src/main/java/org/onap/vid/model/GroupProperties.java new file mode 100644 index 00000000..c7ca6006 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/GroupProperties.java @@ -0,0 +1,40 @@ +package org.onap.vid.model; + +public class GroupProperties { + private Integer minCountInstances; + private Integer maxCountInstances; + private Integer initialCount; + private String vfModuleLabel; + + public String getVfModuleLabel() { + return vfModuleLabel; + } + + public void setVfModuleLabel(String vfModuleLabel) { + this.vfModuleLabel = vfModuleLabel; + } + + public Integer getMinCountInstances() { + return minCountInstances; + } + + public void setMinCountInstances(Integer minCountInstances) { + this.minCountInstances = minCountInstances; + } + + public Integer getMaxCountInstances() { + return maxCountInstances; + } + + public void setMaxCountInstances(Integer maxCountInstances) { + this.maxCountInstances = maxCountInstances; + } + + public Integer getInitialCount() { + return initialCount; + } + + public void setInitialCount(Integer initialCount) { + this.initialCount = initialCount; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/JobAuditStatus.java b/vid-app-common/src/main/java/org/onap/vid/model/JobAuditStatus.java new file mode 100644 index 00000000..61426799 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/JobAuditStatus.java @@ -0,0 +1,159 @@ +package org.onap.vid.model; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.hibernate.annotations.Type; +import org.onap.vid.job.Job.JobStatus; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; + +import javax.persistence.*; +import java.util.Date; +import java.util.UUID; + +@Entity +@Table(name = "vid_job_audit_status") +public class JobAuditStatus extends VidBaseEntity { + + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JobAuditStatus.class); + + public JobAuditStatus(){} + + public JobAuditStatus(UUID jobId, String jobStatus, SourceStatus source){ + this.jobId = jobId; + this.jobStatus = jobStatus; + this.source = source; + } + + public JobAuditStatus(UUID jobId, String jobStatus, SourceStatus source, Date date){ + this(jobId, jobStatus, source); + this.created = date; + } + + public JobAuditStatus(UUID jobId, String jobStatus, SourceStatus source, UUID requestId, String additionalInfo) { + this(jobId, jobStatus, source); + this.requestId = requestId; + this.additionalInfo = additionalInfo; + } + + public JobAuditStatus(UUID jobId, String jobStatus, SourceStatus source, UUID requestId, String additionalInfo, Date date){ + this(jobId, jobStatus, source, requestId, additionalInfo); + this.created = date; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + + if (o == null || getClass() != o.getClass()) return false; + + JobAuditStatus that = (JobAuditStatus) o; + + return new EqualsBuilder() + .append(jobId, that.jobId) + .append(jobStatus, that.jobStatus) + .append(source, that.source) + .append(requestId, that.requestId) + .append(additionalInfo, that.additionalInfo) + .isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(17, 37) + .append(jobId) + .append(jobStatus) + .append(source) + .append(requestId) + .append(additionalInfo) + .toHashCode(); + } + + public enum SourceStatus { + MSO, + VID + } + + private UUID jobId; + private String jobStatus; + private SourceStatus source; + private UUID requestId; + private String additionalInfo; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Override + @Column(name = "ID", columnDefinition = "INT(11)") + public Long getId() { + return this.id; + } + + @Column(name = "JOB_ID", columnDefinition = "CHAR(36)") + @Type(type="org.hibernate.type.UUIDCharType") + public UUID getJobId() { + return jobId; + } + + public void setJobId(UUID jobId) { + this.jobId = jobId; + } + + + @Column(name = "JOB_STATUS") + public String getJobStatus() { + return jobStatus; + } + + public void setJobStatus(String jobStatus) { + this.jobStatus = jobStatus; + } + + + @Enumerated(EnumType.STRING) + @Column(name = "SOURCE") + public SourceStatus getSource() { + return source; + } + + public void setSource(SourceStatus source) { + this.source = source; + } + + @Column(name = "REQUEST_ID", columnDefinition = "CHAR(36)") + @Type(type="org.hibernate.type.UUIDCharType") + public UUID getRequestId() { + return requestId; + } + + public void setRequestId(UUID requestId) { + this.requestId = requestId; + } + + @Column(name = "ADDITIONAL_INFO") + public String getAdditionalInfo() { + return additionalInfo; + } + + public void setAdditionalInfo(String additionalInfo) { + this.additionalInfo = additionalInfo; + } + + @Transient + public Boolean isFinal(){ + try { + if (getSource() == SourceStatus.VID) { + return JobStatus.valueOf(getJobStatus()).isFinal(); + } + } + catch (IllegalArgumentException e){ + logger.error("JobStatus: " + getJobStatus() + " from vid isn't a value of JobStatus enum" + e.getMessage()); + return false; + } + return false; + } + + @Transient + public Date getCreatedDate() { + return getCreated(); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/JobBulk.java b/vid-app-common/src/main/java/org/onap/vid/model/JobBulk.java new file mode 100644 index 00000000..40050277 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/JobBulk.java @@ -0,0 +1,20 @@ +package org.onap.vid.model; + +import java.util.List; + +public class JobBulk { + + private List<JobModel> jobs; + + public JobBulk(List<JobModel> jobs) { + this.jobs = jobs; + } + + public List<JobModel> getJobs() { + return jobs; + } + + public void setJobs(List<JobModel> jobs) { + this.jobs = jobs; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/JobModel.java b/vid-app-common/src/main/java/org/onap/vid/model/JobModel.java new file mode 100644 index 00000000..bd2b46c6 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/JobModel.java @@ -0,0 +1,47 @@ +package org.onap.vid.model; + +import org.onap.vid.job.Job; +import org.onap.vid.job.JobType; + +import java.util.UUID; + +public class JobModel { + + private UUID uuid; + private Job.JobStatus status; + private UUID templateId; + private JobType type; + + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public Job.JobStatus getStatus() { + return status; + } + + public void setStatus(Job.JobStatus status) { + this.status = status; + } + + public UUID getTemplateId() { + return templateId; + } + + public void setTemplateId(UUID templateId) { + this.templateId = templateId; + } + + public JobType getType() { + return type; + } + + public void setType(JobType type) { + this.type = type; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/NameCounter.java b/vid-app-common/src/main/java/org/onap/vid/model/NameCounter.java new file mode 100644 index 00000000..aae39e44 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/NameCounter.java @@ -0,0 +1,42 @@ +package org.onap.vid.model; + + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "vid_name_counter") +public class NameCounter { + + private String name; + private Integer counter; + + public NameCounter() { + } + + public NameCounter(String name) { + this.name = name; + this.counter = 1; + } + + @Id + @Column(name = "name", columnDefinition = "VARCHAR(100)") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Column(name = "counter", columnDefinition = "INT") + public Integer getCounter() { + return counter; + } + + public void setCounter(Integer counter) { + this.counter = counter; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/NetworkCollection.java b/vid-app-common/src/main/java/org/onap/vid/model/NetworkCollection.java new file mode 100644 index 00000000..69ff286d --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/NetworkCollection.java @@ -0,0 +1,59 @@ +package org.onap.vid.model; + +public class NetworkCollection { + + private String uuid; + + private String invariantUuid; + + private String name; + + private String version; + + private NetworkCollectionProperties networkCollectionProperties; + + public NetworkCollection(){ + this.networkCollectionProperties = new NetworkCollectionProperties(); + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getInvariantUuid() { + return invariantUuid; + } + + public void setInvariantUuid(String invariantUuid) { + this.invariantUuid = invariantUuid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public NetworkCollectionProperties getNetworkCollectionProperties() { + return networkCollectionProperties; + } + + public void setNetworkCollectionProperties(NetworkCollectionProperties networkCollectionProperties) { + this.networkCollectionProperties = networkCollectionProperties; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/NetworkCollectionProperties.java b/vid-app-common/src/main/java/org/onap/vid/model/NetworkCollectionProperties.java new file mode 100644 index 00000000..16edff7a --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/NetworkCollectionProperties.java @@ -0,0 +1,22 @@ +package org.onap.vid.model; + +public class NetworkCollectionProperties { + private String networkCollectionFunction; + private String networkCollectionDescription; + + public String getNetworkCollectionFunction() { + return networkCollectionFunction; + } + + public void setNetworkCollectionFunction(String networkCollectionFunction) { + this.networkCollectionFunction = networkCollectionFunction; + } + + public String getNetworkCollectionDescription() { + return networkCollectionDescription; + } + + public void setNetworkCollectionDescription(String networkCollectionDescription) { + this.networkCollectionDescription = networkCollectionDescription; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/NewService.java b/vid-app-common/src/main/java/org/onap/vid/model/NewService.java index 1346c0d9..6d525506 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/NewService.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/NewService.java @@ -20,11 +20,11 @@ package org.onap.vid.model; +import org.onap.vid.asdc.beans.tosca.Input; + import java.util.Map; import java.util.UUID; -import org.onap.vid.asdc.beans.tosca.Input; - /** * The Class Service. */ @@ -220,9 +220,7 @@ public class NewService { */ @Override public int hashCode() { - final UUID uuid = UUID.fromString(getUuid()); - - return uuid.hashCode(); + return UUID.fromString(getUuid()).hashCode(); } /* (non-Javadoc) @@ -237,16 +235,4 @@ public class NewService { return (service.getUuid().equals(getUuid())); } - /*public static void extractVfModuleCustomizationUUID (Service s, String vnfCustomizationName, VfModule vfMod ) { - - //Look for vnfCustomizationName..vfModuleCustomizationName - String nameToFind = vnfCustomizationName + ".." + vfMod.getModelCustomizationName(); - for (Entry<UUID, VfModule> vfModuleComponent : s.getVfModules().entrySet()) { - VfModule xMod = vfModuleComponent.getValue(); - if ( (xMod.getModelCustomizationName() != null) && (xMod.getModelCustomizationName().equalsIgnoreCase(nameToFind)) ) { - vfMod.setCustomizationUuid( xMod.getCustomizationUuid()); - return; - } - } - }*/ } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/NewServiceModel.java b/vid-app-common/src/main/java/org/onap/vid/model/NewServiceModel.java index 9ac0836a..e55ba4a4 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/NewServiceModel.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/NewServiceModel.java @@ -67,6 +67,9 @@ public class NewServiceModel { private Map<String, Node> pnfs; + private Map<String, CR> collectionResource; + + /** * Instantiates a new service model. */ @@ -178,6 +181,14 @@ public class NewServiceModel { this.pnfs = pnfs; } + public Map<String, CR> getCollectionResource() { + return collectionResource; + } + + public void setCollectionResource(Map<String, CR> collectionResource) { + this.collectionResource = collectionResource; + } + /** * Extract service. * diff --git a/vid-app-common/src/main/java/org/onap/vid/model/Node.java b/vid-app-common/src/main/java/org/onap/vid/model/Node.java index 474dfb55..3b7abd39 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/Node.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/Node.java @@ -60,7 +60,7 @@ public class Node { private String customizationUuid; /** The inputs. */ - private Map<String, Input> inputs; + private Map<String, Input> inputs = new HashMap<>(); /** The get_input or other constructs from node template properties. */ private Map<String, CommandProperty> commands; @@ -271,45 +271,10 @@ public class Node { try { // nodeTemplate.getProperties() map of String->Object - for (Entry<String, Object> e : nodeTemplate.getProperties().entrySet()) { - - String k = e.getKey(); - - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " node template property: " + k ); - - if ( e.getValue() != null ) { - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " property: " + - k + "=" + e.getValue()); - //LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " V class name: " + - // e.getValue().getClass().getName()); - Class<?> c = e.getValue().getClass(); - if ( c.getName().equalsIgnoreCase(java.lang.String.class.getName())) { - getProperties().put (k, (String)e.getValue()); - } - else { - Class<?>[] interfaces = e.getValue().getClass().getInterfaces(); - - for(Class<?> ifc: interfaces ) { - //LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " ifc name: " + - // ifc.getName()); - if ( ifc.getName().equalsIgnoreCase(java.util.Map.class.getName()) ) { - // only extract get_input for now - @SuppressWarnings("unchecked") - HashMap<String,String> v = (HashMap<String,String>)e.getValue(); - for (Entry<String, String> entry : v.entrySet()) { - // only include get_input for now - if ( ModelConstants.GET_INPUT_TAG.equalsIgnoreCase ( entry.getKey() ) ) { - CommandProperty cp = new CommandProperty(); - cp.setCommand(entry.getKey()); - cp.setInputName(entry.getValue()); - cp.setDisplayName(k); - getCommands().put(k,cp); - } - } - } - } - - } + for (Entry<String, Object> entrySet : nodeTemplate.getProperties().entrySet()) { + LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " node template property: " + entrySet.getKey()); + if ( entrySet.getValue() != null ) { + readStringAndCommandsProperties(entrySet); } } } @@ -319,4 +284,42 @@ public class Node { } } + private void readStringAndCommandsProperties(Entry<String, Object> entrySet) { + String key = entrySet.getKey(); + String methodName = "readStringAndCommandsProperties"; + LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " property: " + + key + "=" + entrySet.getValue()); + Class<?> c = entrySet.getValue().getClass(); + if ( c.getName().equalsIgnoreCase(String.class.getName())) { + getProperties().put (key, (String) entrySet.getValue()); + } + else { + Class<?>[] interfaces = entrySet.getValue().getClass().getInterfaces(); + + for(Class<?> ifc: interfaces ) { + if ( ifc.getName().equalsIgnoreCase(Map.class.getName()) ) { + readGetInputAsCommands(entrySet, key); + + } + } + + } + } + + private void readGetInputAsCommands(Entry<String, Object> entrySet, String key) { + // only extract get_input for now + @SuppressWarnings("unchecked") + HashMap<String,String> v = (HashMap<String,String>) entrySet.getValue(); + for (Entry<String, String> entry : v.entrySet()) { + // only include get_input for now + if ( ModelConstants.GET_INPUT_TAG.equalsIgnoreCase ( entry.getKey() ) ) { + CommandProperty cp = new CommandProperty(); + cp.setCommand(entry.getKey()); + cp.setInputName(entry.getValue()); + cp.setDisplayName(key); + getCommands().put(key,cp); + } + } + } + } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/PombaInstance/PombaRequest.java b/vid-app-common/src/main/java/org/onap/vid/model/PombaInstance/PombaRequest.java new file mode 100644 index 00000000..f7327acf --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/PombaInstance/PombaRequest.java @@ -0,0 +1,7 @@ +package org.onap.vid.model.PombaInstance; + +import java.util.List; + +public class PombaRequest { + public List<ServiceInstance> serviceInstanceList; +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/PombaInstance/ServiceInstance.java b/vid-app-common/src/main/java/org/onap/vid/model/PombaInstance/ServiceInstance.java new file mode 100644 index 00000000..08b224a3 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/PombaInstance/ServiceInstance.java @@ -0,0 +1,21 @@ +package org.onap.vid.model.PombaInstance; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ServiceInstance { + + @JsonProperty + public String serviceInstanceId; + + @JsonProperty + public String modelVersionId; + + @JsonProperty + public String modelInvariantId; + + @JsonProperty + public String customerId; + + @JsonProperty + public String serviceType; +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/Service.java b/vid-app-common/src/main/java/org/onap/vid/model/Service.java index b0597c64..d00f58f0 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/Service.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/Service.java @@ -234,9 +234,7 @@ public class Service { */ @Override public int hashCode() { - final UUID uuid = UUID.fromString(getUuid()); - - return uuid.hashCode(); + return UUID.fromString(getUuid()).hashCode(); } /* (non-Javadoc) @@ -267,17 +265,4 @@ public class Service { public void setServiceRole(String serviceRole) { this.serviceRole = serviceRole; } - - /*public static void extractVfModuleCustomizationUUID (Service s, String vnfCustomizationName, VfModule vfMod ) { - - //Look for vnfCustomizationName..vfModuleCustomizationName - String nameToFind = vnfCustomizationName + ".." + vfMod.getModelCustomizationName(); - for (Entry<UUID, VfModule> vfModuleComponent : s.getVfModules().entrySet()) { - VfModule xMod = vfModuleComponent.getValue(); - if ( (xMod.getModelCustomizationName() != null) && (xMod.getModelCustomizationName().equalsIgnoreCase(nameToFind)) ) { - vfMod.setCustomizationUuid( xMod.getCustomizationUuid()); - return; - } - } - }*/ } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/ServiceInfo.java b/vid-app-common/src/main/java/org/onap/vid/model/ServiceInfo.java new file mode 100644 index 00000000..4f04adf5 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/ServiceInfo.java @@ -0,0 +1,395 @@ + package org.onap.vid.model; + + + import org.hibernate.annotations.Type; + import org.onap.vid.job.Job; + import org.onap.portalsdk.core.domain.support.DomainVo; + + import javax.persistence.*; + import java.io.Serializable; + import java.util.Date; + import java.util.Objects; + import java.util.Set; + import java.util.UUID; + +@Entity +@Table(name = "vid_service_info") +public class ServiceInfo extends DomainVo { + + public void setUserId(String userId) { + this.userId = userId; + } + + private UUID jobId; + private UUID templateId; + private String userId; + private Job.JobStatus jobStatus; + private Date statusModifiedDate; + private boolean hidden; + private boolean pause; + private Date deletedAt; + private String owningEntityId; + private String owningEntityName; + private String project; + private String aicZoneId; + private String aicZoneName; + private String tenantId; + private String tenantName; + private String regionId; + private String regionName; + private String serviceType; + private String subscriberName; + private String serviceInstanceId; + private String serviceInstanceName; + private String serviceModelId; + private String serviceModelName; + private String serviceModelVersion; + private Date createdBulkDate; + + public ServiceInfo(){ + + } + + public ServiceInfo(String userId, Job.JobStatus jobStatus, boolean pause, UUID jobId, UUID templateId, String owningEntityId, String owningEntityName, String project, String aicZoneId, String aicZoneName, String tenantId, String tenantName, String regionId, String regionName, String serviceType, String subscriberName, String serviceInstanceId, String serviceInstanceName, String serviceModelId, String serviceModelName, String serviceModelVersion, Date createdBulkDate) { + this.userId = userId; + this.jobStatus = jobStatus; + this.jobId = jobId; + this.templateId = templateId; + this.pause = pause; + this.owningEntityId = owningEntityId; + this.owningEntityName = owningEntityName; + this.project = project; + this.aicZoneId = aicZoneId; + this.aicZoneName = aicZoneName; + this.tenantId = tenantId; + this.tenantName = tenantName; + this.regionId = regionId; + this.regionName = regionName; + this.serviceType = serviceType; + this.subscriberName = subscriberName; + this.serviceInstanceId = serviceInstanceId; + this.serviceInstanceName = serviceInstanceName; + this.serviceModelId = serviceModelId; + this.serviceModelName = serviceModelName; + this.serviceModelVersion = serviceModelVersion; + this.createdBulkDate = createdBulkDate; + } + + @Column(name = "JOB_ID", columnDefinition = "CHAR(36)") + @Type(type="org.hibernate.type.UUIDCharType") + public UUID getJobId() { + return jobId; + } + + @Column(name = "TEMPLATE_ID", columnDefinition = "CHAR(36)") + @Type(type="org.hibernate.type.UUIDCharType") + public UUID getTemplateId() { + return templateId; + } + + @Column(name="USER_ID") + public String getUserId() { + return userId; + } + + @Column(name="JOB_STATUS") + @Enumerated(EnumType.STRING) + public Job.JobStatus getJobStatus() { + return jobStatus; + } + + @Column(name="STATUS_MODIFIED_DATE") + public Date getStatusModifiedDate() { + return statusModifiedDate; + } + + @Column(name="IS_HIDDEN") + public boolean isHidden() { + return hidden; + } + + @Column(name="IS_PAUSE") + public boolean isPause() { + return pause; + } + + @Column(name="OWNING_ENTITY_ID") + public String getOwningEntityId() { + return owningEntityId; + } + + @Column(name="OWNING_ENTITY_NAME") + public String getOwningEntityName() { + return owningEntityName; + } + + @Column(name="PROJECT") + public String getProject() { + return project; + } + + @Column(name="AIC_ZONE_ID") + public String getAicZoneId() { + return aicZoneId; + } + + @Column(name="AIC_ZONE_NAME") + public String getAicZoneName() { + return aicZoneName; + } + + @Column(name="TENANT_ID") + public String getTenantId() { + return tenantId; + } + + @Column(name="TENANT_NAME") + public String getTenantName() { + return tenantName; + } + + @Column(name="REGION_ID") + public String getRegionId() { + return regionId; + } + + @Column(name="REGION_NAME") + public String getRegionName() { + return regionName; + } + + @Column(name="SERVICE_TYPE") + public String getServiceType() { + return serviceType; + } + + @Column(name="SUBSCRIBER_NAME") + public String getSubscriberName() { + return subscriberName; + } + + @Column(name="SERVICE_INSTANCE_ID") + public String getServiceInstanceId() { + return serviceInstanceId; + } + + @Column(name="SERVICE_INSTANCE_NAME") + public String getServiceInstanceName() { + return serviceInstanceName; + } + + @Column(name="SERVICE_MODEL_ID") + public String getServiceModelId() { + return serviceModelId; + } + + @Column(name="SERVICE_MODEL_NAME") + public String getServiceModelName() { + return serviceModelName; + } + + @Column(name="SERVICE_MODEL_VERSION") + public String getServiceModelVersion() { + return serviceModelVersion; + } + + @Column(name="CREATED_BULK_DATE") + public Date getCreatedBulkDate() { + return createdBulkDate; + } + + @Column(name="DELETED_AT") + public Date getDeletedAt() { + return deletedAt; + } + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Override + @Column(name = "ID", columnDefinition = "INT(11)") + public Long getId() { + return this.id; + } + + @Override + @Column(name = "CREATED_DATE") + public Date getCreated() { + return super.getCreated(); + } + + @Override + @Column(name = "MODIFIED_DATE") + public Date getModified() { + return super.getModified(); + } + + @Override + @Transient + public Long getCreatedId() { + return super.getCreatedId(); + } + + @Override + @Transient + public Long getModifiedId() { + return super.getModifiedId(); + } + + @Override + @Transient + public Serializable getAuditUserId() { + return super.getAuditUserId(); + } + + @Override + @Transient + public Long getRowNum() { + return super.getRowNum(); + } + + @Override + @Transient + public Set getAuditTrail() { + return super.getAuditTrail(); + } + + public void setJobId(UUID jobId) { + this.jobId = jobId; + } + + public void setTemplateId(UUID templateId) { + this.templateId = templateId; + } + + public void setJobStatus(Job.JobStatus jobStatus) { + this.jobStatus = jobStatus; + } + + public void setStatusModifiedDate(Date statusModifiedDate) { + this.statusModifiedDate = statusModifiedDate; + } + + public void setHidden(boolean isHidden) { + hidden = isHidden; + } + + public void setPause(boolean pause) { + this.pause = pause; + } + + public void setOwningEntityId(String owningEntityId) { + this.owningEntityId = owningEntityId; + } + + public void setOwningEntityName(String owningEntityName) { + this.owningEntityName = owningEntityName; + } + + public void setProject(String project) { + this.project = project; + } + + public void setAicZoneId(String aicZoneId) { + this.aicZoneId = aicZoneId; + } + + public void setAicZoneName(String aicZoneName) { + this.aicZoneName = aicZoneName; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public void setTenantName(String tenantName) { + this.tenantName = tenantName; + } + + public void setRegionId(String regionId) { + this.regionId = regionId; + } + + public void setRegionName(String regionName) { + this.regionName = regionName; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public void setSubscriberName(String subscriberName) { + this.subscriberName = subscriberName; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public void setServiceInstanceName(String serviceInstanceName) { + this.serviceInstanceName = serviceInstanceName; + } + + public void setServiceModelId(String serviceModelId) { + this.serviceModelId = serviceModelId; + } + + public void setServiceModelName(String serviceModelName) { + this.serviceModelName = serviceModelName; + } + + public void setServiceModelVersion(String serviceModelVersion) { + this.serviceModelVersion = serviceModelVersion; + } + + public void setCreatedBulkDate(Date createdBulkDate) { + this.createdBulkDate = createdBulkDate; + } + + public void setDeletedAt(Date deletedAt) { + this.deletedAt = deletedAt; + } + + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ServiceInfo)) return false; + ServiceInfo that = (ServiceInfo) o; + return isHidden() == that.isHidden() && + isPause() == that.isPause() && + Objects.equals(getDeletedAt(), that.getDeletedAt()) && + Objects.equals(getJobId(), that.getJobId()) && + Objects.equals(getTemplateId(), that.getTemplateId()) && + Objects.equals(getUserId(), that.getUserId()) && + getJobStatus() == that.getJobStatus() && + Objects.equals(getStatusModifiedDate(), that.getStatusModifiedDate()) && + Objects.equals(getOwningEntityId(), that.getOwningEntityId()) && + Objects.equals(getOwningEntityName(), that.getOwningEntityName()) && + Objects.equals(getProject(), that.getProject()) && + Objects.equals(getAicZoneId(), that.getAicZoneId()) && + Objects.equals(getAicZoneName(), that.getAicZoneName()) && + Objects.equals(getTenantId(), that.getTenantId()) && + Objects.equals(getTenantName(), that.getTenantName()) && + Objects.equals(getRegionId(), that.getRegionId()) && + Objects.equals(getRegionName(), that.getRegionName()) && + Objects.equals(getServiceType(), that.getServiceType()) && + Objects.equals(getSubscriberName(), that.getSubscriberName()) && + Objects.equals(getServiceInstanceId(), that.getServiceInstanceId()) && + Objects.equals(getServiceInstanceName(), that.getServiceInstanceName()) && + Objects.equals(getServiceModelId(), that.getServiceModelId()) && + Objects.equals(getServiceModelName(), that.getServiceModelName()) && + Objects.equals(getServiceModelVersion(), that.getServiceModelVersion()) && + Objects.equals(getCreatedBulkDate(), that.getCreatedBulkDate()); + } + + @Override + public int hashCode() { + + return Objects.hash(getJobId(), getTemplateId(), getUserId(), getJobStatus(), getStatusModifiedDate(), + isHidden(), isPause(), getDeletedAt(), getOwningEntityId(), getOwningEntityName(), getProject(), + getAicZoneId(), getAicZoneName(), getTenantId(), getTenantName(), getRegionId(), + getRegionName(), getServiceType(), getSubscriberName(), getServiceInstanceId(), + getServiceInstanceName(), getServiceModelId(), getServiceModelName(), + getServiceModelVersion(), getCreatedBulkDate()); + } + } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/ServiceModel.java b/vid-app-common/src/main/java/org/onap/vid/model/ServiceModel.java index 7a1da804..53eb18c6 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/ServiceModel.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/ServiceModel.java @@ -20,18 +20,18 @@ package org.onap.vid.model; +import org.apache.commons.collections.MapUtils; +import org.onap.vid.asdc.beans.tosca.Group; +import org.onap.vid.asdc.beans.tosca.ToscaModel; +import org.onap.vid.properties.VidProperties; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; + import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; - -import org.onap.vid.asdc.beans.tosca.Group; -import org.onap.vid.asdc.beans.tosca.NodeTemplate; -import org.onap.vid.asdc.beans.tosca.ToscaModel; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.vid.properties.VidProperties; /** * The Class ServiceModel. */ @@ -42,7 +42,7 @@ public class ServiceModel { private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(ServiceModel.class); /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); /** The service. */ private Service service; @@ -52,6 +52,9 @@ public class ServiceModel { /** The networks. */ private Map<String, Network> networks; + private Map<String, CR> collectionResource; + + /** Port Mirroring Configuration node templates */ private Map<String, PortMirroringConfig> configurations; @@ -218,6 +221,14 @@ public class ServiceModel { */ public void setPnfs(Map<String,Node> pnfs) {this.pnfs = pnfs;} + public Map<String, CR> getCollectionResource() { + return collectionResource; + } + + public void setCollectionResource(Map<String, CR> collectionResource) { + this.collectionResource = collectionResource; + } + /** * Extract service. * @@ -247,8 +258,8 @@ public class ServiceModel { // Get the groups. The groups may duplicate the groups that are in the VNF model and have // additional data like the VF module customization String> - final Map<String, VfModule> vfModules = new HashMap<String, VfModule> (); - final Map<String, VolumeGroup> volumeGroups = new HashMap<String, VolumeGroup> (); + final Map<String, VfModule> vfModules = new HashMap<> (); + final Map<String, VolumeGroup> volumeGroups = new HashMap<> (); String asdcModelNamespace = VidProperties.getAsdcModelNamespace(); String vfModuleTag = asdcModelNamespace + ModelConstants.VF_MODULE; @@ -283,41 +294,25 @@ public class ServiceModel { String vnfCustomizationName = null; String normalizedVnfCustomizationName = null; String vfModuleCustomizationName = null; - VNF tmpVnf = null; - - if ( ( getVnfs() != null ) && (!(getVnfs().isEmpty())) ) { + + if (!MapUtils.isEmpty(getVnfs())) { for (Entry<String, VNF> vnfComponent : getVnfs().entrySet()) { vnfCustomizationName = vnfComponent.getValue().getModelCustomizationName(); normalizedVnfCustomizationName = VNF.normalizeName(vnfCustomizationName); - + LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " VNF customizationName=" + vnfCustomizationName + "normalized customization name=" + normalizedVnfCustomizationName); // now check to see if there is a vf module with customization name that starts with normalizedVnfCustomizationName - - if (( getVfModules() != null ) && (!(getVfModules().isEmpty()))) { + + if (!MapUtils.isEmpty(getVolumeGroups())) { for (Entry<String, VfModule> vfModuleComponent : getVfModules().entrySet()) { vfModuleCustomizationName = vfModuleComponent.getValue().getModelCustomizationName(); LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " VF Module customizationName=" + vfModuleCustomizationName ); if ( vfModuleCustomizationName.startsWith(normalizedVnfCustomizationName + ".." )) { - - // this vf module belongs to the VNF - tmpVnf = vnfComponent.getValue(); - (tmpVnf.getVfModules()).put(vfModuleComponent.getKey(), vfModuleComponent.getValue()); - - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + - " Associated VF Module customizationName=" + vfModuleComponent.getKey() + " with VNF customization name=" + vnfCustomizationName); - - // now find if this vf module has volume groups, if so, find the volume group with the same customization name and put it under the VNF - if ( vfModuleComponent.getValue().isVolumeGroupAllowed() ) { - if (( getVolumeGroups() != null ) && (!(getVolumeGroups().isEmpty()))) { - if (getVolumeGroups().containsKey((vfModuleCustomizationName))) { - (vnfComponent.getValue().getVolumeGroups()).put(vfModuleCustomizationName, (getVolumeGroups()).get(vfModuleCustomizationName)); - } - } - } + handleCustomizationName(methodName, vnfCustomizationName, vfModuleCustomizationName, vnfComponent, vfModuleComponent); } } } @@ -327,4 +322,26 @@ public class ServiceModel { } + + private void handleCustomizationName(String methodName, String vnfCustomizationName, String vfModuleCustomizationName, Entry<String, VNF> vnfComponent, Entry<String, VfModule> vfModuleComponent) { + VNF tmpVnf;// this vf module belongs to the VNF + tmpVnf = vnfComponent.getValue(); + (tmpVnf.getVfModules()).put(vfModuleComponent.getKey(), vfModuleComponent.getValue()); + + LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + + " Associated VF Module customizationName=" + vfModuleComponent.getKey() + " with VNF customization name=" + vnfCustomizationName); + + // now find if this vf module has volume groups, if so, find the volume group with the same customization name and put it under the VNF + if ( vfModuleComponent.getValue().isVolumeGroupAllowed() ) { + if (isVolumeGroupsContainsVfModuleCustomName(vfModuleCustomizationName)) { + (vnfComponent.getValue().getVolumeGroups()).put(vfModuleCustomizationName, (getVolumeGroups()).get(vfModuleCustomizationName)); + } + } + } + + private boolean isVolumeGroupsContainsVfModuleCustomName(String vfModuleCustomizationName) { + return (!MapUtils.isEmpty(getVolumeGroups())) && (getVolumeGroups().containsKey((vfModuleCustomizationName))); + } + + } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/SubscriberList.java b/vid-app-common/src/main/java/org/onap/vid/model/SubscriberList.java index 6e3d3e79..a08b585b 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/SubscriberList.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/SubscriberList.java @@ -8,6 +8,11 @@ import java.util.List; * Created by Oren on 7/4/17. */ public class SubscriberList { + public SubscriberList(List<Subscriber> customer) { + this.customer = customer; + } + + public SubscriberList(){} public List<Subscriber> customer; diff --git a/vid-app-common/src/main/java/org/onap/vid/model/VNF.java b/vid-app-common/src/main/java/org/onap/vid/model/VNF.java index 54e54947..9da88870 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/VNF.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/VNF.java @@ -56,7 +56,10 @@ public class VNF extends Node { /** The volume groups. */ private Map<String, VolumeGroup> volumeGroups = new HashMap<String, VolumeGroup>(); - + + private Map<String, VfcInstanceGroup> vfcInstanceGroups = new HashMap<>(); + + /** * Instantiates a new vnf. */ @@ -109,6 +112,15 @@ public class VNF extends Node { this.volumeGroups = volumeGroups; } + + public Map<String, VfcInstanceGroup> getVfcInstanceGroups() { + return vfcInstanceGroups; + } + + public void setVfcInstanceGroups(Map<String, VfcInstanceGroup> vfcInstanceGroups) { + this.vfcInstanceGroups = vfcInstanceGroups; + } + /** * Extract vnf. * diff --git a/vid-app-common/src/main/java/org/onap/vid/model/VfModule.java b/vid-app-common/src/main/java/org/onap/vid/model/VfModule.java index f7b4d88f..ea30571a 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/VfModule.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/VfModule.java @@ -20,130 +20,27 @@ package org.onap.vid.model; +import org.onap.vid.asdc.beans.tosca.Group; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; + import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import org.onap.vid.asdc.beans.tosca.Group; - -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.sdc.toscaparser.api.Property; /** * The Class VfModule. */ -public class VfModule { +public class VfModule extends org.onap.vid.model.Group { /** The Constant LOG. */ private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VfModule.class); /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - /** The uuid. */ - private String uuid; - - /** The invariant uuid. */ - private String invariantUuid; - - /** The customization uuid. */ - private String customizationUuid; - - /** The description. */ - private String description; - - /** The name. */ - private String name; - - /** The version. */ - private String version; - + static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + public static final String VOLUME_GROUP = "volume_group"; + /** The volume group allowed. */ private boolean volumeGroupAllowed; - - /** The get_input or other constructs for VF Module. */ - private Map<String, CommandProperty> commands; - - /** The model customization name. */ - private String modelCustomizationName; - - /** The model properties. */ - private Map<String, Property> properties; - - /** - * Instantiates a new vf module. - */ - public VfModule() { - commands = new HashMap<String, CommandProperty>(); - } - /** - * Gets the model customization name. - * - * @return the model customization name - */ - public String getModelCustomizationName() { - return modelCustomizationName; - } - /** - * Gets the uuid. - * - * @return the uuid - */ - public String getUuid() { - return uuid; - } - - /** - * Gets the invariant uuid. - * - * @return the invariant uuid - */ - public String getInvariantUuid() { - return invariantUuid; - } - /** - * Gets the customization uuid. - * - * @return the invariant uuid - */ - public String getCustomizationUuid() { - return customizationUuid; - } - /** - * Gets the description. - * - * @return the description - */ - public String getDescription() { - return description; - } - /** - * Gets the commands. - * - * @return the commands - */ - public Map<String, CommandProperty> getCommands() { - return commands; - } - /** - * Gets the name. - * - * @return the name - */ - public String getName() { - return name; - } - - /** - * Gets the version. - * - * @return the version - */ - public String getVersion() { - return version; - } /** * Checks if is volume group allowed. @@ -153,58 +50,7 @@ public class VfModule { public boolean isVolumeGroupAllowed() { return volumeGroupAllowed; } - - /** - * Sets the uuid. - * - * @param uuid the new uuid - */ - public void setUuid(String uuid) { - this.uuid = uuid; - } - - /** - * Sets the invariant uuid. - * - * @param invariantUuid the new invariant uuid - */ - public void setInvariantUuid(String invariantUuid) { - this.invariantUuid = invariantUuid; - } - /** - * Sets the customization uuid. - * - * @param customizationUuid the new customization uuid - */ - public void setCustomizationUuid(String customizationUuid) { - this.customizationUuid = customizationUuid; - } - /** - * Sets the description. - * - * @param description the new description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Sets the name. - * - * @param name the new name - */ - public void setName(String name) { - this.name = name; - } - /** - * Sets the version. - * - * @param version the new version - */ - public void setVersion(String version) { - this.version = version; - } /** * Sets the volume group allowed. @@ -214,22 +60,8 @@ public class VfModule { public void setVolumeGroupAllowed(boolean volumeGroupAllowed) { this.volumeGroupAllowed = volumeGroupAllowed; } - /** - * Sets the commands. - * - * @param m the commands - */ - public void setCommands( Map<String, CommandProperty>m ) { - commands = m; - } - /** - * Sets the model customization name. - * - * @param modelCustomizationName the new model customization name - */ - public void setModelCustomizationName(String modelCustomizationName) { - this.modelCustomizationName = modelCustomizationName; - } + + /** * Extract vf module. * @@ -250,17 +82,17 @@ public class VfModule { vfModule.setVersion(group.getMetadata().getVfModuleModelVersion()); vfModule.setCustomizationUuid(group.getMetadata().getVfModuleModelCustomizationUUID()); vfModule.setModelCustomizationName (modelCustomizationName); - //?vfModule.setProperties(group.getProperties()); - - if (group.getProperties().containsKey("volume_group")) { - if (group.getProperties().get("volume_group") != null) { + vfModule.setProperties(VfModule.extractPropertiesForGroup(group)); + + if (group.getProperties().containsKey(VOLUME_GROUP)) { + if (group.getProperties().get(VOLUME_GROUP) != null) { - Class<?> c = group.getProperties().get("volume_group").getClass(); - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " class name=" + + Class<?> c = group.getProperties().get(VOLUME_GROUP).getClass(); + LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " class name=" + c.getName()); if ( c.getName().equalsIgnoreCase(Boolean.class.getName()) ) { - Boolean b = (Boolean)group.getProperties().get("volume_group"); + Boolean b = (Boolean)group.getProperties().get(VOLUME_GROUP); vfModule.setVolumeGroupAllowed( b.booleanValue() ); } } @@ -272,48 +104,8 @@ public class VfModule { LOG.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + methodName + " Unable to parse VF Module from group: e=" + e.toString()); } - /* Not extracting other types of properties for 1702 - try { - - for (Entry<String, Object> e : group.getProperties().entrySet()) { - - String k = e.getKey(); - if ( e.getValue() != null ) { - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " property: " + - k + "=" + e.getValue()); - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " V class name: " + - e.getValue().getClass().getName()); - Class<?>[] interfaces = e.getValue().getClass().getInterfaces(); - - for(Class<?> ifc: interfaces ){ - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " ifc name: " + - ifc.getName()); - } - - // only extract get_input for now - for (Entry<String, String> entry : v.entrySet()) { - // only include get_input for now - if ( ModelConstants.GET_INPUT_TAG.equalsIgnoreCase ( entry.getKey() ) ) { - CommandProperty cp = new CommandProperty(); - cp.setDisplayName(entry.getValue()); - cp.setCommand(entry.getKey()); - cp.setInputName(k); - (vfModule.getCommands()).put(k,cp); - } - } - } - } - } - catch ( Exception e ) { - LOG.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + methodName + " Unable to parse VF Module properties: e=" + - e.toString()); - }*/ - return vfModule; + return vfModule; } - public Map<String, Property> getProperties() { - return properties; - } - public void setProperties(Map<String, Property> properties) { - this.properties = properties; - } + + } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/VfcInstanceGroup.java b/vid-app-common/src/main/java/org/onap/vid/model/VfcInstanceGroup.java new file mode 100644 index 00000000..1a7ca431 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/VfcInstanceGroup.java @@ -0,0 +1,55 @@ +package org.onap.vid.model; + +public class VfcInstanceGroup { + + private String uuid; + private String invariantUuid; + private String name; + private String version; + private VfcInstanceGroupProperties vfcInstanceGroupProperties; + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getInvariantUuid() { + return invariantUuid; + } + + public void setInvariantUuid(String invariantUuid) { + this.invariantUuid = invariantUuid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public VfcInstanceGroupProperties getVfcInstanceGroupProperties() { + return vfcInstanceGroupProperties; + } + + public void setVfcInstanceGroupProperties(VfcInstanceGroupProperties vfcInstanceGroupProperties) { + this.vfcInstanceGroupProperties = vfcInstanceGroupProperties; + } + + + + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/VfcInstanceGroupProperties.java b/vid-app-common/src/main/java/org/onap/vid/model/VfcInstanceGroupProperties.java new file mode 100644 index 00000000..d6c04618 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/VfcInstanceGroupProperties.java @@ -0,0 +1,44 @@ +package org.onap.vid.model; + +public class VfcInstanceGroupProperties { + + private String vfcParentPortRole; + private String networkCollectionFunction; + private String vfcInstanceGroupFunction; + private String subinterfaceRole; + + public String getVfcParentPortRole() { + return vfcParentPortRole; + } + + public void setVfcParentPortRole(String vfcParentPortRole) { + this.vfcParentPortRole = vfcParentPortRole; + } + + public String getNetworkCollectionFunction() { + return networkCollectionFunction; + } + + public void setNetworkCollectionFunction(String networkCollectionFunction) { + this.networkCollectionFunction = networkCollectionFunction; + } + + public String getVfcInstanceGroupFunction() { + return vfcInstanceGroupFunction; + } + + public void setVfcInstanceGroupFunction(String vfcInstanceGroupFunction) { + this.vfcInstanceGroupFunction = vfcInstanceGroupFunction; + } + + public String getSubinterfaceRole() { + return subinterfaceRole; + } + + public void setSubinterfaceRole(String subinterfaceRole) { + this.subinterfaceRole = subinterfaceRole; + } + + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/VidBaseEntity.java b/vid-app-common/src/main/java/org/onap/vid/model/VidBaseEntity.java new file mode 100644 index 00000000..28c80b68 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/VidBaseEntity.java @@ -0,0 +1,64 @@ +package org.onap.vid.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.onap.portalsdk.core.domain.support.DomainVo; + +import javax.persistence.Column; +import javax.persistence.MappedSuperclass; +import javax.persistence.Transient; +import java.io.Serializable; +import java.util.Date; +import java.util.Set; + +@MappedSuperclass +public class VidBaseEntity extends DomainVo { + + @Override + @Column(name = "CREATED_DATE") + @JsonIgnore + public Date getCreated() { + return super.getCreated(); + } + + @Override + @Column(name = "MODIFIED_DATE") + @JsonIgnore + public Date getModified() { + return super.getModified(); + } + + @Override + @Transient + @JsonIgnore + public Long getCreatedId() { + return super.getCreatedId(); + } + + @Override + @Transient + @JsonIgnore + public Long getModifiedId() { + return super.getModifiedId(); + } + + @Override + @Transient + @JsonIgnore + public Serializable getAuditUserId() { + return super.getAuditUserId(); + } + + @Override + @Transient + @JsonIgnore + public Long getRowNum() { + return super.getRowNum(); + } + + @Override + @Transient + @JsonIgnore + public Set getAuditTrail() { + return super.getAuditTrail(); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/VidWorkflow.java b/vid-app-common/src/main/java/org/onap/vid/model/VidWorkflow.java index 5b9eeeba..9054898e 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/VidWorkflow.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/VidWorkflow.java @@ -2,16 +2,12 @@ package org.onap.vid.model; import com.fasterxml.jackson.annotation.JsonIgnore; -import org.onap.portalsdk.core.domain.support.DomainVo; import javax.persistence.*; -import java.io.Serializable; -import java.util.Date; -import java.util.Set; @Entity @Table(name = "vid_workflow") -public class VidWorkflow extends DomainVo { +public class VidWorkflow extends VidBaseEntity { private String wokflowName; @@ -23,55 +19,6 @@ public class VidWorkflow extends DomainVo { return id; } - @Override - @Column(name = "CREATED_DATE") - @JsonIgnore - public Date getCreated() { - return super.getCreated(); - } - - @Override - @Column(name = "MODIFIED_DATE") - @JsonIgnore - public Date getModified() { - return super.getModified(); - } - - @Override - @Transient - @JsonIgnore - public Long getCreatedId() { - return super.getCreatedId(); - } - - @Override - @Transient - @JsonIgnore - public Long getModifiedId() { - return super.getModifiedId(); - } - - @Override - @Transient - @JsonIgnore - public Serializable getAuditUserId() { - return super.getAuditUserId(); - } - - @Override - @Transient - @JsonIgnore - public Long getRowNum() { - return super.getRowNum(); - } - - @Override - @Transient - @JsonIgnore - public Set getAuditTrail() { - return super.getAuditTrail(); - } - @Column(name = "WORKFLOW_APP_NAME") public String getWokflowName() { return wokflowName; diff --git a/vid-app-common/src/main/java/org/onap/vid/model/VolumeGroup.java b/vid-app-common/src/main/java/org/onap/vid/model/VolumeGroup.java index 969c287c..888c5f5c 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/VolumeGroup.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/VolumeGroup.java @@ -25,28 +25,10 @@ import org.onap.vid.asdc.beans.tosca.Group; /** * The Class VolumeGroup. */ -public class VolumeGroup { +public class VolumeGroup extends org.onap.vid.model.Group { + + - /** The uuid. */ - private String uuid; - - /** The invariant uuid. */ - private String invariantUuid; - - /** The description. */ - private String description; - - /** The name. */ - private String name; - - /** The version. */ - private String version; - - /** The customization uuid. */ - private String customizationUuid; - - /** The customization uuid. */ - private String modelCustomizationName; /** * Instantiates a new volume group. */ @@ -57,124 +39,8 @@ public class VolumeGroup { * * @return the uuid */ - public String getUuid() { - return uuid; - } - /** - * Gets the customization uuid. - * - * @return the customization uuid - */ - public String getCustomizationUuid() { - return customizationUuid; - } - /** - * Gets the customization name. - * - * @return the customization name - */ - public String getModelCustomizationName() { - return modelCustomizationName; - } - /** - * Gets the invariant uuid. - * - * @return the invariant uuid - */ - public String getInvariantUuid() { - return invariantUuid; - } - - /** - * Gets the description. - * - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * Gets the name. - * - * @return the name - */ - public String getName() { - return name; - } - - /** - * Gets the version. - * - * @return the version - */ - public String getVersion() { - return version; - } - - /** - * Sets the uuid. - * - * @param uuid the new uuid - */ - public void setUuid(String uuid) { - this.uuid = uuid; - } - - /** - * Sets the invariant uuid. - * - * @param invariantUuid the new invariant uuid - */ - public void setInvariantUuid(String invariantUuid) { - this.invariantUuid = invariantUuid; - } - - /** - * Sets the description. - * - * @param description the new description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Sets the name. - * - * @param name the new name - */ - public void setName(String name) { - this.name = name; - } /** - * Sets the version. - * - * @param version the new version - */ - public void setVersion(String version) { - this.version = version; - } - /** - * Sets the customization uuid. - * - * @param u the new customization uuid - */ - public void setCustomizationUuid(String u) { - this.customizationUuid = u; - - } - /** - * Sets the customization name. - * - * @param u the new customization name - */ - public void setModelCustomizationName(String u) { - this.modelCustomizationName = u; - - } - /** * Extract volume group. * * @param group the group @@ -190,6 +56,7 @@ public class VolumeGroup { volumeGroup.setVersion(group.getMetadata().getVfModuleModelVersion()); volumeGroup.setCustomizationUuid(group.getMetadata().getVfModuleModelCustomizationUUID()); volumeGroup.setModelCustomizationName(modelCustomizationName); + volumeGroup.setProperties(VolumeGroup.extractPropertiesForGroup(group)); return volumeGroup; } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/probes/ErrorMetadata.java b/vid-app-common/src/main/java/org/onap/vid/model/probes/ErrorMetadata.java new file mode 100644 index 00000000..1f3fdfd7 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/probes/ErrorMetadata.java @@ -0,0 +1,7 @@ +package org.onap.vid.model.probes; + +public class ErrorMetadata extends StatusMetadata { + public ErrorMetadata(String description, long duration) { + super(description, duration); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/probes/ExternalComponentStatus.java b/vid-app-common/src/main/java/org/onap/vid/model/probes/ExternalComponentStatus.java new file mode 100644 index 00000000..da8c912e --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/probes/ExternalComponentStatus.java @@ -0,0 +1,26 @@ +package org.onap.vid.model.probes; + +public class ExternalComponentStatus { + public enum Component {AAI, MSO} + private final Component component; + private final boolean available; + private final StatusMetadata metadata; + + public ExternalComponentStatus(Component component, boolean isAvailable, StatusMetadata metadata) { + this.component = component; + this.available = isAvailable; + this.metadata = metadata; + } + + public Component getComponent() { + return component; + } + + public boolean isAvailable() { + return available; + } + + public StatusMetadata getMetadata() { + return metadata; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/probes/HttpRequestMetadata.java b/vid-app-common/src/main/java/org/onap/vid/model/probes/HttpRequestMetadata.java new file mode 100644 index 00000000..e80d563b --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/probes/HttpRequestMetadata.java @@ -0,0 +1,34 @@ +package org.onap.vid.model.probes; + +import org.springframework.http.HttpMethod; + +public class HttpRequestMetadata extends StatusMetadata { + private final HttpMethod httpMethod; + private final int httpCode; + private final String url; + private final String rawData; + + public HttpRequestMetadata(HttpMethod httpMethod, int httpCode, String url, String rawData, String description, long duration) { + super(description, duration); + this.httpMethod = httpMethod; + this.url = url; + this.httpCode = httpCode; + this.rawData = rawData; + } + + public HttpMethod getHttpMethod() { + return httpMethod; + } + + public int getHttpCode() { + return httpCode; + } + + public String getUrl() { + return url; + } + + public String getRawData() { + return rawData; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/probes/StatusMetadata.java b/vid-app-common/src/main/java/org/onap/vid/model/probes/StatusMetadata.java new file mode 100644 index 00000000..c1e7202c --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/probes/StatusMetadata.java @@ -0,0 +1,19 @@ +package org.onap.vid.model.probes; + +public abstract class StatusMetadata { + protected final long duration; + protected final String description; + + public StatusMetadata(String description, long duration) { + this.description = description; + this.duration = duration; + } + + public long getDuration() { + return duration; + } + + public String getDescription() { + return description; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiation.java b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiation.java new file mode 100644 index 00000000..1d2e69d5 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiation.java @@ -0,0 +1,174 @@ +package org.onap.vid.model.serviceInstantiation; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.onap.vid.domain.mso.ModelInfo; +import org.onap.vid.job.JobAdapter; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class ServiceInstantiation implements JobAdapter.AsyncJobRequest { + + private final ModelInfo modelInfo; + + private final String owningEntityId; + + private final String owningEntityName; + + private final String projectName; + + private final String subscriberName; + + private final String globalSubscriberId; + + private final String productFamilyId; + + private final String instanceName; + + private final Boolean isUserProvidedNaming; + + private final String subscriptionServiceType; + + private final String lcpCloudRegionId; + + private final String tenantId; + + private final String tenantName; + + private final String aicZoneId; + + private final String aicZoneName; + + private final Map<String, Vnf> vnfs; + + private final List<Map<String,String>> instanceParams; + + private final boolean isPause; + + private final int bulkSize; + + private final boolean rollbackOnFailure; + + public ServiceInstantiation(@JsonProperty("modelInfo") ModelInfo modelInfo, + @JsonProperty("owningEntityId") String owningEntityId, + @JsonProperty("owningEntityName") String owningEntityName, + @JsonProperty("projectName") String projectName, + @JsonProperty("globalSubscriberId") String globalSubscriberId, + @JsonProperty("subscriberName") String subscriberName, + @JsonProperty("productFamilyId") String productFamilyId, + @JsonProperty("instanceName") String instanceName, + @JsonProperty("isUserProvidedNaming") Boolean isUserProvidedNaming, + @JsonProperty("subscriptionServiceType") String subscriptionServiceType, + @JsonProperty("lcpCloudRegionId") String lcpCloudRegionId, + @JsonProperty("tenantId") String tenantId, + @JsonProperty("tenantName") String tenantName, + @JsonProperty("aicZoneId") String aicZoneId, + @JsonProperty("aicZoneName") String aicZoneName, + @JsonProperty("vnfs") Map<String, Vnf> vnfs, + @JsonProperty("instanceParams") List<Map<String, String>> instanceParams, + @JsonProperty("pause") boolean isPause, + @JsonProperty("bulkSize") int bulkSize, + @JsonProperty("rollbackOnFailure") boolean rollbackOnFailure + ) { + + this.modelInfo = modelInfo; + this.modelInfo.setModelType("service"); + this.owningEntityId = owningEntityId; + this.owningEntityName = owningEntityName; + this.projectName = projectName; + this.globalSubscriberId = globalSubscriberId; + this.subscriberName = subscriberName; + this.productFamilyId = productFamilyId; + this.instanceName = instanceName; + this.isUserProvidedNaming = isUserProvidedNaming; + this.subscriptionServiceType = subscriptionServiceType; + this.lcpCloudRegionId = lcpCloudRegionId; + this.tenantId = tenantId; + this.tenantName = tenantName; + this.aicZoneId = aicZoneId; + this.aicZoneName = aicZoneName; + this.vnfs = vnfs; + this.instanceParams = instanceParams; + this.isPause = isPause; + this.bulkSize = bulkSize; + this.rollbackOnFailure = rollbackOnFailure; + } + + public ModelInfo getModelInfo() { + return modelInfo; + } + + public String getOwningEntityId() { + return owningEntityId; + } + + public String getOwningEntityName() { + return owningEntityName; + } + + public String getProjectName() { + return projectName; + } + + public String getGlobalSubscriberId() { + return globalSubscriberId; + } + + public String getSubscriberName() { + return subscriberName; + } + + public String getProductFamilyId() { + return productFamilyId; + } + + public String getInstanceName() { + return instanceName; + } + + @JsonProperty("isUserProvidedNaming") + public Boolean isUserProvidedNaming() { return isUserProvidedNaming; } + + public String getSubscriptionServiceType() { + return subscriptionServiceType; + } + + public String getLcpCloudRegionId() { + return lcpCloudRegionId; + } + + public String getTenantId() { + return tenantId; + } + + public String getTenantName() { + return tenantName; + } + + public String getAicZoneId() { + return aicZoneId; + } + + public String getAicZoneName() { + return aicZoneName; + } + + public Map<String, Vnf> getVnfs() { + return vnfs; + } + + public List<Map<String, String>> getInstanceParams() { + return instanceParams == null ? Collections.emptyList() : instanceParams; + } + + public boolean isPause() { + return isPause; + } + + public int getBulkSize() { return bulkSize; } + + public boolean isRollbackOnFailure() { + return rollbackOnFailure; + } +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/VfModule.java b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/VfModule.java new file mode 100644 index 00000000..f63fb336 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/VfModule.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * 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.vid.model.serviceInstantiation; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.StringUtils; +import org.onap.vid.domain.mso.ModelInfo; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; + +/** + * The Class VfModule. + */ +public class VfModule { + + + + private final ModelInfo modelInfo; + + @JsonInclude(NON_NULL) private final String instanceName; + + private final List<Map<String, String>> instanceParams; + @JsonInclude(NON_NULL) private final String volumeGroupInstanceName; + + public VfModule(@JsonProperty("modelInfo") ModelInfo modelInfo, + @JsonProperty("instanceName") String instanceName, + @JsonProperty(value = "volumeGroupName") String volumeGroupInstanceName, + @JsonProperty("instanceParams") List<Map<String, String>> instanceParams) { + this.modelInfo = modelInfo; + this.modelInfo.setModelType("vfModule"); + this.instanceName = instanceName; + this.instanceParams = instanceParams; + this.volumeGroupInstanceName = volumeGroupInstanceName; + } + + public ModelInfo getModelInfo() { + return modelInfo; + } + + public String getInstanceName() { + return instanceName; + } + + public String getVolumeGroupInstanceName() { + return volumeGroupInstanceName; + } + + public List<Map<String, String>> getInstanceParams() { + return instanceParams == null ? Collections.emptyList() : instanceParams; + } + +}
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/Vnf.java b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/Vnf.java new file mode 100644 index 00000000..621754d1 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/Vnf.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * 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.vid.model.serviceInstantiation; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.StringUtils; +import org.onap.vid.domain.mso.ModelInfo; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * The Class VNF. + */ +public class Vnf { + private final ModelInfo modelInfo; + + private final String productFamilyId; + + private final String instanceName; + + private final String platformName; + + private final String lcpCloudRegionId; + + private final String tenantId; + + private final Boolean isUserProvidedNaming; + + private final List<Map<String, String>> instanceParams; + + private final String lineOfBusiness; + + + private final Map<String, Map<String, VfModule>> vfModules; + + public Vnf(@JsonProperty("modelInfo") ModelInfo modelInfo, + @JsonProperty("productFamilyId") String productFamilyId, + @JsonProperty("instanceName") String instanceName, + @JsonProperty("isUserProvidedNaming") Boolean isUserProvidedNaming, + @JsonProperty("platformName") String platformName, + @JsonProperty("lcpCloudRegionId") String lcpCloudRegionId, + @JsonProperty("tenantId") String tenantId, + @JsonProperty("instanceParams") List<Map<String, String>> instanceParams, + @JsonProperty("lineOfBusinessName") String lineOfBusiness, + @JsonProperty("vfModules") Map<String, Map<String, VfModule>> vfModules) { + this.modelInfo = modelInfo; + this.modelInfo.setModelType("vnf"); + this.productFamilyId = productFamilyId; + this.instanceName = instanceName; + this.isUserProvidedNaming = isUserProvidedNaming; + this.platformName = platformName; + this.lcpCloudRegionId = lcpCloudRegionId; + this.tenantId = tenantId; + this.instanceParams = instanceParams; + this.vfModules = vfModules; + this.lineOfBusiness = lineOfBusiness; + } + + public ModelInfo getModelInfo() { + return modelInfo; + } + + public String getProductFamilyId() { + return productFamilyId; + } + + public String getInstanceName() { + return instanceName; + } + + @JsonProperty("isUserProvidedNaming") + public Boolean isUserProvidedNaming() { + return isUserProvidedNaming; + } + + public String getPlatformName() { + return platformName; + } + + public String getLcpCloudRegionId() { + return lcpCloudRegionId; + } + + public String getTenantId() { + return tenantId; + } + + public List<Map<String, String>> getInstanceParams() { + return instanceParams == null ? Collections.emptyList() : instanceParams; + } + + public Map<String, Map<String, VfModule>> getVfModules() { + return vfModules; + } + + public String getLineOfBusiness() { + return lineOfBusiness; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogic.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogic.java index 80d60d9c..79befe17 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogic.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogic.java @@ -14,68 +14,68 @@ import java.util.List; public interface MsoBusinessLogic { // this function should get params from tosca and send them to instance at mso, then return success response. - MsoResponseWrapper createSvcInstance(RequestDetails msoRequest) throws Exception; + MsoResponseWrapper createSvcInstance(RequestDetails msoRequest); - MsoResponseWrapper createE2eSvcInstance(Object msoRequest) throws Exception; + MsoResponseWrapper createE2eSvcInstance(Object msoRequest); - MsoResponseWrapper deleteE2eSvcInstance(Object requestDetails, String serviceInstanceId) throws Exception; + MsoResponseWrapper deleteE2eSvcInstance(Object requestDetails, String serviceInstanceId); - MsoResponseWrapper createVnf(RequestDetails requestDetails, String serviceInstanceId) throws Exception; + MsoResponseWrapper createVnf(RequestDetails requestDetails, String serviceInstanceId); - MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String serviceInstanceId) throws Exception; + MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String serviceInstanceId); - MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception; + MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId); - MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception; + MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId); - MsoResponseWrapper createConfigurationInstance(RequestDetails requestDetails, String serviceInstanceId) throws Exception; + MsoResponseWrapper createConfigurationInstance(org.onap.vid.mso.rest.RequestDetailsWrapper requestDetailsWrapper, String serviceInstanceId); - MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String serviceInstanceId) throws Exception; + MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String serviceInstanceId, String serviceStatus); - MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception; + MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId); - MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId, String vfModuleId) throws Exception; + MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId, String vfModuleId); - MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId, String volumeGroupId)throws Exception; + MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId, String volumeGroupId); - MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String serviceInstanceId, String networkInstanceId) throws Exception; + MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String serviceInstanceId, String networkInstanceId); - MsoResponseWrapper getOrchestrationRequest(String requestId)throws Exception; + MsoResponseWrapper getOrchestrationRequest(String requestId); - MsoResponseWrapper getOrchestrationRequests(String filterString)throws Exception; + MsoResponseWrapper getOrchestrationRequests(String filterString); - List<Request> getOrchestrationRequestsForDashboard()throws Exception; + List<Request> getOrchestrationRequestsForDashboard(); - List<Task> getManualTasksByRequestId(String originalRequestId)throws Exception; + List<Task> getManualTasksByRequestId(String originalRequestId); - MsoResponseWrapper completeManualTask(RequestDetails requestDetails, String taskId)throws Exception; + MsoResponseWrapper completeManualTask(RequestDetails requestDetails, String taskId); - MsoResponseWrapper activateServiceInstance(RequestDetails requestDetails, String serviceInstanceId)throws Exception; + MsoResponseWrapper activateServiceInstance(RequestDetails requestDetails, String serviceInstanceId); - MsoResponseWrapperInterface updateVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception; + MsoResponseWrapperInterface updateVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId); - MsoResponseWrapperInterface replaceVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception; + MsoResponseWrapperInterface replaceVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId); - MsoResponseWrapperInterface updateVnfSoftware(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception; + MsoResponseWrapperInterface updateVnfSoftware(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId); - MsoResponseWrapperInterface updateVnfConfig(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception; + MsoResponseWrapperInterface updateVnfConfig(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId); MsoResponseWrapper deleteConfiguration( - RequestDetails requestDetails, + org.onap.vid.mso.rest.RequestDetailsWrapper requestDetailsWrapper, String serviceInstanceId, - String configurationId) throws Exception; + String configurationId); MsoResponseWrapper setConfigurationActiveStatus( RequestDetails requestDetails, String serviceInstanceId, String configurationId, - boolean isActivate) throws Exception; + boolean isActivate); MsoResponseWrapper setPortOnConfigurationStatus( RequestDetails requestDetails, String serviceInstanceId, String configurationId, - boolean isEnable) throws Exception; + boolean isEnable); RequestDetailsWrapper<RequestDetails> createOperationalEnvironmentActivationRequestDetails(OperationalEnvironmentActivateInfo details); @@ -91,13 +91,13 @@ public interface MsoBusinessLogic { RequestDetailsWrapper<OperationEnvironmentRequestDetails> convertParametersToRequestDetails(OperationalEnvironmentController.OperationalEnvironmentCreateBody input, String userId); - MsoResponseWrapper removeRelationshipFromServiceInstance(RequestDetails requestDetails, String serviceInstanceId) throws Exception; + MsoResponseWrapper removeRelationshipFromServiceInstance(RequestDetails requestDetails, String serviceInstanceId); - MsoResponseWrapper addRelationshipToServiceInstance(RequestDetails requestDetails, String serviceInstanceId) throws Exception; + MsoResponseWrapper addRelationshipToServiceInstance(RequestDetails requestDetails, String serviceInstanceId); - MsoResponseWrapper setServiceInstanceStatus(RequestDetails requestDetails , String serviceInstanceId, boolean isActivate)throws Exception; + MsoResponseWrapper setServiceInstanceStatus(RequestDetails requestDetails , String serviceInstanceId, boolean isActivate); - RequestDetailsWrapper generateInPlaceMsoRequest(org.onap.vid.changeManagement.RequestDetails requestDetails) throws Exception; + RequestDetailsWrapper generateInPlaceMsoRequest(org.onap.vid.changeManagement.RequestDetails requestDetails); - RequestDetailsWrapper generateConfigMsoRequest(org.onap.vid.changeManagement.RequestDetails requestDetails) throws Exception; + RequestDetailsWrapper generateConfigMsoRequest(org.onap.vid.changeManagement.RequestDetails requestDetails); } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java index 7cea0301..a2e32bab 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java @@ -1,165 +1,138 @@ package org.onap.vid.mso; -import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.changeManagement.ChangeManagementRequest; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.controllers.OperationalEnvironmentController; import org.onap.vid.domain.mso.RequestInfo; +import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo; import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo; import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails; import org.onap.vid.mso.rest.*; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; +import org.togglz.core.manager.FeatureManager; import javax.ws.rs.BadRequestException; +import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Pattern; +import static org.apache.commons.lang.StringUtils.upperCase; import static org.onap.vid.changeManagement.ChangeManagementRequest.MsoChangeManagementRequest; import static org.onap.vid.controllers.MsoController.*; import static org.onap.vid.mso.MsoProperties.*; +import static org.onap.vid.properties.Features.FLAG_UNASSIGN_SERVICE; +import static org.onap.vid.utils.Logging.debugRequestDetails; public class MsoBusinessLogicImpl implements MsoBusinessLogic { + public static final String START = " start"; + public static final String RESOURCE_TYPE = "resourceType"; + FeatureManager featureManager; + /** * The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - final static Pattern SOFTWARE_VERSION_PATTERN = Pattern.compile("^[A-Za-z0-9.\\-]+$"); - final static Pattern NUMBER_PATTERN = Pattern.compile("^[0-9]+$"); + private static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + private static final Pattern SOFTWARE_VERSION_PATTERN = Pattern.compile("^[A-Za-z0-9.\\-]+$"); + private static final Pattern NUMBER_PATTERN = Pattern.compile("^[0-9]+$"); private static final String ACTIVATE = "/activate"; private static final String DEACTIVATE = "/deactivate"; private static final String ENABLE_PORT = "/enablePort"; private static final String DISABLE_PORT = "/disablePort"; - private final static String RESOURCE_TYPE_OPERATIONAL_ENVIRONMENT = "operationalEnvironment"; - private final static String SOURCE_OPERATIONAL_ENVIRONMENT = "VID"; - final static private ObjectMapper objectMapper = new ObjectMapper(); + private static final String RESOURCE_TYPE_OPERATIONAL_ENVIRONMENT = "operationalEnvironment"; + private static final String SOURCE_OPERATIONAL_ENVIRONMENT = "VID"; + private static final ObjectMapper objectMapper = new ObjectMapper(); /** * The Mso REST client * This should be replaced with mso client factory. */ private final MsoInterface msoClientInterface; + /** * The logger. */ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoBusinessLogicImpl.class); - + @Autowired - public MsoBusinessLogicImpl(MsoInterface msoClientInterface) { + public MsoBusinessLogicImpl(MsoInterface msoClientInterface, FeatureManager featureManager) { this.msoClientInterface = msoClientInterface; + this.featureManager = featureManager; } - static String validateEndpointPath(String endpointEnvVariable) { + public static String validateEndpointPath(String endpointEnvVariable) { String endpoint = SystemProperties.getProperty(endpointEnvVariable); if (endpoint == null || endpoint.isEmpty()) { - throw new RuntimeException(endpointEnvVariable + " env variable is not defined"); + throw new GenericUncheckedException(endpointEnvVariable + " env variable is not defined"); } return endpoint; } // this function should get params from tosca and send them to instance at mso, then return success response. @Override - public MsoResponseWrapper createSvcInstance(RequestDetails msoRequest) throws Exception { + public MsoResponseWrapper createSvcInstance(RequestDetails msoRequest) { String methodName = "createSvcInstance "; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { - endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_SVC_INSTANCE); - } catch (Exception exception) { - throw exception; - } + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_SVC_INSTANCE); return msoClientInterface.createSvcInstance(msoRequest, endpoint); } @Override - public MsoResponseWrapper createE2eSvcInstance(Object msoRequest) throws Exception { + public MsoResponseWrapper createE2eSvcInstance(Object msoRequest){ String methodName = "createE2eSvcInstance "; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { - endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_E2E_SVC_INSTANCE); - } catch (Exception exception) { - throw exception; - } - - return msoClientInterface.createE2eSvcInstance(msoRequest, endpoint); - } - - void validateLineOfBusiness(RequestDetails requestDetails) { - - Object value = requestDetails.getAdditionalProperties(); + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_E2E_SVC_INSTANCE); - for(String prop: ImmutableList.of("requestDetails", "lineOfBusiness", "lineOfBusinessName")) { - if(value==null ||!(value instanceof Map)) { - value = null; - break; - } - else { - value = ((Map)value).get(prop); - } - } - if(value == null || value.toString().isEmpty()) { - throw new BadRequestException("lineOfBusiness is required"); - } - - } + return msoClientInterface.createE2eSvcInstance(msoRequest, endpoint); + } @Override - public MsoResponseWrapper createVnf(RequestDetails requestDetails, String serviceInstanceId) throws Exception { + public MsoResponseWrapper createVnf(RequestDetails requestDetails, String serviceInstanceId) { String methodName = "createVnf"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { - endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); - } catch (Exception exception) { - throw exception; - } + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); return msoClientInterface.createVnf(requestDetails, vnf_endpoint); } @Override - public MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String serviceInstanceId) throws Exception { + public MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String serviceInstanceId) { String methodName = "createNwInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { - endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); - } catch (Exception exception) { - throw exception; - } + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); String nw_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); return msoClientInterface.createNwInstance(requestDetails, nw_endpoint); } @Override - public MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception { + public MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) { String methodName = "createVolumeGroupInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { - endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); - } catch (Exception exception) { - throw exception; - } + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); vnf_endpoint = vnf_endpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); @@ -168,16 +141,12 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } @Override - public MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception { + public MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) { String methodName = "createVfModuleInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { - endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); - } catch (Exception exception) { - throw exception; - } + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); String partial_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); String vf_module_endpoint = partial_endpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); @@ -186,61 +155,59 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } @Override - public MsoResponseWrapper createConfigurationInstance(RequestDetails requestDetails, String serviceInstanceId) throws Exception { + public MsoResponseWrapper createConfigurationInstance(org.onap.vid.mso.rest.RequestDetailsWrapper requestDetailsWrapper, String serviceInstanceId) { String methodName = "createConfigurationInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_CONFIGURATIONS); endpoint = endpoint.replace(SVC_INSTANCE_ID, serviceInstanceId); - return msoClientInterface.createConfigurationInstance(requestDetails, endpoint); + return msoClientInterface.createConfigurationInstance(requestDetailsWrapper, endpoint); } @Override - public MsoResponseWrapper deleteE2eSvcInstance(Object requestDetails, String serviceInstanceId) throws Exception { + public MsoResponseWrapper deleteE2eSvcInstance(Object requestDetails, String serviceInstanceId) { String methodName = "deleteE2eSvcInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { - endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_E2E_SVC_INSTANCE); - } catch (Exception exception) { - throw exception; - } - - String svc_endpoint = endpoint + "/" + serviceInstanceId; + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_E2E_SVC_INSTANCE) + "/" + serviceInstanceId; - return msoClientInterface.deleteE2eSvcInstance(requestDetails, svc_endpoint); + return msoClientInterface.deleteE2eSvcInstance(requestDetails, endpoint); } - + @Override - public MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String serviceInstanceId) throws Exception { + public MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String serviceInstanceId, String serviceStatus) { String methodName = "deleteSvcInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { + + if (featureManager.isActive(FLAG_UNASSIGN_SERVICE)){ + endpoint = validateEndpointPath(MsoProperties.MSO_DELETE_OR_UNASSIGN_REST_API_SVC_INSTANCE); + if (shouldUnassignService(serviceStatus)){ + logger.debug(EELFLoggerDelegate.debugLogger, "unassign service"); + String svc_endpoint = endpoint + "/" + serviceInstanceId + "/unassign"; + return msoClientInterface.unassignSvcInstance(requestDetails, svc_endpoint); + } + } else { endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_SVC_INSTANCE); - } catch (Exception exception) { - throw exception; } String svc_endpoint = endpoint + "/" + serviceInstanceId; - return msoClientInterface.deleteSvcInstance(requestDetails, svc_endpoint); } + private boolean shouldUnassignService(String serviceStatus) { + return ImmutableList.of("created","pendingdelete","pending-delete", "assigned").contains(serviceStatus.toLowerCase()); + } + @Override - public MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception { + public MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) { String methodName = "deleteVnf"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { - endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); - } catch (Exception exception) { - throw exception; - } + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); vnf_endpoint = vnf_endpoint + '/' + vnfInstanceId; @@ -248,16 +215,12 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } @Override - public MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId, String vfModuleId) throws Exception { + public MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId, String vfModuleId) { String methodName = "deleteVfModule"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { - endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); - } catch (Exception exception) { - throw exception; - } + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); String vf__modules_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId).replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); @@ -267,16 +230,12 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } @Override - public MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId, String volumeGroupId) throws Exception { + public MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId, String volumeGroupId) { String methodName = "deleteVolumeGroupInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { - endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); - } catch (Exception exception) { - throw exception; - } + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); String svc_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); String vnf_endpoint = svc_endpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); @@ -286,16 +245,12 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } @Override - public MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String serviceInstanceId, String networkInstanceId) throws Exception { + public MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String serviceInstanceId, String networkInstanceId) { String methodName = "deleteNwInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { - endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); - } catch (Exception exception) { - throw exception; - } + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); String svc_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); String delete_nw_endpoint = svc_endpoint + "/" + networkInstanceId; @@ -304,15 +259,14 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } @Override - public MsoResponseWrapper getOrchestrationRequest(String requestId) throws Exception { + public MsoResponseWrapper getOrchestrationRequest(String requestId) { String methodName = "getOrchestrationRequest"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - MsoResponseWrapper w = null; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQ); String path = p + "/" + requestId; - RestObject<String> restObjStr = new RestObject<String>(); + RestObject<String> restObjStr = new RestObject<>(); String str = new String(); restObjStr.set(str); @@ -328,15 +282,14 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } @Override - public MsoResponseWrapper getOrchestrationRequests(String filterString) throws Exception { + public MsoResponseWrapper getOrchestrationRequests(String filterString) { String methodName = "getOrchestrationRequest"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - MsoResponseWrapper w = null; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQS); String path = p + filterString; - RestObject<String> restObjStr = new RestObject<String>(); + RestObject<String> restObjStr = new RestObject<>(); String str = new String(); restObjStr.set(str); @@ -352,25 +305,32 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } @Override - public List<Request> getOrchestrationRequestsForDashboard() throws Exception { + public List<Request> getOrchestrationRequestsForDashboard() { String methodName = "getOrchestrationRequestsForDashboard"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); List<Request> filteredOrchestrationRequests = new ArrayList<>(); try { String path = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQS); path += "filter=modelType:EQUALS:vnf"; - RestObject<String> restObjStr = new RestObject<String>(); + RestObject<String> restObjStr = new RestObject<>(); String str = new String(); restObjStr.set(str); MsoResponseWrapper msoResponseWrapper = msoClientInterface.getOrchestrationRequestsForDashboard(str, "", path, restObjStr); List<RequestWrapper> allOrchestrationRequests = deserializeOrchestrationRequestsJson(msoResponseWrapper.getEntity()); - ; + final ImmutableList<String> suppoertedRequestTypes = ImmutableList.of( + RequestType.REPLACE_INSTANCE.toString().toUpperCase(), + RequestType.UPDATE_INSTANCE.toString().toUpperCase(), + RequestType.APPLY_UPDATED_CONFIG.toString().toUpperCase(), + RequestType.IN_PLACE_SOFTWARE_UPDATE.toString().toUpperCase() + ); + for (RequestWrapper currentRequest : allOrchestrationRequests) { - if ((currentRequest.getRequest() != null) && (currentRequest.getRequest().getRequestScope() == Request.RequestScope.VNF) && ((currentRequest.getRequest().getRequestType() == - Request.RequestType.REPLACE_INSTANCE) || (currentRequest.getRequest().getRequestType() == - Request.RequestType.UPDATE_INSTANCE))) { + if (currentRequest.getRequest() != null + && "vnf".equalsIgnoreCase(currentRequest.getRequest().getRequestScope()) + && suppoertedRequestTypes.contains(upperCase(currentRequest.getRequest().getRequestType())) + ) { filteredOrchestrationRequests.add(currentRequest.getRequest()); } } @@ -379,31 +339,35 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); } return filteredOrchestrationRequests; - } - private List<RequestWrapper> deserializeOrchestrationRequestsJson(String orchestrationRequestsJson) throws Exception { + private List<RequestWrapper> deserializeOrchestrationRequestsJson(String orchestrationRequestsJson) { String methodName = "deserializeOrchestrationRequestsJson"; - logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true); - RequestList requestList = mapper.readValue(orchestrationRequestsJson, RequestList.class); + RequestList requestList = null; + try { + requestList = mapper.readValue(orchestrationRequestsJson, RequestList.class); + } catch (IOException e) { + throw new GenericUncheckedException(e); + } return requestList.getRequestList(); } @Override - public List<Task> getManualTasksByRequestId(String originalRequestId) throws Exception { + public List<Task> getManualTasksByRequestId(String originalRequestId) { String methodName = "getManualTasksByRequestId"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_MAN_TASKS); String path = p + "?originalRequestId=" + originalRequestId; - RestObject<String> restObjStr = new RestObject<String>(); + RestObject<String> restObjStr = new RestObject<>(); String str = new String(); restObjStr.set(str); @@ -417,26 +381,29 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } } - private List<Task> deserializeManualTasksJson(String manualTasksJson) throws Exception { + private List<Task> deserializeManualTasksJson(String manualTasksJson) { String methodName = "deserializeManualTasksJson"; - logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START); ObjectMapper mapper = new ObjectMapper(); - TaskList taskList = mapper.readValue(manualTasksJson, TaskList.class); - return taskList.getTaskList(); + try { + TaskList taskList = mapper.readValue(manualTasksJson, TaskList.class); + return taskList.getTaskList(); + } catch (IOException e) { + throw new GenericUncheckedException(e); + } } @Override - public MsoResponseWrapper completeManualTask(RequestDetails requestDetails, String taskId) throws Exception { + public MsoResponseWrapper completeManualTask(RequestDetails requestDetails, String taskId) { String methodName = "completeManualTask"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - MsoResponseWrapper w = null; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_MAN_TASKS); String path = p + "/" + taskId + "/complete"; - RestObject<String> restObjStr = new RestObject<String>(); + RestObject<String> restObjStr = new RestObject<>(); String str = new String(); restObjStr.set(str); @@ -452,12 +419,12 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } @Override - public MsoResponseWrapper activateServiceInstance(RequestDetails requestDetails, String serviceInstanceId) throws Exception { + public MsoResponseWrapper activateServiceInstance(RequestDetails requestDetails, String serviceInstanceId) { String methodName = "activateServiceInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { String serviceEndpoint = SystemProperties.getProperty(MsoProperties.MSO_REST_API_SVC_INSTANCE); - String activateServicePath = serviceEndpoint + "/" + serviceInstanceId + "/activate"; + String activateServicePath = serviceEndpoint + "/" + serviceInstanceId + ACTIVATE; RestObject<String> restObjStr = new RestObject<>(); String str = ""; @@ -476,39 +443,31 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { @Override - public MsoResponseWrapperInterface updateVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception { + public MsoResponseWrapperInterface updateVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) { String methodName = "updateVnf"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { - endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); - } catch (Exception exception) { - throw exception; - } + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); vnf_endpoint = vnf_endpoint + '/' + vnfInstanceId; return msoClientInterface.updateVnf(requestDetails, vnf_endpoint); } @Override - public MsoResponseWrapperInterface replaceVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception { + public MsoResponseWrapperInterface replaceVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) { String methodName = "replaceVnf"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint; - try { - endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_CHANGE_MANAGEMENT_INSTANCE); - } catch (Exception exception) { - throw exception; - } + endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_CHANGE_MANAGEMENT_INSTANCE); String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); vnf_endpoint = vnf_endpoint.replace(VNF_INSTANCE_ID, vnfInstanceId); vnf_endpoint = vnf_endpoint.replace(REQUEST_TYPE, MsoChangeManagementRequest.REPLACE); return msoClientInterface.replaceVnf(requestDetails, vnf_endpoint); } - public RequestDetailsWrapper generateInPlaceMsoRequest(org.onap.vid.changeManagement.RequestDetails requestDetails) throws Exception { + public RequestDetailsWrapper generateInPlaceMsoRequest(org.onap.vid.changeManagement.RequestDetails requestDetails) { validateUpdateVnfSoftwarePayload(requestDetails); RequestDetails inPlaceSoftwareUpdateRequest = new RequestDetails(); inPlaceSoftwareUpdateRequest.setCloudConfiguration(requestDetails.getCloudConfiguration()); @@ -520,7 +479,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } @Override - public RequestDetailsWrapper generateConfigMsoRequest(org.onap.vid.changeManagement.RequestDetails requestDetails) throws Exception { + public RequestDetailsWrapper generateConfigMsoRequest(org.onap.vid.changeManagement.RequestDetails requestDetails) { validateUpdateVnfConfig(requestDetails); RequestDetails ConfigUpdateRequest = new RequestDetails(); ConfigUpdateRequest.setRequestParameters(requestDetails.getRequestParameters()); @@ -530,19 +489,23 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { return requestDetailsWrapper; } + + + + @Override - public MsoResponseWrapperInterface updateVnfSoftware(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception { + public MsoResponseWrapperInterface updateVnfSoftware(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) { String methodName = "updateVnfSoftware"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String vnf_endpoint = getChangeManagementEndpoint(serviceInstanceId, vnfInstanceId, MsoChangeManagementRequest.SOFTWARE_UPDATE); //workflow name in mso is different than workflow name in vid UI RequestDetailsWrapper finalRequestDetails = generateInPlaceMsoRequest(requestDetails); return msoClientInterface.changeManagementUpdate(finalRequestDetails, vnf_endpoint); } @Override - public MsoResponseWrapperInterface updateVnfConfig(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) throws Exception { + public MsoResponseWrapperInterface updateVnfConfig(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) { String methodName = "updateVnfConfig"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); RequestDetailsWrapper finalRequestDetails = generateConfigMsoRequest(requestDetails); String vnf_endpoint = getChangeManagementEndpoint(serviceInstanceId, vnfInstanceId, MsoChangeManagementRequest.CONFIG_UPDATE); return msoClientInterface.changeManagementUpdate(finalRequestDetails, vnf_endpoint); @@ -556,7 +519,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { return vnf_endpoint; } - private Map getChangeManagementPayload(RequestDetails requestDetails, String message) throws Exception{ + private Map getChangeManagementPayload(RequestDetails requestDetails, String message){ if(requestDetails.getRequestParameters()==null||requestDetails.getRequestParameters().getAdditionalProperties()==null){ throw new BadRequestException(message); } @@ -569,18 +532,17 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } } - private void validateUpdateVnfSoftwarePayload(RequestDetails requestDetails) throws Exception { + private void validateUpdateVnfSoftwarePayload(RequestDetails requestDetails) { final String noValidPayloadMsg = "No valid payload in " + ChangeManagementRequest.VNF_IN_PLACE_SOFTWARE_UPDATE + " request"; Map payload = getChangeManagementPayload(requestDetails, noValidPayloadMsg); validateUpdateVnfSoftwarePayloadProperty(payload, noValidPayloadMsg, "existing_software_version", SOFTWARE_VERSION_PATTERN); validateUpdateVnfSoftwarePayloadProperty(payload, noValidPayloadMsg, "new_software_version", SOFTWARE_VERSION_PATTERN); - //if "operations-timeout" is not integer, trying to read it as String that represent a number - if (!(payload.get("operations-timeout") instanceof Integer)) { + //if "operations_timeout" is not integer, trying to read it as String that represent a number + if (!(payload.get("operations_timeout") instanceof Integer)) { validateUpdateVnfSoftwarePayloadProperty(payload, noValidPayloadMsg, "operations_timeout", NUMBER_PATTERN); } - } private void validateUpdateVnfSoftwarePayloadProperty(Map payload, String noValidPayloadMsg, String propertyName, Pattern pattern) { @@ -594,7 +556,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } } - private void validateUpdateVnfConfig(RequestDetails requestDetails) throws Exception { + private void validateUpdateVnfConfig(RequestDetails requestDetails) { final String noValidPayloadMsg = "No valid payload in " + ChangeManagementRequest.CONFIG_UPDATE + " request"; Map payload = getChangeManagementPayload(requestDetails, noValidPayloadMsg); @@ -603,7 +565,6 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } private void validateConfigUpdateVnfPayloadProperty(Map payload, String noValidPayloadMsg, String propertyName) { - Object forValidation = payload.get(propertyName); final String noValidPayloadPropertyMsg = noValidPayloadMsg+ ", "+ propertyName + " property is not valid"; if(!payload.containsKey(propertyName)) { throw new BadRequestException( noValidPayloadPropertyMsg); @@ -612,18 +573,18 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { @Override public MsoResponseWrapper deleteConfiguration( - RequestDetails requestDetails, + org.onap.vid.mso.rest.RequestDetailsWrapper requestDetailsWrapper, String serviceInstanceId, - String configurationId) throws Exception { + String configurationId) { String methodName = "deleteConfiguration"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_CONFIGURATION_INSTANCE); endpoint = endpoint.replace(SVC_INSTANCE_ID, serviceInstanceId); endpoint = endpoint.replace(CONFIGURATION_ID, configurationId); - return msoClientInterface.deleteConfiguration(requestDetails, endpoint); + return msoClientInterface.deleteConfiguration(requestDetailsWrapper, endpoint); } @Override @@ -631,10 +592,10 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { RequestDetails requestDetails, String serviceInstanceId, String configurationId, - boolean isActivate) throws Exception { + boolean isActivate) { String methodName = "setConfigurationActiveStatus"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_CONFIGURATION_INSTANCE); endpoint = endpoint.replace(SVC_INSTANCE_ID, serviceInstanceId); @@ -647,9 +608,9 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } @Override - public MsoResponseWrapper setServiceInstanceStatus(RequestDetails requestDetails , String serviceInstanceId, boolean isActivate)throws Exception{ + public MsoResponseWrapper setServiceInstanceStatus(RequestDetails requestDetails , String serviceInstanceId, boolean isActivate) { String methodName = "setServiceInstanceStatus"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { String serviceEndpoint = validateEndpointPath(MsoProperties.MSO_REST_API_SVC_INSTANCE); String endpoint = serviceEndpoint + "/" + serviceInstanceId; @@ -678,9 +639,9 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { RequestDetails requestDetails, String serviceInstanceId, String configurationId, - boolean isEnable) throws Exception { + boolean isEnable) { String methodName = "setPortOnConfigurationStatus"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_CONFIGURATION_INSTANCE); endpoint = endpoint.replace(SVC_INSTANCE_ID, serviceInstanceId); @@ -697,13 +658,13 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { public RequestDetailsWrapper<RequestDetails> createOperationalEnvironmentActivationRequestDetails(OperationalEnvironmentActivateInfo details) { RequestDetails requestDetails = new RequestDetails(); RequestInfo requestInfo = new RequestInfo(); - requestInfo.setAdditionalProperty("resourceType", RESOURCE_TYPE_OPERATIONAL_ENVIRONMENT); + requestInfo.setAdditionalProperty(RESOURCE_TYPE, RESOURCE_TYPE_OPERATIONAL_ENVIRONMENT); requestInfo.setSource(SOURCE_OPERATIONAL_ENVIRONMENT); requestInfo.setRequestorId(details.getUserId()); requestDetails.setRequestInfo(requestInfo); org.onap.vid.domain.mso.RelatedInstance relatedInstance = new org.onap.vid.domain.mso.RelatedInstance(); - relatedInstance.setAdditionalProperty("resourceType", RESOURCE_TYPE_OPERATIONAL_ENVIRONMENT); + relatedInstance.setAdditionalProperty(RESOURCE_TYPE, RESOURCE_TYPE_OPERATIONAL_ENVIRONMENT); relatedInstance.setInstanceId(details.getRelatedInstanceId()); relatedInstance.setInstanceName(details.getRelatedInstanceName()); requestDetails.setAdditionalProperty("relatedInstanceList", Collections.singletonList(ImmutableMap.of("relatedInstance", relatedInstance))); @@ -717,7 +678,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { RequestDetailsWrapper<RequestDetails> requestDetailsWrapper = new RequestDetailsWrapper<>(requestDetails); - debugRequestDetails(requestDetailsWrapper); + debugRequestDetails(requestDetailsWrapper, logger); return requestDetailsWrapper; } @@ -734,7 +695,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { RequestDetails requestDetails = new RequestDetails(); RequestInfo requestInfo = new RequestInfo(); - requestInfo.setAdditionalProperty("resourceType", RESOURCE_TYPE_OPERATIONAL_ENVIRONMENT); + requestInfo.setAdditionalProperty(RESOURCE_TYPE, RESOURCE_TYPE_OPERATIONAL_ENVIRONMENT); requestInfo.setSource(SOURCE_OPERATIONAL_ENVIRONMENT); requestInfo.setRequestorId(details.getUserId()); requestDetails.setRequestInfo(requestInfo); @@ -744,7 +705,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { requestParameters.setAdditionalProperty("operationalEnvironmentType", "VNF"); requestDetails.setRequestParameters(requestParameters); RequestDetailsWrapper<RequestDetails> requestDetailsWrapper = new RequestDetailsWrapper<>(requestDetails); - debugRequestDetails(requestDetailsWrapper); + debugRequestDetails(requestDetailsWrapper, logger); return requestDetailsWrapper; } @@ -762,24 +723,13 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { return path; } - private void debugRequestDetails(Object requestDetails) { - if (logger.isDebugEnabled()) { - String requestDetailsAsString; - try { - requestDetailsAsString = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(requestDetails); - } catch (JsonProcessingException e) { - requestDetailsAsString = "error: cannot stringify RequestDetails"; - } - logger.debug(EELFLoggerDelegate.debugLogger, "requestDetailsAsString: {}", requestDetailsAsString); - } - } - @Override public String getOperationalEnvironmentCreationPath() { - String path = validateEndpointPath(MSO_REST_API_OPERATIONAL_ENVIRONMENT_CREATE); - return path; + return validateEndpointPath(MSO_REST_API_OPERATIONAL_ENVIRONMENT_CREATE); } + + @Override public RequestDetailsWrapper<OperationEnvironmentRequestDetails> convertParametersToRequestDetails(OperationalEnvironmentController.OperationalEnvironmentCreateBody input, String userId) { OperationEnvironmentRequestDetails.RequestInfo requestInfo = new OperationEnvironmentRequestDetails.RequestInfo( @@ -802,14 +752,14 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { OperationEnvironmentRequestDetails requestDetails = new OperationEnvironmentRequestDetails(requestInfo, relatedInstanceList, requestParameters); RequestDetailsWrapper<OperationEnvironmentRequestDetails> requestDetailsWrapper = new RequestDetailsWrapper<>(requestDetails); - debugRequestDetails(requestDetailsWrapper); + debugRequestDetails(requestDetailsWrapper, logger); return requestDetailsWrapper; } @Override - public MsoResponseWrapper removeRelationshipFromServiceInstance(RequestDetails requestDetails, String serviceInstanceId) throws Exception { + public MsoResponseWrapper removeRelationshipFromServiceInstance(RequestDetails requestDetails, String serviceInstanceId) { String methodName = "removeRelationshipFromServiceInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String serviceEndpoint = SystemProperties.getProperty(MsoProperties.MSO_REST_API_SVC_INSTANCE); String removeRelationshipsPath = serviceEndpoint + "/" + serviceInstanceId + "/removeRelationships"; @@ -818,9 +768,9 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } @Override - public MsoResponseWrapper addRelationshipToServiceInstance(RequestDetails requestDetails, String serviceInstanceId) throws Exception { + public MsoResponseWrapper addRelationshipToServiceInstance(RequestDetails requestDetails, String serviceInstanceId) { String methodName = "addRelationshipToServiceInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); String serviceEndpoint = SystemProperties.getProperty(MsoProperties.MSO_REST_API_SVC_INSTANCE); String addRelationshipsPath = serviceEndpoint + "/" + serviceInstanceId + "/addRelationships"; @@ -829,4 +779,45 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } + public enum RequestType { + + CREATE_INSTANCE("createInstance"), + DELETE_INSTANCE("deleteInstance"), + REPLACE_INSTANCE("replaceInstance"), + UPDATE_INSTANCE("updateInstance"), + ACTIVATE_INSTANCE("activateInstance"), + DEACTIVATE_INSTANCE("deactivateInstance"), + APPLY_UPDATED_CONFIG("applyUpdatedConfig"), + IN_PLACE_SOFTWARE_UPDATE("inPlaceSoftwareUpdate"), + UNKNOWN("unknown"), + NOT_PROVIDED("not provided"); + private final String value; + private static final Map<String, RequestType> CONSTANTS = new HashMap<>(); + + static { + for (RequestType c: values()) { + CONSTANTS.put(c.value, c); + } + } + + RequestType(String value) { + this.value = value; + } + + @JsonValue + @Override + public String toString() { + return this.value; + } + + @JsonCreator + public static RequestType fromValue(String value) { + RequestType constant = CONSTANTS.get(value); + if (constant == null) { + throw new IllegalArgumentException(value); + } else { + return constant; + } + } + } }
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java index 350be441..a5fb7602 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java @@ -16,11 +16,11 @@ public interface MsoInterface { * --> failure : would return 200 with failure data. * @throws Exception */ - MsoResponseWrapper createSvcInstance(RequestDetails requestDetails, String endpoint) throws Exception; + MsoResponseWrapper createSvcInstance(RequestDetails requestDetails, String endpoint); //For VoLTE E2E services - MsoResponseWrapper createE2eSvcInstance(Object requestDetails, String endpoint) throws Exception; - MsoResponseWrapper deleteE2eSvcInstance(Object requestDetails, String endpoint) throws Exception; + MsoResponseWrapper createE2eSvcInstance(Object requestDetails, String endpoint); + MsoResponseWrapper deleteE2eSvcInstance(Object requestDetails, String endpoint); /** * will create a virtual network function using MSO service. @@ -28,9 +28,9 @@ public interface MsoInterface { * @return - the response body recived from MSO * @throws Exception */ - MsoResponseWrapper createVnf(RequestDetails requestDetails, String endpoint) throws Exception; + MsoResponseWrapper createVnf(RequestDetails requestDetails, String endpoint); - MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String endpoint) throws Exception; + MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String endpoint); /** * * @param requestDetails @@ -38,7 +38,7 @@ public interface MsoInterface { * @return * @throws Exception */ - MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String path) throws Exception; + MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String path); /** * @@ -46,44 +46,46 @@ public interface MsoInterface { * @return * @throws Exception */ - MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String endpoint) throws Exception; + MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String endpoint); - MsoResponseWrapper createConfigurationInstance(RequestDetails requestDetails, String endpoint) throws Exception; + MsoResponseWrapper createConfigurationInstance(org.onap.vid.mso.rest.RequestDetailsWrapper requestDetailsWrapper, String endpoint); - MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String endpoint) throws Exception; + MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String endpoint); - MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String endpoint) throws Exception; + MsoResponseWrapper unassignSvcInstance(RequestDetails requestDetails, String endpoint); - MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String endpoint) throws Exception; + MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String endpoint); - MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String endpoint) throws Exception; + MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String endpoint); - MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String endpoint) throws Exception; + MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String endpoint); - void getOrchestrationRequest(String t, String sourceId, String endpoint, RestObject restObject) throws Exception; + MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String endpoint); - MsoResponseWrapper getOrchestrationRequestsForDashboard(String t , String sourceId , String endpoint , RestObject restObject) throws Exception; + void getOrchestrationRequest(String t, String sourceId, String endpoint, RestObject restObject); - MsoResponseWrapper getManualTasksByRequestId(String t , String sourceId , String endpoint , RestObject restObject) throws Exception; + MsoResponseWrapper getOrchestrationRequestsForDashboard(String t , String sourceId , String endpoint , RestObject restObject); - MsoResponseWrapper completeManualTask(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject restObject) throws Exception; + MsoResponseWrapper getManualTasksByRequestId(String t , String sourceId , String endpoint , RestObject restObject); - MsoResponseWrapper updateVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String vnf_endpoint) throws Exception; + MsoResponseWrapper completeManualTask(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject restObject); - MsoResponseWrapper replaceVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String vnf_endpoint) throws Exception; + MsoResponseWrapper updateVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String vnf_endpoint); - MsoResponseWrapper deleteConfiguration(RequestDetails requestDetails, String pmc_endpoint) throws Exception; + MsoResponseWrapper replaceVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String vnf_endpoint); - MsoResponseWrapper setConfigurationActiveStatus(RequestDetails requestDetails, String endpoint) throws Exception; + MsoResponseWrapper deleteConfiguration(org.onap.vid.mso.rest.RequestDetailsWrapper requestDetailsWrapper, String pmc_endpoint); - MsoResponseWrapper setPortOnConfigurationStatus(RequestDetails requestDetails, String endpoint) throws Exception; + MsoResponseWrapper setConfigurationActiveStatus(RequestDetails requestDetails, String endpoint); - void setServiceInstanceStatus(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject<String> restObject) throws Exception; + MsoResponseWrapper setPortOnConfigurationStatus(RequestDetails requestDetails, String endpoint); - MsoResponseWrapperInterface changeManagementUpdate(RequestDetailsWrapper requestDetails, String endpoint) throws Exception; + void setServiceInstanceStatus(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject<String> restObject); - MsoResponseWrapper removeRelationshipFromServiceInstance(RequestDetails requestDetails, String endpoint) throws Exception; + MsoResponseWrapperInterface changeManagementUpdate(RequestDetailsWrapper requestDetails, String endpoint); - MsoResponseWrapper addRelationshipToServiceInstance(RequestDetails requestDetails, String addRelationshipsPath) throws Exception; + MsoResponseWrapper removeRelationshipFromServiceInstance(RequestDetails requestDetails, String endpoint); + + MsoResponseWrapper addRelationshipToServiceInstance(RequestDetails requestDetails, String addRelationshipsPath); } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoProperties.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoProperties.java index f6b3f946..773b8a83 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoProperties.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoProperties.java @@ -74,7 +74,10 @@ public class MsoProperties extends SystemProperties { /** The Constant MSO_REST_API_SVC_INSTANCE. */ public static final String MSO_REST_API_SVC_INSTANCE = "mso.restapi.svc.instance"; // /serviceInstances/v2 - + + /** The Constant MSO_DELETE_OR_UNASSIGN_REST_API_SVC_INSTANCE. */ + public static final String MSO_DELETE_OR_UNASSIGN_REST_API_SVC_INSTANCE = "mso.restapi.svc.instance.deleteAndUnassign"; + /** The Constant MSO_REST_API_VNF_INSTANCE. */ public static final String MSO_REST_API_VNF_INSTANCE = "mso.restapi.vnf.instance"; // /serviceInstances/v2/{service_instance_id}/vnfs @@ -100,7 +103,7 @@ public class MsoProperties extends SystemProperties { public static final String MSO_REST_API_VOLUME_GROUP_INSTANCE = "mso.restapi.volume.group.instance"; //serviceInstances/v2/{serviceInstanceId}/volumeGroups /** The Constant MSO_REST_API_CONFIGURATION_INSTANCE. */ - public static final String MSO_REST_API_CONFIGURATIONS = "mso.restapi.configurations"; //serviceInstances/v5/{serviceInstanceId}/configurations/ + public static final String MSO_REST_API_CONFIGURATIONS = "mso.restapi.configurations"; //serviceInstances/v5/{serviceInstanceId}/configurations public static final String MSO_REST_API_CONFIGURATION_INSTANCE = "mso.restapi.configuration.instance"; //serviceInstances/v5/{serviceInstanceId}/configurations/{configurationId} /** The Constant MSO_REST_API_OPERATIONAL_ENVIRONMENT */ @@ -118,5 +121,5 @@ public class MsoProperties extends SystemProperties { /** The Constant dateFormat. */ final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - + } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java b/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java index 7924a7d7..0494facd 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java @@ -4,17 +4,17 @@ import com.att.eelf.configuration.EELFLogger; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.codec.binary.Base64; import org.eclipse.jetty.util.security.Password; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.aai.util.HttpClientMode; +import org.onap.vid.aai.util.HttpsAuthClient; import org.onap.vid.client.HttpBasicClient; -import org.onap.vid.client.HttpsBasicClient; -import org.onap.vid.mso.rest.RequestDetails; +import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.mso.rest.RestInterface; import org.onap.vid.utils.Logging; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; -import javax.servlet.http.HttpServletRequest; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; @@ -25,6 +25,7 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; +import java.util.UUID; import static org.onap.vid.utils.Logging.*; @@ -33,22 +34,33 @@ import static org.onap.vid.utils.Logging.*; */ public class RestMsoImplementation implements RestInterface { + public static final String START_LOG = " start"; + public static final String APPLICATION_JSON = "application/json"; + public static final String WITH_STATUS = " with status="; + public static final String URL_LOG = ", url="; + public static final String NO_RESPONSE_ENTITY_LOG = " No response entity, this is probably ok, e="; + public static final String WITH_URL_LOG = " with url="; + public static final String EXCEPTION_LOG = ", Exception: "; + public static final String REST_API_SUCCESSFULL_LOG = " REST api was successfull!"; + public static final String REST_API_POST_WAS_SUCCESSFUL_LOG = " REST api POST was successful!"; /** * The logger. */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMsoImplementation.class); - final private EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("mso"); + private final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("mso"); /** * The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); /** The client. */ - private static Client client = null; + private Client client = null; + + @Autowired + HttpsAuthClient httpsAuthClient; /** The common headers. */ - //private MultivaluedHashMap<String, Object> commonHeaders; /** * Instantiates a new mso rest interface. */ @@ -71,30 +83,28 @@ public class RestMsoImplementation implements RestInterface { MultivaluedHashMap<String, Object> commonHeaders = new MultivaluedHashMap(); commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc))); - commonHeaders.put(requestIdHeaderKey, Collections.singletonList(getHttpServletRequest().getHeader(requestIdHeaderKey))); - //Pass calling application identifier to SO + //Pass calling application identifier to SO commonHeaders.put("X-FromAppId", Collections.singletonList(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME))); + try { + commonHeaders.put(REQUEST_ID_HEADER_KEY, Collections.singletonList(Logging.extractOrGenerateRequestId())); + } + catch (IllegalStateException e){ + //in async jobs we don't have any HttpServletRequest + commonHeaders.put(REQUEST_ID_HEADER_KEY, Collections.singletonList(UUID.randomUUID().toString())); + } + - boolean use_ssl = true; + boolean useSsl = true; if ( (mso_url != null) && ( !(mso_url.isEmpty()) ) ) { - if ( mso_url.startsWith("https")) { - use_ssl = true; - } - else { - use_ssl = false; - } + useSsl = mso_url.startsWith("https"); } if (client == null) { try { - if ( use_ssl ) { - //logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + methodname + " getting HttpsBasicClient with username=" + username - // + " password=" + password); - client = HttpsBasicClient.getClient(); + if ( useSsl ) { + client = httpsAuthClient.getClient(HttpClientMode.WITHOUT_KEYSTORE); } else { - //logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + methodname + " getting HttpsBasicClient with username=" + username - // + " password=" + password); client = HttpBasicClient.getClient(); } } catch (Exception e) { @@ -105,10 +115,10 @@ public class RestMsoImplementation implements RestInterface { return commonHeaders; } - public <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ) throws Exception { + public <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ) { String methodName = "Get"; - logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_LOG); String url=""; restObject.set(t); @@ -119,7 +129,7 @@ public class RestMsoImplementation implements RestInterface { Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); final Response cres = client.target(url) .request() - .accept("application/json") + .accept(APPLICATION_JSON) .headers(commonHeaders) .get(); Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres); @@ -129,10 +139,10 @@ public class RestMsoImplementation implements RestInterface { if (status == 200 || status == 202) { t = (T) cres.readEntity(t.getClass()); restObject.set(t); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " REST api was successfull!"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + REST_API_SUCCESSFULL_LOG); } else { - throw new Exception(methodName + " with status="+ status + ", url= " + url ); + throw new GenericUncheckedException(methodName + WITH_STATUS + status + ", url= " + url ); } logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status ); @@ -140,7 +150,7 @@ public class RestMsoImplementation implements RestInterface { return; } - public <T> RestObject<T> GetForObject(String sourceID, String path, Class<T> clazz) throws Exception { + public <T> RestObject<T> GetForObject(String sourceID, String path, Class<T> clazz) { final String methodName = getMethodName(); logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {}, {})", getMethodCallerName(), methodName, sourceID, path, clazz); @@ -151,7 +161,7 @@ public class RestMsoImplementation implements RestInterface { Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); final Response cres = client.target(url) .request() - .accept("application/json") + .accept(APPLICATION_JSON) .headers(commonHeaders) .get(); Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres); @@ -159,9 +169,9 @@ public class RestMsoImplementation implements RestInterface { int status = cres.getStatus(); if (status == 200 || status == 202) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " REST api was successfull!"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + REST_API_SUCCESSFULL_LOG); } else { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with status="+status+", url="+url); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS +status+ URL_LOG +url); } logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status ); @@ -176,7 +186,7 @@ public class RestMsoImplementation implements RestInterface { String url=""; Response cres = null; - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + START_LOG); try { MultivaluedHashMap<String, Object> commonHeaders = initMsoClient(); @@ -185,7 +195,8 @@ public class RestMsoImplementation implements RestInterface { Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url, r); cres = client.target(url) .request() - .accept("application/json") + + .accept(APPLICATION_JSON) .headers(commonHeaders) //.entity(r) .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)).invoke(); @@ -212,30 +223,30 @@ public class RestMsoImplementation implements RestInterface { restObject.set(t); } catch ( Exception e ) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " No response entity, this is probably ok, e=" + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + NO_RESPONSE_ENTITY_LOG + e.getMessage()); } } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString()); throw e; } } - public <T> RestObject<T> PostForObject(Object requestDetails, String sourceID, String path, Class<T> clazz) throws RuntimeException { + public <T> RestObject<T> PostForObject(Object requestDetails, String sourceID, String path, Class<T> clazz) { logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {}, {}, {})", getMethodCallerName(), getMethodName(), requestDetails, sourceID, path, clazz); RestObject<T> restObject = new RestObject<>(); - Post(clazz, requestDetails, sourceID, path, restObject); + Post(clazz, requestDetails, path, restObject); return restObject; } @Override - public <T> void Post(T t, Object r, String sourceID, String path, RestObject<T> restObject) throws RuntimeException { + public <T> void Post(T t, Object r, String sourceID, String path, RestObject<T> restObject) { logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {}, {}, {})", getMethodCallerName(), getMethodName(), t.getClass(), r, sourceID, path); - Post(t.getClass(), r, sourceID, path, restObject); + Post(t.getClass(), r, path, restObject); } public Invocation.Builder prepareClient(String path, String methodName) { @@ -246,13 +257,13 @@ public class RestMsoImplementation implements RestInterface { // Change the content length return client.target(url) .request() - .accept("application/json") + .accept(APPLICATION_JSON) .headers(commonHeaders); } - public <T> void Post(Class<?> tClass, Object requestDetails, String sourceID, String path, RestObject<T> restObject) throws RuntimeException { + public <T> void Post(Class<?> tClass, Object requestDetails, String path, RestObject<T> restObject) { String methodName = "Post"; String url=""; @@ -265,11 +276,10 @@ public class RestMsoImplementation implements RestInterface { // Change the content length final Response cres = client.target(url) .request() - .accept("application/json") + .accept(APPLICATION_JSON) .headers(commonHeaders) .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); Logging.logResponse(outgoingRequestsLogger, HttpMethod.POST, url, cres); - final RestObject<T> cresToRestObject = cresToRestObject(cres, tClass); restObject.set(cresToRestObject.get()); restObject.setStatusCode(cresToRestObject.getStatusCode()); @@ -279,16 +289,16 @@ public class RestMsoImplementation implements RestInterface { restObject.setStatusCode (status); if ( status >= 200 && status <= 299 ) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!"); - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!"); + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + REST_API_POST_WAS_SUCCESSFUL_LOG); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + REST_API_POST_WAS_SUCCESSFUL_LOG); } else { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with status="+status+", url="+url); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS +status+ URL_LOG +url); } } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString()); throw e; } @@ -303,16 +313,16 @@ public class RestMsoImplementation implements RestInterface { try { cres.bufferEntity(); rawEntity = cres.readEntity(String.class); + restObject.setRaw(rawEntity); T t = (T) new ObjectMapper().readValue(rawEntity, tClass); restObject.set(t); } catch ( Exception e ) { try { - restObject.setRaw(rawEntity); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + getMethodCallerName() + " Error reading response entity as " + tClass + ": , e=" + e.getMessage() + ", Entity=" + rawEntity); } catch (Exception e2) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + getMethodCallerName() + " No response entity, this is probably ok, e=" + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + getMethodCallerName() + NO_RESPONSE_ENTITY_LOG + e.getMessage()); } } @@ -325,14 +335,13 @@ public class RestMsoImplementation implements RestInterface { } @Override - public <T> void Put(T t, org.onap.vid.changeManagement.RequestDetailsWrapper r, String sourceID, String path, RestObject<T> restObject) throws Exception { + public <T> void Put(T t, org.onap.vid.changeManagement.RequestDetailsWrapper r, String sourceID, String path, RestObject<T> restObject) { String methodName = "Put"; String url=""; - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + START_LOG); -// logRequest (r); try { MultivaluedHashMap<String, Object> commonHeaders = initMsoClient(); @@ -342,7 +351,7 @@ public class RestMsoImplementation implements RestInterface { // Change the content length final Response cres = client.target(url) .request() - .accept("application/json") + .accept(APPLICATION_JSON) .headers(commonHeaders) //.header("content-length", 201) //.header("X-FromAppId", sourceID) @@ -355,7 +364,7 @@ public class RestMsoImplementation implements RestInterface { restObject.set(t); } catch ( Exception e ) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " No response entity, this is probably ok, e=" + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + NO_RESPONSE_ENTITY_LOG + e.getMessage()); } @@ -363,16 +372,16 @@ public class RestMsoImplementation implements RestInterface { restObject.setStatusCode (status); if ( status >= 200 && status <= 299 ) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!"); - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " REST api POST was successful!"); + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + REST_API_POST_WAS_SUCCESSFUL_LOG); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + REST_API_POST_WAS_SUCCESSFUL_LOG); } else { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with status="+status+", url="+url); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS +status+ URL_LOG +url); } } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString()); throw e; } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/ServiceInstantiationRequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/ServiceInstantiationRequestDetails.java new file mode 100644 index 00000000..1a54b74c --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/ServiceInstantiationRequestDetails.java @@ -0,0 +1,165 @@ +package org.onap.vid.mso.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import org.onap.vid.domain.mso.CloudConfiguration; +import org.onap.vid.domain.mso.ModelInfo; +import org.onap.vid.domain.mso.SubscriberInfo; +import org.onap.vid.model.serviceInstantiation.VfModule; + +import java.util.List; +import java.util.Map; + +import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY; +import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; + +public class ServiceInstantiationRequestDetails { + + @JsonProperty("modelInfo") + private ModelInfo modelInfo; + + @JsonProperty("owningEntity") + private ServiceInstantiationOwningEntity owningEntity; + + @JsonProperty("subscriberInfo") + private SubscriberInfo subscriberInfo; + + @JsonProperty("project") + private Project project; + + @JsonProperty("requestParameters") + private RequestParameters requestParameters; + + @JsonProperty("requestInfo") + private RequestInfo requestInfo; + + public ServiceInstantiationRequestDetails(@JsonProperty(value = "modelInfo", required = true) ModelInfo modelInfo, + @JsonProperty(value = "owningEntity", required = true) ServiceInstantiationOwningEntity owningEntity, + @JsonProperty(value = "subscriberInfo", required = true) SubscriberInfo subscriberInfo, + @JsonProperty(value = "project", required = true) Project project, + @JsonProperty(value = "requestInfo", required = true) RequestInfo requestInfo, + @JsonProperty(value = "requestParameters", required = true) RequestParameters requestParameters) { + this.modelInfo = modelInfo; + this.owningEntity = owningEntity; + this.subscriberInfo = subscriberInfo; + this.project = project; + this.requestInfo = requestInfo; + this.requestParameters = requestParameters; + } + + public static class ServiceInstantiationOwningEntity{ + public final String owningEntityId; + public final String owningEntityName; + + public ServiceInstantiationOwningEntity(String owningEntityId, String owningEntityName) { + this.owningEntityId = owningEntityId; + this.owningEntityName = owningEntityName; + } + } + + public static class RequestInfo { + + @JsonInclude(NON_NULL) public final String instanceName; + public final String productFamilyId; + public final String source; + public final boolean suppressRollback; + public final String requestorId; + + public RequestInfo(String instanceName, String productFamilyId, String source, boolean rollbackOnFailure, String requestorId) { + this.instanceName = instanceName; + this.productFamilyId = productFamilyId; + this.source = source; + this.requestorId = requestorId; + // in the FE we are asking for "RollbackOnFailure" but to MSO we are passing the negative value "suppressRollback" + this.suppressRollback = !rollbackOnFailure; + } + } + + public static class Project{ + public final String projectName; + + public Project(String projectName) { + this.projectName = projectName; + } + } + + public static class RequestParameters { + + public final String subscriptionServiceType; + public final boolean aLaCarte; + public final List<ServiceInstantiationService> userParams; + + public RequestParameters(String subscriptionServiceType, boolean aLaCarte, List<ServiceInstantiationService> userParams) { + this.subscriptionServiceType = subscriptionServiceType; + this.aLaCarte = aLaCarte; + this.userParams = userParams; + } + } + + @JsonTypeName("service") + @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME) + public static class ServiceInstantiationService{ + public ModelInfo modelInfo = new ModelInfo(); + @JsonInclude(NON_NULL) public String instanceName; + public List<Map<String,String>> instanceParams; + public ServiceInstantiationVnfList resources; + + public ServiceInstantiationService (ModelInfo modelInfo, String instanceName, List<Map<String,String>> instanceParams, ServiceInstantiationVnfList vnfs){ + this.modelInfo.setModelType(modelInfo.getModelType()); + this.modelInfo.setModelName(modelInfo.getModelName()); + this.modelInfo.setModelVersionId(modelInfo.getModelVersionId()); + this.instanceName = instanceName; + this.instanceParams = instanceParams; + this.resources = vnfs; + } + } + + public static class ServiceInstantiationVnfList{ + public final List<ServiceInstantiationVnf> vnfs; + + public ServiceInstantiationVnfList(List<ServiceInstantiationVnf> vnfList) { + this.vnfs = vnfList; + } + } + + public static class ServiceInstantiationVnf{ + public final ModelInfo modelInfo; + public final CloudConfiguration cloudConfiguration; + public final Platform platform; + public final LineOfBusiness lineOfBusiness; + public final String productFamilyId; + public final List<Map<String, String>> instanceParams; + @JsonInclude(NON_EMPTY) public final List<VfModule> vfModules; + @JsonInclude(NON_NULL) public final String instanceName; + + public ServiceInstantiationVnf(ModelInfo modelInfo, CloudConfiguration cloudConfiguration, String platform, String lineOfBusiness, String productFamilyId, List<Map<String, String>> instanceParams, List<VfModule> vfModules, String instanceName) { + this.modelInfo = modelInfo; + this.cloudConfiguration = cloudConfiguration; + this.platform = new Platform(platform); + this.lineOfBusiness = new LineOfBusiness(lineOfBusiness); + this.productFamilyId = productFamilyId; + this.instanceParams = instanceParams; + this.vfModules = vfModules; + this.instanceName = instanceName; + } + } + + public static class Platform{ + public final String platformName; + + public Platform(String platformName) { + this.platformName = platformName; + } + } + + public static class LineOfBusiness{ + public final String lineOfBusinessName; + + public LineOfBusiness(String lineOfBusiness) { + this.lineOfBusinessName = lineOfBusiness; + } + } +} + diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/AsyncRequestStatus.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/AsyncRequestStatus.java index 4dd6eaca..4c3dca26 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/AsyncRequestStatus.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/AsyncRequestStatus.java @@ -20,104 +20,56 @@ package org.onap.vid.mso.rest; -//import java.util.HashMap; -//import java.util.Map; -//import javax.annotation.Generated; -import org.onap.vid.domain.mso.InstanceIds; -import org.onap.vid.domain.mso.RequestStatus; -//import com.fasterxml.jackson.annotation.JsonAnyGetter; -//import com.fasterxml.jackson.annotation.JsonAnySetter; -//import com.fasterxml.jackson.annotation.JsonCreator; -//import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -//import com.fasterxml.jackson.annotation.JsonPropertyOrder; -//import com.fasterxml.jackson.annotation.JsonValue; -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; - +import org.onap.vid.domain.mso.RequestStatus; /** - * request structure. + * Represent response for: GET orchestrationRequests */ @JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class AsyncRequestStatus { -public class AsyncRequestStatus extends org.onap.vid.domain.mso.AsyncRequestStatus { + public Request request; - - /** The instance ids. */ - private InstanceIds instanceIds; - - /** The request status. */ - private RequestStatus requestStatus; - - /* (non-Javadoc) - * @see org.onap.vid.domain.mso.AsyncRequestStatus#getInstanceIds() - */ - public InstanceIds getInstanceIds() { - return instanceIds; + public AsyncRequestStatus(Request request) { + this.request = request; } - /** - * Sets the instance ids. - * - * @param instanceIds the new instance ids - */ - public void setInstanceIds(InstanceIds instanceIds) { - this.instanceIds = instanceIds; - } + public AsyncRequestStatus() { - - /** - * (Required). - * - * @return The requestStatus - */ - @JsonProperty("requestStatus") - public RequestStatus getRequestStatus() { - return requestStatus; } - /** - * (Required). - * - * @param requestStatus The requestStatus - */ - @JsonProperty("requestStatus") - public void setRequestStatus(RequestStatus requestStatus) { - this.requestStatus = requestStatus; - } - - /* (non-Javadoc) - * @see org.onap.vid.domain.mso.AsyncRequestStatus#toString() - */ - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - /* (non-Javadoc) - * @see org.onap.vid.domain.mso.AsyncRequestStatus#hashCode() - */ - @Override - public int hashCode() { - return new HashCodeBuilder().append(getCorrelator()).append(getFinishTime()).append(instanceIds).append(getRequestId()).append(getRequestScope()).append(getRequestStatus()).append(getRequestType()).append(getStartTime()).append(getAdditionalProperties()).toHashCode(); - } + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Request { - /* (non-Javadoc) - * @see org.onap.vid.domain.mso.AsyncRequestStatus#equals(java.lang.Object) - */ - @Override - public boolean equals(Object other) { - if (other == this) { - return true; + public Request(RequestStatus requestStatus) { + this.requestStatus = requestStatus; } - if ((other instanceof AsyncRequestStatus) == false) { - return false; + + public Request() { } - AsyncRequestStatus rhs = ((AsyncRequestStatus) other); - return new EqualsBuilder().append(getCorrelator(), rhs.getCorrelator()).append(getFinishTime(), rhs.getFinishTime()).append(instanceIds, rhs.instanceIds).append(getRequestId(), rhs.getRequestId()).append(getRequestScope(), rhs.getRequestScope()).append(getRequestStatus(), rhs.getRequestStatus()).append(getRequestType(), rhs.getRequestType()).append(getStartTime(), rhs.getStartTime()).append(getAdditionalProperties(), rhs.getAdditionalProperties()).isEquals(); + + public String requestId; + + /** + * The instance ids. + */ + public InstanceReferences instanceReferences; + + /** + * The request status. + */ + public RequestStatus requestStatus; } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static class InstanceReferences { + + public String serviceInstanceId; + } + + } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java index 14761cad..ae1b7a2a 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java @@ -20,6 +20,7 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf * The Constant dateFormat. */ final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + private static final String START = " start"; private final String ORIGINAL_REQUEST_ID = "originalRequestId"; /** * The logger. @@ -27,124 +28,131 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoRestClientNew.class); @Override - public MsoResponseWrapper createSvcInstance(RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper createSvcInstance(RequestDetails requestDetails, String endpoint) { String methodName = "createSvcInstance "; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); return createInstance(requestDetails, endpoint); } @Override - public MsoResponseWrapper createE2eSvcInstance(Object requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper createE2eSvcInstance(Object requestDetails, String endpoint) { String methodName = "createE2eSvcInstance "; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); return createInstance(requestDetails, endpoint); } @Override - public MsoResponseWrapper createVnf(RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper createVnf(RequestDetails requestDetails, String endpoint) { String methodName = "createVnf"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); return createInstance(requestDetails, endpoint); } @Override - public MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String endpoint) { String methodName = "createNwInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); return createInstance(requestDetails, endpoint); } @Override - public MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String endpoint) { String methodName = "createVolumeGroupInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); return createInstance(requestDetails, endpoint); } @Override - public MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String endpoint) { String methodName = "createVfModuleInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); return createInstance(requestDetails, endpoint); } @Override - public MsoResponseWrapper createConfigurationInstance(RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper createConfigurationInstance(org.onap.vid.mso.rest.RequestDetailsWrapper requestDetailsWrapper, String endpoint) { String methodName = "createConfigurationInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - return createInstance(requestDetails, endpoint); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + return createInstance(requestDetailsWrapper, endpoint); } @Override - public MsoResponseWrapper deleteE2eSvcInstance(Object requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper deleteE2eSvcInstance(Object requestDetails, String endpoint) { String methodName = "deleteE2eSvcInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); return deleteInstance(requestDetails, endpoint); } - + @Override - public MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String endpoint) { String methodName = "deleteSvcInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); return deleteInstance(requestDetails, endpoint); } @Override - public MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper unassignSvcInstance(RequestDetails requestDetails, String endpoint) { + String methodName = "unassignSvcInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + + RestObject<String> msoResponse = PostForObject(requestDetails, "", endpoint, String.class); + return MsoUtil.wrapResponse(msoResponse); + } + + @Override + public MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String endpoint) { String methodName = "deleteVnf"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); return deleteInstance(requestDetails, endpoint); } @Override - public MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String endpoint) { String methodName = "deleteVfModule"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); return deleteInstance(requestDetails, endpoint); } @Override - public MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String endpoint) { String methodName = "deleteVolumeGroupInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); return deleteInstance(requestDetails, endpoint); } @Override - public MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String endpoint) { String methodName = "deleteNwInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); return deleteInstance(requestDetails, endpoint); } @Override - public void getOrchestrationRequest(String t, String sourceId, String endpoint, RestObject restObject) throws Exception { + public void getOrchestrationRequest(String t, String sourceId, String endpoint, RestObject restObject) { Get(t, sourceId, endpoint, restObject); } - public void getManualTasks(String t, String sourceId, String endpoint, RestObject restObject) throws Exception { + public void getManualTasks(String t, String sourceId, String endpoint, RestObject restObject) { Get(t, sourceId, endpoint, restObject); } - - public MsoResponseWrapper createInstance(Object request, String path) throws Exception { + public MsoResponseWrapper createInstance(Object request, String path) { String methodName = "createInstance"; - logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START); try { RestObject<String> restObjStr = new RestObject<String>(); @@ -164,7 +172,6 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } } - /** * Delete instance. * @@ -173,9 +180,9 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf * @return the mso response wrapper * @throws Exception the exception */ - public MsoResponseWrapper deleteInstance(Object request, String path) throws Exception { + public MsoResponseWrapper deleteInstance(Object request, String path) { String methodName = "deleteInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Delete, path =[" + path + "]"); @@ -197,9 +204,9 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } - public MsoResponseWrapper getOrchestrationRequestsForDashboard(String t, String sourceId, String endpoint, RestObject restObject) throws Exception { + public MsoResponseWrapper getOrchestrationRequestsForDashboard(String t, String sourceId, String endpoint, RestObject restObject) { String methodName = "getOrchestrationRequestsForDashboard"; - logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START); try { getOrchestrationRequest(t, sourceId, endpoint, restObject); @@ -215,9 +222,9 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } } - public MsoResponseWrapper getManualTasksByRequestId(String t, String sourceId, String endpoint, RestObject restObject) throws Exception { + public MsoResponseWrapper getManualTasksByRequestId(String t, String sourceId, String endpoint, RestObject restObject) { String methodName = "getManualTasksByRequestId"; - logger.debug(dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START); try { getManualTasks(t, sourceId, endpoint, restObject); @@ -233,9 +240,8 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } } - @Override - public MsoResponseWrapper completeManualTask(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject restObject) throws Exception { + public MsoResponseWrapper completeManualTask(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject restObject) { String methodName = "completeManualTask"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Complete "); try { @@ -254,26 +260,25 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } @Override - public MsoResponseWrapper replaceVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper replaceVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String endpoint) { String methodName = "replaceVnf"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); return replaceInstance(requestDetails, endpoint); } @Override - public MsoResponseWrapper deleteConfiguration(RequestDetails requestDetails, String pmc_endpoint) - throws Exception { + public MsoResponseWrapper deleteConfiguration(org.onap.vid.mso.rest.RequestDetailsWrapper requestDetailsWrapper, String pmc_endpoint) { String methodName = "deleteConfiguration"; logger.debug(EELFLoggerDelegate.debugLogger, - dateFormat.format(new Date()) + "<== " + methodName + " start"); + dateFormat.format(new Date()) + "<== " + methodName + START); - return deleteInstance(requestDetails, pmc_endpoint); + return deleteInstance(requestDetailsWrapper, pmc_endpoint); } @Override - public MsoResponseWrapper setConfigurationActiveStatus(RequestDetails request, String path) throws Exception { + public MsoResponseWrapper setConfigurationActiveStatus(RequestDetails request, String path) { String methodName = "setConfigurationActiveStatus"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling change configuration active status, path =[" + path + "]"); @@ -293,9 +298,9 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } @Override - public MsoResponseWrapper setPortOnConfigurationStatus(RequestDetails request, String path) throws Exception { + public MsoResponseWrapper setPortOnConfigurationStatus(RequestDetails request, String path) { String methodName = "setPortOnConfigurationStatus"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling change port configuration status, path =[" + path + "]"); @@ -315,14 +320,14 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } @Override - public MsoResponseWrapperInterface changeManagementUpdate(RequestDetailsWrapper requestDetails, String endpoint) throws Exception { + public MsoResponseWrapperInterface changeManagementUpdate(RequestDetailsWrapper requestDetails, String endpoint) { RestObject<RequestReferencesContainer> msoResponse = PostForObject(requestDetails, "", endpoint, RequestReferencesContainer.class); return new MsoResponseWrapper2<>(msoResponse); } - public MsoResponseWrapper replaceInstance(org.onap.vid.changeManagement.RequestDetails request, String path) throws Exception { + public MsoResponseWrapper replaceInstance(org.onap.vid.changeManagement.RequestDetails request, String path) { String methodName = "replaceInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { @@ -357,17 +362,17 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } @Override - public MsoResponseWrapper updateVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper updateVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String endpoint) { String methodName = "updateVnf"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); RequestDetailsWrapper wrapper = new RequestDetailsWrapper(); wrapper.requestDetails = new MsoRequestDetails(requestDetails); return updateInstance(requestDetails, endpoint); } - public MsoResponseWrapper updateInstance(org.onap.vid.changeManagement.RequestDetails request, String path) throws Exception { + public MsoResponseWrapper updateInstance(org.onap.vid.changeManagement.RequestDetails request, String path) { String methodName = "updateInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Delete, path =[" + path + "]"); @@ -390,7 +395,7 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } - public void setServiceInstanceStatus(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject<String> restObject) throws Exception { + public void setServiceInstanceStatus(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject<String> restObject) { String methodName = "activateServiceInstance"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start "); try { @@ -408,9 +413,9 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } @Override - public MsoResponseWrapper removeRelationshipFromServiceInstance(RequestDetails requestDetails, String endpoint) throws Exception { + public MsoResponseWrapper removeRelationshipFromServiceInstance(RequestDetails requestDetails, String endpoint) { String methodName = "removeRelationshipFromServiceInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Remove relationship from service instance, path =[" + endpoint + "]"); @@ -429,9 +434,9 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } @Override - public MsoResponseWrapper addRelationshipToServiceInstance(RequestDetails requestDetails, String addRelationshipsPath) throws Exception { + public MsoResponseWrapper addRelationshipToServiceInstance(RequestDetails requestDetails, String addRelationshipsPath) { String methodName = "addRelationshipToServiceInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Add relationship to service instance, path =[" + addRelationshipsPath + "]"); @@ -447,5 +452,4 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf throw e; } } - }
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RelatedInstanceWrapper.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RelatedInstanceWrapper.java new file mode 100644 index 00000000..0dd64670 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RelatedInstanceWrapper.java @@ -0,0 +1,5 @@ +package org.onap.vid.mso.rest; + +public class RelatedInstanceWrapper { + public RelatedInstance relatedInstance; +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestDetails.java index 9e744736..df691484 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestDetails.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestDetails.java @@ -20,21 +20,15 @@ package org.onap.vid.mso.rest; -import java.util.HashMap; -import java.util.Map; -import java.util.List; - -import org.onap.vid.domain.mso.*; -import org.onap.vid.domain.mso.SubscriberInfo; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.*; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; +import org.onap.vid.domain.mso.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** @@ -51,6 +45,8 @@ import org.apache.commons.lang.builder.ToStringBuilder; }) public class RequestDetails{ + + /** The cloud configuration. */ @JsonProperty("cloudConfiguration") private CloudConfiguration cloudConfiguration; @@ -60,8 +56,8 @@ public class RequestDetails{ private ModelInfo modelInfo; /** The related model list. */ - @JsonProperty("relatedModelList") - private List<RelatedModel> relatedInstanceList; + @JsonProperty("relatedInstanceList") + private List<RelatedInstanceWrapper> relatedInstanceList; /** The request info. */ @JsonProperty("requestInfo") @@ -124,7 +120,7 @@ public class RequestDetails{ * @return The relatedInstanceList */ @JsonProperty("relatedInstanceList") - public List<RelatedModel> getRelatedInstanceList() { + public List<RelatedInstanceWrapper> getRelatedInstanceList() { return relatedInstanceList; } @@ -134,7 +130,7 @@ public class RequestDetails{ * @param relatedInstanceList The relatedInstanceList */ @JsonProperty("relatedInstanceList") - public void setRelatedInstanceList( List<RelatedModel> relatedInstanceList) { + public void setRelatedInstanceList(List<RelatedInstanceWrapper> relatedInstanceList) { this.relatedInstanceList = relatedInstanceList; } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestDetailsWrapper.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestDetailsWrapper.java new file mode 100644 index 00000000..0e320a35 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestDetailsWrapper.java @@ -0,0 +1,5 @@ +package org.onap.vid.mso.rest; + +public class RequestDetailsWrapper { + public RequestDetails requestDetails; +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RestInterface.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RestInterface.java index 38cd5151..feb3f3c1 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RestInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RestInterface.java @@ -24,7 +24,7 @@ public interface RestInterface { * @param restObject the rest object * @throws Exception the exception */ - <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ) throws Exception; + <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ); /** * Delete. @@ -37,7 +37,7 @@ public interface RestInterface { * @param restObject the rest object * @throws Exception the exception */ - <T> void Delete(T t, Object r, String sourceID, String path, RestObject<T> restObject) throws Exception; + <T> void Delete(T t, Object r, String sourceID, String path, RestObject<T> restObject); /** * Post. @@ -50,7 +50,7 @@ public interface RestInterface { * @param restObject the rest object * @throws Exception the exception */ - <T> void Post(T t, Object r, String sourceID, String path, RestObject<T> restObject) throws Exception; + <T> void Post(T t, Object r, String sourceID, String path, RestObject<T> restObject); /** * Put. @@ -63,6 +63,6 @@ public interface RestInterface { * @param restObject the rest object * @throws Exception the exception */ - <T> void Put(T t, org.onap.vid.changeManagement.RequestDetailsWrapper r, String sourceID, String path, RestObject<T> restObject) throws Exception; + <T> void Put(T t, org.onap.vid.changeManagement.RequestDetailsWrapper r, String sourceID, String path, RestObject<T> restObject); } diff --git a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterface.java b/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterface.java index eb5db7db..e550f026 100644 --- a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterface.java @@ -3,10 +3,11 @@ package org.onap.vid.policy; import org.apache.commons.codec.binary.Base64; import org.eclipse.jetty.util.security.Password; import org.json.simple.JSONObject; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.client.HttpBasicClient; +import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.policy.rest.RequestDetails; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; @@ -23,25 +24,24 @@ public class PolicyRestInterface extends PolicyRestInt implements PolicyRestInte /** The logger. */ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyRestInterface.class); - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - + public static final String APPLICATION_JSON = "application/json"; + /** The client. */ private static Client client = null; - + /** The common headers. */ private MultivaluedHashMap<String, Object> commonHeaders; - public PolicyRestInterface() { super(); } - + + /** The Constant dateFormat. */ + static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + public void initRestClient() { final String methodname = "initRestClient()"; - //final String clientAuth = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENTAUTH_VAL); - //final String authorization = SystemProperties.getProperty(PolicyProperties.POLICY_AUTHORIZATION_VAL); final String mechId = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENT_MECHID_VAL); final String clientPassword = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENT_PASSWORD_VAL); final String username = SystemProperties.getProperty(PolicyProperties.POLICY_USERNAME_VAL); @@ -58,7 +58,7 @@ public class PolicyRestInterface extends PolicyRestInt implements PolicyRestInte byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authorization = new String(authEncBytes); - commonHeaders = new MultivaluedHashMap<String, Object> (); + commonHeaders = new MultivaluedHashMap<> (); commonHeaders.put("ClientAuth", Collections.singletonList((Object) ("Basic " + clientAuth))); commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authorization))); commonHeaders.put("Environment", Collections.singletonList((Object) (environment))); @@ -74,7 +74,7 @@ public class PolicyRestInterface extends PolicyRestInt implements PolicyRestInte } @SuppressWarnings("unchecked") - public <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ) throws Exception { + public <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ) { String methodName = "Get"; logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start"); @@ -89,7 +89,7 @@ public class PolicyRestInterface extends PolicyRestInt implements PolicyRestInte final Response cres = client.target(url) .request() - .accept("application/json") + .accept(APPLICATION_JSON) .headers(commonHeaders) .get(); @@ -102,7 +102,7 @@ public class PolicyRestInterface extends PolicyRestInt implements PolicyRestInte logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " REST api was successfull!"); } else { - throw new Exception(methodName + " with status="+ status + ", url= " + url ); + throw new GenericUncheckedException(methodName + " with status="+ status + ", url= " + url ); } logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status ); @@ -128,13 +128,11 @@ public class PolicyRestInterface extends PolicyRestInt implements PolicyRestInte cres = client.target(url) .request() - .accept("application/json") + .accept(APPLICATION_JSON) .headers(commonHeaders) //.entity(r) .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)).invoke(); - // .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)); - //.delete(Entity.entity(r, MediaType.APPLICATION_JSON)); - + int status = cres.getStatus(); restObject.setStatusCode (status); @@ -171,14 +169,13 @@ public class PolicyRestInterface extends PolicyRestInt implements PolicyRestInte } @SuppressWarnings("unchecked") - public <T> void Post(T t, JSONObject requestDetails, String uuid, String path, RestObject<T> restObject) throws Exception { + public <T> void Post(T t, JSONObject requestDetails, String uuid, String path, RestObject<T> restObject) { String methodName = "Post"; String url=""; System.out.println( "POST policy rest interface"); - // logRequest (requestDetails); try { initRestClient(); @@ -188,7 +185,7 @@ public class PolicyRestInterface extends PolicyRestInt implements PolicyRestInte // Change the content length final Response cres = client.target(url) .request() - .accept("application/json") + .accept(APPLICATION_JSON) .headers(commonHeaders) //.header("content-length", 201) //.header("X-FromAppId", sourceID) diff --git a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterfaceIfc.java b/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterfaceIfc.java index 59b0ad3d..61108fc5 100644 --- a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterfaceIfc.java +++ b/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterfaceIfc.java @@ -20,7 +20,7 @@ public interface PolicyRestInterfaceIfc { * @param restObject the rest object * @throws Exception the exception */ - public <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ) throws Exception; + public <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ); /** * Delete. @@ -33,7 +33,7 @@ public interface PolicyRestInterfaceIfc { * @param restObject the rest object * @throws Exception the exception */ - public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) throws Exception; + public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject); /** * Post. @@ -46,7 +46,7 @@ public interface PolicyRestInterfaceIfc { * @param restObject the rest object * @throws Exception the exception */ - public <T> void Post(T t, JSONObject r, String sourceID, String path, RestObject<T> restObject) throws Exception; + public <T> void Post(T t, JSONObject r, String sourceID, String path, RestObject<T> restObject); /*** * Log request. diff --git a/vid-app-common/src/main/java/org/onap/vid/properties/Features.java b/vid-app-common/src/main/java/org/onap/vid/properties/Features.java new file mode 100644 index 00000000..e08a92ea --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/properties/Features.java @@ -0,0 +1,31 @@ +package org.onap.vid.properties; + +import org.togglz.core.Feature; +import org.togglz.core.context.FeatureContext; + +public enum Features implements Feature { + + /******************************* + * Use /docs/feature-flags.md for details + */ + + FLAG_ASYNC_JOBS, + FLAG_REGION_ID_FROM_REMOTE, + CREATE_INSTANCE_TEST, + EMPTY_DRAWING_BOARD_TEST, + FLAG_ADVANCED_PORTS_FILTER, + FLAG_ADD_MSO_TESTAPI_FIELD, + FLAG_ASYNC_INSTANTIATION, + FLAG_SERVICE_MODEL_CACHE, + FLAG_UNASSIGN_SERVICE, + FLAG_NETWORK_TO_ASYNC_INSTANTIATION, + FLAG_COLLECTION_RESOURCE_SUPPORT, + FLAG_SHOW_ASSIGNMENTS, + FLAG_SHOW_VERIFY_SERVICE, + FLAG_SETTING_DEFAULTS_IN_DRAWING_BOARD; + + public boolean isActive() { + return FeatureContext.getFeatureManager().isActive(this); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/properties/FeaturesTogglingConfiguration.java b/vid-app-common/src/main/java/org/onap/vid/properties/FeaturesTogglingConfiguration.java new file mode 100644 index 00000000..ef28ea40 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/properties/FeaturesTogglingConfiguration.java @@ -0,0 +1,40 @@ +package org.onap.vid.properties; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.context.ApplicationListener; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.togglz.core.manager.FeatureManager; +import org.togglz.core.manager.FeatureManagerBuilder; +import org.togglz.core.repository.file.FileBasedStateRepository; +import org.togglz.spring.listener.TogglzApplicationContextBinderApplicationListener; + +import javax.servlet.ServletContext; +import java.io.File; + +@Configuration +public class FeaturesTogglingConfiguration { + @Bean + public ApplicationListener getApplicationListener() { + return new TogglzApplicationContextBinderApplicationListener(); + } + + @Bean + public FeatureManager featureManager(ServletContext servletContext, Environment environment) { + final String defaultFilename = "features.properties"; + + String filename = environment.getProperty("featureFlags.filename"); + + if (StringUtils.isBlank(filename)) { + filename = defaultFilename; + } + + return new FeatureManagerBuilder() + .featureEnum(Features.class) + .stateRepository(new FileBasedStateRepository( + new File(servletContext.getRealPath("/WEB-INF/conf/" + filename)) + )) + .build(); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/properties/VidProperties.java b/vid-app-common/src/main/java/org/onap/vid/properties/VidProperties.java index 7324fe9e..d670e978 100644 --- a/vid-app-common/src/main/java/org/onap/vid/properties/VidProperties.java +++ b/vid-app-common/src/main/java/org/onap/vid/properties/VidProperties.java @@ -33,7 +33,11 @@ import java.util.Date; public class VidProperties extends SystemProperties { //VID General Properties - + public static final String MSO_DISPLAY_TEST_API_ON_SCREEN="mso.displayTestAPIOnScreen"; + public static final String MSO_DEFAULT_TEST_API="mso.defaultTestAPI"; + public static final String MSO_MAX_OPENED_INSTANTIATION_REQUESTS="mso.maxOpenedInstantiationRequests"; + public static final String MSO_ASYNC_POLLING_INTERVAL_SECONDS="mso.asyncPollingIntervalSeconds"; + /** The Constant VID_TRUSTSTORE_FILENAME. */ public static final String VID_TRUSTSTORE_FILENAME = "vid.truststore.filename"; diff --git a/vid-app-common/src/main/java/org/onap/vid/roles/RoleProvider.java b/vid-app-common/src/main/java/org/onap/vid/roles/RoleProvider.java index 1886f333..45835d45 100644 --- a/vid-app-common/src/main/java/org/onap/vid/roles/RoleProvider.java +++ b/vid-app-common/src/main/java/org/onap/vid/roles/RoleProvider.java @@ -13,7 +13,6 @@ import org.onap.vid.services.AaiService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import java.util.*; @@ -39,7 +38,6 @@ public class RoleProvider { } - @PostConstruct public void init() { LOG.debug(EELFLoggerDelegate.debugLogger, "Role provider => init method started"); AaiResponse<SubscriberList> subscribersResponse = aaiService.getFullSubscriberList(); @@ -54,9 +52,9 @@ public class RoleProvider { List<Role> roleList = new ArrayList<>(); //Disable roles until AAF integration finishes - /*Map roles = UserUtils.getRoles(request); + /*HashMap roles = UserUtils.getRoles(request); for (Object role : roles.keySet()) { - org.onap.portalsdk.core.domain.Role sdkRol = (org.onap.portalsdk.core.domain.Role) roles.get(role); + org.openecomp.portalsdk.core.domain.Role sdkRol = (org.openecomp.portalsdk.core.domain.Role) roles.get(role); LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Role " + sdkRol.getName() + " is being proccessed"); try { diff --git a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerProperties.java b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerProperties.java index 8f0b6b0e..4b45f4b4 100644 --- a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerProperties.java +++ b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerProperties.java @@ -15,5 +15,7 @@ public class SchedulerProperties extends SystemProperties { public static final String SCHEDULER_DELETE_SCHEDULE = "scheduler.delete.schedule"; + public static final String SCHEDULER_BASIC_AUTH = "scheduler.basic.auth"; + } diff --git a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterface.java b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterface.java index 77fc5c2c..abd03f3e 100644 --- a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterface.java @@ -1,43 +1,42 @@ package org.onap.vid.scheduler; -import java.util.Collections; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; - +import com.att.eelf.configuration.EELFLogger; import org.apache.commons.codec.binary.Base64; import org.eclipse.jetty.util.security.Password; -import org.json.simple.JSONObject; +import org.onap.vid.aai.util.HttpClientMode; +import org.onap.vid.aai.util.HttpsAuthClient; +import org.onap.vid.client.HttpBasicClient; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.utils.Logging; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.client.HttpBasicClient; -import org.onap.vid.client.HttpsBasicClient; -import org.onap.vid.scheduler.SchedulerProperties; -import org.onap.vid.scheduler.RestObjects.RestObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; -import static org.onap.vid.utils.Logging.getHttpServletRequest; -import static org.onap.vid.utils.Logging.requestIdHeaderKey; +import javax.ws.rs.client.Client; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.Response; +import java.util.Collections; + +import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; @Service public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { - private static Client client = null; - + private Client client = null; + + @Autowired + HttpsAuthClient httpsAuthClient; + private MultivaluedHashMap<String, Object> commonHeaders; /** The logger. */ - static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); - - public SchedulerRestInterface() { - super(); - } + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); + final private static EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("scheduler"); - public void initRestClient() - { - System.out.println( "\t <== Starting to initialize rest client "); + public void initRestClient() { + logger.info("Starting to initialize rest client "); final String username; final String password; @@ -68,42 +67,36 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { String authStringEnc = new String(authEncBytes); commonHeaders = new MultivaluedHashMap<String, Object> (); - commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authStringEnc))); + commonHeaders.put("Authorization", Collections.singletonList("Basic " + authStringEnc)); try { if ( !username.isEmpty() ) { - - client = HttpsBasicClient.getClient(); + client = httpsAuthClient.getClient(HttpClientMode.WITHOUT_KEYSTORE); } else { client = HttpBasicClient.getClient(); } } catch (Exception e) { - System.out.println( " <== Unable to initialize rest client "); + logger.error(" <== Unable to initialize rest client ", e); } - - System.out.println( "\t<== Client Initialized \n"); + + logger.info("\t<== Client Initialized \n"); } - @SuppressWarnings("unchecked") - public <T> void Get (T t, String sourceId, String path, org.onap.vid.scheduler.RestObject<T> restObject ) throws Exception { + public <T> void Get (T t, String sourceId, String path, org.onap.vid.scheduler.RestObject<T> restObject ) { String methodName = "Get"; String url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; - - - System.out.println( "<== URL FOR GET : " + url + "\n"); - - initRestClient(); - + initRestClient(); + Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); final Response cres = client.target(url) .request() .accept("application/json") .headers(commonHeaders) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) + .header(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()) .get(); - + Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres); int status = cres.getStatus(); restObject.setStatusCode (status); @@ -112,100 +105,33 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { restObject.set(t); } else { - throw new Exception(methodName + " with status="+ status + ", url= " + url ); + throw new GenericUncheckedException(methodName + " with status="+ status + ", url= " + url ); } - return; } - - @SuppressWarnings("unchecked") - public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) throws Exception { - - String methodName = "Post"; - String url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; - - System.out.println( "<== URL FOR POST : " + url + "\n"); - - try { - - initRestClient(); - - // Change the content length - final Response cres = client.target(url) - .request() - .accept("application/json") - .headers(commonHeaders) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); - - try { - t = (T) cres.readEntity(t.getClass()); - restObject.set(t); - } - catch ( Exception e ) { - - System.out.println("<== " + methodName + " : No response entity, this is probably ok, e=" + e.getMessage()); - } - - int status = cres.getStatus(); - restObject.setStatusCode (status); - - if ( status >= 200 && status <= 299 ) { - - System.out.println( "<== " + methodName + " : REST api POST was successful!" + "\n"); - - } else { - System.out.println( "<== " + methodName + " : FAILED with http status : "+status+", url = " + url + "\n"); - } - - } catch (Exception e) - { - System.out.println( "<== " + methodName + " : with url="+url+ ", Exception: " + e.toString() + "\n"); - throw e; - } - } - - @Override - public void logRequest(JSONObject requestDetails) {} - - @SuppressWarnings("unchecked") - public <T> void Delete(T t, String sourceID, String path, org.onap.vid.scheduler.RestObject<T> restObject) { - - String url=""; - Response cres = null; - - try { - initRestClient(); - - url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; - - cres = client.target(url) - .request() - .accept("application/json") - .headers(commonHeaders) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - //.entity(r) - .delete(); - // .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)); - //.delete(Entity.entity(r, MediaType.APPLICATION_JSON)); - - int status = cres.getStatus(); - restObject.setStatusCode (status); - - try { - t = (T) cres.readEntity(t.getClass()); - restObject.set(t); - } - catch ( Exception e ) { - } - - } - catch (Exception e) - { - throw e; - } + + public <T> void Delete(T t, String sourceID, String path, org.onap.vid.scheduler.RestObject<T> restObject) { + + initRestClient(); + + String url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; + Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url); + Response cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + .header(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()) + .delete(); + Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres); + + int status = cres.getStatus(); + restObject.setStatusCode(status); + + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + } - + public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException { return clazz.newInstance(); diff --git a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterfaceFactory.java b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterfaceFactory.java deleted file mode 100644 index 1c3bea9f..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterfaceFactory.java +++ /dev/null @@ -1,15 +0,0 @@ - -package org.onap.vid.scheduler; - -public class SchedulerRestInterfaceFactory { - - - public static SchedulerRestInterfaceIfc getInstance () { - SchedulerRestInterfaceIfc obj = null; - - obj = new SchedulerRestInterface(); - - return ( obj ); - } - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterfaceIfc.java b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterfaceIfc.java index 7be8480f..d39e938b 100644 --- a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterfaceIfc.java +++ b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterfaceIfc.java @@ -1,23 +1,18 @@ package org.onap.vid.scheduler; -import org.json.simple.JSONObject; -import org.onap.vid.scheduler.RestObjects.RestObject; import org.springframework.stereotype.Service; @Service public interface SchedulerRestInterfaceIfc { - public void initRestClient(); + void initRestClient(); - public <T> void Get (T t, String sourceId, String path, org.onap.vid.scheduler.RestObject<T> restObject ) throws Exception; + <T> void Get(T t, String sourceId, String path, org.onap.vid.scheduler.RestObject<T> restObject); - public <T> void Delete(T t, String sourceID, String path, org.onap.vid.scheduler.RestObject<T> restObject) + <T> void Delete(T t, String sourceID, String path, org.onap.vid.scheduler.RestObject<T> restObject) throws Exception; - public <T> void Post(T t, JSONObject r, String path, RestObject<T> restObject) throws Exception; - - public void logRequest(JSONObject requestDetails); } 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 diff --git a/vid-app-common/src/main/java/org/onap/vid/utils/DaoUtils.java b/vid-app-common/src/main/java/org/onap/vid/utils/DaoUtils.java new file mode 100644 index 00000000..c8a91626 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/utils/DaoUtils.java @@ -0,0 +1,53 @@ +package org.onap.vid.utils; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.portalsdk.core.FusionObject; + +import java.util.HashMap; +import java.util.function.Function; + +public class DaoUtils { + + //all credit for this wonderful method go to is9613 + public static<T> T tryWithSessionAndTransaction(SessionFactory sessionFactory, Function<Session, T> update) { + // opens a session and transactions, executes the input query. + // gracefully close session and transaction once error occurres. + Session session = null; + Transaction tx = null; + try { + session = sessionFactory.openSession(); + tx = session.beginTransaction(); + + T res = update.apply(session); + + tx.commit(); + + return res; + } catch (RuntimeException e) { + try { + if (tx != null) { + tx.rollback(); + } + } catch (RuntimeException e2) { + // e2 is ingnored; we would like to know the + // original failure reason, not only the reason + // for rollback's failure + throw new GenericUncheckedException("Failed rolling back transaction", e); + } + throw new GenericUncheckedException("Rolled back transaction", e); + } finally { + if (session != null) { + session.close(); + } + } + } + + public static HashMap<String, Object> getPropsMap() { + HashMap<String, Object> props = new HashMap<>(); + props.put(FusionObject.Parameters.PARAM_USERID, 0); + return props; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java b/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java index 61cf0956..e0ee6fbf 100644 --- a/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java +++ b/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java @@ -3,6 +3,10 @@ package org.onap.vid.utils; import com.att.eelf.configuration.EELFLogger; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang3.StringUtils; +import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.http.HttpMethod; @@ -14,7 +18,11 @@ import javax.ws.rs.ProcessingException; import javax.ws.rs.core.Response; import java.util.Arrays; import java.util.Optional; +import java.util.UUID; +import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; +import static org.apache.commons.lang3.exception.ExceptionUtils.getRootCause; +import static org.apache.commons.lang3.exception.ExceptionUtils.getThrowableList; import static org.onap.vid.utils.Streams.not; public class Logging { @@ -24,7 +32,7 @@ public class Logging { public static final String HTTP_REQUESTS_OUTGOING = "http.requests.outgoing."; - public static final String requestIdHeaderKey = SystemProperties.ECOMP_REQUEST_ID; + public static final String REQUEST_ID_HEADER_KEY = SystemProperties.ECOMP_REQUEST_ID; private static ObjectMapper objectMapper = new ObjectMapper(); @@ -101,5 +109,60 @@ public class Logging { return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); } + public static String extractOrGenerateRequestId() { + try { + return getHttpServletRequest().getHeader(REQUEST_ID_HEADER_KEY); + } + catch (IllegalStateException e) { + //in async jobs we don't have any HttpServletRequest + return UUID.randomUUID().toString(); + } + } + + public static void debugRequestDetails(Object requestDetails, final EELFLogger logger) { + if (logger.isDebugEnabled()) { + String requestDetailsAsString; + try { + requestDetailsAsString = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(requestDetails); + } catch (JsonProcessingException e) { + requestDetailsAsString = "error: cannot stringify RequestDetails"; + } + logger.debug("requestDetailsAsString: {}", requestDetailsAsString); + } + } + + public static String exceptionToDescription(Throwable exceptionToDescribe) { + // Ignore top-most GenericUnchecked or Runtime exceptions that has no added message + final Throwable top = getThrowableList(exceptionToDescribe).stream() + .filter(not(e -> ImmutableList.of(GenericUncheckedException.class, RuntimeException.class).contains(e.getClass()) + && StringUtils.equals(e.getMessage(), e.getCause() == null ? null : e.getCause().toString()))) + .findFirst().orElse(exceptionToDescribe); + + final Throwable root = defaultIfNull(getRootCause(top), top); + + String rootToString = root.toString(); + + // nullPointer description will include some context + if (root.getClass().equals(NullPointerException.class) && root.getStackTrace().length > 0) { + rootToString = String.format("NullPointerException at %s:%d", + root.getStackTrace()[0].getFileName(), + root.getStackTrace()[0].getLineNumber()); + } + + // if input is a single exception, without cause: top.toString + // else: return top.toString + root.toString + // but not if root is already described in top.toString + if (top.equals(root)) { + return rootToString; + } else { + final String topToString = top.toString(); + if (topToString.contains(root.getClass().getName()) && topToString.contains(root.getLocalizedMessage())) { + return topToString; + } else { + return topToString + ": " + rootToString; + } + } + } + } diff --git a/vid-app-common/src/main/resources/adiod.zip b/vid-app-common/src/main/resources/adiod.zip Binary files differindex a0fddbed..415fa483 100644 --- a/vid-app-common/src/main/resources/adiod.zip +++ b/vid-app-common/src/main/resources/adiod.zip diff --git a/vid-app-common/src/main/resources/csar317927061915233480.zip b/vid-app-common/src/main/resources/csar317927061915233480.zip Binary files differindex dbf0df17..36ac9f9b 100644 --- a/vid-app-common/src/main/resources/csar317927061915233480.zip +++ b/vid-app-common/src/main/resources/csar317927061915233480.zip diff --git a/vid-app-common/src/main/resources/csar3933948645405128424.zip b/vid-app-common/src/main/resources/csar3933948645405128424.zip Binary files differindex 4601acb7..b92d5339 100644 --- a/vid-app-common/src/main/resources/csar3933948645405128424.zip +++ b/vid-app-common/src/main/resources/csar3933948645405128424.zip diff --git a/vid-app-common/src/main/resources/json/mso/asyncRequestStatus b/vid-app-common/src/main/resources/json/mso/asyncRequestStatus deleted file mode 100755 index 23d2c288..00000000 --- a/vid-app-common/src/main/resources/json/mso/asyncRequestStatus +++ /dev/null @@ -1,54 +0,0 @@ -{
- "$schema": "http://json-schema.org/draft-04/schema#",
- "description": "request structure",
- "properties": {
- "correlator": {
- "description": "Optional correlation Id originally provided with the request in requestInfo",
- "type": "string"
- },
- "finishTime": {
- "description": "Date and time the request was finished in GMT with the following sample format: Wed, 15 Oct 2014 13:01:52 GMT",
- "type": "string"
- },
- "instanceIds": {},
- "requestId": {
- "description": "UUID for the request generated by the instantiation service",
- "pattern": "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$",
- "type": "string"
- },
- "requestScope": {
- "description": "short description of the entity being operated on",
- "enum": [
- "network",
- "service",
- "vfModule",
- "vnf",
- "volumeGroup"
- ],
- "type": "string"
- },
- "requestStatus": {},
- "requestType": {
- "description": "short description of the action being performed on the requestScope",
- "enum": [
- "createInstance",
- "deleteInstance",
- "replaceInstance",
- "updateInstance"
- ],
- "type": "string"
- },
- "startTime": {
- "description": "Date and time the request was created in GMT with the following sample format: Wed, 15 Oct 2014 13:01:52 GMT",
- "type": "string"
- }
- },
- "required": [
- "requestId",
- "requestScope",
- "requestStatus",
- "requestType",
- "startTime"
- ],
- "type": "object"
-}
diff --git a/vid-app-common/src/main/resources/json/mso/modelInfo b/vid-app-common/src/main/resources/json/mso/modelInfo index d368e353..56d268ce 100755 --- a/vid-app-common/src/main/resources/json/mso/modelInfo +++ b/vid-app-common/src/main/resources/json/mso/modelInfo @@ -31,16 +31,7 @@ },
"modelType": {
"description": "short description of the entity being operated on",
- "type": "string",
- "enum": [
- "pnf",
- "network",
- "service",
- "vfModule",
- "vnf",
- "volumeGroup",
- "configuration"
- ]
+ "type": "string"
},
"modelVersion": {
"description": "the version of the model as defined in SDC--not authoritative",
diff --git a/vid-app-common/src/main/resources/json/mso/request b/vid-app-common/src/main/resources/json/mso/request index 95720bf9..61f10400 100755 --- a/vid-app-common/src/main/resources/json/mso/request +++ b/vid-app-common/src/main/resources/json/mso/request @@ -16,31 +16,12 @@ },
"requestScope": {
"description": "short description of the entity being operated on",
- "type": "string",
- "enum": [
- "network",
- "service",
- "vfModule",
- "vnf",
- "volumeGroup",
- "unknown",
- "configuration"
- ]
+ "type": "string"
},
"requestStatus": {},
"requestType": {
"description": "short description of the action being performed on the requestScope",
- "type": "string",
- "enum": [
- "createInstance",
- "deleteInstance",
- "replaceInstance",
- "updateInstance",
- "activateInstance",
- "deactivateInstance",
- "unknown",
- "not provided"
- ]
+ "type": "string"
},
"startTime": {
"description": "Date and time the request was created in GMT with the following sample format: Wed, 15 Oct 2014 13:01:52 GMT",
diff --git a/vid-app-common/src/main/resources/sdcservices.json b/vid-app-common/src/main/resources/sdcservices.json index 1d936f63..1d9d160e 100644 --- a/vid-app-common/src/main/resources/sdcservices.json +++ b/vid-app-common/src/main/resources/sdcservices.json @@ -1,6 +1,48 @@ { "services": [ { + "uuid": "6bce7302-70bd-4057-b48e-8d5b99e686ca", + "invariantUUID": "9aa04749-c02c-432d-a90c-18caa361c833", + "name": "vDBE_srv", + "version": "1.0", + "toscaModelURL": "./service-VdbeSrv-csar.zip", + "category": "Mobility", + "lifecycleState": "CERTIFIED", + "lastUpdaterUserId": "rg276b", + "lastUpdaterFullName": null, + "distributionStatus": "DISTRIBUTED", + "artifacts": null, + "resources": null + }, + { + "uuid": "76f27dfe-33e5-472f-8e0b-acf524adc4f0", + "invariantUUID": "c3618e16-bb5b-433a-a6e0-565ca79d8b65", + "name": "4-27_vMME_Service", + "version": "1.0", + "toscaModelURL": "./service-MsoExampleService-csar.zip", + "category": "Mobility", + "lifecycleState": "CERTIFIED", + "lastUpdaterUserId": "rg276b", + "lastUpdaterFullName": null, + "distributionStatus": "DISTRIBUTED", + "artifacts": null, + "resources": null + }, + { + "uuid": "f4d84bb4-a416-4b4e-997e-0059973630b9", + "invariantUUID": "598e3f9e-3244-4d8f-a8e0-0e5d7a29eda9", + "name": "ADIOD vMX vPE_BV Service 488", + "version": "1.0", + "toscaModelURL": "./service-vf-with-annotations.zip", + "category": "Mobility", + "lifecycleState": "CERTIFIED", + "lastUpdaterUserId": "rg276b", + "lastUpdaterFullName": null, + "distributionStatus": "DISTRIBUTED", + "artifacts": null, + "resources": null + }, + { "uuid": "48a52540-8772-4368-9cdb-1f124ea5c931", "invariantUUID": "f430728a-4530-42be-a577-1206b9484cef", "name": "4-27_vMME_Service", @@ -103,7 +145,7 @@ "invariantUUID": "b7d923c9-6175-41f1-91ba-4565c4953408", "name": "Multiple pProbes", "version": "1.0", - "toscaModelURL": "./service-Servicecontainermultiplepprobes-csar.csar", + "toscaModelURL": "./service-Servicecontainermultiplepprobes-csar.zip", "category": "Mobility", "lifecycleState": "CERTIFIED", "lastUpdaterUserId": "rg276b", @@ -111,6 +153,20 @@ "distributionStatus": "DISTRIBUTED", "artifacts": null, "resources": null + }, + { + "uuid": "ee6d61be-4841-4f98-8f23-5de9da845544", + "invariantUUID": "b7d923c9-6175-41f1-91ba-4565c4955555", + "name": "ServiceContainerMultiplepProbes2", + "version": "2.0", + "toscaModelURL": "./service-ServicecontainerContainsPprobe.zip", + "category": "Network L1-3", + "lifecycleState": "CERTIFIED", + "lastUpdaterUserId": "rg276b", + "lastUpdaterFullName": null, + "distributionStatus": "DISTRIBUTED", + "artifacts": null, + "resources": null } ] }
\ No newline at end of file diff --git a/vid-app-common/src/main/resources/service-AmpPhSvc-csar.zip b/vid-app-common/src/main/resources/service-AmpPhSvc-csar.zip Binary files differindex 5b50f4d3..6d5002c6 100644 --- a/vid-app-common/src/main/resources/service-AmpPhSvc-csar.zip +++ b/vid-app-common/src/main/resources/service-AmpPhSvc-csar.zip diff --git a/vid-app-common/src/main/resources/service-MsoExampleService-csar.zip b/vid-app-common/src/main/resources/service-MsoExampleService-csar.zip Binary files differnew file mode 100644 index 00000000..83131de5 --- /dev/null +++ b/vid-app-common/src/main/resources/service-MsoExampleService-csar.zip diff --git a/vid-app-common/src/main/resources/service-ServicecontainerContainsPprobe.zip b/vid-app-common/src/main/resources/service-ServicecontainerContainsPprobe.zip Binary files differnew file mode 100644 index 00000000..fc74ba06 --- /dev/null +++ b/vid-app-common/src/main/resources/service-ServicecontainerContainsPprobe.zip diff --git a/vid-app-common/src/main/resources/service-Servicecontainermultiplepprobes-csar.csar b/vid-app-common/src/main/resources/service-Servicecontainermultiplepprobes-csar.zip Binary files differindex 81691fe1..e0a53310 100644 --- a/vid-app-common/src/main/resources/service-Servicecontainermultiplepprobes-csar.csar +++ b/vid-app-common/src/main/resources/service-Servicecontainermultiplepprobes-csar.zip diff --git a/vid-app-common/src/main/resources/service-VdbeSrv-csar.zip b/vid-app-common/src/main/resources/service-VdbeSrv-csar.zip Binary files differnew file mode 100644 index 00000000..3defd1e9 --- /dev/null +++ b/vid-app-common/src/main/resources/service-VdbeSrv-csar.zip diff --git a/vid-app-common/src/main/resources/service-vf-csar.zip b/vid-app-common/src/main/resources/service-vf-csar.zip Binary files differindex 090c8efb..f66d0846 100644 --- a/vid-app-common/src/main/resources/service-vf-csar.zip +++ b/vid-app-common/src/main/resources/service-vf-csar.zip diff --git a/vid-app-common/src/main/resources/service-vf-with-annotations.zip b/vid-app-common/src/main/resources/service-vf-with-annotations.zip Binary files differnew file mode 100644 index 00000000..a742d60c --- /dev/null +++ b/vid-app-common/src/main/resources/service-vf-with-annotations.zip diff --git a/vid-app-common/src/main/webapp/app/vid/external/angular-feature-flags/featureFlags.min.js b/vid-app-common/src/main/webapp/app/vid/external/angular-feature-flags/featureFlags.min.js new file mode 100644 index 00000000..9b113d4a --- /dev/null +++ b/vid-app-common/src/main/webapp/app/vid/external/angular-feature-flags/featureFlags.min.js @@ -0,0 +1,2 @@ +/*! Angular Feature Flags v1.6.1 © 2017 Michael Taranto */ +!function(){function e(e,a,t){var r={},n=[],i=function(a){var t=e.defer();return t.resolve(a),t.promise},l=function(e){return a.isPresent(e)},f=function(e){return l(e)?"true"===a.get(e):r[e]},u=function(e){return r[e]},s=function(e){return e.forEach(function(e){r[e.key]=e.active,e.active=f(e.key)}),angular.copy(e,n),n},c=function(e){return e.then(function(e){return s(e.data||e)})},g=function(){return n},o=function(e){return angular.isArray(e)?i(s(e)):c(e)},d=function(e){e.active=!0,a.set(e.key,!0)},v=function(e){e.active=!1,a.set(e.key,!1)},y=function(e){e.active=r[e.key],a.remove(e.key)},m=function(){t&&o(t)};return m(),{set:o,get:g,enable:d,disable:v,reset:y,isOn:f,isOnByDefault:u,isOverridden:l}}angular.module("feature-flags",[]),angular.module("feature-flags").directive("featureFlag",["featureFlags","$interpolate",function(e,a){return{transclude:"element",priority:599,terminal:!0,restrict:"A",$$tlb:!0,compile:function(t,r){var n="featureFlagHide"in r;return t[0].textContent=" featureFlag: "+r.featureFlag+" is "+(n?"on":"off")+" ",function(t,r,i,l,f){var u,s;t.$watch(function(){var r=a(i.featureFlag)(t);return e.isOn(r)},function(e){var a=n?!e:e;a?(s=t.$new(),f(s,function(e){u=e,r.after(u).remove()})):(s&&(s.$destroy(),s=null),u&&(u.after(r).remove(),u=null))})}}}}]),angular.module("feature-flags").directive("featureFlagOverrides",["featureFlags",function(e){return{restrict:"A",link:function(a){a.flags=e.get(),a.isOn=e.isOn,a.isOverridden=e.isOverridden,a.enable=e.enable,a.disable=e.disable,a.reset=e.reset,a.isOnByDefault=e.isOnByDefault},template:'<div class="feature-flags"> <h1>Feature Flags</h1> <div id="feature-flag--{{flag.key}}" class="feature-flags-flag" ng-repeat="flag in flags"> <div class="feature-flags-name">{{flag.name || flag.key}}</div> <div id="feature-flag--{{flag.key}}--enable" class="feature-flags-switch" ng-click="enable(flag)" ng-class="{\'active\': isOverridden(flag.key) && isOn(flag.key)}">ON</div> <div id="feature-flag--{{flag.key}}--disable" class="feature-flags-switch" ng-click="disable(flag)" ng-class="{\'active\': isOverridden(flag.key) && !isOn(flag.key)}">OFF</div> <div id="feature-flag--{{flag.key}}--reset" class="feature-flags-switch" ng-click="reset(flag)" ng-class="{\'active\': !isOverridden(flag.key)}">DEFAULT ({{isOnByDefault(flag.key) ? \'ON\' : \'OFF\'}})</div> <div class="feature-flags-desc">{{flag.description}}</div> </div></div>',replace:!0}}]),angular.module("feature-flags").service("featureFlagOverrides",["$rootElement",function(e){var a=e.attr("ng-app"),t="featureFlags."+a+".",r=function(){try{return localStorage.setItem("featureFlags.availableTest","test"),localStorage.removeItem("featureFlags.availableTest"),!0}catch(e){return!1}}(),n=function(e){return t+e},i=function(e){return 0===e.indexOf(t)},l=function(e,a){r&&localStorage.setItem(n(a),e)},f=function(e){return r?localStorage.getItem(n(e)):void 0},u=function(e){r&&localStorage.removeItem(n(e))};return{isPresent:function(e){var a=f(e);return"undefined"!=typeof a&&null!==a},get:f,set:function(e,a){angular.isObject(e)?angular.forEach(e,l):l(a,e)},remove:u,reset:function(){var e;if(r)for(e in localStorage)i(e)&&localStorage.removeItem(e)}}}]),angular.module("feature-flags").provider("featureFlags",function(){var a=[];this.setInitialFlags=function(e){a=e},this.$get=["$q","featureFlagOverrides",function(t,r){return new e(t,r,a)}]})}();
\ No newline at end of file diff --git a/vid-app-common/src/main/webapp/app/vid/external/angular-moment/angular-moment.min.js b/vid-app-common/src/main/webapp/app/vid/external/angular-moment/angular-moment.min.js new file mode 100644 index 00000000..e800ee7b --- /dev/null +++ b/vid-app-common/src/main/webapp/app/vid/external/angular-moment/angular-moment.min.js @@ -0,0 +1,2 @@ +"format amd";!function(){"use strict";function a(a){return angular.isUndefined(a)||null===a}function b(){try{return require("moment")}catch(a){throw new Error("Please install moment via npm. Please reference to: https://github.com/urish/angular-moment")}}function c(c,d){if("undefined"==typeof d){if("function"!=typeof require)throw new Error("Moment cannot be found by angular-moment! Please reference to: https://github.com/urish/angular-moment");d=b()}return c.module("angularMoment",[]).constant("angularMomentConfig",{preprocess:null,timezone:null,format:null,statefulFilters:!0}).constant("moment",d).constant("amTimeAgoConfig",{withoutSuffix:!1,serverTime:null,titleFormat:null,fullDateThreshold:null,fullDateFormat:null,fullDateThresholdUnit:"day"}).directive("amTimeAgo",["$window","moment","amMoment","amTimeAgoConfig",function(b,d,e,f){return function(g,h,i){function j(){var a;if(p)a=p;else if(f.serverTime){var b=(new Date).getTime(),c=b-w+f.serverTime;a=d(c)}else a=d();return a}function k(){q&&(b.clearTimeout(q),q=null)}function l(a){var c=j().diff(a,v),d=t&&c>=t;if(d?h.text(a.format(u)):h.text(a.from(j(),r)),s&&z&&h.attr("title",a.format(s)),!d){var e=Math.abs(j().diff(a,"minute")),f=3600;e<1?f=1:e<60?f=30:e<180&&(f=300),q=b.setTimeout(function(){l(a)},1e3*f)}}function m(a){y&&h.attr("datetime",a)}function n(){if(k(),o){var a=e.preprocessDate(o);l(a),m(a.toISOString())}}var o,p,q=null,r=f.withoutSuffix,s=f.titleFormat,t=f.fullDateThreshold,u=f.fullDateFormat,v=f.fullDateThresholdUnit,w=(new Date).getTime(),x=i.amTimeAgo,y="TIME"===h[0].nodeName.toUpperCase(),z=!h.attr("title");g.$watch(x,function(b){return a(b)||""===b?(k(),void(o&&(h.text(""),m(""),o=null))):(o=b,void n())}),c.isDefined(i.amFrom)&&g.$watch(i.amFrom,function(b){p=a(b)||""===b?null:d(b),n()}),c.isDefined(i.amWithoutSuffix)&&g.$watch(i.amWithoutSuffix,function(a){"boolean"==typeof a?(r=a,n()):r=f.withoutSuffix}),i.$observe("amFullDateThreshold",function(a){t=a,n()}),i.$observe("amFullDateFormat",function(a){u=a,n()}),i.$observe("amFullDateThresholdUnit",function(a){v=a,n()}),g.$on("$destroy",function(){k()}),g.$on("amMoment:localeChanged",function(){n()})}}]).service("amMoment",["moment","$rootScope","$log","angularMomentConfig",function(a,b,d,e){var f=null;this.changeLocale=function(d,e){var f=a.locale(d,e);return c.isDefined(d)&&b.$broadcast("amMoment:localeChanged"),f},this.changeTimezone=function(c){a.tz&&a.tz.setDefault?(a.tz.setDefault(c),b.$broadcast("amMoment:timezoneChanged")):d.warn("angular-moment: changeTimezone() works only with moment-timezone.js v0.3.0 or greater."),e.timezone=c,f=c},this.preprocessDate=function(b){return f!==e.timezone&&this.changeTimezone(e.timezone),e.preprocess?e.preprocess(b):a(!isNaN(parseFloat(b))&&isFinite(b)?parseInt(b,10):b)}}]).filter("amParse",["moment",function(a){return function(b,c){return a(b,c)}}]).filter("amFromUnix",["moment",function(a){return function(b){return a.unix(b)}}]).filter("amUtc",["moment",function(a){return function(b){return a.utc(b)}}]).filter("amUtcOffset",["amMoment",function(a){function b(b,c){return a.preprocessDate(b).utcOffset(c)}return b}]).filter("amLocal",["moment",function(a){return function(b){return a.isMoment(b)?b.local():null}}]).filter("amTimezone",["amMoment","angularMomentConfig","$log",function(a,b,c){function d(b,d){var e=a.preprocessDate(b);return d?e.tz?e.tz(d):(c.warn("angular-moment: named timezone specified but moment.tz() is undefined. Did you forget to include moment-timezone.js ?"),e):e}return d}]).filter("amCalendar",["moment","amMoment","angularMomentConfig",function(b,c,d){function e(b,d,e){if(a(b))return"";var f=c.preprocessDate(b);return f.isValid()?f.calendar(d,e):""}return e.$stateful=d.statefulFilters,e}]).filter("amDifference",["moment","amMoment","angularMomentConfig",function(b,c,d){function e(d,e,f,g){if(a(d))return"";var h=c.preprocessDate(d),i=a(e)?b():c.preprocessDate(e);return h.isValid()&&i.isValid()?h.diff(i,f,g):""}return e.$stateful=d.statefulFilters,e}]).filter("amDateFormat",["moment","amMoment","angularMomentConfig",function(b,c,d){function e(b,d){if(a(b))return"";var e=c.preprocessDate(b);return e.isValid()?e.format(d):""}return e.$stateful=d.statefulFilters,e}]).filter("amDurationFormat",["moment","angularMomentConfig",function(b,c){function d(c,d,e){return a(c)?"":b.duration(c,d).humanize(e)}return d.$stateful=c.statefulFilters,d}]).filter("amTimeAgo",["moment","amMoment","angularMomentConfig",function(b,c,d){function e(d,e,f){var g,h;return a(d)?"":(d=c.preprocessDate(d),g=b(d),g.isValid()?(h=b(f),!a(f)&&h.isValid()?g.from(h,e):g.fromNow(e)):"")}return e.$stateful=d.statefulFilters,e}]).filter("amSubtract",["moment","angularMomentConfig",function(b,c){function d(c,d,e){return a(c)?"":b(c).subtract(parseInt(d,10),e)}return d.$stateful=c.statefulFilters,d}]).filter("amAdd",["moment","angularMomentConfig",function(b,c){function d(c,d,e){return a(c)?"":b(c).add(parseInt(d,10),e)}return d.$stateful=c.statefulFilters,d}]).filter("amStartOf",["moment","angularMomentConfig",function(b,c){function d(c,d){return a(c)?"":b(c).startOf(d)}return d.$stateful=c.statefulFilters,d}]).filter("amEndOf",["moment","angularMomentConfig",function(b,c){function d(c,d){return a(c)?"":b(c).endOf(d)}return d.$stateful=c.statefulFilters,d}]),"angularMoment"}var d=window&&window.process&&window.process.type;"function"==typeof define&&define.amd?define(["angular","moment"],c):"undefined"!=typeof module&&module&&module.exports&&"function"==typeof require&&!d?module.exports=c(require("angular"),require("moment")):c(angular,("undefined"!=typeof global?global:window).moment)}(); +//# sourceMappingURL=angular-moment.min.js.map
\ No newline at end of file diff --git a/vid-app-common/src/main/webapp/app/vid/external/angular-moment/moment.min.js b/vid-app-common/src/main/webapp/app/vid/external/angular-moment/moment.min.js new file mode 100644 index 00000000..57427d24 --- /dev/null +++ b/vid-app-common/src/main/webapp/app/vid/external/angular-moment/moment.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.moment=t()}(this,function(){"use strict";var e,i;function c(){return e.apply(null,arguments)}function o(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function u(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function l(e){return void 0===e}function d(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function h(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function f(e,t){var n,s=[];for(n=0;n<e.length;++n)s.push(t(e[n],n));return s}function m(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function _(e,t){for(var n in t)m(t,n)&&(e[n]=t[n]);return m(t,"toString")&&(e.toString=t.toString),m(t,"valueOf")&&(e.valueOf=t.valueOf),e}function y(e,t,n,s){return Ot(e,t,n,s,!0).utc()}function g(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function p(e){if(null==e._isValid){var t=g(e),n=i.call(t.parsedDateParts,function(e){return null!=e}),s=!isNaN(e._d.getTime())&&t.overflow<0&&!t.empty&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n);if(e._strict&&(s=s&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return s;e._isValid=s}return e._isValid}function v(e){var t=y(NaN);return null!=e?_(g(t),e):g(t).userInvalidated=!0,t}i=Array.prototype.some?Array.prototype.some:function(e){for(var t=Object(this),n=t.length>>>0,s=0;s<n;s++)if(s in t&&e.call(this,t[s],s,t))return!0;return!1};var r=c.momentProperties=[];function w(e,t){var n,s,i;if(l(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),l(t._i)||(e._i=t._i),l(t._f)||(e._f=t._f),l(t._l)||(e._l=t._l),l(t._strict)||(e._strict=t._strict),l(t._tzm)||(e._tzm=t._tzm),l(t._isUTC)||(e._isUTC=t._isUTC),l(t._offset)||(e._offset=t._offset),l(t._pf)||(e._pf=g(t)),l(t._locale)||(e._locale=t._locale),0<r.length)for(n=0;n<r.length;n++)l(i=t[s=r[n]])||(e[s]=i);return e}var t=!1;function M(e){w(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===t&&(t=!0,c.updateOffset(this),t=!1)}function S(e){return e instanceof M||null!=e&&null!=e._isAMomentObject}function D(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function k(e){var t=+e,n=0;return 0!==t&&isFinite(t)&&(n=D(t)),n}function a(e,t,n){var s,i=Math.min(e.length,t.length),r=Math.abs(e.length-t.length),a=0;for(s=0;s<i;s++)(n&&e[s]!==t[s]||!n&&k(e[s])!==k(t[s]))&&a++;return a+r}function Y(e){!1===c.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function n(i,r){var a=!0;return _(function(){if(null!=c.deprecationHandler&&c.deprecationHandler(null,i),a){for(var e,t=[],n=0;n<arguments.length;n++){if(e="","object"==typeof arguments[n]){for(var s in e+="\n["+n+"] ",arguments[0])e+=s+": "+arguments[0][s]+", ";e=e.slice(0,-2)}else e=arguments[n];t.push(e)}Y(i+"\nArguments: "+Array.prototype.slice.call(t).join("")+"\n"+(new Error).stack),a=!1}return r.apply(this,arguments)},r)}var s,O={};function T(e,t){null!=c.deprecationHandler&&c.deprecationHandler(e,t),O[e]||(Y(t),O[e]=!0)}function x(e){return e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function b(e,t){var n,s=_({},e);for(n in t)m(t,n)&&(u(e[n])&&u(t[n])?(s[n]={},_(s[n],e[n]),_(s[n],t[n])):null!=t[n]?s[n]=t[n]:delete s[n]);for(n in e)m(e,n)&&!m(t,n)&&u(e[n])&&(s[n]=_({},s[n]));return s}function P(e){null!=e&&this.set(e)}c.suppressDeprecationWarnings=!1,c.deprecationHandler=null,s=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)m(e,t)&&n.push(t);return n};var W={};function H(e,t){var n=e.toLowerCase();W[n]=W[n+"s"]=W[t]=e}function R(e){return"string"==typeof e?W[e]||W[e.toLowerCase()]:void 0}function C(e){var t,n,s={};for(n in e)m(e,n)&&(t=R(n))&&(s[t]=e[n]);return s}var F={};function L(e,t){F[e]=t}function U(e,t,n){var s=""+Math.abs(e),i=t-s.length;return(0<=e?n?"+":"":"-")+Math.pow(10,Math.max(0,i)).toString().substr(1)+s}var N=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,G=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,V={},E={};function I(e,t,n,s){var i=s;"string"==typeof s&&(i=function(){return this[s]()}),e&&(E[e]=i),t&&(E[t[0]]=function(){return U(i.apply(this,arguments),t[1],t[2])}),n&&(E[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function A(e,t){return e.isValid()?(t=j(t,e.localeData()),V[t]=V[t]||function(s){var e,i,t,r=s.match(N);for(e=0,i=r.length;e<i;e++)E[r[e]]?r[e]=E[r[e]]:r[e]=(t=r[e]).match(/\[[\s\S]/)?t.replace(/^\[|\]$/g,""):t.replace(/\\/g,"");return function(e){var t,n="";for(t=0;t<i;t++)n+=x(r[t])?r[t].call(e,s):r[t];return n}}(t),V[t](e)):e.localeData().invalidDate()}function j(e,t){var n=5;function s(e){return t.longDateFormat(e)||e}for(G.lastIndex=0;0<=n&&G.test(e);)e=e.replace(G,s),G.lastIndex=0,n-=1;return e}var Z=/\d/,z=/\d\d/,$=/\d{3}/,q=/\d{4}/,J=/[+-]?\d{6}/,B=/\d\d?/,Q=/\d\d\d\d?/,X=/\d\d\d\d\d\d?/,K=/\d{1,3}/,ee=/\d{1,4}/,te=/[+-]?\d{1,6}/,ne=/\d+/,se=/[+-]?\d+/,ie=/Z|[+-]\d\d:?\d\d/gi,re=/Z|[+-]\d\d(?::?\d\d)?/gi,ae=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,oe={};function ue(e,n,s){oe[e]=x(n)?n:function(e,t){return e&&s?s:n}}function le(e,t){return m(oe,e)?oe[e](t._strict,t._locale):new RegExp(de(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,s,i){return t||n||s||i})))}function de(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var he={};function ce(e,n){var t,s=n;for("string"==typeof e&&(e=[e]),d(n)&&(s=function(e,t){t[n]=k(e)}),t=0;t<e.length;t++)he[e[t]]=s}function fe(e,i){ce(e,function(e,t,n,s){n._w=n._w||{},i(e,n._w,n,s)})}var me=0,_e=1,ye=2,ge=3,pe=4,ve=5,we=6,Me=7,Se=8;function De(e){return ke(e)?366:365}function ke(e){return e%4==0&&e%100!=0||e%400==0}I("Y",0,0,function(){var e=this.year();return e<=9999?""+e:"+"+e}),I(0,["YY",2],0,function(){return this.year()%100}),I(0,["YYYY",4],0,"year"),I(0,["YYYYY",5],0,"year"),I(0,["YYYYYY",6,!0],0,"year"),H("year","y"),L("year",1),ue("Y",se),ue("YY",B,z),ue("YYYY",ee,q),ue("YYYYY",te,J),ue("YYYYYY",te,J),ce(["YYYYY","YYYYYY"],me),ce("YYYY",function(e,t){t[me]=2===e.length?c.parseTwoDigitYear(e):k(e)}),ce("YY",function(e,t){t[me]=c.parseTwoDigitYear(e)}),ce("Y",function(e,t){t[me]=parseInt(e,10)}),c.parseTwoDigitYear=function(e){return k(e)+(68<k(e)?1900:2e3)};var Ye,Oe=Te("FullYear",!0);function Te(t,n){return function(e){return null!=e?(be(this,t,e),c.updateOffset(this,n),this):xe(this,t)}}function xe(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function be(e,t,n){e.isValid()&&!isNaN(n)&&("FullYear"===t&&ke(e.year())&&1===e.month()&&29===e.date()?e._d["set"+(e._isUTC?"UTC":"")+t](n,e.month(),Pe(n,e.month())):e._d["set"+(e._isUTC?"UTC":"")+t](n))}function Pe(e,t){if(isNaN(e)||isNaN(t))return NaN;var n,s=(t%(n=12)+n)%n;return e+=(t-s)/12,1===s?ke(e)?29:28:31-s%7%2}Ye=Array.prototype.indexOf?Array.prototype.indexOf:function(e){var t;for(t=0;t<this.length;++t)if(this[t]===e)return t;return-1},I("M",["MM",2],"Mo",function(){return this.month()+1}),I("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),I("MMMM",0,0,function(e){return this.localeData().months(this,e)}),H("month","M"),L("month",8),ue("M",B),ue("MM",B,z),ue("MMM",function(e,t){return t.monthsShortRegex(e)}),ue("MMMM",function(e,t){return t.monthsRegex(e)}),ce(["M","MM"],function(e,t){t[_e]=k(e)-1}),ce(["MMM","MMMM"],function(e,t,n,s){var i=n._locale.monthsParse(e,s,n._strict);null!=i?t[_e]=i:g(n).invalidMonth=e});var We=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,He="January_February_March_April_May_June_July_August_September_October_November_December".split("_");var Re="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_");function Ce(e,t){var n;if(!e.isValid())return e;if("string"==typeof t)if(/^\d+$/.test(t))t=k(t);else if(!d(t=e.localeData().monthsParse(t)))return e;return n=Math.min(e.date(),Pe(e.year(),t)),e._d["set"+(e._isUTC?"UTC":"")+"Month"](t,n),e}function Fe(e){return null!=e?(Ce(this,e),c.updateOffset(this,!0),this):xe(this,"Month")}var Le=ae;var Ue=ae;function Ne(){function e(e,t){return t.length-e.length}var t,n,s=[],i=[],r=[];for(t=0;t<12;t++)n=y([2e3,t]),s.push(this.monthsShort(n,"")),i.push(this.months(n,"")),r.push(this.months(n,"")),r.push(this.monthsShort(n,""));for(s.sort(e),i.sort(e),r.sort(e),t=0;t<12;t++)s[t]=de(s[t]),i[t]=de(i[t]);for(t=0;t<24;t++)r[t]=de(r[t]);this._monthsRegex=new RegExp("^("+r.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+s.join("|")+")","i")}function Ge(e){var t=new Date(Date.UTC.apply(null,arguments));return e<100&&0<=e&&isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e),t}function Ve(e,t,n){var s=7+t-n;return-((7+Ge(e,0,s).getUTCDay()-t)%7)+s-1}function Ee(e,t,n,s,i){var r,a,o=1+7*(t-1)+(7+n-s)%7+Ve(e,s,i);return o<=0?a=De(r=e-1)+o:o>De(e)?(r=e+1,a=o-De(e)):(r=e,a=o),{year:r,dayOfYear:a}}function Ie(e,t,n){var s,i,r=Ve(e.year(),t,n),a=Math.floor((e.dayOfYear()-r-1)/7)+1;return a<1?s=a+Ae(i=e.year()-1,t,n):a>Ae(e.year(),t,n)?(s=a-Ae(e.year(),t,n),i=e.year()+1):(i=e.year(),s=a),{week:s,year:i}}function Ae(e,t,n){var s=Ve(e,t,n),i=Ve(e+1,t,n);return(De(e)-s+i)/7}I("w",["ww",2],"wo","week"),I("W",["WW",2],"Wo","isoWeek"),H("week","w"),H("isoWeek","W"),L("week",5),L("isoWeek",5),ue("w",B),ue("ww",B,z),ue("W",B),ue("WW",B,z),fe(["w","ww","W","WW"],function(e,t,n,s){t[s.substr(0,1)]=k(e)});I("d",0,"do","day"),I("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),I("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),I("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),I("e",0,0,"weekday"),I("E",0,0,"isoWeekday"),H("day","d"),H("weekday","e"),H("isoWeekday","E"),L("day",11),L("weekday",11),L("isoWeekday",11),ue("d",B),ue("e",B),ue("E",B),ue("dd",function(e,t){return t.weekdaysMinRegex(e)}),ue("ddd",function(e,t){return t.weekdaysShortRegex(e)}),ue("dddd",function(e,t){return t.weekdaysRegex(e)}),fe(["dd","ddd","dddd"],function(e,t,n,s){var i=n._locale.weekdaysParse(e,s,n._strict);null!=i?t.d=i:g(n).invalidWeekday=e}),fe(["d","e","E"],function(e,t,n,s){t[s]=k(e)});var je="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_");var Ze="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_");var ze="Su_Mo_Tu_We_Th_Fr_Sa".split("_");var $e=ae;var qe=ae;var Je=ae;function Be(){function e(e,t){return t.length-e.length}var t,n,s,i,r,a=[],o=[],u=[],l=[];for(t=0;t<7;t++)n=y([2e3,1]).day(t),s=this.weekdaysMin(n,""),i=this.weekdaysShort(n,""),r=this.weekdays(n,""),a.push(s),o.push(i),u.push(r),l.push(s),l.push(i),l.push(r);for(a.sort(e),o.sort(e),u.sort(e),l.sort(e),t=0;t<7;t++)o[t]=de(o[t]),u[t]=de(u[t]),l[t]=de(l[t]);this._weekdaysRegex=new RegExp("^("+l.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+u.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+o.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+a.join("|")+")","i")}function Qe(){return this.hours()%12||12}function Xe(e,t){I(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function Ke(e,t){return t._meridiemParse}I("H",["HH",2],0,"hour"),I("h",["hh",2],0,Qe),I("k",["kk",2],0,function(){return this.hours()||24}),I("hmm",0,0,function(){return""+Qe.apply(this)+U(this.minutes(),2)}),I("hmmss",0,0,function(){return""+Qe.apply(this)+U(this.minutes(),2)+U(this.seconds(),2)}),I("Hmm",0,0,function(){return""+this.hours()+U(this.minutes(),2)}),I("Hmmss",0,0,function(){return""+this.hours()+U(this.minutes(),2)+U(this.seconds(),2)}),Xe("a",!0),Xe("A",!1),H("hour","h"),L("hour",13),ue("a",Ke),ue("A",Ke),ue("H",B),ue("h",B),ue("k",B),ue("HH",B,z),ue("hh",B,z),ue("kk",B,z),ue("hmm",Q),ue("hmmss",X),ue("Hmm",Q),ue("Hmmss",X),ce(["H","HH"],ge),ce(["k","kk"],function(e,t,n){var s=k(e);t[ge]=24===s?0:s}),ce(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),ce(["h","hh"],function(e,t,n){t[ge]=k(e),g(n).bigHour=!0}),ce("hmm",function(e,t,n){var s=e.length-2;t[ge]=k(e.substr(0,s)),t[pe]=k(e.substr(s)),g(n).bigHour=!0}),ce("hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[ge]=k(e.substr(0,s)),t[pe]=k(e.substr(s,2)),t[ve]=k(e.substr(i)),g(n).bigHour=!0}),ce("Hmm",function(e,t,n){var s=e.length-2;t[ge]=k(e.substr(0,s)),t[pe]=k(e.substr(s))}),ce("Hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[ge]=k(e.substr(0,s)),t[pe]=k(e.substr(s,2)),t[ve]=k(e.substr(i))});var et,tt=Te("Hours",!0),nt={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:He,monthsShort:Re,week:{dow:0,doy:6},weekdays:je,weekdaysMin:ze,weekdaysShort:Ze,meridiemParse:/[ap]\.?m?\.?/i},st={},it={};function rt(e){return e?e.toLowerCase().replace("_","-"):e}function at(e){var t=null;if(!st[e]&&"undefined"!=typeof module&&module&&module.exports)try{t=et._abbr,require("./locale/"+e),ot(t)}catch(e){}return st[e]}function ot(e,t){var n;return e&&((n=l(t)?lt(e):ut(e,t))?et=n:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),et._abbr}function ut(e,t){if(null!==t){var n,s=nt;if(t.abbr=e,null!=st[e])T("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),s=st[e]._config;else if(null!=t.parentLocale)if(null!=st[t.parentLocale])s=st[t.parentLocale]._config;else{if(null==(n=at(t.parentLocale)))return it[t.parentLocale]||(it[t.parentLocale]=[]),it[t.parentLocale].push({name:e,config:t}),null;s=n._config}return st[e]=new P(b(s,t)),it[e]&&it[e].forEach(function(e){ut(e.name,e.config)}),ot(e),st[e]}return delete st[e],null}function lt(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return et;if(!o(e)){if(t=at(e))return t;e=[e]}return function(e){for(var t,n,s,i,r=0;r<e.length;){for(t=(i=rt(e[r]).split("-")).length,n=(n=rt(e[r+1]))?n.split("-"):null;0<t;){if(s=at(i.slice(0,t).join("-")))return s;if(n&&n.length>=t&&a(i,n,!0)>=t-1)break;t--}r++}return et}(e)}function dt(e){var t,n=e._a;return n&&-2===g(e).overflow&&(t=n[_e]<0||11<n[_e]?_e:n[ye]<1||n[ye]>Pe(n[me],n[_e])?ye:n[ge]<0||24<n[ge]||24===n[ge]&&(0!==n[pe]||0!==n[ve]||0!==n[we])?ge:n[pe]<0||59<n[pe]?pe:n[ve]<0||59<n[ve]?ve:n[we]<0||999<n[we]?we:-1,g(e)._overflowDayOfYear&&(t<me||ye<t)&&(t=ye),g(e)._overflowWeeks&&-1===t&&(t=Me),g(e)._overflowWeekday&&-1===t&&(t=Se),g(e).overflow=t),e}function ht(e,t,n){return null!=e?e:null!=t?t:n}function ct(e){var t,n,s,i,r,a=[];if(!e._d){var o,u;for(o=e,u=new Date(c.now()),s=o._useUTC?[u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()]:[u.getFullYear(),u.getMonth(),u.getDate()],e._w&&null==e._a[ye]&&null==e._a[_e]&&function(e){var t,n,s,i,r,a,o,u;if(null!=(t=e._w).GG||null!=t.W||null!=t.E)r=1,a=4,n=ht(t.GG,e._a[me],Ie(Tt(),1,4).year),s=ht(t.W,1),((i=ht(t.E,1))<1||7<i)&&(u=!0);else{r=e._locale._week.dow,a=e._locale._week.doy;var l=Ie(Tt(),r,a);n=ht(t.gg,e._a[me],l.year),s=ht(t.w,l.week),null!=t.d?((i=t.d)<0||6<i)&&(u=!0):null!=t.e?(i=t.e+r,(t.e<0||6<t.e)&&(u=!0)):i=r}s<1||s>Ae(n,r,a)?g(e)._overflowWeeks=!0:null!=u?g(e)._overflowWeekday=!0:(o=Ee(n,s,i,r,a),e._a[me]=o.year,e._dayOfYear=o.dayOfYear)}(e),null!=e._dayOfYear&&(r=ht(e._a[me],s[me]),(e._dayOfYear>De(r)||0===e._dayOfYear)&&(g(e)._overflowDayOfYear=!0),n=Ge(r,0,e._dayOfYear),e._a[_e]=n.getUTCMonth(),e._a[ye]=n.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=a[t]=s[t];for(;t<7;t++)e._a[t]=a[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[ge]&&0===e._a[pe]&&0===e._a[ve]&&0===e._a[we]&&(e._nextDay=!0,e._a[ge]=0),e._d=(e._useUTC?Ge:function(e,t,n,s,i,r,a){var o=new Date(e,t,n,s,i,r,a);return e<100&&0<=e&&isFinite(o.getFullYear())&&o.setFullYear(e),o}).apply(null,a),i=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[ge]=24),e._w&&void 0!==e._w.d&&e._w.d!==i&&(g(e).weekdayMismatch=!0)}}var ft=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,mt=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,_t=/Z|[+-]\d\d(?::?\d\d)?/,yt=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],gt=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],pt=/^\/?Date\((\-?\d+)/i;function vt(e){var t,n,s,i,r,a,o=e._i,u=ft.exec(o)||mt.exec(o);if(u){for(g(e).iso=!0,t=0,n=yt.length;t<n;t++)if(yt[t][1].exec(u[1])){i=yt[t][0],s=!1!==yt[t][2];break}if(null==i)return void(e._isValid=!1);if(u[3]){for(t=0,n=gt.length;t<n;t++)if(gt[t][1].exec(u[3])){r=(u[2]||" ")+gt[t][0];break}if(null==r)return void(e._isValid=!1)}if(!s&&null!=r)return void(e._isValid=!1);if(u[4]){if(!_t.exec(u[4]))return void(e._isValid=!1);a="Z"}e._f=i+(r||"")+(a||""),kt(e)}else e._isValid=!1}var wt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;function Mt(e,t,n,s,i,r){var a=[function(e){var t=parseInt(e,10);{if(t<=49)return 2e3+t;if(t<=999)return 1900+t}return t}(e),Re.indexOf(t),parseInt(n,10),parseInt(s,10),parseInt(i,10)];return r&&a.push(parseInt(r,10)),a}var St={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Dt(e){var t,n,s,i=wt.exec(e._i.replace(/\([^)]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim());if(i){var r=Mt(i[4],i[3],i[2],i[5],i[6],i[7]);if(t=i[1],n=r,s=e,t&&Ze.indexOf(t)!==new Date(n[0],n[1],n[2]).getDay()&&(g(s).weekdayMismatch=!0,!(s._isValid=!1)))return;e._a=r,e._tzm=function(e,t,n){if(e)return St[e];if(t)return 0;var s=parseInt(n,10),i=s%100;return(s-i)/100*60+i}(i[8],i[9],i[10]),e._d=Ge.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),g(e).rfc2822=!0}else e._isValid=!1}function kt(e){if(e._f!==c.ISO_8601)if(e._f!==c.RFC_2822){e._a=[],g(e).empty=!0;var t,n,s,i,r,a,o,u,l=""+e._i,d=l.length,h=0;for(s=j(e._f,e._locale).match(N)||[],t=0;t<s.length;t++)i=s[t],(n=(l.match(le(i,e))||[])[0])&&(0<(r=l.substr(0,l.indexOf(n))).length&&g(e).unusedInput.push(r),l=l.slice(l.indexOf(n)+n.length),h+=n.length),E[i]?(n?g(e).empty=!1:g(e).unusedTokens.push(i),a=i,u=e,null!=(o=n)&&m(he,a)&&he[a](o,u._a,u,a)):e._strict&&!n&&g(e).unusedTokens.push(i);g(e).charsLeftOver=d-h,0<l.length&&g(e).unusedInput.push(l),e._a[ge]<=12&&!0===g(e).bigHour&&0<e._a[ge]&&(g(e).bigHour=void 0),g(e).parsedDateParts=e._a.slice(0),g(e).meridiem=e._meridiem,e._a[ge]=function(e,t,n){var s;if(null==n)return t;return null!=e.meridiemHour?e.meridiemHour(t,n):(null!=e.isPM&&((s=e.isPM(n))&&t<12&&(t+=12),s||12!==t||(t=0)),t)}(e._locale,e._a[ge],e._meridiem),ct(e),dt(e)}else Dt(e);else vt(e)}function Yt(e){var t,n,s,i,r=e._i,a=e._f;return e._locale=e._locale||lt(e._l),null===r||void 0===a&&""===r?v({nullInput:!0}):("string"==typeof r&&(e._i=r=e._locale.preparse(r)),S(r)?new M(dt(r)):(h(r)?e._d=r:o(a)?function(e){var t,n,s,i,r;if(0===e._f.length)return g(e).invalidFormat=!0,e._d=new Date(NaN);for(i=0;i<e._f.length;i++)r=0,t=w({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[i],kt(t),p(t)&&(r+=g(t).charsLeftOver,r+=10*g(t).unusedTokens.length,g(t).score=r,(null==s||r<s)&&(s=r,n=t));_(e,n||t)}(e):a?kt(e):l(n=(t=e)._i)?t._d=new Date(c.now()):h(n)?t._d=new Date(n.valueOf()):"string"==typeof n?(s=t,null===(i=pt.exec(s._i))?(vt(s),!1===s._isValid&&(delete s._isValid,Dt(s),!1===s._isValid&&(delete s._isValid,c.createFromInputFallback(s)))):s._d=new Date(+i[1])):o(n)?(t._a=f(n.slice(0),function(e){return parseInt(e,10)}),ct(t)):u(n)?function(e){if(!e._d){var t=C(e._i);e._a=f([t.year,t.month,t.day||t.date,t.hour,t.minute,t.second,t.millisecond],function(e){return e&&parseInt(e,10)}),ct(e)}}(t):d(n)?t._d=new Date(n):c.createFromInputFallback(t),p(e)||(e._d=null),e))}function Ot(e,t,n,s,i){var r,a={};return!0!==n&&!1!==n||(s=n,n=void 0),(u(e)&&function(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;var t;for(t in e)if(e.hasOwnProperty(t))return!1;return!0}(e)||o(e)&&0===e.length)&&(e=void 0),a._isAMomentObject=!0,a._useUTC=a._isUTC=i,a._l=n,a._i=e,a._f=t,a._strict=s,(r=new M(dt(Yt(a))))._nextDay&&(r.add(1,"d"),r._nextDay=void 0),r}function Tt(e,t,n,s){return Ot(e,t,n,s,!1)}c.createFromInputFallback=n("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),c.ISO_8601=function(){},c.RFC_2822=function(){};var xt=n("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=Tt.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:v()}),bt=n("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=Tt.apply(null,arguments);return this.isValid()&&e.isValid()?this<e?this:e:v()});function Pt(e,t){var n,s;if(1===t.length&&o(t[0])&&(t=t[0]),!t.length)return Tt();for(n=t[0],s=1;s<t.length;++s)t[s].isValid()&&!t[s][e](n)||(n=t[s]);return n}var Wt=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Ht(e){var t=C(e),n=t.year||0,s=t.quarter||0,i=t.month||0,r=t.week||0,a=t.day||0,o=t.hour||0,u=t.minute||0,l=t.second||0,d=t.millisecond||0;this._isValid=function(e){for(var t in e)if(-1===Ye.call(Wt,t)||null!=e[t]&&isNaN(e[t]))return!1;for(var n=!1,s=0;s<Wt.length;++s)if(e[Wt[s]]){if(n)return!1;parseFloat(e[Wt[s]])!==k(e[Wt[s]])&&(n=!0)}return!0}(t),this._milliseconds=+d+1e3*l+6e4*u+1e3*o*60*60,this._days=+a+7*r,this._months=+i+3*s+12*n,this._data={},this._locale=lt(),this._bubble()}function Rt(e){return e instanceof Ht}function Ct(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Ft(e,n){I(e,0,0,function(){var e=this.utcOffset(),t="+";return e<0&&(e=-e,t="-"),t+U(~~(e/60),2)+n+U(~~e%60,2)})}Ft("Z",":"),Ft("ZZ",""),ue("Z",re),ue("ZZ",re),ce(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=Ut(re,e)});var Lt=/([\+\-]|\d\d)/gi;function Ut(e,t){var n=(t||"").match(e);if(null===n)return null;var s=((n[n.length-1]||[])+"").match(Lt)||["-",0,0],i=60*s[1]+k(s[2]);return 0===i?0:"+"===s[0]?i:-i}function Nt(e,t){var n,s;return t._isUTC?(n=t.clone(),s=(S(e)||h(e)?e.valueOf():Tt(e).valueOf())-n.valueOf(),n._d.setTime(n._d.valueOf()+s),c.updateOffset(n,!1),n):Tt(e).local()}function Gt(e){return 15*-Math.round(e._d.getTimezoneOffset()/15)}function Vt(){return!!this.isValid()&&(this._isUTC&&0===this._offset)}c.updateOffset=function(){};var Et=/^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/,It=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function At(e,t){var n,s,i,r=e,a=null;return Rt(e)?r={ms:e._milliseconds,d:e._days,M:e._months}:d(e)?(r={},t?r[t]=e:r.milliseconds=e):(a=Et.exec(e))?(n="-"===a[1]?-1:1,r={y:0,d:k(a[ye])*n,h:k(a[ge])*n,m:k(a[pe])*n,s:k(a[ve])*n,ms:k(Ct(1e3*a[we]))*n}):(a=It.exec(e))?(n="-"===a[1]?-1:(a[1],1),r={y:jt(a[2],n),M:jt(a[3],n),w:jt(a[4],n),d:jt(a[5],n),h:jt(a[6],n),m:jt(a[7],n),s:jt(a[8],n)}):null==r?r={}:"object"==typeof r&&("from"in r||"to"in r)&&(i=function(e,t){var n;if(!e.isValid()||!t.isValid())return{milliseconds:0,months:0};t=Nt(t,e),e.isBefore(t)?n=Zt(e,t):((n=Zt(t,e)).milliseconds=-n.milliseconds,n.months=-n.months);return n}(Tt(r.from),Tt(r.to)),(r={}).ms=i.milliseconds,r.M=i.months),s=new Ht(r),Rt(e)&&m(e,"_locale")&&(s._locale=e._locale),s}function jt(e,t){var n=e&&parseFloat(e.replace(",","."));return(isNaN(n)?0:n)*t}function Zt(e,t){var n={milliseconds:0,months:0};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function zt(s,i){return function(e,t){var n;return null===t||isNaN(+t)||(T(i,"moment()."+i+"(period, number) is deprecated. Please use moment()."+i+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),n=e,e=t,t=n),$t(this,At(e="string"==typeof e?+e:e,t),s),this}}function $t(e,t,n,s){var i=t._milliseconds,r=Ct(t._days),a=Ct(t._months);e.isValid()&&(s=null==s||s,a&&Ce(e,xe(e,"Month")+a*n),r&&be(e,"Date",xe(e,"Date")+r*n),i&&e._d.setTime(e._d.valueOf()+i*n),s&&c.updateOffset(e,r||a))}At.fn=Ht.prototype,At.invalid=function(){return At(NaN)};var qt=zt(1,"add"),Jt=zt(-1,"subtract");function Bt(e,t){var n=12*(t.year()-e.year())+(t.month()-e.month()),s=e.clone().add(n,"months");return-(n+(t-s<0?(t-s)/(s-e.clone().add(n-1,"months")):(t-s)/(e.clone().add(n+1,"months")-s)))||0}function Qt(e){var t;return void 0===e?this._locale._abbr:(null!=(t=lt(e))&&(this._locale=t),this)}c.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",c.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var Xt=n("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});function Kt(){return this._locale}function en(e,t){I(0,[e,e.length],0,t)}function tn(e,t,n,s,i){var r;return null==e?Ie(this,s,i).year:((r=Ae(e,s,i))<t&&(t=r),function(e,t,n,s,i){var r=Ee(e,t,n,s,i),a=Ge(r.year,0,r.dayOfYear);return this.year(a.getUTCFullYear()),this.month(a.getUTCMonth()),this.date(a.getUTCDate()),this}.call(this,e,t,n,s,i))}I(0,["gg",2],0,function(){return this.weekYear()%100}),I(0,["GG",2],0,function(){return this.isoWeekYear()%100}),en("gggg","weekYear"),en("ggggg","weekYear"),en("GGGG","isoWeekYear"),en("GGGGG","isoWeekYear"),H("weekYear","gg"),H("isoWeekYear","GG"),L("weekYear",1),L("isoWeekYear",1),ue("G",se),ue("g",se),ue("GG",B,z),ue("gg",B,z),ue("GGGG",ee,q),ue("gggg",ee,q),ue("GGGGG",te,J),ue("ggggg",te,J),fe(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,s){t[s.substr(0,2)]=k(e)}),fe(["gg","GG"],function(e,t,n,s){t[s]=c.parseTwoDigitYear(e)}),I("Q",0,"Qo","quarter"),H("quarter","Q"),L("quarter",7),ue("Q",Z),ce("Q",function(e,t){t[_e]=3*(k(e)-1)}),I("D",["DD",2],"Do","date"),H("date","D"),L("date",9),ue("D",B),ue("DD",B,z),ue("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),ce(["D","DD"],ye),ce("Do",function(e,t){t[ye]=k(e.match(B)[0])});var nn=Te("Date",!0);I("DDD",["DDDD",3],"DDDo","dayOfYear"),H("dayOfYear","DDD"),L("dayOfYear",4),ue("DDD",K),ue("DDDD",$),ce(["DDD","DDDD"],function(e,t,n){n._dayOfYear=k(e)}),I("m",["mm",2],0,"minute"),H("minute","m"),L("minute",14),ue("m",B),ue("mm",B,z),ce(["m","mm"],pe);var sn=Te("Minutes",!1);I("s",["ss",2],0,"second"),H("second","s"),L("second",15),ue("s",B),ue("ss",B,z),ce(["s","ss"],ve);var rn,an=Te("Seconds",!1);for(I("S",0,0,function(){return~~(this.millisecond()/100)}),I(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),I(0,["SSS",3],0,"millisecond"),I(0,["SSSS",4],0,function(){return 10*this.millisecond()}),I(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),I(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),I(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),I(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),I(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),H("millisecond","ms"),L("millisecond",16),ue("S",K,Z),ue("SS",K,z),ue("SSS",K,$),rn="SSSS";rn.length<=9;rn+="S")ue(rn,ne);function on(e,t){t[we]=k(1e3*("0."+e))}for(rn="S";rn.length<=9;rn+="S")ce(rn,on);var un=Te("Milliseconds",!1);I("z",0,0,"zoneAbbr"),I("zz",0,0,"zoneName");var ln=M.prototype;function dn(e){return e}ln.add=qt,ln.calendar=function(e,t){var n=e||Tt(),s=Nt(n,this).startOf("day"),i=c.calendarFormat(this,s)||"sameElse",r=t&&(x(t[i])?t[i].call(this,n):t[i]);return this.format(r||this.localeData().calendar(i,this,Tt(n)))},ln.clone=function(){return new M(this)},ln.diff=function(e,t,n){var s,i,r;if(!this.isValid())return NaN;if(!(s=Nt(e,this)).isValid())return NaN;switch(i=6e4*(s.utcOffset()-this.utcOffset()),t=R(t)){case"year":r=Bt(this,s)/12;break;case"month":r=Bt(this,s);break;case"quarter":r=Bt(this,s)/3;break;case"second":r=(this-s)/1e3;break;case"minute":r=(this-s)/6e4;break;case"hour":r=(this-s)/36e5;break;case"day":r=(this-s-i)/864e5;break;case"week":r=(this-s-i)/6048e5;break;default:r=this-s}return n?r:D(r)},ln.endOf=function(e){return void 0===(e=R(e))||"millisecond"===e?this:("date"===e&&(e="day"),this.startOf(e).add(1,"isoWeek"===e?"week":e).subtract(1,"ms"))},ln.format=function(e){e||(e=this.isUtc()?c.defaultFormatUtc:c.defaultFormat);var t=A(this,e);return this.localeData().postformat(t)},ln.from=function(e,t){return this.isValid()&&(S(e)&&e.isValid()||Tt(e).isValid())?At({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},ln.fromNow=function(e){return this.from(Tt(),e)},ln.to=function(e,t){return this.isValid()&&(S(e)&&e.isValid()||Tt(e).isValid())?At({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},ln.toNow=function(e){return this.to(Tt(),e)},ln.get=function(e){return x(this[e=R(e)])?this[e]():this},ln.invalidAt=function(){return g(this).overflow},ln.isAfter=function(e,t){var n=S(e)?e:Tt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=R(l(t)?"millisecond":t))?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(t).valueOf())},ln.isBefore=function(e,t){var n=S(e)?e:Tt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=R(l(t)?"millisecond":t))?this.valueOf()<n.valueOf():this.clone().endOf(t).valueOf()<n.valueOf())},ln.isBetween=function(e,t,n,s){return("("===(s=s||"()")[0]?this.isAfter(e,n):!this.isBefore(e,n))&&(")"===s[1]?this.isBefore(t,n):!this.isAfter(t,n))},ln.isSame=function(e,t){var n,s=S(e)?e:Tt(e);return!(!this.isValid()||!s.isValid())&&("millisecond"===(t=R(t||"millisecond"))?this.valueOf()===s.valueOf():(n=s.valueOf(),this.clone().startOf(t).valueOf()<=n&&n<=this.clone().endOf(t).valueOf()))},ln.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},ln.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},ln.isValid=function(){return p(this)},ln.lang=Xt,ln.locale=Qt,ln.localeData=Kt,ln.max=bt,ln.min=xt,ln.parsingFlags=function(){return _({},g(this))},ln.set=function(e,t){if("object"==typeof e)for(var n=function(e){var t=[];for(var n in e)t.push({unit:n,priority:F[n]});return t.sort(function(e,t){return e.priority-t.priority}),t}(e=C(e)),s=0;s<n.length;s++)this[n[s].unit](e[n[s].unit]);else if(x(this[e=R(e)]))return this[e](t);return this},ln.startOf=function(e){switch(e=R(e)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":case"date":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===e&&this.weekday(0),"isoWeek"===e&&this.isoWeekday(1),"quarter"===e&&this.month(3*Math.floor(this.month()/3)),this},ln.subtract=Jt,ln.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},ln.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}},ln.toDate=function(){return new Date(this.valueOf())},ln.toISOString=function(e){if(!this.isValid())return null;var t=!0!==e,n=t?this.clone().utc():this;return n.year()<0||9999<n.year()?A(n,t?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):x(Date.prototype.toISOString)?t?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",A(n,"Z")):A(n,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")},ln.inspect=function(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e="moment",t="";this.isLocal()||(e=0===this.utcOffset()?"moment.utc":"moment.parseZone",t="Z");var n="["+e+'("]',s=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",i=t+'[")]';return this.format(n+s+"-MM-DD[T]HH:mm:ss.SSS"+i)},ln.toJSON=function(){return this.isValid()?this.toISOString():null},ln.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},ln.unix=function(){return Math.floor(this.valueOf()/1e3)},ln.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},ln.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},ln.year=Oe,ln.isLeapYear=function(){return ke(this.year())},ln.weekYear=function(e){return tn.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)},ln.isoWeekYear=function(e){return tn.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},ln.quarter=ln.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},ln.month=Fe,ln.daysInMonth=function(){return Pe(this.year(),this.month())},ln.week=ln.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},ln.isoWeek=ln.isoWeeks=function(e){var t=Ie(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},ln.weeksInYear=function(){var e=this.localeData()._week;return Ae(this.year(),e.dow,e.doy)},ln.isoWeeksInYear=function(){return Ae(this.year(),1,4)},ln.date=nn,ln.day=ln.days=function(e){if(!this.isValid())return null!=e?this:NaN;var t,n,s=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=e?(t=e,n=this.localeData(),e="string"!=typeof t?t:isNaN(t)?"number"==typeof(t=n.weekdaysParse(t))?t:null:parseInt(t,10),this.add(e-s,"d")):s},ln.weekday=function(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")},ln.isoWeekday=function(e){if(!this.isValid())return null!=e?this:NaN;if(null!=e){var t=(n=e,s=this.localeData(),"string"==typeof n?s.weekdaysParse(n)%7||7:isNaN(n)?null:n);return this.day(this.day()%7?t:t-7)}return this.day()||7;var n,s},ln.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},ln.hour=ln.hours=tt,ln.minute=ln.minutes=sn,ln.second=ln.seconds=an,ln.millisecond=ln.milliseconds=un,ln.utcOffset=function(e,t,n){var s,i=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null!=e){if("string"==typeof e){if(null===(e=Ut(re,e)))return this}else Math.abs(e)<16&&!n&&(e*=60);return!this._isUTC&&t&&(s=Gt(this)),this._offset=e,this._isUTC=!0,null!=s&&this.add(s,"m"),i!==e&&(!t||this._changeInProgress?$t(this,At(e-i,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,c.updateOffset(this,!0),this._changeInProgress=null)),this}return this._isUTC?i:Gt(this)},ln.utc=function(e){return this.utcOffset(0,e)},ln.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Gt(this),"m")),this},ln.parseZone=function(){if(null!=this._tzm)this.utcOffset(this._tzm,!1,!0);else if("string"==typeof this._i){var e=Ut(ie,this._i);null!=e?this.utcOffset(e):this.utcOffset(0,!0)}return this},ln.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?Tt(e).utcOffset():0,(this.utcOffset()-e)%60==0)},ln.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},ln.isLocal=function(){return!!this.isValid()&&!this._isUTC},ln.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},ln.isUtc=Vt,ln.isUTC=Vt,ln.zoneAbbr=function(){return this._isUTC?"UTC":""},ln.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},ln.dates=n("dates accessor is deprecated. Use date instead.",nn),ln.months=n("months accessor is deprecated. Use month instead",Fe),ln.years=n("years accessor is deprecated. Use year instead",Oe),ln.zone=n("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()}),ln.isDSTShifted=n("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){if(!l(this._isDSTShifted))return this._isDSTShifted;var e={};if(w(e,this),(e=Yt(e))._a){var t=e._isUTC?y(e._a):Tt(e._a);this._isDSTShifted=this.isValid()&&0<a(e._a,t.toArray())}else this._isDSTShifted=!1;return this._isDSTShifted});var hn=P.prototype;function cn(e,t,n,s){var i=lt(),r=y().set(s,t);return i[n](r,e)}function fn(e,t,n){if(d(e)&&(t=e,e=void 0),e=e||"",null!=t)return cn(e,t,n,"month");var s,i=[];for(s=0;s<12;s++)i[s]=cn(e,s,n,"month");return i}function mn(e,t,n,s){"boolean"==typeof e?d(t)&&(n=t,t=void 0):(t=e,e=!1,d(n=t)&&(n=t,t=void 0)),t=t||"";var i,r=lt(),a=e?r._week.dow:0;if(null!=n)return cn(t,(n+a)%7,s,"day");var o=[];for(i=0;i<7;i++)o[i]=cn(t,(i+a)%7,s,"day");return o}hn.calendar=function(e,t,n){var s=this._calendar[e]||this._calendar.sameElse;return x(s)?s.call(t,n):s},hn.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.replace(/MMMM|MM|DD|dddd/g,function(e){return e.slice(1)}),this._longDateFormat[e])},hn.invalidDate=function(){return this._invalidDate},hn.ordinal=function(e){return this._ordinal.replace("%d",e)},hn.preparse=dn,hn.postformat=dn,hn.relativeTime=function(e,t,n,s){var i=this._relativeTime[n];return x(i)?i(e,t,n,s):i.replace(/%d/i,e)},hn.pastFuture=function(e,t){var n=this._relativeTime[0<e?"future":"past"];return x(n)?n(t):n.replace(/%s/i,t)},hn.set=function(e){var t,n;for(n in e)x(t=e[n])?this[n]=t:this["_"+n]=t;this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},hn.months=function(e,t){return e?o(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||We).test(t)?"format":"standalone"][e.month()]:o(this._months)?this._months:this._months.standalone},hn.monthsShort=function(e,t){return e?o(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[We.test(t)?"format":"standalone"][e.month()]:o(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},hn.monthsParse=function(e,t,n){var s,i,r;if(this._monthsParseExact)return function(e,t,n){var s,i,r,a=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],s=0;s<12;++s)r=y([2e3,s]),this._shortMonthsParse[s]=this.monthsShort(r,"").toLocaleLowerCase(),this._longMonthsParse[s]=this.months(r,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=Ye.call(this._shortMonthsParse,a))?i:null:-1!==(i=Ye.call(this._longMonthsParse,a))?i:null:"MMM"===t?-1!==(i=Ye.call(this._shortMonthsParse,a))?i:-1!==(i=Ye.call(this._longMonthsParse,a))?i:null:-1!==(i=Ye.call(this._longMonthsParse,a))?i:-1!==(i=Ye.call(this._shortMonthsParse,a))?i:null}.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),s=0;s<12;s++){if(i=y([2e3,s]),n&&!this._longMonthsParse[s]&&(this._longMonthsParse[s]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[s]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[s]||(r="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[s]=new RegExp(r.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[s].test(e))return s;if(n&&"MMM"===t&&this._shortMonthsParse[s].test(e))return s;if(!n&&this._monthsParse[s].test(e))return s}},hn.monthsRegex=function(e){return this._monthsParseExact?(m(this,"_monthsRegex")||Ne.call(this),e?this._monthsStrictRegex:this._monthsRegex):(m(this,"_monthsRegex")||(this._monthsRegex=Ue),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},hn.monthsShortRegex=function(e){return this._monthsParseExact?(m(this,"_monthsRegex")||Ne.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(m(this,"_monthsShortRegex")||(this._monthsShortRegex=Le),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},hn.week=function(e){return Ie(e,this._week.dow,this._week.doy).week},hn.firstDayOfYear=function(){return this._week.doy},hn.firstDayOfWeek=function(){return this._week.dow},hn.weekdays=function(e,t){return e?o(this._weekdays)?this._weekdays[e.day()]:this._weekdays[this._weekdays.isFormat.test(t)?"format":"standalone"][e.day()]:o(this._weekdays)?this._weekdays:this._weekdays.standalone},hn.weekdaysMin=function(e){return e?this._weekdaysMin[e.day()]:this._weekdaysMin},hn.weekdaysShort=function(e){return e?this._weekdaysShort[e.day()]:this._weekdaysShort},hn.weekdaysParse=function(e,t,n){var s,i,r;if(this._weekdaysParseExact)return function(e,t,n){var s,i,r,a=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],s=0;s<7;++s)r=y([2e3,1]).day(s),this._minWeekdaysParse[s]=this.weekdaysMin(r,"").toLocaleLowerCase(),this._shortWeekdaysParse[s]=this.weekdaysShort(r,"").toLocaleLowerCase(),this._weekdaysParse[s]=this.weekdays(r,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=Ye.call(this._weekdaysParse,a))?i:null:"ddd"===t?-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:null:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:"dddd"===t?-1!==(i=Ye.call(this._weekdaysParse,a))?i:-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:"ddd"===t?-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:-1!==(i=Ye.call(this._weekdaysParse,a))?i:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:null:-1!==(i=Ye.call(this._minWeekdaysParse,a))?i:-1!==(i=Ye.call(this._weekdaysParse,a))?i:-1!==(i=Ye.call(this._shortWeekdaysParse,a))?i:null}.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),s=0;s<7;s++){if(i=y([2e3,1]).day(s),n&&!this._fullWeekdaysParse[s]&&(this._fullWeekdaysParse[s]=new RegExp("^"+this.weekdays(i,"").replace(".",".?")+"$","i"),this._shortWeekdaysParse[s]=new RegExp("^"+this.weekdaysShort(i,"").replace(".",".?")+"$","i"),this._minWeekdaysParse[s]=new RegExp("^"+this.weekdaysMin(i,"").replace(".",".?")+"$","i")),this._weekdaysParse[s]||(r="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[s]=new RegExp(r.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[s].test(e))return s;if(n&&"ddd"===t&&this._shortWeekdaysParse[s].test(e))return s;if(n&&"dd"===t&&this._minWeekdaysParse[s].test(e))return s;if(!n&&this._weekdaysParse[s].test(e))return s}},hn.weekdaysRegex=function(e){return this._weekdaysParseExact?(m(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(m(this,"_weekdaysRegex")||(this._weekdaysRegex=$e),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},hn.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(m(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(m(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=qe),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},hn.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(m(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(m(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=Je),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},hn.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},hn.meridiem=function(e,t,n){return 11<e?n?"pm":"PM":n?"am":"AM"},ot("en",{dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===k(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th")}}),c.lang=n("moment.lang is deprecated. Use moment.locale instead.",ot),c.langData=n("moment.langData is deprecated. Use moment.localeData instead.",lt);var _n=Math.abs;function yn(e,t,n,s){var i=At(t,n);return e._milliseconds+=s*i._milliseconds,e._days+=s*i._days,e._months+=s*i._months,e._bubble()}function gn(e){return e<0?Math.floor(e):Math.ceil(e)}function pn(e){return 4800*e/146097}function vn(e){return 146097*e/4800}function wn(e){return function(){return this.as(e)}}var Mn=wn("ms"),Sn=wn("s"),Dn=wn("m"),kn=wn("h"),Yn=wn("d"),On=wn("w"),Tn=wn("M"),xn=wn("y");function bn(e){return function(){return this.isValid()?this._data[e]:NaN}}var Pn=bn("milliseconds"),Wn=bn("seconds"),Hn=bn("minutes"),Rn=bn("hours"),Cn=bn("days"),Fn=bn("months"),Ln=bn("years");var Un=Math.round,Nn={ss:44,s:45,m:45,h:22,d:26,M:11};var Gn=Math.abs;function Vn(e){return(0<e)-(e<0)||+e}function En(){if(!this.isValid())return this.localeData().invalidDate();var e,t,n=Gn(this._milliseconds)/1e3,s=Gn(this._days),i=Gn(this._months);t=D((e=D(n/60))/60),n%=60,e%=60;var r=D(i/12),a=i%=12,o=s,u=t,l=e,d=n?n.toFixed(3).replace(/\.?0+$/,""):"",h=this.asSeconds();if(!h)return"P0D";var c=h<0?"-":"",f=Vn(this._months)!==Vn(h)?"-":"",m=Vn(this._days)!==Vn(h)?"-":"",_=Vn(this._milliseconds)!==Vn(h)?"-":"";return c+"P"+(r?f+r+"Y":"")+(a?f+a+"M":"")+(o?m+o+"D":"")+(u||l||d?"T":"")+(u?_+u+"H":"")+(l?_+l+"M":"")+(d?_+d+"S":"")}var In=Ht.prototype;return In.isValid=function(){return this._isValid},In.abs=function(){var e=this._data;return this._milliseconds=_n(this._milliseconds),this._days=_n(this._days),this._months=_n(this._months),e.milliseconds=_n(e.milliseconds),e.seconds=_n(e.seconds),e.minutes=_n(e.minutes),e.hours=_n(e.hours),e.months=_n(e.months),e.years=_n(e.years),this},In.add=function(e,t){return yn(this,e,t,1)},In.subtract=function(e,t){return yn(this,e,t,-1)},In.as=function(e){if(!this.isValid())return NaN;var t,n,s=this._milliseconds;if("month"===(e=R(e))||"year"===e)return t=this._days+s/864e5,n=this._months+pn(t),"month"===e?n:n/12;switch(t=this._days+Math.round(vn(this._months)),e){case"week":return t/7+s/6048e5;case"day":return t+s/864e5;case"hour":return 24*t+s/36e5;case"minute":return 1440*t+s/6e4;case"second":return 86400*t+s/1e3;case"millisecond":return Math.floor(864e5*t)+s;default:throw new Error("Unknown unit "+e)}},In.asMilliseconds=Mn,In.asSeconds=Sn,In.asMinutes=Dn,In.asHours=kn,In.asDays=Yn,In.asWeeks=On,In.asMonths=Tn,In.asYears=xn,In.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*k(this._months/12):NaN},In._bubble=function(){var e,t,n,s,i,r=this._milliseconds,a=this._days,o=this._months,u=this._data;return 0<=r&&0<=a&&0<=o||r<=0&&a<=0&&o<=0||(r+=864e5*gn(vn(o)+a),o=a=0),u.milliseconds=r%1e3,e=D(r/1e3),u.seconds=e%60,t=D(e/60),u.minutes=t%60,n=D(t/60),u.hours=n%24,o+=i=D(pn(a+=D(n/24))),a-=gn(vn(i)),s=D(o/12),o%=12,u.days=a,u.months=o,u.years=s,this},In.clone=function(){return At(this)},In.get=function(e){return e=R(e),this.isValid()?this[e+"s"]():NaN},In.milliseconds=Pn,In.seconds=Wn,In.minutes=Hn,In.hours=Rn,In.days=Cn,In.weeks=function(){return D(this.days()/7)},In.months=Fn,In.years=Ln,In.humanize=function(e){if(!this.isValid())return this.localeData().invalidDate();var t,n,s,i,r,a,o,u,l,d,h,c=this.localeData(),f=(n=!e,s=c,i=At(t=this).abs(),r=Un(i.as("s")),a=Un(i.as("m")),o=Un(i.as("h")),u=Un(i.as("d")),l=Un(i.as("M")),d=Un(i.as("y")),(h=r<=Nn.ss&&["s",r]||r<Nn.s&&["ss",r]||a<=1&&["m"]||a<Nn.m&&["mm",a]||o<=1&&["h"]||o<Nn.h&&["hh",o]||u<=1&&["d"]||u<Nn.d&&["dd",u]||l<=1&&["M"]||l<Nn.M&&["MM",l]||d<=1&&["y"]||["yy",d])[2]=n,h[3]=0<+t,h[4]=s,function(e,t,n,s,i){return i.relativeTime(t||1,!!n,e,s)}.apply(null,h));return e&&(f=c.pastFuture(+this,f)),c.postformat(f)},In.toISOString=En,In.toString=En,In.toJSON=En,In.locale=Qt,In.localeData=Kt,In.toIsoString=n("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",En),In.lang=Xt,I("X",0,0,"unix"),I("x",0,0,"valueOf"),ue("x",se),ue("X",/[+-]?\d+(\.\d{1,3})?/),ce("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e,10))}),ce("x",function(e,t,n){n._d=new Date(k(e))}),c.version="2.22.1",e=Tt,c.fn=ln,c.min=function(){return Pt("isBefore",[].slice.call(arguments,0))},c.max=function(){return Pt("isAfter",[].slice.call(arguments,0))},c.now=function(){return Date.now?Date.now():+new Date},c.utc=y,c.unix=function(e){return Tt(1e3*e)},c.months=function(e,t){return fn(e,t,"months")},c.isDate=h,c.locale=ot,c.invalid=v,c.duration=At,c.isMoment=S,c.weekdays=function(e,t,n){return mn(e,t,n,"weekdays")},c.parseZone=function(){return Tt.apply(null,arguments).parseZone()},c.localeData=lt,c.isDuration=Rt,c.monthsShort=function(e,t){return fn(e,t,"monthsShort")},c.weekdaysMin=function(e,t,n){return mn(e,t,n,"weekdaysMin")},c.defineLocale=ut,c.updateLocale=function(e,t){if(null!=t){var n,s,i=nt;null!=(s=at(e))&&(i=s._config),(n=new P(t=b(i,t))).parentLocale=st[e],st[e]=n,ot(e)}else null!=st[e]&&(null!=st[e].parentLocale?st[e]=st[e].parentLocale:null!=st[e]&&delete st[e]);return st[e]},c.locales=function(){return s(st)},c.weekdaysShort=function(e,t,n){return mn(e,t,n,"weekdaysShort")},c.normalizeUnits=R,c.relativeTimeRounding=function(e){return void 0===e?Un:"function"==typeof e&&(Un=e,!0)},c.relativeTimeThreshold=function(e,t){return void 0!==Nn[e]&&(void 0===t?Nn[e]:(Nn[e]=t,"s"===e&&(Nn.ss=t-1),!0))},c.calendarFormat=function(e,t){var n=e.diff(t,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"},c.prototype=ln,c.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"YYYY-[W]WW",MONTH:"YYYY-MM"},c});
\ No newline at end of file diff --git a/vid-app-common/src/main/webapp/app/vid/styles/common.css b/vid-app-common/src/main/webapp/app/vid/styles/common.css index 35f2e33f..9377c3f6 100644 --- a/vid-app-common/src/main/webapp/app/vid/styles/common.css +++ b/vid-app-common/src/main/webapp/app/vid/styles/common.css @@ -63,6 +63,61 @@ html, body { font-size:14px; } +html { + height: 100%; +} + +body { + display: flex; + flex-direction: column; + min-height: 100%; +} + +.applicationWindow { + height: 100%; + display: flex; + flex-direction: column; + flex: 1; +} + +#mContent { + display: flex; + flex-direction: column; + flex: 1; +} +.content.modal-open .body-content-jsp{ + margin: 0 auto; +} +.content .body-content-jsp > div.ng-scope > div.overlay{ + display: none; +} +.content.modal-open .body-content-jsp .service-models-page .overlay{ + display: block !important; + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: 3004; + background-color: #000; + opacity: 0.5; +} + +.content.modal-open .body-content-jsp .service-models-page .service-model-content{ + z-index: 3005; + margin: 0 auto; + flex: none; + width: 1100px; + padding: 10px; +} +.content.modal-open{ + margin: 0 !important; +} + +.body-content-jsp { + flex: 1; +} + .button--inactive { border: none !important; } @@ -114,3 +169,37 @@ input:focus:invalid { border-color: Tomato; box-shadow: none; } + +iframe { + top: 0; + left: 0; + width: 100%; + height: 100%; + border:0; +} + +iframe.popup{ + width: 1103px; + height: 691px; +} + +/*todo: remove. this a temporary fix for the sub-interface popup not showing as a page beside the sidebar. currently showing it in full screen.*/ +iframe.iframeDialog { + width: 100vw; + height: 100vh; + position: fixed; +} + +.service-models-page { + flex: 1; + display: flex; + min-height: 700px; +} + +.service-model-content { + flex: 1; +} + +.service-model-content .popupContents { + padding: 0 !important; +} diff --git a/vid-app-common/src/main/webapp/app/vid/styles/dialogs.css b/vid-app-common/src/main/webapp/app/vid/styles/dialogs.css index f199aaa0..02866903 100755 --- a/vid-app-common/src/main/webapp/app/vid/styles/dialogs.css +++ b/vid-app-common/src/main/webapp/app/vid/styles/dialogs.css @@ -34,7 +34,6 @@ margin: 10px;
padding: 10px;
max-height: 300px;
- width: 600px;
overflow: auto;
}
|