View Javadoc

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