Search in sources :

Example 1 with FileUploadIOException

use of org.apache.commons.fileupload.FileUploadBase.FileUploadIOException in project ksan by infinistor.

the class DataPostObject method extract.

@Override
public void extract() throws GWException {
    String boundaryHeader = s3Parameter.getRequest().getHeader(HttpHeaders.CONTENT_TYPE);
    String boundary = boundaryHeader.substring(boundaryHeader.indexOf('=') + 1);
    try {
        s3Parameter.setInputStream(s3Parameter.getRequest().getInputStream());
    } catch (IOException e) {
        PrintStack.logging(logger, e);
        throw new GWException(GWErrorCode.INTERNAL_SERVER_ERROR, s3Parameter);
    }
    MultipartStream multipartStream = new MultipartStream(s3Parameter.getInputStream(), boundary.getBytes(StandardCharsets.UTF_8), 4096, null);
    boolean nextPart = false;
    try {
        nextPart = multipartStream.skipPreamble();
    } catch (IOException e) {
        PrintStack.logging(logger, e);
        throw new GWException(GWErrorCode.INTERNAL_SERVER_ERROR, s3Parameter);
    }
    while (nextPart) {
        String header;
        try {
            header = multipartStream.readHeaders();
            try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                multipartStream.readBodyData(baos);
                if (GWUtils.isField(header, GWConstants.PARAMETER_ACL)) {
                    aclkeyword = true;
                    acl = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.AWS_ACCESS_KEY_ID) || GWUtils.isField(header, GWConstants.X_AMZ_CREDENTIAL)) {
                    accesskey = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.CONTENT_TYPE)) {
                    contentType = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.OBJECT_TYPE_FILE)) {
                    payload = baos.toByteArray();
                } else if (GWUtils.isField(header, GWConstants.KEY)) {
                    key = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.PARAMETER_POLICY)) {
                    policy = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.SIGNATURE) || GWUtils.isField(header, GWConstants.X_AMZ_SIGNATURE)) {
                    signature = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.X_AMZ_ALGORITHM)) {
                    algorithm = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.CACHE_CONTROL)) {
                    cacheControl = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.CONTENT_DISPOSITION)) {
                    contentDisposition = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.CONTENT_ENCODING)) {
                    contentEncoding = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.EXPIRES)) {
                    expires = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.PARAMETER_TAGGING)) {
                    tagging = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.SUCCESS_ACTION_STATUS)) {
                    successActionStatus = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.SUCCESS_ACTION_REDIRECT)) {
                    successActionRedirect = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.X_AMZ_STORAGE_CLASS)) {
                    storageClass = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.X_AMZ_SERVER_SIDE_ENCRYPTION)) {
                    serverSideEncryption = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.X_AMZ_SERVER_SIDE_ENCRYPTION_AWS_KMS_KEY_ID)) {
                    serverSideEncryptionAwsKmsKeyId = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.X_AMZ_SERVER_SIDE_ENCRYPTION_CONTEXT)) {
                    serverSideEncryptionContext = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.X_AMZ_SERVER_SIDE_ENCRYPTION_BUCKET_KEY_ENABLED)) {
                    serverSideEncryptionBucketKeyEnabled = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM)) {
                    serverSideEncryptionCustomerAlgorithm = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY)) {
                    serverSideEncryptionCustomerKey = new String(baos.toByteArray());
                } else if (GWUtils.isField(header, GWConstants.X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_KEY_MD5)) {
                    serverSideEncryptionCustomerKeyMD5 = new String(baos.toByteArray());
                } else if (GWUtils.startsField(header, GWConstants.USER_METADATA_PREFIX)) {
                    String parseHeader = header.substring(GWConstants.CONTENT_DISPOSITION_FORM_DATA.length());
                    parseHeader = parseHeader.substring(0, parseHeader.lastIndexOf(GWConstants.DOUBLE_QUOTE));
                    userMetadata.put(parseHeader, new String(baos.toByteArray()));
                }
            } catch (IOException e) {
                PrintStack.logging(logger, e);
                throw new GWException(GWErrorCode.INTERNAL_SERVER_ERROR, s3Parameter);
            }
            nextPart = multipartStream.readBoundary();
        } catch (FileUploadIOException e) {
            PrintStack.logging(logger, e);
            throw new GWException(GWErrorCode.INTERNAL_SERVER_ERROR, s3Parameter);
        } catch (MalformedStreamException e) {
            PrintStack.logging(logger, e);
            throw new GWException(GWErrorCode.INTERNAL_SERVER_ERROR, s3Parameter);
        }
    }
}
Also used : IOException(java.io.IOException) FileUploadIOException(org.apache.commons.fileupload.FileUploadBase.FileUploadIOException) GWException(com.pspace.ifs.ksan.gw.exception.GWException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MalformedStreamException(org.apache.commons.fileupload.MultipartStream.MalformedStreamException) MultipartStream(org.apache.commons.fileupload.MultipartStream) FileUploadIOException(org.apache.commons.fileupload.FileUploadBase.FileUploadIOException)

Example 2 with FileUploadIOException

use of org.apache.commons.fileupload.FileUploadBase.FileUploadIOException in project jahia by Jahia.

the class GWTFileManagerUploadServlet method doPost.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    final PrintWriter printWriter = response.getWriter();
    final JahiaUser user = (JahiaUser) request.getSession().getAttribute(Constants.SESSION_USER);
    if (JahiaUserManagerService.isGuest(user)) {
        printWriter.write("READONLY\n");
        return;
    }
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    SettingsBean settingsBean = SettingsBean.getInstance();
    final long fileSizeLimit = settingsBean.getJahiaFileUploadMaxSize();
    upload.setHeaderEncoding("UTF-8");
    Map<String, FileItem> uploads = new HashMap<String, FileItem>();
    String location = null;
    String type = null;
    boolean unzip = false;
    LinkedHashSet<FileItem> fileItems = new LinkedHashSet<>();
    try {
        try {
            FileItemIterator itemIterator = upload.getItemIterator(request);
            FileSizeLimitExceededException sizeLimitExceededException = null;
            while (itemIterator.hasNext()) {
                final FileItemStream item = itemIterator.next();
                if (sizeLimitExceededException != null) {
                    continue;
                }
                FileItem fileItem = factory.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), item.getName());
                fileItems.add(fileItem);
                long contentLength = getContentLength(item.getHeaders());
                // If we have a content length in the header we can use it
                if (fileSizeLimit > 0 && contentLength != -1L && contentLength > fileSizeLimit) {
                    throw new FileSizeLimitExceededException("The field " + item.getFieldName() + " exceeds its maximum permitted size of " + fileSizeLimit + " bytes.", contentLength, fileSizeLimit);
                }
                InputStream itemStream = item.openStream();
                InputStream limitedInputStream = null;
                try {
                    limitedInputStream = fileSizeLimit > 0 ? new LimitedInputStream(itemStream, fileSizeLimit) {

                        @Override
                        protected void raiseError(long pSizeMax, long pCount) throws IOException {
                            throw new FileUploadIOException(new FileSizeLimitExceededException("The field " + item.getFieldName() + " exceeds its maximum permitted size of " + fileSizeLimit + " bytes.", pCount, pSizeMax));
                        }
                    } : itemStream;
                    Streams.copy(limitedInputStream, fileItem.getOutputStream(), true);
                } catch (FileUploadIOException e) {
                    if (e.getCause() instanceof FileSizeLimitExceededException) {
                        if (sizeLimitExceededException == null) {
                            sizeLimitExceededException = (FileSizeLimitExceededException) e.getCause();
                        }
                    } else {
                        throw e;
                    }
                } finally {
                    IOUtils.closeQuietly(limitedInputStream);
                }
                if ("unzip".equals(fileItem.getFieldName())) {
                    unzip = true;
                } else if ("uploadLocation".equals(fileItem.getFieldName())) {
                    location = fileItem.getString("UTF-8");
                } else if ("asyncupload".equals(fileItem.getFieldName())) {
                    String name = fileItem.getName();
                    if (name.trim().length() > 0) {
                        uploads.put(extractFileName(name, uploads), fileItem);
                    }
                    type = "async";
                } else if (!fileItem.isFormField() && fileItem.getFieldName().startsWith("uploadedFile")) {
                    String name = fileItem.getName();
                    if (name.trim().length() > 0) {
                        uploads.put(extractFileName(name, uploads), fileItem);
                    }
                    type = "sync";
                }
            }
            if (sizeLimitExceededException != null) {
                throw sizeLimitExceededException;
            }
        } catch (FileUploadBase.FileSizeLimitExceededException e) {
            printWriter.write("UPLOAD-SIZE-ISSUE: " + getSizeLimitErrorMessage(fileSizeLimit, e, request) + "\n");
            return;
        } catch (FileUploadIOException e) {
            if (e.getCause() != null && (e.getCause() instanceof FileSizeLimitExceededException)) {
                printWriter.write("UPLOAD-SIZE-ISSUE: " + getSizeLimitErrorMessage(fileSizeLimit, (FileSizeLimitExceededException) e.getCause(), request) + "\n");
            } else {
                logger.error("UPLOAD-ISSUE", e);
                printWriter.write("UPLOAD-ISSUE: " + e.getLocalizedMessage() + "\n");
            }
            return;
        } catch (FileUploadException e) {
            logger.error("UPLOAD-ISSUE", e);
            printWriter.write("UPLOAD-ISSUE: " + e.getLocalizedMessage() + "\n");
            return;
        }
        if (type == null || type.equals("sync")) {
            response.setContentType("text/plain");
            final List<String> pathsToUnzip = new ArrayList<String>();
            for (String fileName : uploads.keySet()) {
                final FileItem fileItem = uploads.get(fileName);
                try {
                    StringBuilder name = new StringBuilder(fileName);
                    final int saveResult = saveToJcr(user, fileItem, location, name);
                    switch(saveResult) {
                        case OK:
                            if (unzip && fileName.toLowerCase().endsWith(".zip")) {
                                pathsToUnzip.add(new StringBuilder(location).append("/").append(name.toString()).toString());
                            }
                            printWriter.write("OK: " + UriUtils.encode(name.toString()) + "\n");
                            break;
                        case EXISTS:
                            storeUploadedFile(request.getSession().getId(), fileItem);
                            printWriter.write("EXISTS: " + UriUtils.encode(fileItem.getFieldName()) + " " + UriUtils.encode(fileItem.getName()) + " " + UriUtils.encode(fileName) + "\n");
                            break;
                        case READONLY:
                            printWriter.write("READONLY: " + UriUtils.encode(fileItem.getFieldName()) + "\n");
                            break;
                        default:
                            printWriter.write("UPLOAD-FAILED: " + UriUtils.encode(fileItem.getFieldName()) + "\n");
                            break;
                    }
                } catch (IOException e) {
                    logger.error("Upload failed for file", e);
                }
            }
            // direct blocking unzip
            if (unzip && pathsToUnzip.size() > 0) {
                try {
                    ZipHelper zip = ZipHelper.getInstance();
                    // todo : in which workspace do we upload ?
                    zip.unzip(pathsToUnzip, true, JCRSessionFactory.getInstance().getCurrentUserSession(), (Locale) request.getSession().getAttribute(Constants.SESSION_UI_LOCALE));
                } catch (RepositoryException e) {
                    logger.error("Auto-unzipping failed", e);
                } catch (GWTJahiaServiceException e) {
                    logger.error("Auto-unzipping failed", e);
                }
            }
        } else {
            response.setContentType("text/html");
            for (FileItem fileItem : uploads.values()) {
                storeUploadedFile(request.getSession().getId(), fileItem);
                printWriter.write("<html><body>");
                String itemName = Encode.forHtmlAttribute(fileItem.getName());
                printWriter.write("<div id=\"uploaded\" key=\"" + itemName + "\" name=\"" + itemName + "\"></div>\n");
                printWriter.write("</body></html>");
            }
        }
    } finally {
        for (FileItem fileItem : fileItems) {
            fileItem.delete();
        }
    }
}
Also used : LimitedInputStream(org.apache.commons.fileupload.util.LimitedInputStream) FileSizeLimitExceededException(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException) ZipHelper(org.jahia.ajax.gwt.helper.ZipHelper) SettingsBean(org.jahia.settings.SettingsBean) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileSizeLimitExceededException(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException) PrintWriter(java.io.PrintWriter) BufferedInputStream(java.io.BufferedInputStream) LimitedInputStream(org.apache.commons.fileupload.util.LimitedInputStream) InputStream(java.io.InputStream) RepositoryException(javax.jcr.RepositoryException) IOException(java.io.IOException) FileUploadIOException(org.apache.commons.fileupload.FileUploadBase.FileUploadIOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadIOException(org.apache.commons.fileupload.FileUploadBase.FileUploadIOException) GWTJahiaServiceException(org.jahia.ajax.gwt.client.service.GWTJahiaServiceException) JahiaUser(org.jahia.services.usermanager.JahiaUser)

Example 3 with FileUploadIOException

use of org.apache.commons.fileupload.FileUploadBase.FileUploadIOException in project jahia by Jahia.

the class FileUpload method prepareUploadFileItem.

private DiskFileItemFactory prepareUploadFileItem(FileItemStream item, DiskFileItemFactory factory) throws FileUploadException, IOException {
    try (InputStream stream = item.openStream()) {
        if (item.isFormField()) {
            final String name = item.getFieldName();
            final List<String> v;
            if (params.containsKey(name)) {
                v = params.get(name);
            } else {
                v = new ArrayList<>();
                params.put(name, v);
            }
            v.add(Streams.asString(stream, encoding));
            paramsContentType.put(name, item.getContentType());
        } else {
            if (factory == null) {
                factory = new DiskFileItemFactory();
                factory.setSizeThreshold(1);
                factory.setRepository(new File(savePath));
            }
            DiskFileItem fileItem = (DiskFileItem) factory.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), item.getName());
            try {
                Streams.copy(stream, fileItem.getOutputStream(), true);
            } catch (FileUploadIOException e) {
                throw (FileUploadException) e.getCause();
            } catch (IOException e) {
                throw new IOFileUploadException("Processing of " + FileUploadBase.MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e);
            }
            final FileItemHeaders fih = item.getHeaders();
            fileItem.setHeaders(fih);
            if (fileItem.getSize() > 0) {
                files.put(fileItem.getStoreLocation().getName(), fileItem);
                filesByFieldName.put(fileItem.getFieldName(), fileItem);
            }
        }
    }
    return factory;
}
Also used : InputStream(java.io.InputStream) FileItemHeaders(org.apache.commons.fileupload.FileItemHeaders) IOFileUploadException(org.apache.commons.fileupload.FileUploadBase.IOFileUploadException) IOException(java.io.IOException) FileUploadIOException(org.apache.commons.fileupload.FileUploadBase.FileUploadIOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) File(java.io.File) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) FileUploadIOException(org.apache.commons.fileupload.FileUploadBase.FileUploadIOException)

Aggregations

IOException (java.io.IOException)3 FileUploadIOException (org.apache.commons.fileupload.FileUploadBase.FileUploadIOException)3 InputStream (java.io.InputStream)2 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)2 GWException (com.pspace.ifs.ksan.gw.exception.GWException)1 BufferedInputStream (java.io.BufferedInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 PrintWriter (java.io.PrintWriter)1 RepositoryException (javax.jcr.RepositoryException)1 FileItemHeaders (org.apache.commons.fileupload.FileItemHeaders)1 FileSizeLimitExceededException (org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException)1 IOFileUploadException (org.apache.commons.fileupload.FileUploadBase.IOFileUploadException)1 MultipartStream (org.apache.commons.fileupload.MultipartStream)1 MalformedStreamException (org.apache.commons.fileupload.MultipartStream.MalformedStreamException)1 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)1 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)1 LimitedInputStream (org.apache.commons.fileupload.util.LimitedInputStream)1 GWTJahiaServiceException (org.jahia.ajax.gwt.client.service.GWTJahiaServiceException)1 ZipHelper (org.jahia.ajax.gwt.helper.ZipHelper)1