Search in sources :

Example 16 with ServletFileUpload

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

the class FileUploadServlet method saveUpload.

public static Upload saveUpload(InputStream is, String filename, String contentType, String accountId, long limit) throws ServiceException, IOException {
    FileItem fi = null;
    boolean success = false;
    try {
        // store the fetched file as a normal upload
        ServletFileUpload upload = getUploader(limit);
        long sizeMax = upload.getSizeMax();
        fi = upload.getFileItemFactory().createItem("upload", contentType, false, filename);
        // sizeMax=-1 means "no limit"
        long size = ByteUtil.copy(is, true, fi.getOutputStream(), true, sizeMax < 0 ? sizeMax : sizeMax + 1);
        if (upload.getSizeMax() >= 0 && size > upload.getSizeMax()) {
            mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes");
            throw MailServiceException.UPLOAD_TOO_LARGE(filename, "upload too large");
        }
        Upload up = new Upload(accountId, fi);
        mLog.info("saveUpload(): received %s", up);
        synchronized (mPending) {
            mPending.put(up.uuid, up);
        }
        success = true;
        return up;
    } finally {
        if (!success && fi != null) {
            mLog.debug("saveUpload(): unsuccessful attempt.  Deleting %s", fi);
            fi.delete();
        }
    }
}
Also used : DefaultFileItem(org.apache.commons.fileupload.DefaultFileItem) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload)

Example 17 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload 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 18 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload in project jena by apache.

the class SPARQL_Upload method uploadWorker.

/** Process an HTTP file upload of RDF with additiona name field for the graph name.
     *  We can't stream straight into a dataset because the graph name can be after the data.
     *  @return graph name and count
     */
// ?? Combine with Upload.fileUploadWorker
// Difference is the handling of names for graphs.
private static UploadDetails uploadWorker(HttpAction action, String base) {
    DatasetGraph dsgTmp = DatasetGraphFactory.create();
    ServletFileUpload upload = new ServletFileUpload();
    String graphName = null;
    boolean isQuads = false;
    long count = -1;
    String name = null;
    ContentType ct = null;
    Lang lang = null;
    try {
        FileItemIterator iter = upload.getItemIterator(action.request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String fieldName = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                // Graph name.
                String value = Streams.asString(stream, "UTF-8");
                if (fieldName.equals(HttpNames.paramGraph)) {
                    graphName = value;
                    if (graphName != null && !graphName.equals("") && !graphName.equals(HttpNames.valueDefault)) {
                        IRI iri = IRIResolver.parseIRI(value);
                        if (iri.hasViolation(false))
                            ServletOps.errorBadRequest("Bad IRI: " + graphName);
                        if (iri.getScheme() == null)
                            ServletOps.errorBadRequest("Bad IRI: no IRI scheme name: " + graphName);
                        if (iri.getScheme().equalsIgnoreCase("http") || iri.getScheme().equalsIgnoreCase("https")) {
                            // Redundant??
                            if (iri.getRawHost() == null)
                                ServletOps.errorBadRequest("Bad IRI: no host name: " + graphName);
                            if (iri.getRawPath() == null || iri.getRawPath().length() == 0)
                                ServletOps.errorBadRequest("Bad IRI: no path: " + graphName);
                            if (iri.getRawPath().charAt(0) != '/')
                                ServletOps.errorBadRequest("Bad IRI: Path does not start '/': " + graphName);
                        }
                    }
                } else if (fieldName.equals(HttpNames.paramDefaultGraphURI))
                    graphName = null;
                else
                    // Add file type?
                    action.log.info(format("[%d] Upload: Field=%s ignored", action.id, fieldName));
            } else {
                // Process the input stream
                name = item.getName();
                if (name == null || name.equals("") || name.equals("UNSET FILE NAME"))
                    ServletOps.errorBadRequest("No name for content - can't determine RDF syntax");
                String contentTypeHeader = item.getContentType();
                ct = ContentType.create(contentTypeHeader);
                lang = RDFLanguages.contentTypeToLang(ct.getContentType());
                if (lang == null) {
                    lang = RDFLanguages.filenameToLang(name);
                    // present we wrap the stream accordingly
                    if (name.endsWith(".gz"))
                        stream = new GZIPInputStream(stream);
                }
                if (lang == null)
                    // Desperate.
                    lang = RDFLanguages.RDFXML;
                isQuads = RDFLanguages.isQuads(lang);
                action.log.info(format("[%d] Upload: Filename: %s, Content-Type=%s, Charset=%s => %s", action.id, name, ct.getContentType(), ct.getCharset(), lang.getName()));
                StreamRDF x = StreamRDFLib.dataset(dsgTmp);
                StreamRDFCounting dest = StreamRDFLib.count(x);
                ActionSPARQL.parse(action, dest, stream, lang, base);
                count = dest.count();
            }
        }
        if (graphName == null || graphName.equals(""))
            graphName = HttpNames.valueDefault;
        if (isQuads)
            graphName = null;
        return new UploadDetails(graphName, dsgTmp, count);
    } catch (ActionErrorException ex) {
        throw ex;
    } catch (Exception ex) {
        ServletOps.errorOccurred(ex);
        return null;
    }
}
Also used : IRI(org.apache.jena.iri.IRI) ContentType(org.apache.jena.atlas.web.ContentType) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) Lang(org.apache.jena.riot.Lang) DatasetGraph(org.apache.jena.sparql.core.DatasetGraph) GZIPInputStream(java.util.zip.GZIPInputStream) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) StreamRDF(org.apache.jena.riot.system.StreamRDF) StreamRDFCounting(org.apache.jena.riot.lang.StreamRDFCounting) FileItemIterator(org.apache.commons.fileupload.FileItemIterator)

Example 19 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload in project sling by apache.

the class InstallServlet method installBasedOnUploadedJar.

private void installBasedOnUploadedJar(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    InstallationResult result = null;
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // try to hold even largish bundles in memory to potentially improve performance
        factory.setSizeThreshold(UPLOAD_IN_MEMORY_SIZE_THRESHOLD);
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileItemFactory(factory);
        @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req);
        if (items.size() != 1) {
            logAndWriteError("Found " + items.size() + " items to process, but only updating 1 bundle is supported", resp);
            return;
        }
        FileItem item = items.get(0);
        JarInputStream jar = null;
        InputStream rawInput = null;
        try {
            jar = new JarInputStream(item.getInputStream());
            Manifest manifest = jar.getManifest();
            if (manifest == null) {
                logAndWriteError("Uploaded jar file does not contain a manifest", resp);
                return;
            }
            final String symbolicName = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
            if (symbolicName == null) {
                logAndWriteError("Manifest does not have a " + Constants.BUNDLE_SYMBOLICNAME, resp);
                return;
            }
            final String version = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION);
            // the JarInputStream is used only for validation, we need a fresh input stream for updating
            rawInput = item.getInputStream();
            Bundle found = getBundle(symbolicName);
            try {
                installOrUpdateBundle(found, rawInput, "inputstream:" + symbolicName + "-" + version + ".jar");
                result = new InstallationResult(true, null);
                resp.setStatus(200);
                result.render(resp.getWriter());
                return;
            } catch (BundleException e) {
                logAndWriteError("Unable to install/update bundle " + symbolicName, e, resp);
                return;
            }
        } finally {
            IOUtils.closeQuietly(jar);
            IOUtils.closeQuietly(rawInput);
        }
    } catch (FileUploadException e) {
        logAndWriteError("Failed parsing uploaded bundle", e, resp);
        return;
    }
}
Also used : JarInputStream(java.util.jar.JarInputStream) JarInputStream(java.util.jar.JarInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Bundle(org.osgi.framework.Bundle) Manifest(java.util.jar.Manifest) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) BundleException(org.osgi.framework.BundleException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 20 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload in project tomee by apache.

the class CommonsFileUploadPartFactory method read.

public static Collection<Part> read(final HttpRequestImpl request) {
    // mainly for testing
    // Create a new file upload handler
    final DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(REPO);
    final ServletFileUpload upload = new ServletFileUpload();
    upload.setFileItemFactory(factory);
    final List<Part> parts = new ArrayList<>();
    try {
        final List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
        final String enc = request.getCharacterEncoding();
        for (final FileItem item : items) {
            final CommonsFileUploadPart part = new CommonsFileUploadPart(item, null);
            parts.add(part);
            if (part.getSubmittedFileName() == null) {
                String name = part.getName();
                String value = null;
                try {
                    String encoding = request.getCharacterEncoding();
                    if (encoding == null) {
                        if (enc == null) {
                            encoding = "UTF-8";
                        } else {
                            encoding = enc;
                        }
                    }
                    value = part.getString(encoding);
                } catch (final UnsupportedEncodingException uee) {
                    try {
                        value = part.getString("UTF-8");
                    } catch (final UnsupportedEncodingException e) {
                    // not possible
                    }
                }
                request.addInternalParameter(name, value);
            }
        }
        return parts;
    } catch (final FileUploadException e) {
        throw new IllegalStateException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Part(javax.servlet.http.Part) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)43 FileItem (org.apache.commons.fileupload.FileItem)29 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)29 FileUploadException (org.apache.commons.fileupload.FileUploadException)20 File (java.io.File)17 IOException (java.io.IOException)13 ArrayList (java.util.ArrayList)13 InputStream (java.io.InputStream)7 HashMap (java.util.HashMap)7 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)7 FileItemStream (org.apache.commons.fileupload.FileItemStream)7 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)6 ServletException (javax.servlet.ServletException)5 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 List (java.util.List)4 Locale (java.util.Locale)4 GZIPInputStream (java.util.zip.GZIPInputStream)4 OpenClinicaSystemException (org.akaza.openclinica.exception.OpenClinicaSystemException)4 DataBinder (org.springframework.validation.DataBinder)4 Errors (org.springframework.validation.Errors)4