fbdd923078bcfae480ee136bc26ade09073893f6
[dmaap/datarouter.git] / datarouter-node / src / test / java / org / onap / dmaap / datarouter / node / NodeServletTest.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.node;
24
25 import org.apache.commons.lang3.reflect.FieldUtils;
26 import org.junit.Before;
27 import org.junit.Test;
28 import org.junit.runner.RunWith;
29 import org.mockito.Mock;
30 import org.powermock.api.mockito.PowerMockito;
31 import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
32 import org.powermock.modules.junit4.PowerMockRunner;
33
34 import javax.servlet.ServletOutputStream;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
37
38 import java.util.*;
39
40 import static org.hamcrest.Matchers.notNullValue;
41 import static org.mockito.Matchers.eq;
42 import static org.mockito.Mockito.*;
43
44 @RunWith(PowerMockRunner.class)
45 @SuppressStaticInitializationFor("org.onap.dmaap.datarouter.node.NodeConfigManager")
46 public class NodeServletTest {
47
48     private NodeServlet nodeServlet;
49
50     @Mock
51     private HttpServletRequest request;
52
53     @Mock
54     private HttpServletResponse response;
55
56     @Before
57     public void setUp() throws Exception{
58         nodeServlet = new NodeServlet();
59         setBehalfHeader("Stub_Value");
60         when(request.getPathInfo()).thenReturn("2");
61         when(request.isSecure()).thenReturn(true);
62         setUpConfig();
63         setUpNodeMainDelivery();
64         when(request.getHeader("Authorization")).thenReturn("User1");
65         when(request.getHeader("X-ATT-DR-PUBLISH-ID")).thenReturn("User1");
66     }
67
68     @Test
69     public void Given_Request_Is_HTTP_GET_And_Config_Is_Down_Then_Service_Unavailable_Response_Is_Generated() throws Exception {
70         setNodeConfigManagerIsConfiguredToReturnFalse();
71         nodeServlet.doGet(request, response);
72         verify(response).sendError(eq(HttpServletResponse.SC_SERVICE_UNAVAILABLE));
73     }
74
75     @Test
76     public void Given_Request_Is_HTTP_GET_And_Endpoint_Is_Internal_FetchProv_Then_No_Content_Response_Is_Generated() throws Exception {
77         when(request.getPathInfo()).thenReturn("/internal/fetchProv");
78         nodeServlet.doGet(request, response);
79         verify(response).setStatus(eq(HttpServletResponse.SC_NO_CONTENT));
80     }
81
82     @Test
83     public void Given_Request_Is_HTTP_GET_And_Endpoint_Is_ResetSubscription_Then_No_Content_Response_Is_Generated() throws Exception {
84         when(request.getPathInfo()).thenReturn("/internal/resetSubscription/1");
85         nodeServlet.doGet(request, response);
86         verify(response).setStatus(eq(HttpServletResponse.SC_NO_CONTENT));
87     }
88
89     @Test
90     public void Given_Request_Is_HTTP_GET_To_Invalid_Endpoint_Then_Not_Found_Response_Is_Generated() throws Exception {
91         when(request.getPathInfo()).thenReturn("/incorrect");
92         nodeServlet.doGet(request, response);
93         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND));
94     }
95
96     @Test
97     public void Given_Request_Is_HTTP_PUT_And_Config_Is_Down_Then_Service_Unavailable_Response_Is_Generated() throws Exception {
98         setNodeConfigManagerIsConfiguredToReturnFalse();
99         nodeServlet.doPut(request, response);
100         verify(response).sendError(eq(HttpServletResponse.SC_SERVICE_UNAVAILABLE));
101     }
102
103     @Test
104     public void Given_Request_Is_HTTP_PUT_And_Endpoint_Is_Incorrect_Then_Not_Found_Response_Is_Generated() throws Exception {
105         when(request.getPathInfo()).thenReturn("/incorrect/");
106         nodeServlet.doPut(request, response);
107         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
108     }
109
110     @Test
111     public void Given_Request_Is_HTTP_PUT_And_Request_Is_Not_Secure_Then_Forbidden_Response_Is_Generated() throws Exception {
112         when(request.isSecure()).thenReturn(false);
113         nodeServlet.doPut(request, response);
114         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
115     }
116
117     @Test
118     public void Given_Request_Is_HTTP_PUT_And_File_Id_Is_Null_Then_Not_Found_Response_Is_Generated() throws Exception {
119         when(request.getPathInfo()).thenReturn(null);
120         nodeServlet.doPut(request, response);
121         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
122     }
123
124     @Test
125     public void Given_Request_Is_HTTP_PUT_And_Authorization_Is_Null_Then_Forbidden_Response_Is_Generated() throws Exception {
126         when(request.getHeader("Authorization")).thenReturn(null);
127         nodeServlet.doPut(request, response);
128         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
129     }
130
131     @Test
132     public void Given_Request_Is_HTTP_PUT_And_Publish_Does_Not_Include_File_Id_Then_Not_Found_Response_Is_Generated() throws Exception {
133         when(request.getPathInfo()).thenReturn("/publish/");
134         nodeServlet.doPut(request, response);
135         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
136     }
137
138     @Test
139     public void Given_Request_Is_HTTP_PUT_And_Publish_Not_Permitted_Then_Forbidden_Response_Is_Generated() throws Exception {
140         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
141         setNodeConfigManagerIsPublishPermittedToReturnAReason();
142         nodeServlet.doPut(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_PUT_And_Internal_Publish_On_Same_Node_Then_Forbidden_Response_Is_Generated() throws Exception {
148         when(request.getPathInfo()).thenReturn("/internal/publish/1/fileName");
149         setNodeConfigManagerIsPublishPermittedToReturnAReason();
150         nodeServlet.doPut(request, response);
151         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN));
152     }
153
154     @Test
155     public void Given_Request_Is_HTTP_PUT_And_Internal_Publish_But_Invalid_File_Id_Then_Not_Found_Response_Is_Generated() throws Exception {
156         when(request.getPathInfo()).thenReturn("/internal/publish/1/");
157         nodeServlet.doPut(request, response);
158         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
159     }
160
161     @Test
162     public void Given_Request_Is_HTTP_PUT_On_Publish_And_Ingress_Node_Is_Provided_Then_Request_Is_Redirected() throws Exception {
163         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
164         setNodeConfigManagerToAllowRedirectOnIngressNode();
165         nodeServlet.doPut(request, response);
166         verify(response).sendRedirect(anyString());
167     }
168
169     @Test
170     public void Given_Request_Is_HTTP_PUT_On_Publish_With_Meta_Data_Too_Long_Then_Bad_Request_Response_Is_Generated() throws Exception {
171         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
172         setHeadersForValidRequest(true);
173         nodeServlet.doPut(request, response);
174         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
175     }
176
177     @Test
178     public void Given_Request_Is_HTTP_PUT_On_Publish_With_Meta_Data_Malformed_Then_Bad_Request_Response_Is_Generated() throws Exception {
179         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
180         setHeadersForValidRequest(false);
181         nodeServlet.doPut(request, response);
182         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
183     }
184
185     @Test
186     public void Given_Request_Is_HTTP_DELETE_On_Publish_With_Meta_Data_Malformed_Then_Bad_Request_Response_Is_Generated() throws Exception {
187         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
188         setHeadersForValidRequest(false);
189         nodeServlet.doDelete(request, response);
190         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
191     }
192
193
194     private void setBehalfHeader(String headerValue) {
195         when(request.getHeader("X-ATT-DR-ON-BEHALF-OF")).thenReturn(headerValue);
196     }
197
198     private void setUpConfig() throws IllegalAccessException{
199         NodeConfigManager config = mock(NodeConfigManager.class);
200         PowerMockito.mockStatic(NodeConfigManager.class);
201         when(config.isShutdown()).thenReturn(false);
202         when(config.isConfigured()).thenReturn(true);
203         when(config.getSpoolDir()).thenReturn("spool/dir");
204         when(config.getLogDir()).thenReturn("log/dir");
205         when(config.getPublishId()).thenReturn("User1");
206         when(config.isAnotherNode(anyString(), anyString())).thenReturn(true);
207         when(config.getEventLogInterval()).thenReturn("40");
208         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
209         FieldUtils.writeDeclaredStaticField(NodeMain.class, "nodeConfigManager", config, true);
210         PowerMockito.when(NodeConfigManager.getInstance()).thenReturn(config);
211     }
212
213
214     private void setUpNodeMainDelivery() throws IllegalAccessException{
215         Delivery delivery = mock(Delivery.class);
216         doNothing().when(delivery).resetQueue(anyObject());
217         FieldUtils.writeDeclaredStaticField(NodeMain.class, "delivery", delivery, true);
218     }
219
220     private void setNodeConfigManagerIsConfiguredToReturnFalse() throws IllegalAccessException{
221         NodeConfigManager config = mock(NodeConfigManager.class);
222         when(config.isConfigured()).thenReturn(false);
223         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
224     }
225
226     private void setNodeConfigManagerIsPublishPermittedToReturnAReason() throws IllegalAccessException{
227         NodeConfigManager config = mock(NodeConfigManager.class);
228         when(config.isShutdown()).thenReturn(false);
229         when(config.isConfigured()).thenReturn(true);
230         when(config.getSpoolDir()).thenReturn("spool/dir");
231         when(config.getLogDir()).thenReturn("log/dir");
232         when(config.isPublishPermitted(anyString(), anyString(), anyString())).thenReturn("Not Permitted");
233         when(config.isAnotherNode(anyString(), anyString())).thenReturn(false);
234         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
235     }
236
237     private void setNodeConfigManagerToAllowRedirectOnIngressNode() throws IllegalAccessException{
238         NodeConfigManager config = mock(NodeConfigManager.class);
239         when(config.isShutdown()).thenReturn(false);
240         when(config.isConfigured()).thenReturn(true);
241         when(config.getSpoolDir()).thenReturn("spool/dir");
242         when(config.getLogDir()).thenReturn("log/dir");
243         when(config.getPublishId()).thenReturn("User1");
244         when(config.isAnotherNode(anyString(), anyString())).thenReturn(true);
245         when(config.getAuthUser(anyString(), anyString())).thenReturn("User1");
246         when(config.getIngressNode(anyString(), anyString(), anyString())).thenReturn("NewNode");
247         when(config.getExtHttpsPort()).thenReturn(8080);
248         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
249     }
250
251     private String createLargeMetaDataString() {
252         StringBuilder myString = new StringBuilder("meta");
253         for (int i = 0; i <= 4098; ++i) {
254             myString.append('x');
255         }
256         return myString.toString();
257     }
258
259     private void setHeadersForValidRequest(boolean isMetaTooLong) {
260         String metaDataString;
261         if (isMetaTooLong) {
262             metaDataString = createLargeMetaDataString();
263         } else {
264             metaDataString = "?#@><";
265         }
266         List<String> headers = new ArrayList<>();
267         headers.add("Content-Type");
268         headers.add("X-ATT-DR-ON-BEHALF-OF");
269         headers.add("X-ATT-DR-META");
270         Enumeration<String> headerNames = Collections.enumeration(headers);
271         when(request.getHeaderNames()).thenReturn(headerNames);
272         Enumeration<String> contentTypeHeader = Collections.enumeration(Arrays.asList("text/plain"));
273         Enumeration<String> behalfHeader = Collections.enumeration(Arrays.asList("User1"));
274         Enumeration<String> metaDataHeader = Collections.enumeration(Arrays.asList(metaDataString));
275         when(request.getHeaders("Content-Type")).thenReturn(contentTypeHeader);
276         when(request.getHeaders("X-ATT-DR-ON-BEHALF-OF")).thenReturn(behalfHeader);
277         when(request.getHeaders("X-ATT-DR-META")).thenReturn(metaDataHeader);
278     }
279 }