Refactor Prov DB handling
[dmaap/datarouter.git] / datarouter-prov / src / test / java / org / onap / dmaap / datarouter / provisioning / SubscriptionServletTest.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 ch.qos.logback.classic.spi.ILoggingEvent;
26 import ch.qos.logback.core.read.ListAppender;
27 import java.sql.Connection;
28 import org.apache.commons.lang3.reflect.FieldUtils;
29 import org.jetbrains.annotations.NotNull;
30 import org.json.JSONObject;
31 import org.junit.AfterClass;
32 import org.junit.Before;
33 import org.junit.BeforeClass;
34 import org.junit.Test;
35 import org.junit.runner.RunWith;
36 import org.mockito.Mock;
37 import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
38 import org.onap.dmaap.datarouter.authz.Authorizer;
39 import org.onap.dmaap.datarouter.provisioning.beans.Deleteable;
40 import org.onap.dmaap.datarouter.provisioning.beans.SubDelivery;
41 import org.onap.dmaap.datarouter.provisioning.beans.Subscription;
42 import org.onap.dmaap.datarouter.provisioning.beans.Updateable;
43 import org.onap.dmaap.datarouter.provisioning.utils.PasswordProcessor;
44 import org.onap.dmaap.datarouter.provisioning.utils.Poker;
45 import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
46 import org.powermock.api.mockito.PowerMockito;
47 import org.powermock.core.classloader.annotations.PrepareForTest;
48 import org.powermock.modules.junit4.PowerMockRunner;
49
50 import javax.persistence.EntityManager;
51 import javax.persistence.EntityManagerFactory;
52 import javax.persistence.Persistence;
53 import javax.servlet.ServletInputStream;
54 import javax.servlet.ServletOutputStream;
55 import javax.servlet.http.HttpServletRequest;
56 import javax.servlet.http.HttpServletResponse;
57 import java.sql.SQLException;
58 import java.util.HashSet;
59 import java.util.Set;
60
61 import static org.hamcrest.Matchers.notNullValue;
62 import static org.mockito.Mockito.*;
63 import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
64
65
66 @RunWith(PowerMockRunner.class)
67 @PrepareForTest(PasswordProcessor.class)
68 public class SubscriptionServletTest extends DrServletTestBase {
69     private static EntityManagerFactory emf;
70     private static EntityManager em;
71     private SubscriptionServlet subscriptionServlet;
72     private final String URL= "https://172.100.0.5";
73     private final String USER = "user1";
74     private final String PASSWORD="password1";
75
76
77     @Mock
78     private HttpServletRequest request;
79     @Mock
80     private HttpServletResponse response;
81
82     private ListAppender<ILoggingEvent> listAppender;
83
84     @BeforeClass
85     public static void init() {
86         emf = Persistence.createEntityManagerFactory("dr-unit-tests");
87         em = emf.createEntityManager();
88         System.setProperty(
89             "org.onap.dmaap.datarouter.provserver.properties",
90             "src/test/resources/h2Database.properties");
91     }
92
93     @AfterClass
94     public static void tearDownClass() {
95         em.clear();
96         em.close();
97         emf.close();
98     }
99
100     @Before
101     public void setUp() throws Exception {
102         listAppender = setTestLogger(SubscriptionServlet.class);
103         subscriptionServlet = new SubscriptionServlet();
104         setAuthoriserToReturnRequestIsAuthorized();
105         setPokerToNotCreateTimersWhenDeleteSubscriptionIsCalled();
106         setupValidAuthorisedRequest();
107         setUpValidSecurityOnHttpRequest();
108     }
109
110     @Test
111     public void Given_Request_Is_HTTP_DELETE_SC_Forbidden_Response_Is_Generated() throws Exception {
112         when(request.isSecure()).thenReturn(false);
113         subscriptionServlet.doDelete(request, response);
114         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
115         verifyEnteringExitCalled(listAppender);
116     }
117
118     @Test
119     public void Given_Request_Is_HTTP_DELETE_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
120         setBehalfHeader(null);
121         subscriptionServlet.doDelete(request, response);
122         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
123     }
124
125     @Test
126     public void Given_Request_Is_HTTP_DELETE_And_Path_Header_Is_Not_Set_In_Request_With_Valid_Path_Then_Bad_Request_Response_Is_Generated() throws Exception {
127         when(request.getPathInfo()).thenReturn(null);
128         subscriptionServlet.doDelete(request, response);
129         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
130     }
131
132     @Test
133     public void Given_Request_Is_HTTP_DELETE_And_Subscription_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception {
134         when(request.getPathInfo()).thenReturn("/123");
135         subscriptionServlet.doDelete(request, response);
136         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
137     }
138
139     @Test
140     public void Given_Request_Is_HTTP_DELETE_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated() throws Exception {
141         setAuthoriserToReturnRequestNotAuthorized();
142         subscriptionServlet.doDelete(request, response);
143         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
144     }
145
146     @Test
147     public void Given_Request_Is_HTTP_DELETE_And_Delete_On_Database_Fails_An_Internal_Server_Error_Is_Reported() throws Exception {
148         SubscriptionServlet subscriptionServlet = new SubscriptionServlet(){
149             public boolean doDelete(Deleteable deletable){
150                 return false;
151             }
152         };
153         subscriptionServlet.doDelete(request, response);
154         verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), argThat(notNullValue(String.class)));
155     }
156
157     @Test
158     public void Given_Request_Is_HTTP_DELETE_And_AAF_CADI_Is_Enabled_Without_Permissions_Then_Forbidden_Response_Is_Generated() throws Exception {
159         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
160         when(request.getPathInfo()).thenReturn("/2");
161         subscriptionServlet.doDelete(request, response);
162         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), contains("AAF disallows access"));
163     }
164
165     @Test
166     public void Given_Request_Is_HTTP_DELETE_And_AAF_CADI_Is_Enabled_With_Permissions_Then_A_NO_CONTENT_Response_Is_Generated() throws Exception {
167         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
168         when(request.getPathInfo()).thenReturn("/2");
169         when(request.isUserInRole("org.onap.dmaap-dr.sub|*|delete")).thenReturn(true);
170         subscriptionServlet.doDelete(request, response);
171         verify(response).setStatus(eq(HttpServletResponse.SC_NO_CONTENT));
172         verifyEnteringExitCalled(listAppender);
173         resetAafSubscriptionInDB();
174     }
175
176     @Test
177     public void Given_Request_Is_HTTP_GET_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception {
178         when(request.isSecure()).thenReturn(false);
179         subscriptionServlet.doGet(request, response);
180         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
181         verifyEnteringExitCalled(listAppender);
182     }
183
184     @Test
185     public void Given_Request_Is_HTTP_GET_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
186         setBehalfHeader(null);
187         subscriptionServlet.doGet(request, response);
188         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
189     }
190
191     @Test
192     public void Given_Request_Is_HTTP_GET_And_Path_Header_Is_Not_Set_In_Request_With_Valid_Path_Then_Bad_Request_Response_Is_Generated() throws Exception {
193         when(request.getPathInfo()).thenReturn(null);
194         subscriptionServlet.doGet(request, response);
195         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
196     }
197
198     @Test
199     public void Given_Request_Is_HTTP_GET_And_Subscription_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception {
200         when(request.getPathInfo()).thenReturn("/123");
201         subscriptionServlet.doGet(request, response);
202         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
203     }
204
205     @Test
206     public void Given_Request_Is_HTTP_GET_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated() throws Exception {
207         setAuthoriserToReturnRequestNotAuthorized();
208         subscriptionServlet.doGet(request, response);
209         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
210     }
211
212     @Test
213     public void Given_Request_Is_HTTP_GET_And_Request_Succeeds() throws Exception {
214         ServletOutputStream outStream = mock(ServletOutputStream.class);
215         when(response.getOutputStream()).thenReturn(outStream);
216         subscriptionServlet.doGet(request, response);
217         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
218         verifyEnteringExitCalled(listAppender);
219     }
220
221     @Test
222     public void Given_Request_Is_HTTP_PUT_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception {
223         when(request.isSecure()).thenReturn(false);
224         subscriptionServlet.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_PUT_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
231         setBehalfHeader(null);
232         subscriptionServlet.doPut(request, response);
233         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
234     }
235
236     @Test
237     public void Given_Request_Is_HTTP_PUT_And_Path_Header_Is_Not_Set_In_Request_With_Valid_Path_Then_Bad_Request_Response_Is_Generated() throws Exception {
238         when(request.getPathInfo()).thenReturn(null);
239         subscriptionServlet.doPut(request, response);
240         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
241     }
242
243     @Test
244     public void Given_Request_Is_HTTP_PUT_And_Subscription_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception {
245         when(request.getPathInfo()).thenReturn("/123");
246         subscriptionServlet.doPut(request, response);
247         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
248     }
249
250     @Test
251     public void Given_Request_Is_HTTP_PUT_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated() throws Exception {
252         setAuthoriserToReturnRequestNotAuthorized();
253         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
254         JSONObject JSObject = buildRequestJsonObject();
255         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
256             public JSONObject getJSONfromInput(HttpServletRequest req) {
257                 JSONObject jo = new JSONObject();
258                 jo.put("name", "stub_name");
259                 jo.put("version", "2.0");
260                 jo.put("metadataOnly", true);
261                 jo.put("suspend", true);
262                 jo.put("delivery", JSObject);
263                 jo.put("aaf_instance", "legacy");
264                 jo.put("follow_redirect", false);
265                 jo.put("decompress", true);
266                 jo.put("sync", true);
267                 jo.put("changeowner", true);
268                 return jo;
269             }
270         };
271         subscriptionServlet.doPut(request, response);
272         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
273     }
274
275     @Test
276     public void Given_Request_Is_HTTP_PUT_And_AAF_CADI_Is_Enabled_Without_Permissions_Then_Forbidden_Response_Is_Generated() throws Exception {
277         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
278         when(request.getPathInfo()).thenReturn("/3");
279         JSONObject JSObject = buildRequestJsonObject();
280         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
281             public JSONObject getJSONfromInput(HttpServletRequest req) {
282                 JSONObject jo = new JSONObject();
283                 jo.put("name", "stub_name");
284                 jo.put("version", "2.0");
285                 jo.put("metadataOnly", true);
286                 jo.put("suspend", true);
287                 jo.put("delivery", JSObject);
288                 jo.put("aaf_instance", "*");
289                 jo.put("follow_redirect", false);
290                 jo.put("sync", true);
291                 jo.put("changeowner", true);
292                 return jo;
293             }
294         };
295         subscriptionServlet.doPut(request, response);
296         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), contains("AAF disallows access"));
297     }
298
299     @Test
300     public void Given_Request_Is_HTTP_PUT_And_AAF_CADI_Is_Enabled_With_Permissions_Then_OK_Response_Is_Generated() throws Exception {
301         ServletOutputStream outStream = mock(ServletOutputStream.class);
302         when(response.getOutputStream()).thenReturn(outStream);
303         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
304         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
305         when(request.getPathInfo()).thenReturn("/3");
306         when(request.isUserInRole("org.onap.dmaap-dr.sub|*|edit")).thenReturn(true);
307         PowerMockito.mockStatic(PasswordProcessor.class);
308         JSONObject JSObject = buildRequestJsonObject();
309         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
310             public JSONObject getJSONfromInput(HttpServletRequest req) {
311                 JSONObject jo = new JSONObject();
312                 jo.put("name", "stub_name");
313                 jo.put("version", "2.0");
314                 jo.put("metadataOnly", true);
315                 jo.put("suspend", true);
316                 jo.put("delivery", JSObject);
317                 jo.put("aaf_instance", "*");
318                 jo.put("follow_redirect", false);
319                 jo.put("sync", true);
320                 return jo;
321             }
322         };
323         subscriptionServlet.doPut(request, response);
324         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
325         resetAafSubscriptionInDB();
326         addNewSubscriptionInDB();
327         verifyEnteringExitCalled(listAppender);
328     }
329
330     @Test
331     public void Given_Request_Is_HTTP_PUT_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated() throws Exception {
332         when(request.getContentType()).thenReturn("stub_ContentType");
333         subscriptionServlet.doPut(request, response);
334         verify(response).sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), argThat(notNullValue(String.class)));
335     }
336
337     @Test
338     public void Given_Request_Is_HTTP_PUT_And_Request_Contains_Badly_Formed_JSON_Then_Bad_Request_Response_Is_Generated() throws Exception {
339         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
340         ServletInputStream inStream = mock(ServletInputStream.class);
341         when(request.getInputStream()).thenReturn(inStream);
342         subscriptionServlet.doPut(request, response);
343         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
344     }
345
346     @Test
347     public void Given_Request_Is_HTTP_PUT_And_Subscription_Object_Is_Invalid_Bad_Request_Response_Is_Generated() throws Exception {
348         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
349         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
350             public JSONObject getJSONfromInput(HttpServletRequest req) {
351                 JSONObject jo = new JSONObject();
352                 return jo;
353             }
354         };
355         subscriptionServlet.doPut(request, response);
356         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
357     }
358
359     @Test
360     public void Given_Request_Is_HTTP_PUT_And_Subscriber_Modified_By_Different_Creator_Then_Bad_Request_Is_Generated() throws Exception {
361         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn(null);
362         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
363         JSONObject JSObject = buildRequestJsonObject();
364         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
365             public JSONObject getJSONfromInput(HttpServletRequest req) {
366                 JSONObject jo = new JSONObject();
367                 jo.put("name", "stub_name");
368                 jo.put("version", "2.0");
369                 jo.put("metadataOnly", true);
370                 jo.put("suspend", true);
371                 jo.put("privilegedSubscriber", true);
372                 jo.put("decompress", true);
373                 jo.put("delivery", JSObject);
374                 jo.put("aaf_instance", "legacy");
375                 jo.put("follow_redirect", false);
376                 jo.put("subscriber", "differentSubscriber");
377                 jo.put("sync", true);
378                 return jo;
379             }
380         };
381         subscriptionServlet.doPut(request, response);
382         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
383     }
384
385     @Test
386     public void Given_Request_Is_HTTP_PUT_And_Update_Fails() throws Exception {
387         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
388         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
389         JSONObject JSObject = buildRequestJsonObject();
390         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
391             public JSONObject getJSONfromInput(HttpServletRequest req) {
392                 JSONObject jo = new JSONObject();
393                 jo.put("name", "stub_name");
394                 jo.put("version", "2.0");
395                 jo.put("metadataOnly", true);
396                 jo.put("suspend", true);
397                 jo.put("privilegedSubscriber", true);
398                 jo.put("delivery", JSObject);
399                 jo.put("aaf_instance", "legacy");
400                 jo.put("decompress", true);
401                 jo.put("follow_redirect", false);
402                 jo.put("sync", true);
403                 return jo;
404             }
405
406             @Override
407             protected boolean doUpdate(Updateable bean) {
408                 return false;
409             }
410         };
411         subscriptionServlet.doPut(request, response);
412         verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), argThat(notNullValue(String.class)));
413     }
414
415     @Test
416     public void Given_Request_Is_HTTP_PUT_And_Update_Succeeds() throws Exception {
417         ServletOutputStream outStream = mock(ServletOutputStream.class);
418         when(response.getOutputStream()).thenReturn(outStream);
419         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
420         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
421         PowerMockito.mockStatic(PasswordProcessor.class);
422         JSONObject JSObject = buildRequestJsonObject();
423         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
424             public JSONObject getJSONfromInput(HttpServletRequest req) {
425                 JSONObject jo = new JSONObject();
426                 jo.put("name", "stub_name");
427                 jo.put("version", "2.0");
428                 jo.put("metadataOnly", true);
429                 jo.put("suspend", true);
430                 jo.put("privilegedSubscriber", true);
431                 jo.put("decompress", true);
432                 jo.put("delivery", JSObject);
433                 jo.put("aaf_instance", "legacy");
434                 jo.put("follow_redirect", false);
435                 jo.put("sync", true);
436                 jo.put("changeowner", true);
437                 return jo;
438             }
439         };
440         subscriptionServlet.doPut(request, response);
441         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
442         changeSubscriptionBackToNormal();
443         verifyEnteringExitCalled(listAppender);
444     }
445
446     @Test
447     public void Given_Request_Is_HTTP_POST_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception {
448         when(request.isSecure()).thenReturn(false);
449         subscriptionServlet.doPost(request, response);
450         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
451         verifyEnteringExitCalled(listAppender);
452     }
453
454     @Test
455     public void Given_Request_Is_HTTP_POST_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
456         setBehalfHeader(null);
457         subscriptionServlet.doPost(request, response);
458         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
459     }
460
461     @Test
462     public void Given_Request_Is_HTTP_POST_And_Path_Header_Is_Not_Set_In_Request_With_Valid_Path_Then_Bad_Request_Response_Is_Generated() throws Exception {
463         when(request.getPathInfo()).thenReturn(null);
464         subscriptionServlet.doPost(request, response);
465         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
466     }
467
468     @Test
469     public void Given_Request_Is_HTTP_POST_And_Subscription_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception {
470         when(request.getPathInfo()).thenReturn("/123");
471         subscriptionServlet.doPost(request, response);
472         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
473     }
474
475     @Test
476     public void Given_Request_Is_HTTP_POST_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated() throws Exception {
477         when(request.getContentType()).thenReturn("stub_ContentType");
478         subscriptionServlet.doPost(request, response);
479         verify(response).sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), argThat(notNullValue(String.class)));
480     }
481
482     @Test
483     public void Given_Request_Is_HTTP_POST_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated() throws Exception {
484         when(request.getHeader(anyString())).thenReturn("application/vnd.dmaap-dr.subscription-control");
485         setAuthoriserToReturnRequestNotAuthorized();
486         subscriptionServlet.doPost(request, response);
487         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
488     }
489
490     @Test
491     public void Given_Request_Is_HTTP_POST_And_Request_Contains_Badly_Formed_JSON_Then_Bad_Request_Response_Is_Generated() throws Exception {
492         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription-control; version=1.0");
493         ServletInputStream inStream = mock(ServletInputStream.class);
494         when(request.getInputStream()).thenReturn(inStream);
495         subscriptionServlet.doPost(request, response);
496         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
497     }
498
499     @Test
500     public void Given_Request_Is_HTTP_POST_And_Post_Fails() throws Exception {
501         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
502         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription-control; version=1.0");
503         JSONObject JSObject = buildRequestJsonObject();
504         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
505             public JSONObject getJSONfromInput(HttpServletRequest req) {
506                 JSONObject jo = new JSONObject();
507                 jo.put("name", "stub_name");
508                 jo.put("version", "2.0");
509                 jo.put("metadataOnly", true);
510                 jo.put("suspend", true);
511                 jo.put("delivery", JSObject);
512                 return jo;
513             }
514         };
515         subscriptionServlet.doPost(request, response);
516         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
517     }
518
519     @Test
520     public void Given_Request_Is_HTTP_POST_And_Post_Succeeds() throws Exception {
521         ServletOutputStream outStream = mock(ServletOutputStream.class);
522         when(response.getOutputStream()).thenReturn(outStream);
523         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
524         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription-control; version=1.0");
525         JSONObject JSObject = buildRequestJsonObject();
526         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
527             public JSONObject getJSONfromInput(HttpServletRequest req) {
528                 JSONObject jo = new JSONObject();
529                 jo.put("name", "stub_name");
530                 jo.put("version", "2.0");
531                 jo.put("metadataOnly", true);
532                 jo.put("suspend", true);
533                 jo.put("delivery", JSObject);
534                 jo.put("privilegedSubscriber", false);
535                 jo.put("aaf_instance", "legacy");
536                 jo.put("follow_redirect", false);
537                 jo.put("decompress", false);
538                 jo.put("failed", false);
539                 return jo;
540             }
541         };
542         subscriptionServlet.doPost(request, response);
543         verify(response).setStatus(eq(HttpServletResponse.SC_ACCEPTED));
544         verifyEnteringExitCalled(listAppender);
545     }
546
547     @NotNull
548     private JSONObject buildRequestJsonObject() {
549         JSONObject JSObject = new JSONObject();
550         JSObject.put("url", "https://stub_address");
551         JSObject.put("use100", "true");
552         JSObject.put("password", "stub_password");
553         JSObject.put("user", "stub_user");
554         return JSObject;
555     }
556
557     private void setUpValidSecurityOnHttpRequest() throws Exception {
558         when(request.isSecure()).thenReturn(true);
559         Set<String> authAddressesAndNetworks = new HashSet<String>();
560         authAddressesAndNetworks.add(("127.0.0.1"));
561         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authorizedAddressesAndNetworks", authAddressesAndNetworks, true);
562         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", false, true);
563     }
564
565     private void setBehalfHeader(String headerValue) {
566         when(request.getHeader(BEHALF_HEADER)).thenReturn(headerValue);
567     }
568
569     private void setValidPathInfoInHttpHeader() {
570         when(request.getPathInfo()).thenReturn("/1");
571     }
572
573     private void setAuthoriserToReturnRequestNotAuthorized() throws IllegalAccessException {
574         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
575         Authorizer authorizer = mock(Authorizer.class);
576         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
577         when(authorizer.decide(request)).thenReturn(authResponse);
578         when(authResponse.isAuthorized()).thenReturn(false);
579     }
580
581     private void setAuthoriserToReturnRequestIsAuthorized() throws IllegalAccessException {
582         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
583         Authorizer authorizer = mock(Authorizer.class);
584         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
585         when(authorizer.decide(request)).thenReturn(authResponse);
586         when(authResponse.isAuthorized()).thenReturn(true);
587     }
588
589     private void setPokerToNotCreateTimersWhenDeleteSubscriptionIsCalled() throws Exception {
590         Poker poker = mock(Poker.class);
591         FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
592     }
593
594     private void setupValidAuthorisedRequest() throws Exception {
595         setUpValidSecurityOnHttpRequest();
596         setBehalfHeader("Stub_Value");
597         setValidPathInfoInHttpHeader();
598     }
599
600     private void changeSubscriptionBackToNormal() throws SQLException {
601         Subscription subscription = new Subscription("https://172.100.0.5", "user1", "password1");
602         subscription.setSubid(1);
603         subscription.setSubscriber("user1");
604         subscription.setFeedid(1);
605         SubDelivery subDelivery = new SubDelivery(URL, USER, PASSWORD, true);
606         subscription.setDelivery(subDelivery);
607         subscription.setGroupid(1);
608         subscription.setMetadataOnly(false);
609         subscription.setSuspended(false);
610         subscription.setPrivilegedSubscriber(false);
611         subscription.setDecompress(false);
612         subscription.changeOwnerShip();
613         try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
614             subscription.doUpdate(conn);
615         }
616     }
617
618     private void resetAafSubscriptionInDB() throws SQLException {
619         Subscription subscription = new Subscription("https://172.100.0.5:8080", "user2", "password2");
620         subscription.setSubid(2);
621         subscription.setSubscriber("user2");
622         subscription.setFeedid(1);
623         SubDelivery subDelivery = new SubDelivery(URL, USER, PASSWORD, true);
624         subscription.setDelivery(subDelivery);
625         subscription.setGroupid(1);
626         subscription.setMetadataOnly(false);
627         subscription.setSuspended(false);
628         subscription.setAafInstance("https://aaf-onap-test.osaaf.org:8095");
629         subscription.setDecompress(false);
630         subscription.setPrivilegedSubscriber(false);
631         try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
632             subscription.doUpdate(conn);
633         }
634     }
635
636     private void addNewSubscriptionInDB() throws SQLException {
637         Subscription subscription = new Subscription("https://172.100.0.6:8080", "user3", "password3");
638         subscription.setSubid(3);
639         subscription.setSubscriber("user3");
640         subscription.setFeedid(1);
641         SubDelivery subDelivery = new SubDelivery(URL, USER, PASSWORD, true);
642         subscription.setDelivery(subDelivery);
643         subscription.setGroupid(1);
644         subscription.setMetadataOnly(false);
645         subscription.setSuspended(false);
646         subscription.setDecompress(false);
647         try (Connection conn = ProvDbUtils.getInstance().getConnection()) {
648             subscription.doInsert(conn);
649         }
650     }
651 }