Search in sources :

Example 21 with FileItemIterator

use of org.apache.commons.fileupload.FileItemIterator in project OpenRefine by OpenRefine.

the class ImportProjectCommand method internalImport.

protected void internalImport(HttpServletRequest request, Properties options, long projectID) throws Exception {
    String url = null;
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName().toLowerCase();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            if (name.equals("url")) {
                url = Streams.asString(stream);
            } else {
                options.put(name, Streams.asString(stream));
            }
        } else {
            String fileName = item.getName().toLowerCase();
            try {
                ProjectManager.singleton.importProject(projectID, stream, !fileName.endsWith(".tar"));
            } finally {
                stream.close();
            }
        }
    }
    if (url != null && url.length() > 0) {
        internalImportURL(request, options, projectID, url);
    }
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) InputStream(java.io.InputStream) FileItemIterator(org.apache.commons.fileupload.FileItemIterator)

Example 22 with FileItemIterator

use of org.apache.commons.fileupload.FileItemIterator in project zm-mailbox by Zimbra.

the class UserServletContext method getRequestInputStream.

public InputStream getRequestInputStream(long limit) throws IOException, ServiceException, UserServletException {
    String contentType = MimeConstants.CT_APPLICATION_OCTET_STREAM;
    String filename = null;
    InputStream is = null;
    final long DEFAULT_MAX_SIZE = 10 * 1024 * 1024;
    if (limit == 0) {
        if (req.getParameter("lbfums") != null) {
            limit = Provisioning.getInstance().getLocalServer().getLongAttr(Provisioning.A_zimbraFileUploadMaxSize, DEFAULT_MAX_SIZE);
        } else {
            limit = Provisioning.getInstance().getConfig().getLongAttr(Provisioning.A_zimbraMtaMaxMessageSize, DEFAULT_MAX_SIZE);
        }
    }
    boolean doCsrfCheck = false;
    if (req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK) != null) {
        doCsrfCheck = (Boolean) req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK);
    }
    if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload sfu = new ServletFileUpload();
        try {
            FileItemIterator iter = sfu.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream fis = iter.next();
                if (fis.isFormField()) {
                    is = fis.openStream();
                    params.put(fis.getFieldName(), new String(ByteUtil.getContent(is, -1), "UTF-8"));
                    if (doCsrfCheck && !this.csrfAuthSucceeded) {
                        String csrfToken = params.get(FileUploadServlet.PARAM_CSRF_TOKEN);
                        if (UserServlet.log.isDebugEnabled()) {
                            String paramValue = req.getParameter(UserServlet.QP_AUTH);
                            UserServlet.log.debug("CSRF check is: %s, CSRF token is: %s, Authentication recd with request is: %s", doCsrfCheck, csrfToken, paramValue);
                        }
                        if (!CsrfUtil.isValidCsrfToken(csrfToken, authToken)) {
                            setCsrfAuthSucceeded(Boolean.FALSE);
                            UserServlet.log.debug("CSRF token validation failed for account: %s" + ", Auth token is CSRF enabled:  %s" + "CSRF token is: %s", authToken, authToken.isCsrfTokenEnabled(), csrfToken);
                            throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, L10nUtil.getMessage(MsgKey.errMustAuthenticate));
                        } else {
                            setCsrfAuthSucceeded(Boolean.TRUE);
                        }
                    }
                    is.close();
                    is = null;
                } else {
                    is = new UploadInputStream(fis.openStream(), limit);
                    break;
                }
            }
        } catch (UserServletException e) {
            throw new UserServletException(e.getHttpStatusCode(), e.getMessage(), e);
        } catch (Exception e) {
            throw new UserServletException(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, e.toString());
        }
        if (is == null)
            throw new UserServletException(HttpServletResponse.SC_NO_CONTENT, "No file content");
    } else {
        ContentType ctype = new ContentType(req.getContentType());
        String contentEncoding = req.getHeader("Content-Encoding");
        contentType = ctype.getContentType();
        filename = ctype.getParameter("name");
        if (filename == null || filename.trim().equals(""))
            filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename");
        is = new UploadInputStream(contentEncoding != null && contentEncoding.indexOf("gzip") != -1 ? new GZIPInputStream(req.getInputStream()) : req.getInputStream(), limit);
    }
    if (filename == null || filename.trim().equals(""))
        filename = "unknown";
    else
        params.put(UserServlet.UPLOAD_NAME, filename);
    params.put(UserServlet.UPLOAD_TYPE, contentType);
    ZimbraLog.mailbox.info("UserServlet received file %s - %d request bytes", filename, req.getContentLength());
    return is;
}
Also used : ContentType(com.zimbra.common.mime.ContentType) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) ServiceException(com.zimbra.common.service.ServiceException) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ContentDisposition(com.zimbra.common.mime.ContentDisposition) FileItemStream(org.apache.commons.fileupload.FileItemStream) FileItemIterator(org.apache.commons.fileupload.FileItemIterator)

Example 23 with FileItemIterator

use of org.apache.commons.fileupload.FileItemIterator in project jeeshop by remibantos.

the class Medias method upload.

@POST
@Consumes("multipart/form-data")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ADMIN)
@Path("/{type}/{id}/{locale}/upload")
public void upload(@Context HttpServletRequest request, @NotNull @PathParam("type") String itemType, @NotNull @PathParam("id") Long itemId, @NotNull @PathParam("locale") String locale) {
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            java.nio.file.Path itemBasePath = getBasePath().resolve(itemType).resolve(itemId.toString()).resolve(locale);
            if (!Files.exists(itemBasePath))
                Files.createDirectories(itemBasePath);
            java.nio.file.Path filePath = itemBasePath.resolve(item.getName());
            Files.copy(item.openStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            LOG.info("File written to " + filePath);
        }
    } catch (IOException | FileUploadException e) {
        LOG.error("Could not handle upload of file with type: " + itemType + " and id: " + itemId, e);
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) WebApplicationException(org.rembx.jeeshop.rest.WebApplicationException) FileItemStream(org.apache.commons.fileupload.FileItemStream) IOException(java.io.IOException) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException) RolesAllowed(javax.annotation.security.RolesAllowed)

Example 24 with FileItemIterator

use of org.apache.commons.fileupload.FileItemIterator in project alfresco-remote-api by Alfresco.

the class PostSnapshotCommandProcessor method process.

/* (non-Javadoc)
     * @see org.alfresco.repo.web.scripts.transfer.CommandProcessor#process(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.WebScriptResponse)
     */
public int process(WebScriptRequest req, WebScriptResponse resp) {
    int result = Status.STATUS_OK;
    // Unwrap to a WebScriptServletRequest if we have one
    WebScriptServletRequest webScriptServletRequest = null;
    WebScriptRequest current = req;
    do {
        if (current instanceof WebScriptServletRequest) {
            webScriptServletRequest = (WebScriptServletRequest) current;
            current = null;
        } else if (current instanceof WrappingWebScriptRequest) {
            current = ((WrappingWebScriptRequest) req).getNext();
        } else {
            current = null;
        }
    } while (current != null);
    if (webScriptServletRequest == null) {
        logger.debug("bad request, not assignable from");
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }
    // We can't use the WebScriptRequest version of getParameter, since that may cause the content stream
    // to be parsed. Get hold of the raw HttpServletRequest and work with that.
    HttpServletRequest servletRequest = webScriptServletRequest.getHttpServletRequest();
    // Read the transfer id from the request
    String transferId = servletRequest.getParameter("transferId");
    if ((transferId == null) || !ServletFileUpload.isMultipartContent(servletRequest)) {
        logger.debug("bad request, not multipart");
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }
    try {
        logger.debug("about to upload manifest file");
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(servletRequest);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField() && TransferCommons.PART_NAME_MANIFEST.equals(item.getFieldName())) {
                logger.debug("got manifest file");
                receiver.saveSnapshot(transferId, item.openStream());
            }
        }
        logger.debug("success");
        resp.setStatus(Status.STATUS_OK);
        OutputStream out = resp.getOutputStream();
        resp.setContentType("text/xml");
        resp.setContentEncoding("utf-8");
        receiver.generateRequsite(transferId, out);
        out.close();
    } catch (Exception ex) {
        logger.debug("exception caught", ex);
        if (transferId != null) {
            logger.debug("ending transfer", ex);
            receiver.end(transferId);
        }
        if (ex instanceof TransferException) {
            throw (TransferException) ex;
        }
        throw new TransferException(MSG_CAUGHT_UNEXPECTED_EXCEPTION, ex);
    }
    return result;
}
Also used : WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) TransferException(org.alfresco.service.cmr.transfer.TransferException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) OutputStream(java.io.OutputStream) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) TransferException(org.alfresco.service.cmr.transfer.TransferException)

Example 25 with FileItemIterator

use of org.apache.commons.fileupload.FileItemIterator in project alfresco-remote-api by Alfresco.

the class PostContentCommandProcessor method process.

/*
     * (non-Javadoc)
     * 
     * @see org.alfresco.repo.web.scripts.transfer.CommandProcessor#process(org.alfresco.web.scripts.WebScriptRequest,
     * org.alfresco.web.scripts.WebScriptResponse)
     */
public int process(WebScriptRequest req, WebScriptResponse resp) {
    logger.debug("post content start");
    // Unwrap to a WebScriptServletRequest if we have one
    WebScriptServletRequest webScriptServletRequest = null;
    WebScriptRequest current = req;
    do {
        if (current instanceof WebScriptServletRequest) {
            webScriptServletRequest = (WebScriptServletRequest) current;
            current = null;
        } else if (current instanceof WrappingWebScriptRequest) {
            current = ((WrappingWebScriptRequest) req).getNext();
        } else {
            current = null;
        }
    } while (current != null);
    if (webScriptServletRequest == null) {
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }
    HttpServletRequest servletRequest = webScriptServletRequest.getHttpServletRequest();
    // Read the transfer id from the request
    String transferId = servletRequest.getParameter("transferId");
    if ((transferId == null) || !ServletFileUpload.isMultipartContent(servletRequest)) {
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(servletRequest);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (!item.isFormField()) {
                logger.debug("got content Mime Part : " + name);
                receiver.saveContent(transferId, item.getName(), item.openStream());
            }
        }
        // WebScriptServletRequest alfRequest = (WebScriptServletRequest)req;
        // String[] names = alfRequest.getParameterNames();
        // for(String name : names)
        // {
        // FormField item = alfRequest.getFileField(name);
        // 
        // if(item != null)
        // {
        // logger.debug("got content Mime Part : " + name);
        // receiver.saveContent(transferId, item.getName(), item.getInputStream());
        // }
        // else
        // {
        // //TODO - should this be an exception?
        // logger.debug("Unable to get content for Mime Part : " + name);
        // }
        // }
        logger.debug("success");
        resp.setStatus(Status.STATUS_OK);
    } catch (Exception ex) {
        logger.debug("exception caught", ex);
        if (transferId != null) {
            logger.debug("ending transfer", ex);
            receiver.end(transferId);
        }
        if (ex instanceof TransferException) {
            throw (TransferException) ex;
        }
        throw new TransferException(MSG_CAUGHT_UNEXPECTED_EXCEPTION, ex);
    }
    resp.setStatus(Status.STATUS_OK);
    return Status.STATUS_OK;
}
Also used : WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) TransferException(org.alfresco.service.cmr.transfer.TransferException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) TransferException(org.alfresco.service.cmr.transfer.TransferException)

Aggregations

FileItemIterator (org.apache.commons.fileupload.FileItemIterator)47 FileItemStream (org.apache.commons.fileupload.FileItemStream)45 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)37 IOException (java.io.IOException)29 InputStream (java.io.InputStream)21 FileUploadException (org.apache.commons.fileupload.FileUploadException)20 NotFoundException (org.opencastproject.util.NotFoundException)7 HashMap (java.util.HashMap)6 HttpServletRequest (javax.servlet.http.HttpServletRequest)6 IngestException (org.opencastproject.ingest.api.IngestException)6 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 GZIPInputStream (java.util.zip.GZIPInputStream)5 POST (javax.ws.rs.POST)5 Path (javax.ws.rs.Path)5 Produces (javax.ws.rs.Produces)5 WebApplicationException (javax.ws.rs.WebApplicationException)5 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)5 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)5 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)5