[DMaaP DR] JKD 11 migration
[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.Poker;
44 import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
45 import org.powermock.core.classloader.annotations.PowerMockIgnore;
46 import org.powermock.modules.junit4.PowerMockRunner;
47
48 import javax.persistence.EntityManager;
49 import javax.persistence.EntityManagerFactory;
50 import javax.persistence.Persistence;
51 import javax.servlet.ServletInputStream;
52 import javax.servlet.ServletOutputStream;
53 import javax.servlet.http.HttpServletRequest;
54 import javax.servlet.http.HttpServletResponse;
55 import java.sql.SQLException;
56 import java.util.HashSet;
57 import java.util.Set;
58
59 import static org.mockito.ArgumentMatchers.anyString;
60 import static org.mockito.ArgumentMatchers.contains;
61 import static org.mockito.ArgumentMatchers.eq;
62 import static org.mockito.Mockito.mock;
63 import static org.mockito.Mockito.verify;
64 import static org.mockito.Mockito.when;
65 import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
66
67
68 @RunWith(PowerMockRunner.class)
69 @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
70 public class SubscriptionServletTest extends DrServletTestBase {
71     private static EntityManagerFactory emf;
72     private static EntityManager em;
73     private SubscriptionServlet subscriptionServlet;
74     private final String URL= "https://172.100.0.5";
75     private final String USER = "user1";
76     private final String PASSWORD="password1";
77
78
79     @Mock
80     private HttpServletRequest request;
81     @Mock
82     private HttpServletResponse response;
83
84     private ListAppender<ILoggingEvent> listAppender;
85
86     @BeforeClass
87     public static void init() {
88         emf = Persistence.createEntityManagerFactory("dr-unit-tests");
89         em = emf.createEntityManager();
90         System.setProperty(
91             "org.onap.dmaap.datarouter.provserver.properties",
92             "src/test/resources/h2Database.properties");
93     }
94
95     @AfterClass
96     public static void tearDownClass() {
97         em.clear();
98         em.close();
99         emf.close();
100     }
101
102     @Before
103     public void setUp() throws Exception {
104         listAppender = setTestLogger(SubscriptionServlet.class);
105         subscriptionServlet = new SubscriptionServlet();
106         setAuthoriserToReturnRequestIsAuthorized();
107         setPokerToNotCreateTimersWhenDeleteSubscriptionIsCalled();
108         setupValidAuthorisedRequest();
109         setUpValidSecurityOnHttpRequest();
110     }
111
112     @Test
113     public void Given_Request_Is_HTTP_DELETE_SC_Forbidden_Response_Is_Generated() throws Exception {
114         when(request.isSecure()).thenReturn(false);
115         subscriptionServlet.doDelete(request, response);
116         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
117         verifyEnteringExitCalled(listAppender);
118     }
119
120     @Test
121     public void Given_Request_Is_HTTP_DELETE_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
122         setBehalfHeader(null);
123         subscriptionServlet.doDelete(request, response);
124         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
125     }
126
127     @Test
128     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 {
129         when(request.getPathInfo()).thenReturn(null);
130         subscriptionServlet.doDelete(request, response);
131         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
132     }
133
134     @Test
135     public void Given_Request_Is_HTTP_DELETE_And_Subscription_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception {
136         when(request.getPathInfo()).thenReturn("/123");
137         subscriptionServlet.doDelete(request, response);
138         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
139     }
140
141     @Test
142     public void Given_Request_Is_HTTP_DELETE_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated() throws Exception {
143         setAuthoriserToReturnRequestNotAuthorized();
144         subscriptionServlet.doDelete(request, response);
145         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
146     }
147
148     @Test
149     public void Given_Request_Is_HTTP_DELETE_And_Delete_On_Database_Fails_An_Internal_Server_Error_Is_Reported() throws Exception {
150         SubscriptionServlet subscriptionServlet = new SubscriptionServlet(){
151             public boolean doDelete(Deleteable deletable){
152                 return false;
153             }
154         };
155         subscriptionServlet.doDelete(request, response);
156         verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), anyString());
157     }
158
159     @Test
160     public void Given_Request_Is_HTTP_DELETE_And_AAF_CADI_Is_Enabled_Without_Permissions_Then_Forbidden_Response_Is_Generated() throws Exception {
161         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
162         when(request.getPathInfo()).thenReturn("/2");
163         subscriptionServlet.doDelete(request, response);
164         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), contains("AAF disallows access"));
165     }
166
167     @Test
168     public void Given_Request_Is_HTTP_DELETE_And_AAF_CADI_Is_Enabled_With_Permissions_Then_A_NO_CONTENT_Response_Is_Generated() throws Exception {
169         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
170         when(request.getPathInfo()).thenReturn("/2");
171         when(request.isUserInRole("org.onap.dmaap-dr.sub|*|delete")).thenReturn(true);
172         subscriptionServlet.doDelete(request, response);
173         verify(response).setStatus(eq(HttpServletResponse.SC_NO_CONTENT));
174         verifyEnteringExitCalled(listAppender);
175         resetAafSubscriptionInDB();
176     }
177
178     @Test
179     public void Given_Request_Is_HTTP_GET_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception {
180         when(request.isSecure()).thenReturn(false);
181         subscriptionServlet.doGet(request, response);
182         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
183         verifyEnteringExitCalled(listAppender);
184     }
185
186     @Test
187     public void Given_Request_Is_HTTP_GET_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
188         setBehalfHeader(null);
189         subscriptionServlet.doGet(request, response);
190         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
191     }
192
193     @Test
194     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 {
195         when(request.getPathInfo()).thenReturn(null);
196         subscriptionServlet.doGet(request, response);
197         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
198     }
199
200     @Test
201     public void Given_Request_Is_HTTP_GET_And_Subscription_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception {
202         when(request.getPathInfo()).thenReturn("/123");
203         subscriptionServlet.doGet(request, response);
204         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
205     }
206
207     @Test
208     public void Given_Request_Is_HTTP_GET_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated() throws Exception {
209         setAuthoriserToReturnRequestNotAuthorized();
210         subscriptionServlet.doGet(request, response);
211         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
212     }
213
214     @Test
215     public void Given_Request_Is_HTTP_GET_And_Request_Succeeds() throws Exception {
216         ServletOutputStream outStream = mock(ServletOutputStream.class);
217         when(response.getOutputStream()).thenReturn(outStream);
218         subscriptionServlet.doGet(request, response);
219         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
220         verifyEnteringExitCalled(listAppender);
221     }
222
223     @Test
224     public void Given_Request_Is_HTTP_PUT_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception {
225         when(request.isSecure()).thenReturn(false);
226         subscriptionServlet.doPut(request, response);
227         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
228         verifyEnteringExitCalled(listAppender);
229     }
230
231     @Test
232     public void Given_Request_Is_HTTP_PUT_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
233         setBehalfHeader(null);
234         subscriptionServlet.doPut(request, response);
235         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
236     }
237
238     @Test
239     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 {
240         when(request.getPathInfo()).thenReturn(null);
241         subscriptionServlet.doPut(request, response);
242         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
243     }
244
245     @Test
246     public void Given_Request_Is_HTTP_PUT_And_Subscription_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception {
247         when(request.getPathInfo()).thenReturn("/123");
248         subscriptionServlet.doPut(request, response);
249         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
250     }
251
252     @Test
253     public void Given_Request_Is_HTTP_PUT_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated() throws Exception {
254         setAuthoriserToReturnRequestNotAuthorized();
255         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
256         JSONObject JSObject = buildRequestJsonObject();
257         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
258             public JSONObject getJSONfromInput(HttpServletRequest req) {
259                 JSONObject jo = new JSONObject();
260                 jo.put("name", "stub_name");
261                 jo.put("version", "2.0");
262                 jo.put("metadataOnly", true);
263                 jo.put("suspend", true);
264                 jo.put("delivery", JSObject);
265                 jo.put("aaf_instance", "legacy");
266                 jo.put("follow_redirect", false);
267                 jo.put("decompress", true);
268                 jo.put("sync", true);
269                 jo.put("changeowner", true);
270                 return jo;
271             }
272         };
273         subscriptionServlet.doPut(request, response);
274         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
275     }
276
277     @Test
278     public void Given_Request_Is_HTTP_PUT_And_AAF_CADI_Is_Enabled_Without_Permissions_Then_Forbidden_Response_Is_Generated() throws Exception {
279         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
280         when(request.getPathInfo()).thenReturn("/3");
281         JSONObject JSObject = buildRequestJsonObject();
282         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
283             public JSONObject getJSONfromInput(HttpServletRequest req) {
284                 JSONObject jo = new JSONObject();
285                 jo.put("name", "stub_name");
286                 jo.put("version", "2.0");
287                 jo.put("metadataOnly", true);
288                 jo.put("suspend", true);
289                 jo.put("delivery", JSObject);
290                 jo.put("aaf_instance", "*");
291                 jo.put("follow_redirect", false);
292                 jo.put("sync", true);
293                 jo.put("changeowner", true);
294                 return jo;
295             }
296         };
297         subscriptionServlet.doPut(request, response);
298         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), contains("AAF disallows access"));
299     }
300
301     @Test
302     public void Given_Request_Is_HTTP_PUT_And_AAF_CADI_Is_Enabled_With_Permissions_Then_OK_Response_Is_Generated() throws Exception {
303         ServletOutputStream outStream = mock(ServletOutputStream.class);
304         when(response.getOutputStream()).thenReturn(outStream);
305         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
306         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
307         when(request.getPathInfo()).thenReturn("/3");
308         when(request.isUserInRole("org.onap.dmaap-dr.sub|*|edit")).thenReturn(true);
309         JSONObject JSObject = buildRequestJsonObject();
310         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
311             public JSONObject getJSONfromInput(HttpServletRequest req) {
312                 JSONObject jo = new JSONObject();
313                 jo.put("name", "stub_name");
314                 jo.put("version", "2.0");
315                 jo.put("metadataOnly", true);
316                 jo.put("suspend", true);
317                 jo.put("delivery", JSObject);
318                 jo.put("aaf_instance", "*");
319                 jo.put("follow_redirect", false);
320                 jo.put("sync", true);
321                 return jo;
322             }
323         };
324         subscriptionServlet.doPut(request, response);
325         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
326         resetAafSubscriptionInDB();
327         addNewSubscriptionInDB();
328         verifyEnteringExitCalled(listAppender);
329     }
330
331     @Test
332     public void Given_Request_Is_HTTP_PUT_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated() throws Exception {
333         when(request.getContentType()).thenReturn("stub_ContentType");
334         subscriptionServlet.doPut(request, response);
335         verify(response).sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), anyString());
336     }
337
338     @Test
339     public void Given_Request_Is_HTTP_PUT_And_Request_Contains_Badly_Formed_JSON_Then_Bad_Request_Response_Is_Generated() throws Exception {
340         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
341         ServletInputStream inStream = mock(ServletInputStream.class);
342         when(request.getInputStream()).thenReturn(inStream);
343         subscriptionServlet.doPut(request, response);
344         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
345     }
346
347     @Test
348     public void Given_Request_Is_HTTP_PUT_And_Subscription_Object_Is_Invalid_Bad_Request_Response_Is_Generated() throws Exception {
349         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
350         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
351             public JSONObject getJSONfromInput(HttpServletRequest req) {
352                 JSONObject jo = new JSONObject();
353                 return jo;
354             }
355         };
356         subscriptionServlet.doPut(request, response);
357         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
358     }
359
360     @Test
361     public void Given_Request_Is_HTTP_PUT_And_Subscriber_Modified_By_Different_Creator_Then_Bad_Request_Is_Generated() throws Exception {
362         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn(null);
363         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
364         JSONObject JSObject = buildRequestJsonObject();
365         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
366             public JSONObject getJSONfromInput(HttpServletRequest req) {
367                 JSONObject jo = new JSONObject();
368                 jo.put("name", "stub_name");
369                 jo.put("version", "2.0");
370                 jo.put("metadataOnly", true);
371                 jo.put("suspend", true);
372                 jo.put("privilegedSubscriber", true);
373                 jo.put("decompress", true);
374                 jo.put("delivery", JSObject);
375                 jo.put("aaf_instance", "legacy");
376                 jo.put("follow_redirect", false);
377                 jo.put("subscriber", "differentSubscriber");
378                 jo.put("sync", true);
379                 return jo;
380             }
381         };
382         subscriptionServlet.doPut(request, response);
383         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
384     }
385
386     @Test
387     public void Given_Request_Is_HTTP_PUT_And_Update_Fails() throws Exception {
388         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
389         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
390         JSONObject JSObject = buildRequestJsonObject();
391         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
392             public JSONObject getJSONfromInput(HttpServletRequest req) {
393                 JSONObject jo = new JSONObject();
394                 jo.put("name", "stub_name");
395                 jo.put("version", "2.0");
396                 jo.put("metadataOnly", true);
397                 jo.put("suspend", true);
398                 jo.put("privilegedSubscriber", true);
399                 jo.put("delivery", JSObject);
400                 jo.put("aaf_instance", "legacy");
401                 jo.put("decompress", true);
402                 jo.put("follow_redirect", false);
403                 jo.put("sync", true);
404                 return jo;
405             }
406
407             @Override
408             protected boolean doUpdate(Updateable bean) {
409                 return false;
410             }
411         };
412         subscriptionServlet.doPut(request, response);
413         verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), anyString());
414     }
415
416     @Test
417     public void Given_Request_Is_HTTP_PUT_And_Update_Succeeds() throws Exception {
418         ServletOutputStream outStream = mock(ServletOutputStream.class);
419         when(response.getOutputStream()).thenReturn(outStream);
420         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
421         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
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), anyString());
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), anyString());
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), anyString());
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), anyString());
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), anyString());
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), anyString());
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), anyString());
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), anyString());
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 }