Add RequestId and InvocationId to DR
[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 testFile = new File("unit-test-logs/testFile.txt");
173     testFile.createNewFile();
174     testFile.deleteOnExit();
175     ServletOutputStream outStream = mock(ServletOutputStream.class);
176     when(response.getOutputStream()).thenReturn(outStream);
177     internalServlet.doGet(request, response);
178     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
179   }
180
181   @Test
182   public void Given_Request_Is_HTTP_GET_With_Api_In_Endpoint_Then_Request_Succeeds() throws Exception {
183     when(request.getPathInfo()).thenReturn("/api/DELIVERY_MAX_RETRY_INTERVAL");
184     ServletOutputStream outStream = mock(ServletOutputStream.class);
185     when(response.getOutputStream()).thenReturn(outStream);
186     internalServlet.doGet(request, response);
187     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
188   }
189
190   @Test
191   public void Given_Request_Is_HTTP_GET_With_Drlogs_In_Endpoint_Then_Request_Succeeds()
192       throws Exception {
193     when(request.getPathInfo()).thenReturn("/drlogs/");
194     ServletOutputStream outStream = mock(ServletOutputStream.class);
195     when(response.getOutputStream()).thenReturn(outStream);
196     internalServlet.doGet(request, response);
197     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
198   }
199
200   @Test
201   public void Given_Request_Is_HTTP_GET_With_Incorrect_Endpoint_Then_No_Content_Response_Is_Generated()
202       throws Exception {
203     when(request.getPathInfo()).thenReturn("/incorrect/");
204     internalServlet.doGet(request, response);
205     verify(response)
206         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
207   }
208
209   @Test
210   public void Given_Request_Is_HTTP_PUT_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
211       throws Exception {
212     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
213     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
214     internalServlet.doPut(request, response);
215     verify(response)
216         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
217     verifyEnteringExitCalled(listAppender);
218   }
219
220   @Test
221   public void Given_Request_Is_HTTP_PUT_With_Api_In_Endpoint_Request_Succeeds() throws Exception {
222     when(request.getPathInfo()).thenReturn("/api/NODES");
223     String[] values = {"V", "a", "l", "u", "e", "s"};
224     when(request.getParameterValues(anyString())).thenReturn(values);
225     internalServlet = internalServerSuccess();
226     setPokerToNotCreateTimers();
227     internalServlet.doPut(request, response);
228     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
229     verifyEnteringExitCalled(listAppender);
230   }
231
232   @Test
233   public void Given_Request_Is_HTTP_PUT_With_Api_In_Endpoint_And_Update_Fails_Then_Internal_Server_Error_Is_Generated()
234       throws Exception {
235     when(request.getPathInfo()).thenReturn("/api/NODES");
236     String[] values = {"V", "a", "l", "u", "e", "s"};
237     when(request.getParameterValues(anyString())).thenReturn(values);
238     internalServlet = internalServerFailure();
239     internalServlet.doPut(request, response);
240     verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
241         argThat(notNullValue(String.class)));
242   }
243
244   @Test
245   public void Given_Request_Is_HTTP_PUT_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
246       throws Exception {
247     when(request.getPathInfo()).thenReturn("/incorrect");
248     internalServlet.doPut(request, response);
249     verify(response)
250         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
251   }
252
253   @Test
254   public void Given_Request_Is_HTTP_DELETE_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
255       throws Exception {
256     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
257     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
258     internalServlet.doDelete(request, response);
259     verify(response)
260         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
261     verifyEnteringExitCalled(listAppender);
262   }
263
264   @Test
265   public void Given_Request_Is_HTTP_DELETE_With_Api_In_Endpoint_Request_Succeeds()
266       throws Exception {
267     when(request.getPathInfo()).thenReturn("/api/NODES");
268     String[] values = {"V", "a", "l", "u", "e", "s"};
269     when(request.getParameterValues(anyString())).thenReturn(values);
270     internalServlet = internalServerSuccess();
271     setPokerToNotCreateTimers();
272     internalServlet.doDelete(request, response);
273     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
274     verifyEnteringExitCalled(listAppender);
275   }
276
277   @Test
278   public void Given_Request_Is_HTTP_DELETE_With_Api_In_Endpoint_And_Delete_Fails_Then_Internal_Server_Error_Is_Generated()
279       throws Exception {
280     when(request.getPathInfo()).thenReturn("/api/NODES");
281     String[] values = {"V", "a", "l", "u", "e", "s"};
282     when(request.getParameterValues(anyString())).thenReturn(values);
283     internalServlet = internalServerFailure();
284     internalServlet.doDelete(request, response);
285     verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
286         argThat(notNullValue(String.class)));
287   }
288
289   @Test
290   public void Given_Request_Is_HTTP_DELETE_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
291       throws Exception {
292     when(request.getPathInfo()).thenReturn("/incorrect");
293     internalServlet.doDelete(request, response);
294     verify(response)
295         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
296   }
297
298   @Test
299   public void Given_Request_Is_HTTP_POST_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
300       throws Exception {
301     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
302     internalServlet.doPost(request, response);
303     verify(response)
304         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
305     verifyEnteringExitCalled(listAppender);
306   }
307
308   @Test
309   public void Given_Request_Is_HTTP_POST_With_Api_In_Endpoint_Request_Succeeds() throws Exception {
310     when(request.getPathInfo()).thenReturn("/api/key");
311     String[] values = {"V", "a", "l", "u", "e", "s"};
312     when(request.getParameterValues(anyString())).thenReturn(values);
313     internalServlet = internalServerSuccess();
314     setPokerToNotCreateTimers();
315     internalServlet.doPost(request, response);
316     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
317     verifyEnteringExitCalled(listAppender);
318   }
319
320   @Test
321   public void Given_Request_Is_HTTP_POST_With_Api_In_Endpoint_And_Insert_Fails_Then_Internal_Server_Error_Is_Generated()
322       throws Exception {
323     when(request.getPathInfo()).thenReturn("/api/Key");
324     String[] values = {"V", "a", "l", "u", "e", "s"};
325     when(request.getParameterValues(anyString())).thenReturn(values);
326     internalServlet = internalServerFailure();
327     internalServlet.doPost(request, response);
328     verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
329         argThat(notNullValue(String.class)));
330   }
331
332   @Test
333   public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
334       throws Exception {
335     when(request.getHeader("Content-Type")).thenReturn("stub_contentType");
336     when(request.getPathInfo()).thenReturn("/logs/");
337     internalServlet.doPost(request, response);
338     verify(response).setStatus(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE));
339   }
340
341   @Test
342   public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Encoding_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
343       throws Exception {
344     when(request.getHeader("Content-Encoding")).thenReturn("not-supported");
345     when(request.getPathInfo()).thenReturn("/logs/");
346     internalServlet.doPost(request, response);
347     verify(response).setStatus(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE));
348   }
349
350   @Test
351   public void Given_Request_Is_HTTP_POST_To_Logs_Then_Request_Succeeds()
352       throws Exception {
353     when(request.getHeader("Content-Encoding")).thenReturn("gzip");
354     when(request.getPathInfo()).thenReturn("/logs/");
355     ServletInputStream inStream = mock(ServletInputStream.class);
356     when(request.getInputStream()).thenReturn(inStream);
357     File testDir = new File("unit-test-logs/spool");
358     testDir.mkdirs();
359     testDir.deleteOnExit();
360     internalServlet.doPost(request, response);
361     verify(response).setStatus(eq(HttpServletResponse.SC_CREATED));
362   }
363
364   @Test
365   public void Given_Request_Is_HTTP_POST_To_Drlogs_And_Then_Unsupported_Media_Type_Response_Is_Generated()
366       throws Exception {
367     when(request.getHeader("Content-Type")).thenReturn("stub_contentType");
368     when(request.getPathInfo()).thenReturn("/drlogs/");
369     internalServlet.doPost(request, response);
370     verify(response).setStatus(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE));
371   }
372
373   @Test
374   public void Given_Request_Is_HTTP_POST_To_Drlogs_And_Request_Succeeds() throws Exception {
375     when(request.getPathInfo()).thenReturn("/drlogs/");
376     ServletInputStream inStream = mock(ServletInputStream.class);
377     when(inStream.read()).thenReturn(1, -1);
378     when(request.getInputStream()).thenReturn(inStream);
379     PowerMockito.mockStatic(LogRecord.class);
380     internalServlet.doPost(request, response);
381     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
382   }
383
384   @Test
385   public void Given_Request_Is_HTTP_POST_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
386       throws Exception {
387     when(request.getPathInfo()).thenReturn("/incorrect/");
388     internalServlet.doPost(request, response);
389     verify(response)
390         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
391   }
392
393   private void setUpValidAuthorisedRequest() throws Exception {
394     setUpValidSecurityOnHttpRequest();
395     setBehalfHeader("Stub_Value");
396     setValidPathInfoInHttpHeader();
397     when(request.getHeader("Content-Type")).thenReturn("text/plain");
398     when(request.getHeader("Content-Encoding")).thenReturn("gzip");
399   }
400
401   private void setUpValidSecurityOnHttpRequest() throws Exception {
402     when(request.isSecure()).thenReturn(true);
403     when(request.getRemoteAddr()).thenReturn(InetAddress.getLocalHost().getHostAddress());
404     InetAddress[] nodeAddresses = new InetAddress[1];
405     nodeAddresses[0] = InetAddress.getLocalHost();
406     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "nodeAddresses", nodeAddresses, true);
407     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", false, true);
408   }
409
410   private void setBehalfHeader(String headerValue) {
411     when(request.getHeader(BEHALF_HEADER)).thenReturn(headerValue);
412   }
413
414   private void setValidPathInfoInHttpHeader() {
415     when(request.getPathInfo()).thenReturn("/123");
416   }
417
418   private void setPokerToNotCreateTimers() throws Exception {
419     Poker poker = mock(Poker.class);
420     FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
421   }
422
423   private InternalServlet internalServerSuccess() {
424     InternalServlet internalServlet = new InternalServlet() {
425
426       protected boolean doUpdate(Updateable bean) {
427         return true;
428       }
429
430       protected boolean doDelete(Deleteable bean) {
431         return true;
432       }
433
434       protected boolean doInsert(Insertable bean) {
435         return true;
436       }
437     };
438     return internalServlet;
439   }
440
441   private InternalServlet internalServerFailure() {
442     InternalServlet internalServlet = new InternalServlet() {
443
444       protected boolean doUpdate(Updateable bean) {
445         return false;
446       }
447
448       protected boolean doDelete(Deleteable bean) {
449         return false;
450       }
451
452       protected boolean doInsert(Insertable bean) {
453         return false;
454       }
455     };
456     return internalServlet;
457   }
458 }