Removing code smells
[dmaap/datarouter.git] / datarouter-node / src / test / java / org / onap / dmaap / datarouter / node / NodeServletTest.java
1 /*******************************************************************************
2  * ============LICENSE_START==================================================
3  * * org.onap.dmaap
4  * * ===========================================================================
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * * ===========================================================================
7  * * Licensed under the Apache License, Version 2.0 (the "License");
8  * * you may not use this file except in compliance with the License.
9  * * You may obtain a copy of the License at
10  * *
11  *  *      http://www.apache.org/licenses/LICENSE-2.0
12  * *
13  *  * Unless required by applicable law or agreed to in writing, software
14  * * distributed under the License is distributed on an "AS IS" BASIS,
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * * See the License for the specific language governing permissions and
17  * * limitations under the License.
18  * * ============LICENSE_END====================================================
19  * *
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  * *
22  ******************************************************************************/
23 package org.onap.dmaap.datarouter.node;
24
25 import ch.qos.logback.classic.spi.ILoggingEvent;
26 import ch.qos.logback.core.read.ListAppender;
27 import ch.qos.logback.classic.Logger;
28 import org.apache.commons.lang3.reflect.FieldUtils;
29 import org.junit.*;
30 import org.junit.runner.RunWith;
31 import org.mockito.Mock;
32 import org.powermock.api.mockito.PowerMockito;
33 import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
34 import org.powermock.modules.junit4.PowerMockRunner;
35 import org.slf4j.LoggerFactory;
36
37 import javax.servlet.http.HttpServletRequest;
38 import javax.servlet.http.HttpServletResponse;
39
40 import java.io.File;
41 import java.io.IOException;
42 import java.util.*;
43
44 import static org.hamcrest.Matchers.notNullValue;
45 import static org.junit.Assert.assertEquals;
46 import static org.mockito.Matchers.eq;
47 import static org.mockito.Mockito.*;
48
49 @RunWith(PowerMockRunner.class)
50 @SuppressStaticInitializationFor("org.onap.dmaap.datarouter.node.NodeConfigManager")
51 public class NodeServletTest {
52
53     private NodeServlet nodeServlet;
54     private Delivery delivery;
55
56     @Mock
57     private HttpServletRequest request;
58
59     @Mock
60     private HttpServletResponse response;
61
62     private ListAppender<ILoggingEvent> listAppender;
63
64     private NodeConfigManager config = mock(NodeConfigManager.class);
65
66     @Before
67     public void setUp() throws Exception {
68         listAppender = setTestLogger();
69         setBehalfHeader("Stub_Value");
70         when(request.getPathInfo()).thenReturn("2");
71         when(request.isSecure()).thenReturn(true);
72         createFilesAndDirectories();
73         setUpConfig();
74         setUpNodeMainDelivery();
75         delivery = mock(Delivery.class);
76         when(delivery.markTaskSuccess("spool/s/0/1", "dmaap-dr-node.1234567")).thenReturn(true);
77         nodeServlet = new NodeServlet(delivery);
78         when(request.getHeader("Authorization")).thenReturn("User1");
79         when(request.getHeader("X-DMAAP-DR-PUBLISH-ID")).thenReturn("User1");
80     }
81
82     @AfterClass
83     public static void tearDown() {
84         deleteCreatedDirectories();
85     }
86
87     @Test
88     public void Given_Request_Is_HTTP_GET_And_Config_Is_Down_Then_Service_Unavailable_Response_Is_Generated() throws Exception {
89         setNodeConfigManagerIsConfiguredToReturnFalse();
90         nodeServlet.doGet(request, response);
91         verify(response).sendError(eq(HttpServletResponse.SC_SERVICE_UNAVAILABLE));
92         verifyEnteringExitCalled(listAppender);
93     }
94
95     @Test
96     public void Given_Request_Is_HTTP_GET_And_Endpoint_Is_Internal_FetchProv_Then_No_Content_Response_Is_Generated() {
97         when(request.getPathInfo()).thenReturn("/internal/fetchProv");
98         nodeServlet.doGet(request, response);
99         verify(response).setStatus(eq(HttpServletResponse.SC_NO_CONTENT));
100         verifyEnteringExitCalled(listAppender);
101     }
102
103     @Test
104     public void Given_Request_Is_HTTP_GET_And_Endpoint_Is_ResetSubscription_Then_No_Content_Response_Is_Generated() {
105         when(request.getPathInfo()).thenReturn("/internal/resetSubscription/1");
106         nodeServlet.doGet(request, response);
107         verify(response).setStatus(eq(HttpServletResponse.SC_NO_CONTENT));
108         verifyEnteringExitCalled(listAppender);
109     }
110
111     @Test
112     public void Given_Request_Is_HTTP_GET_To_Invalid_Endpoint_Then_Not_Found_Response_Is_Generated() throws Exception {
113         when(request.getPathInfo()).thenReturn("/incorrect");
114         nodeServlet.doGet(request, response);
115         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND));
116         verifyEnteringExitCalled(listAppender);
117     }
118
119     @Test
120     public void Given_Request_Is_HTTP_PUT_And_Config_Is_Down_Then_Service_Unavailable_Response_Is_Generated() throws Exception {
121         setNodeConfigManagerIsConfiguredToReturnFalse();
122         nodeServlet.doPut(request, response);
123         verify(response).sendError(eq(HttpServletResponse.SC_SERVICE_UNAVAILABLE));
124         verifyEnteringExitCalled(listAppender);
125     }
126
127     @Test
128     public void Given_Request_Is_HTTP_PUT_And_Endpoint_Is_Incorrect_Then_Not_Found_Response_Is_Generated() throws Exception {
129         when(request.getPathInfo()).thenReturn("/incorrect/");
130         nodeServlet.doPut(request, response);
131         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
132         verifyEnteringExitCalled(listAppender);
133     }
134
135     @Test
136     public void Given_Request_Is_HTTP_PUT_And_Request_Is_Not_Secure_Then_Forbidden_Response_Is_Generated() throws Exception {
137         when(request.isSecure()).thenReturn(false);
138         nodeServlet.doPut(request, response);
139         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
140         verifyEnteringExitCalled(listAppender);
141     }
142
143     @Test
144     public void Given_Request_Is_HTTP_PUT_And_File_Id_Is_Null_Then_Not_Found_Response_Is_Generated() throws Exception {
145         when(request.getPathInfo()).thenReturn(null);
146         nodeServlet.doPut(request, response);
147         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
148         verifyEnteringExitCalled(listAppender);
149     }
150
151     @Test
152     public void Given_Request_Is_HTTP_PUT_And_Authorization_Is_Null_Then_Forbidden_Response_Is_Generated() throws Exception {
153         when(request.getHeader("Authorization")).thenReturn(null);
154         nodeServlet.doPut(request, response);
155         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
156         verifyEnteringExitCalled(listAppender);
157     }
158
159     @Test
160     public void Given_Request_Is_HTTP_PUT_And_Publish_Does_Not_Include_File_Id_Then_Not_Found_Response_Is_Generated() throws Exception {
161         when(request.getPathInfo()).thenReturn("/publish/");
162         nodeServlet.doPut(request, response);
163         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
164         verifyEnteringExitCalled(listAppender);
165     }
166
167     @Test
168     public void Given_Request_Is_HTTP_PUT_And_Publish_Not_Permitted_Then_Forbidden_Response_Is_Generated() throws Exception {
169         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
170         setNodeConfigManagerIsPublishPermittedToReturnAReason();
171         nodeServlet.doPut(request, response);
172         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
173         verifyEnteringExitCalled(listAppender);
174     }
175
176     @Test
177     public void Given_Request_Is_HTTP_PUT_And_Internal_Publish_On_Same_Node_Then_Forbidden_Response_Is_Generated() throws Exception {
178         when(request.getPathInfo()).thenReturn("/internal/publish/1/fileName");
179         setNodeConfigManagerIsPublishPermittedToReturnAReason();
180         nodeServlet.doPut(request, response);
181         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN));
182         verifyEnteringExitCalled(listAppender);
183     }
184
185     @Test
186     public void Given_Request_Is_HTTP_PUT_And_Internal_Publish_But_Invalid_File_Id_Then_Not_Found_Response_Is_Generated() throws Exception {
187         when(request.getPathInfo()).thenReturn("/internal/publish/1/");
188         nodeServlet.doPut(request, response);
189         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
190         verifyEnteringExitCalled(listAppender);
191     }
192
193     @Test
194     public void Given_Request_Is_HTTP_PUT_On_Publish_And_Ingress_Node_Is_Provided_Then_Request_Is_Redirected() throws Exception {
195         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
196         setNodeConfigManagerToAllowRedirectOnIngressNode();
197         nodeServlet.doPut(request, response);
198         verify(response).sendRedirect(anyString());
199         verifyEnteringExitCalled(listAppender);
200     }
201
202     @Test
203     public void Given_Request_Is_HTTP_PUT_On_Publish_With_Meta_Data_Too_Long_Then_Bad_Request_Response_Is_Generated() throws Exception {
204         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
205         setHeadersForValidRequest(true);
206         nodeServlet.doPut(request, response);
207         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
208     }
209
210     @Test
211     public void Given_Request_Is_HTTP_PUT_On_Publish_With_Meta_Data_Malformed_Then_Bad_Request_Response_Is_Generated() throws Exception {
212         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
213         setHeadersForValidRequest(false);
214         nodeServlet.doPut(request, response);
215         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
216     }
217
218     @Test
219     public void Given_Request_Is_HTTP_PUT_On_Publish_On_AAF_Feed_And_Cadi_Enabled_And_No_Permissions_Then_Forbidden_Response_Is_Generated() throws Exception {
220         when(config.getCadiEnabled()).thenReturn(true);
221         when(config.getAafInstance("1")).thenReturn("*");
222         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
223         setHeadersForValidRequest(true);
224         nodeServlet.doPut(request, response);
225         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
226         verifyEnteringExitCalled(listAppender);
227     }
228
229     @Test
230     public void Given_Request_Is_HTTP_DELETE_On_Publish_With_Meta_Data_Malformed_Then_Bad_Request_Response_Is_Generated() throws Exception {
231         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
232         setHeadersForValidRequest(false);
233         nodeServlet.doDelete(request, response);
234         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
235     }
236
237     @Test
238     public void Given_Request_Is_HTTP_DELETE_File_With_Invalid_Endpoint_Then_Not_Found_Response_Is_Generated() throws Exception {
239         when(request.getPathInfo()).thenReturn("/delete/1");
240         nodeServlet.doDelete(request, response);
241         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
242         verifyEnteringExitCalled(listAppender);
243     }
244
245     @Test
246     public void Given_Request_Is_HTTP_DELETE_File_And_Is_Not_Privileged_Subscription_Then_Not_Found_Response_Is_Generated() throws Exception {
247         when(request.getPathInfo()).thenReturn("/delete/1/dmaap-dr-node.1234567");
248         setUpConfigToReturnUnprivilegedSubscriber();
249         nodeServlet.doDelete(request, response);
250         verify(response).sendError(eq(HttpServletResponse.SC_UNAUTHORIZED));
251         verifyEnteringExitCalled(listAppender);
252     }
253
254     @Test
255     public void Given_Request_Is_HTTP_DELETE_File_And_Subscription_Does_Not_Exist_Then_Not_Found_Response_Is_Generated() throws Exception {
256         when(request.getPathInfo()).thenReturn("/delete/1/dmaap-dr-node.1234567");
257         setUpConfigToReturnNullOnIsDeletePermitted();
258         nodeServlet.doDelete(request, response);
259         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND));
260         verifyEnteringExitCalled(listAppender);
261     }
262
263     @Test
264     public void Given_Request_Is_HTTP_DELETE_File_Then_Request_Succeeds() throws Exception {
265         when(request.getPathInfo()).thenReturn("/delete/1/dmaap-dr-node.1234567");
266         createFilesAndDirectories();
267         nodeServlet.doDelete(request, response);
268         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
269         verifyEnteringExitCalled(listAppender);
270     }
271
272     @Test
273     public void Given_Request_Is_HTTP_DELETE_File_And_File_Does_Not_Exist_Then_Not_Found_Response_Is_Generated() throws IOException {
274         when(request.getPathInfo()).thenReturn("/delete/1/nonExistingFile");
275         nodeServlet.doDelete(request, response);
276         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
277         verifyEnteringExitCalled(listAppender);
278     }
279
280     private void setBehalfHeader(String headerValue) {
281         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF")).thenReturn(headerValue);
282     }
283
284     private ListAppender<ILoggingEvent> setTestLogger() {
285         Logger Logger = (Logger) LoggerFactory.getLogger(NodeServlet.class);
286         ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
287         listAppender.start();
288         Logger.addAppender(listAppender);
289         return listAppender;
290     }
291
292     private void verifyEnteringExitCalled(ListAppender<ILoggingEvent> listAppender) {
293         assertEquals("EELF0004I  Entering data router node component with RequestId and InvocationId", listAppender.list.get(0).getMessage());
294         assertEquals("EELF0005I  Exiting data router node component with RequestId and InvocationId", listAppender.list.get(listAppender.list.size() -1).getMessage());
295     }
296
297     private void setUpConfig() throws IllegalAccessException {
298         PowerMockito.mockStatic(NodeConfigManager.class);
299         when(config.isShutdown()).thenReturn(false);
300         when(config.isConfigured()).thenReturn(true);
301         when(config.getSpoolDir()).thenReturn("spool/f");
302         when(config.getSpoolBase()).thenReturn("spool");
303         when(config.getLogDir()).thenReturn("log/dir");
304         when(config.getPublishId()).thenReturn("User1");
305         when(config.isAnotherNode(anyString(), anyString())).thenReturn(true);
306         when(config.getEventLogInterval()).thenReturn("40");
307         when(config.isDeletePermitted("1")).thenReturn(true);
308         when(config.getAllDests()).thenReturn(new DestInfo[0]);
309         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
310         FieldUtils.writeDeclaredStaticField(NodeMain.class, "nodeConfigManager", config, true);
311         PowerMockito.when(NodeConfigManager.getInstance()).thenReturn(config);
312     }
313
314     private void setUpConfigToReturnUnprivilegedSubscriber() throws IllegalAccessException {
315         NodeConfigManager config = mock(NodeConfigManager.class);
316         PowerMockito.mockStatic(NodeConfigManager.class);
317         when(config.isShutdown()).thenReturn(false);
318         when(config.isConfigured()).thenReturn(true);
319         when(config.isDeletePermitted("1")).thenReturn(false);
320         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
321         FieldUtils.writeDeclaredStaticField(NodeMain.class, "nodeConfigManager", config, true);
322         PowerMockito.when(NodeConfigManager.getInstance()).thenReturn(config);
323     }
324
325     private void setUpConfigToReturnNullOnIsDeletePermitted() throws IllegalAccessException {
326         NodeConfigManager config = mock(NodeConfigManager.class);
327         PowerMockito.mockStatic(NodeConfigManager.class);
328         when(config.isShutdown()).thenReturn(false);
329         when(config.isConfigured()).thenReturn(true);
330         when(config.isDeletePermitted("1")).thenThrow(new NullPointerException());
331         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
332         FieldUtils.writeDeclaredStaticField(NodeMain.class, "nodeConfigManager", config, true);
333         PowerMockito.when(NodeConfigManager.getInstance()).thenReturn(config);
334     }
335
336     private void setUpNodeMainDelivery() throws IllegalAccessException{
337         Delivery delivery = mock(Delivery.class);
338         doNothing().when(delivery).resetQueue(anyObject());
339         FieldUtils.writeDeclaredStaticField(NodeMain.class, "delivery", delivery, true);
340     }
341
342     private void setNodeConfigManagerIsConfiguredToReturnFalse() throws IllegalAccessException{
343         NodeConfigManager config = mock(NodeConfigManager.class);
344         when(config.isConfigured()).thenReturn(false);
345         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
346     }
347
348     private void setNodeConfigManagerIsPublishPermittedToReturnAReason() throws IllegalAccessException{
349         NodeConfigManager config = mock(NodeConfigManager.class);
350         when(config.isShutdown()).thenReturn(false);
351         when(config.isConfigured()).thenReturn(true);
352         when(config.getSpoolDir()).thenReturn("spool/dir");
353         when(config.getLogDir()).thenReturn("log/dir");
354         when(config.isPublishPermitted(anyString(), anyString(), anyString())).thenReturn("Not Permitted");
355         when(config.isAnotherNode(anyString(), anyString())).thenReturn(false);
356         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
357     }
358
359     private void setNodeConfigManagerToAllowRedirectOnIngressNode() throws IllegalAccessException{
360         NodeConfigManager config = mock(NodeConfigManager.class);
361         when(config.isShutdown()).thenReturn(false);
362         when(config.isConfigured()).thenReturn(true);
363         when(config.getSpoolDir()).thenReturn("spool/dir");
364         when(config.getLogDir()).thenReturn("log/dir");
365         when(config.getPublishId()).thenReturn("User1");
366         when(config.isAnotherNode(anyString(), anyString())).thenReturn(true);
367         when(config.getAuthUser(anyString(), anyString())).thenReturn("User1");
368         when(config.getIngressNode(anyString(), anyString(), anyString())).thenReturn("NewNode");
369         when(config.getExtHttpsPort()).thenReturn(8080);
370         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
371     }
372
373     private String createLargeMetaDataString() {
374         StringBuilder myString = new StringBuilder("meta");
375         for (int i = 0; i <= 4098; ++i) {
376             myString.append('x');
377         }
378         return myString.toString();
379     }
380
381     private void setHeadersForValidRequest(boolean isMetaTooLong) {
382         String metaDataString;
383         if (isMetaTooLong) {
384             metaDataString = createLargeMetaDataString();
385         } else {
386             metaDataString = "?#@><";
387         }
388         List<String> headers = new ArrayList<>();
389         headers.add("Content-Type");
390         headers.add("X-DMAAP-DR-ON-BEHALF-OF");
391         headers.add("X-DMAAP-DR-META");
392         Enumeration<String> headerNames = Collections.enumeration(headers);
393         when(request.getHeaderNames()).thenReturn(headerNames);
394         Enumeration<String> contentTypeHeader = Collections.enumeration(Arrays.asList("text/plain"));
395         Enumeration<String> behalfHeader = Collections.enumeration(Arrays.asList("User1"));
396         Enumeration<String> metaDataHeader = Collections.enumeration(Arrays.asList(metaDataString));
397         when(request.getHeaders("Content-Type")).thenReturn(contentTypeHeader);
398         when(request.getHeaders("X-DMAAP-DR-ON-BEHALF-OF")).thenReturn(behalfHeader);
399         when(request.getHeaders("X-DMAAP-DR-META")).thenReturn(metaDataHeader);
400     }
401
402     private void createFilesAndDirectories() throws IOException {
403         File nodeDir = new File("spool/n/172.0.0.1");
404         File spoolDir = new File("spool/s/0/1");
405         File dataFile = new File("spool/s/0/1/dmaap-dr-node.1234567");
406         File metaDataFile = new File("spool/s/0/1/dmaap-dr-node.1234567.M");
407         nodeDir.mkdirs();
408         spoolDir.mkdirs();
409         dataFile.createNewFile();
410         metaDataFile.createNewFile();
411     }
412
413     private static void deleteCreatedDirectories() {
414         File spoolDir = new File("spool");
415         delete(spoolDir);
416     }
417
418     private static void delete(File file) {
419         if (file.isDirectory()) {
420             for (File f: file.listFiles()) {
421                 delete(f);
422             }
423         }
424         if (!file.delete()) {
425             System.out.println("Failed to delete: " + file);
426         }
427     }
428 }