Refactor of prh-aai-client 81/48681/5
authorpwielebs <piotr.wielebski@nokia.com>
Wed, 23 May 2018 13:31:11 +0000 (15:31 +0200)
committerpwielebs <piotr.wielebski@nokia.com>
Thu, 24 May 2018 09:50:34 +0000 (11:50 +0200)
Change-Id: Idbca6fe4c050c789f4479164846437039d3b549d
Issue-ID: DCAEGEN2-451
Signed-off-by: pwielebs <piotr.wielebski@nokia.com>
14 files changed:
pom.xml
prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/service/AAIConsumerClient.java
prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/service/AAIProducerClient.java
prh-aai-client/src/test/java/org/onap/dcaegen2/services/prh/service/AAIProducerClientTest.java
prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTask.java
prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImpl.java
prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImplTest.java
prh-commons/pom.xml
prh-commons/src/main/java/org/onap/dcaegen2/services/prh/model/CommonFunctions.java
prh-commons/src/main/java/org/onap/dcaegen2/services/prh/model/utils/HttpUtils.java [moved from prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/utils/HttpUtils.java with 96% similarity]
prh-commons/src/test/java/org/onap/dcaegen2/services/prh/model/CommonFunctionsTest.java
prh-commons/src/test/java/org/onap/dcaegen2/services/prh/model/utils/HttpUtilsTest.java [moved from prh-aai-client/src/test/java/org/onap/dcaegen2/services/prh/service/utils/HttpUtilsTest.java with 85% similarity]
prh-dmaap-client/src/main/java/org/onap/dcaegen2/services/prh/service/producer/ExtendedDmaapProducerHttpClientImpl.java
prh-dmaap-client/src/test/java/org/onap/dcaegen2/services/prh/service/producer/ExtendedDmaapProducerHttpClientImplTest.java

diff --git a/pom.xml b/pom.xml
index 41f6f8c..955e6e1 100644 (file)
--- a/pom.xml
+++ b/pom.xml
                   <exclude>**/Immutable*</exclude>
                   <exclude>**/GsonAdapters*</exclude>
                   <exclude>**/*ForUnitTest*</exclude>
+                  <exclude>**/AAIConsumer*</exclude>
                 </excludes>
                 <rules>
                   <rule>
index aa4630b..dfacc6b 100644 (file)
@@ -29,7 +29,7 @@ import org.apache.http.impl.client.CloseableHttpClient;
 import org.apache.http.util.EntityUtils;
 import org.onap.dcaegen2.services.prh.config.AAIClientConfiguration;
 import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModel;
-import org.onap.dcaegen2.services.prh.utils.HttpUtils;
+import org.onap.dcaegen2.services.prh.model.utils.HttpUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
index bb4d145..dce326e 100644 (file)
 
 package org.onap.dcaegen2.services.prh.service;
 
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.ResponseHandler;
 import org.apache.http.client.methods.HttpPatch;
 import org.apache.http.client.methods.HttpRequestBase;
 import org.apache.http.client.utils.URIBuilder;
 import org.apache.http.entity.StringEntity;
 import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.util.EntityUtils;
 import org.onap.dcaegen2.services.prh.config.AAIClientConfiguration;
 import org.onap.dcaegen2.services.prh.model.CommonFunctions;
 import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModel;
-import org.onap.dcaegen2.services.prh.utils.HttpUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -53,7 +48,7 @@ public class AAIProducerClient implements AAIExtendedHttpClient {
     private final String aaiProtocol;
     private final Integer aaiHostPortNumber;
     private final String aaiPath;
-    private final Map<String, String> aaiHeaders;
+    private final Map<String,String> aaiHeaders;
 
 
     public AAIProducerClient(AAIClientConfiguration aaiClientConfiguration) {
@@ -67,16 +62,16 @@ public class AAIProducerClient implements AAIExtendedHttpClient {
 
 
     @Override
-    public Optional<Integer> getHttpResponse(ConsumerDmaapModel consumerDmaapModel) throws
-        URISyntaxException {
-        return createRequest(consumerDmaapModel).flatMap(x -> {
+    public Optional<Integer> getHttpResponse(ConsumerDmaapModel consumerDmaapModel) throws URISyntaxException {
+        return createRequest(consumerDmaapModel).flatMap(httpRequestBase -> {
             try {
-                return closeableHttpClient.execute(x, aaiResponseHandler());
+                return closeableHttpClient.execute(httpRequestBase, CommonFunctions::handleResponse);
             } catch (IOException e) {
                 logger.warn(EXCEPTION_MESSAGE, e);
                 return Optional.empty();
             }
         });
+
     }
 
     private Optional<HttpRequestBase> createRequest(ConsumerDmaapModel consumerDmaapModel) throws URISyntaxException {
@@ -92,38 +87,20 @@ public class AAIProducerClient implements AAIExtendedHttpClient {
             .setPath(aaiPath + "/" + pnfName).build();
     }
 
-    private ResponseHandler<Optional<Integer>> aaiResponseHandler() {
-        return (HttpResponse httpResponse) -> {
-            final Integer responseCode = httpResponse.getStatusLine().getStatusCode();
-            logger.info("Status code of operation: {}", responseCode);
-            final HttpEntity responseEntity = httpResponse.getEntity();
-
-            if (HttpUtils.isSuccessfulResponseCode(responseCode)) {
-                logger.trace("HTTP response successful.");
-                return Optional.of(responseCode);
-            } else {
-                String aaiResponse = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
-                logger.warn("HTTP response not successful : {}", aaiResponse);
-                return Optional.of(responseCode);
+    Optional<HttpRequestBase> createHttpRequest(URI extendedURI, ConsumerDmaapModel consumerDmaapModel) {
+        return Optional.ofNullable(CommonFunctions.createJsonBody(consumerDmaapModel)).filter(x-> !x.isEmpty()).flatMap(myJson -> {
+            try {
+                return Optional.of(createHttpPatch(extendedURI, myJson));
+            } catch (UnsupportedEncodingException e) {
+                logger.warn(EXCEPTION_MESSAGE, e);
             }
-        };
-    }
-
-    private Optional<HttpRequestBase> createHttpRequest(URI extendedURI, ConsumerDmaapModel consumerDmaapModel) {
-        return Optional.ofNullable(CommonFunctions.createJsonBody(consumerDmaapModel)).filter(x -> !x.isEmpty())
-            .flatMap(myJson -> {
-                try {
-                    return Optional.of(createHttpPatch(extendedURI, myJson));
-                } catch (UnsupportedEncodingException e) {
-                    logger.warn(EXCEPTION_MESSAGE, e);
-                }
-                return Optional.empty();
-            });
+            return Optional.empty();
+        });
     }
 
     private HttpPatch createHttpPatch(URI extendedURI, String jsonBody) throws UnsupportedEncodingException {
         HttpPatch httpPatch = new HttpPatch(extendedURI);
-        httpPatch.setEntity(new StringEntity(jsonBody));
+        httpPatch.setEntity( new StringEntity(jsonBody));
         aaiHeaders.forEach(httpPatch::addHeader);
         httpPatch.addHeader("Content-Type", "application/merge-patch+json");
         return httpPatch;
index ec92629..594df66 100644 (file)
@@ -23,19 +23,22 @@ package org.onap.dcaegen2.services.prh.service;
 import org.apache.http.client.ResponseHandler;
 import org.apache.http.client.methods.HttpPatch;
 import org.apache.http.impl.client.CloseableHttpClient;
-import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.Test;
 import org.onap.dcaegen2.services.prh.config.AAIClientConfiguration;
 import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModel;
 import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModelForUnitTest;
 
 import java.io.IOException;
+import java.io.UnsupportedEncodingException;
 import java.lang.reflect.Field;
 import java.net.URISyntaxException;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Optional;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
@@ -49,18 +52,8 @@ public class AAIProducerClientTest {
     private static ConsumerDmaapModel consumerDmaapModel = new ConsumerDmaapModelForUnitTest();
 
 
-    @Test
-    public void getHttpResponse_shouldReturnSuccessStatusCode()
-            throws IOException, URISyntaxException, NoSuchFieldException, IllegalAccessException {
-
-        //given
-        Map<String, String> aaiHeaders = new HashMap<>();
-        aaiHeaders.put("X-FromAppId", "prh");
-        aaiHeaders.put("X-TransactionId", "vv-temp");
-        aaiHeaders.put("Accept", "application/json");
-        aaiHeaders.put("Real-Time", "true");
-        aaiHeaders.put("Content-Type", "application/merge-patch+json");
-
+    @BeforeAll
+    static void setup() throws NoSuchFieldException, IllegalAccessException {
         when(aaiHttpClientConfigurationMock.aaiHost()).thenReturn("eucalyptus.es-si-eu-dhn-20.eecloud.nsn-net.net");
         when(aaiHttpClientConfigurationMock.aaiProtocol()).thenReturn("https");
         when(aaiHttpClientConfigurationMock.aaiHostPortNumber()).thenReturn(1234);
@@ -68,16 +61,41 @@ public class AAIProducerClientTest {
         when(aaiHttpClientConfigurationMock.aaiUserPassword()).thenReturn("PRH");
         when(aaiHttpClientConfigurationMock.aaiBasePath()).thenReturn("/aai/v11");
         when(aaiHttpClientConfigurationMock.aaiPnfPath()).thenReturn("/network/pnfs/pnf");
-        when(aaiHttpClientConfigurationMock.aaiHeaders()).thenReturn(aaiHeaders);
+        when(aaiHttpClientConfigurationMock.aaiHeaders()).thenReturn(setupHeaders());
 
         testedObject = new AAIProducerClient(aaiHttpClientConfigurationMock);
         setField();
+    }
+
+    @Test
+    void getHttpResponse_shouldReturnSuccessStatusCode() throws IOException, URISyntaxException {
+        // when
         when(closeableHttpClientMock.execute(any(HttpPatch.class), any(ResponseHandler.class)))
                 .thenReturn(Optional.of(SUCCESS));
         Optional<Integer> actualResult = testedObject.getHttpResponse(consumerDmaapModel);
+        // then
+        assertEquals(SUCCESS, actualResult.get());
+    }
 
-        //then
-        Assertions.assertEquals(SUCCESS, actualResult.get());
+    @Test
+    void getHttpResponse_shouldHandleIOException() throws IOException, URISyntaxException {
+        // when
+        when(closeableHttpClientMock.execute(any(HttpPatch.class), any(ResponseHandler.class)))
+                .thenThrow(new IOException("Error occur"));
+
+        testedObject.getHttpResponse(consumerDmaapModel);
+        // then
+        assertNotNull(testedObject.getHttpResponse(consumerDmaapModel));
+    }
+
+    @Test
+    void createHttpRequest_shouldCatchUnsupportedEncodingException() throws URISyntaxException, IOException {
+        // when
+        when(closeableHttpClientMock.execute(any(HttpPatch.class), any(ResponseHandler.class)))
+                .thenThrow(new UnsupportedEncodingException("A new Error"));
+        testedObject.getHttpResponse(consumerDmaapModel);
+        // then
+        assertNotNull(testedObject.getHttpResponse(consumerDmaapModel));
     }
 
     private static void setField() throws NoSuchFieldException, IllegalAccessException {
@@ -85,4 +103,15 @@ public class AAIProducerClientTest {
         field.setAccessible(true);
         field.set(testedObject, closeableHttpClientMock);
     }
+
+    private static Map<String,String> setupHeaders() {
+        Map<String, String> aaiHeaders = new HashMap<>();
+        aaiHeaders.put("X-FromAppId", "prh");
+        aaiHeaders.put("X-TransactionId", "vv-temp");
+        aaiHeaders.put("Accept", "application/json");
+        aaiHeaders.put("Real-Time", "true");
+        aaiHeaders.put("Content-Type", "application/merge-patch+json");
+        return aaiHeaders;
+
+    }
 }
index 4e95a0d..ba8e6e4 100644 (file)
@@ -28,7 +28,7 @@ import org.onap.dcaegen2.services.prh.service.producer.ExtendedDmaapProducerHttp
  */
 abstract class DmaapPublisherTask<R, S, C> extends Task<R, S, C> {
 
-    abstract String publish(ConsumerDmaapModel consumerDmaapModel) throws DmaapNotFoundException;
+    abstract Integer publish(ConsumerDmaapModel consumerDmaapModel) throws DmaapNotFoundException;
 
     abstract ExtendedDmaapProducerHttpClientImpl resolveClient();
 }
index 8f2541c..6a51474 100644 (file)
@@ -37,7 +37,7 @@ import org.springframework.stereotype.Component;
  */
 @Component
 public class DmaapPublisherTaskImpl extends
-    DmaapPublisherTask<ConsumerDmaapModel, String, DmaapPublisherConfiguration> {
+    DmaapPublisherTask<ConsumerDmaapModel, Integer, DmaapPublisherConfiguration> {
 
     private static final Logger logger = LoggerFactory.getLogger(DmaapPublisherTaskImpl.class);
     private final Config prhAppConfig;
@@ -49,15 +49,15 @@ public class DmaapPublisherTaskImpl extends
     }
 
     @Override
-    String publish(ConsumerDmaapModel consumerDmaapModel) throws DmaapNotFoundException {
+    Integer publish(ConsumerDmaapModel consumerDmaapModel) throws DmaapNotFoundException {
         logger.trace("Method called with arg {}", consumerDmaapModel);
         return extendedDmaapProducerHttpClient.getHttpProducerResponse(consumerDmaapModel)
-            .filter(response -> !response.isEmpty() && response.equals(String.valueOf(HttpStatus.OK.value())))
+            .filter(response -> response == HttpStatus.OK.value())
             .orElseThrow(() -> new DmaapNotFoundException("Incorrect response from Dmaap"));
     }
 
     @Override
-    public String execute(ConsumerDmaapModel consumerDmaapModel) throws DmaapNotFoundException {
+    public Integer execute(ConsumerDmaapModel consumerDmaapModel) throws DmaapNotFoundException {
         consumerDmaapModel = Optional.ofNullable(consumerDmaapModel)
             .orElseThrow(() -> new DmaapNotFoundException("Invoked null object to Dmaap task"));
         extendedDmaapProducerHttpClient = resolveClient();
index 41d46f6..13534ce 100644 (file)
@@ -82,22 +82,22 @@ class DmaapPublisherTaskImplTest {
     @Test
     public void whenPassedObjectFits_ReturnsCorrectStatus() throws PrhTaskException {
         //given
-        prepareMocksForTests(HttpStatus.OK.toString());
+        prepareMocksForTests(HttpStatus.OK.value());
 
         //when
-        String response = dmaapPublisherTask.execute(consumerDmaapModel);
+        Integer response = dmaapPublisherTask.execute(consumerDmaapModel);
 
         //then
         verify(extendedDmaapProducerHttpClient, times(1))
             .getHttpProducerResponse(any(ConsumerDmaapModel.class));
         verifyNoMoreInteractions(extendedDmaapProducerHttpClient);
-        Assertions.assertEquals(HttpStatus.OK.toString(), response);
+        Assertions.assertEquals((Integer) HttpStatus.OK.value(), response);
     }
 
     @Test
     public void whenPassedObjectFits_butIncorrectResponseReturns() {
         //given
-        prepareMocksForTests("400");
+        prepareMocksForTests(HttpStatus.UNAUTHORIZED.value());
 
         //when
         Executable executableFunction = () -> dmaapPublisherTask.execute(consumerDmaapModel);
@@ -110,7 +110,7 @@ class DmaapPublisherTaskImplTest {
     }
 
 
-    private void prepareMocksForTests(String httpResponseCode) {
+    private void prepareMocksForTests(Integer httpResponseCode) {
         extendedDmaapProducerHttpClient = mock(ExtendedDmaapProducerHttpClientImpl.class);
         when(extendedDmaapProducerHttpClient.getHttpProducerResponse(consumerDmaapModel))
             .thenReturn(Optional.of(httpResponseCode));
index 00f7247..40ad85f 100644 (file)
             <groupId>org.immutables</groupId>
             <artifactId>gson</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpclient</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+        </dependency>
 
         <!-- TEST DEPENDENCIES-->
         <dependency>
             <artifactId>junit-jupiter-engine</artifactId>
             <scope>test</scope>
         </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <!-- LOGGING DEPENDENCIES-->
+        <dependency>
+            <groupId>ch.qos.logback</groupId>
+            <artifactId>logback-classic</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>jul-to-slf4j</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>log4j-over-slf4j</artifactId>
+        </dependency>
     </dependencies>
 </project>
\ No newline at end of file
index d5156e3..f7f3d36 100644 (file)
@@ -22,9 +22,20 @@ package org.onap.dcaegen2.services.prh.model;
 
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.util.EntityUtils;
+import org.onap.dcaegen2.services.prh.model.utils.HttpUtils;
+import org.slf4j.LoggerFactory;
+import org.slf4j.Logger;
+import java.io.IOException;
+import java.util.Optional;
+
 
 public class CommonFunctions {
 
+    private static Logger logger = LoggerFactory.getLogger(CommonFunctions.class);
+
     private static Gson gson = new GsonBuilder().create();
 
 
@@ -33,4 +44,19 @@ public class CommonFunctions {
     public static String createJsonBody(ConsumerDmaapModel consumerDmaapModel) {
         return gson.toJson(consumerDmaapModel);
     }
+
+    public static Optional<Integer> handleResponse(HttpResponse response) throws IOException {
+        final Integer responseCode = response.getStatusLine().getStatusCode();
+        logger.trace("Status code of operation: {}", responseCode);
+        final HttpEntity responseEntity = response.getEntity();
+
+        if (HttpUtils.isSuccessfulResponseCode(responseCode)) {
+            logger.trace("HTTP response successful.");
+            return Optional.of(responseCode);
+        } else {
+            String aaiResponse = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
+            logger.warn("HTTP response not successful : {}", aaiResponse);
+            return Optional.of(responseCode);
+        }
+    }
 }
@@ -17,7 +17,7 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-package org.onap.dcaegen2.services.prh.utils;
+package org.onap.dcaegen2.services.prh.model.utils;
 
 import org.apache.http.HttpStatus;
 
index 3981901..a2b077e 100644 (file)
 
 package org.onap.dcaegen2.services.prh.model;
 
-import org.junit.jupiter.api.Assertions;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpStatus;
+import org.apache.http.StatusLine;
+import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.Test;
 
-public class CommonFunctionsTest {
+import java.io.IOException;
+import java.util.Optional;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class CommonFunctionsTest {
+    // Given
     private ConsumerDmaapModel model = new ConsumerDmaapModelForUnitTest();
     private String expectedResult = "{\"pnfName\":\"NOKnhfsadhff\",\"ipv4\":\"256.22.33.155\",\"ipv6\":\"2001:0db8:85a3:0000:0000:8a2e:0370:7334\"}";
 
+    final static HttpResponse httpResponseMock = mock(HttpResponse.class);
+    final static HttpEntity httpEntityMock = mock(HttpEntity.class);
+    final static StatusLine statusLineMock = mock(StatusLine.class);
+
+    @BeforeAll
+    static void setup() {
+        when(httpResponseMock.getEntity()).thenReturn(httpEntityMock);
+        when(httpResponseMock.getStatusLine()).thenReturn(statusLineMock);
+    }
+
+    @Test
+    void createJsonBody_shouldReturnJsonInString() {
+        assertEquals(expectedResult, CommonFunctions.createJsonBody(model));
+    }
+
+    @Test
+    void handleResponse_shouldReturn200() throws IOException {
+        // When
+        when(httpResponseMock.getStatusLine().getStatusCode()).thenReturn(HttpStatus.SC_OK);
+        // Then
+        assertEquals(Optional.of(HttpStatus.SC_OK), CommonFunctions.handleResponse(httpResponseMock));
+    }
+
     @Test
-    public void createJsonBody_shouldReturnJsonInString() {
-        Assertions.assertEquals(expectedResult, CommonFunctions.createJsonBody(model));
+    void handleResponse_shouldReturn300() throws IOException {
+        // When
+        when(httpResponseMock.getStatusLine().getStatusCode()).thenReturn(HttpStatus.SC_BAD_REQUEST);
+        // Then
+        assertEquals(Optional.of(HttpStatus.SC_BAD_REQUEST), CommonFunctions.handleResponse(httpResponseMock));
     }
 }
  * ============LICENSE_END=========================================================
  */
 
-package org.onap.dcaegen2.services.prh.service.utils;
+package org.onap.dcaegen2.services.prh.model.utils;
 
 import org.apache.http.HttpStatus;
-import org.junit.Test;
-import org.onap.dcaegen2.services.prh.utils.HttpUtils;
+import org.junit.jupiter.api.Test;
 
-import static junit.framework.TestCase.assertFalse;
-import static junit.framework.TestCase.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 
 public class HttpUtilsTest {
index 72e70b9..b93c9c6 100644 (file)
 
 package org.onap.dcaegen2.services.prh.service.producer;
 
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Optional;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.client.methods.HttpRequestBase;
 import org.apache.http.client.utils.URIBuilder;
 import org.apache.http.entity.StringEntity;
 import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.util.EntityUtils;
 import org.onap.dcaegen2.services.prh.config.DmaapPublisherConfiguration;
 import org.onap.dcaegen2.services.prh.model.CommonFunctions;
 import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModel;
 import org.onap.dcaegen2.services.prh.service.DmaapHttpClientImpl;
-import org.onap.dcaegen2.services.prh.service.HttpUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Optional;
+
 public class ExtendedDmaapProducerHttpClientImpl {
 
     private static Logger logger = LoggerFactory.getLogger(ExtendedDmaapProducerHttpClientImpl.class);
@@ -63,7 +60,7 @@ public class ExtendedDmaapProducerHttpClientImpl {
         this.dmaapContentType = configuration.dmaapContentType();
     }
 
-    public Optional<String> getHttpProducerResponse(ConsumerDmaapModel consumerDmaapModel) {
+    public Optional<Integer> getHttpProducerResponse(ConsumerDmaapModel consumerDmaapModel) {
         this.consumerDmaapModel = consumerDmaapModel;
         try {
             return createRequest()
@@ -74,9 +71,9 @@ public class ExtendedDmaapProducerHttpClientImpl {
         return Optional.empty();
     }
 
-    private Optional<String> executeHttpClient(HttpRequestBase httpRequestBase) {
+    private Optional<Integer> executeHttpClient(HttpRequestBase httpRequestBase) {
         try {
-            return closeableHttpClient.execute(httpRequestBase, this::getDmaapProducerResponseHandler);
+            return closeableHttpClient.execute(httpRequestBase, CommonFunctions::handleResponse);
         } catch (IOException e) {
             logger.warn("Exception while executing HTTP request: ", e);
         }
@@ -112,19 +109,4 @@ public class ExtendedDmaapProducerHttpClientImpl {
         }
         return Optional.empty();
     }
-
-    private Optional<String> getDmaapProducerResponseHandler(HttpResponse httpResponse) throws IOException {
-        final int responseCode = httpResponse.getStatusLine().getStatusCode();
-        logger.info("Status code of operation: {}", responseCode);
-        final HttpEntity responseEntity = httpResponse.getEntity();
-
-        if (HttpUtils.isSuccessfulResponseCode(responseCode)) {
-            logger.trace("HTTP response successful.");
-            return Optional.of("" + responseCode);
-        } else {
-            String response = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
-            logger.trace("HTTP response not successful : {}", response);
-            return Optional.of("" + responseCode);
-        }
-    }
 }
\ No newline at end of file
index 3cb8420..aa6810e 100644 (file)
@@ -42,18 +42,15 @@ import static org.mockito.Mockito.when;
 public class ExtendedDmaapProducerHttpClientImplTest {
 
     private static ExtendedDmaapProducerHttpClientImpl objectUnderTest;
-
     private static DmaapPublisherConfiguration configurationMock = mock(DmaapPublisherConfiguration.class);
     private static CloseableHttpClient closeableHttpClientMock = mock(CloseableHttpClient.class);
     private static ConsumerDmaapModel consumerDmaapModel = new ConsumerDmaapModelForUnitTest();
-
-    private static Optional<String> expectedResult = Optional.empty();
-    private static final String RESPONSE_SUCCESS = "200";
-    private static final String RESPONSE_FAILURE = "404";
+    private static Integer expectedResult;
+    private static final Integer RESPONSE_SUCCESS = 200;
+    private static final Integer RESPONSE_FAILURE = 404;
 
     @BeforeAll
     public static void init() throws NoSuchFieldException, IllegalAccessException {
-
         when(configurationMock.dmaapHostName()).thenReturn("54.45.33.2");
         when(configurationMock.dmaapProtocol()).thenReturn("https");
         when(configurationMock.dmaapPortNumber()).thenReturn(1234);
@@ -61,35 +58,29 @@ public class ExtendedDmaapProducerHttpClientImplTest {
         when(configurationMock.dmaapUserPassword()).thenReturn("PRH");
         when(configurationMock.dmaapContentType()).thenReturn("application/json");
         when(configurationMock.dmaapTopicName()).thenReturn("pnfReady");
-
         objectUnderTest = new ExtendedDmaapProducerHttpClientImpl(configurationMock);
-
         setField();
     }
 
 
     @Test
     public void getHttpResponsePost_success() throws IOException {
-        expectedResult = Optional.of(RESPONSE_SUCCESS);
-
+        expectedResult = RESPONSE_SUCCESS;
         when(closeableHttpClientMock.execute(any(HttpPost.class), any(ResponseHandler.class)))
-            .thenReturn(expectedResult);
-
-        Optional<String> actualResult = objectUnderTest.getHttpProducerResponse(consumerDmaapModel);
-
-        Assertions.assertEquals(expectedResult.get(), actualResult.get());
+            .thenReturn(Optional.of(expectedResult));
+        Optional<Integer> actualResult = objectUnderTest.getHttpProducerResponse(consumerDmaapModel);
+        Assertions.assertEquals(expectedResult, actualResult.get());
     }
 
     @Test
     public void getExtendedDetails_returnsFailure() throws IOException {
-        expectedResult = Optional.of(RESPONSE_FAILURE);
+        expectedResult = RESPONSE_FAILURE;
         when(closeableHttpClientMock.execute(any(HttpPost.class), any(ResponseHandler.class)))
-            .thenReturn(Optional.empty());
-        Optional<String> actualResult = objectUnderTest.getHttpProducerResponse(consumerDmaapModel);
-        Assertions.assertEquals(Optional.empty(), actualResult);
+            .thenReturn(Optional.of(expectedResult));
+        Optional<Integer> actualResult = objectUnderTest.getHttpProducerResponse(consumerDmaapModel);
+        Assertions.assertEquals(expectedResult, actualResult.get());
     }
 
-
     private static void setField() throws NoSuchFieldException, IllegalAccessException {
         Field field = objectUnderTest.getClass().getDeclaredField("closeableHttpClient");
         field.setAccessible(true);