From 7ddaf390698fe5ae9143d91e7011059b3973f8ce Mon Sep 17 00:00:00 2001 From: pwielebs Date: Wed, 23 May 2018 15:31:11 +0200 Subject: Refactor of prh-aai-client Change-Id: Idbca6fe4c050c789f4479164846437039d3b549d Issue-ID: DCAEGEN2-451 Signed-off-by: pwielebs --- pom.xml | 1 + .../services/prh/service/AAIConsumerClient.java | 2 +- .../services/prh/service/AAIProducerClient.java | 51 +++++------------- .../dcaegen2/services/prh/utils/HttpUtils.java | 31 ----------- .../prh/service/AAIProducerClientTest.java | 61 ++++++++++++++++------ .../services/prh/service/utils/HttpUtilsTest.java | 42 --------------- .../services/prh/tasks/DmaapPublisherTask.java | 2 +- .../services/prh/tasks/DmaapPublisherTaskImpl.java | 8 +-- .../prh/tasks/DmaapPublisherTaskImplTest.java | 10 ++-- prh-commons/pom.xml | 27 ++++++++++ .../services/prh/model/CommonFunctions.java | 26 +++++++++ .../services/prh/model/utils/HttpUtils.java | 31 +++++++++++ .../services/prh/model/CommonFunctionsTest.java | 45 ++++++++++++++-- .../services/prh/model/utils/HttpUtilsTest.java | 41 +++++++++++++++ .../ExtendedDmaapProducerHttpClientImpl.java | 36 ++++--------- .../ExtendedDmaapProducerHttpClientImplTest.java | 31 ++++------- 16 files changed, 257 insertions(+), 188 deletions(-) delete mode 100644 prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/utils/HttpUtils.java delete mode 100644 prh-aai-client/src/test/java/org/onap/dcaegen2/services/prh/service/utils/HttpUtilsTest.java create mode 100644 prh-commons/src/main/java/org/onap/dcaegen2/services/prh/model/utils/HttpUtils.java create mode 100644 prh-commons/src/test/java/org/onap/dcaegen2/services/prh/model/utils/HttpUtilsTest.java diff --git a/pom.xml b/pom.xml index 41f6f8c3..955e6e1d 100644 --- a/pom.xml +++ b/pom.xml @@ -355,6 +355,7 @@ **/Immutable* **/GsonAdapters* **/*ForUnitTest* + **/AAIConsumer* diff --git a/prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/service/AAIConsumerClient.java b/prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/service/AAIConsumerClient.java index aa4630b5..dfacc6b1 100644 --- a/prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/service/AAIConsumerClient.java +++ b/prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/service/AAIConsumerClient.java @@ -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; diff --git a/prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/service/AAIProducerClient.java b/prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/service/AAIProducerClient.java index bb4d145e..dce326ec 100644 --- a/prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/service/AAIProducerClient.java +++ b/prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/service/AAIProducerClient.java @@ -20,19 +20,14 @@ 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 aaiHeaders; + private final Map aaiHeaders; public AAIProducerClient(AAIClientConfiguration aaiClientConfiguration) { @@ -67,16 +62,16 @@ public class AAIProducerClient implements AAIExtendedHttpClient { @Override - public Optional getHttpResponse(ConsumerDmaapModel consumerDmaapModel) throws - URISyntaxException { - return createRequest(consumerDmaapModel).flatMap(x -> { + public Optional 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 createRequest(ConsumerDmaapModel consumerDmaapModel) throws URISyntaxException { @@ -92,38 +87,20 @@ public class AAIProducerClient implements AAIExtendedHttpClient { .setPath(aaiPath + "/" + pnfName).build(); } - private ResponseHandler> 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 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 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; diff --git a/prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/utils/HttpUtils.java b/prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/utils/HttpUtils.java deleted file mode 100644 index 3d5c3abf..00000000 --- a/prh-aai-client/src/main/java/org/onap/dcaegen2/services/prh/utils/HttpUtils.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PNF-REGISTRATION-HANDLER - * ================================================================================ - * Copyright (C) 2018 NOKIA 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.dcaegen2.services.prh.utils; - -import org.apache.http.HttpStatus; - -public final class HttpUtils implements HttpStatus { - - private HttpUtils() {} - - public static boolean isSuccessfulResponseCode(Integer statusCode) { - return statusCode >= 200 && statusCode < 300; - } -} diff --git a/prh-aai-client/src/test/java/org/onap/dcaegen2/services/prh/service/AAIProducerClientTest.java b/prh-aai-client/src/test/java/org/onap/dcaegen2/services/prh/service/AAIProducerClientTest.java index ec926294..594df662 100644 --- a/prh-aai-client/src/test/java/org/onap/dcaegen2/services/prh/service/AAIProducerClientTest.java +++ b/prh-aai-client/src/test/java/org/onap/dcaegen2/services/prh/service/AAIProducerClientTest.java @@ -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 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 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 setupHeaders() { + Map 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; + + } } diff --git a/prh-aai-client/src/test/java/org/onap/dcaegen2/services/prh/service/utils/HttpUtilsTest.java b/prh-aai-client/src/test/java/org/onap/dcaegen2/services/prh/service/utils/HttpUtilsTest.java deleted file mode 100644 index 87a14799..00000000 --- a/prh-aai-client/src/test/java/org/onap/dcaegen2/services/prh/service/utils/HttpUtilsTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PNF-REGISTRATION-HANDLER - * ================================================================================ - * Copyright (C) 2018 NOKIA 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.dcaegen2.services.prh.service.utils; - -import org.apache.http.HttpStatus; -import org.junit.Test; -import org.onap.dcaegen2.services.prh.utils.HttpUtils; - -import static junit.framework.TestCase.assertFalse; -import static junit.framework.TestCase.assertTrue; - - -public class HttpUtilsTest { - - @Test - public void isSuccessfulResponseCode_shouldReturnTrue() { - assertTrue(HttpUtils.isSuccessfulResponseCode(HttpUtils.SC_ACCEPTED)); - } - - @Test - public void isSuccessfulResponseCode_shouldReturnFalse() { - assertFalse(HttpUtils.isSuccessfulResponseCode(HttpStatus.SC_BAD_GATEWAY)); - } -} \ No newline at end of file diff --git a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTask.java b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTask.java index 4e95a0d1..ba8e6e45 100644 --- a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTask.java +++ b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTask.java @@ -28,7 +28,7 @@ import org.onap.dcaegen2.services.prh.service.producer.ExtendedDmaapProducerHttp */ abstract class DmaapPublisherTask extends Task { - abstract String publish(ConsumerDmaapModel consumerDmaapModel) throws DmaapNotFoundException; + abstract Integer publish(ConsumerDmaapModel consumerDmaapModel) throws DmaapNotFoundException; abstract ExtendedDmaapProducerHttpClientImpl resolveClient(); } diff --git a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImpl.java b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImpl.java index 8f2541c8..6a514747 100644 --- a/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImpl.java +++ b/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImpl.java @@ -37,7 +37,7 @@ import org.springframework.stereotype.Component; */ @Component public class DmaapPublisherTaskImpl extends - DmaapPublisherTask { + DmaapPublisherTask { 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(); diff --git a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImplTest.java b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImplTest.java index 41d46f66..13534ce8 100644 --- a/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImplTest.java +++ b/prh-app-server/src/test/java/org/onap/dcaegen2/services/prh/tasks/DmaapPublisherTaskImplTest.java @@ -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)); diff --git a/prh-commons/pom.xml b/prh-commons/pom.xml index 00f72475..40ad85f5 100644 --- a/prh-commons/pom.xml +++ b/prh-commons/pom.xml @@ -28,6 +28,14 @@ org.immutables gson + + org.apache.httpcomponents + httpclient + + + org.apache.commons + commons-lang3 + @@ -40,5 +48,24 @@ junit-jupiter-engine test + + org.mockito + mockito-core + test + + + + + ch.qos.logback + logback-classic + + + org.slf4j + jul-to-slf4j + + + org.slf4j + log4j-over-slf4j + \ No newline at end of file diff --git a/prh-commons/src/main/java/org/onap/dcaegen2/services/prh/model/CommonFunctions.java b/prh-commons/src/main/java/org/onap/dcaegen2/services/prh/model/CommonFunctions.java index d5156e3a..f7f3d36a 100644 --- a/prh-commons/src/main/java/org/onap/dcaegen2/services/prh/model/CommonFunctions.java +++ b/prh-commons/src/main/java/org/onap/dcaegen2/services/prh/model/CommonFunctions.java @@ -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 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); + } + } } diff --git a/prh-commons/src/main/java/org/onap/dcaegen2/services/prh/model/utils/HttpUtils.java b/prh-commons/src/main/java/org/onap/dcaegen2/services/prh/model/utils/HttpUtils.java new file mode 100644 index 00000000..b280949e --- /dev/null +++ b/prh-commons/src/main/java/org/onap/dcaegen2/services/prh/model/utils/HttpUtils.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.services.prh.model.utils; + +import org.apache.http.HttpStatus; + +public final class HttpUtils implements HttpStatus { + + private HttpUtils() {} + + public static boolean isSuccessfulResponseCode(Integer statusCode) { + return statusCode >= 200 && statusCode < 300; + } +} diff --git a/prh-commons/src/test/java/org/onap/dcaegen2/services/prh/model/CommonFunctionsTest.java b/prh-commons/src/test/java/org/onap/dcaegen2/services/prh/model/CommonFunctionsTest.java index 3981901e..a2b077e5 100644 --- a/prh-commons/src/test/java/org/onap/dcaegen2/services/prh/model/CommonFunctionsTest.java +++ b/prh-commons/src/test/java/org/onap/dcaegen2/services/prh/model/CommonFunctionsTest.java @@ -20,16 +20,53 @@ 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)); } } diff --git a/prh-commons/src/test/java/org/onap/dcaegen2/services/prh/model/utils/HttpUtilsTest.java b/prh-commons/src/test/java/org/onap/dcaegen2/services/prh/model/utils/HttpUtilsTest.java new file mode 100644 index 00000000..d7295071 --- /dev/null +++ b/prh-commons/src/test/java/org/onap/dcaegen2/services/prh/model/utils/HttpUtilsTest.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA 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.dcaegen2.services.prh.model.utils; + +import org.apache.http.HttpStatus; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +public class HttpUtilsTest { + + @Test + public void isSuccessfulResponseCode_shouldReturnTrue() { + assertTrue(HttpUtils.isSuccessfulResponseCode(HttpUtils.SC_ACCEPTED)); + } + + @Test + public void isSuccessfulResponseCode_shouldReturnFalse() { + assertFalse(HttpUtils.isSuccessfulResponseCode(HttpStatus.SC_BAD_GATEWAY)); + } +} \ No newline at end of file diff --git a/prh-dmaap-client/src/main/java/org/onap/dcaegen2/services/prh/service/producer/ExtendedDmaapProducerHttpClientImpl.java b/prh-dmaap-client/src/main/java/org/onap/dcaegen2/services/prh/service/producer/ExtendedDmaapProducerHttpClientImpl.java index 72e70b98..b93c9c6b 100644 --- a/prh-dmaap-client/src/main/java/org/onap/dcaegen2/services/prh/service/producer/ExtendedDmaapProducerHttpClientImpl.java +++ b/prh-dmaap-client/src/main/java/org/onap/dcaegen2/services/prh/service/producer/ExtendedDmaapProducerHttpClientImpl.java @@ -20,27 +20,24 @@ 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 getHttpProducerResponse(ConsumerDmaapModel consumerDmaapModel) { + public Optional getHttpProducerResponse(ConsumerDmaapModel consumerDmaapModel) { this.consumerDmaapModel = consumerDmaapModel; try { return createRequest() @@ -74,9 +71,9 @@ public class ExtendedDmaapProducerHttpClientImpl { return Optional.empty(); } - private Optional executeHttpClient(HttpRequestBase httpRequestBase) { + private Optional 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 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 diff --git a/prh-dmaap-client/src/test/java/org/onap/dcaegen2/services/prh/service/producer/ExtendedDmaapProducerHttpClientImplTest.java b/prh-dmaap-client/src/test/java/org/onap/dcaegen2/services/prh/service/producer/ExtendedDmaapProducerHttpClientImplTest.java index 3cb84206..aa6810e3 100644 --- a/prh-dmaap-client/src/test/java/org/onap/dcaegen2/services/prh/service/producer/ExtendedDmaapProducerHttpClientImplTest.java +++ b/prh-dmaap-client/src/test/java/org/onap/dcaegen2/services/prh/service/producer/ExtendedDmaapProducerHttpClientImplTest.java @@ -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 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 actualResult = objectUnderTest.getHttpProducerResponse(consumerDmaapModel); - - Assertions.assertEquals(expectedResult.get(), actualResult.get()); + .thenReturn(Optional.of(expectedResult)); + Optional 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 actualResult = objectUnderTest.getHttpProducerResponse(consumerDmaapModel); - Assertions.assertEquals(Optional.empty(), actualResult); + .thenReturn(Optional.of(expectedResult)); + Optional 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); -- cgit 1.2.3-korg