use of org.apache.commons.fileupload.FileUploadException in project structr by structr.
the class UploadServlet method doPut.
@Override
protected void doPut(final HttpServletRequest request, final HttpServletResponse response) throws ServletException {
try (final Tx tx = StructrApp.getInstance().tx(true, false, false)) {
final String uuid = PathHelper.getName(request.getPathInfo());
if (uuid == null) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getOutputStream().write("URL path doesn't end with UUID.\n".getBytes("UTF-8"));
return;
}
Matcher matcher = threadLocalUUIDMatcher.get();
matcher.reset(uuid);
if (!matcher.matches()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getOutputStream().write("ERROR (400): URL path doesn't end with UUID.\n".getBytes("UTF-8"));
return;
}
final SecurityContext securityContext = getConfig().getAuthenticator().initializeAndExamineRequest(request, response);
// Ensure access mode is frontend
securityContext.setAccessMode(AccessMode.Frontend);
request.setCharacterEncoding("UTF-8");
// Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4
response.setCharacterEncoding("UTF-8");
// don't continue on redirects
if (response.getStatus() == 302) {
return;
}
uploader.setFileSizeMax(MEGABYTE * Settings.UploadMaxFileSize.getValue());
uploader.setSizeMax(MEGABYTE * Settings.UploadMaxRequestSize.getValue());
FileItemIterator fileItemsIterator = uploader.getItemIterator(request);
while (fileItemsIterator.hasNext()) {
final FileItemStream fileItem = fileItemsIterator.next();
try {
final GraphObject node = StructrApp.getInstance().getNodeById(uuid);
if (node == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.getOutputStream().write("ERROR (404): File not found.\n".getBytes("UTF-8"));
}
if (node instanceof org.structr.web.entity.File) {
final File file = (File) node;
if (file.isGranted(Permission.write, securityContext)) {
try (final InputStream is = fileItem.openStream()) {
FileHelper.writeToFile(file, is);
file.increaseVersion();
// upload trigger
file.notifyUploadCompletion();
}
} else {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.getOutputStream().write("ERROR (403): Write access forbidden.\n".getBytes("UTF-8"));
}
}
} catch (IOException ex) {
logger.warn("Could not write to file", ex);
}
}
tx.success();
} catch (FrameworkException | IOException | FileUploadException t) {
logger.error("Exception while processing request", t);
UiAuthenticator.writeInternalServerError(response);
}
}
use of org.apache.commons.fileupload.FileUploadException in project Gemma by PavlidisLab.
the class CommonsMultipartFile method transferTo.
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
if (!isAvailable()) {
throw new IllegalStateException("File has already been moved - cannot be transferred again");
}
if (dest.exists() && !dest.delete()) {
throw new IOException("Destination file [" + dest.getAbsolutePath() + "] already exists and could not be deleted");
}
try {
this.fileItem.write(dest);
if (logger.isDebugEnabled()) {
String action = "transferred";
if (!this.fileItem.isInMemory()) {
action = isAvailable() ? "copied" : "moved";
}
logger.debug("Multipart file '" + getName() + "' with original filename [" + getOriginalFilename() + "], stored " + getStorageDescription() + ": " + action + " to [" + dest.getAbsolutePath() + "]");
}
} catch (FileUploadException ex) {
throw new IllegalStateException(ex.getMessage());
} catch (IOException ex) {
throw ex;
} catch (Exception ex) {
logger.error("Could not transfer to file", ex);
throw new IOException("Could not transfer to file: " + ex.getMessage());
}
}
use of org.apache.commons.fileupload.FileUploadException in project com-liferay-apio-architect by liferay.
the class MultipartBodyMessageBodyReader method readFrom.
@Override
public Body readFrom(Class<Body> clazz, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
if (!isMultipartContent(_httpServletRequest)) {
throw new BadRequestException("Request body is not a valid multipart form");
}
FileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
try {
List<FileItem> fileItems = servletFileUpload.parseRequest(_httpServletRequest);
Iterator<FileItem> iterator = fileItems.iterator();
Map<String, String> values = new HashMap<>();
Map<String, BinaryFile> binaryFiles = new HashMap<>();
Map<String, Map<Integer, String>> indexedValueLists = new HashMap<>();
Map<String, Map<Integer, BinaryFile>> indexedFileLists = new HashMap<>();
while (iterator.hasNext()) {
FileItem fileItem = iterator.next();
String name = fileItem.getFieldName();
Matcher matcher = _arrayPattern.matcher(name);
if (matcher.matches()) {
int index = Integer.parseInt(matcher.group(2));
String actualName = matcher.group(1);
_storeFileItem(fileItem, value -> {
Map<Integer, String> indexedMap = indexedValueLists.computeIfAbsent(actualName, __ -> new HashMap<>());
indexedMap.put(index, value);
}, binaryFile -> {
Map<Integer, BinaryFile> indexedMap = indexedFileLists.computeIfAbsent(actualName, __ -> new HashMap<>());
indexedMap.put(index, binaryFile);
});
} else {
_storeFileItem(fileItem, value -> values.put(name, value), binaryFile -> binaryFiles.put(name, binaryFile));
}
}
Map<String, List<String>> valueLists = _flattenMap(indexedValueLists);
Map<String, List<BinaryFile>> fileLists = _flattenMap(indexedFileLists);
return Body.create(key -> Optional.ofNullable(values.get(key)), key -> Optional.ofNullable(valueLists.get(key)), key -> Optional.ofNullable(fileLists.get(key)), key -> Optional.ofNullable(binaryFiles.get(key)));
} catch (FileUploadException | IndexOutOfBoundsException | NumberFormatException e) {
throw new BadRequestException("Request body is not a valid multipart form", e);
}
}
use of org.apache.commons.fileupload.FileUploadException in project ninja by ninjaframework.
the class UploadController method uploadFinish.
/**
* This upload method expects a file and simply displays the file in the
* multipart upload again to the user (in the correct mime encoding).
*
* @param context
* @return
* @throws Exception
*/
public Result uploadFinish(Context context) throws Exception {
// we are using a renderable inner class to stream the input again to
// the user
Renderable renderable = new Renderable() {
@Override
public void render(Context context, Result result) {
try {
// make sure the context really is a multipart context...
if (context.isMultipart()) {
// This is the iterator we can use to iterate over the
// contents
// of the request.
FileItemIterator fileItemIterator = context.getFileItemIterator();
while (fileItemIterator.hasNext()) {
FileItemStream item = fileItemIterator.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
String contentType = item.getContentType();
if (contentType != null) {
result.contentType(contentType);
} else {
contentType = mimeTypes.getMimeType(name);
}
ResponseStreams responseStreams = context.finalizeHeaders(result);
if (item.isFormField()) {
System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
} else {
System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
// Process the input stream
ByteStreams.copy(stream, responseStreams.getOutputStream());
}
}
}
} catch (IOException | FileUploadException exception) {
throw new InternalServerErrorException(exception);
}
}
};
return new Result(200).render(renderable);
}
use of org.apache.commons.fileupload.FileUploadException in project ninja by ninjaframework.
the class NinjaServletContext method getFileItemIterator.
@Override
public FileItemIterator getFileItemIterator() {
long maxFileSize = ninjaProperties.getIntegerWithDefault(NinjaConstant.UPLOADS_MAX_FILE_SIZE, -1);
long maxTotalSize = ninjaProperties.getIntegerWithDefault(NinjaConstant.UPLOADS_MAX_TOTAL_SIZE, -1);
ServletFileUpload upload = new ServletFileUpload();
upload.setFileSizeMax(maxFileSize);
upload.setSizeMax(maxTotalSize);
FileItemIterator fileItemIterator = null;
try {
fileItemIterator = upload.getItemIterator(httpServletRequest);
} catch (FileUploadException | IOException e) {
logger.error("Error while trying to process mulitpart file upload", e);
}
return fileItemIterator;
}
Aggregations