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         JSONObject JSObject = buildRequestJsonObject();
205         SubscribeServlet subscribeServlet = new SubscribeServlet() {
206             protected JSONObject getJSONfromInput(HttpServletRequest req) {
207                 JSONObject jo = new JSONObject();
208                 jo.put("name", "stub_name");
209                 jo.put("version", "2.0");
210                 jo.put("metadataOnly", true);
211                 jo.put("suspend", true);
212                 jo.put("delivery", JSObject);
213                 jo.put("sync", false);
214                 return jo;
215             }
216
217             @Override
218             protected boolean doInsert(Insertable bean) {
219                 return false;
220             }
221         };
222         subscribeServlet.doPost(request, response);
223         verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), argThat(notNullValue(String.class)));
224     }
225
226
227     @Test
228     public void Given_Request_Is_HTTP_POST_And_Change_On_Feeds_Succeeds_A_STATUS_OK_Response_Is_Generated() throws Exception {
229         ServletOutputStream outStream = mock(ServletOutputStream.class);
230         when(response.getOutputStream()).thenReturn(outStream);
231         PowerMockito.mockStatic(Subscription.class);
232         PowerMockito.when(Subscription.getSubscriptionMatching(mock(Subscription.class))).thenReturn(null);
233         JSONObject JSObject = buildRequestJsonObject();
234         SubscribeServlet subscribeServlet = new SubscribeServlet() {
235             protected JSONObject getJSONfromInput(HttpServletRequest req) {
236                 JSONObject jo = new JSONObject();
237                 jo.put("name", "stub_name");
238                 jo.put("version", "2.0");
239                 jo.put("metadataOnly", true);
240                 jo.put("suspend", true);
241                 jo.put("delivery", JSObject);
242                 jo.put("sync", true);
243                 return jo;
244             }
245
246             @Override
247             protected boolean doInsert(Insertable bean) {
248                 return true;
249             }
250         };
251         subscribeServlet.doPost(request, response);
252         verify(response).setStatus(eq(HttpServletResponse.SC_CREATED));
253     }
254
255
256     @NotNull
257     private JSONObject buildRequestJsonObject() {
258         JSONObject JSObject = new JSONObject();
259         JSObject.put("url", "https://stub_address");
260         JSObject.put("use100", "true");
261         JSObject.put("password", "stub_password");
262         JSObject.put("user", "stub_user");
263         return JSObject;
264     }
265
266     private void setUpValidSecurityOnHttpRequest() throws Exception {
267         when(request.isSecure()).thenReturn(true);
268         Set<String> authAddressesAndNetworks = new HashSet<String>();
269         authAddressesAndNetworks.add(("127.0.0.1"));
270         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authorizedAddressesAndNetworks", authAddressesAndNetworks, true);
271         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", false, true);
272         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "maxSubs", 1, true);
273     }
274
275     private void setBehalfHeader(String headerValue) {
276         when(request.getHeader(BEHALF_HEADER)).thenReturn(headerValue);
277     }
278
279     private void setValidPathInfoInHttpHeader() {
280         when(request.getPathInfo()).thenReturn("/123");
281     }
282
283     private void setFeedToReturnInvalidFeedIdSupplied() {
284         PowerMockito.mockStatic(Feed.class);
285         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(null);
286     }
287
288     private void setFeedToReturnValidFeedForSuppliedId() {
289         PowerMockito.mockStatic(Feed.class);
290         Feed feed = mock(Feed.class);
291         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(feed);
292         when(feed.isDeleted()).thenReturn(false);
293         when(feed.asJSONObject(true)).thenReturn(mock(JSONObject.class));
294         when(feed.getPublisher()).thenReturn("Stub_Value");
295         when(feed.getName()).thenReturn("stub_name");
296         when(feed.getVersion()).thenReturn("1.0");
297         when(feed.asLimitedJSONObject()).thenReturn(mock(JSONObject.class));
298     }
299
300     private void setAuthoriserToReturnRequestNotAuthorized() throws IllegalAccessException {
301         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
302         Authorizer authorizer = mock(Authorizer.class);
303         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
304         when(authorizer.decide(request)).thenReturn(authResponse);
305         when(authResponse.isAuthorized()).thenReturn(false);
306     }
307
308     private void setAuthoriserToReturnRequestIsAuthorized() throws IllegalAccessException {
309         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
310         Authorizer authorizer = mock(Authorizer.class);
311         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
312         when(authorizer.decide(request)).thenReturn(authResponse);
313         when(authResponse.isAuthorized()).thenReturn(true);
314     }
315
316     private void setPokerToNotCreateTimersWhenDeleteFeedIsCalled() throws Exception {
317         Poker poker = mock(Poker.class);
318         FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
319     }
320
321     private void setupValidAuthorisedRequest() throws Exception {
322         setUpValidSecurityOnHttpRequest();
323         setBehalfHeader("Stub_Value");
324         setValidPathInfoInHttpHeader();
325         setFeedToReturnValidFeedForSuppliedId();
326     }
327
328     private void setUpValidContentHeadersAndJSONOnHttpRequest() {
329         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.subscription; version=1.0");
330         when(request.getHeader("X-ATT-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
331
332     }
333 }