diff options
Diffstat (limited to 'mso-api-handlers/mso-api-handler-common/src')
-rw-r--r-- | mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/CamundaClient.java | 31 | ||||
-rw-r--r-- | mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java | 3 | ||||
-rw-r--r-- | mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java | 58 | ||||
-rw-r--r-- | mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java | 86 | ||||
-rw-r--r-- | mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapperTest.java (renamed from mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionMapperTest.java) | 91 |
5 files changed, 208 insertions, 61 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 e9062effad..3ebad8b02c 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 @@ -24,6 +24,7 @@ package org.onap.so.apihandler.common; import java.io.IOException; +import java.util.UUID; import javax.xml.bind.DatatypeConverter; @@ -32,6 +33,7 @@ import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandler.camundabeans.CamundaBooleanInput; import org.onap.so.apihandler.camundabeans.CamundaInput; import org.onap.so.apihandler.camundabeans.CamundaIntegerInput; @@ -39,6 +41,7 @@ import org.onap.so.apihandler.camundabeans.CamundaRequest; import org.onap.so.apihandler.camundabeans.CamundaVIDRequest; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; +import org.slf4j.MDC; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @@ -63,6 +66,22 @@ public class CamundaClient extends RequestClient{ StringEntity input = new StringEntity(jsonReq); input.setContentType(CommonConstants.CONTENT_TYPE_JSON); msoLogger.info("Camunda Request Content: " + jsonReq); + + + post.setEntity(input); + setupHeaders(post); + + HttpResponse response = client.execute(post); + msoLogger.debug("Response is: " + 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()); + String encryptedCredentials = null; if(props!=null){ encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH); @@ -73,12 +92,6 @@ public class CamundaClient extends RequestClient{ } } } - - post.setEntity(input); - HttpResponse response = client.execute(post); - msoLogger.debug("Response is: " + response); - - return response; } @Override @@ -86,10 +99,10 @@ public class CamundaClient extends RequestClient{ throws ClientProtocolException, IOException{ HttpPost post = new HttpPost(url); msoLogger.debug(CAMUNDA_URL_MESAGE + url); - //String jsonReq = wrapRequest(camundaReqXML, requestId, serviceInstanceId, requestTimeout, schemaVersion); StringEntity input = new StringEntity(jsonReq); input.setContentType(CommonConstants.CONTENT_TYPE_JSON); + setupHeaders(post); String encryptedCredentials = null; if(props!=null){ @@ -102,6 +115,7 @@ public class CamundaClient extends RequestClient{ } } + post.setEntity(input); HttpResponse response = client.execute(post); msoLogger.debug("Response is: " + response); @@ -120,6 +134,9 @@ public class CamundaClient extends RequestClient{ StringEntity input = new StringEntity(jsonReq); input.setContentType(CommonConstants.CONTENT_TYPE_JSON); + + setupHeaders(post); + String encryptedCredentials = null; if(props!=null){ encryptedCredentials = props.getProperty(CommonConstants.CAMUNDA_AUTH); diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java index 8dba63b44b..3a35c23a86 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java @@ -43,5 +43,6 @@ public enum Action { compareModel, scaleInstance, deactivateAndCloudDelete, - scaleOut + scaleOut, + recreateInstance } 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 0e581cb48a..7c49eeadcc 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 @@ -20,11 +20,21 @@ 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; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; import org.onap.so.apihandlerinfra.logging.AlarmLoggerInfo; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; @@ -34,7 +44,6 @@ import org.onap.so.logger.MsoLogger; import org.onap.so.serviceinstancebeans.RequestError; import org.onap.so.serviceinstancebeans.ServiceException; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -45,6 +54,22 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> { private static MsoLogger logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, ApiExceptionMapper.class); private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger(); + + private final JAXBContext context; + private final Marshaller marshaller; + + @Context + private HttpHeaders headers; + + public ApiExceptionMapper() { + try { + context = JAXBContext.newInstance(RequestError.class); + marshaller = context.createMarshaller(); + } catch (JAXBException e) { + logger.debug("could not create JAXB marshaller"); + throw new IllegalStateException(e); + } + } @Override public Response toResponse(ApiException exception) { @@ -64,12 +89,23 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> { } writeErrorLog(exception, errorText, errorLoggerInfo, alarmLoggerInfo); + + List<MediaType> typeList = Optional.ofNullable(headers.getAcceptableMediaTypes()).orElse(new ArrayList<>()); + List<String> typeListString = typeList.stream().map(item -> item.toString()).collect(Collectors.toList()); + MediaType type; + if (typeListString.stream().anyMatch(item -> item.contains(MediaType.APPLICATION_XML))) { + type = MediaType.APPLICATION_XML_TYPE; + } else if (typeListString.stream().anyMatch(item -> typeListString.contains(MediaType.APPLICATION_JSON))) { + type = MediaType.APPLICATION_JSON_TYPE; + } else { + type = MediaType.APPLICATION_JSON_TYPE; + } - return buildServiceErrorResponse(errorText,messageId,variables); + return buildServiceErrorResponse(errorText,messageId,variables, type); } - protected String buildServiceErrorResponse(String errorText, String messageId, List<String> variables){ + protected String buildServiceErrorResponse(String errorText, String messageId, List<String> variables, MediaType type){ RequestError re = new RequestError(); ServiceException se = new ServiceException(); se.setMessageId(messageId); @@ -83,11 +119,18 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> { String requestErrorStr; ObjectMapper mapper = createObjectMapper(); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); try { - requestErrorStr = mapper.writeValueAsString(re); - } catch (JsonProcessingException e) { + if (MediaType.APPLICATION_JSON_TYPE.equals(type)) { + requestErrorStr = mapper.writeValueAsString(re); + } else { + StringWriter sw = new StringWriter(); + this.getMarshaller().marshal(re, sw); + requestErrorStr = sw.toString(); + } + } catch (JsonProcessingException | JAXBException e) { String errorMsg = "Exception in buildServiceErrorResponse writing exceptionType to string " + e.getMessage(); logger.error(MessageEnum.GENERAL_EXCEPTION, "BuildServiceErrorResponse", "", "", MsoLogger.ErrorCode.DataError, errorMsg, e); return errorMsg; @@ -109,4 +152,9 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> { public ObjectMapper createObjectMapper(){ return new ObjectMapper(); } + + public Marshaller getMarshaller() { + return marshaller; + } + } 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 d7052762ab..7a4b587fd2 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 @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (C) 2018 IBM. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,6 +24,7 @@ package org.onap.so.apihandler.common; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import java.io.IOException; import java.nio.file.Files; @@ -122,45 +125,60 @@ public class CamundaClientTest{ } public String inputStream(String JsonInput)throws IOException{ - JsonInput = "src/test/resources/CamundaClientTest" + JsonInput; - String input = new String(Files.readAllBytes(Paths.get(JsonInput))); - return input; - } + JsonInput = "src/test/resources/CamundaClientTest" + JsonInput; + String input = new String(Files.readAllBytes(Paths.get(JsonInput))); + return input; + } @Test public void wrapVIDRequestTest() throws IOException{ - CamundaClient testClient = new CamundaClient(); - testClient.setUrl("/mso/async/services/CreateGenericALaCarteServiceInstance"); - - String requestId = "f7ce78bb-423b-11e7-93f8-0050569a796"; - boolean isBaseVfModule = true; - int recipeTimeout = 10000; - String requestAction = "createInstance"; - String serviceInstanceId = "12345679"; - String correlationId = "12345679"; - String vnfId = "234567891"; - String vfModuleId = "345678912"; - String volumeGroupId = "456789123"; - String networkId = "567891234"; - String configurationId = "678912345"; - String serviceType = "testService"; - String vnfType = "testVnf"; - String vfModuleType = "vfModuleType"; - String networkType = "networkType"; - String requestDetails = "{requestDetails: }"; - String apiVersion = "6"; - boolean aLaCarte = true; - String requestUri = "v7/serviceInstances/assign"; - - String testResult = testClient.wrapVIDRequest(requestId, isBaseVfModule, recipeTimeout, requestAction, serviceInstanceId, correlationId, - vnfId, vfModuleId, volumeGroupId, networkId, configurationId, serviceType, - vnfType, vfModuleType, networkType, requestDetails, apiVersion, aLaCarte, requestUri, ""); - String expected = inputStream("/WrappedVIDRequest.json"); - - assertEquals(expected, testResult); + CamundaClient testClient = new CamundaClient(); + testClient.setUrl("/mso/async/services/CreateGenericALaCarteServiceInstance"); + + String requestId = "f7ce78bb-423b-11e7-93f8-0050569a796"; + boolean isBaseVfModule = true; + int recipeTimeout = 10000; + String requestAction = "createInstance"; + String serviceInstanceId = "12345679"; + String correlationId = "12345679"; + String vnfId = "234567891"; + String vfModuleId = "345678912"; + String volumeGroupId = "456789123"; + String networkId = "567891234"; + String configurationId = "678912345"; + String serviceType = "testService"; + String vnfType = "testVnf"; + String vfModuleType = "vfModuleType"; + String networkType = "networkType"; + String requestDetails = "{requestDetails: }"; + String apiVersion = "6"; + boolean aLaCarte = true; + String requestUri = "v7/serviceInstances/assign"; + + String testResult = testClient.wrapVIDRequest(requestId, isBaseVfModule, recipeTimeout, requestAction, serviceInstanceId, correlationId, + vnfId, vfModuleId, volumeGroupId, networkId, configurationId, serviceType, + vnfType, vfModuleType, networkType, requestDetails, apiVersion, aLaCarte, requestUri, ""); + String expected = inputStream("/WrappedVIDRequest.json"); + + assertEquals(expected, testResult); } - + @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)); + + } } diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionMapperTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapperTest.java index b98c47490a..e666df34f9 100644 --- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionMapperTest.java +++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapperTest.java @@ -18,39 +18,75 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.apihandlerinfra; +package org.onap.so.apihandlerinfra.exceptions; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.StringStartsWith.startsWith; +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.so.apihandler.common.ErrorNumbers; -import org.onap.so.apihandlerinfra.exceptions.*; +import java.io.IOException; +import java.io.Writer; +import java.util.Arrays; +import java.util.List; -import org.apache.http.HttpStatus; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.ApiExceptionMapper; +import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; +import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException; +import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException; +import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException; -import java.io.IOException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.anyObject; -import static org.hamcrest.core.StringStartsWith.startsWith; +@RunWith(MockitoJUnitRunner.class) public class ApiExceptionMapperTest { + @Mock + private HttpHeaders headers; + @Mock + private Marshaller marshaller; + + @InjectMocks ApiExceptionMapper mapper = new ApiExceptionMapper(); + @Before + public void setUp() { + when(headers.getAcceptableMediaTypes()).thenReturn(Arrays.asList(MediaType.APPLICATION_JSON_TYPE)); + } @Test public void testObjectMapperError() throws JsonProcessingException { ObjectMapper mockedMapper = Mockito.mock(ObjectMapper.class); Mockito.when(mockedMapper.writeValueAsString(anyObject())).thenThrow(JsonProcessingException.class); ValidateException validateException = new ValidateException.Builder("Test", 0 , null).build(); - ApiExceptionMapper mockedException = Mockito.spy(new ApiExceptionMapper()); + ApiExceptionMapper mockedException = Mockito.spy(mapper); Mockito.doReturn(mockedMapper).when(mockedException).createObjectMapper(); Response resp = mockedException.toResponse((ApiException) validateException); @@ -94,4 +130,31 @@ public class ApiExceptionMapperTest { assertEquals(resp.getStatus(), HttpStatus.SC_BAD_GATEWAY); } + + @Test + public void verifyXMLPath() throws JAXBException { + when(headers.getAcceptableMediaTypes()).thenReturn(Arrays.asList(MediaType.APPLICATION_XML_TYPE)); + BPMNFailureException bpmnException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).build(); + ApiExceptionMapper mapperSpy = Mockito.spy(mapper); + doReturn(marshaller).when(mapperSpy).getMarshaller(); + Response resp = mapperSpy.toResponse((ApiException) bpmnException); + verify(marshaller, times(1)).marshal(any(Object.class), any(Writer.class)); + } + + @Test + public void verifyMediaType() { + ApiExceptionMapper mapperSpy = Mockito.spy(mapper); + BPMNFailureException bpmnException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).build(); + when(headers.getAcceptableMediaTypes()).thenReturn(Arrays.asList(MediaType.APPLICATION_XML_TYPE.withCharset("UTF-8"))); + mapperSpy.toResponse(bpmnException); + verify(mapperSpy, times(1)).buildServiceErrorResponse(any(String.class), any(String.class), any(List.class), eq(MediaType.APPLICATION_XML_TYPE)); + when(headers.getAcceptableMediaTypes()).thenReturn(Arrays.asList(MediaType.APPLICATION_JSON_TYPE.withCharset("UTF-8"))); + mapperSpy = Mockito.spy(mapper); + mapperSpy.toResponse(bpmnException); + verify(mapperSpy, times(1)).buildServiceErrorResponse(any(String.class), any(String.class), any(List.class), eq(MediaType.APPLICATION_JSON_TYPE)); + when(headers.getAcceptableMediaTypes()).thenReturn(null); + mapperSpy = Mockito.spy(mapper); + mapperSpy.toResponse(bpmnException); + verify(mapperSpy, times(1)).buildServiceErrorResponse(any(String.class), any(String.class), any(List.class), eq(MediaType.APPLICATION_JSON_TYPE)); + } } |