Merge "Fixed Sonar Issues"
[dmaap/datarouter.git] / datarouter-prov / src / test / java / org / onap / dmaap / datarouter / provisioning / SubscribeServletTest.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 org.apache.commons.lang3.reflect.FieldUtils;
26 import org.jetbrains.annotations.NotNull;
27 import org.json.JSONObject;
28 import org.junit.Before;
29 import org.junit.Test;
30 import org.junit.runner.RunWith;
31 import org.mockito.Mock;
32 import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
33 import org.onap.dmaap.datarouter.authz.Authorizer;
34 import org.onap.dmaap.datarouter.provisioning.beans.Feed;
35 import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
36 import org.onap.dmaap.datarouter.provisioning.beans.Subscription;
37 import org.powermock.api.mockito.PowerMockito;
38 import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
39 import org.powermock.modules.junit4.PowerMockRunner;
40
41 import javax.servlet.ServletOutputStream;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
44 import java.util.ArrayList;
45 import java.util.HashSet;
46 import java.util.List;
47 import java.util.Set;
48
49 import static org.hamcrest.Matchers.notNullValue;
50 import static org.mockito.Mockito.*;
51 import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
52
53
54 @RunWith(PowerMockRunner.class)
55 @SuppressStaticInitializationFor({"org.onap.dmaap.datarouter.provisioning.beans.Feed", "org.onap.dmaap.datarouter.provisioning.beans.Subscription"})
56 public class SubscribeServletTest extends DrServletTestBase {
57     private static SubscribeServlet subscribeServlet;
58
59     @Mock
60     private HttpServletRequest request;
61     @Mock
62     private HttpServletResponse response;
63
64     @Before
65     public void setUp() throws Exception {
66         super.setUp();
67         subscribeServlet = new SubscribeServlet();
68         setAuthoriserToReturnRequestIsAuthorized();
69         setPokerToNotCreateTimersWhenDeleteFeedIsCalled();
70         setupValidAuthorisedRequest();
71         setUpValidSecurityOnHttpRequest();
72         setUpValidContentHeadersAndJSONOnHttpRequest();
73     }
74
75     @Test
76     public void Given_Request_Is_HTTP_DELETE_SC_METHOD_NOT_ALLOWED_Response_Is_Generated() throws Exception {
77         subscribeServlet.doDelete(request, response);
78         verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), argThat(notNullValue(String.class)));
79     }
80
81     @Test
82     public void Given_Request_Is_HTTP_GET_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception {
83         when(request.isSecure()).thenReturn(false);
84         subscribeServlet.doGet(request, response);
85         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
86     }
87
88     @Test
89     public void Given_Request_Is_HTTP_GET_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
90         setBehalfHeader(null);
91         subscribeServlet.doGet(request, response);
92         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
93     }
94
95
96     @Test
97     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 {
98         when(request.getPathInfo()).thenReturn(null);
99         subscribeServlet.doGet(request, response);
100         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
101     }
102
103     @Test
104     public void Given_Request_Is_HTTP_GET_And_Feed_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception {
105         setFeedToReturnInvalidFeedIdSupplied();
106         subscribeServlet.doGet(request, response);
107         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
108     }
109
110
111     @Test
112     public void Given_Request_Is_HTTP_GET_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated() throws Exception {
113         setAuthoriserToReturnRequestNotAuthorized();
114         subscribeServlet.doGet(request, response);
115         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
116     }
117
118
119     @Test
120     public void Given_Request_Is_HTTP_GET_And_Request_Succeeds() throws Exception {
121         ServletOutputStream outStream = mock(ServletOutputStream.class);
122         when(response.getOutputStream()).thenReturn(outStream);
123         PowerMockito.mockStatic(Subscription.class);
124         List<String> list = new ArrayList<String>();
125         list.add("{}");
126         PowerMockito.when(Subscription.getSubscriptionUrlList(anyInt())).thenReturn(list);
127         subscribeServlet.doGet(request, response);
128         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
129     }
130
131
132     @Test
133     public void Given_Request_Is_HTTP_PUT_SC_METHOD_NOT_ALLOWED_Response_Is_Generated() throws Exception {
134         subscribeServlet.doPut(request, response);
135         verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), argThat(notNullValue(String.class)));
136     }
137     @Test
138     public void Given_Request_Is_HTTP_POST_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception {
139         when(request.isSecure()).thenReturn(false);
140         subscribeServlet.doPost(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_POST_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
146         setBehalfHeader(null);
147         subscribeServlet.doPost(request, response);
148         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
149     }
150
151
152     @Test
153     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 {
154         when(request.getPathInfo()).thenReturn(null);
155         subscribeServlet.doPost(request, response);
156         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
157     }
158
159
160     @Test
161     public void Given_Request_Is_HTTP_POST_And_Feed_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception {
162         setFeedToReturnInvalidFeedIdSupplied();
163         subscribeServlet.doPost(request, response);
164         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
165     }
166
167     @Test
168     public void Given_Request_Is_HTTP_POST_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated() throws Exception {
169         setAuthoriserToReturnRequestNotAuthorized();
170         subscribeServlet.doPost(request, response);
171         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
172     }
173
174     @Test
175     public void Given_Request_Is_HTTP_POST_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated() throws Exception {
176         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.feed; version=1.1");
177         when(request.getContentType()).thenReturn("stub_contentType");
178         subscribeServlet.doPost(request, response);
179         verify(response).sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), argThat(notNullValue(String.class)));
180     }
181
182     @Test
183     public void Given_Request_Is_HTTP_POST_And_Request_Contains_Badly_Formed_JSON_Then_Bad_Request_Response_Is_Generated() throws Exception {
184         subscribeServlet.doPost(request, response);
185         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
186     }
187
188     @Test
189     public void Given_Request_Is_HTTP_POST_And_Active_Feeds_Equals_Max_Feeds_Then_Bad_Request_Response_Is_Generated() throws Exception {
190         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "maxSubs", 0, true);
191         SubscribeServlet subscribeServlet = new SubscribeServlet() {
192             protected JSONObject getJSONfromInput(HttpServletRequest req) {
193                 return new JSONObject();
194             }
195         };
196         subscribeServlet.doPost(request, response);
197         verify(response).sendError(eq(HttpServletResponse.SC_CONFLICT), argThat(notNullValue(String.class)));
198     }
199
200     @Test
201     public void Given_Request_Is_HTTP_POST_And_POST_Fails_Bad_Request_Response_Is_Generated() throws Exception {
202         PowerMockito.mockStatic(Subscription.class);
203         PowerMockito.when(Subscription.getSubscriptionMatching(mock(Subscription.class))).thenReturn(null);
204         PowerMockito.when(Subscription.countActiveSubscriptions()).thenReturn(0);
205         JSONObject JSObject = buildRequestJsonObject();
206         SubscribeServlet subscribeServlet = new SubscribeServlet() {
207             protected JSONObject getJSONfromInput(HttpServletRequest req) {
208                 JSONObject jo = new JSONObject();
209                 jo.put("name", "stub_name");
210                 jo.put("version", "2.0");
211                 jo.put("metadataOnly", true);
212                 jo.put("suspend", true);
213                 jo.put("delivery", JSObject);
214                 jo.put("sync", false);
215                 return jo;
216             }
217
218             @Override
219             protected boolean doInsert(Insertable bean) {
220                 return false;
221             }
222         };
223         subscribeServlet.doPost(request, response);
224         verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), argThat(notNullValue(String.class)));
225     }
226
227
228     @Test
229     public void Given_Request_Is_HTTP_POST_And_Change_On_Feeds_Succeeds_A_STATUS_OK_Response_Is_Generated() throws Exception {
230         ServletOutputStream outStream = mock(ServletOutputStream.class);
231         when(response.getOutputStream()).thenReturn(outStream);
232         PowerMockito.mockStatic(Subscription.class);
233         PowerMockito.when(Subscription.getSubscriptionMatching(mock(Subscription.class))).thenReturn(null);
234         JSONObject JSObject = buildRequestJsonObject();
235         SubscribeServlet subscribeServlet = new SubscribeServlet() {
236             protected JSONObject getJSONfromInput(HttpServletRequest req) {
237                 JSONObject jo = new JSONObject();
238                 jo.put("name", "stub_name");
239                 jo.put("version", "2.0");
240                 jo.put("metadataOnly", true);
241                 jo.put("suspend", true);
242                 jo.put("delivery", JSObject);
243                 jo.put("sync", true);
244                 return jo;
245             }
246
247             @Override
248             protected boolean doInsert(Insertable bean) {
249                 return true;
250             }
251         };
252         subscribeServlet.doPost(request, response);
253         verify(response).setStatus(eq(HttpServletResponse.SC_CREATED));
254     }
255
256
257     @NotNull
258     private JSONObject buildRequestJsonObject() {
259         JSONObject JSObject = new JSONObject();
260         JSObject.put("url", "https://stub_address");
261         JSObject.put("use100", "true");
262         JSObject.put("password", "stub_password");
263         JSObject.put("user", "stub_user");
264         return JSObject;
265     }
266
267     private void setUpValidSecurityOnHttpRequest() throws Exception {
268         when(request.isSecure()).thenReturn(true);
269         Set<String> authAddressesAndNetworks = new HashSet<String>();
270         authAddressesAndNetworks.add(("127.0.0.1"));
271         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authorizedAddressesAndNetworks", authAddressesAndNetworks, true);
272         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", false, true);
273         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "maxSubs", 1, true);
274     }
275
276     private void setBehalfHeader(String headerValue) {
277         when(request.getHeader(BEHALF_HEADER)).thenReturn(headerValue);
278     }
279
280     private void setValidPathInfoInHttpHeader() {
281         when(request.getPathInfo()).thenReturn("/123");
282     }
283
284     private void setFeedToReturnInvalidFeedIdSupplied() {
285         PowerMockito.mockStatic(Feed.class);
286         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(null);
287     }
288
289     private void setFeedToReturnValidFeedForSuppliedId() {
290         PowerMockito.mockStatic(Feed.class);
291         Feed feed = mock(Feed.class);
292         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(feed);
293         when(feed.isDeleted()).thenReturn(false);
294         when(feed.asJSONObject(true)).thenReturn(mock(JSONObject.class));
295         when(feed.getPublisher()).thenReturn("Stub_Value");
296         when(feed.getName()).thenReturn("stub_name");
297         when(feed.getVersion()).thenReturn("1.0");
298         when(feed.asLimitedJSONObject()).thenReturn(mock(JSONObject.class));
299     }
300
301     private void setAuthoriserToReturnRequestNotAuthorized() throws IllegalAccessException {
302         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
303         Authorizer authorizer = mock(Authorizer.class);
304         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
305         when(authorizer.decide(request)).thenReturn(authResponse);
306         when(authResponse.isAuthorized()).thenReturn(false);
307     }
308
309     private void setAuthoriserToReturnRequestIsAuthorized() throws IllegalAccessException {
310         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
311         Authorizer authorizer = mock(Authorizer.class);
312         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
313         when(authorizer.decide(request)).thenReturn(authResponse);
314         when(authResponse.isAuthorized()).thenReturn(true);
315     }
316
317     private void setPokerToNotCreateTimersWhenDeleteFeedIsCalled() throws Exception {
318         Poker poker = mock(Poker.class);
319         FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
320     }
321
322     private void setupValidAuthorisedRequest() throws Exception {
323         setUpValidSecurityOnHttpRequest();
324         setBehalfHeader("Stub_Value");
325         setValidPathInfoInHttpHeader();
326         setFeedToReturnValidFeedForSuppliedId();
327     }
328
329     private void setUpValidContentHeadersAndJSONOnHttpRequest() {
330         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.subscription; version=1.0");
331         when(request.getHeader("X-ATT-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
332
333     }
334 }