Search in sources :

Example 31 with FileUploadException

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);
    }
}
Also used : Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) Matcher(java.util.regex.Matcher) ThreadLocalMatcher(org.structr.common.ThreadLocalMatcher) InputStream(java.io.InputStream) IOException(java.io.IOException) GraphObject(org.structr.core.GraphObject) FileItemStream(org.apache.commons.fileupload.FileItemStream) SecurityContext(org.structr.common.SecurityContext) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) AbstractFile(org.structr.web.entity.AbstractFile) File(org.structr.web.entity.File) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 32 with FileUploadException

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());
    }
}
Also used : IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 33 with FileUploadException

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);
    }
}
Also used : HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ArrayList(java.util.ArrayList) List(java.util.List) BinaryFile(com.liferay.apio.architect.file.BinaryFile) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) BadRequestException(javax.ws.rs.BadRequestException) HashMap(java.util.HashMap) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 34 with FileUploadException

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);
}
Also used : Context(ninja.Context) Renderable(ninja.Renderable) ResponseStreams(ninja.utils.ResponseStreams) FileItemStream(org.apache.commons.fileupload.FileItemStream) InputStream(java.io.InputStream) InternalServerErrorException(ninja.exceptions.InternalServerErrorException) IOException(java.io.IOException) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException) Result(ninja.Result)

Example 35 with FileUploadException

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;
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) IOException(java.io.IOException) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

FileUploadException (org.apache.commons.fileupload.FileUploadException)88 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)65 FileItem (org.apache.commons.fileupload.FileItem)57 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)51 IOException (java.io.IOException)37 HashMap (java.util.HashMap)27 ArrayList (java.util.ArrayList)23 List (java.util.List)21 File (java.io.File)20 InputStream (java.io.InputStream)19 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)19 FileItemStream (org.apache.commons.fileupload.FileItemStream)19 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)16 ServletException (javax.servlet.ServletException)12 Map (java.util.Map)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 Iterator (java.util.Iterator)8 ApplicationContext (org.springframework.context.ApplicationContext)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6