Java Examples for com.oreilly.servlet.MultipartRequest

The following java examples will help you to understand the usage of com.oreilly.servlet.MultipartRequest. These source code samples are taken from different open source projects.

Example 1
Project: Magnolia-master  File: CosMultipartRequestFilter.java View source code
/**
     * Adds all request paramaters as request attributes.
     * @param request HttpServletRequest
     */
private static MultipartForm parseParameters(HttpServletRequest request) throws IOException {
    MultipartForm form = new MultipartForm();
    String encoding = StringUtils.defaultString(request.getCharacterEncoding(), "UTF-8");
    MultipartRequest multi = new MultipartRequest(request, Path.getTempDirectoryPath(), MAX_FILE_SIZE, encoding, null);
    Enumeration params = multi.getParameterNames();
    while (params.hasMoreElements()) {
        String name = (String) params.nextElement();
        String value = multi.getParameter(name);
        form.addParameter(name, value);
        String[] s = multi.getParameterValues(name);
        if (s != null) {
            form.addparameterValues(name, s);
        }
    }
    Enumeration files = multi.getFileNames();
    while (files.hasMoreElements()) {
        String name = (String) files.nextElement();
        form.addDocument(name, multi.getFilesystemName(name), multi.getContentType(name), multi.getFile(name));
    }
    request.setAttribute(MultipartForm.REQUEST_ATTRIBUTE_NAME, form);
    return form;
}
Example 2
Project: crezoo-master  File: viewPheno.java View source code
/**
    * Creates or updates phenotypes from file.
    *
    * @param request The request object to use.
    * @param response The response object to use.
    * @return True if everything was ok.
    *         False if any errors.
    * @exception IOException If writing any page fails.
    * @exception ServletException If writing any page fails.
    */
private boolean createFile(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    boolean isOk = true;
    String errMessage = null;
    Connection connection = null;
    try {
        HttpSession session = request.getSession(true);
        connection = (Connection) session.getValue("conn");
        connection.setAutoCommit(false);
        String upPath = getUpFilePath();
        MultipartRequest multiRequest = new MultipartRequest(request, upPath, 6 * 1024 * 1024);
        // Get parameters from request
        int samplingUnitId = Integer.parseInt(multiRequest.getParameter("suid"));
        int userId = Integer.parseInt((String) session.getValue("UserID"));
        String uploadMode = multiRequest.getParameter("type");
        Enumeration files = multiRequest.getFileNames();
        if (files.hasMoreElements()) {
            String givenFileName = (String) files.nextElement();
            String systemFileName = multiRequest.getFilesystemName(givenFileName);
            DbPhenotype dbp = new DbPhenotype();
            FileParser fileParser = new FileParser(upPath + "/" + systemFileName);
            FileHeader header = FileParser.scanFileHeader(upPath + "/" + systemFileName);
            // Ensure file format is list or matrix
            Assertion.assertMsg(header.formatTypeName().equalsIgnoreCase(FileTypeDefinition.LIST) || header.formatTypeName().equalsIgnoreCase(FileTypeDefinition.MATRIX), "Format type name should be list or matrix " + "but found found " + header.formatTypeName());
            // If file is a list
            if (header.formatTypeName().equalsIgnoreCase(FileTypeDefinition.LIST)) {
                fileParser.Parse(FileTypeDefinitionList.matchingDefinitions(FileTypeDefinition.PHENOTYPE, FileTypeDefinition.LIST));
                if (uploadMode.equals("CREATE")) {
                    dbp.CreatePhenotypesList(fileParser, connection, samplingUnitId, userId);
                } else if (uploadMode.equals("UPDATE")) {
                    dbp.UpdatePhenotypesList(fileParser, connection, samplingUnitId, userId);
                } else if (uploadMode.equals("CREATE_OR_UPDATE")) {
                    dbp.CreateOrUpdatePhenotypesList(fileParser, connection, samplingUnitId, userId);
                }
            } else // If file is a matrix
            if (header.formatTypeName().equalsIgnoreCase(FileTypeDefinition.MATRIX)) {
                fileParser.Parse(FileTypeDefinitionList.matchingDefinitions(FileTypeDefinition.PHENOTYPE, FileTypeDefinition.MATRIX));
                if (uploadMode.equals("CREATE")) {
                    dbp.CreatePhenotypesMatrix(fileParser, connection, samplingUnitId, userId);
                } else if (uploadMode.equals("UPDATE")) {
                    dbp.UpdatePhenotypesMatrix(fileParser, connection, samplingUnitId, userId);
                } else if (uploadMode.equals("CREATE_OR_UPDATE")) {
                    dbp.CreateOrUpdatePhenotypesMatrix(fileParser, connection, samplingUnitId, userId);
                }
            }
            errMessage = dbp.getErrorMessage();
            Assertion.assertMsg(errMessage == null || errMessage.trim().equals(""), errMessage);
        }
    } catch (Exception e) {
        isOk = false;
        e.printStackTrace(System.err);
        if (errMessage == null) {
            errMessage = e.getMessage();
        }
    }
    // if commit/rollback ok and database operation ok, write the frame 
    if (commitOrRollback(connection, request, response, "Phenotypes.Import.Send", errMessage, "viewPheno/impFile", isOk) && isOk) {
        writeFrame(request, response);
    }
    return isOk;
}
Example 3
Project: stripes-master  File: CosMultipartWrapper.java View source code
/**
     * Pseudo-constructor that allows the class to perform any initialization
     * necessary.
     *
     * @param request an HttpServletRequest that has a content-type of
     * multipart.
     * @param tempDir a File representing the temporary directory that can be
     * used to store file parts as they are uploaded if this is desirable
     * @param maxPostSize the size in bytes beyond which the request should not
     * be read, and a FileUploadLimitExceeded exception should be thrown
     * @throws IOException if a problem occurs processing the request of storing
     * temporary files
     * @throws FileUploadLimitExceededException if the POST content is longer
     * than the maxPostSize supplied.
     */
public void build(HttpServletRequest request, final File tempDir, long maxPostSize) throws IOException, FileUploadLimitExceededException {
    try {
        // Create a new file in the temp directory in case of file name conflict
        FileRenamePolicy renamePolicy = new FileRenamePolicy() {

            public File rename(File arg0) {
                try {
                    return File.createTempFile("cos", "", tempDir);
                } catch (IOException e) {
                    throw new StripesRuntimeException("Caught an exception while trying to rename an uploaded file", e);
                }
            }
        };
        this.charset = request.getCharacterEncoding();
        this.multipart = new MultipartRequest(request, tempDir.getAbsolutePath(), (int) maxPostSize, this.charset, renamePolicy);
    } catch (IOException ioe) {
        Matcher matcher = EXCEPTION_PATTERN.matcher(ioe.getMessage());
        if (matcher.matches()) {
            throw new FileUploadLimitExceededException(Long.parseLong(matcher.group(2)), Long.parseLong(matcher.group(1)));
        } else {
            throw ioe;
        }
    }
}
Example 4
Project: taplib-master  File: MultipartParser.java View source code
@Override
@SuppressWarnings("unchecked")
public final Map<String, Object> parse(final HttpServletRequest request) throws UWSException {
    LinkedHashMap<String, Object> parameters = new LinkedHashMap<String, Object>();
    MultipartRequest multipart = null;
    try {
        // Parse the request body:
        multipart = new MultipartRequest(request, UWSFileManager.TMP_UPLOAD_DIR.getPath(), (SIZE_LIMIT < 0 ? DEFAULT_SIZE_LIMIT : SIZE_LIMIT), new FileRenamePolicy() {

            @Override
            public File rename(File file) {
                Object reqID = request.getAttribute(UWS.REQ_ATTRIBUTE_ID);
                if (reqID == null || !(reqID instanceof String))
                    reqID = (new Date()).getTime();
                char uniq = 'A';
                File f = new File(file.getParentFile(), "UPLOAD_" + reqID + uniq + "_" + file.getName());
                while (f.exists()) {
                    uniq++;
                    f = new File(file.getParentFile(), "UPLOAD_" + reqID + "_" + file.getName());
                }
                return f;
            }
        });
        // Extract all "normal" parameters:
        String param;
        Enumeration<String> e = multipart.getParameterNames();
        while (e.hasMoreElements()) {
            param = e.nextElement();
            for (String occurence : multipart.getParameterValues(param)) consumeParameter(param, occurence, parameters);
        }
        // Extract all inline files as additional parameters:
        e = multipart.getFileNames();
        if (!allowUpload && e.hasMoreElements())
            throw new UWSException(UWSException.BAD_REQUEST, "Uploads are not allowed by this service!");
        while (e.hasMoreElements()) {
            param = e.nextElement();
            if (multipart.getFile(param) == null)
                continue;
            /*
				 * TODO !!!POSSIBLE ISSUE!!!
				 * MultipartRequest is not able to deal with multiple files having the same parameter name. However, all files are created/uploaded
				 * but only the last one is accessible through this object....so only the last can be deleted, which could be a problem later
				 * (hence the usage of the system temporary directory).
				 */
            // build its description/pointer:
            UploadFile lob = new UploadFile(param, multipart.getOriginalFileName(param), multipart.getFile(param).toURI().toString(), fileManager);
            lob.mimeType = multipart.getContentType(param);
            lob.length = multipart.getFile(param).length();
            // add it inside the parameters map:
            consumeParameter(param, lob, parameters);
        }
    } catch (IOException ioe) {
        throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ioe, "Internal Error => Impossible to extract parameters from the Multipart HTTP request!");
    } catch (IllegalArgumentException iae) {
        String confError = iae.getMessage();
        if (UWSFileManager.TMP_UPLOAD_DIR == null)
            confError = "Missing upload directory!";
        throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, iae, "Internal Error: Incorrect UPLOAD configuration: " + confError);
    }
    return parameters;
}
Example 5
Project: jfinal-master  File: MultipartRequest.java View source code
private void wrapMultipartRequest(HttpServletRequest request, String uploadPath, int maxPostSize, String encoding) {
    File dir = new File(uploadPath);
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            throw new RuntimeException("Directory " + uploadPath + " not exists and can not create directory.");
        }
    }
    //		String content_type = request.getContentType();
    //        if (content_type == null || content_type.indexOf("multipart/form-data") == -1) {
    //        	throw new RuntimeException("Not multipart request, enctype=\"multipart/form-data\" is not found of form.");
    //        }
    uploadFiles = new ArrayList<UploadFile>();
    try {
        multipartRequest = new com.oreilly.servlet.MultipartRequest(request, uploadPath, maxPostSize, encoding, fileRenamePolicy);
        Enumeration files = multipartRequest.getFileNames();
        while (files.hasMoreElements()) {
            String name = (String) files.nextElement();
            String filesystemName = multipartRequest.getFilesystemName(name);
            // 文件没有上传则不生成 UploadFile, 这与 cos的解决方案不一样
            if (filesystemName != null) {
                String originalFileName = multipartRequest.getOriginalFileName(name);
                String contentType = multipartRequest.getContentType(name);
                UploadFile uploadFile = new UploadFile(name, uploadPath, filesystemName, originalFileName, contentType);
                if (isSafeFile(uploadFile)) {
                    uploadFiles.add(uploadFile);
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 6
Project: BlinkCoder-master  File: MultipartRequest.java View source code
private void wrapMultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize, String encoding) {
    if (!isMultipartSupported)
        throw new RuntimeException("Oreilly cos.jar is not found, Multipart post can not be supported.");
    saveDirectory = handleSaveDirectory(saveDirectory);
    File dir = new File(saveDirectory);
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            throw new RuntimeException("Directory " + saveDirectory + " not exists and can not create directory.");
        }
    }
    //		String content_type = request.getContentType();
    //        if (content_type == null || content_type.indexOf("multipart/form-data") == -1) {
    //        	throw new RuntimeException("Not multipart request, enctype=\"multipart/form-data\" is not found of form.");
    //        }
    uploadFiles = new ArrayList<UploadFile>();
    try {
        multipartRequest = new com.oreilly.servlet.MultipartRequest(request, saveDirectory, maxPostSize, encoding, fileRenamePolicy);
        Enumeration files = multipartRequest.getFileNames();
        while (files.hasMoreElements()) {
            String name = (String) files.nextElement();
            String filesystemName = multipartRequest.getFilesystemName(name);
            // 文件没有上传则不生成 UploadFile, 这与 cos的解决方案不一样
            if (filesystemName != null) {
                String originalFileName = multipartRequest.getOriginalFileName(name);
                String contentType = multipartRequest.getContentType(name);
                UploadFile uploadFile = new UploadFile(name, saveDirectory, filesystemName, originalFileName, contentType);
                if (isSafeFile(uploadFile))
                    uploadFiles.add(uploadFile);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 7
Project: ynpay-old-master  File: MultipartRequest.java View source code
private void wrapMultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize, String encoding) {
    if (!isMultipartSupported)
        throw new RuntimeException("Oreilly cos.jar is not found, Multipart post can not be supported.");
    saveDirectory = handleSaveDirectory(saveDirectory);
    File dir = new File(saveDirectory);
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            throw new RuntimeException("Directory " + saveDirectory + " not exists and can not create directory.");
        }
    }
    //		String content_type = request.getContentType();
    //        if (content_type == null || content_type.indexOf("multipart/form-data") == -1) {
    //        	throw new RuntimeException("Not multipart request, enctype=\"multipart/form-data\" is not found of form.");
    //        }
    uploadFiles = new ArrayList<UploadFile>();
    try {
        multipartRequest = new com.oreilly.servlet.MultipartRequest(request, saveDirectory, maxPostSize, encoding, fileRenamePolicy);
        Enumeration files = multipartRequest.getFileNames();
        while (files.hasMoreElements()) {
            String name = (String) files.nextElement();
            String filesystemName = multipartRequest.getFilesystemName(name);
            // 文件没有上传则不生成 UploadFile, 这与 cos的解决方案不一样
            if (filesystemName != null) {
                String originalFileName = multipartRequest.getOriginalFileName(name);
                String contentType = multipartRequest.getContentType(name);
                UploadFile uploadFile = new UploadFile(name, saveDirectory, filesystemName, originalFileName, contentType);
                if (isSafeFile(uploadFile))
                    uploadFiles.add(uploadFile);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 8
Project: JFOA-master  File: MultipartRequest.java View source code
private void wrapMultipartRequest(HttpServletRequest request, String saveDirectory, int maxPostSize, String encoding) {
    if (!isMultipartSupported)
        throw new RuntimeException("Oreilly cos.jar is not found, Multipart post can not be supported.");
    saveDirectory = handleSaveDirectory(saveDirectory);
    File dir = new File(saveDirectory);
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            throw new RuntimeException("Directory " + saveDirectory + " not exists and can not create directory.");
        }
    }
    //		String content_type = request.getContentType();
    //        if (content_type == null || content_type.indexOf("multipart/form-data") == -1) {
    //        	throw new RuntimeException("Not multipart request, enctype=\"multipart/form-data\" is not found of form.");
    //        }
    uploadFiles = new ArrayList<UploadFile>();
    try {
        multipartRequest = new com.oreilly.servlet.MultipartRequest(request, saveDirectory, maxPostSize, encoding, fileRenamePolicy);
        Enumeration files = multipartRequest.getFileNames();
        while (files.hasMoreElements()) {
            String name = (String) files.nextElement();
            String filesystemName = multipartRequest.getFilesystemName(name);
            // 文件没有上传则不生成 UploadFile, 这与 cos的解决方案不一样
            if (filesystemName != null) {
                String originalFileName = multipartRequest.getOriginalFileName(name);
                String contentType = multipartRequest.getContentType(name);
                UploadFile uploadFile = new UploadFile(name, saveDirectory, filesystemName, originalFileName, contentType);
                if (isSafeFile(uploadFile))
                    uploadFiles.add(uploadFile);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 9
Project: transmem-master  File: ServletParams.java View source code
public MultipartRequest getMultipartRequest() {
    return this.mrequest_;
}