use of org.apache.struts2.dispatcher.multipart.UploadedFile in project struts by apache.
the class FileUploadInterceptor method intercept.
/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext ac = invocation.getInvocationContext();
HttpServletRequest request = ac.getServletRequest();
if (!(request instanceof MultiPartRequestWrapper)) {
if (LOG.isDebugEnabled()) {
ActionProxy proxy = invocation.getProxy();
LOG.debug(getTextMessage("struts.messages.bypass.request", new String[] { proxy.getNamespace(), proxy.getActionName() }));
}
return invocation.invoke();
}
ValidationAware validation = null;
Object action = invocation.getAction();
if (action instanceof ValidationAware) {
validation = (ValidationAware) action;
}
MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
if (multiWrapper.hasErrors() && validation != null) {
TextProvider textProvider = getTextProvider(action);
for (LocalizedMessage error : multiWrapper.getErrors()) {
String errorMessage;
if (textProvider.hasKey(error.getTextKey())) {
errorMessage = textProvider.getText(error.getTextKey(), Arrays.asList(error.getArgs()));
} else {
errorMessage = textProvider.getText("struts.messages.error.uploading", error.getDefaultMessage());
}
validation.addActionError(errorMessage);
}
}
// bind allowed Files
Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {
// get the value of this input tag
String inputName = (String) fileParameterNames.nextElement();
// get the content type
String[] contentType = multiWrapper.getContentTypes(inputName);
if (isNonEmpty(contentType)) {
// get the name of the file from the input tag
String[] fileName = multiWrapper.getFileNames(inputName);
if (isNonEmpty(fileName)) {
// get a File object for the uploaded File
UploadedFile[] files = multiWrapper.getFiles(inputName);
if (files != null && files.length > 0) {
List<UploadedFile> acceptedFiles = new ArrayList<>(files.length);
List<String> acceptedContentTypes = new ArrayList<>(files.length);
List<String> acceptedFileNames = new ArrayList<>(files.length);
String contentTypeName = inputName + "ContentType";
String fileNameName = inputName + "FileName";
for (int index = 0; index < files.length; index++) {
if (acceptFile(action, files[index], fileName[index], contentType[index], inputName, validation)) {
acceptedFiles.add(files[index]);
acceptedContentTypes.add(contentType[index]);
acceptedFileNames.add(fileName[index]);
}
}
if (!acceptedFiles.isEmpty()) {
Map<String, Parameter> newParams = new HashMap<>();
newParams.put(inputName, new Parameter.File(inputName, acceptedFiles.toArray(new UploadedFile[acceptedFiles.size()])));
newParams.put(contentTypeName, new Parameter.File(contentTypeName, acceptedContentTypes.toArray(new String[acceptedContentTypes.size()])));
newParams.put(fileNameName, new Parameter.File(fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()])));
ac.getParameters().appendAll(newParams);
}
}
} else {
if (LOG.isWarnEnabled()) {
LOG.warn(getTextMessage(action, "struts.messages.invalid.file", new String[] { inputName }));
}
}
} else {
if (LOG.isWarnEnabled()) {
LOG.warn(getTextMessage(action, "struts.messages.invalid.content.type", new String[] { inputName }));
}
}
}
// invoke action
return invocation.invoke();
}
use of org.apache.struts2.dispatcher.multipart.UploadedFile in project struts by apache.
the class UploadedFileConverter method convertValue.
@Override
public Object convertValue(Map<String, Object> context, Object target, Member member, String propertyName, Object value, Class toType) {
if (File.class.equals(toType)) {
LOG.debug("Converting {} into {}, consider switching to {} and do not access {} directly!", File.class.getName(), UploadedFile.class.getName(), UploadedFile.class.getName(), File.class.getName());
Object obj;
if (value.getClass().isArray() && Array.getLength(value) == 1) {
obj = Array.get(value, 0);
} else {
obj = value;
}
if (obj instanceof UploadedFile) {
UploadedFile file = (UploadedFile) obj;
if (file.getContent() instanceof File) {
return file.getContent();
}
return new File(file.getAbsolutePath());
}
}
return super.convertValue(context, target, member, propertyName, value, toType);
}
use of org.apache.struts2.dispatcher.multipart.UploadedFile in project struts by apache.
the class FileUploadInterceptorTest method testSuccessUploadOfATextFileMultipartRequest.
public void testSuccessUploadOfATextFileMultipartRequest() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
req.setCharacterEncoding(StandardCharsets.UTF_8.name());
req.setMethod("post");
req.addHeader("Content-type", "multipart/form-data; boundary=---1234");
// inspired by the unit tests for jakarta commons fileupload
String content = ("-----1234\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"deleteme.txt\"\r\n" + "Content-Type: text/html\r\n" + "\r\n" + "Unit test of FileUploadInterceptor" + "\r\n" + "-----1234--\r\n");
req.setContent(content.getBytes("US-ASCII"));
MyFileupAction action = new MyFileupAction();
MockActionInvocation mai = new MockActionInvocation();
mai.setAction(action);
mai.setResultCode("success");
mai.setInvocationContext(ActionContext.getContext());
Map<String, Object> param = new HashMap<>();
ActionContext.getContext().setParameters(HttpParameters.create(param).build());
ActionContext.getContext().put(ServletActionContext.HTTP_REQUEST, createMultipartRequest(req, 2000));
interceptor.intercept(mai);
assertTrue(!action.hasErrors());
HttpParameters parameters = mai.getInvocationContext().getParameters();
assertTrue(parameters.keySet().size() == 3);
UploadedFile[] files = (UploadedFile[]) parameters.get("file").getObject();
String[] fileContentTypes = parameters.get("fileContentType").getMultipleValues();
String[] fileRealFilenames = parameters.get("fileFileName").getMultipleValues();
assertNotNull(files);
assertNotNull(fileContentTypes);
assertNotNull(fileRealFilenames);
assertTrue(files.length == 1);
assertTrue(fileContentTypes.length == 1);
assertTrue(fileRealFilenames.length == 1);
assertEquals("text/html", fileContentTypes[0]);
assertNotNull("deleteme.txt", fileRealFilenames[0]);
}
use of org.apache.struts2.dispatcher.multipart.UploadedFile in project struts by apache.
the class FileUploadInterceptorTest method testMultipleAccept.
/**
* tests whether with multiple files sent with the same name, the ones with forbiddenTypes (see
* FileUploadInterceptor.setAllowedTypes(...) ) are sorted out.
*
* @throws Exception
*/
public void testMultipleAccept() throws Exception {
final String htmlContent = "<html><head></head><body>html content</body></html>";
final String plainContent = "plain content";
final String bondary = "simple boundary";
final String endline = "\r\n";
MockHttpServletRequest req = new MockHttpServletRequest();
req.setCharacterEncoding(StandardCharsets.UTF_8.name());
req.setMethod("POST");
req.addHeader("Content-type", "multipart/form-data; boundary=" + bondary);
StringBuilder content = new StringBuilder(128);
content.append(encodeTextFile(bondary, endline, "file", "test.html", "text/plain", plainContent));
content.append(encodeTextFile(bondary, endline, "file", "test1.html", "text/html", htmlContent));
content.append(encodeTextFile(bondary, endline, "file", "test2.html", "text/html", htmlContent));
content.append(endline);
content.append(endline);
content.append(endline);
content.append("--");
content.append(bondary);
content.append("--");
content.append(endline);
req.setContent(content.toString().getBytes());
assertTrue(ServletFileUpload.isMultipartContent(req));
MyFileupAction action = new MyFileupAction();
container.inject(action);
MockActionInvocation mai = new MockActionInvocation();
mai.setAction(action);
mai.setResultCode("success");
mai.setInvocationContext(ActionContext.getContext());
Map<String, Object> param = new HashMap<String, Object>();
ActionContext.getContext().setParameters(HttpParameters.create(param).build());
ActionContext.getContext().put(ServletActionContext.HTTP_REQUEST, createMultipartRequest(req, 2000));
interceptor.setAllowedTypes("text/html");
interceptor.intercept(mai);
HttpParameters parameters = mai.getInvocationContext().getParameters();
assertEquals(3, parameters.keySet().size());
UploadedFile[] files = (UploadedFile[]) parameters.get("file").getObject();
String[] fileContentTypes = parameters.get("fileContentType").getMultipleValues();
String[] fileRealFilenames = parameters.get("fileFileName").getMultipleValues();
assertNotNull(files);
assertNotNull(fileContentTypes);
assertNotNull(fileRealFilenames);
assertEquals("files accepted ", 2, files.length);
assertEquals(2, fileContentTypes.length);
assertEquals(2, fileRealFilenames.length);
assertEquals("text/html", fileContentTypes[0]);
assertNotNull("test1.html", fileRealFilenames[0]);
}
use of org.apache.struts2.dispatcher.multipart.UploadedFile in project struts by apache.
the class UploadedFileConverterTest method convertUploadedFileToFile.
@Test
public void convertUploadedFileToFile() throws Exception {
// given
UploadedFileConverter ufc = new UploadedFileConverter();
UploadedFile uploadedFile = new StrutsUploadedFile(tempFile);
// when
Object result = ufc.convertValue(context, target, member, propertyName, uploadedFile, File.class);
// then
assertThat(result).isInstanceOf(File.class);
File file = (File) result;
assertThat(file.length()).isEqualTo(tempFile.length());
assertThat(file.getAbsolutePath()).isEqualTo(tempFile.getAbsolutePath());
}
Aggregations