06ff570ccb23cb5b749fbdd219c60cb22a10e6af
[dcaegen2/collectors/datafile.git] /
1 /*
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2018 NOKIA Intellectual Property, 2018-2019 Nordix Foundation. All rights reserved.
4  * ===============================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
6  * in compliance with the License. You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software distributed under the License
11  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12  * or implied. See the License for the specific language governing permissions and limitations under
13  * the License.
14  * ============LICENSE_END========================================================================
15  */
16
17 package org.onap.dcaegen2.collectors.datafile.service.producer;
18
19 import static org.mockito.ArgumentMatchers.any;
20 import static org.mockito.Mockito.doReturn;
21 import static org.mockito.Mockito.doThrow;
22 import static org.mockito.Mockito.mock;
23 import static org.mockito.Mockito.spy;
24 import static org.mockito.Mockito.verify;
25 import static org.mockito.Mockito.when;
26
27 import com.google.gson.JsonElement;
28 import com.google.gson.JsonParser;
29
30 import java.io.ByteArrayInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.net.URI;
34 import java.nio.charset.StandardCharsets;
35 import java.nio.file.Paths;
36 import java.security.KeyManagementException;
37 import java.security.KeyStoreException;
38 import java.security.NoSuchAlgorithmException;
39 import java.util.HashMap;
40 import java.util.Map;
41 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.Future;
43
44 import org.apache.commons.codec.binary.Base64;
45 import org.apache.commons.io.IOUtils;
46 import org.apache.http.HttpResponse;
47 import org.apache.http.StatusLine;
48 import org.apache.http.client.methods.HttpPut;
49 import org.apache.http.entity.ByteArrayEntity;
50 import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
51 import org.junit.jupiter.api.BeforeEach;
52 import org.junit.jupiter.api.Test;
53 import org.onap.dcaegen2.collectors.datafile.io.IFileSystemResource;
54 import org.onap.dcaegen2.collectors.datafile.model.CommonFunctions;
55 import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel;
56 import org.onap.dcaegen2.collectors.datafile.model.ImmutableConsumerDmaapModel;
57 import org.onap.dcaegen2.collectors.datafile.service.HttpUtils;
58 import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
59 import org.springframework.http.HttpHeaders;
60 import org.springframework.http.HttpStatus;
61 import org.springframework.web.util.DefaultUriBuilderFactory;
62
63 import reactor.test.StepVerifier;
64
65 /**
66  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 7/4/18
67  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
68  */
69 class DmaapProducerReactiveHttpClientTest {
70
71     private static final String FILE_NAME = "A20161224.1030-1045.bin.gz";
72     private static final String INTERNAL_LOCATION_JSON_TAG = "internalLocation";
73     private static final String NAME_JSON_TAG = "name";
74     private static final String X_DMAAP_DR_META = "X-DMAAP-DR-META";
75
76     private static final String HOST = "54.45.33.2";
77     private static final String HTTPS_SCHEME = "https";
78     private static final int PORT = 1234;
79     private static final String APPLICATION_OCTET_STREAM_CONTENT_TYPE = "application/octet-stream";
80     private static final String URI_SEPARATOR = "/";
81     private static final String PUBLISH_TOPIC = "publish";
82     private static final String DEFAULT_FEED_ID = "1";
83     private static final String FILE_CONTENT = "Just a string.";
84
85     private DmaapProducerReactiveHttpClient dmaapProducerReactiveHttpClient;
86
87     private DmaapPublisherConfiguration dmaapPublisherConfigurationMock = mock(DmaapPublisherConfiguration.class);
88     private ConsumerDmaapModel consumerDmaapModel;
89
90     private IFileSystemResource fileSystemResourceMock = mock(IFileSystemResource.class);
91     private CloseableHttpAsyncClient clientMock;
92     private HttpResponse responseMock = mock(HttpResponse.class);
93     @SuppressWarnings("unchecked")
94     private Future<HttpResponse> futureMock = mock(Future.class);
95     private StatusLine statusLine = mock(StatusLine.class);
96     private InputStream fileStream;
97
98     @BeforeEach
99     void setUp() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
100         when(dmaapPublisherConfigurationMock.dmaapHostName()).thenReturn(HOST);
101         when(dmaapPublisherConfigurationMock.dmaapProtocol()).thenReturn(HTTPS_SCHEME);
102         when(dmaapPublisherConfigurationMock.dmaapPortNumber()).thenReturn(PORT);
103         when(dmaapPublisherConfigurationMock.dmaapUserName()).thenReturn("dradmin");
104         when(dmaapPublisherConfigurationMock.dmaapUserPassword()).thenReturn("dradmin");
105         when(dmaapPublisherConfigurationMock.dmaapContentType()).thenReturn(APPLICATION_OCTET_STREAM_CONTENT_TYPE);
106         when(dmaapPublisherConfigurationMock.dmaapTopicName()).thenReturn(PUBLISH_TOPIC);
107
108         // @formatter:off
109         consumerDmaapModel = ImmutableConsumerDmaapModel.builder()
110                 .productName("NrRadio")
111                 .vendorName("Ericsson")
112                 .lastEpochMicrosec("8745745764578")
113                 .sourceName("oteNB5309")
114                 .startEpochMicrosec("8745745764578")
115                 .timeZoneOffset("UTC+05:00")
116                 .name("A20161224.1030-1045.bin.gz")
117                 .location("ftpes://192.168.0.101:22/ftp/rop/A20161224.1030-1145.bin.gz")
118                 .internalLocation("target/A20161224.1030-1045.bin.gz")
119                 .compression("gzip")
120                 .fileFormatType("org.3GPP.32.435#measCollec")
121                 .fileFormatVersion("V10")
122                 .build();
123         //formatter:on
124
125         dmaapProducerReactiveHttpClient = spy(new DmaapProducerReactiveHttpClient(dmaapPublisherConfigurationMock));
126         dmaapProducerReactiveHttpClient.setFileSystemResource(fileSystemResourceMock);
127         clientMock = mock(CloseableHttpAsyncClient.class);
128         doReturn(clientMock).when(dmaapProducerReactiveHttpClient).createWebClient();
129     }
130
131     @Test
132     void getHttpResponse_Success() throws Exception {
133         mockWebClientDependantObject();
134
135         HttpPut httpPut = new HttpPut();
136         httpPut.addHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_OCTET_STREAM_CONTENT_TYPE);
137
138         URI expectedUri = new DefaultUriBuilderFactory().builder().scheme(HTTPS_SCHEME).host(HOST).port(PORT)
139                 .path(PUBLISH_TOPIC + URI_SEPARATOR + DEFAULT_FEED_ID + URI_SEPARATOR + FILE_NAME).build();
140         httpPut.setURI(expectedUri);
141
142         JsonElement metaData = new JsonParser().parse(CommonFunctions.createJsonBody(consumerDmaapModel));
143         metaData.getAsJsonObject().remove(NAME_JSON_TAG).getAsString();
144         metaData.getAsJsonObject().remove(INTERNAL_LOCATION_JSON_TAG);
145         httpPut.addHeader(X_DMAAP_DR_META, metaData.toString());
146
147         String plainCreds = "dradmin" + ":" + "dradmin";
148         byte[] plainCredsBytes = plainCreds.getBytes(StandardCharsets.ISO_8859_1);
149         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
150         String base64Creds = new String(base64CredsBytes);
151         httpPut.addHeader("Authorization", "Basic " + base64Creds);
152
153         fileStream.reset();
154         Map<String, String> contextMap = new HashMap<>();
155         StepVerifier.create(dmaapProducerReactiveHttpClient.getDmaapProducerResponse(consumerDmaapModel, contextMap))
156         .expectNext(HttpStatus.OK).verifyComplete();
157
158         verify(fileSystemResourceMock).setPath(Paths.get("target/" + FILE_NAME));
159         InputStream fileInputStream = fileSystemResourceMock.getInputStream();
160         httpPut.setEntity(new ByteArrayEntity(IOUtils.toByteArray(fileInputStream)));
161     }
162
163     @Test
164     void getHttpResponse_Fail() throws Exception {
165         Map<String, String> contextMap = new HashMap<>();
166         doReturn(futureMock).when(clientMock).execute(any(), any());
167         doThrow(new InterruptedException()).when(futureMock).get();
168         StepVerifier.create(dmaapProducerReactiveHttpClient.getDmaapProducerResponse(consumerDmaapModel, contextMap)) //
169            .expectError() //
170            .verify(); //
171     }
172
173     private void mockWebClientDependantObject()
174             throws IOException, InterruptedException, ExecutionException {
175         fileStream = new ByteArrayInputStream(FILE_CONTENT.getBytes());
176         when(fileSystemResourceMock.getInputStream()).thenReturn(fileStream);
177         when(clientMock.execute(any(HttpPut.class), any())).thenReturn(futureMock);
178         when(futureMock.get()).thenReturn(responseMock);
179         when(responseMock.getStatusLine()).thenReturn(statusLine);
180         when(statusLine.getStatusCode()).thenReturn(HttpUtils.SC_OK);
181
182     }
183 }