<exclude>**/Immutable*</exclude>
<exclude>**/GsonAdapters*</exclude>
<exclude>**/*ForUnitTest*</exclude>
+ <exclude>**/AAIConsumer*</exclude>
</excludes>
<rules>
<rule>
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;
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;
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) {
@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 {
.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;
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;
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);
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 {
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;
+
+ }
}
*/
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();
}
*/
@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;
}
@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();
@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);
}
- private void prepareMocksForTests(String httpResponseCode) {
+ private void prepareMocksForTests(Integer httpResponseCode) {
extendedDmaapProducerHttpClient = mock(ExtendedDmaapProducerHttpClientImpl.class);
when(extendedDmaapProducerHttpClient.getHttpProducerResponse(consumerDmaapModel))
.thenReturn(Optional.of(httpResponseCode));
<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
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();
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);
+ }
+ }
}
* 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;
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 {
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);
this.dmaapContentType = configuration.dmaapContentType();
}
- public Optional<String> getHttpProducerResponse(ConsumerDmaapModel consumerDmaapModel) {
+ public Optional<Integer> getHttpProducerResponse(ConsumerDmaapModel consumerDmaapModel) {
this.consumerDmaapModel = consumerDmaapModel;
try {
return createRequest()
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);
}
}
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
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);
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);