2bbe8e1d1cd0e9e01ef2b3f4e102c697fd3f4d5a
[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.mock;
21 import static org.mockito.Mockito.verify;
22 import static org.mockito.Mockito.when;
23 import com.google.gson.JsonElement;
24 import com.google.gson.JsonParser;
25 import java.io.ByteArrayInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.net.URI;
29 import java.nio.charset.StandardCharsets;
30 import java.nio.file.Paths;
31 import java.util.HashMap;
32 import java.util.Map;
33 import java.util.concurrent.ExecutionException;
34 import java.util.concurrent.Future;
35 import org.apache.commons.codec.binary.Base64;
36 import org.apache.commons.io.IOUtils;
37 import org.apache.http.HttpResponse;
38 import org.apache.http.StatusLine;
39 import org.apache.http.client.methods.HttpPut;
40 import org.apache.http.entity.ByteArrayEntity;
41 import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
42 import org.junit.jupiter.api.BeforeEach;
43 import org.junit.jupiter.api.Test;
44 import org.onap.dcaegen2.collectors.datafile.io.IFileSystemResource;
45 import org.onap.dcaegen2.collectors.datafile.model.CommonFunctions;
46 import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel;
47 import org.onap.dcaegen2.collectors.datafile.model.ImmutableConsumerDmaapModel;
48 import org.onap.dcaegen2.collectors.datafile.service.HttpUtils;
49 import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
50 import org.springframework.http.HttpHeaders;
51 import org.springframework.http.HttpStatus;
52 import org.springframework.web.util.DefaultUriBuilderFactory;
53 import reactor.test.StepVerifier;
54
55 /**
56  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 7/4/18
57  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
58  */
59 class DmaapProducerReactiveHttpClientTest {
60
61     private static final String FILE_NAME = "A20161224.1030-1045.bin.gz";
62     private static final String INTERNAL_LOCATION_JSON_TAG = "internalLocation";
63     private static final String NAME_JSON_TAG = "name";
64     private static final String X_DMAAP_DR_META = "X-DMAAP-DR-META";
65
66     private static final String HOST = "54.45.33.2";
67     private static final String HTTPS_SCHEME = "https";
68     private static final int PORT = 1234;
69     private static final String APPLICATION_OCTET_STREAM_CONTENT_TYPE = "application/octet-stream";
70     private static final String URI_SEPARATOR = "/";
71     private static final String PUBLISH_TOPIC = "publish";
72     private static final String DEFAULT_FEED_ID = "1";
73     private static final String FILE_CONTENT = "Just a string.";
74
75     private DmaapProducerReactiveHttpClient dmaapProducerReactiveHttpClient;
76
77     private DmaapPublisherConfiguration dmaapPublisherConfigurationMock = mock(DmaapPublisherConfiguration.class);
78     private ConsumerDmaapModel consumerDmaapModel;
79
80     private IFileSystemResource fileSystemResourceMock = mock(IFileSystemResource.class);
81     private CloseableHttpAsyncClient clientMock;
82     private HttpResponse responseMock = mock(HttpResponse.class);
83     private Future<HttpResponse> futureMock = mock(Future.class);
84     private StatusLine statusLine = mock(StatusLine.class);
85     private InputStream fileStream;
86
87     @BeforeEach
88     void setUp() {
89         when(dmaapPublisherConfigurationMock.dmaapHostName()).thenReturn(HOST);
90         when(dmaapPublisherConfigurationMock.dmaapProtocol()).thenReturn(HTTPS_SCHEME);
91         when(dmaapPublisherConfigurationMock.dmaapPortNumber()).thenReturn(PORT);
92         when(dmaapPublisherConfigurationMock.dmaapUserName()).thenReturn("dradmin");
93         when(dmaapPublisherConfigurationMock.dmaapUserPassword()).thenReturn("dradmin");
94         when(dmaapPublisherConfigurationMock.dmaapContentType()).thenReturn(APPLICATION_OCTET_STREAM_CONTENT_TYPE);
95         when(dmaapPublisherConfigurationMock.dmaapTopicName()).thenReturn(PUBLISH_TOPIC);
96
97         // @formatter:off
98         consumerDmaapModel = ImmutableConsumerDmaapModel.builder()
99                 .productName("NrRadio")
100                 .vendorName("Ericsson")
101                 .lastEpochMicrosec("8745745764578")
102                 .sourceName("oteNB5309")
103                 .startEpochMicrosec("8745745764578")
104                 .timeZoneOffset("UTC+05:00")
105                 .name("A20161224.1030-1045.bin.gz")
106                 .location("ftpes://192.168.0.101:22/ftp/rop/A20161224.1030-1145.bin.gz")
107                 .internalLocation("target/A20161224.1030-1045.bin.gz")
108                 .compression("gzip")
109                 .fileFormatType("org.3GPP.32.435#measCollec")
110                 .fileFormatVersion("V10")
111                 .build();
112         //formatter:on
113
114         dmaapProducerReactiveHttpClient = new DmaapProducerReactiveHttpClient(dmaapPublisherConfigurationMock);
115         dmaapProducerReactiveHttpClient.setFileSystemResource(fileSystemResourceMock);
116         clientMock = mock(CloseableHttpAsyncClient.class);
117         dmaapProducerReactiveHttpClient.setWebClient(clientMock);
118     }
119
120     @Test
121     void getHttpResponse_Success() throws Exception {
122         mockWebClientDependantObject(true);
123
124         HttpPut httpPut = new HttpPut();
125         httpPut.addHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_OCTET_STREAM_CONTENT_TYPE);
126
127         URI expectedUri = new DefaultUriBuilderFactory().builder().scheme(HTTPS_SCHEME).host(HOST).port(PORT)
128                 .path(PUBLISH_TOPIC + URI_SEPARATOR + DEFAULT_FEED_ID + URI_SEPARATOR + FILE_NAME).build();
129         httpPut.setURI(expectedUri);
130
131         JsonElement metaData = new JsonParser().parse(CommonFunctions.createJsonBody(consumerDmaapModel));
132         metaData.getAsJsonObject().remove(NAME_JSON_TAG).getAsString();
133         metaData.getAsJsonObject().remove(INTERNAL_LOCATION_JSON_TAG);
134         httpPut.addHeader(X_DMAAP_DR_META, metaData.toString());
135
136         String plainCreds = "dradmin" + ":" + "dradmin";
137         byte[] plainCredsBytes = plainCreds.getBytes(StandardCharsets.ISO_8859_1);
138         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
139         String base64Creds = new String(base64CredsBytes);
140         httpPut.addHeader("Authorization", "Basic " + base64Creds);
141
142         fileStream.reset();
143         Map<String, String> contextMap = new HashMap<>();
144         StepVerifier.create(dmaapProducerReactiveHttpClient.getDmaapProducerResponse(consumerDmaapModel, contextMap))
145         .expectNext(HttpStatus.OK).verifyComplete();
146
147         verify(fileSystemResourceMock).setPath(Paths.get("target/" + FILE_NAME));
148         InputStream fileInputStream = fileSystemResourceMock.getInputStream();
149         httpPut.setEntity(new ByteArrayEntity(IOUtils.toByteArray(fileInputStream)));
150     }
151
152     @Test
153     void getHttpResponse_Fail() throws Exception {
154         mockWebClientDependantObject(false);
155         StepVerifier.create(dmaapProducerReactiveHttpClient.getDmaapProducerResponse(consumerDmaapModel, any()))
156         .expectError()
157         .verify();
158     }
159
160     private void mockWebClientDependantObject(boolean success)
161             throws IOException, InterruptedException, ExecutionException {
162         fileStream = new ByteArrayInputStream(FILE_CONTENT.getBytes());
163         when(fileSystemResourceMock.getInputStream()).thenReturn(fileStream);
164         if (success) {
165             when(clientMock.execute(any(HttpPut.class), any())).thenReturn(futureMock);
166             when(futureMock.get()).thenReturn(responseMock);
167             when(responseMock.getStatusLine()).thenReturn(statusLine);
168             when(statusLine.getStatusCode()).thenReturn(HttpUtils.SC_OK);
169         } else {
170             when(clientMock.execute(any(HttpPut.class), any())).thenReturn(futureMock);
171             when(futureMock.get()).thenThrow(new InterruptedException());
172         }
173     }
174 }