DR AAF CADI integration
[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 org.apache.commons.lang3.reflect.FieldUtils;
28 import org.jetbrains.annotations.NotNull;
29 import org.json.JSONObject;
30 import org.junit.AfterClass;
31 import org.junit.Before;
32 import org.junit.BeforeClass;
33 import org.junit.Test;
34 import org.junit.runner.RunWith;
35 import org.mockito.Mock;
36 import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
37 import org.onap.dmaap.datarouter.authz.Authorizer;
38 import org.onap.dmaap.datarouter.provisioning.beans.Deleteable;
39 import org.onap.dmaap.datarouter.provisioning.beans.SubDelivery;
40 import org.onap.dmaap.datarouter.provisioning.beans.Subscription;
41 import org.onap.dmaap.datarouter.provisioning.beans.Updateable;
42 import org.onap.dmaap.datarouter.provisioning.utils.DB;
43 import org.onap.dmaap.datarouter.provisioning.utils.PasswordProcessor;
44 import org.powermock.api.mockito.PowerMockito;
45 import org.powermock.core.classloader.annotations.PrepareForTest;
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.hamcrest.Matchers.notNullValue;
60 import static org.mockito.Mockito.*;
61 import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
62
63
64 @RunWith(PowerMockRunner.class)
65 @PrepareForTest(PasswordProcessor.class)
66 public class SubscriptionServletTest extends DrServletTestBase {
67     private static EntityManagerFactory emf;
68     private static EntityManager em;
69     private SubscriptionServlet subscriptionServlet;
70     private DB db;
71     private final String URL= "https://172.100.0.5";
72     private final String USER = "user1";
73     private final String PASSWORD="password1";
74
75
76     @Mock
77     private HttpServletRequest request;
78     @Mock
79     private HttpServletResponse response;
80
81     private ListAppender<ILoggingEvent> listAppender;
82
83     @BeforeClass
84     public static void init() {
85         emf = Persistence.createEntityManagerFactory("dr-unit-tests");
86         em = emf.createEntityManager();
87         System.setProperty(
88             "org.onap.dmaap.datarouter.provserver.properties",
89             "src/test/resources/h2Database.properties");
90     }
91
92     @AfterClass
93     public static void tearDownClass() {
94         em.clear();
95         em.close();
96         emf.close();
97     }
98
99     @Before
100     public void setUp() throws Exception {
101         listAppender = setTestLogger(SubscriptionServlet.class);
102         subscriptionServlet = new SubscriptionServlet();
103         db = new DB();
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             protected 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             protected 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             protected 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         verifyEnteringExitCalled(listAppender);
327     }
328
329     @Test
330     public void Given_Request_Is_HTTP_PUT_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated() throws Exception {
331         when(request.getContentType()).thenReturn("stub_ContentType");
332         subscriptionServlet.doPut(request, response);
333         verify(response).sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), argThat(notNullValue(String.class)));
334     }
335
336     @Test
337     public void Given_Request_Is_HTTP_PUT_And_Request_Contains_Badly_Formed_JSON_Then_Bad_Request_Response_Is_Generated() throws Exception {
338         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
339         ServletInputStream inStream = mock(ServletInputStream.class);
340         when(request.getInputStream()).thenReturn(inStream);
341         subscriptionServlet.doPut(request, response);
342         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
343     }
344
345     @Test
346     public void Given_Request_Is_HTTP_PUT_And_Subscription_Object_Is_Invalid_Bad_Request_Response_Is_Generated() throws Exception {
347         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
348         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
349             protected JSONObject getJSONfromInput(HttpServletRequest req) {
350                 JSONObject jo = new JSONObject();
351                 return jo;
352             }
353         };
354         subscriptionServlet.doPut(request, response);
355         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
356     }
357
358     @Test
359     public void Given_Request_Is_HTTP_PUT_And_Subscriber_Modified_By_Different_Creator_Then_Bad_Request_Is_Generated() throws Exception {
360         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn(null);
361         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
362         JSONObject JSObject = buildRequestJsonObject();
363         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
364             protected JSONObject getJSONfromInput(HttpServletRequest req) {
365                 JSONObject jo = new JSONObject();
366                 jo.put("name", "stub_name");
367                 jo.put("version", "2.0");
368                 jo.put("metadataOnly", true);
369                 jo.put("suspend", true);
370                 jo.put("privilegedSubscriber", true);
371                 jo.put("decompress", true);
372                 jo.put("delivery", JSObject);
373                 jo.put("aaf_instance", "legacy");
374                 jo.put("follow_redirect", false);
375                 jo.put("subscriber", "differentSubscriber");
376                 jo.put("sync", true);
377                 return jo;
378             }
379         };
380         subscriptionServlet.doPut(request, response);
381         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
382     }
383
384     @Test
385     public void Given_Request_Is_HTTP_PUT_And_Update_Fails() throws Exception {
386         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
387         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
388         JSONObject JSObject = buildRequestJsonObject();
389         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
390             protected JSONObject getJSONfromInput(HttpServletRequest req) {
391                 JSONObject jo = new JSONObject();
392                 jo.put("name", "stub_name");
393                 jo.put("version", "2.0");
394                 jo.put("metadataOnly", true);
395                 jo.put("suspend", true);
396                 jo.put("privilegedSubscriber", true);
397                 jo.put("delivery", JSObject);
398                 jo.put("aaf_instance", "legacy");
399                 jo.put("decompress", true);
400                 jo.put("follow_redirect", false);
401                 jo.put("sync", true);
402                 return jo;
403             }
404
405             @Override
406             protected boolean doUpdate(Updateable bean) {
407                 return false;
408             }
409         };
410         subscriptionServlet.doPut(request, response);
411         verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), argThat(notNullValue(String.class)));
412     }
413
414     @Test
415     public void Given_Request_Is_HTTP_PUT_And_Update_Succeeds() throws Exception {
416         ServletOutputStream outStream = mock(ServletOutputStream.class);
417         when(response.getOutputStream()).thenReturn(outStream);
418         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
419         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
420         PowerMockito.mockStatic(PasswordProcessor.class);
421         JSONObject JSObject = buildRequestJsonObject();
422         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
423             protected JSONObject getJSONfromInput(HttpServletRequest req) {
424                 JSONObject jo = new JSONObject();
425                 jo.put("name", "stub_name");
426                 jo.put("version", "2.0");
427                 jo.put("metadataOnly", true);
428                 jo.put("suspend", true);
429                 jo.put("privilegedSubscriber", true);
430                 jo.put("decompress", true);
431                 jo.put("delivery", JSObject);
432                 jo.put("aaf_instance", "legacy");
433                 jo.put("follow_redirect", false);
434                 jo.put("sync", true);
435                 jo.put("changeowner", true);
436                 return jo;
437             }
438         };
439         subscriptionServlet.doPut(request, response);
440         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
441         changeSubscriptionBackToNormal();
442         verifyEnteringExitCalled(listAppender);
443     }
444
445     @Test
446     public void Given_Request_Is_HTTP_POST_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception {
447         when(request.isSecure()).thenReturn(false);
448         subscriptionServlet.doPost(request, response);
449         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
450         verifyEnteringExitCalled(listAppender);
451     }
452
453     @Test
454     public void Given_Request_Is_HTTP_POST_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
455         setBehalfHeader(null);
456         subscriptionServlet.doPost(request, response);
457         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
458     }
459
460     @Test
461     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 {
462         when(request.getPathInfo()).thenReturn(null);
463         subscriptionServlet.doPost(request, response);
464         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
465     }
466
467     @Test
468     public void Given_Request_Is_HTTP_POST_And_Subscription_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception {
469         when(request.getPathInfo()).thenReturn("/123");
470         subscriptionServlet.doPost(request, response);
471         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
472     }
473
474     @Test
475     public void Given_Request_Is_HTTP_POST_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated() throws Exception {
476         when(request.getContentType()).thenReturn("stub_ContentType");
477         subscriptionServlet.doPost(request, response);
478         verify(response).sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), argThat(notNullValue(String.class)));
479     }
480
481     @Test
482     public void Given_Request_Is_HTTP_POST_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated() throws Exception {
483         when(request.getHeader(anyString())).thenReturn("application/vnd.dmaap-dr.subscription-control");
484         setAuthoriserToReturnRequestNotAuthorized();
485         subscriptionServlet.doPost(request, response);
486         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
487     }
488
489     @Test
490     public void Given_Request_Is_HTTP_POST_And_Request_Contains_Badly_Formed_JSON_Then_Bad_Request_Response_Is_Generated() throws Exception {
491         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription-control; version=1.0");
492         ServletInputStream inStream = mock(ServletInputStream.class);
493         when(request.getInputStream()).thenReturn(inStream);
494         subscriptionServlet.doPost(request, response);
495         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
496     }
497
498     @Test
499     public void Given_Request_Is_HTTP_POST_And_Post_Fails() throws Exception {
500         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
501         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription-control; version=1.0");
502         JSONObject JSObject = buildRequestJsonObject();
503         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
504             protected JSONObject getJSONfromInput(HttpServletRequest req) {
505                 JSONObject jo = new JSONObject();
506                 jo.put("name", "stub_name");
507                 jo.put("version", "2.0");
508                 jo.put("metadataOnly", true);
509                 jo.put("suspend", true);
510                 jo.put("delivery", JSObject);
511                 return jo;
512             }
513         };
514         subscriptionServlet.doPost(request, response);
515         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
516     }
517
518     @Test
519     public void Given_Request_Is_HTTP_POST_And_Post_Succeeds() throws Exception {
520         ServletOutputStream outStream = mock(ServletOutputStream.class);
521         when(response.getOutputStream()).thenReturn(outStream);
522         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
523         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription-control; version=1.0");
524         JSONObject JSObject = buildRequestJsonObject();
525         SubscriptionServlet subscriptionServlet = new SubscriptionServlet() {
526             protected JSONObject getJSONfromInput(HttpServletRequest req) {
527                 JSONObject jo = new JSONObject();
528                 jo.put("name", "stub_name");
529                 jo.put("version", "2.0");
530                 jo.put("metadataOnly", true);
531                 jo.put("suspend", true);
532                 jo.put("delivery", JSObject);
533                 jo.put("privilegedSubscriber", false);
534                 jo.put("aaf_instance", "legacy");
535                 jo.put("follow_redirect", false);
536                 jo.put("decompress", false);
537                 jo.put("failed", false);
538                 return jo;
539             }
540         };
541         subscriptionServlet.doPost(request, response);
542         verify(response).setStatus(eq(HttpServletResponse.SC_ACCEPTED));
543         verifyEnteringExitCalled(listAppender);
544     }
545
546     @NotNull
547     private JSONObject buildRequestJsonObject() {
548         JSONObject JSObject = new JSONObject();
549         JSObject.put("url", "https://stub_address");
550         JSObject.put("use100", "true");
551         JSObject.put("password", "stub_password");
552         JSObject.put("user", "stub_user");
553         return JSObject;
554     }
555
556     private void setUpValidSecurityOnHttpRequest() throws Exception {
557         when(request.isSecure()).thenReturn(true);
558         Set<String> authAddressesAndNetworks = new HashSet<String>();
559         authAddressesAndNetworks.add(("127.0.0.1"));
560         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authorizedAddressesAndNetworks", authAddressesAndNetworks, true);
561         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", false, true);
562     }
563
564     private void setBehalfHeader(String headerValue) {
565         when(request.getHeader(BEHALF_HEADER)).thenReturn(headerValue);
566     }
567
568     private void setValidPathInfoInHttpHeader() {
569         when(request.getPathInfo()).thenReturn("/1");
570     }
571
572     private void setAuthoriserToReturnRequestNotAuthorized() 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(false);
578     }
579
580     private void setAuthoriserToReturnRequestIsAuthorized() throws IllegalAccessException {
581         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
582         Authorizer authorizer = mock(Authorizer.class);
583         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
584         when(authorizer.decide(request)).thenReturn(authResponse);
585         when(authResponse.isAuthorized()).thenReturn(true);
586     }
587
588     private void setPokerToNotCreateTimersWhenDeleteSubscriptionIsCalled() throws Exception {
589         Poker poker = mock(Poker.class);
590         FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
591     }
592
593     private void setupValidAuthorisedRequest() throws Exception {
594         setUpValidSecurityOnHttpRequest();
595         setBehalfHeader("Stub_Value");
596         setValidPathInfoInHttpHeader();
597     }
598
599     private void changeSubscriptionBackToNormal() throws SQLException {
600         Subscription subscription = new Subscription("https://172.100.0.5", "user1", "password1");
601         subscription.setSubid(1);
602         subscription.setSubscriber("user1");
603         subscription.setFeedid(1);
604         SubDelivery subDelivery = new SubDelivery(URL, USER, PASSWORD, true);
605         subscription.setDelivery(subDelivery);
606         subscription.setGroupid(1);
607         subscription.setMetadataOnly(false);
608         subscription.setSuspended(false);
609         subscription.setPrivilegedSubscriber(false);
610         subscription.setDecompress(false);
611         subscription.changeOwnerShip();
612         subscription.doUpdate(db.getConnection());
613     }
614
615     private void resetAafSubscriptionInDB() throws SQLException {
616         Subscription subscription = new Subscription("https://172.100.0.5:8080", "user2", "password2");
617         subscription.setSubid(2);
618         subscription.setSubscriber("user2");
619         subscription.setFeedid(1);
620         SubDelivery subDelivery = new SubDelivery(URL, USER, PASSWORD, true);
621         subscription.setDelivery(subDelivery);
622         subscription.setGroupid(1);
623         subscription.setMetadataOnly(false);
624         subscription.setSuspended(false);
625         subscription.setAafInstance("https://aaf-onap-test.osaaf.org:8095");
626         subscription.setDecompress(false);
627         subscription.setPrivilegedSubscriber(false);
628         subscription.doUpdate(db.getConnection());
629     }
630 }