update DR logging to log under one system
[dmaap/datarouter.git] / datarouter-prov / src / test / java / org / onap / dmaap / datarouter / provisioning / InternalServletTest.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.provisioning;
24
25 import static org.hamcrest.Matchers.notNullValue;
26 import static org.mockito.Matchers.anyString;
27 import static org.mockito.Matchers.argThat;
28 import static org.mockito.Matchers.eq;
29 import static org.mockito.Mockito.mock;
30 import static org.mockito.Mockito.verify;
31 import static org.mockito.Mockito.when;
32 import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
33
34 import java.io.File;
35 import java.net.InetAddress;
36 import javax.persistence.EntityManager;
37 import javax.persistence.EntityManagerFactory;
38 import javax.persistence.Persistence;
39 import javax.servlet.ServletInputStream;
40 import javax.servlet.ServletOutputStream;
41 import javax.servlet.http.HttpServletRequest;
42 import javax.servlet.http.HttpServletResponse;
43
44 import ch.qos.logback.classic.spi.ILoggingEvent;
45 import ch.qos.logback.core.read.ListAppender;
46 import org.apache.commons.lang3.reflect.FieldUtils;
47 import org.junit.Before;
48 import org.junit.Test;
49 import org.junit.runner.RunWith;
50 import org.junit.BeforeClass;
51 import org.junit.AfterClass;
52 import org.mockito.Mock;
53
54 import org.onap.dmaap.datarouter.provisioning.beans.Deleteable;
55 import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
56 import org.onap.dmaap.datarouter.provisioning.beans.LogRecord;
57 import org.onap.dmaap.datarouter.provisioning.beans.Updateable;
58 import org.powermock.api.mockito.PowerMockito;
59 import org.powermock.core.classloader.annotations.PrepareForTest;
60 import org.powermock.modules.junit4.PowerMockRunner;
61
62 @RunWith(PowerMockRunner.class)
63 @PrepareForTest(LogRecord.class)
64 public class InternalServletTest extends DrServletTestBase {
65   private static EntityManagerFactory emf;
66   private static EntityManager em;
67   private InternalServlet internalServlet;
68
69   @Mock
70   private HttpServletRequest request;
71
72   @Mock
73   private HttpServletResponse response;
74
75   ListAppender<ILoggingEvent> listAppender;
76
77   @BeforeClass
78   public static void init() {
79     emf = Persistence.createEntityManagerFactory("dr-unit-tests");
80     em = emf.createEntityManager();
81     System.setProperty(
82             "org.onap.dmaap.datarouter.provserver.properties",
83             "src/test/resources/h2Database.properties");
84   }
85
86   @AfterClass
87   public static void tearDownClass() {
88     em.clear();
89     em.close();
90     emf.close();
91   }
92
93   @Before
94   public void setUp() throws Exception {
95       listAppender = setTestLogger(InternalServlet.class);
96       internalServlet = new InternalServlet();
97       setUpValidAuthorisedRequest();
98   }
99
100   @Test
101   public void Given_Request_Is_HTTP_GET_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
102       throws Exception {
103     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
104     internalServlet.doGet(request, response);
105     verify(response)
106         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
107     verifyEnteringExitCalled(listAppender);
108   }
109
110   @Test
111   public void Given_Request_Is_HTTP_GET_With_Halt_In_Endpoint_But_Not_Sent_From_Localhost_Then_Forbidden_Response_Is_Generated()
112       throws Exception {
113     when(request.getPathInfo()).thenReturn("/halt");
114     when(request.isSecure()).thenReturn(false);
115     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
116     internalServlet.doGet(request, response);
117     verify(response).setStatus(eq(HttpServletResponse.SC_FORBIDDEN));
118   }
119
120   @Test
121   public void Given_Request_Is_HTTP_GET_With_Halt_In_Endpoint_Then_Request_Succeeds() throws Exception {
122     when(request.getPathInfo()).thenReturn("/halt");
123     when(request.isSecure()).thenReturn(false);
124     when(request.getRemoteAddr()).thenReturn("127.0.0.1");
125     internalServlet.doGet(request, response);
126     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
127   }
128
129   @Test
130   public void Given_Request_Is_HTTP_GET_With_FetchProv_In_Endpoint_Then_Request_Succeeds()
131       throws Exception {
132     when(request.getPathInfo()).thenReturn("/fetchProv");
133     when(request.isSecure()).thenReturn(false);
134     internalServlet.doGet(request, response);
135     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
136       verifyEnteringExitCalled(listAppender);
137   }
138
139   @Test
140   public void Given_Request_Is_HTTP_GET_With_Prov_In_Endpoint_Then_Request_Succeeds() throws Exception {
141     when(request.getPathInfo()).thenReturn("/prov");
142     when(request.getQueryString()).thenReturn(null);
143     setPokerToNotCreateTimers();
144     ServletOutputStream outStream = mock(ServletOutputStream.class);
145     when(response.getOutputStream()).thenReturn(outStream);
146     internalServlet.doGet(request, response);
147     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
148   }
149
150   @Test
151   public void Given_Request_Is_HTTP_GET_With_Logs_In_Endpoint_Then_Request_Succeeds() throws Exception {
152     when(request.getPathInfo()).thenReturn("/logs/");
153     ServletOutputStream outStream = mock(ServletOutputStream.class);
154     when(response.getOutputStream()).thenReturn(outStream);
155     internalServlet.doGet(request, response);
156     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
157   }
158
159   @Test
160   public void Given_Request_Is_HTTP_GET_Starts_With_Logs_In_Endpoint_Then_Request_Succeeds()
161       throws Exception {
162     when(request.getPathInfo()).thenReturn("/logs/TestFile");
163     internalServlet.doGet(request, response);
164     verify(response)
165         .sendError(eq(HttpServletResponse.SC_NO_CONTENT), argThat(notNullValue(String.class)));
166   }
167
168   @Test
169   public void Given_Request_Is_HTTP_GET_Starts_With_Logs_In_Endpoint_And_File_Exists_Then_Request_Returns_Ok()
170       throws Exception {
171     when(request.getPathInfo()).thenReturn("/logs/testFile.txt");
172     File testDir = new File("unit-test-logs");
173     File testFile = new File("unit-test-logs/testFile.txt");
174     testDir.mkdirs();
175     testFile.createNewFile();
176     testFile.deleteOnExit();
177     ServletOutputStream outStream = mock(ServletOutputStream.class);
178     when(response.getOutputStream()).thenReturn(outStream);
179     internalServlet.doGet(request, response);
180     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
181   }
182
183   @Test
184   public void Given_Request_Is_HTTP_GET_With_Api_In_Endpoint_Then_Request_Succeeds() throws Exception {
185     when(request.getPathInfo()).thenReturn("/api/DELIVERY_MAX_RETRY_INTERVAL");
186     ServletOutputStream outStream = mock(ServletOutputStream.class);
187     when(response.getOutputStream()).thenReturn(outStream);
188     internalServlet.doGet(request, response);
189     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
190   }
191
192   @Test
193   public void Given_Request_Is_HTTP_GET_With_Drlogs_In_Endpoint_Then_Request_Succeeds()
194       throws Exception {
195     when(request.getPathInfo()).thenReturn("/drlogs/");
196     ServletOutputStream outStream = mock(ServletOutputStream.class);
197     when(response.getOutputStream()).thenReturn(outStream);
198     internalServlet.doGet(request, response);
199     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
200   }
201
202   @Test
203   public void Given_Request_Is_HTTP_GET_With_Incorrect_Endpoint_Then_No_Content_Response_Is_Generated()
204       throws Exception {
205     when(request.getPathInfo()).thenReturn("/incorrect/");
206     internalServlet.doGet(request, response);
207     verify(response)
208         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
209   }
210
211   @Test
212   public void Given_Request_Is_HTTP_PUT_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
213       throws Exception {
214     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
215     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
216     internalServlet.doPut(request, response);
217     verify(response)
218         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
219     verifyEnteringExitCalled(listAppender);
220   }
221
222   @Test
223   public void Given_Request_Is_HTTP_PUT_With_Api_In_Endpoint_Request_Succeeds() throws Exception {
224     when(request.getPathInfo()).thenReturn("/api/NODES");
225     String[] values = {"V", "a", "l", "u", "e", "s"};
226     when(request.getParameterValues(anyString())).thenReturn(values);
227     internalServlet = internalServerSuccess();
228     setPokerToNotCreateTimers();
229     internalServlet.doPut(request, response);
230     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
231     verifyEnteringExitCalled(listAppender);
232   }
233
234   @Test
235   public void Given_Request_Is_HTTP_PUT_With_Api_In_Endpoint_And_Update_Fails_Then_Internal_Server_Error_Is_Generated()
236       throws Exception {
237     when(request.getPathInfo()).thenReturn("/api/NODES");
238     String[] values = {"V", "a", "l", "u", "e", "s"};
239     when(request.getParameterValues(anyString())).thenReturn(values);
240     internalServlet = internalServerFailure();
241     internalServlet.doPut(request, response);
242     verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
243         argThat(notNullValue(String.class)));
244   }
245
246   @Test
247   public void Given_Request_Is_HTTP_PUT_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
248       throws Exception {
249     when(request.getPathInfo()).thenReturn("/incorrect");
250     internalServlet.doPut(request, response);
251     verify(response)
252         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
253   }
254
255   @Test
256   public void Given_Request_Is_HTTP_DELETE_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
257       throws Exception {
258     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
259     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
260     internalServlet.doDelete(request, response);
261     verify(response)
262         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
263     verifyEnteringExitCalled(listAppender);
264   }
265
266   @Test
267   public void Given_Request_Is_HTTP_DELETE_With_Api_In_Endpoint_Request_Succeeds()
268       throws Exception {
269     when(request.getPathInfo()).thenReturn("/api/NODES");
270     String[] values = {"V", "a", "l", "u", "e", "s"};
271     when(request.getParameterValues(anyString())).thenReturn(values);
272     internalServlet = internalServerSuccess();
273     setPokerToNotCreateTimers();
274     internalServlet.doDelete(request, response);
275     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
276     verifyEnteringExitCalled(listAppender);
277   }
278
279   @Test
280   public void Given_Request_Is_HTTP_DELETE_With_Api_In_Endpoint_And_Delete_Fails_Then_Internal_Server_Error_Is_Generated()
281       throws Exception {
282     when(request.getPathInfo()).thenReturn("/api/NODES");
283     String[] values = {"V", "a", "l", "u", "e", "s"};
284     when(request.getParameterValues(anyString())).thenReturn(values);
285     internalServlet = internalServerFailure();
286     internalServlet.doDelete(request, response);
287     verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
288         argThat(notNullValue(String.class)));
289   }
290
291   @Test
292   public void Given_Request_Is_HTTP_DELETE_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
293       throws Exception {
294     when(request.getPathInfo()).thenReturn("/incorrect");
295     internalServlet.doDelete(request, response);
296     verify(response)
297         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
298   }
299
300   @Test
301   public void Given_Request_Is_HTTP_POST_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
302       throws Exception {
303     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
304     internalServlet.doPost(request, response);
305     verify(response)
306         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
307     verifyEnteringExitCalled(listAppender);
308   }
309
310   @Test
311   public void Given_Request_Is_HTTP_POST_With_Api_In_Endpoint_Request_Succeeds() throws Exception {
312     when(request.getPathInfo()).thenReturn("/api/key");
313     String[] values = {"V", "a", "l", "u", "e", "s"};
314     when(request.getParameterValues(anyString())).thenReturn(values);
315     internalServlet = internalServerSuccess();
316     setPokerToNotCreateTimers();
317     internalServlet.doPost(request, response);
318     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
319     verifyEnteringExitCalled(listAppender);
320   }
321
322   @Test
323   public void Given_Request_Is_HTTP_POST_With_Api_In_Endpoint_And_Insert_Fails_Then_Internal_Server_Error_Is_Generated()
324       throws Exception {
325     when(request.getPathInfo()).thenReturn("/api/Key");
326     String[] values = {"V", "a", "l", "u", "e", "s"};
327     when(request.getParameterValues(anyString())).thenReturn(values);
328     internalServlet = internalServerFailure();
329     internalServlet.doPost(request, response);
330     verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
331         argThat(notNullValue(String.class)));
332   }
333
334   @Test
335   public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
336       throws Exception {
337     when(request.getHeader("Content-Type")).thenReturn("stub_contentType");
338     when(request.getPathInfo()).thenReturn("/logs/");
339     internalServlet.doPost(request, response);
340     verify(response).setStatus(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE));
341   }
342
343   @Test
344   public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Encoding_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
345       throws Exception {
346     when(request.getHeader("Content-Encoding")).thenReturn("not-supported");
347     when(request.getPathInfo()).thenReturn("/logs/");
348     internalServlet.doPost(request, response);
349     verify(response).setStatus(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE));
350   }
351
352   @Test
353   public void Given_Request_Is_HTTP_POST_To_Logs_Then_Request_Succeeds()
354       throws Exception {
355     when(request.getHeader("Content-Encoding")).thenReturn("gzip");
356     when(request.getPathInfo()).thenReturn("/logs/");
357     ServletInputStream inStream = mock(ServletInputStream.class);
358     when(request.getInputStream()).thenReturn(inStream);
359     File testDir = new File("unit-test-logs/spool");
360     testDir.mkdirs();
361     testDir.deleteOnExit();
362     internalServlet.doPost(request, response);
363     verify(response).setStatus(eq(HttpServletResponse.SC_CREATED));
364   }
365
366   @Test
367   public void Given_Request_Is_HTTP_POST_To_Drlogs_And_Then_Unsupported_Media_Type_Response_Is_Generated()
368       throws Exception {
369     when(request.getHeader("Content-Type")).thenReturn("stub_contentType");
370     when(request.getPathInfo()).thenReturn("/drlogs/");
371     internalServlet.doPost(request, response);
372     verify(response).setStatus(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE));
373   }
374
375   @Test
376   public void Given_Request_Is_HTTP_POST_To_Drlogs_And_Request_Succeeds() throws Exception {
377     when(request.getPathInfo()).thenReturn("/drlogs/");
378     ServletInputStream inStream = mock(ServletInputStream.class);
379     when(inStream.read()).thenReturn(1, -1);
380     when(request.getInputStream()).thenReturn(inStream);
381     PowerMockito.mockStatic(LogRecord.class);
382     internalServlet.doPost(request, response);
383     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
384   }
385
386   @Test
387   public void Given_Request_Is_HTTP_POST_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
388       throws Exception {
389     when(request.getPathInfo()).thenReturn("/incorrect/");
390     internalServlet.doPost(request, response);
391     verify(response)
392         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
393   }
394
395   private void setUpValidAuthorisedRequest() throws Exception {
396     setUpValidSecurityOnHttpRequest();
397     setBehalfHeader("Stub_Value");
398     setValidPathInfoInHttpHeader();
399     when(request.getHeader("Content-Type")).thenReturn("text/plain");
400     when(request.getHeader("Content-Encoding")).thenReturn("gzip");
401   }
402
403   private void setUpValidSecurityOnHttpRequest() throws Exception {
404     when(request.isSecure()).thenReturn(true);
405     when(request.getRemoteAddr()).thenReturn(InetAddress.getLocalHost().getHostAddress());
406     InetAddress[] nodeAddresses = new InetAddress[1];
407     nodeAddresses[0] = InetAddress.getLocalHost();
408     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "nodeAddresses", nodeAddresses, true);
409     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", false, true);
410   }
411
412   private void setBehalfHeader(String headerValue) {
413     when(request.getHeader(BEHALF_HEADER)).thenReturn(headerValue);
414   }
415
416   private void setValidPathInfoInHttpHeader() {
417     when(request.getPathInfo()).thenReturn("/123");
418   }
419
420   private void setPokerToNotCreateTimers() throws Exception {
421     Poker poker = mock(Poker.class);
422     FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
423   }
424
425   private InternalServlet internalServerSuccess() {
426     InternalServlet internalServlet = new InternalServlet() {
427
428       protected boolean doUpdate(Updateable bean) {
429         return true;
430       }
431
432       protected boolean doDelete(Deleteable bean) {
433         return true;
434       }
435
436       protected boolean doInsert(Insertable bean) {
437         return true;
438       }
439     };
440     return internalServlet;
441   }
442
443   private InternalServlet internalServerFailure() {
444     InternalServlet internalServlet = new InternalServlet() {
445
446       protected boolean doUpdate(Updateable bean) {
447         return false;
448       }
449
450       protected boolean doDelete(Deleteable bean) {
451         return false;
452       }
453
454       protected boolean doInsert(Insertable bean) {
455         return false;
456       }
457     };
458     return internalServlet;
459   }
460 }