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