View Javadoc

1   /*
2    * $Id: FileUploadInterceptorTest.java 651946 2008-04-27 13:41:38Z apetrelli $
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  package org.apache.struts2.interceptor;
23  
24  import java.io.File;
25  import java.io.IOException;
26  import java.net.URI;
27  import java.net.URL;
28  import java.util.HashMap;
29  import java.util.List;
30  import java.util.Locale;
31  import java.util.Map;
32  
33  import javax.servlet.http.HttpServletRequest;
34  
35  import org.apache.struts2.ServletActionContext;
36  import org.apache.struts2.StrutsTestCase;
37  import org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest;
38  import org.apache.struts2.dispatcher.multipart.MultiPartRequest;
39  import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
40  import org.springframework.mock.web.MockHttpServletRequest;
41  
42  import com.opensymphony.xwork2.util.ClassLoaderUtil;
43  import com.opensymphony.xwork2.ActionContext;
44  import com.opensymphony.xwork2.ActionSupport;
45  import com.opensymphony.xwork2.ValidationAwareSupport;
46  import com.opensymphony.xwork2.mock.MockActionInvocation;
47  
48  
49  /***
50   * Test case for FileUploadInterceptor.
51   *
52   */
53  public class FileUploadInterceptorTest extends StrutsTestCase {
54  
55      private FileUploadInterceptor interceptor;
56      private File tempDir;
57  
58      public void testAcceptFileWithEmptyAllowedTypes() throws Exception {
59          // when allowed type is empty
60          ValidationAwareSupport validation = new ValidationAwareSupport();
61          boolean ok = interceptor.acceptFile(new File(""), "text/plain", "inputName", validation, Locale.getDefault());
62  
63          assertTrue(ok);
64          assertTrue(validation.getFieldErrors().isEmpty());
65          assertFalse(validation.hasErrors());
66      }
67  
68      public void testAcceptFileWithoutEmptyTypes() throws Exception {
69          interceptor.setAllowedTypes("text/plain");
70  
71          // when file is of allowed types
72          ValidationAwareSupport validation = new ValidationAwareSupport();
73          boolean ok = interceptor.acceptFile(new File(""), "text/plain", "inputName", validation, Locale.getDefault());
74  
75          assertTrue(ok);
76          assertTrue(validation.getFieldErrors().isEmpty());
77          assertFalse(validation.hasErrors());
78  
79          // when file is not of allowed types
80          validation = new ValidationAwareSupport();
81          boolean notOk = interceptor.acceptFile(new File(""), "text/html", "inputName", validation, Locale.getDefault());
82  
83          assertFalse(notOk);
84          assertFalse(validation.getFieldErrors().isEmpty());
85          assertTrue(validation.hasErrors());
86      }
87  
88      public void testAcceptFileWithNoFile() throws Exception {
89          FileUploadInterceptor interceptor = new FileUploadInterceptor();
90          interceptor.setAllowedTypes("text/plain");
91  
92          // when file is not of allowed types
93          ValidationAwareSupport validation = new ValidationAwareSupport();
94          boolean notOk = interceptor.acceptFile(null, "text/html", "inputName", validation, Locale.getDefault());
95  
96          assertFalse(notOk);
97          assertFalse(validation.getFieldErrors().isEmpty());
98          assertTrue(validation.hasErrors());
99          List errors = (List) validation.getFieldErrors().get("inputName");
100         assertEquals(1, errors.size());
101         String msg = (String) errors.get(0);
102         assertTrue(msg.startsWith("Error uploading:"));
103         assertTrue(msg.indexOf("inputName") > 0);
104     }
105 
106     public void testAcceptFileWithMaxSize() throws Exception {
107         interceptor.setAllowedTypes("text/plain");
108         interceptor.setMaximumSize(new Long(10));
109 
110         // when file is not of allowed types
111         ValidationAwareSupport validation = new ValidationAwareSupport();
112 
113         URL url = ClassLoaderUtil.getResource("log4j.properties", FileUploadInterceptorTest.class);
114         File file = new File(new URI(url.toString()));
115         assertTrue("log4j.properties should be in src/test folder", file.exists());
116         boolean notOk = interceptor.acceptFile(file, "text/html", "inputName", validation, Locale.getDefault());
117 
118         assertFalse(notOk);
119         assertFalse(validation.getFieldErrors().isEmpty());
120         assertTrue(validation.hasErrors());
121         List errors = (List) validation.getFieldErrors().get("inputName");
122         assertEquals(1, errors.size());
123         String msg = (String) errors.get(0);
124         // the error message shoul contain at least this test
125         assertTrue(msg.startsWith("The file is to large to be uploaded"));
126         assertTrue(msg.indexOf("inputName") > 0);
127         assertTrue(msg.indexOf("log4j.properties") > 0);
128     }
129 
130     public void testNoMultipartRequest() throws Exception {
131         MyFileupAction action = new MyFileupAction();
132 
133         MockActionInvocation mai = new MockActionInvocation();
134         mai.setAction(action);
135         mai.setResultCode("NoMultipart");
136         mai.setInvocationContext(ActionContext.getContext());
137 
138         // if no multipart request it will bypass and execute it
139         assertEquals("NoMultipart", interceptor.intercept(mai));
140     }
141 
142     public void testInvalidContentTypeMultipartRequest() throws Exception {
143         MockHttpServletRequest req = new MockHttpServletRequest();
144 
145         req.setCharacterEncoding("text/html");
146         req.setContentType("text/xml"); // not a multipart contentype
147         req.addHeader("Content-type", "multipart/form-data");
148 
149         MyFileupAction action = new MyFileupAction();
150         MockActionInvocation mai = new MockActionInvocation();
151         mai.setAction(action);
152         mai.setResultCode("success");
153         mai.setInvocationContext(ActionContext.getContext());
154 
155         Map param = new HashMap();
156         ActionContext.getContext().setParameters(param);
157         ActionContext.getContext().put(ServletActionContext.HTTP_REQUEST, createMultipartRequest((HttpServletRequest) req, 2000));
158 
159         interceptor.intercept(mai);
160 
161         assertTrue(action.hasErrors());
162     }
163 
164     public void testNoContentMultipartRequest() throws Exception {
165         MockHttpServletRequest req = new MockHttpServletRequest();
166 
167         req.setCharacterEncoding("text/html");
168         req.setContentType("multipart/form-data; boundary=---1234");
169         req.setContent(null); // there is no content
170 
171         MyFileupAction action = new MyFileupAction();
172         MockActionInvocation mai = new MockActionInvocation();
173         mai.setAction(action);
174         mai.setResultCode("success");
175         mai.setInvocationContext(ActionContext.getContext());
176 
177         Map param = new HashMap();
178         ActionContext.getContext().setParameters(param);
179         ActionContext.getContext().put(ServletActionContext.HTTP_REQUEST, createMultipartRequest((HttpServletRequest) req, 2000));
180 
181         interceptor.intercept(mai);
182 
183         assertTrue(action.hasErrors());
184     }
185 
186     public void testSuccessUploadOfATextFileMultipartRequest() throws Exception {
187         MockHttpServletRequest req = new MockHttpServletRequest();
188         req.setCharacterEncoding("text/html");
189         req.setContentType("multipart/form-data; boundary=---1234");
190         req.addHeader("Content-type", "multipart/form-data");
191 
192         // inspired by the unit tests for jakarta commons fileupload
193         String content = ("-----1234\r\n" +
194             "Content-Disposition: form-data; name=\"file\"; filename=\"deleteme.txt\"\r\n" +
195             "Content-Type: text/html\r\n" +
196             "\r\n" +
197             "Unit test of FileUploadInterceptor" +
198             "\r\n" +
199             "-----1234--\r\n");
200         req.setContent(content.getBytes("US-ASCII"));
201 
202         MyFileupAction action = new MyFileupAction();
203 
204         MockActionInvocation mai = new MockActionInvocation();
205         mai.setAction(action);
206         mai.setResultCode("success");
207         mai.setInvocationContext(ActionContext.getContext());
208         Map param = new HashMap();
209         ActionContext.getContext().setParameters(param);
210         ActionContext.getContext().put(ServletActionContext.HTTP_REQUEST, createMultipartRequest((HttpServletRequest) req, 2000));
211 
212         interceptor.intercept(mai);
213 
214         assertTrue(! action.hasErrors());
215 
216         assertTrue(param.size() == 3);
217         File[] files = (File[]) param.get("file");
218         String[] fileContentTypes = (String[]) param.get("fileContentType");
219         String[] fileRealFilenames = (String[]) param.get("fileFileName");
220 
221         assertNotNull(files);
222         assertNotNull(fileContentTypes);
223         assertNotNull(fileRealFilenames);
224         assertTrue(files.length == 1);
225         assertTrue(fileContentTypes.length == 1);
226         assertTrue(fileRealFilenames.length == 1);
227         assertEquals("text/html", fileContentTypes[0]);
228         assertNotNull("deleteme.txt", fileRealFilenames[0]);
229     }
230 
231     private MultiPartRequestWrapper createMultipartRequest(HttpServletRequest req, int maxsize) throws IOException {
232        JakartaMultiPartRequest jak = new JakartaMultiPartRequest();
233        jak.setMaxSize(String.valueOf(maxsize));
234        return new MultiPartRequestWrapper(jak, req, tempDir.getAbsolutePath());
235     }
236 
237     protected void setUp() throws Exception {
238         super.setUp();
239         interceptor = new FileUploadInterceptor();
240         tempDir = File.createTempFile("struts", "fileupload");
241         tempDir.delete();
242         tempDir.mkdirs();
243     }
244 
245     protected void tearDown() throws Exception {
246         tempDir.delete();
247         interceptor.destroy();
248         super.tearDown();
249     }
250 
251     private class MyFileupAction extends ActionSupport {
252 
253         private static final long serialVersionUID = 6255238895447968889L;
254 
255         // no methods
256     }
257 
258 
259 }