diff options
Diffstat (limited to 'mso-api-handlers')
78 files changed, 1072 insertions, 1571 deletions
diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java index 4517811494..65c850a785 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java @@ -65,7 +65,8 @@ public class CamundaVIDRequest { @JsonProperty(CommonConstants.SERVICE_INSTANCE_ID_VARIABLE) private CamundaInput serviceInstanceId; - + @JsonProperty(CommonConstants.OPERATION_TYPE) + private CamundaInput operationType; @JsonProperty(CommonConstants.PNF_CORRELATION_ID) private CamundaInput pnfCorrelationId; @@ -194,6 +195,16 @@ public class CamundaVIDRequest { this.serviceInstanceId = serviceInstanceId; } + @JsonProperty(CommonConstants.OPERATION_TYPE) + public CamundaInput getOperationType() { + return operationType; + } + + @JsonProperty(CommonConstants.OPERATION_TYPE) + public void setOperationType(CamundaInput operationType) { + this.operationType = operationType; + } + @JsonProperty(CommonConstants.PNF_CORRELATION_ID) public CamundaInput getPnfCorrelationId() { return pnfCorrelationId; diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java index bc8af6e690..4bbfa1d067 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java @@ -25,84 +25,63 @@ package org.onap.so.apihandler.common; import java.io.IOException; -import java.util.UUID; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.DatatypeConverter; import org.apache.commons.lang3.StringUtils; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.apache.http.HttpStatus; import org.onap.so.apihandler.camundabeans.CamundaBooleanInput; import org.onap.so.apihandler.camundabeans.CamundaInput; import org.onap.so.apihandler.camundabeans.CamundaIntegerInput; import org.onap.so.apihandler.camundabeans.CamundaRequest; +import org.onap.so.apihandler.camundabeans.CamundaResponse; import org.onap.so.apihandler.camundabeans.CamundaVIDRequest; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; +import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException; +import org.onap.so.utils.CryptoUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; -public class CamundaClient extends RequestClient { +@Component +public class CamundaClient { private static Logger logger = LoggerFactory.getLogger(CamundaClient.class); - private static final String CAMUNDA_URL_MESAGE = "Camunda url is: "; - private static final String CAMUNDA_RESPONSE = "Response is: {}"; - private static final String AUTHORIZATION = "Authorization"; private static final String BASIC = "Basic "; - public CamundaClient() { - super(CommonConstants.CAMUNDA); - } + @Autowired + private RestTemplate restTemplate; + @Autowired + private Environment env; - @Override - public HttpResponse post(String camundaReqXML, String requestId, String requestTimeout, String schemaVersion, - String serviceInstanceId, String action) throws IOException { - HttpPost post = new HttpPost(url); - logger.debug(CAMUNDA_URL_MESAGE + url); - String jsonReq = wrapRequest(camundaReqXML, requestId, serviceInstanceId, requestTimeout, schemaVersion); + @Autowired + private ResponseHandler responseHandler; - StringEntity input = new StringEntity(jsonReq); - input.setContentType(CommonConstants.CONTENT_TYPE_JSON); + public ResponseEntity<String> post(String camundaReqXML, String requestId, String requestTimeout, + String schemaVersion, String serviceInstanceId, String action, String orchestrationURI) + throws ApiException { + String jsonReq = wrapRequest(camundaReqXML, requestId, serviceInstanceId, requestTimeout, schemaVersion, + orchestrationURI); logger.info("Camunda Request Content: {}", jsonReq); - - post.setEntity(input); - setupHeaders(post); - - HttpResponse response = client.execute(post); - logger.debug(CAMUNDA_RESPONSE, response); - - return response; - } - - - private void setupHeaders(HttpPost post) { - post.addHeader(ONAPLogConstants.Headers.REQUEST_ID, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); - post.addHeader(ONAPLogConstants.Headers.INVOCATION_ID, UUID.randomUUID().toString()); - addAuthorizationHeader(post); + return post(jsonReq, orchestrationURI); } - @Override - public HttpResponse post(String jsonReq) throws IOException { - HttpPost post = new HttpPost(url); - logger.debug(CAMUNDA_URL_MESAGE + url); - - StringEntity input = new StringEntity(jsonReq); - input.setContentType(CommonConstants.CONTENT_TYPE_JSON); - setupHeaders(post); - addAuthorizationHeader(post); - post.setEntity(input); - HttpResponse response = client.execute(post); - logger.debug(CAMUNDA_RESPONSE, response); - - return response; - } - - @Override - public HttpResponse post(RequestClientParameter parameterObject) throws IOException { - HttpPost post = new HttpPost(url); - logger.debug(CAMUNDA_URL_MESAGE + url); + public ResponseEntity<String> post(RequestClientParameter parameterObject, String orchestrationURI) + throws ApiException { String jsonReq = wrapVIDRequest(parameterObject.getRequestId(), parameterObject.isBaseVfModule(), parameterObject.getRecipeTimeout(), parameterObject.getRequestAction(), parameterObject.getServiceInstanceId(), parameterObject.getPnfCorrelationId(), @@ -111,28 +90,47 @@ public class CamundaClient extends RequestClient { parameterObject.getVnfType(), parameterObject.getVfModuleType(), parameterObject.getNetworkType(), parameterObject.getRequestDetails(), parameterObject.getApiVersion(), parameterObject.isaLaCarte(), parameterObject.getRequestUri(), parameterObject.getRecipeParamXsd(), - parameterObject.getInstanceGroupId(), parameterObject.isGenerateIdsOnly()); + parameterObject.getInstanceGroupId(), parameterObject.isGenerateIdsOnly(), + parameterObject.getOperationType()); - StringEntity input = new StringEntity(jsonReq); - input.setContentType(CommonConstants.CONTENT_TYPE_JSON); - setupHeaders(post); - addAuthorizationHeader(post); - post.setEntity(input); - HttpResponse response = client.execute(post); - logger.debug(CAMUNDA_RESPONSE, response); + return post(jsonReq, orchestrationURI); + } - return response; + public ResponseEntity<String> get(String url) throws ApiException { + url = env.getRequiredProperty(CommonConstants.CAMUNDA_URL) + url; + HttpEntity<?> requestEntity = new HttpEntity<>(setHeaders()); + try { + return restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class); + } catch (HttpStatusCodeException e) { + logger.error("Error returned from sending GET request to BPMN", e); + throw createBPMNFailureException(e); + } catch (ResourceAccessException e) { + logger.error("Error sending GET to BPMN", e); + ClientConnectionException clientException = new ClientConnectionException.Builder(url, + HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); + throw clientException; + } } - @Override - public HttpResponse get() { - return null; + public ResponseEntity<String> post(String jsonReq, String url) throws ApiException { + url = env.getRequiredProperty(CommonConstants.CAMUNDA_URL) + url; + HttpEntity<String> request = new HttpEntity<String>(jsonReq, setHeaders()); + try { + return restTemplate.postForEntity(url, request, String.class); + } catch (HttpStatusCodeException e) { + logger.error("Error returned after sending POST request to BPMN", e); + throw createBPMNFailureException(e); + } catch (ResourceAccessException e) { + logger.error("Error sending POST to BPMN", e); + ClientConnectionException clientException = new ClientConnectionException.Builder(url, + HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); + throw clientException; + } } protected String wrapRequest(String reqXML, String requestId, String serviceInstanceId, String requestTimeout, - String schemaVersion) { + String schemaVersion, String url) { String jsonReq = null; - try { CamundaRequest camundaRequest = new CamundaRequest(); CamundaInput camundaInput = new CamundaInput(); @@ -142,7 +140,7 @@ public class CamundaClient extends RequestClient { CamundaInput svcid = new CamundaInput(); CamundaInput timeout = new CamundaInput(); camundaInput.setValue(StringUtils.defaultString(reqXML)); - host.setValue(parseURL()); + host.setValue(CommonConstants.CAMUNDA_URL); schema.setValue(StringUtils.defaultString(schemaVersion)); reqid.setValue(requestId); svcid.setValue(serviceInstanceId); @@ -160,7 +158,7 @@ public class CamundaClient extends RequestClient { jsonReq = mapper.writeValueAsString(camundaRequest); logger.trace("request body is {}", jsonReq); } catch (Exception e) { - logger.error("Error in APIH Warp request", e); + logger.error("Error in APIH Wrap request", e); } return jsonReq; } @@ -170,7 +168,7 @@ public class CamundaClient extends RequestClient { String serviceInstanceId, String pnfCorrelationId, String vnfId, String vfModuleId, String volumeGroupId, String networkId, String configurationId, String serviceType, String vnfType, String vfModuleType, String networkType, String requestDetails, String apiVersion, boolean aLaCarte, String requestUri, - String paramXsd, String instanceGroupId, boolean generateIdsOnly) { + String paramXsd, String instanceGroupId, boolean generateIdsOnly, String operationType) { String jsonReq = null; try { @@ -182,6 +180,7 @@ public class CamundaClient extends RequestClient { CamundaIntegerInput recipeTimeoutInput = new CamundaIntegerInput(); CamundaInput requestActionInput = new CamundaInput(); CamundaInput serviceInstanceIdInput = new CamundaInput(); + CamundaInput operationTypeInput = new CamundaInput(); CamundaInput pnfCorrelationIdInput = new CamundaInput(); CamundaInput vnfIdInput = new CamundaInput(); CamundaInput vfModuleIdInput = new CamundaInput(); @@ -199,7 +198,7 @@ public class CamundaClient extends RequestClient { CamundaInput instanceGroupIdInput = new CamundaInput(); CamundaBooleanInput generateIds = new CamundaBooleanInput(); - + operationTypeInput.setValue(StringUtils.defaultString(operationType)); requestIdInput.setValue(StringUtils.defaultString(requestId)); isBaseVfModuleInput.setValue(isBaseVfModule); recipeTimeoutInput.setValue(recipeTimeout); @@ -231,6 +230,7 @@ public class CamundaClient extends RequestClient { camundaRequest.setRecipeTimeout(recipeTimeoutInput); camundaRequest.setRequestAction(requestActionInput); camundaRequest.setServiceInstanceId(serviceInstanceIdInput); + camundaRequest.setOperationType(operationTypeInput); camundaRequest.setPnfCorrelationId(pnfCorrelationIdInput); camundaRequest.setVnfId(vnfIdInput); camundaRequest.setVfModuleId(vfModuleIdInput); @@ -254,35 +254,53 @@ public class CamundaClient extends RequestClient { jsonReq = mapper.writeValueAsString(camundaRequest); logger.trace("request body is {}", jsonReq); } catch (Exception e) { - logger.error("Error in APIH Warp request", e); + logger.error("Error in wrapVIDRequest", e); } return jsonReq; } - private String parseURL() { - String[] parts = url.split(":"); - String host = ""; - if (parts.length >= 2) { - host = parts[1]; - if (host.length() > 2) { - host = host.substring(2); + protected HttpHeaders setHeaders() { + HttpHeaders headers = new HttpHeaders(); + List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>(); + acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON); + headers.setAccept(acceptableMediaTypes); + headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON); + headers.add(HttpHeaders.AUTHORIZATION, addAuthorizationHeader(env.getRequiredProperty("mso.camundaAuth"), + env.getRequiredProperty("mso.msoKey"))); + return headers; + } + + protected String addAuthorizationHeader(String auth, String msoKey) { + String basicAuth = null; + try { + String userCredentials = CryptoUtils.decrypt(auth, msoKey); + if (userCredentials != null) { + basicAuth = BASIC + DatatypeConverter.printBase64Binary(userCredentials.getBytes()); } + } catch (GeneralSecurityException e) { + logger.error("Security exception", e); } - return host; + return basicAuth; } - private void addAuthorizationHeader(HttpPost post) { - String encryptedCredentials; - if (props != null) { - encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH); - if (encryptedCredentials != null) { - String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, - props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP)); - if (userCredentials != null) { - post.addHeader(AUTHORIZATION, - BASIC + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes()))); - } - } + protected BPMNFailureException createBPMNFailureException(HttpStatusCodeException e) { + ObjectMapper mapper = new ObjectMapper(); + String responseText = null; + String message = null; + try { + CamundaResponse response = mapper.readValue(e.getResponseBodyAsString(), CamundaResponse.class); + responseText = response.getResponse(); + } catch (IOException ex) { + responseText = e.getResponseBodyAsString(); + } + message = String.valueOf(e.getStatusCode()); + if (responseText != null && !responseText.isEmpty()) { + message = message + " " + responseText; } + BPMNFailureException bpmnException = + new BPMNFailureException.Builder(message, responseHandler.setStatus(e.getStatusCode().value()), + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, e.getStatusCode()).build(); + return bpmnException; } + } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaTaskClient.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaTaskClient.java deleted file mode 100644 index d6d999b4b5..0000000000 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaTaskClient.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.apihandler.common; - -import java.io.IOException; -import javax.xml.bind.DatatypeConverter; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class CamundaTaskClient extends RequestClient { - private static Logger logger = LoggerFactory.getLogger(CamundaTaskClient.class); - - public CamundaTaskClient() { - super(CommonConstants.CAMUNDATASK); - } - - @Override - public HttpResponse post(String jsonReq) throws IOException { - HttpPost post = new HttpPost(url); - logger.debug("Camunda Task url is: {}", url); - - StringEntity input = new StringEntity(jsonReq); - input.setContentType(CommonConstants.CONTENT_TYPE_JSON); - - String encryptedCredentials; - if (props != null) { - encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH); - if (encryptedCredentials != null) { - String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, - props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP)); - if (userCredentials != null) { - post.addHeader("Authorization", - "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes())); - } - } - } - - post.setEntity(input); - return client.execute(post); - } - - @Override - public HttpResponse post(String camundaReqXML, String requestId, String requestTimeout, String schemaVersion, - String serviceInstanceId, String action) { - throw new UnsupportedOperationException("Method not supported."); - } - - @Override - public HttpResponse post(RequestClientParameter params) { - throw new UnsupportedOperationException("Method not supported."); - } - - @Override - public HttpResponse get() throws IOException { - HttpGet get = new HttpGet(url); - logger.debug("Camunda Task url is: {}", url); - String encryptedCredentials; - if (props != null) { - encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH); - if (encryptedCredentials != null) { - String userCredentials = getEncryptedPropValue(encryptedCredentials, CommonConstants.DEFAULT_BPEL_AUTH, - props.getProperty(CommonConstants.ENCRYPTION_KEY_PROP)); - if (userCredentials != null) { - get.addHeader("Authorization", - "Basic " + new String(DatatypeConverter.printBase64Binary(userCredentials.getBytes()))); - } - } - } - return client.execute(get); - } - -} diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CommonConstants.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CommonConstants.java index 6d2bbfc613..d667126afa 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CommonConstants.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CommonConstants.java @@ -54,6 +54,7 @@ public final class CommonConstants { public static final String RECIPE_TIMEOUT_VARIABLE = "recipeTimeout"; public static final String REQUEST_ACTION_VARIABLE = "requestAction"; public static final String SERVICE_INSTANCE_ID_VARIABLE = "serviceInstanceId"; + public static final String OPERATION_TYPE = "operationType"; public static final String PNF_CORRELATION_ID = "pnfCorrelationId"; public static final String VNF_ID_VARIABLE = "vnfId"; public static final String VF_MODULE_ID_VARIABLE = "vfModuleId"; diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java deleted file mode 100644 index 318b3ba5af..0000000000 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.apihandler.common; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.onap.so.utils.CryptoUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.env.Environment; - -public abstract class RequestClient { - private static Logger logger = LoggerFactory.getLogger(RequestClient.class); - protected Environment props; - protected String url; - protected HttpClient client; - private int type; - - public RequestClient(int type) { - this.type = type; - } - - public void setProps(Environment env) { - this.props = env; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getUrl() { - return url; - } - - public int getType() { - return type; - } - - public HttpClient getClient() { - return client; - } - - public void setClient(HttpClient client) { - this.client = client; - } - - public abstract HttpResponse post(String request, String requestId, String requestTimeout, String schemaVersion, - String serviceInstanceId, String action) throws IOException; - - public abstract HttpResponse post(String request) throws IOException; - - public abstract HttpResponse post(RequestClientParameter parameterObject) throws IOException; - - public abstract HttpResponse get() throws IOException; - - protected String getEncryptedPropValue(String prop, String defaultValue, String encryptionKey) { - try { - return CryptoUtils.decrypt(prop, encryptionKey); - } catch (GeneralSecurityException e) { - logger.debug("Security exception", e); - } - return defaultValue; - } -} diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java deleted file mode 100644 index c2ffa7e004..0000000000 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.apihandler.common; - -import org.apache.http.impl.client.HttpClientBuilder; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -public class RequestClientFactory { - - @Autowired - private Environment env; - - // based on URI, returns BPEL, CamundaTask or Camunda client - public RequestClient getRequestClient(String orchestrationURI) { - RequestClient retClient; - - String url; - if (orchestrationURI.contains(CommonConstants.TASK_SEARCH_STR)) { - url = env.getProperty(CommonConstants.CAMUNDA_URL) + orchestrationURI; - retClient = new CamundaTaskClient(); - } else { - url = env.getProperty(CommonConstants.CAMUNDA_URL) + orchestrationURI; - retClient = new CamundaClient(); - } - retClient.setClient(HttpClientBuilder.create().build()); - retClient.setProps(env); - retClient.setUrl(url); - return retClient; - - } - - public Environment getEnv() { - return env; - } - - public void setEnv(Environment env) { - this.env = env; - } - - - -} diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java index 806646022c..af1258e963 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java @@ -24,144 +24,55 @@ package org.onap.so.apihandler.common; import java.io.IOException; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; -import org.apache.http.util.EntityUtils; import org.onap.so.apihandler.camundabeans.CamundaResponse; -import org.onap.so.apihandlerinfra.Constants; -import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; -import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; -import org.onap.logging.filter.base.ErrorCode; -import org.onap.so.logger.MessageEnum; -import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import com.fasterxml.jackson.databind.ObjectMapper; -public class ResponseHandler { - private CamundaResponse response; - private int status; - private String responseBody = ""; - private HttpResponse httpResponse; - private int type; +@Component +public class ResponseHandler { private static Logger logger = LoggerFactory.getLogger(ResponseHandler.class); - public ResponseHandler(HttpResponse httpResponse, int type) throws ApiException { - this.httpResponse = httpResponse; - this.type = type; - parseResponse(); - } - - - private void parseResponse() throws ApiException { - int statusCode = httpResponse.getStatusLine().getStatusCode(); - status = setStatus(statusCode); - if (type == CommonConstants.CAMUNDA) { - parseCamunda(); - } else if (type == CommonConstants.CAMUNDATASK) { - parseCamundaTask(); - } else { - parseBpel(); - } - - } - - - - private void parseCamunda() throws ApiException { - try { - HttpEntity entity = httpResponse.getEntity(); - responseBody = EntityUtils.toString(entity); - } catch (IOException e) { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - throw new ValidateException.Builder("IOException getting Camunda response body", HttpStatus.SC_BAD_REQUEST, - ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); - } - + public CamundaResponse getCamundaResponse(ResponseEntity<String> camundaResponse) throws ValidateException { + String responseBody = camundaResponse.getBody(); + CamundaResponse response = null; ObjectMapper mapper = new ObjectMapper(); try { response = mapper.readValue(responseBody, CamundaResponse.class); - } catch (IOException e) { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - throw new ValidateException.Builder("Cannot parse Camunda Response", HttpStatus.SC_BAD_REQUEST, - ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); - } - if (response != null) { - responseBody = response.getResponse(); - } else { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_ERROR_FROM_BPEL_SERVER, ErrorCode.BusinessProcessError) - .targetEntity("Camunda").targetServiceName("parseCamunda").build(); - BPMNFailureException bpmnFailureException = - new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL) - .errorInfo(errorLoggerInfo).build(); + } catch (IOException | NullPointerException e) { + logger.error("Cannot parse Camunda Response: ", e); + throw new ValidateException.Builder( + "Cannot parse Camunda ResponseBody. BPMN HTTP status: " + camundaResponse.getStatusCodeValue(), + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).build(); } + return response; } - private void parseBpel() throws ApiException { - - HttpEntity bpelEntity = httpResponse.getEntity(); - - try { - if (bpelEntity != null) { - responseBody = EntityUtils.toString(bpelEntity); - - } - } catch (IOException e) { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - - throw new ValidateException.Builder("Could not convert BPEL response to string", HttpStatus.SC_BAD_REQUEST, - ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); - } + public void acceptedResponse(ResponseEntity<String> response) throws BPMNFailureException { + int status = setStatus(response.getStatusCodeValue()); if (status != HttpStatus.SC_ACCEPTED) { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_ERROR_FROM_BPEL_SERVER, ErrorCode.BusinessProcessError) - .targetEntity("BPEL").targetServiceName("parseBpel").build(); - - throw new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL) - .errorInfo(errorLoggerInfo).build(); + logger.info("Camunda did not return a valid response"); + throw new BPMNFailureException.Builder(String.valueOf(status), HttpStatus.SC_INTERNAL_SERVER_ERROR, + ErrorNumbers.ERROR_FROM_BPEL).build(); } - } - private void parseCamundaTask() throws ApiException { - - HttpEntity camundataskEntity = httpResponse.getEntity(); - - try { - if (camundataskEntity != null) { - responseBody = EntityUtils.toString(camundataskEntity); - } - } catch (IOException e) { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - - throw new ValidateException.Builder("Could not convert CamundaTask response to string", - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo) - .build(); - } + public void acceptedOrNoContentResponse(ResponseEntity<String> response) throws BPMNFailureException { + int status = setStatus(response.getStatusCodeValue()); if (status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_ACCEPTED) { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_ERROR_FROM_BPEL_SERVER, ErrorCode.BusinessProcessError) - .targetEntity("CAMUNDATASK").targetServiceName("parseCamundaTask").build(); - - throw new BPMNFailureException.Builder(String.valueOf(status), status, ErrorNumbers.ERROR_FROM_BPEL) - .errorInfo(errorLoggerInfo).build(); + logger.info("Camunda did not return a valid response"); + throw new BPMNFailureException.Builder(String.valueOf(status), HttpStatus.SC_INTERNAL_SERVER_ERROR, + ErrorNumbers.ERROR_FROM_BPEL).build(); } - } - private int setStatus(int statusCode) { + public int setStatus(int statusCode) { int httpStatus; switch (statusCode) { case HttpStatus.SC_ACCEPTED: @@ -193,30 +104,4 @@ public class ResponseHandler { } return httpStatus; } - - - public CamundaResponse getResponse() { - return response; - } - - - public void setResponse(CamundaResponse response) { - this.response = response; - } - - - public String getResponseBody() { - return responseBody; - } - - - public void setResponseBody(String responseBody) { - this.responseBody = responseBody; - } - - - public int getStatus() { - return status; - } - } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java index ab2ce10690..2ca18de9e3 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java @@ -23,6 +23,7 @@ package org.onap.so.apihandlerinfra.exceptions; import java.util.List; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; +import org.springframework.http.HttpStatus; public abstract class ApiException extends Exception { /** @@ -32,17 +33,16 @@ public abstract class ApiException extends Exception { private int httpResponseCode = 500; private String messageID; private ErrorLoggerInfo errorLoggerInfo; - + private HttpStatus originalHttpResponseCode; private List<String> variables; public ApiException(Builder builder) { super(builder.message, builder.cause); - this.httpResponseCode = builder.httpResponseCode; this.messageID = builder.messageID; this.variables = builder.variables; this.errorLoggerInfo = builder.errorLoggerInfo; - this.variables = builder.variables; + this.originalHttpResponseCode = builder.originalHttpResponseCode; } public ApiException(String message, Throwable cause) { @@ -54,6 +54,12 @@ public abstract class ApiException extends Exception { this.httpResponseCode = httpResponseCode; } + public ApiException(String message, int httpResponseCode, HttpStatus original) { + super(message); + this.httpResponseCode = httpResponseCode; + this.originalHttpResponseCode = original; + } + public ApiException(String message) { super(message); } @@ -75,13 +81,17 @@ public abstract class ApiException extends Exception { return variables; } + public HttpStatus getOriginalHttpResponseCode() { + return originalHttpResponseCode; + } + public static class Builder<T extends Builder<T>> { private String message; private Throwable cause = null; private int httpResponseCode; private String messageID; + private HttpStatus originalHttpResponseCode; private ErrorLoggerInfo errorLoggerInfo = null; - private List<String> variables = null; public Builder(String message, int httpResponseCode, String messageID) { @@ -90,6 +100,13 @@ public abstract class ApiException extends Exception { this.messageID = messageID; } + public Builder(String message, int httpResponseCode, String messageID, HttpStatus originalHttpResponseCode) { + this.message = message; + this.httpResponseCode = httpResponseCode; + this.messageID = messageID; + this.originalHttpResponseCode(originalHttpResponseCode); + } + public T message(String message) { this.message = message; return (T) this; @@ -119,5 +136,10 @@ public abstract class ApiException extends Exception { this.variables = variables; return (T) this; } + + public T originalHttpResponseCode(HttpStatus originalHttpResponseCode) { + this.originalHttpResponseCode = originalHttpResponseCode; + return (T) this; + } } } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java index 62f39d9148..696a518ceb 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java @@ -22,14 +22,9 @@ package org.onap.so.apihandlerinfra.exceptions; -import java.io.StringWriter; -import java.util.ArrayList; import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; @@ -41,10 +36,7 @@ import org.onap.so.serviceinstancebeans.RequestError; import org.onap.so.serviceinstancebeans.ServiceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; @Provider public class ApiExceptionMapper implements ExceptionMapper<ApiException> { diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/BPMNFailureException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/BPMNFailureException.java index 97d46bd6f1..0d2b9be93a 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/BPMNFailureException.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/BPMNFailureException.java @@ -20,6 +20,8 @@ package org.onap.so.apihandlerinfra.exceptions; +import org.springframework.http.HttpStatus; + public class BPMNFailureException extends ApiException { private static final String bpmnFailMessage = "Request Failed due to BPEL error with HTTP Status = $HTTPSTATUS"; @@ -35,6 +37,12 @@ public class BPMNFailureException extends ApiException { super(bpmnFailMessage.replaceAll("\\$HTTPSTATUS", message), httpResponseCode, messageID); } + public Builder(String message, int httpResponseCode, String messageID, HttpStatus originalHttpResponseCode) { + super(bpmnFailMessage.replaceAll("\\$HTTPSTATUS", message), httpResponseCode, messageID, + originalHttpResponseCode); + } + + public BPMNFailureException build() { return new BPMNFailureException(this); } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ClientConnectionException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ClientConnectionException.java index 4af5289ad7..9ef2072fef 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ClientConnectionException.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ClientConnectionException.java @@ -26,7 +26,7 @@ public class ClientConnectionException extends ApiException { * */ private static final long serialVersionUID = 1L; - private static final String clientFailMessage = "Client from $URL failed to connect"; + private static final String clientFailMessage = "Client from $URL failed to connect or respond"; private ClientConnectionException(Builder builder) { super(builder); diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java index 94c62a9689..e0f4fe3f7a 100644 --- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java +++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java @@ -24,109 +24,61 @@ package org.onap.so.apihandler.common; -import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.ProtocolVersion; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.message.BasicHttpResponse; -import org.apache.http.message.BasicStatusLine; -import org.junit.Assert; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; -import org.mockito.ArgumentCaptor; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; +import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException; import org.skyscreamer.jsonassert.JSONAssert; -import org.springframework.mock.env.MockEnvironment; -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.databind.JsonMappingException; - -/** - * This class implements test methods of Camunda Beans. - * - * - */ +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; + +@RunWith(MockitoJUnitRunner.class) public class CamundaClientTest { - - @Mock - private HttpClient mockHttpClient; - private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void tesCamundaPost() throws JsonGenerationException, JsonMappingException, IOException { - - - String responseBody = - "{\"links\":[{\"method\":\"GET\",\"href\":\"http://localhost:9080/engine-rest/process-instance/2047c658-37ae-11e5-9505-7a1020524153\",\"rel\":\"self\"}],\"id\":\"2047c658-37ae-11e5-9505-7a1020524153\",\"definitionId\":\"dummy:10:73298961-37ad-11e5-9505-7a1020524153\",\"businessKey\":null,\"caseInstanceId\":null,\"ended\":true,\"suspended\":false}"; - - HttpResponse mockResponse = createResponse(200, responseBody); - mockHttpClient = Mockito.mock(HttpClient.class); - ArgumentCaptor<HttpPost> httpPostCaptor = ArgumentCaptor.forClass(HttpPost.class); - Mockito.when(mockHttpClient.execute(Mockito.any(HttpPost.class))).thenReturn(mockResponse); - - String reqXML = "<xml>test</xml>"; - String orchestrationURI = "/engine-rest/process-definition/key/dummy/start"; - MockEnvironment environment = new MockEnvironment(); - - environment.setProperty("mso.camundaUR", "yourValue1"); - environment.setProperty("mso.camundaAuth", - "E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE"); - environment.setProperty("org.onap.so.adapters.network.encryptionKey", "aa3871669d893c7fb8abbcda31b88b4f"); - - - RequestClientFactory reqClientFactory = new RequestClientFactory(); - reqClientFactory.setEnv(environment); - RequestClient requestClient = reqClientFactory.getRequestClient(orchestrationURI); - - requestClient.setClient(mockHttpClient); - HttpResponse response = requestClient.post(reqXML, "reqId", "timeout", "version", null, null); + private RestTemplate restTemplate; + @Mock + private Environment env; - int statusCode = response.getStatusLine().getStatusCode(); - assertEquals(requestClient.getType(), CommonConstants.CAMUNDA); - assertEquals(statusCode, HttpStatus.SC_OK); + @Spy + private ResponseHandler responseHandler; + @Spy + @InjectMocks + private CamundaClient client; - requestClient = reqClientFactory.getRequestClient(orchestrationURI); - requestClient.setClient(mockHttpClient); - response = requestClient.post(null, "reqId", null, null, null, null); - assertEquals(requestClient.getType(), CommonConstants.CAMUNDA); - assertEquals(statusCode, HttpStatus.SC_OK); - verify(mockHttpClient, times(2)).execute(httpPostCaptor.capture()); - assertThat(httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)).isNotEmpty(); - Assert.assertEquals("Basic YXBpaEJwbW46Y2FtdW5kYS1SMTUxMiE=", - httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)[0].getValue()); - } + @Rule + public ExpectedException thrown = ExpectedException.none(); - private HttpResponse createResponse(int respStatus, String respBody) { - HttpResponse response = - new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), respStatus, "")); - response.setStatusCode(respStatus); - try { - response.setEntity(new StringEntity(respBody)); - response.setHeader("Content-Type", "application/json"); - } catch (Exception e) { - e.printStackTrace(); - } - return response; + @Before + public void setup() { + when(env.getRequiredProperty("mso.camundaAuth")) + .thenReturn("015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"); + when(env.getRequiredProperty("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7"); + when(env.getRequiredProperty("mso.camundaURL")).thenReturn("http://localhost:8080"); } public String inputStream(String JsonInput) throws IOException { @@ -136,10 +88,37 @@ public class CamundaClientTest { } @Test - public void wrapVIDRequestTest() throws IOException { - CamundaClient testClient = new CamundaClient(); - testClient.setUrl("/mso/async/services/CreateGenericALaCarteServiceInstance"); + public void createBPMNFailureExceptionNoResponseBodyTest() { + HttpServerErrorException e = new HttpServerErrorException(HttpStatus.NOT_FOUND); + BPMNFailureException ex = client.createBPMNFailureException(e); + assertEquals(HttpStatus.NOT_IMPLEMENTED.value(), ex.getHttpResponseCode()); + assertEquals("Request Failed due to BPEL error with HTTP Status = 404 NOT_FOUND", ex.getMessage()); + } + + @Test + public void createBPMNFailureExceptionWithCamundaResponseTest() throws IOException { + HttpClientErrorException e = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, null, + inputStream("/CamundaFailure.json").getBytes(), null); + BPMNFailureException ex = client.createBPMNFailureException(e); + assertEquals(HttpStatus.BAD_GATEWAY.value(), ex.getHttpResponseCode()); + assertEquals( + "Request Failed due to BPEL error with HTTP Status = 500 INTERNAL_SERVER_ERROR <aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>Exception in create execution list 500 </aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>", + ex.getMessage()); + } + + @Test + public void createBPMNFailureExceptionTest() throws IOException { + String response = "Request failed"; + HttpClientErrorException e = + new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, null, response.getBytes(), null); + BPMNFailureException ex = client.createBPMNFailureException(e); + assertEquals(HttpStatus.BAD_GATEWAY.value(), ex.getHttpResponseCode()); + assertEquals("Request Failed due to BPEL error with HTTP Status = 500 INTERNAL_SERVER_ERROR Request failed", + ex.getMessage()); + } + @Test + public void wrapVIDRequestTest() throws IOException { String requestId = "f7ce78bb-423b-11e7-93f8-0050569a796"; boolean isBaseVfModule = true; int recipeTimeout = 10000; @@ -160,50 +139,55 @@ public class CamundaClientTest { boolean aLaCarte = true; String requestUri = "v7/serviceInstances/assign"; String instanceGroupId = "ff305d54-75b4-431b-adb2-eb6b9e5ff000"; + String operationType = "activation"; - String testResult = testClient.wrapVIDRequest(requestId, isBaseVfModule, recipeTimeout, requestAction, + String testResult = client.wrapVIDRequest(requestId, isBaseVfModule, recipeTimeout, requestAction, serviceInstanceId, pnfCorrelationId, vnfId, vfModuleId, volumeGroupId, networkId, configurationId, serviceType, vnfType, vfModuleType, networkType, requestDetails, apiVersion, aLaCarte, requestUri, "", - instanceGroupId, false); + instanceGroupId, false, operationType); String expected = inputStream("/WrappedVIDRequest.json"); JSONAssert.assertEquals(expected, testResult, false); } @Test - public void testPost() throws Exception { - CamundaClient testClient = new CamundaClient(); - String orchestrationURI = "/engine-rest/process-definition/key/dummy/start"; - MockEnvironment environment = new MockEnvironment(); - - environment.setProperty("mso.camundaUR", "yourValue1"); - testClient.setProps(environment); - testClient.setClient(mockHttpClient); - - testClient.setUrl(orchestrationURI); - - String responseBody = - "{\"links\":[{\"method\":\"GET\",\"href\":\"http://localhost:9080/engine-rest/process-instance/2047c658-37ae-11e5-9505-7a1020524153\",\"rel\":\"self\"}],\"id\":\"2047c658-37ae-11e5-9505-7a1020524153\",\"definitionId\":\"dummy:10:73298961-37ad-11e5-9505-7a1020524153\",\"businessKey\":null,\"caseInstanceId\":null,\"ended\":true,\"suspended\":false}"; - assertNull(testClient.post(responseBody)); - + public void getClientConnectionExceptionTest() throws ApiException { + doThrow(ResourceAccessException.class).when(restTemplate).exchange(eq("http://localhost:8080/path"), + eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class)); + thrown.expect(ClientConnectionException.class); + thrown.expectMessage("Client from http://localhost:8080/path failed to connect or respond"); + client.get("/path"); } @Test - public void testPostWithRequestClientParameter() throws Exception { - CamundaClient testClient = new CamundaClient(); - String orchestrationURI = "/engine-rest/process-definition/key/dummy/start"; - HttpResponse mockResponse = createResponse(200, "{}"); - mockHttpClient = Mockito.mock(HttpClient.class); - Mockito.when(mockHttpClient.execute(Mockito.any(HttpPost.class))).thenReturn(mockResponse); - - testClient.setClient(mockHttpClient); - testClient.setUrl(orchestrationURI); - - HttpResponse response = testClient.post(new RequestClientParameter.Builder().build()); - - assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + public void postClientConnectionExceptionTest() throws ApiException, IOException { + String jsonReq = inputStream("/WrappedVIDRequest.json"); + doThrow(ResourceAccessException.class).when(restTemplate).postForEntity(eq("http://localhost:8080/path"), + any(HttpEntity.class), eq(String.class)); + thrown.expect(ClientConnectionException.class); + thrown.expectMessage("Client from http://localhost:8080/path failed to connect or respond"); + client.post(jsonReq, "/path"); + } + @Test + public void getHttpStatusCodeExceptionTest() throws ApiException { + HttpServerErrorException e = new HttpServerErrorException(HttpStatus.NOT_FOUND); + doThrow(e).when(restTemplate).exchange(eq("http://localhost:8080/path"), eq(HttpMethod.GET), + any(HttpEntity.class), eq(String.class)); + thrown.expect(BPMNFailureException.class); + thrown.expectMessage("Request Failed due to BPEL error with HTTP Status = 404 NOT_FOUND"); + client.get("/path"); } + @Test + public void postHttpStatusCodeExceptionTest() throws ApiException, IOException { + HttpServerErrorException e = new HttpServerErrorException(HttpStatus.NOT_FOUND); + String jsonReq = inputStream("/WrappedVIDRequest.json"); + doThrow(e).when(restTemplate).postForEntity(eq("http://localhost:8080/path"), any(HttpEntity.class), + eq(String.class)); + thrown.expect(BPMNFailureException.class); + thrown.expectMessage("Request Failed due to BPEL error with HTTP Status = 404 NOT_FOUND"); + client.post(jsonReq, "/path"); + } } diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaTaskClientTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaTaskClientTest.java deleted file mode 100644 index 9e9ab6048e..0000000000 --- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaTaskClientTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.apihandler.common; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import org.apache.http.HttpEntity; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpRequestBase; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.core.env.Environment; - -@RunWith(MockitoJUnitRunner.class) -public class CamundaTaskClientTest { - - @Mock - private Environment env; - private CamundaTaskClient testedObject = new CamundaTaskClient(); - private HttpClient httpClientMock; - private static final String JSON_REQUEST = "{\"value1\": \"aaa\",\"value2\": \"bbb\"}"; - private static final String URL_SCHEMA = "http"; - private static final String HOST = "testhost"; - private static final int PORT = 1234; - private static final String URL_PATH = "/requestMethodSuccessful"; - private static final String URL = URL_SCHEMA + "://" + HOST + ":" + PORT + URL_PATH; - private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; - - @Before - public void init() { - when(env.getProperty(eq(CommonConstants.CAMUNDA_AUTH))).thenReturn( - "E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE"); - when(env.getProperty(eq(CommonConstants.ENCRYPTION_KEY_PROP))).thenReturn("aa3871669d893c7fb8abbcda31b88b4f"); - testedObject = new CamundaTaskClient(); - httpClientMock = mock(HttpClient.class); - testedObject.setClient(httpClientMock); - testedObject.setUrl(URL); - } - - @Test - public void postMethodSuccessful() throws IOException { - ArgumentCaptor<HttpPost> httpPostCaptor = ArgumentCaptor.forClass(HttpPost.class); - testedObject.post(JSON_REQUEST); - verify(httpClientMock).execute(httpPostCaptor.capture()); - checkUri(httpPostCaptor.getValue()); - assertThat(httpPostCaptor.getValue().getEntity().getContentType().getValue()) - .isEqualTo(CommonConstants.CONTENT_TYPE_JSON); - assertThat(getJsonFromEntity(httpPostCaptor.getValue().getEntity())).isEqualTo(JSON_REQUEST); - } - - @Test - public void postMethodSuccessfulWithCredentials() throws IOException { - ArgumentCaptor<HttpPost> httpPostCaptor = ArgumentCaptor.forClass(HttpPost.class); - testedObject.setProps(env); - testedObject.post(JSON_REQUEST); - verify(httpClientMock).execute(httpPostCaptor.capture()); - assertThat(httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)).isNotEmpty(); - Assert.assertEquals("Basic YXBpaEJwbW46Y2FtdW5kYS1SMTUxMiE=", - httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)[0].getValue()); - } - - @Test - public void getMethodSuccessful() throws IOException { - ArgumentCaptor<HttpGet> httpGetCaptor = ArgumentCaptor.forClass(HttpGet.class); - testedObject.get(); - verify(httpClientMock).execute(httpGetCaptor.capture()); - checkUri(httpGetCaptor.getValue()); - } - - @Test - public void getMethodSuccessfulWithCredentials() throws IOException { - ArgumentCaptor<HttpGet> httpGetCaptor = ArgumentCaptor.forClass(HttpGet.class); - testedObject.setUrl(URL); - testedObject.setProps(env); - testedObject.get(); - verify(httpClientMock).execute(httpGetCaptor.capture()); - assertThat(httpGetCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)).isNotEmpty(); - Assert.assertEquals("Basic YXBpaEJwbW46Y2FtdW5kYS1SMTUxMiE=", - httpGetCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)[0].getValue()); - } - - @Test(expected = UnsupportedOperationException.class) - public void postMethodUnsupported() { - testedObject.post("", "", "", "", "", ""); - } - - @Test(expected = UnsupportedOperationException.class) - public void postMethodUnsupported2() { - testedObject.post(new RequestClientParameter.Builder().build()); - } - - private void checkUri(HttpRequestBase httpRequestBase) { - assertThat(httpRequestBase.getURI().getScheme()).isEqualTo(URL_SCHEMA); - assertThat(httpRequestBase.getURI().getHost()).isEqualTo(HOST); - assertThat(httpRequestBase.getURI().getPort()).isEqualTo(PORT); - assertThat(httpRequestBase.getURI().getPath()).isEqualTo(URL_PATH); - } - - private String getJsonFromEntity(HttpEntity httpEntity) throws IOException { - BufferedReader rd = new BufferedReader(new InputStreamReader(httpEntity.getContent())); - StringBuilder result = new StringBuilder(); - String line; - while ((line = rd.readLine()) != null) { - result.append(line); - } - return result.toString(); - } - -} diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/RequestClientTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/RequestClientTest.java deleted file mode 100644 index 86b12ae8f6..0000000000 --- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/RequestClientTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (c) 2019 Samsung. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.so.apihandler.common; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class RequestClientTest { - - private static final String ENCRYPTION_KEY = "aa3871669d893c7fb8abbcda31b88b4f"; - - private RequestClient requestClient; - - @Before - public void init() { - requestClient = Mockito.mock(RequestClient.class, Mockito.CALLS_REAL_METHODS); - } - - @Test - public void getEncryptedPropValueWithSuccess() { - - String encryptedValue = requestClient.getEncryptedPropValue( - "E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE", - "defaultValue", ENCRYPTION_KEY); - - Assert.assertEquals("apihBpmn:camunda-R1512!", encryptedValue); - } - - @Test - public void getDefaultEncryptedPropValue() { - - String encryptedValue = - requestClient.getEncryptedPropValue("012345678901234567890123456789", "defaultValue", ENCRYPTION_KEY); - - Assert.assertEquals("defaultValue", encryptedValue); - } - -} diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/ResponseHandlerTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/ResponseHandlerTest.java index 2095a9117d..e6f7a3663a 100644 --- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/ResponseHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/ResponseHandlerTest.java @@ -23,122 +23,42 @@ package org.onap.so.apihandler.common; -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.ProtocolVersion; -import org.apache.http.entity.StringEntity; -import org.apache.http.message.BasicHttpResponse; -import org.apache.http.message.BasicStatusLine; +import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.onap.so.apihandlerinfra.exceptions.ApiException; -import org.onap.so.apihandlerinfra.exceptions.ValidateException; - -/** - * This class implements test methods of CamundaResoponseHandler. - * - * - */ +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; +import org.springframework.http.ResponseEntity; + +@RunWith(MockitoJUnitRunner.class) public class ResponseHandlerTest { + @Spy + @InjectMocks + private ResponseHandler responseHandler; + @Rule public ExpectedException thrown = ExpectedException.none(); @Test - public void tesParseCamundaResponse() throws ApiException { - // String body - // ="{\"links\":[{\"method\":\"GET\",\"href\":\"http://localhost:9080/engine-rest/process-instance/2047c658-37ae-11e5-9505-7a1020524153\",\"rel\":\"self\"}],\"id\":\"2047c658-37ae-11e5-9505-7a1020524153\",\"definitionId\":\"dummy:10:73298961-37ad-11e5-9505-7a1020524153\",\"businessKey\":null,\"caseInstanceId\":null,\"ended\":true,\"suspended\":false}"; - - String body = "{ \"response\": \"<xml>xml</xml>\"," + "\"messageCode\": 200," - + "\"message\": \"Successfully started the process\"}"; - - HttpResponse response = createResponse(200, body, "application/json"); - - ResponseHandler respHandler = new ResponseHandler(response, 1); - - int status = respHandler.getStatus(); - assertEquals(status, HttpStatus.SC_ACCEPTED); - assertEquals(respHandler.getResponse().getMessage(), "Successfully started the process"); - - } - - @Test - public void tesParseCamundaResponseForCamundaTaskType() throws ApiException { - String body = "{ \"response\": \"<xml>xml</xml>\"," + "\"messageCode\": 200," - + "\"message\": \"Successfully started the process\"}"; - - HttpResponse response = createResponse(200, body, "application/json"); - - ResponseHandler respHandler = new ResponseHandler(response, 2); - - int status = respHandler.getStatus(); - assertEquals(status, HttpStatus.SC_ACCEPTED); - assertEquals(respHandler.getResponseBody(), body); - - } - - @Test - public void tesParseBpelResponse() throws ApiException { - String body = "<test:service-response xmlns:test=\"http://org.onap/so/test\">" - + "<test:request-id>req5</test:request-id>" + "<test:request-action>test</test:request-action>" - + "<test:source>test</test:source>" + "<test:ack-final-indicator>n</test:ack-final-indicator>" - + "</test:service-response>"; - - HttpResponse response = createResponse(200, body, "text/xml"); - - ResponseHandler respHandler = new ResponseHandler(response, 0); - - int status = respHandler.getStatus(); - assertEquals(status, HttpStatus.SC_ACCEPTED); - assertTrue(respHandler.getResponseBody() != null); - } - - @Test - public void tesMappingErrorResponse() throws ApiException { - thrown.expect(ValidateException.class); - thrown.expectMessage(startsWith("Cannot parse Camunda Response")); - thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST))); - thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); - - HttpResponse response = createResponse(HttpStatus.SC_NOT_FOUND, "<html>error</html>", "text/html"); - ResponseHandler respHandler = new ResponseHandler(response, 1); - - int status = respHandler.getStatus(); - - assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, status); - + public void acceptedResponseTest() throws IOException, BPMNFailureException { + ResponseEntity<String> camundaResponse = ResponseEntity.noContent().build(); + thrown.expect(BPMNFailureException.class); + thrown.expectMessage("Request Failed due to BPEL error with HTTP Status = 204"); + responseHandler.acceptedResponse(camundaResponse); } @Test - public void tesGenricErrorResponse() throws ApiException { - - String body = "{ \"response\": \"<xml>xml</xml>\"," + "\"messageCode\": 500," - + "\"message\": \"Something went wrong\"}"; - - HttpResponse response = createResponse(500, body, "application/json"); - ResponseHandler respHandler = new ResponseHandler(response, 1); - int status = respHandler.getStatus(); - assertEquals(status, HttpStatus.SC_BAD_GATEWAY); - assertEquals(respHandler.getResponse().getMessage(), "Something went wrong"); - } + public void acceptedOrNoContentResponseTest() throws IOException, BPMNFailureException { + ResponseEntity<String> camundaResponse = ResponseEntity.badRequest().build(); + thrown.expect(BPMNFailureException.class); + thrown.expectMessage("Request Failed due to BPEL error with HTTP Status = 400"); + responseHandler.acceptedOrNoContentResponse(camundaResponse); - private HttpResponse createResponse(int respStatus, String respBody, String contentType) { - HttpResponse response = - new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), respStatus, "")); - response.setStatusCode(respStatus); - try { - response.setEntity(new StringEntity(respBody)); - response.setHeader("Content-Type", contentType); - } catch (Exception e) { - e.printStackTrace(); - } - return response; } } diff --git a/mso-api-handlers/mso-api-handler-common/src/test/resources/CamundaClientTest/CamundaFailure.json b/mso-api-handlers/mso-api-handler-common/src/test/resources/CamundaClientTest/CamundaFailure.json new file mode 100644 index 0000000000..2d9e3ddef8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-common/src/test/resources/CamundaClientTest/CamundaFailure.json @@ -0,0 +1,7 @@ +{ + "response":"<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>Exception in create execution list 500 </aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>", + "message":"Fail", + "processInstanceID":"4b33ca85-5860-11e8-ae53-0a580ae94342", + "variables":null, + "messageCode":500 +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-common/src/test/resources/CamundaClientTest/WrappedVIDRequest.json b/mso-api-handlers/mso-api-handler-common/src/test/resources/CamundaClientTest/WrappedVIDRequest.json index 3353f8c7ce..6eebb5f703 100644 --- a/mso-api-handlers/mso-api-handler-common/src/test/resources/CamundaClientTest/WrappedVIDRequest.json +++ b/mso-api-handlers/mso-api-handler-common/src/test/resources/CamundaClientTest/WrappedVIDRequest.json @@ -95,6 +95,10 @@ "generateIdsOnly": { "value": false, "type": "Boolean" + }, + "operationType": { + "value": "activation", + "type": "String" } } } diff --git a/mso-api-handlers/mso-api-handler-infra/pom.xml b/mso-api-handlers/mso-api-handler-infra/pom.xml index 3a7c7ad477..7d6bbc4fc4 100644 --- a/mso-api-handlers/mso-api-handler-infra/pom.xml +++ b/mso-api-handlers/mso-api-handler-infra/pom.xml @@ -167,7 +167,7 @@ <dependency> <groupId>org.onap.sdc.sdc-distribution-client</groupId> <artifactId>sdc-distribution-client</artifactId> - <version>1.3.0</version> + <version>1.4.1</version> <exclusions> <exclusion> <groupId>org.slf4j</groupId> @@ -244,6 +244,34 @@ <build> <finalName>${project.artifactId}-${project.version}</finalName> + <pluginManagement> + <plugins> + <plugin> + <groupId>org.eclipse.m2e</groupId> + <artifactId>lifecycle-mapping</artifactId> + <version>1.0.0</version> + <configuration> + <lifecycleMappingMetadata> + <pluginExecutions> + <pluginExecution> + <pluginExecutionFilter> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + <versionRange>[1.0.0,)</versionRange> + <goals> + <goal>unpack</goal> + </goals> + </pluginExecutionFilter> + <action> + <execute /> + </action> + </pluginExecution> + </pluginExecutions> + </lifecycleMappingMetadata> + </configuration> + </plugin> + </plugins> + </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> @@ -300,7 +328,7 @@ </plugin> <plugin> <groupId>io.fabric8</groupId> - <artifactId>fabric8-maven-plugin</artifactId> + <artifactId>docker-maven-plugin</artifactId> <executions> <execution> <id>start</id> diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java index f30b66c6b5..4e0ba083ea 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java @@ -13,7 +13,6 @@ import org.json.JSONObject; import org.onap.logging.filter.spring.SpringClientPayloadFilter; import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; import org.onap.so.utils.CryptoUtils; -import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java index d4bc4fd165..665fa547cc 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java @@ -36,17 +36,16 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.onap.so.apihandlerinfra.e2eserviceinstancebeans.*; import org.onap.aai.domain.yang.v16.ServiceInstance; -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIResourcesClient; -import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.so.client.aai.entities.uri.AAIUriFactory; -import org.onap.so.logger.LoggingAnchor; -import org.apache.http.HttpResponse; +import org.onap.aaiclient.client.aai.AAIObjectType; +import org.onap.aaiclient.client.aai.AAIResourcesClient; +import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; +import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; import org.apache.http.HttpStatus; import org.json.JSONObject; +import org.onap.logging.filter.base.ErrorCode; +import org.onap.so.apihandler.camundabeans.CamundaResponse; +import org.onap.so.apihandler.common.CamundaClient; import org.onap.so.apihandler.common.ErrorNumbers; -import org.onap.so.apihandler.common.RequestClient; -import org.onap.so.apihandler.common.RequestClientFactory; import org.onap.so.apihandler.common.RequestClientParameter; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandler.common.ResponseHandler; @@ -56,6 +55,7 @@ import org.onap.so.apihandlerinfra.e2eserviceinstancebeans.E2EServiceInstanceReq import org.onap.so.apihandlerinfra.e2eserviceinstancebeans.E2EServiceInstanceScaleRequest; import org.onap.so.apihandlerinfra.e2eserviceinstancebeans.GetE2EServiceInstanceResponse; import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.constants.Status; @@ -64,7 +64,7 @@ import org.onap.so.db.catalog.beans.ServiceRecipe; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.beans.OperationStatus; import org.onap.so.db.request.client.RequestsDbClient; -import org.onap.logging.filter.base.ErrorCode; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.onap.so.serviceinstancebeans.ModelInfo; import org.onap.so.serviceinstancebeans.ModelType; @@ -76,6 +76,7 @@ import org.onap.so.serviceinstancebeans.SubscriberInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.v3.oas.annotations.OpenAPIDefinition; @@ -106,9 +107,6 @@ public class E2EServiceInstances { private MsoRequest msoRequest; @Autowired - private RequestClientFactory requestClientFactory; - - @Autowired private RequestsDbClient requestsDbClient; @Autowired @@ -117,6 +115,12 @@ public class E2EServiceInstances { @Autowired private ResponseBuilder builder; + @Autowired + private CamundaClient camundaClient; + + @Autowired + private ResponseHandler responseHandler; + /** * POST Requests for E2E Service create Instance on a version provided * @@ -288,24 +292,16 @@ public class E2EServiceInstances { String workflowUrl = "/mso/async/services/CompareModelofE2EServiceInstance"; int recipeTimeout = 180; - RequestClient requestClient; - HttpResponse response; - + String bpmnRequest = null; + RequestClientParameter postParam = null; try { - requestClient = requestClientFactory.getRequestClient(workflowUrl); - JSONObject jjo = new JSONObject(requestJSON); - String bpmnRequest = jjo.toString(); - - // Capture audit event - logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); + bpmnRequest = jjo.toString(); String serviceId = instanceIdMap.get(SERVICE_ID); String serviceType = e2eCompareModelReq.getServiceType(); - RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId) - .setBaseVfModule(false).setRecipeTimeout(recipeTimeout).setRequestAction(action.name()) - .setServiceInstanceId(serviceId).setServiceType(serviceType).setRequestDetails(bpmnRequest) - .setALaCarte(false).build(); - response = requestClient.post(postParam); + postParam = new RequestClientParameter.Builder().setRequestId(requestId).setBaseVfModule(false) + .setRecipeTimeout(recipeTimeout).setRequestAction(action.name()).setServiceInstanceId(serviceId) + .setServiceType(serviceType).setRequestDetails(bpmnRequest).setALaCarte(false).build(); } catch (Exception e) { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), @@ -315,21 +311,7 @@ public class E2EServiceInstances { logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString()); return resp; } - - if (response == null) { - Response resp = - msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, - "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcessError.getValue(), "Null response from BPEL"); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString()); - return resp; - } - - ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); - int bpelStatus = respHandler.getStatus(); - - return beplStatusUpdate(requestClient, respHandler, bpelStatus, version); + return postRequest(workflowUrl, postParam, version); } private Response getE2EServiceInstance(String serviceId, String operationId, String version) { @@ -431,29 +413,21 @@ public class E2EServiceInstances { return response; } - RequestClient requestClient; - HttpResponse response; + String bpmnRequest = null; + RequestClientParameter postParam = null; try { - requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI()); - JSONObject jjo = new JSONObject(requestJSON); jjo.put("operationId", requestId); - - String bpmnRequest = jjo.toString(); - - // Capture audit event - logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); + bpmnRequest = jjo.toString(); String serviceId = instanceIdMap.get(SERVICE_ID); String operationType = instanceIdMap.get("operationType"); String serviceInstanceType = e2eActReq.getServiceType(); - RequestClientParameter clientParam = new RequestClientParameter.Builder().setRequestId(requestId) - .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(action.name()).setServiceInstanceId(serviceId).setOperationType(operationType) - .setServiceType(serviceInstanceType).setRequestDetails(bpmnRequest).setApiVersion(version) - .setALaCarte(false).setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); - response = requestClient.post(clientParam); - + postParam = new RequestClientParameter.Builder().setRequestId(requestId).setBaseVfModule(false) + .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()).setRequestAction(action.name()) + .setServiceInstanceId(serviceId).setOperationType(operationType).setServiceType(serviceInstanceType) + .setRequestDetails(bpmnRequest).setApiVersion(version).setALaCarte(false) + .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); } catch (Exception e) { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), @@ -464,21 +438,7 @@ public class E2EServiceInstances { logger.debug("End of the transaction, the final response is: " + resp.getEntity()); return resp; } - - if (response == null) { - Response resp = - msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, - "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcessError.getValue(), "Null response from BPEL"); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; - } - - ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); - int bpelStatus = respHandler.getStatus(); - - return beplStatusUpdate(requestClient, respHandler, bpelStatus, version); + return postRequest(recipeLookupResult.getOrchestrationURI(), postParam, version); } private Response deleteE2EserviceInstances(String requestJSON, Action action, HashMap<String, String> instanceIdMap, @@ -540,29 +500,19 @@ public class E2EServiceInstances { logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } - - RequestClient requestClient; - HttpResponse response; - + String bpmnRequest = null; + RequestClientParameter clientParam = null; try { - requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI()); - JSONObject jjo = new JSONObject(requestJSON); jjo.put("operationId", requestId); - - String bpmnRequest = jjo.toString(); - - // Capture audit event - logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); + bpmnRequest = jjo.toString(); String serviceId = instanceIdMap.get(SERVICE_ID); String serviceInstanceType = e2eDelReq.getServiceType(); - RequestClientParameter clientParam = new RequestClientParameter.Builder().setRequestId(requestId) - .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType) - .setRequestDetails(bpmnRequest).setApiVersion(version).setALaCarte(false) - .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); - response = requestClient.post(clientParam); - + clientParam = new RequestClientParameter.Builder().setRequestId(requestId).setBaseVfModule(false) + .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()).setRequestAction(action.name()) + .setServiceInstanceId(serviceId).setServiceType(serviceInstanceType).setRequestDetails(bpmnRequest) + .setApiVersion(version).setALaCarte(false).setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()) + .build(); } catch (Exception e) { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), @@ -574,20 +524,7 @@ public class E2EServiceInstances { return resp; } - if (response == null) { - Response resp = - msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, - "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcessError.getValue(), "Null response from BPEL"); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; - } - - ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); - int bpelStatus = respHandler.getStatus(); - - return beplStatusUpdate(requestClient, respHandler, bpelStatus, version); + return postRequest(recipeLookupResult.getOrchestrationURI(), clientParam, version); } private Response updateE2EserviceInstances(String requestJSON, Action action, String version) throws ApiException { @@ -657,51 +594,14 @@ public class E2EServiceInstances { } String serviceInstanceType = e2eSir.getService().getServiceType(); - - RequestClient requestClient; - HttpResponse response; - String sirRequestJson = convertToString(sir); + RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId) + .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType) + .setRequestDetails(sirRequestJson).setApiVersion(version).setALaCarte(false) + .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); - try { - requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI()); - - // Capture audit event - logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); - RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId) - .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType) - .setRequestDetails(sirRequestJson).setApiVersion(version).setALaCarte(false) - .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); - response = requestClient.post(postParam); - } catch (Exception e) { - logger.debug("Exception while communicate with BPMN engine", e); - Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, - MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), - ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - - logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), - "Exception while communicate with BPMN engine"); - logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity()); - - return getBPMNResp; - } - - if (response == null) { - Response getBPMNResp = - msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, - "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcessError.getValue(), "Null response from BPEL"); - logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity()); - return getBPMNResp; - } - - ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); - int bpelStatus = respHandler.getStatus(); - - return beplStatusUpdate(requestClient, respHandler, bpelStatus, version); + return postRequest(recipeLookupResult.getOrchestrationURI(), postParam, version); } private Response processE2EserviceInstances(String requestJSON, Action action, @@ -771,48 +671,14 @@ public class E2EServiceInstances { String serviceInstanceType = e2eSir.getService().getServiceType(); String serviceId = e2eSir.getService().getServiceId(); - RequestClient requestClient; - HttpResponse response; - String sirRequestJson = convertToString(sir); + RequestClientParameter parameter = new RequestClientParameter.Builder().setRequestId(requestId) + .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType) + .setRequestDetails(sirRequestJson).setApiVersion(version).setALaCarte(false) + .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); - try { - requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI()); - - // Capture audit event - logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); - RequestClientParameter parameter = new RequestClientParameter.Builder().setRequestId(requestId) - .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType) - .setRequestDetails(sirRequestJson).setApiVersion(version).setALaCarte(false) - .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); - response = requestClient.post(parameter); - } catch (Exception e) { - Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, - MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), - ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - - logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), - "Exception while communicate with BPMN engine"); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; - } - - if (response == null) { - Response resp = - msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, - "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcessError.getValue(), "Null response from BPEL"); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; - } - - ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); - int bpelStatus = respHandler.getStatus(); - - return beplStatusUpdate(requestClient, respHandler, bpelStatus, version); + return postRequest(recipeLookupResult.getOrchestrationURI(), parameter, version); } private Response scaleE2EserviceInstances(String requestJSON, Action action, String version) throws ApiException { @@ -865,90 +731,67 @@ public class E2EServiceInstances { logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } - - RequestClient requestClient; - HttpResponse response; - + String bpmnRequest = null; + RequestClientParameter postParam = null; try { - requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI()); - JSONObject jjo = new JSONObject(requestJSON); jjo.put("operationId", requestId); - - String bpmnRequest = jjo.toString(); - - // Capture audit event - logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); + bpmnRequest = jjo.toString(); String serviceId = instanceIdMap.get(SERVICE_ID); String serviceInstanceType = e2eScaleReq.getService().getServiceType(); - RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId) - .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType) - .setRequestDetails(bpmnRequest).setApiVersion(version).setALaCarte(false) - .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); - response = requestClient.post(postParam); + postParam = new RequestClientParameter.Builder().setRequestId(requestId).setBaseVfModule(false) + .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()).setRequestAction(action.name()) + .setServiceInstanceId(serviceId).setServiceType(serviceInstanceType).setRequestDetails(bpmnRequest) + .setApiVersion(version).setALaCarte(false).setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()) + .build(); } catch (Exception e) { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, - MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), + MsoException.ServiceException, "Failed creating bpmnRequest " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), - "Exception while communicate with BPMN engine", e); + "Exception while creating bpmnRequest", e); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } + return postRequest(recipeLookupResult.getOrchestrationURI(), postParam, version); + } - if (response == null) { - Response resp = - msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, - "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); + protected Response postRequest(String orchestrationURI, RequestClientParameter postParam, String version) + throws ApiException { + ResponseEntity<String> response = null; + try { + response = camundaClient.post(postParam, orchestrationURI); + } catch (BPMNFailureException e) { + Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), + ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcessError.getValue(), "Null response from BPEL"); + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine"); + logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); + return resp; + } catch (Exception e) { + Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, + MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), + ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } - - ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); - int bpelStatus = respHandler.getStatus(); - - return beplStatusUpdate(requestClient, respHandler, bpelStatus, version); + return bpelStatusUpdate(response, version); } - private Response beplStatusUpdate(RequestClient requestClient, ResponseHandler respHandler, int bpelStatus, - String version) { - + private Response bpelStatusUpdate(ResponseEntity<String> responseEntity, String version) throws ApiException { String apiVersion = version.substring(1); - - // BPMN accepted the request, the request is in progress - if (bpelStatus == HttpStatus.SC_ACCEPTED) { - String camundaJSONResponseBody = respHandler.getResponseBody(); - logger.debug("Received from Camunda: " + camundaJSONResponseBody); - logger.debug(END_OF_THE_TRANSACTION + camundaJSONResponseBody); - return builder.buildResponse(HttpStatus.SC_ACCEPTED, null, camundaJSONResponseBody, apiVersion); - } else { - List<String> variables = new ArrayList<>(); - variables.add(bpelStatus + ""); - String camundaJSONResponseBody = respHandler.getResponseBody(); - if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) { - Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException, - "Request Failed due to BPEL error with HTTP Status= %1 " + '\n' + camundaJSONResponseBody, - ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version); - logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), - requestClient.getUrl(), ErrorCode.BusinessProcessError.getValue(), - "Response from BPEL engine is failed with HTTP Status=" + bpelStatus); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; - } else { - Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException, - "Request Failed due to BPEL error with HTTP Status= %1", - ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version); - logger.error("", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(), - ErrorCode.BusinessProcessError.getValue(), "Response from BPEL engine is empty"); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; - } - } + responseHandler.acceptedResponse(responseEntity); + CamundaResponse camundaResponse = responseHandler.getCamundaResponse(responseEntity); + String response = camundaResponse.getResponse(); + logger.debug(END_OF_THE_TRANSACTION + response); + return builder.buildResponse(HttpStatus.SC_ACCEPTED, null, response, apiVersion); } /** diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java index 3007ddd7c9..f39a95e92c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java @@ -197,6 +197,7 @@ public class InstanceManagement { vnfId = sir.getVnfInstanceId(); } + currentActiveReq = setWorkflowNameAndOperationName(currentActiveReq, workflowUuid); saveCurrentActiveRequest(currentActiveReq); RequestClientParameter requestClientParameter; @@ -293,6 +294,7 @@ public class InstanceManagement { RecipeLookupResult recipeLookupResult = getInstanceManagementWorkflowRecipe(currentActiveReq, workflowUuid); + currentActiveReq = setWorkflowNameAndOperationName(currentActiveReq, workflowUuid); saveCurrentActiveRequest(currentActiveReq); RequestClientParameter requestClientParameter; @@ -357,4 +359,14 @@ public class InstanceManagement { } return null; } + + protected InfraActiveRequests setWorkflowNameAndOperationName(InfraActiveRequests currentActiveReq, + String workflowUuid) { + Workflow workflow = catalogDbClient.findWorkflowByArtifactUUID(workflowUuid); + if (workflow != null) { + currentActiveReq.setWorkflowName(workflow.getName()); + currentActiveReq.setOperationName(workflow.getOperationName()); + } + return currentActiveReq; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java index 0ec61785fd..b01bbecf0a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java @@ -34,15 +34,13 @@ import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; +import org.onap.logging.filter.base.ErrorCode; +import org.onap.so.apihandler.common.CamundaClient; import org.onap.so.apihandler.common.ErrorNumbers; -import org.onap.so.apihandler.common.RequestClient; -import org.onap.so.apihandler.common.RequestClientFactory; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandler.common.ResponseHandler; import org.onap.so.apihandlerinfra.exceptions.ApiException; -import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.apihandlerinfra.tasksbeans.TaskRequestReference; @@ -50,12 +48,12 @@ import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest; import org.onap.so.apihandlerinfra.tasksbeans.Value; import org.onap.so.apihandlerinfra.tasksbeans.Variables; import org.onap.so.exceptions.ValidationException; -import org.onap.logging.filter.base.ErrorCode; import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -76,13 +74,13 @@ public class ManualTasks { private String taskUri; @Autowired - private RequestClientFactory reqClientFactory; + private ResponseBuilder builder; @Autowired - private MsoRequest msoRequest; + private CamundaClient camundaClient; @Autowired - private ResponseBuilder builder; + private ResponseHandler responseHandler; @POST @Path("/{version:[vV]1}/{taskId}/complete") @@ -161,100 +159,37 @@ public class ManualTasks { mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); camundaJsonReq = mapper.writeValueAsString(variablesForComplete); } catch (JsonProcessingException e) { - - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.UnknownError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - + logger.error("Mapping of JSON object to Camunda request failed"); ValidateException validateException = new ValidateException.Builder("Mapping of JSON object to Camunda request failed", - HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR) - .errorInfo(errorLoggerInfo).build(); + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).build(); throw validateException; } - RequestClient requestClient; - HttpResponse response; String requestUrl = taskUri + "/" + taskId + "/complete"; - try { - requestClient = reqClientFactory.getRequestClient(requestUrl); - // Capture audit event - - response = requestClient.post(camundaJsonReq); - - } catch (Exception e) { - - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - - - BPMNFailureException bpmnFailureException = - new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), - HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo) - .build(); - - throw bpmnFailureException; - } - - if (response == null) { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcessError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ResponseEntity<String> response = camundaClient.post(camundaJsonReq, requestUrl); + int bpelStatus = responseHandler.setStatus(response.getStatusCodeValue()); - BPMNFailureException bpmnFailureException = - new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), - HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo) - .build(); - - throw bpmnFailureException; - - } - - ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); - int bpelStatus = respHandler.getStatus(); - - // BPEL accepted the request, the request is in progress - if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) { - logger.debug("Received good response from Camunda"); - TaskRequestReference trr = new TaskRequestReference(); - trr.setTaskId(taskId); - String completeResp = null; - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); - completeResp = mapper.writeValueAsString(trr); - } catch (JsonProcessingException e) { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, - ErrorCode.BusinessProcessError).build(); - - - ValidateException validateException = - new ValidateException.Builder("Request Failed due to bad response format", bpelStatus, - ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); - - throw validateException; - } - logger.debug("Response to the caller: {}", completeResp); - logger.debug("End of the transaction, the final response is: {}", completeResp); - return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, completeResp, apiVersion); - } else { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError) - .build(); - - - BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), - bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); - - throw bpmnFailureException; - + responseHandler.acceptedOrNoContentResponse(response); + logger.debug("Received good response from Camunda"); + TaskRequestReference trr = new TaskRequestReference(); + trr.setTaskId(taskId); + String completeResp = null; + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); + completeResp = mapper.writeValueAsString(trr); + } catch (JsonProcessingException e) { + logger.error("Unable to map response from Camunda"); + ValidateException validateException = + new ValidateException.Builder("Request Failed due to bad response format", bpelStatus, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).build(); + throw validateException; } - + logger.debug("Response to the caller: {}", completeResp); + logger.debug("End of the transaction, the final response is: {}", completeResp); + return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, completeResp, apiVersion); } private static boolean empty(String s) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java index ce371203ab..f3c3ec5ff1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java @@ -42,8 +42,6 @@ import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.aai.domain.yang.ServiceInstance; import org.onap.aai.domain.yang.Tenant; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.infra.rest.AAIDataRetrieval; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java index c43a050500..acd3a8321e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java @@ -49,7 +49,6 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.exceptions.ApiException; -import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.constants.OrchestrationRequestFormat; @@ -311,6 +310,19 @@ public class OrchestrationRequests { request.setOriginalRequestId(originalRequestId); } + if (!version.matches("v[1-7]")) { + String workflowName = iar.getWorkflowName(); + if (workflowName == null) { + workflowName = iar.getRequestAction(); + } + request.setWorkflowName(workflowName); + + String operationName = iar.getOperationName(); + if (operationName != null) { + request.setOperationName(operationName); + } + } + InstanceReferences ir = new InstanceReferences(); if (iar.getNetworkId() != null) ir.setNetworkInstanceId(iar.getNetworkId()); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java index 9b37043b2d..a61975f529 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java @@ -38,22 +38,19 @@ import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import org.apache.commons.lang.StringUtils; -import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; -import org.camunda.bpm.engine.history.HistoricProcessInstance; import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; +import org.onap.logging.filter.base.ErrorCode; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandler.camundabeans.CamundaResponse; +import org.onap.so.apihandler.common.CamundaClient; import org.onap.so.apihandler.common.CommonConstants; import org.onap.so.apihandler.common.ErrorNumbers; -import org.onap.so.apihandler.common.RequestClient; -import org.onap.so.apihandler.common.RequestClientFactory; import org.onap.so.apihandler.common.RequestClientParameter; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandler.common.ResponseHandler; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; -import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException; import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException; import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException; @@ -74,9 +71,7 @@ import org.onap.so.db.catalog.beans.VnfResource; import org.onap.so.db.catalog.beans.VnfResourceCustomization; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.beans.InfraActiveRequests; -import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; -import org.onap.logging.filter.base.ErrorCode; import org.onap.so.logger.LogConstants; import org.onap.so.logger.MessageEnum; import org.onap.so.serviceinstancebeans.CloudConfiguration; @@ -117,9 +112,6 @@ public class RequestHandlerUtils extends AbstractRestHandler { private Environment env; @Autowired - private RequestClientFactory reqClientFactory; - - @Autowired private ResponseBuilder builder; @Autowired @@ -131,122 +123,62 @@ public class RequestHandlerUtils extends AbstractRestHandler { @Autowired private CatalogDbClient catalogDbClient; - public Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter, - String orchestrationUri, String requestScope) throws ApiException { - HttpResponse response = null; - RequestClient requestClient = null; - - try { - requestClient = reqClientFactory.getRequestClient(orchestrationUri); - response = requestClient.post(requestClientParameter); - } catch (Exception e) { - logger.error("Error posting request to BPMN", e); - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - String url = requestClient != null ? requestClient.getUrl() : ""; - ClientConnectionException clientException = - new ClientConnectionException.Builder(url, HttpStatus.SC_BAD_GATEWAY, - ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage()); - throw clientException; - } - - if (response == null) { + @Autowired + private CamundaClient camundaClient; - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcessError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ClientConnectionException clientException = new ClientConnectionException.Builder(requestClient.getUrl(), - HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage()); - throw clientException; - } + @Autowired + private ResponseHandler responseHandler; - ResponseHandler respHandler = null; - int bpelStatus = 500; + protected ResponseEntity<String> postRequest(InfraActiveRequests currentActiveReq, + RequestClientParameter requestClientParameter, String orchestrationUri) throws ApiException { try { - respHandler = new ResponseHandler(response, requestClient.getType()); - bpelStatus = respHandler.getStatus(); + return camundaClient.post(requestClientParameter, orchestrationUri); } catch (ApiException e) { - logger.error("Exception occurred", e); - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ValidateException validateException = - new ValidateException.Builder("Exception caught mapping Camunda JSON response to object", - HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); - throw validateException; + updateStatus(currentActiveReq, Status.FAILED, e.getMessage()); + throw e; } + } - // BPEL accepted the request, the request is in progress - if (bpelStatus == HttpStatus.SC_ACCEPTED) { - ServiceInstancesResponse jsonResponse; - CamundaResponse camundaResp = respHandler.getResponse(); - - if ("Success".equalsIgnoreCase(camundaResp.getMessage())) { - try { - ObjectMapper mapper = new ObjectMapper(); - jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class); - jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId()); - Optional<URL> selfLinkUrl = - buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId()); - if (selfLinkUrl.isPresent()) { - jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get()); - } else { - jsonResponse.getRequestReferences().setRequestSelfLink(null); - } - } catch (IOException e) { - logger.error("Exception occurred", e); - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ValidateException validateException = - new ValidateException.Builder("Exception caught mapping Camunda JSON response to object", - HttpStatus.SC_NOT_ACCEPTABLE, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); - throw validateException; + public Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter, + String orchestrationUri, String requestScope) throws ApiException { + ObjectMapper mapper = new ObjectMapper(); + ResponseEntity<String> response = postRequest(currentActiveReq, requestClientParameter, orchestrationUri); + ServiceInstancesResponse jsonResponse = null; + int bpelStatus = responseHandler.setStatus(response.getStatusCodeValue()); + try { + responseHandler.acceptedResponse(response); + CamundaResponse camundaResponse = responseHandler.getCamundaResponse(response); + String responseBody = camundaResponse.getResponse(); + if ("Success".equalsIgnoreCase(camundaResponse.getMessage())) { + jsonResponse = mapper.readValue(responseBody, ServiceInstancesResponse.class); + jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId()); + Optional<URL> selfLinkUrl = + buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId()); + if (selfLinkUrl.isPresent()) { + jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get()); + } else { + jsonResponse.getRequestReferences().setRequestSelfLink(null); } - return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(), - jsonResponse, requestClientParameter.getApiVersion()); + } else { + BPMNFailureException bpmnException = + new BPMNFailureException.Builder(String.valueOf(bpelStatus) + responseBody, bpelStatus, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).build(); + updateStatus(currentActiveReq, Status.FAILED, bpmnException.getMessage()); + throw bpmnException; } + } catch (ApiException e) { + updateStatus(currentActiveReq, Status.FAILED, e.getMessage()); + throw e; + } catch (IOException e) { + logger.error("Exception caught mapping Camunda JSON response to object: ", e); + updateStatus(currentActiveReq, Status.FAILED, e.getMessage()); + throw new ValidateException.Builder("Exception caught mapping Camunda JSON response to object", + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).build(); } - - List<String> variables = new ArrayList<>(); - variables.add(bpelStatus + ""); - String camundaJSONResponseBody = respHandler.getResponseBody(); - if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) { - - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError) - .errorSource(requestClient.getUrl()).build(); - BPMNFailureException bpmnException = - new BPMNFailureException.Builder(String.valueOf(bpelStatus) + camundaJSONResponseBody, bpelStatus, - ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); - - updateStatus(currentActiveReq, Status.FAILED, bpmnException.getMessage()); - - throw bpmnException; - } else { - - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError) - .errorSource(requestClient.getUrl()).build(); - - - BPMNFailureException servException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), - bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, servException.getMessage()); - - throw servException; - } + return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(), jsonResponse, + requestClientParameter.getApiVersion()); } - - @Override public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage) throws RequestDbFailureException { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java index 418c702768..dadb7c7558 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java @@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra; -import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -33,13 +32,12 @@ import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; -import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.json.JSONArray; import org.json.JSONObject; +import org.onap.logging.filter.base.ErrorCode; +import org.onap.so.apihandler.common.CamundaClient; import org.onap.so.apihandler.common.ErrorNumbers; -import org.onap.so.apihandler.common.RequestClient; -import org.onap.so.apihandler.common.RequestClientFactory; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandler.common.ResponseHandler; import org.onap.so.apihandlerinfra.exceptions.ApiException; @@ -50,12 +48,12 @@ import org.onap.so.apihandlerinfra.tasksbeans.TaskList; import org.onap.so.apihandlerinfra.tasksbeans.TaskVariableValue; import org.onap.so.apihandlerinfra.tasksbeans.TaskVariables; import org.onap.so.apihandlerinfra.tasksbeans.TasksGetResponse; -import org.onap.logging.filter.base.ErrorCode; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -79,10 +77,13 @@ public class TasksHandler { private String requestUrl; @Autowired - private RequestClientFactory reqClientFactory; + private ResponseBuilder builder; @Autowired - private ResponseBuilder builder; + private CamundaClient camundaClient; + + @Autowired + private ResponseHandler responseHandler; @Path("/{version:[vV]1}") @GET @@ -148,18 +149,12 @@ public class TasksHandler { } tv.setTaskVariables(tvvList); - - RequestClient requestClient = null; - - HttpResponse response = null; + ResponseEntity<String> response = null; + String camundaJsonReq = null; try { - requestClient = reqClientFactory.getRequestClient(requestUrl); - // Capture audit event ObjectMapper mapper = new ObjectMapper(); - String camundaJsonReq = mapper.writeValueAsString(tv); - response = requestClient.post(camundaJsonReq); - + camundaJsonReq = mapper.writeValueAsString(tv); } catch (JsonProcessingException e) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) @@ -167,21 +162,16 @@ public class TasksHandler { throw new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo) .build(); - - } catch (IOException e) { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) - .build(); - throw new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, - ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build(); } + + response = camundaClient.post(camundaJsonReq, requestUrl); TasksGetResponse trr = new TasksGetResponse(); List<TaskList> taskList = new ArrayList<>(); - ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); - int bpelStatus = respHandler.getStatus(); - String respBody = respHandler.getResponseBody(); - if ((bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) && (null != respBody)) { + int bpelStatus = responseHandler.setStatus(response.getStatusCodeValue()); + String respBody = response.getBody(); + responseHandler.acceptedOrNoContentResponse(response); + if (null != respBody) { JSONArray data = new JSONArray(respBody); @@ -230,45 +220,22 @@ public class TasksHandler { private TaskList getTaskInfo(String taskId) throws ApiException { TaskList taskList; String getRequestUrl = UriBuilder.fromUri(requestUrl).path(taskId).path("variables").build().toString(); - HttpResponse getResponse; - - RequestClient requestClient = reqClientFactory.getRequestClient(getRequestUrl); - // Capture audit event - try { - getResponse = requestClient.get(); - } catch (IOException e) { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) - .build(); - throw new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, - ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build(); - } - ResponseHandler respHandler = new ResponseHandler(getResponse, requestClient.getType()); - int bpelStatus = respHandler.getStatus(); - if (bpelStatus == HttpStatus.SC_ACCEPTED) { - String respBody = respHandler.getResponseBody(); - if (respBody != null) { - taskList = buildTaskList(taskId, respBody); - } else { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, - ErrorCode.AvailabilityError).build(); - throw new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), - HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo) - .build(); + ResponseEntity<String> getResponse; - } + getResponse = camundaClient.get(getRequestUrl); + responseHandler.acceptedResponse(getResponse); + String respBody = getResponse.getBody(); + if (respBody != null) { + taskList = buildTaskList(taskId, respBody); } else { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) .build(); - - throw new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, + throw new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build(); } - return taskList; - } private TaskList buildTaskList(String taskId, String respBody) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java index 4e3d8736c2..fc0048bacf 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java @@ -1,19 +1,35 @@ package org.onap.so.apihandlerinfra.infra.rest; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; import org.onap.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.L3Network; +import org.onap.aai.domain.yang.LInterface; import org.onap.aai.domain.yang.Service; import org.onap.aai.domain.yang.ServiceInstance; import org.onap.aai.domain.yang.Tenant; import org.onap.aai.domain.yang.VfModule; +import org.onap.aai.domain.yang.VfModules; import org.onap.aai.domain.yang.VolumeGroup; +import org.onap.aai.domain.yang.VolumeGroups; import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound; -import org.onap.so.client.aai.AAIObjectPlurals; -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIResourcesClient; -import org.onap.so.client.aai.entities.AAIResultWrapper; -import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.aai.AAIDSLQueryClient; +import org.onap.aaiclient.client.aai.AAIObjectPlurals; +import org.onap.aaiclient.client.aai.AAIObjectType; +import org.onap.aaiclient.client.aai.AAIResourcesClient; +import org.onap.aaiclient.client.aai.entities.AAIResultWrapper; +import org.onap.aaiclient.client.aai.entities.uri.AAIPluralResourceUri; +import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.graphinventory.entities.DSLQuery; +import org.onap.aaiclient.client.graphinventory.entities.DSLQueryBuilder; +import org.onap.aaiclient.client.graphinventory.entities.DSLStartNode; +import org.onap.aaiclient.client.graphinventory.entities.Node; +import org.onap.aaiclient.client.graphinventory.entities.Start; +import org.onap.aaiclient.client.graphinventory.entities.TraversalBuilder; +import org.onap.aaiclient.client.graphinventory.entities.__; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -25,6 +41,8 @@ public class AAIDataRetrieval { private AAIResourcesClient aaiResourcesClient; + private AAIDSLQueryClient aaiDslQueryClient; + private static final Logger logger = LoggerFactory.getLogger(AAIDataRetrieval.class); public ServiceInstance getServiceInstance(String serviceInstanceId) { @@ -129,6 +147,22 @@ public class AAIDataRetrieval { }); } + public List<LInterface> getLinterfacesOfVnf(String vnfId) { + DSLStartNode startNode = new DSLStartNode(AAIObjectType.GENERIC_VNF, __.key("generic-vnf-id", vnfId)); + DSLQueryBuilder<Start, Node> builder = TraversalBuilder.fragment(startNode) + .to(__.node(AAIObjectType.VSERVER).to(__.node(AAIObjectType.L_INTERFACE).output())); + List<LInterface> linterfaces = + getAAIDSLQueryClient().querySingleResource(new DSLQuery(builder.build()), LInterface.class); + return linterfaces; + } + + private AAIDSLQueryClient getAAIDSLQueryClient() { + if (aaiDslQueryClient == null) { + aaiDslQueryClient = new AAIDSLQueryClient(); + } + return aaiDslQueryClient; + } + protected AAIResourcesClient getAaiResourcesClient() { if (aaiResourcesClient == null) { aaiResourcesClient = new AAIResourcesClient(); @@ -136,4 +170,52 @@ public class AAIDataRetrieval { return aaiResourcesClient; } + public boolean isVnfRelatedToVFModule(String vnfId) { + return !getVfModulesOfVnf(vnfId).isEmpty(); + } + + public List<VfModule> getVfModulesOfVnf(String vnfId) { + List<VfModule> vfModuleList = new ArrayList<VfModule>(); + AAIPluralResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, vnfId); + Optional<VfModules> vfModules = getAaiResourcesClient().get(VfModules.class, uri); + if (!vfModules.isPresent() || vfModules.get().getVfModule().isEmpty()) { + logger.debug("No VfModules attached to Vnf in AAI : {}", vnfId); + } else { + vfModuleList = vfModules.get().getVfModule(); + } + return vfModuleList; + } + + public Optional<String> getVfModuleIdsByVnfId(String vnfId) { + List<VfModule> vfModulesList = getVfModulesOfVnf(vnfId); + if (!vfModulesList.isEmpty()) { + return Optional.of(vfModulesList.stream().map(item -> item.getVfModuleId()).collect(Collectors.toList()) + .stream().sorted().collect(Collectors.joining(","))); + } else { + return Optional.empty(); + } + } + + public List<VolumeGroup> getVolumeGroupsOfVnf(String vnfId) { + List<VolumeGroup> volumeGroupList = new ArrayList<VolumeGroup>(); + AAIPluralResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + .relatedTo(AAIObjectPlurals.VOLUME_GROUP); + Optional<VolumeGroups> volumeGroups = getAaiResourcesClient().get(VolumeGroups.class, uri); + if (!volumeGroups.isPresent() || volumeGroups.get().getVolumeGroup().isEmpty()) { + logger.debug("No VolumeGroups attached to Vnf in AAI : {}", vnfId); + } else { + volumeGroupList = volumeGroups.get().getVolumeGroup(); + } + return volumeGroupList; + } + + public Optional<String> getVolumeGroupIdsByVnfId(String vnfId) { + List<VolumeGroup> volumeGroupList = getVolumeGroupsOfVnf(vnfId); + if (!volumeGroupList.isEmpty()) { + return Optional.of(volumeGroupList.stream().map(item -> item.getVolumeGroupId()) + .collect(Collectors.toList()).stream().sorted().collect(Collectors.joining(","))); + } else { + return Optional.empty(); + } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java index f37713d5b2..e8046a2cd9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java @@ -29,11 +29,12 @@ import org.onap.aai.domain.yang.L3Network; import org.onap.aai.domain.yang.ServiceInstance; import org.onap.aai.domain.yang.VfModule; import org.onap.aai.domain.yang.VolumeGroup; +import org.onap.aaiclient.client.aai.AAIObjectType; +import org.onap.aaiclient.client.aai.entities.AAIResultWrapper; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound; import org.onap.so.apihandlerinfra.infra.rest.exception.CloudConfigurationNotFoundException; -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.constants.Status; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; @@ -56,12 +57,6 @@ public class BpmnRequestBuilder { private static final String CLOUD_CONFIGURATION_COULD_NOT_BE_FOUND = "Cloud Configuration could not be found"; - private static final String CLOUD_REGION_ID = "cloud-region-id"; - - private static final String CLOUD_OWNER = "cloud-owner"; - - private static final String TENANT_ID = "tenant-id"; - private static final String GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID = "Generic Vnf Not Found In Inventory, VnfId: "; @@ -277,17 +272,20 @@ public class BpmnRequestBuilder { public CloudConfiguration mapCloudConfiguration(GenericVnf vnf, String vfModuleId) { CloudConfiguration cloudConfig = new CloudConfiguration(); AAIResultWrapper wrapper = new AAIResultWrapper(vnf); - Optional<org.onap.so.client.aai.entities.Relationships> relationshipsOpt = wrapper.getRelationships(); + Optional<org.onap.aaiclient.client.aai.entities.Relationships> relationshipsOpt = wrapper.getRelationships(); String tenantId = null; String cloudOwner = null; String lcpRegionId = null; if (relationshipsOpt.isPresent()) { tenantId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst() - .map(item -> item.getURIKeys().get(TENANT_ID)).orElse(null); - cloudOwner = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst() - .map(item -> item.getURIKeys().get(CLOUD_OWNER)).orElse(null); - lcpRegionId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst() - .map(item -> item.getURIKeys().get(CLOUD_REGION_ID)).orElse(null); + .map(item -> item.getURIKeys().get(AAIFluentTypeBuilder.Types.TENANT.getUriParams().tenantId)) + .orElse(null); + cloudOwner = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst().map( + item -> item.getURIKeys().get(AAIFluentTypeBuilder.Types.CLOUD_REGION.getUriParams().cloudOwner)) + .orElse(null); + lcpRegionId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst().map( + item -> item.getURIKeys().get(AAIFluentTypeBuilder.Types.CLOUD_REGION.getUriParams().cloudRegionId)) + .orElse(null); } if (tenantId == null || cloudOwner == null || lcpRegionId == null) { @@ -319,17 +317,20 @@ public class BpmnRequestBuilder { public CloudConfiguration mapCloudConfigurationVolume(GenericVnf vnf, VolumeGroup volumeGroup) { CloudConfiguration cloudConfig = new CloudConfiguration(); AAIResultWrapper wrapper = new AAIResultWrapper(vnf); - Optional<org.onap.so.client.aai.entities.Relationships> relationshipsOpt = wrapper.getRelationships(); + Optional<org.onap.aaiclient.client.aai.entities.Relationships> relationshipsOpt = wrapper.getRelationships(); String tenantId = null; String cloudOwner = null; String lcpRegionId = null; if (relationshipsOpt.isPresent()) { tenantId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst() - .map(item -> item.getURIKeys().get(TENANT_ID)).orElse(null); - cloudOwner = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst() - .map(item -> item.getURIKeys().get(CLOUD_OWNER)).orElse(null); - lcpRegionId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst() - .map(item -> item.getURIKeys().get(CLOUD_REGION_ID)).orElse(null); + .map(item -> item.getURIKeys().get(AAIFluentTypeBuilder.Types.TENANT.getUriParams().tenantId)) + .orElse(null); + cloudOwner = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst().map( + item -> item.getURIKeys().get(AAIFluentTypeBuilder.Types.CLOUD_REGION.getUriParams().cloudOwner)) + .orElse(null); + lcpRegionId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst().map( + item -> item.getURIKeys().get(AAIFluentTypeBuilder.Types.CLOUD_REGION.getUriParams().cloudRegionId)) + .orElse(null); } if (tenantId == null || cloudOwner == null || lcpRegionId == null) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java index 3fd672bf42..c806e9fc1b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java @@ -20,16 +20,15 @@ package org.onap.so.apihandlerinfra.infra.rest.handler; -import java.io.IOException; import java.net.URL; import java.sql.Timestamp; import java.util.Map; import java.util.Optional; import javax.ws.rs.container.ContainerRequestContext; import org.apache.http.HttpStatus; +import org.onap.logging.filter.base.ErrorCode; +import org.onap.so.apihandler.common.CamundaClient; import org.onap.so.apihandler.common.ErrorNumbers; -import org.onap.so.apihandler.common.RequestClient; -import org.onap.so.apihandler.common.RequestClientFactory; import org.onap.so.apihandler.common.RequestClientParameter; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.Actions; @@ -45,7 +44,6 @@ import org.onap.so.constants.Status; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; -import org.onap.logging.filter.base.ErrorCode; import org.onap.so.logger.LogConstants; import org.onap.so.logger.MessageEnum; import org.onap.so.serviceinstancebeans.ModelType; @@ -74,7 +72,7 @@ public abstract class AbstractRestHandler { protected RequestsDbClient infraActiveRequestsClient; @Autowired - protected RequestClientFactory reqClientFactory; + private CamundaClient camundaClient; public String getRequestUri(ContainerRequestContext context) { String requestUri = context.getUriInfo().getPath(); @@ -151,10 +149,9 @@ public abstract class AbstractRestHandler { public void callWorkflowEngine(RequestClientParameter requestClientParameter, String orchestrationUri) throws WorkflowEngineConnectionException { - RequestClient requestClient = reqClientFactory.getRequestClient(orchestrationUri); try { - requestClient.post(requestClientParameter); - } catch (IOException e) { + camundaClient.post(requestClientParameter, orchestrationUri); + } catch (ApiException e) { logger.error("Error Calling Workflow Engine", e); throw new WorkflowEngineConnectionException("Error Calling Workflow Engine", e); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/NetworkDeleteValidator.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/NetworkDeleteValidator.java index f75897dda1..89c5cbed9b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/NetworkDeleteValidator.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/NetworkDeleteValidator.java @@ -8,8 +8,9 @@ import org.onap.so.apihandlerinfra.Actions; import org.onap.so.apihandlerinfra.infra.rest.AAIDataRetrieval; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; - +@Component public class NetworkDeleteValidator implements RequestValidator { @Autowired diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java index 1dea57ad9c..50938e6826 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java @@ -24,7 +24,9 @@ import java.util.Map; import java.util.Optional; import org.onap.so.apihandlerinfra.Actions; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.springframework.stereotype.Component; +@Component public interface RequestValidator { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/ServiceInstanceDeleteValidator.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/ServiceInstanceDeleteValidator.java index 0c7ba65cf4..843d94ce6c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/ServiceInstanceDeleteValidator.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/ServiceInstanceDeleteValidator.java @@ -6,11 +6,12 @@ import java.util.regex.Pattern; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.Actions; import org.onap.so.apihandlerinfra.infra.rest.AAIDataRetrieval; -import org.onap.so.listener.Skip; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; -@Skip + +@Component public class ServiceInstanceDeleteValidator implements RequestValidator { @Autowired @@ -18,8 +19,17 @@ public class ServiceInstanceDeleteValidator implements RequestValidator { @Override public boolean shouldRunFor(String requestUri, ServiceInstancesRequest request, Actions action) { + boolean isALaCarte = false; + if (request.getRequestDetails() != null && request.getRequestDetails().getRequestParameters() != null) { + if (request.getRequestDetails().getRequestParameters().getALaCarte() == null) { + isALaCarte = false; + } else { + isALaCarte = request.getRequestDetails().getRequestParameters().getALaCarte(); + } + + } return Pattern.compile("[Vv][5-8]/serviceInstances/[^/]+").matcher(requestUri).matches() - && action.equals(Action.deleteInstance); + && action.equals(Action.deleteInstance) && isALaCarte; } @Override diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/VnfDeleteValidator.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/VnfDeleteValidator.java index d54e60d153..a48fca8d0f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/VnfDeleteValidator.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/VnfDeleteValidator.java @@ -8,8 +8,9 @@ import org.onap.so.apihandlerinfra.Actions; import org.onap.so.apihandlerinfra.infra.rest.AAIDataRetrieval; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; - +@Component public class VnfDeleteValidator implements RequestValidator { @Autowired @@ -24,8 +25,16 @@ public class VnfDeleteValidator implements RequestValidator { @Override public Optional<String> validate(Map<String, String> instanceIdMap, ServiceInstancesRequest request, Map<String, String> queryParams) { - if (aaiDataRetrieval.isVnfRelatedToVolumes(instanceIdMap.get("vnfInstanceId"))) { - return Optional.of("Cannot delete vnf it is still related to existing volume groups"); + final Optional<String> volumeGroupIds = + aaiDataRetrieval.getVolumeGroupIdsByVnfId(instanceIdMap.get("vnfInstanceId")); + final Optional<String> vfModuleIds = aaiDataRetrieval.getVfModuleIdsByVnfId(instanceIdMap.get("vnfInstanceId")); + + if (volumeGroupIds.isPresent()) { + return Optional.of(String.format("Cannot delete vnf it is still related to existing volume group Ids - %s", + volumeGroupIds.get())); + } else if (vfModuleIds.isPresent()) { + return Optional.of(String.format("Cannot delete vnf it is still related to existing vfModule Ids - %s", + vfModuleIds.get())); } else { return Optional.empty(); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/VolumeGroupDeleteValidator.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/VolumeGroupDeleteValidator.java index f010d47f70..e3598af31d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/VolumeGroupDeleteValidator.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/VolumeGroupDeleteValidator.java @@ -8,7 +8,9 @@ import org.onap.so.apihandlerinfra.Actions; import org.onap.so.apihandlerinfra.infra.rest.AAIDataRetrieval; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +@Component public class VolumeGroupDeleteValidator implements RequestValidator { @Autowired diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/AaiClientPropertiesImpl.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/AaiClientPropertiesImpl.java index db2b5b6b4e..822627863a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/AaiClientPropertiesImpl.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/AaiClientPropertiesImpl.java @@ -22,8 +22,8 @@ package org.onap.so.apihandlerinfra.tenantisolation; import java.net.MalformedURLException; import java.net.URL; -import org.onap.so.client.aai.AAIProperties; -import org.onap.so.client.aai.AAIVersion; +import org.onap.aaiclient.client.aai.AAIProperties; +import org.onap.aaiclient.client.aai.AAIVersion; import org.onap.so.spring.SpringContextHelper; import org.springframework.context.ApplicationContext; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java index 6942d441e6..a28298f859 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java @@ -28,12 +28,12 @@ import java.util.Map; import javax.ws.rs.NotFoundException; import org.onap.aai.domain.yang.OperationalEnvironment; import org.onap.so.apihandlerinfra.tenantisolation.exceptions.AAIClientCallFailed; -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIResourcesClient; -import org.onap.so.client.aai.entities.AAIResultWrapper; -import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.so.client.aai.entities.uri.AAIUriFactory; -import org.onap.so.client.graphinventory.entities.uri.Depth; +import org.onap.aaiclient.client.aai.AAIObjectType; +import org.onap.aaiclient.client.aai.AAIResourcesClient; +import org.onap.aaiclient.client.aai.entities.AAIResultWrapper; +import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; +import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.graphinventory.entities.uri.Depth; import org.springframework.stereotype.Component; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java index 1e5958c540..75a1c75e31 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java @@ -24,8 +24,6 @@ package org.onap.so.apihandlerinfra.tenantisolation.helpers; import org.onap.so.db.request.beans.OperationalEnvDistributionStatus; import org.onap.so.db.request.beans.OperationalEnvServiceModelStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java index f0943393ed..7aa6e0f831 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java @@ -108,7 +108,6 @@ public class SDCClientHelper { HttpClient httpClient = httpClientFactory.newJsonClient(url, ONAPComponents.SDC); httpClient.addBasicAuthHeader(sdcClientAuth, msoKey); httpClient.addAdditionalHeader("X-ECOMP-InstanceID", sdcActivateInstanceId); - httpClient.addAdditionalHeader("X-ECOMP-RequestID", UUID.randomUUID().toString()); httpClient.addAdditionalHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE); httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE); httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironment.java index 9b24a14f68..d4c66f62e4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironment.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironment.java @@ -26,8 +26,13 @@ import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; import org.json.JSONObject; import org.onap.aai.domain.yang.OperationalEnvironment; +import org.onap.aaiclient.client.aai.AAIObjectType; +import org.onap.aaiclient.client.aai.entities.AAIResultWrapper; +import org.onap.aaiclient.client.aai.entities.Relationships; +import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; +import org.onap.logging.filter.base.ErrorCode; import org.onap.so.apihandler.common.ErrorNumbers; -import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; @@ -36,13 +41,9 @@ import org.onap.so.apihandlerinfra.tenantisolation.helpers.AAIClientHelper; import org.onap.so.apihandlerinfra.tenantisolation.helpers.ActivateVnfDBHelper; import org.onap.so.apihandlerinfra.tenantisolation.helpers.SDCClientHelper; import org.onap.so.apihandlerinfra.tenantisolationbeans.ServiceModelList; -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.entities.AAIResultWrapper; -import org.onap.so.client.aai.entities.Relationships; -import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.db.request.beans.OperationalEnvDistributionStatus; import org.onap.so.db.request.beans.OperationalEnvServiceModelStatus; -import org.onap.logging.filter.base.ErrorCode; +import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.logger.MessageEnum; import org.onap.so.requestsdb.RequestsDBHelper; import org.slf4j.Logger; @@ -58,7 +59,6 @@ public class ActivateVnfOperationalEnvironment { private static final Logger logger = LoggerFactory.getLogger(ActivateVnfOperationalEnvironment.class); private static final int DEFAULT_ACTIVATE_RETRY_COUNT = 3; private static final String DISTRIBUTION_STATUS_SENT = "SENT"; - private static final String OPER_ENVIRONMENT_ID_KEY = "operational-environment-id"; @Autowired private ActivateVnfDBHelper dbHelper; @@ -97,8 +97,8 @@ public class ActivateVnfOperationalEnvironment { List<AAIResourceUri> operationalEnvironments = relationships.getRelatedAAIUris(AAIObjectType.OPERATIONAL_ENVIRONMENT); if (!operationalEnvironments.isEmpty()) { - ecompOperationalEnvironmentId = - operationalEnvironments.get(0).getURIKeys().get(OPER_ENVIRONMENT_ID_KEY); + ecompOperationalEnvironmentId = operationalEnvironments.get(0).getURIKeys().get( + AAIFluentTypeBuilder.Types.OPERATIONAL_ENVIRONMENT.getUriParams().operationalEnvironmentId); } } logger.debug(" vnfOperationalEnvironmentId : {}", vnfOperationalEnvironmentId); @@ -123,7 +123,8 @@ public class ActivateVnfOperationalEnvironment { .build(); throw new ValidateException.Builder( " The ECOMP OE was not in aai record; the value of relationship.relationship-data key: " - + OPER_ENVIRONMENT_ID_KEY, + + AAIFluentTypeBuilder.Types.OPERATIONAL_ENVIRONMENT + .getUriParams().operationalEnvironmentId, HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo) .build(); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java index 77579817ff..67c5aa2aaa 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java @@ -40,7 +40,7 @@ import org.onap.so.apihandlerinfra.tenantisolation.helpers.ActivateVnfDBHelper; import org.onap.so.apihandlerinfra.tenantisolation.helpers.SDCClientHelper; import org.onap.so.apihandlerinfra.tenantisolationbeans.Distribution; import org.onap.so.apihandlerinfra.tenantisolationbeans.DistributionStatus; -import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.aaiclient.client.aai.entities.AAIResultWrapper; import org.onap.so.db.request.beans.OperationalEnvDistributionStatus; import org.onap.so.db.request.beans.OperationalEnvServiceModelStatus; import org.onap.logging.filter.base.ErrorCode; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java index d6969a9851..23537a7687 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java @@ -37,7 +37,7 @@ import org.onap.so.apihandlerinfra.tenantisolation.exceptions.TenantIsolationExc import org.onap.so.apihandlerinfra.tenantisolation.helpers.AAIClientHelper; import org.onap.so.apihandlerinfra.tenantisolation.helpers.AAIClientObjectBuilder; import org.onap.so.apihandlerinfra.tenantisolationbeans.RelatedInstanceList; -import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.aaiclient.client.aai.entities.AAIResultWrapper; import org.onap.so.client.grm.GRMClient; import org.onap.so.client.grm.beans.OperationalInfo; import org.onap.so.client.grm.beans.Property; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironment.java index 59f7621b90..b30140cd68 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironment.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironment.java @@ -32,7 +32,7 @@ import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestrationRequest; import org.onap.so.apihandlerinfra.tenantisolation.helpers.AAIClientHelper; -import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.aaiclient.client.aai.entities.AAIResultWrapper; import org.onap.logging.filter.base.ErrorCode; import org.onap.so.logger.MessageEnum; import org.onap.so.requestsdb.RequestsDBHelper; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java index 01c7fd33f9..560622faf4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java @@ -23,9 +23,7 @@ package org.onap.so.apihandlerinfra.validation; import org.onap.so.exceptions.ValidationException; -import org.onap.so.serviceinstancebeans.CloudConfiguration; import org.onap.so.serviceinstancebeans.RequestParameters; -import com.google.common.base.Strings; public class CustomWorkflowValidation implements ValidationRule { diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AAIDeserializeTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AAIDeserializeTest.java index e6409fab87..a279144eba 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AAIDeserializeTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AAIDeserializeTest.java @@ -31,7 +31,7 @@ import javax.ws.rs.core.MediaType; import org.junit.Before; import org.junit.Test; import org.onap.aai.domain.yang.Tenant; -import org.onap.so.client.aai.AAIVersion; +import org.onap.aaiclient.client.aai.AAIVersion; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java index 979aa8fbb1..86e847234b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java @@ -103,7 +103,7 @@ public class E2EServiceInstancesTest extends BaseTest { String uri = e2eServInstancesUri + "v3"; ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); } @Test @@ -143,7 +143,7 @@ public class E2EServiceInstancesTest extends BaseTest { String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; ResponseEntity<String> response = sendRequest(inputStream("/DeleteRequest.json"), uri, HttpMethod.DELETE); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); } @Test @@ -183,14 +183,14 @@ public class E2EServiceInstancesTest extends BaseTest { String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/scale"; ResponseEntity<String> response = sendRequest(inputStream("/ScaleRequest.json"), uri, HttpMethod.POST); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); } @Test public void updateE2EServiceInstance() throws IOException { String uri = e2eServInstancesUri + "v3/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.PUT); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); } @Test @@ -240,8 +240,8 @@ public class E2EServiceInstancesTest extends BaseTest { RequestError expectedResponse = new RequestError(); ServiceException exception = new ServiceException(); exception.setMessageId("SVC1000"); - exception.setText( - "Failed calling bpmn localhost:" + env.getProperty("wiremock.server.port") + " failed to respond"); + exception.setText("Failed calling bpmn Client from http://localhost:" + env.getProperty("wiremock.server.port") + + "/mso/async/services/CompareModelofE2EServiceInstance failed to connect or respond"); expectedResponse.setServiceException(exception); String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java index ba7fe2b9cb..081f235db1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java @@ -45,9 +45,11 @@ import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.logger.HttpHeadersConstants; import org.onap.so.serviceinstancebeans.RequestReferences; import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -63,6 +65,9 @@ public class InstanceManagementTest extends BaseTest { private final ObjectMapper mapper = new ObjectMapper(); private ObjectMapper errorMapper = new ObjectMapper(); + @Autowired + InstanceManagement instanceManagement; + @Value("${wiremock.server.port}") private String wiremockPort; @@ -201,4 +206,18 @@ public class InstanceManagementTest extends BaseTest { ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + + @Test + public void workflowAndOperationNameTest() { + wireMockServer.stubFor(get(urlMatching( + ".*/workflow/search/findByArtifactUUID[?]artifactUUID=71526781-e55c-4cb7-adb3-97e09d9c76be")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("workflow_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + InfraActiveRequests activeReq = new InfraActiveRequests(); + activeReq = + instanceManagement.setWorkflowNameAndOperationName(activeReq, "71526781-e55c-4cb7-adb3-97e09d9c76be"); + assertEquals(activeReq.getWorkflowName(), "testingWorkflow"); + assertEquals(activeReq.getOperationName(), "testOperation"); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java index fcf25b23e9..f4ff19f53d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java @@ -182,7 +182,8 @@ public class ManualTasksTest extends BaseTest { RequestError expectedResponse = new RequestError(); ServiceException se = new ServiceException(); se.setMessageId("SVC1000"); - se.setText("Request Failed due to BPEL error with HTTP Status = 502"); + se.setText("Client from http://localhost:" + env.getProperty("wiremock.server.port") + + "/sobpmnengine/task/55/complete failed to connect or respond"); expectedResponse.setServiceException(se); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java index 3db2b2d96d..fdaca3566f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java @@ -85,6 +85,9 @@ public class OrchestrationRequestsUnitTest { private static final String RETRY_STATUS_MESSAGE = "RetryStatusMessage"; private static final String ROLLBACK_STATUS_MESSAGE = "RollbackStatusMessage"; private static final String TASK_INFORMATION = " TASK INFORMATION: Last task executed: Call SDNC"; + private static final String WORKFLOW_NAME = "testWorkflowName"; + private static final String OPERATION_NAME = "testOperationName"; + private static final String REQUEST_ACTION = "createInstance"; private InfraActiveRequests iar; boolean includeCloudRequest = false; private static final String ROLLBACK_EXT_SYSTEM_ERROR_SOURCE = "SDNC"; @@ -152,12 +155,80 @@ public class OrchestrationRequestsUnitTest { expected.setRequestScope(SERVICE); expected.setStartTime(new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(startTime) + " GMT"); + iar.setWorkflowName(WORKFLOW_NAME); + iar.setOperationName(OPERATION_NAME); + Request result = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest, OrchestrationRequestFormat.DETAIL.toString(), "v7"); assertThat(result, sameBeanAs(expected)); } @Test + public void mapInfraActiveRequestToRequestWithWorkflowNameAndOperationNameTest() throws ApiException { + doReturn("Last task executed: Call SDNC").when(camundaRequestHandler).getTaskName(REQUEST_ID); + InstanceReferences instanceReferences = new InstanceReferences(); + instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID); + RequestStatus requestStatus = new RequestStatus(); + requestStatus.setRequestState(iar.getRequestStatus()); + requestStatus.setStatusMessage( + String.format("FLOW STATUS: %s RETRY STATUS: %s ROLLBACK STATUS: %s RESOURCE STATUS: %s", + FLOW_STATUS + TASK_INFORMATION, RETRY_STATUS_MESSAGE, ROLLBACK_STATUS_MESSAGE, + "The vf module already exist")); + + Request expected = new Request(); + expected.setRequestId(REQUEST_ID); + expected.setOriginalRequestId(ORIGINAL_REQUEST_ID); + expected.setInstanceReferences(instanceReferences); + expected.setRequestStatus(requestStatus); + expected.setRequestScope(SERVICE); + expected.setStartTime(new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(startTime) + " GMT"); + expected.setWorkflowName(WORKFLOW_NAME); + expected.setOperationName(OPERATION_NAME); + + iar.setOriginalRequestId(ORIGINAL_REQUEST_ID); + iar.setWorkflowName(WORKFLOW_NAME); + iar.setOperationName(OPERATION_NAME); + + Request result = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest, + OrchestrationRequestFormat.DETAIL.toString(), "v8"); + assertThat(result, sameBeanAs(expected)); + } + + @Test + public void mapInfraActiveRequestToRequestWithNoWorkflowNameAndNoOperationNameTest() throws ApiException { + doReturn("Last task executed: Call SDNC").when(camundaRequestHandler).getTaskName(REQUEST_ID); + InstanceReferences instanceReferences = new InstanceReferences(); + instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID); + RequestStatus requestStatus = new RequestStatus(); + requestStatus.setRequestState(iar.getRequestStatus()); + requestStatus.setStatusMessage( + String.format("FLOW STATUS: %s RETRY STATUS: %s ROLLBACK STATUS: %s RESOURCE STATUS: %s", + FLOW_STATUS + TASK_INFORMATION, RETRY_STATUS_MESSAGE, ROLLBACK_STATUS_MESSAGE, + "The vf module already exist")); + + Request expected = new Request(); + expected.setRequestId(REQUEST_ID); + expected.setOriginalRequestId(ORIGINAL_REQUEST_ID); + expected.setInstanceReferences(instanceReferences); + expected.setRequestStatus(requestStatus); + expected.setRequestScope(SERVICE); + expected.setStartTime(new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(startTime) + " GMT"); + + + expected.setWorkflowName(REQUEST_ACTION); + expected.setRequestType(REQUEST_ACTION); + + iar.setOriginalRequestId(ORIGINAL_REQUEST_ID); + iar.setRequestAction(REQUEST_ACTION); + iar.setWorkflowName(null); + iar.setOperationName(null); + + Request result = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest, + OrchestrationRequestFormat.DETAIL.toString(), "v8"); + assertThat(result, sameBeanAs(expected)); + } + + @Test public void mapRequestStatusAndExtSysErrSrcToRequestFalseTest() throws ApiException { doReturn("Last task executed: Call SDNC").when(camundaRequestHandler).getTaskName(REQUEST_ID); InstanceReferences instanceReferences = new InstanceReferences(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java index 1332ffd913..ef90b22b01 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java @@ -26,6 +26,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -1389,7 +1390,7 @@ public class ServiceInstancesTest extends BaseTest { @Test public void replaceVfModuleInstanceNoCloudConfigurationTest() throws IOException { wireMockServer.stubFor( - get(urlPathEqualTo("/aai/v19/network/generic-vnfs/generic-vnf/ff305d54-75b4-431b-adb2-eb6b9e5ff000")) + get(urlPathMatching("/aai/v\\d+/network/generic-vnfs/generic-vnf/ff305d54-75b4-431b-adb2-eb6b9e5ff000")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("infra/Vnf.json").withStatus(org.apache.http.HttpStatus.SC_OK))); wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) @@ -2214,7 +2215,6 @@ public class ServiceInstancesTest extends BaseTest { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/UnauthorizedResponse.json") .withStatus(org.apache.http.HttpStatus.SC_UNAUTHORIZED))); wireMockServer.stubFor(get(urlMatching(".*/service/.*")) @@ -2231,7 +2231,7 @@ public class ServiceInstancesTest extends BaseTest { assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertEquals("Exception caught mapping Camunda JSON response to object", + assertEquals("Request Failed due to BPEL error with HTTP Status = 401 UNAUTHORIZED", realResponse.getServiceException().getText()); } @@ -2430,7 +2430,7 @@ public class ServiceInstancesTest extends BaseTest { ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatusCode().value()); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals("Exception caught mapping Camunda JSON response to object", realResponse.getServiceException().getText()); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrievalTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrievalTest.java new file mode 100644 index 0000000000..9d5d80592d --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrievalTest.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.apihandlerinfra.infra.rest; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import java.util.List; +import java.util.Optional; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.VfModule; +import org.onap.aai.domain.yang.VfModules; +import org.onap.aai.domain.yang.VolumeGroup; +import org.onap.aai.domain.yang.VolumeGroups; +import org.onap.aaiclient.client.aai.AAIObjectPlurals; +import org.onap.aaiclient.client.aai.AAIObjectType; +import org.onap.aaiclient.client.aai.AAIResourcesClient; +import org.onap.aaiclient.client.aai.entities.uri.AAIPluralResourceUri; +import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; + +@RunWith(MockitoJUnitRunner.class) +public class AAIDataRetrievalTest { + @Mock + private AAIResourcesClient aaiResourcesClient; + + @InjectMocks + private AAIDataRetrieval aaiDataRetrieval = new AAIDataRetrieval(); + + @Test + public void getVfModulesOfVnfTest() { + VfModules vfModules = getVfModules(); + AAIPluralResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, "vnfId"); + doReturn(Optional.of(vfModules)).when(aaiResourcesClient).get(VfModules.class, uri); + List<VfModule> vfModulesList = aaiDataRetrieval.getVfModulesOfVnf("vnfId"); + assertEquals("vfm1", vfModulesList.get(0).getVfModuleId()); + + Optional<String> vfModuleIds = aaiDataRetrieval.getVfModuleIdsByVnfId("vnfId"); + assertEquals(Optional.of("vfm1,vfm2"), vfModuleIds); + } + + @Test + public void getVfModulesOfVnfWhenNoneTest() { + VfModules vfModules = new VfModules(); + AAIPluralResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, "vnfId"); + doReturn(Optional.of(vfModules)).when(aaiResourcesClient).get(VfModules.class, uri); + List<VfModule> vfModulesList = aaiDataRetrieval.getVfModulesOfVnf("vnfId"); + assertEquals(true, vfModulesList.isEmpty()); + + Optional<String> vfModuleIds = aaiDataRetrieval.getVfModuleIdsByVnfId("vnfId"); + assertEquals(false, vfModuleIds.isPresent()); + } + + @Test + public void getVolumeGroupsOfVnfTest() throws Exception { + VolumeGroups volumeGroups = getVolumeGroups(); + AAIPluralResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId") + .relatedTo(AAIObjectPlurals.VOLUME_GROUP); + doReturn(Optional.of(volumeGroups)).when(aaiResourcesClient).get(VolumeGroups.class, uri); + List<VolumeGroup> volumeGroupList = aaiDataRetrieval.getVolumeGroupsOfVnf("vnfId"); + assertEquals("vg1", volumeGroupList.get(0).getVolumeGroupId()); + Optional<String> volumeGroupIds = aaiDataRetrieval.getVolumeGroupIdsByVnfId("vnfId"); + assertEquals(Optional.of("vg1,vg2"), volumeGroupIds); + } + + @Test + public void getVolumeGroupsOfVnfWhenNoneTest() throws Exception { + VolumeGroups volumeGroups = new VolumeGroups(); + AAIPluralResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId") + .relatedTo(AAIObjectPlurals.VOLUME_GROUP); + doReturn(Optional.of(volumeGroups)).when(aaiResourcesClient).get(VolumeGroups.class, uri); + List<VolumeGroup> volumeGroupList = aaiDataRetrieval.getVolumeGroupsOfVnf("vnfId"); + assertEquals(true, volumeGroupList.isEmpty()); + Optional<String> volumeGroupIds = aaiDataRetrieval.getVolumeGroupIdsByVnfId("vnfId"); + assertEquals(false, volumeGroupIds.isPresent()); + } + + + private VfModules getVfModules() { + VfModule vfModule1 = new VfModule(); + VfModule vfModule2 = new VfModule(); + vfModule1.setVfModuleId("vfm1"); + vfModule2.setVfModuleId("vfm2"); + VfModules vfModules = new VfModules(); + vfModules.getVfModule().add(vfModule1); + vfModules.getVfModule().add(vfModule2); + return vfModules; + } + + private VolumeGroups getVolumeGroups() { + VolumeGroup volumeGroup1 = new VolumeGroup(); + volumeGroup1.setVolumeGroupId("vg1"); + VolumeGroup volumeGroup2 = new VolumeGroup(); + volumeGroup2.setVolumeGroupId("vg2"); + VolumeGroups volumeGroups = new VolumeGroups(); + volumeGroups.getVolumeGroup().add(volumeGroup1); + volumeGroups.getVolumeGroup().add(volumeGroup2); + return volumeGroups; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java index faac11715a..389ff28dbd 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java @@ -41,11 +41,11 @@ import org.onap.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.ServiceInstance; import org.onap.aai.domain.yang.VfModule; import org.onap.aai.domain.yang.VolumeGroup; -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIResourcesClient; -import org.onap.so.client.aai.entities.AAIResultWrapper; -import org.onap.so.client.aai.entities.uri.AAIUriFactory; -import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.aaiclient.client.aai.AAIObjectType; +import org.onap.aaiclient.client.aai.AAIResourcesClient; +import org.onap.aaiclient.client.aai.entities.AAIResultWrapper; +import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.graphinventory.GraphInventoryCommonObjectMapperProvider; import org.onap.so.constants.Status; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.serviceinstancebeans.CloudConfiguration; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/validator/ServiceInstanceDeleteValidatorTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/validator/ServiceInstanceDeleteValidatorTest.java index c334d522b6..f461df3720 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/validator/ServiceInstanceDeleteValidatorTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/validator/ServiceInstanceDeleteValidatorTest.java @@ -5,6 +5,7 @@ import static org.mockito.Mockito.when; import java.util.HashMap; import java.util.Map; import java.util.Optional; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -14,6 +15,8 @@ import org.mockito.junit.MockitoJUnitRunner; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.infra.rest.AAIDataRetrieval; import org.onap.so.apihandlerinfra.infra.rest.validators.ServiceInstanceDeleteValidator; +import org.onap.so.serviceinstancebeans.RequestDetails; +import org.onap.so.serviceinstancebeans.RequestParameters; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; @@ -30,22 +33,41 @@ public class ServiceInstanceDeleteValidatorTest { private Map<String, String> instanceIdMap = new HashMap<>(); + private ServiceInstancesRequest serviceInstancesRequest; + + @Before + public void before() { + serviceInstancesRequest = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestParameters requestParameters = new RequestParameters(); + requestParameters.setaLaCarte(true); + requestDetails.setRequestParameters(requestParameters); + serviceInstancesRequest.setRequestDetails(requestDetails); + } + @Test public void validateURIMatchTest() { - assertEquals(true, serviceValidator.shouldRunFor("v8/serviceInstances/uasdfasdf", new ServiceInstancesRequest(), + assertEquals(true, serviceValidator.shouldRunFor("v8/serviceInstances/uasdfasdf", serviceInstancesRequest, Action.deleteInstance)); } @Test public void validateURINotMatchTest() { assertEquals(false, serviceValidator.shouldRunFor("v8/serviceInstances/uasdfasdf/vnfs/asdfasdf", - new ServiceInstancesRequest(), Action.deleteInstance)); + serviceInstancesRequest, Action.deleteInstance)); } @Test public void validateURINotMatch2Test() { assertEquals(false, serviceValidator.shouldRunFor("v8/serviceInstances/uasdfasdf/update", - new ServiceInstancesRequest(), Action.deleteInstance)); + serviceInstancesRequest, Action.deleteInstance)); + } + + @Test + public void validateNotALaCarteTest() { + serviceInstancesRequest.getRequestDetails().getRequestParameters().setaLaCarte(false); + assertEquals(false, serviceValidator.shouldRunFor("v8/serviceInstances/uasdfasdf", serviceInstancesRequest, + Action.deleteInstance)); } @Test diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/validator/VnfDeleteValidatorTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/validator/VnfDeleteValidatorTest.java index d4f57d3146..65ce355ad1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/validator/VnfDeleteValidatorTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/validator/VnfDeleteValidatorTest.java @@ -2,6 +2,7 @@ package org.onap.so.apihandlerinfra.infra.rest.validator; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; +import static org.mockito.Mockito.doReturn; import java.util.HashMap; import java.util.Map; import java.util.Optional; @@ -49,19 +50,34 @@ public class VnfDeleteValidatorTest { } @Test - public void validateSuccessTest() { + public void validateFailureVfModuleVnfTest() { instanceIdMap.put("vnfInstanceId", "1"); - when(aaiDataRetrieval.isVnfRelatedToVolumes("1")).thenReturn(false); + doReturn(Optional.of("test")).when(aaiDataRetrieval).getVfModuleIdsByVnfId("1"); + Optional<String> result = vnfValidator.validate(instanceIdMap, null, null); + assertEquals(true, result.isPresent()); + } + + @Test + public void validateSuccessVfModuleVnfTest() { + instanceIdMap.put("vnfInstanceId", "1"); + doReturn(Optional.empty()).when(aaiDataRetrieval).getVfModuleIdsByVnfId("1"); Optional<String> result = vnfValidator.validate(instanceIdMap, null, null); assertEquals(false, result.isPresent()); } @Test - public void validateFailureVnfTest() { + public void validateFailureVolumeGroupVnfTest() { instanceIdMap.put("vnfInstanceId", "1"); - when(aaiDataRetrieval.isVnfRelatedToVolumes("1")).thenReturn(true); + doReturn(Optional.of("test")).when(aaiDataRetrieval).getVolumeGroupIdsByVnfId("1"); Optional<String> result = vnfValidator.validate(instanceIdMap, null, null); assertEquals(true, result.isPresent()); } + @Test + public void validateSuccessVolumeGroupVnfTest() { + instanceIdMap.put("vnfInstanceId", "1"); + doReturn(Optional.empty()).when(aaiDataRetrieval).getVolumeGroupIdsByVnfId("1"); + Optional<String> result = vnfValidator.validate(instanceIdMap, null, null); + assertEquals(false, result.isPresent()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java index 3a389ce227..75d98180ac 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java @@ -40,8 +40,8 @@ import org.apache.http.HttpStatus; import org.junit.Test; import org.onap.aai.domain.yang.OperationalEnvironment; import org.onap.so.apihandlerinfra.BaseTest; -import org.onap.so.client.aai.AAIVersion; -import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.aaiclient.client.aai.AAIVersion; +import org.onap.aaiclient.client.aai.entities.AAIResultWrapper; import org.springframework.beans.factory.annotation.Autowired; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java index feebbd49d1..2cf9662b82 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java @@ -50,8 +50,8 @@ import org.onap.so.apihandlerinfra.tenantisolationbeans.RecoveryAction; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestDetails; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestParameters; import org.onap.so.apihandlerinfra.tenantisolationbeans.ServiceModelList; -import org.onap.so.client.aai.AAIVersion; -import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.aaiclient.client.aai.AAIVersion; +import org.onap.aaiclient.client.aai.entities.AAIResultWrapper; import org.onap.so.db.request.beans.InfraActiveRequests; import org.springframework.beans.factory.annotation.Autowired; import com.fasterxml.jackson.core.JsonProcessingException; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java index 9100e82beb..b21b468ce3 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java @@ -46,7 +46,7 @@ import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestrationRequest; import org.onap.so.apihandlerinfra.tenantisolationbeans.Distribution; import org.onap.so.apihandlerinfra.tenantisolationbeans.DistributionStatus; import org.onap.so.apihandlerinfra.tenantisolationbeans.Status; -import org.onap.so.client.aai.AAIVersion; +import org.onap.aaiclient.client.aai.AAIVersion; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.beans.OperationalEnvDistributionStatus; import org.onap.so.db.request.beans.OperationalEnvServiceModelStatus; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java index 0f096ee374..865bfd12a2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java @@ -44,7 +44,7 @@ import org.onap.so.apihandlerinfra.tenantisolationbeans.OperationalEnvironment; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestDetails; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestInfo; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestParameters; -import org.onap.so.client.aai.AAIVersion; +import org.onap.aaiclient.client.aai.AAIVersion; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.logging.filter.base.ErrorCode; import org.onap.so.logger.MessageEnum; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java index 6c00f8db27..59fc5075d5 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java @@ -41,7 +41,7 @@ import org.onap.aai.domain.yang.OperationalEnvironment; import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestrationRequest; -import org.onap.so.client.aai.AAIVersion; +import org.onap.aaiclient.client.aai.AAIVersion; import org.onap.so.client.grm.beans.Property; import org.onap.so.client.grm.beans.ServiceEndPointList; import org.onap.so.db.request.beans.InfraActiveRequests; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java index 9911bb8cb8..e49d8f7fe6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java @@ -41,7 +41,7 @@ import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestrationRequest; -import org.onap.so.client.aai.AAIVersion; +import org.onap.aaiclient.client.aai.AAIVersion; import org.onap.so.db.request.beans.InfraActiveRequests; import org.springframework.beans.factory.annotation.Autowired; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json index d6ed585537..5877f43a92 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json @@ -1,5 +1,6 @@ { "artifactUUID": "71526781-e55c-4cb7-adb3-97e09d9c76be", "artifactName": "testingWorkflow.bpmn", - "name": "testingWorkflow" + "name": "testingWorkflow", + "operationName": "testOperation" }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_pnf_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_pnf_Response.json index 133d8bed9b..1d6cd43bf7 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_pnf_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_pnf_Response.json @@ -1,5 +1,6 @@ { "artifactUUID": "81526781-e55c-4cb7-adb3-97e09d9c76bf", "artifactName": "testingPNFWorkflow.bpmn", - "name": "testingPNFWorkflow" + "name": "testingPNFWorkflow", + "operationName": "testPnfOperation" }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml b/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml index 1d6722278c..1429ac9b52 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml @@ -55,8 +55,8 @@ mso: versions: apiMinorVersion: 0 apiPatchVersion: 0 - camundaURL: http://localhost:${wiremock.server.port}/ - camundaAuth: E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE + camundaURL: http://localhost:${wiremock.server.port} + camundaAuth: 015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408 async: core-pool-size: 50 max-pool-size: 50 diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql index 19855bc85e..fd8c273b57 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql @@ -1300,6 +1300,8 @@ CREATE TABLE `infra_active_requests` ( `TENANT_NAME` varchar(200) DEFAULT NULL, `PRODUCT_FAMILY_NAME` varchar(200) DEFAULT NULL, `RESOURCE_STATUS_MESSAGE` longtext, + `WORKFLOW_NAME` varchar(200) DEFAULT NULL, + `OPERATION_NAME` varchar(200) DEFAULT NULL, PRIMARY KEY (`REQUEST_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ArchivedInfraRequestsRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ArchivedInfraRequestsRepository.java index 485ed8357f..f7a7c0eb30 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ArchivedInfraRequestsRepository.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ArchivedInfraRequestsRepository.java @@ -20,9 +20,7 @@ package org.onap.so.db.request.data.repository; -import java.util.List; import org.onap.so.db.request.beans.ArchivedInfraRequests; -import org.onap.so.db.request.beans.InfraActiveRequests; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InstanceNfvoMappingRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InstanceNfvoMappingRepository.java index 2e2c0872b6..31346d4383 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InstanceNfvoMappingRepository.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InstanceNfvoMappingRepository.java @@ -18,6 +18,7 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; + @RepositoryRestResource(collectionResourceRel = "instanceNfvoMapping", path = "instanceNfvoMapping") public interface InstanceNfvoMappingRepository extends JpaRepository<InstanceNfvoMapping, String> { diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvServiceModelStatusRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvServiceModelStatusRepository.java index 65a7ca12cd..f0d717df3c 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvServiceModelStatusRepository.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OperationalEnvServiceModelStatusRepository.java @@ -6,7 +6,7 @@ * ================================================================================ * 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 + * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -24,11 +24,8 @@ import java.util.List; import org.onap.so.db.request.beans.OperationalEnvServiceModelStatus; import org.onap.so.db.request.beans.OperationalEnvServiceModelStatusId; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; -import org.springframework.transaction.annotation.Transactional; @RepositoryRestResource(collectionResourceRel = "operationalEnvServiceModelStatus", path = "operationalEnvServiceModelStatus") diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ResourceOperationStatusRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ResourceOperationStatusRepository.java index 2ed2d7cb42..32e77cd598 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ResourceOperationStatusRepository.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/ResourceOperationStatusRepository.java @@ -25,7 +25,6 @@ import org.onap.so.db.request.beans.ResourceOperationStatus; import org.onap.so.db.request.beans.ResourceOperationStatusId; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; -import org.springframework.stereotype.Repository; @RepositoryRestResource(collectionResourceRel = "resourceOperationStatus", path = "resourceOperationStatus") public interface ResourceOperationStatusRepository diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/SiteStatusRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/SiteStatusRepository.java index ebae4a4cec..b67fe61c19 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/SiteStatusRepository.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/SiteStatusRepository.java @@ -23,7 +23,6 @@ package org.onap.so.db.request.data.repository; import org.onap.so.db.request.beans.SiteStatus; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; -import org.springframework.stereotype.Repository; @RepositoryRestResource(collectionResourceRel = "siteStatus", path = "siteStatus") public interface SiteStatusRepository extends JpaRepository<SiteStatus, String> { diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogComponentDistributionStatusRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogComponentDistributionStatusRepository.java index 9a89cdf783..2e1a401838 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogComponentDistributionStatusRepository.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogComponentDistributionStatusRepository.java @@ -25,7 +25,6 @@ import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus; import org.onap.so.db.request.beans.WatchdogComponentDistributionStatusId; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; -import org.springframework.stereotype.Repository; @RepositoryRestResource(collectionResourceRel = "watchdogComponentDistributionStatus", path = "watchdogComponentDistributionStatus") diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogDistributionStatusRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogDistributionStatusRepository.java index 7dfd61f8d0..a4d42e336b 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogDistributionStatusRepository.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogDistributionStatusRepository.java @@ -23,7 +23,6 @@ package org.onap.so.db.request.data.repository; import org.onap.so.db.request.beans.WatchdogDistributionStatus; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; -import org.springframework.stereotype.Repository; @RepositoryRestResource(collectionResourceRel = "watchdogDistributionStatus", path = "watchdogDistributionStatus") public interface WatchdogDistributionStatusRepository extends JpaRepository<WatchdogDistributionStatus, String> { diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogServiceModVerIdLookupRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogServiceModVerIdLookupRepository.java index cf36d0c6e6..029a3c5fff 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogServiceModVerIdLookupRepository.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/WatchdogServiceModVerIdLookupRepository.java @@ -24,7 +24,6 @@ import org.onap.so.db.request.beans.WatchdogServiceModVerIdLookup; import org.onap.so.db.request.beans.WatchdogServiceModVerIdLookupId; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; -import org.springframework.stereotype.Repository; @RepositoryRestResource(collectionResourceRel = "watchdogServiceModVerIdLookup", path = "watchdogServiceModVerIdLookup") public interface WatchdogServiceModVerIdLookupRepository diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql b/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql index 4c376c7af8..e8f2002399 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql @@ -103,8 +103,9 @@ CREATE TABLE IF NOT EXISTS PUBLIC.INFRA_ACTIVE_REQUESTS( ROLLBACK_EXT_SYSTEM_ERROR_SOURCE VARCHAR SELECTIVITY 1, TENANT_NAME VARCHAR SELECTIVITY 1, PRODUCT_FAMILY_NAME VARCHAR SELECTIVITY 1, - RESOURCE_STATUS_MESSAGE VARCHAR SELECTIVITY 36 - + RESOURCE_STATUS_MESSAGE VARCHAR SELECTIVITY 36, + WORKFLOW_NAME VARCHAR SELECTIVITY 1, + OPERATION_NAME VARCHAR SELECTIVITY 1 ); INSERT INTO PUBLIC.INFRA_ACTIVE_REQUESTS(REQUEST_ID, REQUEST_STATUS, STATUS_MESSAGE, PROGRESS, START_TIME, END_TIME, SOURCE, VNF_ID, VNF_NAME, VNF_TYPE, SERVICE_TYPE, TENANT_ID, VNF_PARAMS, VNF_OUTPUTS, REQUEST_BODY, RESPONSE_BODY, LAST_MODIFIED_BY, MODIFY_TIME, VOLUME_GROUP_ID, VOLUME_GROUP_NAME, VF_MODULE_ID, VF_MODULE_NAME, VF_MODULE_MODEL_NAME, CLOUD_REGION, CALLBACK_URL, CORRELATOR, NETWORK_ID, NETWORK_NAME, NETWORK_TYPE, REQUEST_SCOPE, REQUEST_ACTION, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, REQUESTOR_ID, CONFIGURATION_ID, CONFIGURATION_NAME, OPERATIONAL_ENV_ID, OPERATIONAL_ENV_NAME, REQUEST_URL) VALUES @@ -177,7 +178,9 @@ CREATE CACHED TABLE PUBLIC.ARCHIVED_INFRA_REQUESTS( REQUEST_URL VARCHAR SELECTIVITY 1, TENANT_NAME VARCHAR SELECTIVITY 1, PRODUCT_FAMILY_NAME VARCHAR SELECTIVITY 1, - RESOURCE_STATUS_MESSAGE VARCHAR SELECTIVITY 36 + RESOURCE_STATUS_MESSAGE VARCHAR SELECTIVITY 36, + WORKFLOW_NAME VARCHAR SELECTIVITY 1, + OPERATION_NAME VARCHAR SELECTIVITY 1 ); CREATE TABLE IF NOT EXISTS cloud_api_requests( diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ArchivedInfraRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ArchivedInfraRequests.java index 8c4d0718b1..019530aea4 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ArchivedInfraRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ArchivedInfraRequests.java @@ -78,7 +78,9 @@ public class ArchivedInfraRequests extends InfraRequests { .append("networkName", getNetworkName()).append("networkType", getNetworkType()) .append("requestorId", getRequestorId()).append("configurationId", getConfigurationId()) .append("configurationName", getConfigurationName()).append("operationalEnvId", getOperationalEnvId()) - .append("operationalEnvName", getOperationalEnvName()).append("requestUrl", getRequestUrl()).toString(); + .append("operationalEnvName", getOperationalEnvName()).append("requestUrl", getRequestUrl()) + .append("tenantName", getTenantName()).append("productFamilyName", getProductFamilyName()) + .append("workflowName", getWorkflowName()).append("operationName", getOperationName()).toString(); } } diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java index 750fa13c77..02e403c37e 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java @@ -69,10 +69,10 @@ public class InfraActiveRequests extends InfraRequests { @Override public String toString() { return new ToStringBuilder(this).append("requestId", getRequestId()).append("requestStatus", getRequestStatus()) - .append("statusMessage", getStatusMessage()).append("progress", getProgress()) - .append("startTime", getStartTime()).append("endTime", getEndTime()).append("source", getSource()) - .append("vnfId", getVnfId()).append("vnfName", getVnfName()).append("vnfType", getVnfType()) - .append("pnfName", getPnfName()).append("serviceType", getServiceType()) + .append("statusMessage", getStatusMessage()).append("resourceStatusMessage", getResourceStatusMessage()) + .append("progress", getProgress()).append("startTime", getStartTime()).append("endTime", getEndTime()) + .append("source", getSource()).append("vnfId", getVnfId()).append("vnfName", getVnfName()) + .append("vnfType", getVnfType()).append("pnfName", getPnfName()).append("serviceType", getServiceType()) .append("tenantId", getTenantId()).append("vnfParams", getVnfParams()) .append("vnfOutputs", getVnfOutputs()).append("requestBody", getRequestBody()) .append("responseBody", getResponseBody()).append("lastModifiedBy", getLastModifiedBy()) @@ -90,6 +90,7 @@ public class InfraActiveRequests extends InfraRequests { .append("originalRequestId", getOriginalRequestId()) .append("extSystemErrorSource", getExtSystemErrorSource()) .append("rollbackExtSystemErrorSource", getRollbackExtSystemErrorSource()) - .append("tenantName", getTenantName()).append("productFamilyName", getProductFamilyName()).toString(); + .append("tenantName", getTenantName()).append("productFamilyName", getProductFamilyName()) + .append("workflowName", getWorkflowName()).append("operationName", getOperationName()).toString(); } } diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java index a6d6af8a07..cf6cf687b0 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java @@ -155,6 +155,10 @@ public abstract class InfraRequests implements java.io.Serializable { private String tenantName; @Column(name = "PRODUCT_FAMILY_NAME", length = 80) private String productFamilyName; + @Column(name = "WORKFLOW_NAME", length = 200) + private String workflowName; + @Column(name = "OPERATION_NAME", length = 200) + private String operationName; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "SO_REQUEST_ID", referencedColumnName = "REQUEST_ID", updatable = false) @@ -580,6 +584,22 @@ public abstract class InfraRequests implements java.io.Serializable { this.productFamilyName = productFamilyName; } + public String getWorkflowName() { + return workflowName; + } + + public void setWorkflowName(String workflowName) { + this.workflowName = workflowName; + } + + public String getOperationName() { + return operationName; + } + + public void setOperationName(String operationName) { + this.operationName = operationName; + } + @PrePersist protected void onCreate() { if (requestScope == null) @@ -641,6 +661,7 @@ public abstract class InfraRequests implements java.io.Serializable { .append("instanceGroupName", getInstanceGroupName()).append("requestUrl", getRequestUrl()) .append("originalRequestId", originalRequestId).append("extSystemErrorSource", extSystemErrorSource) .append("rollbackExtSystemErrorSource", rollbackExtSystemErrorSource).append("tenantName", tenantName) - .append("productFamilyName", productFamilyName).toString(); + .append("productFamilyName", productFamilyName).append("workflowName", workflowName) + .append("operationName", operationName).toString(); } } diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvDistributionStatus.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvDistributionStatus.java index b50be2e8be..9727ae2236 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvDistributionStatus.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OperationalEnvDistributionStatus.java @@ -12,7 +12,7 @@ * * 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. + * 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========================================================= @@ -22,14 +22,9 @@ package org.onap.so.db.request.beans; import java.io.Serializable; import java.util.Date; -import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinColumns; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/SiteStatus.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/SiteStatus.java index da426aecef..70758b3860 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/SiteStatus.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/SiteStatus.java @@ -20,8 +20,6 @@ package org.onap.so.db.request.beans; - -import java.time.format.DateTimeFormatter; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/mso-api-handlers/pom.xml b/mso-api-handlers/pom.xml index 5c84ab1d77..db939a6868 100644 --- a/mso-api-handlers/pom.xml +++ b/mso-api-handlers/pom.xml @@ -30,6 +30,11 @@ <artifactId>httpclient</artifactId> </dependency> <dependency> + <groupId>org.onap.so</groupId> + <artifactId>aai-client</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> |