aboutsummaryrefslogtreecommitdiffstats
path: root/mso-api-handlers/mso-api-handler-common/src/main/java/org
diff options
context:
space:
mode:
Diffstat (limited to 'mso-api-handlers/mso-api-handler-common/src/main/java/org')
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java199
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaTaskClient.java96
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClient.java86
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientFactory.java66
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/ResponseHandler.java165
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java30
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/BPMNFailureException.java8
-rw-r--r--mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ClientConnectionException.java2
8 files changed, 167 insertions, 485 deletions
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..33e4740740 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);
- }
-
- @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;
+ return post(jsonReq, orchestrationURI);
}
- @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(),
@@ -113,26 +92,44 @@ public class CamundaClient extends RequestClient {
parameterObject.getRequestUri(), parameterObject.getRecipeParamXsd(),
parameterObject.getInstanceGroupId(), parameterObject.isGenerateIdsOnly());
- 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 +139,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 +157,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;
}
@@ -254,35 +251,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/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/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);