Example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax.

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.server.FlatJobServlet.java

private void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html");

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);/*w  w w .  j  a va  2s.c  om*/
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(1000000);
    String callbackName = null;

    try {
        List<?> fileItems = upload.parseRequest(request);
        Iterator<?> i = fileItems.iterator();

        String commandFile = null;
        String name = null;
        String selectionScript = null;
        String selectionScriptExtension = null;
        String sessionId = null;

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();

            if (fi.isFormField()) {
                if (fi.getFieldName().equals("jobName")) {
                    name = fi.getString();
                    if (name.trim().length() == 0)
                        name = null;
                } else if (fi.getFieldName().equals("sessionId")) {
                    sessionId = fi.getString();
                } else if (fi.getFieldName().equals("flatCallback")) {
                    callbackName = fi.getString();
                }
            } else {
                if (fi.getFieldName().equals("commandFile")) {
                    commandFile = IOUtils.toString(fi.getInputStream());
                    if (commandFile.trim().length() == 0)
                        commandFile = null;
                } else if (fi.getFieldName().equals("selectionScript")) {
                    if (fi.getName().indexOf('.') == -1) {
                        selectionScriptExtension = "js";
                    } else {
                        selectionScriptExtension = fi.getName().substring(fi.getName().lastIndexOf('.') + 1);
                    }
                    selectionScript = IOUtils.toString(fi.getInputStream());
                    if (selectionScript.trim().length() == 0)
                        selectionScript = null;
                }
            }
        }

        String ret;
        if (commandFile == null) {
            ret = "{ \"errorMessage\" : \"Missing parameter: command file\" }";
        } else if (sessionId == null) {
            ret = "{ \"errorMessage\" : \"Missing parameter: sessionId\" }";
        } else if (name == null) {
            ret = "{ \"errorMessage\" : \"Missing parameter: job name\" }";
        } else {
            ret = ((SchedulerServiceImpl) SchedulerServiceImpl.get()).submitFlatJob(sessionId, commandFile,
                    name, selectionScript, selectionScriptExtension);
        }
        /* writing the callback name in as an inlined script,
         * so that the browser, upon receiving it, will evaluate
         * the JS and call the function */
        response.getWriter().write("<script type='text/javascript'>");
        response.getWriter().write("window.top." + callbackName + "(" + ret + ");");
        response.getWriter().write("</script>");

    } catch (RestServerException e) {
        try {
            response.getWriter().write("<script type='text/javascript'>");
            response.getWriter().write("window.top." + callbackName + " (" + e.getMessage() + ")");
            response.getWriter().write("</script>");
        } catch (Throwable e1) {
            LOGGER.warn("Failed to write script back to client", e);
        }
    } catch (Exception e) {
        try {
            String tw = "<script type='text/javascript'>";
            tw += "window.top." + callbackName + "({ \"errorMessage\" : \"" + e.getMessage() + "\" });";
            tw += "</script>";
            response.getWriter().write(tw);
        } catch (IOException e1) {
            LOGGER.warn("Failed to write script back to client", e);
        }
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.server.UploadServlet.java

private void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html");
    File job = null;/* w ww  .jav  a  2 s. co m*/

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1000000);

        List<?> fileItems = upload.parseRequest(request);
        Iterator<?> i = fileItems.iterator();

        String sessionId = null;
        boolean edit = false;

        /*
         * * edit=0, simply submit the job descriptor * edit=1, open the descriptor and return
         * it as a string
         */

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();

            if (fi.isFormField()) {
                if (fi.getFieldName().equals("sessionId")) {
                    sessionId = fi.getString();
                } else if (fi.getFieldName().equals("edit")) {
                    if (fi.getString().equals("1")) {
                        edit = true;
                    } else {
                        edit = false;
                    }
                }
            } else {
                job = File.createTempFile("job_upload", ".xml");
                fi.write(job);
            }

            fi.delete();
        }

        boolean isJar = isJarFile(job);

        if (!isJar) {
            // this _loosely_ checks that the file we got is an XML file 
            try {
                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                Document doc = docBuilder.parse(job);

                if (edit) {
                    // don't go on with edition if there are no variables
                    if (doc.getElementsByTagName("variables").getLength() < 1
                            || doc.getElementsByTagName("variable").getLength() < 1) {
                        response.getWriter().write("This job descriptor contains no variable definition.<br>"
                                + "Uncheck <strong>Edit variables</strong> or submit another descriptor.");
                        return;
                    }
                }
            } catch (Throwable e) {
                response.getWriter().write("Job descriptor must be valid XML<br>" + e.getMessage());
                return;
            }
        }

        if (edit && !isJar) {
            String ret = IOUtils.toString(new FileInputStream(job), "UTF-8");
            response.getWriter().write("{ \"jobEdit\" : \"" + Base64Utils.toBase64(ret.getBytes()) + "\" }");
        } else {
            String responseS = ((SchedulerServiceImpl) Service.get()).submitXMLFile(sessionId, job);
            if (responseS == null || responseS.length() == 0) {
                response.getWriter().write("Job submission returned without a value!");
            } else {
                response.getWriter().write(responseS);
            }
        }

    } catch (Exception e) {
        try {
            String msg = e.getMessage().replace("<", "&lt;").replace(">", "&gt;");
            response.getWriter().write(msg);
        } catch (IOException ignored) {
        }
    } finally {
        if (job != null)
            job.delete();
    }

}

From source file:org.owasp.esapi.reference.DefaultHTTPUtilities.java

/**
 * {@inheritDoc}//from www.ja  va2 s .co  m
 */
public List<File> getFileUploads(HttpServletRequest request, File finalDir, List allowedExtensions)
        throws ValidationException {
    File tempDir = ESAPI.securityConfiguration().getUploadTempDirectory();
    if (!tempDir.exists()) {
        if (!tempDir.mkdirs())
            throw new ValidationUploadException("Upload failed",
                    "Could not create temp directory: " + tempDir.getAbsolutePath());
    }

    if (finalDir != null) {
        if (!finalDir.exists()) {
            if (!finalDir.mkdirs())
                throw new ValidationUploadException("Upload failed",
                        "Could not create final upload directory: " + finalDir.getAbsolutePath());
        }
    } else {
        if (!ESAPI.securityConfiguration().getUploadDirectory().exists()) {
            if (!ESAPI.securityConfiguration().getUploadDirectory().mkdirs())
                throw new ValidationUploadException("Upload failed", "Could not create final upload directory: "
                        + ESAPI.securityConfiguration().getUploadDirectory().getAbsolutePath());
        }
        finalDir = ESAPI.securityConfiguration().getUploadDirectory();
    }

    List<File> newFiles = new ArrayList<File>();
    try {
        final HttpSession session = request.getSession(false);
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new ValidationUploadException("Upload failed", "Not a multipart request");
        }

        // this factory will store ALL files in the temp directory,
        // regardless of size
        DiskFileItemFactory factory = new DiskFileItemFactory(0, tempDir);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxBytes);

        // Create a progress listener
        ProgressListener progressListener = new ProgressListener() {
            private long megaBytes = -1;
            private long progress = 0;

            public void update(long pBytesRead, long pContentLength, int pItems) {
                if (pItems == 0)
                    return;
                long mBytes = pBytesRead / 1000000;
                if (megaBytes == mBytes)
                    return;
                megaBytes = mBytes;
                progress = (long) (((double) pBytesRead / (double) pContentLength) * 100);
                if (session != null) {
                    session.setAttribute("progress", Long.toString(progress));
                }
                // logger.logSuccess(Logger.SECURITY, "   Item " + pItems + " (" + progress + "% of " + pContentLength + " bytes]");
            }
        };
        upload.setProgressListener(progressListener);

        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField() && item.getName() != null && !(item.getName().equals(""))) {
                String[] fparts = item.getName().split("[\\/\\\\]");
                String filename = fparts[fparts.length - 1];

                if (!ESAPI.validator().isValidFileName("upload", filename, allowedExtensions, false)) {
                    throw new ValidationUploadException(
                            "Upload only simple filenames with the following extensions " + allowedExtensions,
                            "Upload failed isValidFileName check");
                }

                logger.info(Logger.SECURITY_SUCCESS, "File upload requested: " + filename);
                File f = new File(finalDir, filename);
                if (f.exists()) {
                    String[] parts = filename.split("\\/.");
                    String extension = "";
                    if (parts.length > 1) {
                        extension = parts[parts.length - 1];
                    }
                    String filenm = filename.substring(0, filename.length() - extension.length());
                    f = File.createTempFile(filenm, "." + extension, finalDir);
                }
                item.write(f);
                newFiles.add(f);
                // delete temporary file
                item.delete();
                logger.fatal(Logger.SECURITY_SUCCESS, "File successfully uploaded: " + f);
                if (session != null) {
                    session.setAttribute("progress", Long.toString(0));
                }
            }
        }
    } catch (Exception e) {
        if (e instanceof ValidationUploadException) {
            throw (ValidationException) e;
        }
        throw new ValidationUploadException("Upload failure", "Problem during upload:" + e.getMessage(), e);
    }
    return Collections.synchronizedList(newFiles);
}

From source file:org.pentaho.platform.web.servlet.RepositoryFilePublisher.java

protected List<FileItem> getFileItems(final HttpServletRequest request) throws FileUploadException {
    ServletFileUpload fu = new ServletFileUpload(new DiskFileItemFactory());
    // If file size exceeds, a FileUploadException will be thrown
    // fu.setSizeMax(10000000);

    long sizeLimit = DEFAULT_MAX_FILE_SIZE;
    String maxFileSizeString = PentahoSystem.getSystemSetting("file-upload-defaults/max-file-limit", //$NON-NLS-1$
            String.valueOf(DEFAULT_MAX_FILE_SIZE));
    try {//from  w ww. j  a va2s .  c o m
        sizeLimit = Long.parseLong(maxFileSizeString);
    } catch (Exception mostlyIgnored) {
        logger.error(Messages.getErrorString("RepositoryFilePublisher.ERROR_0001_INVALID_MAX_FILE_SIZE")); //$NON-NLS-1$
    }
    fu.setSizeMax(sizeLimit);
    return fu.parseRequest(request);
}

From source file:org.sakaiproject.myshowcase.servlet.MyShowcaseFileUploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*  w  w w. ja  v a  2s  .c om*/

        List fileItemsList = null;

        String input1 = request.getParameter("input1");
        String input2 = request.getParameter("input2");
        String input4 = request.getParameter("input4");

        if (ServletFileUpload.isMultipartContent(request)) {

            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());

            fileItemsList = servletFileUpload.parseRequest(request);

            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            String homeDirId = MyShowcaseConfigValues.getInstance().getFileUploadHomeDir();

            File repositoryPath = null;

            String homeDir = "";

            if (homeDirId.equals("ownerName")) {

                homeDir = getOwnerName(fileItemsList);

            } else if (homeDirId.equals("ownerId")) {

                homeDir = getOwnerId(fileItemsList);

            }

            repositoryPath = new File(getRepositoryPath(homeDir));

            diskFileItemFactory.setRepository(repositoryPath);

            servletFileUpload.setSizeMax(81920); /* the unit is bytes */

            Iterator it = fileItemsList.iterator();

            while (it.hasNext()) {

                FileItem fileItem = (FileItem) it.next();

                if (fileItem.isFormField()) {

                } else {

                    String fileName = fileItem.getName();

                    fileName = getRepositoryPath(homeDir) + fileName;

                    File uploadedFile = new File(fileName);

                    fileItem.write(uploadedFile);

                    isValidFileType(fileName);

                }
            }

        } else {

            System.out.println("Not Multipart Request");
        }

        IMyShowcaseService myshowcaseService = getMyShowcaseService();

        String ownerId = getOwnerId(fileItemsList);

        Owner owner = myshowcaseService.getOwnerById(new Long(ownerId));

        String aType = getType(fileItemsList);

        String aTitle = getTitle(fileItemsList);

        String aDescription = getDescription(fileItemsList);

        String aDataValue = getDataValue(fileItemsList);

        // Save Artefact
        Artefact artefact = new Artefact();

        ArtefactDetail artefactDetail = new ArtefactDetail();

        ArtefactType artefactType = myshowcaseService.getArtefactTypeByName(aType);

        artefact.setOwner(owner);

        artefact.setDescription(aDescription);

        artefact.setName(aTitle);

        artefact.setShortDesc(aTitle);

        artefact.setType(artefactType);

        artefactDetail.setFileName(aDataValue);

        artefactDetail.setFileType(getFileType(aDataValue));

        artefactDetail.setFilePath(getRepositoryPath(ownerId));

        artefactDetail.setDetail(aDataValue);

        artefact.setArtefactDetail(artefactDetail);

        myshowcaseService.saveArtefact(artefact);

    } catch (Exception e) {
        System.out.println(e.toString());
    }

    //        response.setContentType("application/json");
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();

    out.write("<html>");
    out.write("<head>");
    out.write("<title>File Upload</title>");
    out.write("</head>");
    out.write("<body>");
    out.write("File uploaded");
    out.write("<script type=\"text/javascript\">");
    out.write("parent.$.fancybox.close();");
    out.write("</script>");
    out.write("</body>");
    out.write("</html>");
    out.flush();
    out.close();

}

From source file:org.sakaiproject.myshowcase.tool.MyShowcaseSaveArtefactFileController.java

protected void upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*  ww w . j av  a 2s  .  c  o m*/

        if (ServletFileUpload.isMultipartContent(request)) {

            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());

            List fileItemsList = servletFileUpload.parseRequest(request);

            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            String homeDirId = MyShowcaseConfigValues.getInstance().getFileUploadHomeDir();

            File repositoryPath = null;

            String homeDir = "";

            if (homeDirId.equals("ownerName")) {

                //                homeDir = getOwnerName(fileItemsList) ;

            } else if (homeDirId.equals("ownerId")) {

                //                homeDir = getOwnerId(fileItemsList) ;

            }

            repositoryPath = new File(getRepositoryPath(homeDir));

            diskFileItemFactory.setRepository(repositoryPath);

            servletFileUpload.setSizeMax(81920); /* the unit is bytes */

            Iterator it = fileItemsList.iterator();

            while (it.hasNext()) {

                FileItem fileItem = (FileItem) it.next();

                if (fileItem.isFormField()) {

                } else {

                    String fileName = fileItem.getName();
                    System.out.println("++++ A file(1) = " + fileName);

                    fileName = getRepositoryPath(homeDir) + fileName;
                    System.out.println("++++ A file(2) = " + fileName);

                    File uploadedFile = new File(fileName);

                    fileItem.write(uploadedFile);
                    System.out.println("YES --- File (" + fileName + ") has been written.");

                    System.out.println("===========================");
                    //                  isValidFileType(fileName); 
                    System.out.println("===========================");
                }
            }

        } else {

            System.out.println("Not Multipart Request");
        }

    } catch (Exception e) {
        System.out.println(e.toString());
    }
}

From source file:org.sakaiproject.util.RequestFilter.java

/**
 * if the filter is configured to parse file uploads, AND the request is multipart (typically a file upload), then parse the
 * request./*  w w w.j a va 2 s . co  m*/
 *
 * @return If there is a file upload, and the filter handles it, return the wrapped request that has the results of the parsed
 *         file upload. Parses the files using Apache commons-fileuplaod. Exposes the results through a wrapped request. Files
 *         are available like: fileItem = (FileItem) request.getAttribute("myHtmlFileUploadId");
 */
protected HttpServletRequest handleFileUpload(HttpServletRequest req, HttpServletResponse resp,
        List<FileItem> tempFiles) throws ServletException, UnsupportedEncodingException {
    if (!m_uploadEnabled || !ServletFileUpload.isMultipartContent(req)
            || req.getAttribute(ATTR_UPLOADS_DONE) != null) {
        return req;
    }

    // mark that the uploads have been parsed, so they aren't parsed again on this request
    req.setAttribute(ATTR_UPLOADS_DONE, ATTR_UPLOADS_DONE);

    // Result - map that will be created of request parameters,
    // parsed parameters, and uploaded files
    Map map = new HashMap();

    // parse using commons-fileupload

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // set the factory parameters: the temp dir and the keep-in-memory-if-smaller threshold
    if (m_uploadTempDir != null)
        factory.setRepository(new File(m_uploadTempDir));
    if (m_uploadThreshold > 0)
        factory.setSizeThreshold(m_uploadThreshold);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // set the encoding
    String encoding = req.getCharacterEncoding();
    if (encoding != null && encoding.length() > 0)
        upload.setHeaderEncoding(encoding);

    // set the max upload size
    long uploadMax = -1;
    if (m_uploadMaxSize > 0)
        uploadMax = m_uploadMaxSize;

    // check for request-scoped override to upload.max (value in megs)
    String override = req.getParameter(CONFIG_UPLOAD_MAX);
    if (override != null) {
        try {
            // get the max in bytes
            uploadMax = Long.parseLong(override) * 1024L * 1024L;
        } catch (NumberFormatException e) {
            M_log.warn(CONFIG_UPLOAD_MAX + " set to non-numeric: " + override);
        }
    }

    // limit to the ceiling
    if (uploadMax > m_uploadCeiling) {
        /**
         * KNL-602 This is the expected behaviour of the request filter honouring the globaly configured
         * value -DH
         */
        M_log.debug("Upload size exceeds ceiling: " + ((uploadMax / 1024L) / 1024L) + " > "
                + ((m_uploadCeiling / 1024L) / 1024L) + " megs");

        uploadMax = m_uploadCeiling;
    }

    // to let commons-fileupload throw the exception on over-max, and also halt full processing of input fields
    if (!m_uploadContinue) {
        // TODO: when we switch to commons-fileupload 1.2
        // // either per file or overall request, as configured
        // if (m_uploadMaxPerFile)
        // {
        // upload.setFileSizeMax(uploadMax);
        // }
        // else
        // {
        // upload.setSizeMax(uploadMax);
        // }

        upload.setSizeMax(uploadMax);
    }

    try {
        // parse multipart encoded parameters
        boolean uploadOk = true;
        List list = upload.parseRequest(req);
        for (int i = 0; i < list.size(); i++) {
            FileItem item = (FileItem) list.get(i);

            if (item.isFormField()) {
                String str = item.getString(encoding);

                Object obj = map.get(item.getFieldName());
                if (obj == null) {
                    map.put(item.getFieldName(), new String[] { str });
                } else if (obj instanceof String[]) {
                    String[] old_vals = (String[]) obj;
                    String[] values = new String[old_vals.length + 1];
                    for (int i1 = 0; i1 < old_vals.length; i1++) {
                        values[i1] = old_vals[i1];
                    }
                    values[values.length - 1] = str;
                    map.put(item.getFieldName(), values);
                } else if (obj instanceof String) {
                    String[] values = new String[2];
                    values[0] = (String) obj;
                    values[1] = str;
                    map.put(item.getFieldName(), values);
                }
            } else {
                // collect it for delete at the end of the request
                tempFiles.add(item);

                // check the max, unless we are letting commons-fileupload throw exception on max exceeded
                // Note: the continue option assumes the max is per-file, not overall.
                if (m_uploadContinue && (item.getSize() > uploadMax)) {
                    uploadOk = false;

                    M_log.info("Upload size limit exceeded: " + ((uploadMax / 1024L) / 1024L));

                    req.setAttribute("upload.status", "size_limit_exceeded");
                    // TODO: for 1.2 commons-fileupload, switch this to a FileSizeLimitExceededException
                    req.setAttribute("upload.exception",
                            new FileUploadBase.SizeLimitExceededException("", item.getSize(), uploadMax));
                    req.setAttribute("upload.limit", Long.valueOf((uploadMax / 1024L) / 1024L));
                } else {
                    req.setAttribute(item.getFieldName(), item);
                }
            }
        }

        // unless we had an upload file that exceeded max, set the upload status to "ok"
        if (uploadOk) {
            req.setAttribute("upload.status", "ok");
        }
    } catch (FileUploadBase.SizeLimitExceededException ex) {
        M_log.info("Upload size limit exceeded: " + ((upload.getSizeMax() / 1024L) / 1024L));

        // DON'T throw an exception, instead note the exception
        // so that the tool down-the-line can handle the problem
        req.setAttribute("upload.status", "size_limit_exceeded");
        req.setAttribute("upload.exception", ex);
        req.setAttribute("upload.limit", Long.valueOf((upload.getSizeMax() / 1024L) / 1024L));
    }
    // TODO: put in for commons-fileupload 1.2
    // catch (FileUploadBase.FileSizeLimitExceededException ex)
    // {
    // M_log.info("Upload size limit exceeded: " + ((upload.getFileSizeMax() / 1024L) / 1024L));
    //
    // // DON'T throw an exception, instead note the exception
    // // so that the tool down-the-line can handle the problem
    // req.setAttribute("upload.status", "size_limit_exceeded");
    // req.setAttribute("upload.exception", ex);
    // req.setAttribute("upload.limit", new Long((upload.getFileSizeMax() / 1024L) / 1024L));
    // }
    catch (FileUploadException ex) {
        M_log.info("Unexpected exception in upload parsing", ex);
        req.setAttribute("upload.status", "exception");
        req.setAttribute("upload.exception", ex);
    }

    // add any parameters that were in the URL - make sure to get multiples
    for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        String[] values = req.getParameterValues(name);
        map.put(name, values);
    }

    // return a wrapped response that exposes the parsed parameters and files
    return new WrappedRequestFileUpload(req, map);
}

From source file:org.sc.probro.servlets.IndexCreatorServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//w  ww  . ja v  a  2 s.  c  om
        OBOParser parser = null;
        Map<String, String[]> params = decodedParams(request);

        UserCredentials creds = new UserCredentials();

        String ontologyName = null;

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            throw new BrokerException(HttpServletResponse.SC_BAD_REQUEST, "No multipart form data.");
        }

        try {
            File repository = new File(System.getProperty("java.io.tmpdir"));

            // Create a factory for disk-based file items
            //DiskFileItemFactory factory = new DiskFileItemFactory();
            DiskFileItemFactory factory = newDiskFileItemFactory(getServletContext(), repository);

            // Set factory constraints
            factory.setSizeThreshold(10 * MB);
            //factory.setRepository(yourTempDirectory);

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(50 * MB);

            // Parse the request
            List<FileItem> items = upload.parseRequest(request);

            for (FileItem item : items) {
                if (item.isFormField()) {
                    String formName = item.getFieldName();
                    String formValue = item.getString();
                    Log.info(String.format("%s=%s", formName, formValue));

                    if (formName.equals("ontology_name")) {
                        ontologyName = formValue;
                    }

                } else {
                    String formName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();

                    if (formName.equals("ontology_file")) {

                        Log.info(String.format("fileName=%s, contentType=%s, size=%d", fileName, contentType,
                                sizeInBytes));

                        if (fileName.length() > 0) {

                            InputStream uploadedStream = item.getInputStream();
                            BufferedReader reader = new BufferedReader(new InputStreamReader(uploadedStream));

                            parser = new OBOParser();
                            parser.parse(reader);

                            reader.close();
                        }

                    } else {
                        Log.warn(String.format("unknown file: %s", formName));
                    }

                }
            }
        } catch (IOException e) {
            throw new BrokerException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        } catch (FileUploadException e) {
            throw new BrokerException(e);
        }

        if (ontologyName == null) {
            throw new BadRequestException("No ontology_name field given.");
        }

        OBOOntology ontology = null;

        try {
            if (parser != null) {
                Log.info(String.format("Retrieving OBO ontology from file."));
                // file was uploaded
                ontology = parser.getOntology();
            } else {
                // try to get it from teh sparql endpoint
                Log.info(String.format("No OBO file uploaded, reading from Sparql endpoint instead."));

                OBOBuilder builder = new OBOBuilder(oboSparql);
                ontology = builder.buildOntology(ontologyName);
            }
        } catch (IOException e) {
            throw new BrokerException(e);
        }

        Broker broker = getBroker();
        try {
            Ontology ont = broker.createOntology(creds, ontologyName, ontology);

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("text");
            response.getWriter().print(ont.id);

        } finally {
            broker.close();
        }

    } catch (BrokerException e) {
        handleException(response, e);
        return;
    }
}

From source file:org.seasar.struts.upload.S2MultipartRequestHandler.java

@SuppressWarnings("unchecked")
@Override//from  w ww.ja v  a 2  s . c om
public void handleRequest(HttpServletRequest request) throws ServletException {
    ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);
    ServletFileUpload upload = new ServletFileUpload(
            new DiskFileItemFactory((int) getSizeThreshold(ac), new File(getRepositoryPath(ac))));
    upload.setHeaderEncoding(request.getCharacterEncoding());
    upload.setSizeMax(getSizeMax(ac));
    elementsText = new Hashtable();
    elementsFile = new Hashtable();
    elementsAll = new Hashtable();
    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (SizeLimitExceededException e) {
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
        request.setAttribute(SIZE_EXCEPTION_KEY, e);
        try {
            InputStream is = request.getInputStream();
            try {
                byte[] buf = new byte[1024];
                @SuppressWarnings("unused")
                int len = 0;
                while ((len = is.read(buf)) != -1) {
                }
            } catch (Exception ignore) {
            } finally {
                try {
                    is.close();
                } catch (Exception ignore) {
                }
            }
        } catch (Exception ignore) {
        }
        return;
    } catch (FileUploadException e) {
        log.error("Failed to parse multipart request", e);
        throw new ServletException(e);
    }

    // Partition the items into form fields and files.
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            addTextParameter(request, item);
        } else {
            addFileParameter(item);
        }
    }
}

From source file:org.signserver.web.GenericProcessServlet.java

/**
 * Handles http post.//  www  .j  a va2s  .  com
 *
 * @param req servlet request
 * @param res servlet response
 *
 * @throws IOException input/output error
 * @throws ServletException error
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    LOG.debug(">doPost()");

    int workerId = 1;
    byte[] data = null;
    String fileName = null;
    String pdfPassword = null;
    boolean workerRequest = false;

    if (LOG.isDebugEnabled()) {
        LOG.debug("Received a request with length: " + req.getContentLength());
    }

    final String workerNameOverride = (String) req.getAttribute(WORKERNAME_PROPERTY_OVERRIDE);

    if (workerNameOverride != null) {
        workerId = getWorkerSession().getWorkerId(workerNameOverride);
        workerRequest = true;
    }

    final long maxUploadSize = getMaxUploadSize();

    ProcessType processType = ProcessType.signDocument;
    final MetaDataHolder metadataHolder = new MetaDataHolder();

    if (ServletFileUpload.isMultipartContent(req)) {
        final DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(Integer.MAX_VALUE); // Don't write to disk

        final ServletFileUpload upload = new ServletFileUpload(factory);

        // Limit the maximum size of input
        upload.setSizeMax(maxUploadSize);

        try {
            final List items = upload.parseRequest(req);
            final Iterator iter = items.iterator();
            FileItem fileItem = null;
            String encoding = null;
            while (iter.hasNext()) {
                final Object o = iter.next();
                if (o instanceof FileItem) {
                    final FileItem item = (FileItem) o;

                    if (item.isFormField()) {
                        if (!workerRequest) {
                            if (WORKERNAME_PROPERTY_NAME.equals(item.getFieldName())) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("Found a signerName in the request: " + item.getString());
                                }
                                workerId = getWorkerSession().getWorkerId(item.getString());
                            } else if (WORKERID_PROPERTY_NAME.equals(item.getFieldName())) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("Found a signerId in the request: " + item.getString());
                                }
                                try {
                                    workerId = Integer.parseInt(item.getString());
                                } catch (NumberFormatException ignored) {
                                }
                            }
                        }

                        final String itemFieldName = item.getFieldName();

                        if (PDFPASSWORD_PROPERTY_NAME.equals(itemFieldName)) {
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Found a pdfPassword in the request.");
                            }
                            pdfPassword = item.getString("ISO-8859-1");
                        } else if (PROCESS_TYPE_PROPERTY_NAME.equals(itemFieldName)) {
                            final String processTypeAttribute = item.getString("ISO-8859-1");

                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Found process type in the request: " + processTypeAttribute);
                            }

                            if (processTypeAttribute != null) {
                                try {
                                    processType = ProcessType.valueOf(processTypeAttribute);
                                } catch (IllegalArgumentException e) {
                                    sendBadRequest(res, "Illegal process type: " + processTypeAttribute);
                                    return;
                                }
                            } else {
                                processType = ProcessType.signDocument;
                            }
                        } else if (ENCODING_PROPERTY_NAME.equals(itemFieldName)) {
                            encoding = item.getString("ISO-8859-1");
                        } else if (isFieldMatchingMetaData(itemFieldName)) {
                            try {
                                metadataHolder.handleMetaDataProperty(itemFieldName,
                                        item.getString("ISO-8859-1"));
                            } catch (IOException e) {
                                sendBadRequest(res, "Malformed properties given using REQUEST_METADATA.");
                                return;
                            }
                        }
                    } else {
                        // We only care for one upload at a time right now
                        if (fileItem == null) {
                            fileItem = item;
                        }
                    }
                }
            }

            if (fileItem == null) {
                sendBadRequest(res, "Missing file content in upload");
                return;
            } else {
                fileName = fileItem.getName();
                data = fileItem.get(); // Note: Reads entiry file to memory

                if (encoding != null && !encoding.isEmpty()) {
                    if (ENCODING_BASE64.equalsIgnoreCase(encoding)) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Decoding base64 data");
                        }
                        data = Base64.decode(data);
                    } else {
                        sendBadRequest(res, "Unknown encoding for the 'data' field: " + encoding);
                        return;
                    }
                }
            }
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            LOG.error(HTTP_MAX_UPLOAD_SIZE + " exceeded: " + ex.getLocalizedMessage());
            res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                    "Maximum content length is " + maxUploadSize + " bytes");
            return;
        } catch (FileUploadException ex) {
            throw new ServletException("Upload failed", ex);
        }
    } else {
        if (!workerRequest) {
            String name = req.getParameter(WORKERNAME_PROPERTY_NAME);
            if (name != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a signerName in the request: " + name);
                }
                workerId = getWorkerSession().getWorkerId(name);
            }
            String id = req.getParameter(WORKERID_PROPERTY_NAME);
            if (id != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a signerId in the request: " + id);
                }
                workerId = Integer.parseInt(id);
            }
        }

        final Enumeration<String> params = req.getParameterNames();

        while (params.hasMoreElements()) {
            final String property = params.nextElement();
            if (PDFPASSWORD_PROPERTY_NAME.equals(property)) {
                pdfPassword = (String) req.getParameter(PDFPASSWORD_PROPERTY_NAME);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a pdfPassword in the request.");
                }
            } else if (isFieldMatchingMetaData(property)) {
                try {
                    metadataHolder.handleMetaDataProperty(property, req.getParameter(property));
                } catch (IOException e) {
                    sendBadRequest(res, "Malformed properties given using REQUEST_METADATA.");
                    return;
                }
            }
        }

        final String processTypeAttribute = (String) req.getParameter(PROCESS_TYPE_PROPERTY_NAME);

        if (processTypeAttribute != null) {
            try {
                processType = ProcessType.valueOf(processTypeAttribute);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found process type in the request: " + processType.name());
                }
            } catch (IllegalArgumentException e) {
                sendBadRequest(res, "Illegal process type: " + processTypeAttribute);
                return;
            }
        } else {
            processType = ProcessType.signDocument;
        }

        if (METHOD_GET.equalsIgnoreCase(req.getMethod())
                || (req.getContentType() != null && req.getContentType().contains(FORM_URL_ENCODED))) {
            LOG.debug("Request is FORM_URL_ENCODED");

            if (req.getParameter(DATA_PROPERTY_NAME) == null) {
                sendBadRequest(res, "Missing field 'data' in request");
                return;
            }
            data = req.getParameter(DATA_PROPERTY_NAME).getBytes();

            String encoding = req.getParameter(ENCODING_PROPERTY_NAME);
            if (encoding != null && !encoding.isEmpty()) {
                if (ENCODING_BASE64.equalsIgnoreCase(encoding)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Decoding base64 data");
                    }
                    data = Base64.decode(data);
                } else {
                    sendBadRequest(res, "Unknown encoding for the 'data' field: " + encoding);
                    return;
                }
            }
        } else {
            // Pass-through the content to be handled by worker if
            // unknown content-type
            if (LOG.isDebugEnabled()) {
                LOG.debug("Request Content-type: " + req.getContentType());
            }

            // Get an input stream and read the bytes from the stream
            InputStream in = req.getInputStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int len;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
            in.close();
            os.close();
            data = os.toByteArray();
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Request of type: " + processType.name());
    }

    // Limit the maximum size of input
    if (data.length > maxUploadSize) {
        LOG.error("Content length exceeds " + maxUploadSize + ", not processed: " + req.getContentLength());
        res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                "Maximum content length is " + maxUploadSize + " bytes");
    } else {
        processRequest(req, res, workerId, data, fileName, pdfPassword, processType, metadataHolder);
    }

    LOG.debug("<doPost()");
}