diff options
Diffstat (limited to 'vid-app-common')
27 files changed, 822 insertions, 191 deletions
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.kt index 567099c81..aaa41c2d3 100644 --- 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.kt @@ -18,32 +18,17 @@ * ============LICENSE_END========================================================= */ -package org.onap.vid.aai; +package org.onap.vid.aai -import org.springframework.http.HttpMethod; +import io.joshworks.restclient.http.HttpResponse +import org.springframework.http.HttpMethod -import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response -public class ResponseWithRequestInfo { - private String requestUrl; - private HttpMethod requestHttpMethod; - private Response response; +open class BaseResponseWithRequestInfo(val requestUrl: String?, val requestHttpMethod: HttpMethod) - public ResponseWithRequestInfo(Response response, String requestUrl, HttpMethod requestHttpMethod) { - this.response = response; - this.requestUrl = requestUrl; - this.requestHttpMethod = requestHttpMethod; - } +class HttpResponseWithRequestInfo<T>(val response: HttpResponse<T>?, requestUrl: String?, requestHttpMethod: HttpMethod) : + BaseResponseWithRequestInfo(requestUrl, requestHttpMethod) - public String getRequestUrl() { - return requestUrl; - } - - public HttpMethod getRequestHttpMethod() { - return requestHttpMethod; - } - - public Response getResponse() { - return response; - } -} +class ResponseWithRequestInfo(val response: Response?, requestUrl: String?, requestHttpMethod: HttpMethod) : + BaseResponseWithRequestInfo(requestUrl, requestHttpMethod) 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 index ec7ea8a53..8ad6cd61a 100644 --- 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 @@ -3,6 +3,7 @@ * VID * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2018 IBM. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,12 +26,13 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class AaiGetNetworkCollectionDetails { + @JsonProperty("results") + private Result results = null; + public AaiGetNetworkCollectionDetails(){ results = new Result(); } - @JsonProperty("results") - private Result results = null; - + @JsonProperty("results") public Result getResults() { return results; 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 index b14cfa8e2..37ec17976 100644 --- 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 @@ -3,6 +3,7 @@ * VID * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2018 IBM. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,15 +22,8 @@ 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 type; private String name; public InstanceGroupInfo(String name){ @@ -37,6 +31,13 @@ public class InstanceGroupInfo { this.type = "instance-group"; } + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } public String getName() { return name; 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 fc04080d9..44257a62e 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 @@ -22,10 +22,11 @@ package org.onap.vid.asdc; import io.joshworks.restclient.http.HttpResponse; -import org.onap.vid.asdc.beans.Service; - +import java.io.InputStream; import java.nio.file.Path; import java.util.UUID; +import org.onap.vid.aai.HttpResponseWithRequestInfo; +import org.onap.vid.asdc.beans.Service; /** * The Interface AsdcClient. @@ -55,6 +56,8 @@ public interface AsdcClient { Path getServiceToscaModel(UUID uuid) throws AsdcCatalogException; + HttpResponseWithRequestInfo<InputStream> getServiceInputStream(UUID serviceUuid, boolean warpException); + HttpResponse<String> checkSDCConnectivity(); String getBaseUrl(); diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/rest/SdcRestClient.java b/vid-app-common/src/main/java/org/onap/vid/asdc/rest/SdcRestClient.java index a82110744..decf446d6 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/rest/SdcRestClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/rest/SdcRestClient.java @@ -20,11 +20,32 @@ package org.onap.vid.asdc.rest; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM; +import static org.onap.portalsdk.core.util.SystemProperties.APP_DISPLAY_NAME; +import static org.onap.vid.asdc.AsdcClient.URIS.METADATA_URL_TEMPLATE; +import static org.onap.vid.asdc.AsdcClient.URIS.TOSCA_MODEL_URL_TEMPLATE; +import static org.onap.vid.client.SyncRestClientInterface.HEADERS.AUTHORIZATION; +import static org.onap.vid.client.SyncRestClientInterface.HEADERS.CONTENT_TYPE; +import static org.onap.vid.client.SyncRestClientInterface.HEADERS.X_ECOMP_INSTANCE_ID; +import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; +import static org.onap.vid.utils.Logging.logRequest; + import com.att.eelf.configuration.EELFLogger; import com.google.common.collect.ImmutableMap; import io.joshworks.restclient.http.HttpResponse; import io.vavr.control.Try; +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.Collections; +import java.util.Map; +import java.util.UUID; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.aai.HttpResponseWithRequestInfo; import org.onap.vid.asdc.AsdcCatalogException; import org.onap.vid.asdc.AsdcClient; import org.onap.vid.asdc.beans.Service; @@ -34,26 +55,6 @@ import org.onap.vid.properties.VidProperties; import org.onap.vid.utils.Logging; import org.springframework.http.HttpMethod; -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.Collections; -import java.util.Map; -import java.util.UUID; - -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; -import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM; -import static org.onap.portalsdk.core.util.SystemProperties.APP_DISPLAY_NAME; -import static org.onap.vid.asdc.AsdcClient.URIS.METADATA_URL_TEMPLATE; -import static org.onap.vid.asdc.AsdcClient.URIS.TOSCA_MODEL_URL_TEMPLATE; -import static org.onap.vid.client.SyncRestClientInterface.HEADERS.AUTHORIZATION; -import static org.onap.vid.client.SyncRestClientInterface.HEADERS.CONTENT_TYPE; -import static org.onap.vid.client.SyncRestClientInterface.HEADERS.X_ECOMP_INSTANCE_ID; -import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; -import static org.onap.vid.utils.Logging.logRequest; - public class SdcRestClient implements AsdcClient { private String baseUrl; @@ -86,17 +87,28 @@ public class SdcRestClient implements AsdcClient { @Override public Path getServiceToscaModel(UUID uuid) throws AsdcCatalogException { - String finalUrl = String.format(TOSCA_MODEL_URL_TEMPLATE, baseUrl, path, uuid); - logRequest(LOGGER, HttpMethod.GET, finalUrl); - InputStream inputStream = Try - .of(() -> syncRestClient.getStream(finalUrl, prepareHeaders(auth, APPLICATION_OCTET_STREAM), Collections.emptyMap())) + .of(() -> getServiceInputStream(uuid, false)) .getOrElseThrow(AsdcCatalogException::new) + .getResponse() .getBody(); return createTmpFile(inputStream); } + @Override + public HttpResponseWithRequestInfo<InputStream> getServiceInputStream(UUID serviceUuid, boolean warpException) { + String finalUrl = String.format(TOSCA_MODEL_URL_TEMPLATE, baseUrl, path, serviceUuid); + logRequest(LOGGER, HttpMethod.GET, finalUrl); + try { + HttpResponse<InputStream> httpResponse = syncRestClient.getStream(finalUrl, prepareHeaders(auth, APPLICATION_OCTET_STREAM), Collections.emptyMap()); + return new HttpResponseWithRequestInfo<>(httpResponse, finalUrl, HttpMethod.GET); + } + catch (RuntimeException exception) { + throw warpException ? new ExceptionWithRequestInfo(HttpMethod.GET, finalUrl, exception) : exception; + } + } + @Override public HttpResponse<String> checkSDCConnectivity() { diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/GetVnfWorkflowRelationRequest.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/GetVnfWorkflowRelationRequest.java index 7a9787c7f..0c3a57df3 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/GetVnfWorkflowRelationRequest.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/GetVnfWorkflowRelationRequest.java @@ -3,6 +3,7 @@ * VID * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 IBM. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +26,9 @@ import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; public class GetVnfWorkflowRelationRequest { + + @JsonProperty("vnfsDetails") + private List<VnfDetails> vnfsDetails; public GetVnfWorkflowRelationRequest() { } @@ -32,9 +36,6 @@ public class GetVnfWorkflowRelationRequest { public GetVnfWorkflowRelationRequest(List<VnfDetails> vnfsDetails) { this.vnfsDetails = vnfsDetails; } - - @JsonProperty("vnfsDetails") - private List<VnfDetails> vnfsDetails; @JsonProperty("vnfsDetails") public List<VnfDetails> getVnfDetails() { diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/MsoController.java b/vid-app-common/src/main/java/org/onap/vid/controller/MsoController.java index fc718f0d2..535c97ce7 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/MsoController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/MsoController.java @@ -302,7 +302,6 @@ public class MsoController extends RestrictedBaseController { * @throws Exception the exception */ @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 msoRequest) { @@ -449,7 +448,6 @@ public class MsoController extends RestrictedBaseController { * @return the response entity * @throws Exception the exception */ - //mso_delete_vf_module/bc305d54-75b4-431b-adb2-eb6b9e546014/vnfs/fe9000-0009-9999/vfmodules/abeeee-abeeee-abeeee @RequestMapping(value = "/mso_delete_vfmodule_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfModuleId}", method = RequestMethod.POST) public ResponseEntity<String> deleteVfModule( @PathVariable("serviceInstanceId") String serviceInstanceId, diff --git a/vid-app-common/src/main/java/org/onap/vid/model/RequestReferencesContainer.java b/vid-app-common/src/main/java/org/onap/vid/model/RequestReferencesContainer.java index cc8fff614..cd6942ee8 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/RequestReferencesContainer.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/RequestReferencesContainer.java @@ -3,6 +3,7 @@ * VID * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 IBM. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +34,11 @@ public class RequestReferencesContainer { @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<>(); - + + public RequestReferencesContainer(@JsonProperty("requestReferences") RequestReferences requestReferences) { + this.requestReferences = requestReferences; + } + @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; @@ -44,10 +49,6 @@ public class RequestReferencesContainer { this.additionalProperties.put(name, value); } - public RequestReferencesContainer(@JsonProperty("requestReferences") RequestReferences requestReferences) { - this.requestReferences = requestReferences; - } - public RequestReferences getRequestReferences() { return requestReferences; } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/RelatedVnf.java b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/RelatedVnf.java index febd8e0fd..f5c1428fe 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/RelatedVnf.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/RelatedVnf.java @@ -3,6 +3,7 @@ * VID * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 IBM. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +31,10 @@ public class RelatedVnf extends Node { private String serviceInstanceName; private String tenantName; + public RelatedVnf(AAITreeNode node) { + super(node); + } + public String getServiceInstanceId() { return serviceInstanceId; } @@ -54,10 +59,6 @@ public class RelatedVnf extends Node { this.tenantName = tenantName; } - public RelatedVnf(AAITreeNode node) { - super(node); - } - public static RelatedVnf from(AAITreeNode node) { RelatedVnf vnf = new RelatedVnf(node); if (node.getParent() != null && node.getParent().getType() == NodeType.SERVICE_INSTANCE) { 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 index 1638a376c..984c0d766 100644 --- 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 @@ -21,17 +21,19 @@ package org.onap.vid.model.probes; +import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; + import com.google.common.base.MoreObjects; -import io.joshworks.restclient.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.aai.HttpResponseWithRequestInfo; import org.onap.vid.aai.ResponseWithRequestInfo; import org.onap.vid.mso.RestObjectWithRequestInfo; import org.onap.vid.utils.Logging; import org.springframework.http.HttpMethod; -import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; - public class HttpRequestMetadata extends StatusMetadata { private final HttpMethod httpMethod; private final int httpCode; @@ -81,6 +83,20 @@ public class HttpRequestMetadata extends StatusMetadata { duration); } + public HttpRequestMetadata(HttpResponseWithRequestInfo response, String description, long duration, boolean readRawData) { + super(description, duration); + this.httpMethod = response.getRequestHttpMethod(); + this.url = response.getRequestUrl(); + this.httpCode = response.getResponse().getStatus(); + if (readRawData) { + try { + response.getResponse().getRawBody().reset(); + this.rawData = IOUtils.toString(response.getResponse().getRawBody(), StandardCharsets.UTF_8.name()); + } catch (Exception e) { + //Nothing to do here + } + } + } public HttpMethod getHttpMethod() { 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 9146e8f1b..4d0d4ee74 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 @@ -60,6 +60,8 @@ import javax.ws.rs.BadRequestException; import org.apache.commons.collections4.ListUtils; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.aai.HttpResponseWithRequestInfo; import org.onap.vid.changeManagement.ChangeManagementRequest; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.changeManagement.WorkflowRequestDetail; @@ -67,6 +69,7 @@ import org.onap.vid.controller.OperationalEnvironmentController; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.SOWorkflowList; import org.onap.vid.model.SoftDeleteRequest; +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.model.probes.StatusMetadata; @@ -84,8 +87,8 @@ import org.onap.vid.mso.rest.RequestList; import org.onap.vid.mso.rest.RequestWrapper; import org.onap.vid.mso.rest.Task; import org.onap.vid.mso.rest.TaskList; +import org.onap.vid.utils.Logging; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; public class MsoBusinessLogicImpl implements MsoBusinessLogic { @@ -383,12 +386,13 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } private List<RequestWrapper> getOrchestrationRequestsByFilter(String filterName, String filterValue) { + HttpResponseWithRequestInfo<String> msoResponseWrapper = getRawOrchestrationRequestsByFilter(filterName, filterValue); + return deserializeOrchestrationRequestsJson(msoResponseWrapper.getResponse().getBody()); + } + + private HttpResponseWithRequestInfo<String> getRawOrchestrationRequestsByFilter(String filterName, String filterValue) { String orchestrationReqPath = constructOrchestrationRequestFilter(filterName, filterValue); - RestObject<String> restObjStr = new RestObject<>(); - String str = new String(); - restObjStr.set(str); - MsoResponseWrapper msoResponseWrapper = msoClientInterface.getOrchestrationRequest(str, "", orchestrationReqPath, restObjStr, true); - return deserializeOrchestrationRequestsJson(msoResponseWrapper.getEntity()); + return msoClientInterface.getOrchestrationRequest(orchestrationReqPath, true); } private List<RequestWrapper> deserializeOrchestrationRequestsJson(String orchestrationRequestsJson) { @@ -837,22 +841,38 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { @Override public ExternalComponentStatus probeComponent() { - String url = SystemProperties.getProperty( - MsoProperties.MSO_SERVER_URL) + "/" + SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQS); - long startTime = System.currentTimeMillis(); - ExternalComponentStatus externalComponentStatus; - + final long startTime = System.currentTimeMillis(); + HttpResponseWithRequestInfo<String> responseWithRequestInfo = null; try { - String rawBody = objectMapper.writeValueAsString(getOrchestrationRequestsForDashboard()); - StatusMetadata statusMetadata=new HttpRequestMetadata(HttpMethod.GET,200,url,rawBody,"VID-SO",System.currentTimeMillis() - startTime); + responseWithRequestInfo = getRawOrchestrationRequestsByFilter("requestExecutionDate", "01-01-2100" ); + int httpCode = responseWithRequestInfo.getResponse().getStatus(); + boolean isAvailable = httpCode == 200 || httpCode == 202; + if (isAvailable) { + //make sure response can be parsed to RequestList.class + JACKSON_OBJECT_MAPPER.readValue(responseWithRequestInfo.getResponse().getBody(), RequestList.class); + } + + HttpRequestMetadata metadata = new HttpRequestMetadata(responseWithRequestInfo, + isAvailable ? "OK" : "MSO returned no orchestration requests", + System.currentTimeMillis() - startTime, true); + return new ExternalComponentStatus(ExternalComponentStatus.Component.MSO, isAvailable, metadata); - externalComponentStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.MSO, true, statusMetadata); + } catch (ExceptionWithRequestInfo e) { + long duration = System.currentTimeMillis() - startTime; + return new ExternalComponentStatus(ExternalComponentStatus.Component.MSO, false, + new HttpRequestMetadata(e, duration)); } catch (Exception e) { - StatusMetadata statusMetadata = new HttpRequestMetadata(HttpMethod.GET, HttpStatus.INTERNAL_SERVER_ERROR.value(), url, "", e.getMessage(), System.currentTimeMillis() - startTime); - externalComponentStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.MSO, false, statusMetadata); - } + StatusMetadata metadata; + long duration = System.currentTimeMillis() - startTime; - return externalComponentStatus; + if (responseWithRequestInfo == null) { + metadata = new ErrorMetadata(Logging.exceptionToDescription(e), duration); + } else { + metadata = new HttpRequestMetadata(responseWithRequestInfo, Logging.exceptionToDescription(e), duration, true); + } + + return new ExternalComponentStatus(ExternalComponentStatus.Component.MSO, false, metadata); + } } private void validateUpdateVnfConfig(RequestDetails requestDetails) { 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 46bd2731d..d1cb3a37b 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 @@ -21,6 +21,7 @@ package org.onap.vid.mso; import io.joshworks.restclient.http.HttpResponse; +import org.onap.vid.aai.HttpResponseWithRequestInfo; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.model.SOWorkflowList; import org.onap.vid.changeManagement.WorkflowRequestDetail; @@ -89,7 +90,7 @@ public interface MsoInterface { MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String endpoint); - MsoResponseWrapper getOrchestrationRequest(String t, String sourceId, String endpoint, RestObject restObject, boolean warpException); + HttpResponseWithRequestInfo<String> getOrchestrationRequest(String endpoint, boolean warpException); MsoResponseWrapper getOrchestrationRequest(String endpoint); 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 df8034b22..cc6d6123d 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 @@ -35,6 +35,7 @@ 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.HttpResponseWithRequestInfo; import org.onap.vid.aai.util.HttpsAuthClient; import org.onap.vid.changeManagement.MsoRequestDetails; import org.onap.vid.changeManagement.RequestDetailsWrapper; @@ -51,6 +52,7 @@ import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.mso.RestObject; import org.onap.vid.utils.Logging; import org.onap.vid.utils.SystemPropertiesWrapper; +import org.springframework.http.HttpMethod; /** @@ -216,11 +218,11 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } @Override - public MsoResponseWrapper getOrchestrationRequest(String t, String sourceId, String endpoint, RestObject restObject, boolean warpException) { + public HttpResponseWithRequestInfo<String> getOrchestrationRequest(String endpoint, boolean warpException) { String path = baseUrl + endpoint; HttpResponse<String> response = client.get(path, commonHeaders, new HashMap<>(), String.class); - return MsoUtil.wrapResponse(response); + return new HttpResponseWithRequestInfo<>(response, path, HttpMethod.GET); } @Override 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 78b3e9709..7878c2fb8 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 @@ -21,6 +21,7 @@ package org.onap.vid.scheduler; import com.att.eelf.configuration.EELFLogger; +import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import io.joshworks.restclient.http.HttpResponse; @@ -43,6 +44,7 @@ import java.util.Collections; import java.util.Map; import java.util.function.Function; +import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER; import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; @Service @@ -90,15 +92,19 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { .putAll(commonHeaders) .put(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()) .build(); - final HttpResponse<T> response = ((HttpResponse<T>) syncRestClient.get(url, requestHeaders, - Collections.emptyMap(), t.getClass())); + final HttpResponse<String> response = syncRestClient.get(url, requestHeaders, + Collections.emptyMap(), String.class); Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, response); status = response.getStatus(); restObject.setStatusCode(status); - + rawData = response.getBody(); if (status == 200) { - t = response.getBody(); - restObject.set(t); + if (t instanceof String) { + restObject.set((T)rawData); + } + else { + restObject.set(JACKSON_OBJECT_MAPPER.readValue(rawData, new TypeReference<T>() {})); + } logger.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + SUCCESSFUL_API_MESSAGE); logger.info(EELFLoggerDelegate.errorLogger, "<== " + methodName + SUCCESSFUL_API_MESSAGE); } else { @@ -106,7 +112,7 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { } return new RestObjectWithRequestInfo<>(HttpMethod.GET, url, restObject, status, rawData); } - catch (RuntimeException e) { + catch (Exception e) { throw new ExceptionWithRequestInfo(HttpMethod.GET, url, rawData, status, e); } } 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 9b890478f..b50dcc3b5 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 @@ -42,7 +42,6 @@ import org.apache.http.HttpStatus; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.vid.aai.AaiClientInterface; import org.onap.vid.aai.AaiGetVnfResponse; -import org.onap.vid.aai.AaiOverTLSClientInterface; import org.onap.vid.aai.AaiResponse; import org.onap.vid.aai.AaiResponseTranslator; import org.onap.vid.aai.ExceptionWithRequestInfo; 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 9d6f74def..a5988a156 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 @@ -20,12 +20,22 @@ */ package org.onap.vid.services; +import static org.onap.vid.model.probes.ExternalComponentStatus.Component.SDC; +import static org.onap.vid.properties.Features.FLAG_SERVICE_MODEL_CACHE; + import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import io.joshworks.restclient.http.HttpResponse; +import java.io.InputStream; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.aai.HttpResponseWithRequestInfo; import org.onap.vid.asdc.AsdcCatalogException; import org.onap.vid.asdc.AsdcClient; import org.onap.vid.asdc.beans.Service; @@ -34,20 +44,16 @@ 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.onap.vid.model.probes.ErrorMetadata; import org.onap.vid.model.probes.ExternalComponentStatus; import org.onap.vid.model.probes.HttpRequestMetadata; +import org.onap.vid.model.probes.StatusMetadata; +import org.onap.vid.properties.VidProperties; import org.onap.vid.utils.Logging; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.togglz.core.manager.FeatureManager; -import java.nio.file.Path; -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. */ @@ -150,6 +156,20 @@ public class VidServiceImpl implements VidService { @Override public ExternalComponentStatus probeComponent() { + UUID modelUUID; + try { + modelUUID = UUID.fromString(VidProperties.getPropertyWithDefault( + VidProperties.PROBE_SDC_MODEL_UUID,"")); + } + //in case of no such PROBE_SDC_MODEL_UUID property or non uuid there we check only sdc connectivity + catch (Exception e) { + return probeComponentBySdcConnectivity(); + } + + return probeSdcByGettingModel(modelUUID); + } + + public ExternalComponentStatus probeComponentBySdcConnectivity() { long startTime = System.currentTimeMillis(); ExternalComponentStatus externalComponentStatus; try { @@ -158,10 +178,49 @@ public class VidServiceImpl implements VidService { System.currentTimeMillis() - startTime); externalComponentStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.SDC, stringHttpResponse.isSuccessful(), httpRequestMetadata); } catch (Exception e) { - HttpRequestMetadata httpRequestMetadata = new HttpRequestMetadata(HttpMethod.GET, 0, - AsdcClient.URIS.HEALTH_CHECK_ENDPOINT, "", Logging.exceptionToDescription(e), System.currentTimeMillis() - startTime); - externalComponentStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.SDC, false, httpRequestMetadata); + ErrorMetadata errorMetadata = new ErrorMetadata(Logging.exceptionToDescription(e), System.currentTimeMillis() - startTime); + externalComponentStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.SDC, false, errorMetadata); } return externalComponentStatus; } + + protected ExternalComponentStatus probeSdcByGettingModel(UUID modelUUID) { + final long startTime = System.currentTimeMillis(); + + HttpResponseWithRequestInfo<InputStream> response = null; + try { + response = asdcClient.getServiceInputStream(modelUUID, true); + int responseStatusCode = response.getResponse().getStatus(); + + if (responseStatusCode == 404) { + return errorStatus(response, startTime, "model " + modelUUID + " not found in SDC" + + " (consider updating vid probe configuration '" + VidProperties.PROBE_SDC_MODEL_UUID + "')"); + } else if (responseStatusCode >= 400) { + return errorStatus(response, startTime, "error while retrieving model " + modelUUID + " from SDC"); + } else { + InputStream inputStreamEntity = response.getResponse().getRawBody();//validate we can read the input steam from the response + if (inputStreamEntity.read() <= 0) { + return errorStatus(response, startTime, "error reading model " + modelUUID + " from SDC"); + } else { + // RESPONSE IS SUCCESS + return new ExternalComponentStatus(SDC, true, + new HttpRequestMetadata(response, "OK", startTime, false)); + } + } + } catch (ExceptionWithRequestInfo e) { + return new ExternalComponentStatus(SDC, false, + new HttpRequestMetadata(e, System.currentTimeMillis() - startTime)); + } catch (Exception e) { + return errorStatus(response, startTime, Logging.exceptionToDescription(e)); + } + } + + private ExternalComponentStatus errorStatus(HttpResponseWithRequestInfo<InputStream> response, long startTime, String description) { + final long duration = System.currentTimeMillis() - startTime; + StatusMetadata statusMetadata = (response == null) ? + new ErrorMetadata(description, duration) : + new HttpRequestMetadata(response, description, duration, true); + + return new ExternalComponentStatus(SDC, false, statusMetadata); + } } 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 df7f20e49..71478fcf1 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 @@ -119,7 +119,7 @@ public class Logging { response.bufferEntity(); logger.debug("Received {} {} Status: {} . Body: {}", method.name(), url, response.getStatus(), response.readEntity(entityClass)); } - catch (ProcessingException | IllegalStateException e) { + catch (Exception e) { logger.debug("Received {} {} Status: {} . Failed to read response as {}", method.name(), url, response.getStatus(), entityClass.getName()); } } @@ -128,7 +128,7 @@ public class Logging { try { logger.debug("Received {} {} Status: {} . Body: {}", method.name(), url, response.getStatus(), response.getBody()); } - catch (ProcessingException | IllegalStateException e) { + catch (Exception e) { logger.debug("Received {} {} Status: {} . Failed to read response", method.name(), url, response.getStatus()); } } diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/InstantiationController.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/InstantiationController.js index 6eed08033..7fa312ed9 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/InstantiationController.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/InstantiationController.js @@ -142,13 +142,13 @@ }
return null;
- }
+ };
$scope.hasVfModules = function (vnfInstance) {
if ($scope.returnVfModules(vnfInstance) != null) {
return true;
}
return false;
- }
+ };
$scope.returnVolumeGroups = function (vnfInstance) {
var svcModel = $scope.service.convertedModel;
@@ -183,13 +183,13 @@ }
return null;
- }
+ };
$scope.hasVolumeGroups = function (vnfInstance) {
if ($scope.returnVolumeGroups(vnfInstance) != null) {
return true;
}
return false;
- }
+ };
$scope.deleteNetwork = function (serviceObject, network) {
console.log("Removing Network " + network.name);
@@ -871,7 +871,7 @@ //Display popup with additional VF-Module information
DataService.setVfModuleInstanceId(vfModule[FIELD.ID.VF_MODULE_ID]);
- DataService.setInventoryItem(vfModule)
+ DataService.setInventoryItem(vfModule);
DataService.setSubscriberName(serviceObject[COMPONENT.SUBSCRIBER_NAME]);
DataService.setServiceType(serviceObject[COMPONENT.SERVICE_TYPE]);
@@ -1323,7 +1323,7 @@ var deleteCallbackFunction = function () {
console.log('hi')
- }
+ };
$scope.resetProgress = function () {
$scope.percentProgress = 0;
@@ -1364,13 +1364,13 @@ else {
return true;
}
- }
+ };
$scope.isMacro = function () {
return $scope.service && AsdcService.isMacro($scope.service.model);
- }
+ };
$scope.reloadRoute = function () {
$route.reload();
- }
+ };
/*
@@ -1539,7 +1539,7 @@ Private metthods + FIELD.STATUS.IS_SUCCESSFUL + response.isSuccessful;
if (response.isSuccessful) {
color = FIELD.ID.COLOR_8F8;
- $location.path(COMPONENT.SERVICEMODELS_MODELS_SERVICES_PATH)
+ $location.path(COMPONENT.SERVICEMODELS_MODELS_SERVICES_PATH);
} else {
color = FIELD.ID.COLOR_F88;
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java index b2d8e85fa..9793862ca 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java @@ -56,6 +56,7 @@ import java.net.URI; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.Map; +import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Stream; diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/local/LocalAsdcClient.java b/vid-app-common/src/test/java/org/onap/vid/asdc/local/LocalAsdcClient.java index ce1bbe930..2f5853e47 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/local/LocalAsdcClient.java +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/local/LocalAsdcClient.java @@ -27,6 +27,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.joshworks.restclient.http.HttpResponse; import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.file.Path; @@ -34,6 +35,7 @@ import java.nio.file.Paths; import java.util.UUID; import org.json.JSONArray; import org.json.JSONObject; +import org.onap.vid.aai.HttpResponseWithRequestInfo; import org.onap.vid.asdc.AsdcCatalogException; import org.onap.vid.asdc.AsdcClient; import org.onap.vid.asdc.beans.Service; @@ -162,6 +164,10 @@ public class LocalAsdcClient implements AsdcClient { return HttpResponse.fallback(""); } + @Override + public HttpResponseWithRequestInfo<InputStream> getServiceInputStream(UUID serviceUuid, boolean warpException) { + return null; + } @Override public String getBaseUrl(){ diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java index 126f30067..589874d2a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java @@ -85,7 +85,7 @@ public class SdcRestClientITTest { String expectedEndpoint = String.format("/sdc/v1/catalog/services/%s/toscaModel", uuid); stubServer.prepareGetCall( - expectedEndpoint, stringContent("sampleFileContent"), "sampleFileContent", ok(), "application/octet-stream"); + expectedEndpoint, stringContent("sampleFileContent"), ok(), "application/octet-stream"); Path serviceToscaModel = sdcRestClient.getServiceToscaModel(uuid); diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java index a1b45590c..a2f86f437 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java @@ -20,6 +20,7 @@ package org.onap.vid.controller; +import static java.lang.String.format; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -44,11 +45,14 @@ import org.jeasy.random.randomizers.misc.BooleanRandomizer; import org.jeasy.random.randomizers.text.StringRandomizer; import org.junit.Before; import org.junit.Test; +import org.onap.vid.model.RequestReferencesContainer; import org.onap.vid.mso.MsoBusinessLogic; import org.onap.vid.mso.MsoResponseWrapper; +import org.onap.vid.mso.RestObject; import org.onap.vid.mso.rest.MsoRestClientNew; 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.vid.services.CloudOwnerService; import org.springframework.test.web.servlet.MockMvc; @@ -80,6 +84,27 @@ public class MsoControllerTest { } @Test + public void shouldGetOrchestrationRequest() throws Exception { + // given + RequestDetails requestDetails = modelGenerator.nextObject(RequestDetails.class); + String requestId = "bc305d54-75b4-431b-adb2-eb6b9e546014"; + + MsoResponseWrapper expectedResponse = new MsoResponseWrapper(200, "test"); + given(msoBusinessLogic + .getOrchestrationRequest(requestId)) + .willReturn(expectedResponse); + + // when & then + mockMvc.perform(get(format("/mso/mso_get_orch_req/%s", requestId)) + .content(asJson(requestDetails)) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(asJson(expectedResponse))); + + then(cloudService).shouldHaveZeroInteractions(); + } + + @Test public void shouldDelegateNewServiceInstantiation() throws Exception { // given RequestDetails requestDetails = modelGenerator.nextObject(RequestDetails.class); @@ -100,6 +125,28 @@ public class MsoControllerTest { } @Test + public void shouldCreateVolumeInstance() throws Exception { + // given + RequestDetails requestDetails = modelGenerator.nextObject(RequestDetails.class); + String serviceInstanceId = "bc305d54-75b4-431b-adb2-eb6b9e546014"; + String vnfInstanceId = "fe9000-0009-9999"; + + MsoResponseWrapper expectedResponse = new MsoResponseWrapper(200, "test"); + given(msoBusinessLogic + .createVolumeGroupInstance(objectEqualTo(requestDetails), eq(serviceInstanceId), eq(vnfInstanceId))) + .willReturn(expectedResponse); + + // when & then + mockMvc.perform(post(format("/mso/mso_create_volumegroup_instance/%s/vnfs/%s", serviceInstanceId, vnfInstanceId)) + .content(asJson(requestDetails)) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(asJson(expectedResponse))); + + then(cloudService).should(only()).enrichRequestWithCloudOwner(objectEqualTo(requestDetails)); + } + + @Test public void shouldReturnOrchestrationRequestsForDashboard() throws Exception { // given List<Request> orchestrationRequests = modelGenerator @@ -195,6 +242,135 @@ public class MsoControllerTest { } @Test + public void shouldDeleteVfModuleInstance() throws Exception { + // given + RequestDetails requestDetails = modelGenerator.nextObject(RequestDetails.class); + String serviceInstanceId = "bc305d54-75b4-431b-adb2-eb6b9e546014"; + String vnfInstanceId = "fe9000-0009-9999"; + String vfModuleId = "abeeee-abeeee-abeeee"; + + MsoResponseWrapper wrapper = mock(MsoResponseWrapper.class); + given(wrapper.getResponse()).willReturn("some response"); + given(msoBusinessLogic.deleteVfModule(objectEqualTo(requestDetails), eq(serviceInstanceId), eq(vnfInstanceId), eq(vfModuleId))).willReturn(wrapper); + + // when & then + mockMvc.perform(post(format("/mso/mso_delete_vfmodule_instance/%s/vnfs/%s/vfModules/%s", serviceInstanceId, vnfInstanceId, vfModuleId)) + .content(asJson(requestDetails)) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("some response")); + + then(cloudService).should(only()).enrichRequestWithCloudOwner(objectEqualTo(requestDetails)); + } + + @Test + public void shouldDeleteVolumeGroup() throws Exception { + // given + RequestDetails requestDetails = modelGenerator.nextObject(RequestDetails.class); + String serviceInstanceId = "bc305d54-75b4-431b-adb2-eb6b9e546014"; + String vnfInstanceId = "fe9000-0009-9999"; + String volumeGroupId = "abeeee-abeeee-abeeee"; + + MsoResponseWrapper wrapper = mock(MsoResponseWrapper.class); + given(wrapper.getResponse()).willReturn("some response"); + given(msoBusinessLogic.deleteVolumeGroupInstance(objectEqualTo(requestDetails), eq(serviceInstanceId), eq(vnfInstanceId), eq(volumeGroupId))).willReturn(wrapper); + + // when & then + mockMvc.perform(post(format("/mso/mso_delete_volumegroup_instance/%s/vnfs/%s/volumeGroups/%s", serviceInstanceId, vnfInstanceId, volumeGroupId)) + .content(asJson(requestDetails)) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("some response")); + + then(cloudService).should(only()).enrichRequestWithCloudOwner(objectEqualTo(requestDetails)); + } + + @Test + public void shouldDeleteInstance() throws Exception { + // given + RequestDetails requestDetails = modelGenerator.nextObject(RequestDetails.class); + String serviceInstanceId = "bc305d54-75b4-431b-adb2-eb6b9e546014"; + String networkInstanceId = "fe9000-0009-9999"; + + MsoResponseWrapper wrapper = mock(MsoResponseWrapper.class); + given(wrapper.getResponse()).willReturn("some response"); + given(msoBusinessLogic.deleteNwInstance(objectEqualTo(requestDetails), eq(serviceInstanceId), eq(networkInstanceId))).willReturn(wrapper); + + // when & then + mockMvc.perform(post(format("/mso/mso_delete_nw_instance/%s/networks/%s", serviceInstanceId, networkInstanceId)) + .content(asJson(requestDetails)) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("some response")); + + then(cloudService).should(only()).enrichRequestWithCloudOwner(objectEqualTo(requestDetails)); + } + + @Test + public void shouldDeleteServiceInstance() throws Exception { + // given + RequestDetails requestDetails = modelGenerator.nextObject(RequestDetails.class); + String serviceInstanceId = "bc305d54-75b4-431b-adb2-eb6b9e546014"; + String serviceStatus = "ACTIVE"; + + MsoResponseWrapper wrapper = mock(MsoResponseWrapper.class); + given(wrapper.getResponse()).willReturn("some response"); + given(msoBusinessLogic.deleteSvcInstance(objectEqualTo(requestDetails), eq(serviceInstanceId), eq(serviceStatus))).willReturn(wrapper); + + // when & then + mockMvc.perform(post(format("/mso/mso_delete_svc_instance/%s", serviceInstanceId)) + .param("serviceStatus", serviceStatus) + .content(asJson(requestDetails)) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("some response")); + + then(cloudService).shouldHaveZeroInteractions(); + } + + @Test + public void shouldDeleteVnf() throws Exception { + // given + RequestDetails requestDetails = modelGenerator.nextObject(RequestDetails.class); + String serviceInstanceId = "bc305d54-75b4-431b-adb2-eb6b9e546014"; + String vnfInstanceId = "fe9000-0009-9999"; + + MsoResponseWrapper wrapper = mock(MsoResponseWrapper.class); + given(wrapper.getResponse()).willReturn("some response"); + given(msoBusinessLogic.deleteVnf(objectEqualTo(requestDetails), eq(serviceInstanceId), eq(vnfInstanceId))).willReturn(wrapper); + + // when & then + mockMvc.perform(post(format("/mso/mso_delete_vnf_instance/%s/vnfs/%s", serviceInstanceId, vnfInstanceId)) + .content(asJson(requestDetails)) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("some response")); + + then(cloudService).should(only()).enrichRequestWithCloudOwner(objectEqualTo(requestDetails)); + } + + @Test + public void shouldDeleteConfiguration() throws Exception { + // given + RequestDetailsWrapper requestDetails = modelGenerator.nextObject(RequestDetailsWrapper.class); + String serviceInstanceId = "bc305d54-75b4-431b-adb2-eb6b9e546014"; + String configurationId = "fe9000-0009-9999"; + + MsoResponseWrapper wrapper = mock(MsoResponseWrapper.class); + given(wrapper.getResponse()).willReturn("some response"); + given(msoBusinessLogic.deleteConfiguration(objectEqualTo(requestDetails), eq(serviceInstanceId), eq(configurationId))).willReturn(wrapper); + + // when & then + mockMvc.perform(post(format("/mso/mso_delete_configuration/%s/configurations/%s", serviceInstanceId, configurationId)) + .content(asJson(requestDetails)) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("some response")); + + then(cloudService).should(only()).enrichRequestWithCloudOwner(objectEqualTo(requestDetails.getRequestDetails())); + } + + @Test public void shouldDelegateNewInstanceCreation() throws Exception { // given RequestDetails requestDetails = modelGenerator.nextObject(RequestDetails.class); @@ -234,6 +410,32 @@ public class MsoControllerTest { then(cloudService).shouldHaveZeroInteractions(); } + @Test + public void shouldActivateFabricConfiguration() throws Exception { + // given + RequestDetails requestDetails = modelGenerator.nextObject(RequestDetails.class); + String serviceInstanceId = "bc305d54-75b4-431b-adb2-eb6b9e546014"; + + String path = "/mso/path"; + given(msoBusinessLogic.getActivateFabricConfigurationPath(eq(serviceInstanceId))).willReturn(path); + + RestObject<RequestReferencesContainer> response = new RestObject<>(); + response.set(mock(RequestReferencesContainer.class)); + response.setRaw("some response"); + response.setStatusCode(200); + + given(msoRestClient.PostForObject(objectEqualTo(requestDetails), eq(path), eq(RequestReferencesContainer.class))).willReturn(response); + + // when & then + mockMvc.perform(post(format("/mso/mso_activate_fabric_configuration/%s", serviceInstanceId)) + .content(asJson(requestDetails)) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("{\"status\":200,\"entity\":{}}")); + + then(cloudService).shouldHaveZeroInteractions(); + } + private <T> String asJson(T value) { try { return objectMapper.writeValueAsString(value); diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java index 4ddbc0f41..830862261 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java @@ -25,7 +25,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.tuple; import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -37,19 +42,20 @@ import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import static org.onap.vid.controller.MsoController.CONFIGURATION_ID; import static org.onap.vid.controller.MsoController.REQUEST_TYPE; import static org.onap.vid.controller.MsoController.SVC_INSTANCE_ID; import static org.onap.vid.controller.MsoController.VNF_INSTANCE_ID; +import static org.onap.vid.model.probes.ExternalComponentStatus.Component.MSO; import static org.onap.vid.mso.MsoBusinessLogicImpl.validateEndpointPath; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.collect.Lists; -import com.google.gson.Gson; import io.joshworks.restclient.http.HttpResponse; import java.io.IOException; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; @@ -60,19 +66,26 @@ import java.util.UUID; import java.util.stream.Collectors; import javax.ws.rs.BadRequestException; import org.apache.commons.io.IOUtils; +import org.apache.http.HttpException; +import org.hamcrest.Matcher; +import org.hamcrest.MatcherAssert; import org.jetbrains.annotations.NotNull; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.hamcrest.MockitoHamcrest; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.aai.HttpResponseWithRequestInfo; import org.onap.vid.changeManagement.ChangeManagementRequest; import org.onap.vid.changeManagement.WorkflowRequestDetail; import org.onap.vid.controller.OperationalEnvironmentController; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.SOWorkflowList; import org.onap.vid.model.SoftDeleteRequest; +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.mso.model.CloudConfiguration; import org.onap.vid.mso.model.ModelInfo; import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo; @@ -83,9 +96,8 @@ import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestD 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.RequestList; -import org.onap.vid.mso.rest.RequestWrapper; import org.onap.vid.mso.rest.Task; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; @@ -496,12 +508,8 @@ public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { String vnfModelTypeOrchestrationRequests = getFileContentAsString("mso_model_info_sample_response.json"); String scaleOutActionOrchestrationRequests = getFileContentAsString("mso_action_scaleout_sample_response.json"); - MsoResponseWrapper msoResponseWrapperMock = mock(MsoResponseWrapper.class); - given(msoInterface - .getOrchestrationRequest(any(String.class), any(String.class), any(String.class), - any(RestObject.class), anyBoolean())) - .willReturn(msoResponseWrapperMock); - given(msoResponseWrapperMock.getEntity()) + HttpResponse<String> httpResponse = mockForGetOrchestrationRequest(); + given(httpResponse.getBody()) .willReturn(vnfModelTypeOrchestrationRequests, scaleOutActionOrchestrationRequests); //when @@ -523,13 +531,7 @@ public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { //given String vnfModelTypeOrchestrationRequests = getFileContentAsString("mso_model_info_sample_wrong_response.json"); - MsoResponseWrapper msoResponseWrapperMock = mock(MsoResponseWrapper.class); - given(msoInterface - .getOrchestrationRequest(any(String.class), any(String.class), any(String.class), - any(RestObject.class), anyBoolean())) - .willReturn(msoResponseWrapperMock); - given(msoResponseWrapperMock.getEntity()) - .willReturn(vnfModelTypeOrchestrationRequests); + mockForGetOrchestrationRequest(200, vnfModelTypeOrchestrationRequests); //when msoBusinessLogic.getOrchestrationRequestsForDashboard(); @@ -1318,9 +1320,15 @@ public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { @Test public void probeShouldReturnOrchestrationRequestsAndConnectionStatus(){ - MsoResponseWrapper wrapper = getMsoResponseWrapper(); - given(msoInterface.getOrchestrationRequest(anyString(),anyString(), - anyString(),any(RestObject.class),anyBoolean())).willReturn(wrapper); + String body = + "{" + + " \"requestList\":" + + " [{" + + " \"request\": {}" + + " }" + + " ]" + + "}"; + mockForGetOrchestrationRequest(200, body); ExternalComponentStatus externalComponentStatus = msoBusinessLogic.probeComponent(); @@ -1328,18 +1336,6 @@ public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { assertThat(externalComponentStatus.getComponent()).isEqualTo(ExternalComponentStatus.Component.MSO); } - @NotNull - private MsoResponseWrapper getMsoResponseWrapper() { - MsoResponseWrapper wrapper=new MsoResponseWrapper(); - RequestWrapper requestWrapper = new RequestWrapper(); - requestWrapper.setRequest(new Request()); - RequestList requestList = new RequestList(); - List<RequestWrapper> response = Lists.newArrayList(requestWrapper); - requestList.setRequestList(response); - wrapper.setEntity(new Gson().toJson(requestList)); - return wrapper; - } - private WorkflowRequestDetail createWorkflowRequestDetail() { WorkflowRequestDetail workflowRequestDetail = new WorkflowRequestDetail(); org.onap.vid.changeManagement.RequestParameters requestParameters = new org.onap.vid.changeManagement.RequestParameters(); @@ -1429,5 +1425,193 @@ public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { super(testException); } } + + //you need to add mocks to httpResponse + private HttpResponse<String> mockForGetOrchestrationRequest() { + + HttpResponse<String> httpResponse = mock(HttpResponse.class); + HttpResponseWithRequestInfo<String> httpResponseWithRequestInfo = new HttpResponseWithRequestInfo<>(httpResponse, "my pretty url", HttpMethod.GET); + when(msoInterface.getOrchestrationRequest(any(String.class),anyBoolean())) + .thenReturn(httpResponseWithRequestInfo); + return httpResponse; + } + + private HttpResponse<String> mockForGetOrchestrationRequest(int statusCode, String body) { + + HttpResponse<String> httpResponse = mockForGetOrchestrationRequest(); + when(httpResponse.getStatus()).thenReturn(statusCode); + when(httpResponse.getBody()).thenReturn(body); + try { + when(httpResponse.getRawBody()).thenReturn(IOUtils.toInputStream(body, StandardCharsets.UTF_8.name())); + } catch (IOException e) { + throw new RuntimeException(e); + } + return httpResponse; + } + + @Test + public void probeComponent_verifyGoodRequest(){ + String responseString = "" + + "{ " + + " \"requestList\": [{ " + + " \"request\": { " + + " \"requestDetails\": { " + + " \"cloudConfiguration\": { " + + " \"lcpCloudRegionId\": \"hvf6\", " + + " \"cloudOwner\": \"irma-aic\", " + + " \"tenantId\": \"ffdf52b5e5104b0e8f329b0b1637ee2e\" " + + " }, " + + " \"modelInfo\": { " + + " \"modelCustomizationName\": \"VSP1710PID298109_vWINIFRED 0\", " + + " \"modelCustomizationId\": \"24d43fdb-9aa6-4287-a68e-1e702ea89d13\", " + + " \"modelInvariantId\": \"e7961100-cde6-4b5a-bcda-b8945086950a\", " + + " \"modelVersionId\": \"959a7ba0-89ee-4984-9af6-65d5bdda4b0e\", " + + " \"modelName\": \"VSP1710PID298109_vWINIFRED\", " + + " \"modelType\": \"vnf\", " + + " \"modelVersion\": \"1.0\" " + + " }, " + + " \"relatedModelList\": [{ " + + " \"relatedInstance\": { " + + " \"instanceId\": \"6dd0f8de-93c7-48a2-914b-1a8d58e0eb48\", " + + " \"modelInfo\": { " + + " \"modelInvariantId\": \"57e00952-0af7-4f0f-b19a-408a6f73c8df\", " + + " \"modelType\": \"service\", " + + " \"modelName\": \"ServicevWINIFREDPID298109\", " + + " \"modelVersion\": \"1.0\", " + + " \"modelVersionId\": \"fe6985cd-ea33-3346-ac12-ab121484a3fe\" " + + " } " + + " } " + + " } " + + " ], " + + " \"requestInfo\": { " + + " \"source\": \"VID\", " + + " \"suppressRollback\": false, " + + " \"requestorId\": \"ds828e\" " + + " }, " + + " \"requestParameters\": { " + + " \"userParams\": [ " + + " ], " + + " \"aLaCarte\": false, " + + " \"usePreload\": true, " + + " \"rebuildVolumeGroups\": false, " + + " \"autoBuildVfModules\": false, " + + " \"cascadeDelete\": false " + + " }, " + + " \"relatedInstanceList\": [{ " + + " \"relatedInstance\": { " + + " \"instanceId\": \"6dd0f8de-93c7-48a2-914b-1a8d58e0eb48\", " + + " \"modelInfo\": { " + + " \"modelInvariantId\": \"57e00952-0af7-4f0f-b19a-408a6f73c8df\", " + + " \"modelType\": \"service\", " + + " \"modelName\": \"ServicevWINIFREDPID298109\", " + + " \"modelVersion\": \"1.0\", " + + " \"modelVersionId\": \"fe6985cd-ea33-3346-ac12-ab121484a3fe\" " + + " } " + + " } " + + " } " + + " ] " + + " }, " + + " \"requestId\": \"d352c70d-5ef8-4977-9ea8-4c8cbe860422\", " + + " \"requestScope\": \"vnf\", " + + " \"requestStatus\": { " + + " \"percentProgress\": 100.0, " + + " \"requestState\": \"Some Unknown Value\", " + + " \"statusMessage\": \"Update Is In Progress\", " + + " \"finishTime\": \"Fri, 08 Sep 2017 19:34:33 GMT\" " + + " }, " + + " \"requestType\": \"updateInstance\", " + + " \"startTime\": \"<IN_PROGRESS_DATE>\", " + + " \"instanceReferences\": { " + + " \"serviceInstanceId\": \"6dd0f8de-93c7-48a2-914b-1a8d58e0eb48\", " + + " \"vnfInstanceId\": \"7c00cc1e-6425-4fc3-afc3-0289db288d4c\", " + + " \"requestorId\": \"ds828e\" " + + " } " + + " } " + + " } " + + " ] " + + "} "; + + mockForGetOrchestrationRequest(200, responseString); + + final ExternalComponentStatus msoStatus = msoBusinessLogic.probeComponent(); + + assertMsoStatus(msoStatus, true); + assertMetadata(msoStatus, 200, startsWith(responseString.substring(0, 400)), "my pretty url", equalTo("OK")); + } + + @Test + public void probeComponent_response200OkButEmptyPayload_shouldDescribeCorrectly() { + String responseString = "" + + "{ " + + " \"requestList\": []" + + "}"; + + mockForGetOrchestrationRequest(200, responseString); + + final ExternalComponentStatus msoStatus = msoBusinessLogic.probeComponent(); + + assertMsoStatus(msoStatus, true); + + assertMetadata(msoStatus, 200, equalTo(responseString), "my pretty url", containsString("OK")); + } + + @Test + public void probeComponent_response200OkButInvalidPayload_shouldDescribeCorrectly() { + String responseString = "this payload is an invalid json"; + + mockForGetOrchestrationRequest(200, responseString); + + final ExternalComponentStatus msoStatus = msoBusinessLogic.probeComponent(); + + assertMsoStatus(msoStatus, false); + + assertMetadata(msoStatus, 200, equalTo(responseString), "my pretty url", containsString("JsonParseException: Unrecognized token")); + } + + @Test + public void probeComponent_verifyResponse406() { + String responseString = "my raw data"; + + when(msoInterface.getOrchestrationRequest(any(), eq(true))).thenThrow( + new ExceptionWithRequestInfo(HttpMethod.GET, "my pretty url", responseString, 406, + new GenericUncheckedException( + new HttpException("Simulating as 406 was returned (200 or 202 expected)")))); + + final ExternalComponentStatus msoStatus = msoBusinessLogic.probeComponent(); + + assertMsoStatus(msoStatus, false); + + assertMetadata(msoStatus, 406, equalTo(responseString), "my pretty url", containsString("HttpException: Simulating as 406 was returned")); + } + + + @Test + public void probeComponent_throwNullPointerException_resultIsWithErrorMetadata() { + when(msoInterface.getOrchestrationRequest(any(), eq(true))).thenThrow(new NullPointerException()); + + final ExternalComponentStatus msoStatus = msoBusinessLogic.probeComponent(); + + MatcherAssert.assertThat(msoStatus.isAvailable(), is(false)); + MatcherAssert.assertThat(msoStatus.getComponent(), is(MSO)); + MatcherAssert.assertThat(msoStatus.getMetadata(), instanceOf(ErrorMetadata.class)); + + final ErrorMetadata metadata = ((ErrorMetadata) msoStatus.getMetadata()); + org.junit.Assert.assertThat(metadata.getDescription(), containsString("NullPointerException")); + } + + private void assertMsoStatus(ExternalComponentStatus msoStatus, boolean isAvailable) { + MatcherAssert.assertThat(msoStatus.isAvailable(), is(isAvailable)); + MatcherAssert.assertThat(msoStatus.getComponent(), is(MSO)); + MatcherAssert.assertThat(msoStatus.getMetadata(), instanceOf(HttpRequestMetadata.class)); + } + + private void assertMetadata(ExternalComponentStatus msoStatus, int httpCode, Matcher<String> rawData, String url, Matcher<String> descriptionMatcher) { + final HttpRequestMetadata metadata = ((HttpRequestMetadata) msoStatus.getMetadata()); + org.junit.Assert.assertThat(metadata.getHttpMethod(), equalTo(HttpMethod.GET)); + org.junit.Assert.assertThat(metadata.getHttpCode(), equalTo(httpCode)); + org.junit.Assert.assertThat(metadata.getUrl(), equalTo(url)); + org.junit.Assert.assertThat(metadata.getRawData(), rawData); + org.junit.Assert.assertThat(metadata.getDescription(), descriptionMatcher); + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java index 6cf7d487e..c47e7ce4e 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java @@ -46,6 +46,7 @@ import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.aai.HttpResponseWithRequestInfo; import org.onap.vid.client.SyncRestClient; import org.onap.vid.controller.MsoController; import org.onap.vid.controller.WebConfig; @@ -325,23 +326,6 @@ public class MsoRestClientNewTest { } @Test - public void testGetOrchestrationRequestsForDashboard() throws Exception { - MsoRestClientNew testSubject; - String t = ""; - String sourceId = ""; - String endpoint = ""; - RestObject restObject = null; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getOrchestrationRequest(t, sourceId, endpoint, restObject, true); - } catch (Exception e) { - } - } - - @Test public void testCompleteManualTask() throws Exception { MsoRestClientNew testSubject; RequestDetails requestDetails = null; diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java index e4e699d55..c91e88be7 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java @@ -38,6 +38,7 @@ import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicStatusLine; import org.mockito.Mock; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.aai.HttpResponseWithRequestInfo; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.changeManagement.WorkflowRequestDetail; import org.onap.vid.client.SyncRestClient; @@ -50,6 +51,7 @@ import org.onap.vid.mso.MsoUtil; import org.onap.vid.mso.RestObject; import org.onap.vid.mso.model.RequestReferences; import org.onap.vid.utils.SystemPropertiesWrapper; +import org.springframework.http.HttpMethod; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.testng.annotations.BeforeClass; @@ -375,17 +377,15 @@ public class MsoRestClientTest { @Test public void shouldProperlyGetOrchestrationRequest() { - // given - RestObject restObject = generateMockMsoRestObject(); - String endpoint = "testEndpoint"; HttpResponse<String> httpResponse = HttpResponse.fallback("testOkResponse"); - MsoResponseWrapper expectedResponse = MsoUtil.wrapResponse(httpResponse); + String expectedPath = baseUrl+endpoint; + HttpResponseWithRequestInfo<String> expectedResponse = new HttpResponseWithRequestInfo<>(httpResponse, expectedPath, HttpMethod.GET); - when( client.get( eq(baseUrl+endpoint),anyMap(),anyMap(),eq(String.class) ) ).thenReturn(httpResponse); + when( client.get( eq(expectedPath), anyMap(), anyMap(), eq(String.class) )).thenReturn(httpResponse); // when - MsoResponseWrapper response = restClient.getOrchestrationRequest(null,null,endpoint,restObject,true); + HttpResponseWithRequestInfo<String> response = restClient.getOrchestrationRequest(endpoint, true); // then assertThat(response).isEqualToComparingFieldByField(expectedResponse); diff --git a/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java index ff6b7f0b1..65712b423 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java @@ -21,27 +21,44 @@ package org.onap.vid.services; import static java.util.stream.Collectors.toMap; +import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.IsSame.sameInstance; import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.testng.AssertJUnit.assertTrue; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.joshworks.restclient.http.HttpResponse; +import java.io.ByteArrayInputStream; +import java.io.InputStream; import java.util.Map; import java.util.UUID; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.ws.rs.ProcessingException; +import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.reflect.FieldUtils; +import org.apache.commons.lang3.tuple.Triple; import org.mockito.Answers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.aai.HttpResponseWithRequestInfo; import org.onap.vid.asdc.AsdcCatalogException; import org.onap.vid.asdc.AsdcClient; import org.onap.vid.asdc.beans.Service; @@ -50,7 +67,10 @@ import org.onap.vid.model.ServiceModel; import org.onap.vid.model.probes.ExternalComponentStatus; import org.onap.vid.model.probes.HttpRequestMetadata; import org.onap.vid.properties.Features; +import org.onap.vid.testUtils.TestUtils; +import org.springframework.http.HttpMethod; import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.togglz.core.manager.FeatureManager; @@ -151,10 +171,7 @@ public class VidServiceImplTest { @Test public void shouldCheckConnectionToSdc() { - when(asdcClientMock.checkSDCConnectivity()).thenReturn(httpResponse); - when(httpResponse.isSuccessful()).thenReturn(true); - when(httpResponse.getBody()).thenReturn("sampleBody"); - + mockGoodSdcConnectivityResponse(); ExternalComponentStatus externalComponentStatus = vidService.probeComponent(); @@ -164,6 +181,12 @@ public class VidServiceImplTest { assertThat(metadata.getRawData(), is("sampleBody")); } + private void mockGoodSdcConnectivityResponse() { + when(asdcClientMock.checkSDCConnectivity()).thenReturn(httpResponse); + when(httpResponse.isSuccessful()).thenReturn(true); + when(httpResponse.getBody()).thenReturn("sampleBody"); + } + @Test public void shouldProperlyHandleNotWorkingSDCConnection(){ when(asdcClientMock.checkSDCConnectivity()).thenThrow(new RuntimeException("not working")); @@ -173,5 +196,129 @@ public class VidServiceImplTest { assertThat(externalComponentStatus.isAvailable(), is(false)); assertThat(externalComponentStatus.getMetadata().getDescription(),containsString("not working")); } + + @Test + public void shouldNotProbeBySdcConnectionIfProbeUuidConfigured() throws Exception { + TestUtils.testWithSystemProperty( + "probe.sdc.model.uuid", + UUID.randomUUID().toString(), + ()->{ + mockGoodSdcConnectivityResponse(); //no mocking for probeSdcByGettingModel + ExternalComponentStatus externalComponentStatus = vidService.probeComponent(); + assertThat(externalComponentStatus.isAvailable(), is(false)); + } + ); + } + + + @Test + public void givenProbeUUID_whenAsdcClientReturnNormal_thenProbeComponentReturnAvailableAnswer() throws Exception { + + final UUID uuidForProbe = UUID.randomUUID(); + final HttpResponse<InputStream> mockResponse = mock(HttpResponse.class); + responseSetupper(mockResponse, 200, new ByteArrayInputStream(RandomUtils.nextBytes(66000))); + when(asdcClientMock.getServiceInputStream(eq(uuidForProbe), eq(true))).thenReturn( + new HttpResponseWithRequestInfo(mockResponse, "my pretty url", HttpMethod.GET) + ); + + TestUtils.testWithSystemProperty( + "probe.sdc.model.uuid", + uuidForProbe.toString(), + ()-> { + + ExternalComponentStatus sdcComponentStatus = vidService.probeComponent(); + assertTrue(sdcComponentStatus.isAvailable()); + assertThat(sdcComponentStatus.getComponent(), is(ExternalComponentStatus.Component.SDC)); + assertThat(sdcComponentStatus.getMetadata().getDescription(), equalTo("OK")); + assertThat(sdcComponentStatus.getMetadata(), instanceOf(HttpRequestMetadata.class)); + + HttpRequestMetadata componentStatusMetadata = ((HttpRequestMetadata) sdcComponentStatus.getMetadata()); + assertThat(componentStatusMetadata.getHttpMethod(), equalTo(HttpMethod.GET)); + assertThat(componentStatusMetadata.getHttpCode(), equalTo(200)); + assertThat(componentStatusMetadata.getUrl(), equalTo("my pretty url")); + } + ); + } + + private static void responseSetupper(HttpResponse<InputStream> r, Integer httpCode, InputStream body) { + when(r.getStatus()).thenReturn(httpCode); + when(r.getRawBody()).thenReturn(body); + } + + @DataProvider + public static Object[][] executionResults() { + final BiConsumer<AsdcClient, HttpResponse<InputStream>> defaultClientSetup = (c, r) -> + when(c.getServiceInputStream(any(), eq(true))).thenReturn(new HttpResponseWithRequestInfo(r, "foo url", HttpMethod.GET)); + + final ByteArrayInputStream defaultResponseBody = new ByteArrayInputStream(RandomUtils.nextBytes(200)); + + return Stream.<Triple<HttpRequestMetadata, BiConsumer<AsdcClient, HttpResponse<InputStream>>, Consumer<HttpResponse<InputStream>>>>of( + + Triple.of( + new HttpRequestMetadata(null, 200, null, null, "IllegalStateException", 0), + defaultClientSetup, + r -> { + when(r.getStatus()).thenReturn(200); + when(r.getRawBody()).thenThrow(new IllegalStateException("good news for people who love bad news")); + } + ), + + Triple.of( + new HttpRequestMetadata(null, 200, null, null, "error reading model", 0), + defaultClientSetup, + r -> responseSetupper(r, 200, new ByteArrayInputStream(new byte[0])) + ), +// + Triple.of( + new HttpRequestMetadata(null, 200, null, null, "NullPointerException", 0), + defaultClientSetup, + r -> responseSetupper(r, 200, null) + ), +// + Triple.of( + new HttpRequestMetadata(null, 0, "bar url", null, "java.net.ConnectException: Connection refused", 0), + (c, r) -> + when(c.getServiceInputStream(any(), eq(true))).thenThrow(new ExceptionWithRequestInfo(HttpMethod.GET, "bar url", + new ProcessingException("java.net.ConnectException: Connection refused: connect"))), + r -> responseSetupper(r, 200, defaultResponseBody) + ), + + Triple.of( + new HttpRequestMetadata(null, 500, null, null, "error while retrieving model", 0), + defaultClientSetup, + r -> responseSetupper(r, 500, defaultResponseBody) + ), + + Triple.of( + new HttpRequestMetadata(null, 404, null, null, "updating vid probe configuration", 0), + defaultClientSetup, + r -> responseSetupper(r, 404, defaultResponseBody) + ) + + ).map(t -> ImmutableList.of(t.getLeft(), t.getMiddle(), t.getRight()).toArray()).collect(Collectors.toList()).toArray(new Object[][]{}); + } + + @Test(dataProvider = "executionResults") + public void whenClientReturnWithError_thenProbeSdcByGettingModelDescribes(HttpRequestMetadata expectedMetadata, + BiConsumer<AsdcClient, HttpResponse<InputStream>> clientSetup, + Consumer<HttpResponse<InputStream>> responseSetup) { + + final HttpResponse<InputStream> mockResponse = mock(HttpResponse.class); + clientSetup.accept(asdcClientMock, mockResponse); + responseSetup.accept(mockResponse); + + ExternalComponentStatus sdcComponentStatus = vidService.probeSdcByGettingModel(UUID.randomUUID()); + assertThat(sdcComponentStatus.getComponent(), is(ExternalComponentStatus.Component.SDC)); + assertThat(sdcComponentStatus.getMetadata(), instanceOf(HttpRequestMetadata.class)); + + HttpRequestMetadata componentStatusMetadata = ((HttpRequestMetadata) sdcComponentStatus.getMetadata()); + assertThat(componentStatusMetadata.getDescription(), containsString(defaultIfNull(expectedMetadata.getDescription(), "OK"))); + assertThat(componentStatusMetadata.getHttpMethod(), equalTo(defaultIfNull(expectedMetadata.getHttpMethod(), HttpMethod.GET))); + assertThat(componentStatusMetadata.getHttpCode(), equalTo(expectedMetadata.getHttpCode())); + assertThat(componentStatusMetadata.getUrl(), equalTo(defaultIfNull(expectedMetadata.getUrl(), "foo url"))); + + assertThat(sdcComponentStatus.isAvailable(), is(false)); + } + } diff --git a/vid-app-common/src/test/java/org/onap/vid/testUtils/StubServerUtil.java b/vid-app-common/src/test/java/org/onap/vid/testUtils/StubServerUtil.java index 3f5bf8163..848f80b1e 100644 --- a/vid-app-common/src/test/java/org/onap/vid/testUtils/StubServerUtil.java +++ b/vid-app-common/src/test/java/org/onap/vid/testUtils/StubServerUtil.java @@ -64,7 +64,7 @@ public class StubServerUtil { return String.format("%s://localhost:%s/%s", protocol, stubServer.getPort(), relativePath); } - public void prepareGetCall(String path, Action actionToReturn,Object returnObj, Action expectedAction, String contentType) throws JsonProcessingException { + public void prepareGetCall(String path, Action actionToReturn, Action expectedAction, String contentType) throws JsonProcessingException { whenHttp(stubServer) .match(Condition.get(path)) .then(expectedAction, actionToReturn, contentType(contentType)); @@ -72,7 +72,7 @@ public class StubServerUtil { public void prepareGetCall(String path, Object returnObj, Action expectedAction) throws JsonProcessingException { - prepareGetCall(path, jsonContent(returnObj),returnObj, expectedAction, APPLICATION_JSON); + prepareGetCall(path, jsonContent(returnObj), expectedAction, APPLICATION_JSON); } public void prepareDeleteCall(String path, Object returnObj, Action expectedAction) throws JsonProcessingException { |