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