View Javadoc

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