6a9dccda5fe09e186873fd2a363b38ac068eb95c
[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.tasks;
18
19 import static org.junit.Assert.assertTrue;
20 import static org.junit.jupiter.api.Assertions.assertEquals;
21 import static org.mockito.ArgumentMatchers.any;
22 import static org.mockito.Mockito.doReturn;
23 import static org.mockito.Mockito.mock;
24 import static org.mockito.Mockito.spy;
25 import static org.mockito.Mockito.times;
26 import static org.mockito.Mockito.verify;
27 import static org.mockito.Mockito.verifyNoMoreInteractions;
28 import static org.mockito.Mockito.when;
29
30 import java.io.File;
31
32 import ch.qos.logback.classic.spi.ILoggingEvent;
33 import ch.qos.logback.core.read.ListAppender;
34 import java.net.URI;
35 import java.nio.file.Path;
36 import java.nio.file.Paths;
37 import java.time.Duration;
38 import java.util.ArrayList;
39 import java.util.HashMap;
40 import java.util.List;
41 import java.util.Map;
42 import org.apache.http.Header;
43 import org.apache.http.HttpResponse;
44 import org.apache.http.StatusLine;
45 import org.apache.http.client.methods.HttpPut;
46 import org.apache.http.client.methods.HttpUriRequest;
47 import org.junit.jupiter.api.BeforeAll;
48 import org.junit.jupiter.api.Test;
49 import org.mockito.ArgumentCaptor;
50 import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig;
51 import org.onap.dcaegen2.collectors.datafile.configuration.PublisherConfiguration;
52 import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException;
53 import org.onap.dcaegen2.collectors.datafile.model.Counters;
54 import org.onap.dcaegen2.collectors.datafile.model.FilePublishInformation;
55 import org.onap.dcaegen2.collectors.datafile.model.ImmutableFilePublishInformation;
56 import org.onap.dcaegen2.collectors.datafile.service.producer.DmaapProducerHttpClient;
57 import org.onap.dcaegen2.collectors.datafile.utils.LoggingUtils;
58 import org.springframework.http.HttpStatus;
59 import reactor.test.StepVerifier;
60
61 /**
62  * Tests the DataRouter publisher.
63  *
64  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 5/17/18
65  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
66  */
67 class DataRouterPublisherTest {
68
69     private static final String PRODUCT_NAME = "NrRadio";
70     private static final String VENDOR_NAME = "Ericsson";
71     private static final String LAST_EPOCH_MICROSEC = "8745745764578";
72     private static final String SOURCE_NAME = "oteNB5309";
73     private static final String START_EPOCH_MICROSEC = "8745745764578";
74     private static final String TIME_ZONE_OFFSET = "UTC+05:00";
75     private static final String PM_FILE_NAME = "A20161224.1030-1045.bin.gz";
76     private static final String FTPES_ADDRESS = "ftpes://192.168.0.101:22/ftp/rop/" + PM_FILE_NAME;
77     private static final String CHANGE_IDENTIFIER = "PM_MEAS_FILES";
78
79     private static final String COMPRESSION = "gzip";
80     private static final String FILE_FORMAT_TYPE = "org.3GPP.32.435#measCollec";
81     private static final String FILE_FORMAT_VERSION = "V10";
82     private static final String X_DMAAP_DR_META = "X-DMAAP-DR-META";
83
84     private static final String HOST = "54.45.33.2";
85     private static final String HTTPS_SCHEME = "https";
86     private static final int PORT = 1234;
87     private static final String APPLICATION_OCTET_STREAM_CONTENT_TYPE = "application/octet-stream";
88     private static final String PUBLISH_TOPIC = "publish";
89     private static final String FEED_ID = "1";
90
91     private static FilePublishInformation filePublishInformation;
92     private static DmaapProducerHttpClient httpClientMock;
93     private static AppConfig appConfig;
94     private static PublisherConfiguration publisherConfigurationMock = mock(PublisherConfiguration.class);
95     private static Map<String, String> context = new HashMap<>();
96     private static DataRouterPublisher publisherTaskUnderTestSpy;
97
98     // "https://54.45.333.2:1234/publish/1";
99     private static final String PUBLISH_URL =
100             HTTPS_SCHEME + "://" + HOST + ":" + PORT + "/" + PUBLISH_TOPIC + "/" + FEED_ID;
101
102     @BeforeAll
103     public static void setUp() {
104         when(publisherConfigurationMock.publishUrl()).thenReturn(PUBLISH_URL);
105
106         filePublishInformation = ImmutableFilePublishInformation.builder() //
107                 .productName(PRODUCT_NAME) //
108                 .vendorName(VENDOR_NAME) //
109                 .lastEpochMicrosec(LAST_EPOCH_MICROSEC) //
110                 .sourceName(SOURCE_NAME) //
111                 .startEpochMicrosec(START_EPOCH_MICROSEC) //
112                 .timeZoneOffset(TIME_ZONE_OFFSET) //
113                 .name(PM_FILE_NAME) //
114                 .location(FTPES_ADDRESS) //
115                 .internalLocation(Paths.get("target/" + PM_FILE_NAME)) //
116                 .compression("gzip") //
117                 .fileFormatType(FILE_FORMAT_TYPE) //
118                 .fileFormatVersion(FILE_FORMAT_VERSION) //
119                 .context(context) //
120                 .changeIdentifier(CHANGE_IDENTIFIER) //
121                 .build(); //
122         appConfig = mock(AppConfig.class);
123         publisherTaskUnderTestSpy = spy(new DataRouterPublisher(appConfig, new Counters()));
124     }
125
126     @Test
127     public void whenPassedObjectFits_ReturnsCorrectStatus() throws Exception {
128         prepareMocksForTests(null, Integer.valueOf(HttpStatus.OK.value()));
129         StepVerifier //
130                 .create(publisherTaskUnderTestSpy.publishFile(filePublishInformation, 1, Duration.ofSeconds(0)))
131                 .expectNext(filePublishInformation) //
132                 .verifyComplete();
133
134         ArgumentCaptor<HttpUriRequest> requestCaptor = ArgumentCaptor.forClass(HttpUriRequest.class);
135         verify(httpClientMock).addUserCredentialsToHead(any(HttpUriRequest.class));
136         verify(httpClientMock).getDmaapProducerResponseWithRedirect(requestCaptor.capture(), any());
137         verifyNoMoreInteractions(httpClientMock);
138
139         HttpPut actualPut = (HttpPut) requestCaptor.getValue();
140         URI actualUri = actualPut.getURI();
141         assertEquals(HTTPS_SCHEME, actualUri.getScheme());
142         assertEquals(HOST, actualUri.getHost());
143         assertEquals(PORT, actualUri.getPort());
144
145         Path actualPath = Paths.get(actualUri.getPath());
146         assertTrue(PUBLISH_TOPIC.equals(actualPath.getName(0).toString()));
147         assertTrue(FEED_ID.equals(actualPath.getName(1).toString()));
148         assertTrue(PM_FILE_NAME.equals(actualPath.getName(2).toString()));
149
150         Header[] contentHeaders = actualPut.getHeaders("content-type");
151         assertEquals(APPLICATION_OCTET_STREAM_CONTENT_TYPE, contentHeaders[0].getValue());
152
153         Header[] metaHeaders = actualPut.getHeaders(X_DMAAP_DR_META);
154         Map<String, String> metaHash = getMetaDataAsMap(metaHeaders);
155
156         assertEquals(PRODUCT_NAME, metaHash.get("productName"));
157         assertEquals(VENDOR_NAME, metaHash.get("vendorName"));
158         assertEquals(LAST_EPOCH_MICROSEC, metaHash.get("lastEpochMicrosec"));
159         assertEquals(SOURCE_NAME, metaHash.get("sourceName"));
160         assertEquals(START_EPOCH_MICROSEC, metaHash.get("startEpochMicrosec"));
161         assertEquals(TIME_ZONE_OFFSET, metaHash.get("timeZoneOffset"));
162         assertEquals(COMPRESSION, metaHash.get("compression"));
163         assertEquals(FTPES_ADDRESS, metaHash.get("location"));
164         assertEquals(FILE_FORMAT_TYPE, metaHash.get("fileFormatType"));
165         assertEquals(FILE_FORMAT_VERSION, metaHash.get("fileFormatVersion"));
166
167         // Note that the following line checks the number of properties that are sent to the data
168         // router.
169         // This should be 10 unless the API is updated (which is the fields checked above)
170         assertEquals(10, metaHash.size());
171     }
172
173     @Test
174     void whenPassedObjectFits_firstFailsWithExceptionThenSucceeds() throws Exception {
175         prepareMocksForTests(new DatafileTaskException("Error"), HttpStatus.OK.value());
176
177         ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(DataRouterPublisher.class);
178         StepVerifier.create(publisherTaskUnderTestSpy.publishFile(filePublishInformation, 2, Duration.ofSeconds(0)))
179                 .expectNext(filePublishInformation) //
180                 .verifyComplete();
181
182         assertTrue("Warning missing in log", logAppender.list.toString()
183                 .contains("[WARN] Publishing file " + PM_FILE_NAME + " to DR unsuccessful."));
184     }
185
186     @Test
187     public void whenPassedObjectFits_firstFailsThenSucceeds() throws Exception {
188         prepareMocksForTests(null, Integer.valueOf(HttpStatus.BAD_GATEWAY.value()),
189                 Integer.valueOf(HttpStatus.OK.value()));
190
191         StepVerifier //
192                 .create(publisherTaskUnderTestSpy.publishFile(filePublishInformation, 1, Duration.ofSeconds(0)))
193                 .expectNext(filePublishInformation) //
194                 .verifyComplete();
195
196         verify(httpClientMock, times(2)).addUserCredentialsToHead(any(HttpUriRequest.class));
197         verify(httpClientMock, times(2)).getDmaapProducerResponseWithRedirect(any(HttpUriRequest.class), any());
198         verifyNoMoreInteractions(httpClientMock);
199     }
200
201     @Test
202     public void whenPassedObjectFits_firstFailsThenFails() throws Exception {
203         prepareMocksForTests(null, Integer.valueOf(HttpStatus.BAD_GATEWAY.value()),
204                 Integer.valueOf((HttpStatus.BAD_GATEWAY.value())));
205
206         ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(DataRouterPublisher.class);
207         StepVerifier.create(publisherTaskUnderTestSpy.publishFile(filePublishInformation, 1, Duration.ofSeconds(0)))
208                 .expectErrorMessage("Retries exhausted: 1/1") //
209                 .verify();
210
211         assertTrue("Warning missing in log", logAppender.list.toString().contains("[WARN] Publishing file "
212                 + PM_FILE_NAME + " to DR unsuccessful. Response code: " + HttpStatus.BAD_GATEWAY));
213
214         verify(httpClientMock, times(2)).addUserCredentialsToHead(any(HttpUriRequest.class));
215         verify(httpClientMock, times(2)).getDmaapProducerResponseWithRedirect(any(HttpUriRequest.class), any());
216         verifyNoMoreInteractions(httpClientMock);
217     }
218
219     @SafeVarargs
220     final void prepareMocksForTests(Exception exception, Integer firstResponse, Integer... nextHttpResponses)
221             throws Exception {
222         httpClientMock = mock(DmaapProducerHttpClient.class);
223         when(appConfig.getPublisherConfiguration(CHANGE_IDENTIFIER)).thenReturn(publisherConfigurationMock);
224         doReturn(publisherConfigurationMock).when(publisherTaskUnderTestSpy).resolveConfiguration(CHANGE_IDENTIFIER);
225         doReturn(httpClientMock).when(publisherTaskUnderTestSpy).resolveClient(CHANGE_IDENTIFIER);
226
227         HttpResponse httpResponseMock = mock(HttpResponse.class);
228         if (exception == null) {
229             when(httpClientMock.getDmaapProducerResponseWithRedirect(any(HttpUriRequest.class), any()))
230                     .thenReturn(httpResponseMock);
231         } else {
232             when(httpClientMock.getDmaapProducerResponseWithRedirect(any(HttpUriRequest.class), any()))
233                     .thenThrow(exception).thenReturn(httpResponseMock);
234         }
235         StatusLine statusLineMock = mock(StatusLine.class);
236         when(httpResponseMock.getStatusLine()).thenReturn(statusLineMock);
237         when(statusLineMock.getStatusCode()).thenReturn(firstResponse, nextHttpResponses);
238
239         File file = File.createTempFile("DFC", "tmp");
240         doReturn(file).when(publisherTaskUnderTestSpy).createInputFile(Paths.get("target", PM_FILE_NAME));
241     }
242
243     private Map<String, String> getMetaDataAsMap(Header[] metaHeaders) {
244         Map<String, String> metaHash = new HashMap<>();
245         String actualMetaData = metaHeaders[0].getValue();
246         actualMetaData = actualMetaData.substring(1, actualMetaData.length() - 1);
247         actualMetaData = actualMetaData.replace("\"", "");
248         String[] commaSplitedMetaData = actualMetaData.split(",");
249         for (int i = 0; i < commaSplitedMetaData.length; i++) {
250             String[] keyValuePair = commaSplitedMetaData[i].split(":");
251             if (keyValuePair.length > 2) {
252                 List<String> arrayKeyValuePair = new ArrayList<>(keyValuePair.length);
253                 for (int j = 1; j < keyValuePair.length; j++) {
254                     arrayKeyValuePair.add(keyValuePair[j]);
255                 }
256                 keyValuePair[1] = String.join(":", arrayKeyValuePair);
257             }
258             metaHash.put(keyValuePair[0], keyValuePair[1]);
259         }
260         return metaHash;
261     }
262 }