Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold.

Prototype

public void setSizeThreshold(int sizeThreshold) 

Source Link

Document

Sets the size threshold beyond which files are written directly to disk.

Usage

From source file:CourseFileManagementSystem.Upload.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.write("<html><head></head><body>");
    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();/* w  w  w  . j a v  a 2s  . co m*/
        return;
    }

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

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String temp_folder = " ";
    try {
        String dataFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;
        temp_folder = dataFolder;
        File uploadD = new File(dataFolder);
        if (!uploadD.exists()) {
            uploadD.mkdir();
        }

        ResultList rs5 = DB.query(
                "SELECT * FROM course AS c, section AS s, year_semester AS ys, upload_checklist AS uc WHERE s.courseCode = c.courseCode "
                        + "AND s.semesterID = ys.semesterID AND s.courseID = c.courseID AND s.sectionID="
                        + sectionID);
        rs5.next();

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

        // Sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // creates the directory if it does not exist
        String path1 = getServletContext().getContextPath() + "/" + DATA_DIRECTORY + "/";
        String temp_semester = rs5.getString("year") + "-" + rs5.getString("semester");
        String real_path = temp_folder + File.separator + temp_semester;
        File semester = new File(real_path);

        if (!semester.exists()) {
            semester.mkdir();
        }
        path1 += temp_semester + "/";
        real_path += File.separator;

        String temp_course = rs5.getString("courseCode") + rs5.getString("courseID") + "-"
                + rs5.getString("courseName");
        String real_path1 = real_path + temp_course;
        File course = new File(real_path1);
        if (!course.exists()) {
            course.mkdir();
        }
        path1 += temp_course + "/";
        real_path1 += File.separator;

        String temp_section = "section-" + rs5.getString("sectionNo");
        String real_path2 = real_path1 + temp_section;
        File section = new File(real_path2);
        if (!section.exists()) {
            section.mkdir();
        }
        path1 += temp_section + "/";
        real_path2 += File.separator;
        String sectionPath = path1;

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        if (items != null && items.size() > 0) {
            // iterates over form's fields
            for (FileItem item : items) {
                // processes only fields that are not form fields
                if (!item.isFormField() && !item.getName().equals("")) {
                    String DBPath = "";
                    System.out.println(item.getName() + " file is for " + item.getFieldName());
                    Scanner field_name = new Scanner(item.getFieldName()).useDelimiter("[^0-9]+");
                    int id = field_name.nextInt();
                    fileName = new File(item.getName()).getName();
                    ResultList rs = DB.query("SELECT * FROM upload_checklist WHERE checklistID =" + id);
                    rs.next();
                    String temp_file = rs.getString("label");
                    String real_path3 = real_path2 + temp_file;
                    File file_type = new File(real_path3);
                    if (!file_type.exists())
                        file_type.mkdir();
                    DBPath = sectionPath + "/" + temp_file + "/";
                    String context_path = DBPath;
                    real_path3 += File.separator;
                    String filePath = real_path3 + fileName;
                    DBPath += fileName;
                    String temp_DBPath = DBPath;

                    int count = 0;
                    File f = new File(filePath);
                    String temp_fileName = f.getName();
                    String fileNameWithOutExt = FilenameUtils.removeExtension(temp_fileName);
                    String extension = FilenameUtils.getExtension(filePath);
                    String newFullPath = filePath;
                    String tempFileName = " ";

                    while (f.exists()) {
                        ++count;
                        tempFileName = fileNameWithOutExt + "_(" + count + ").";
                        newFullPath = real_path3 + tempFileName + extension;
                        temp_DBPath = context_path + tempFileName + extension;
                        f = new File(newFullPath);
                    }

                    filePath = newFullPath;
                    System.out.println("New path: " + filePath);
                    DBPath = temp_DBPath;
                    String changeFilePath = filePath.replace('/', '\\');
                    String changeFilePath1 = changeFilePath.replace("Course_File_Management_System\\", "");
                    File uploadedFile = new File(changeFilePath1);
                    System.out.println("Change filepath = " + changeFilePath1);
                    System.out.println("DBPath = " + DBPath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                    String query = "INSERT INTO files (fileDirectory) values('" + DBPath + "')";
                    DB.update(query);
                    ResultList rs3 = DB.query("SELECT label FROM upload_checklist WHERE id=" + id);
                    while (rs3.next()) {
                        String label = rs3.getString("label");
                        out.write("<a href=\"Upload?fileName=" + changeFilePath1 + "\">Download " + label
                                + "</a>");
                        out.write("<br><br>");
                    }
                    ResultList rs4 = DB.query("SELECT * FROM files ORDER BY fileID DESC LIMIT 1");
                    rs4.next();
                    String query2 = "INSERT INTO lecturer_upload (fileID, sectionID, checklistID) values("
                            + rs4.getString("fileID") + ", " + sectionID + ", " + id + ")";
                    DB.update(query2);
                }
            }
        }
    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
    response.sendRedirect(request.getHeader("Referer"));
}

From source file:com.reachcall.pretty.http.ProxyServlet.java

@SuppressWarnings("unchecked")
private void doMultipart(HttpPost method, HttpServletRequest req)
        throws ServletException, FileUploadException, UnsupportedEncodingException, IOException {
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(TEMP_DIR);

    ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);

    List<FileItem> fileItems = (List<FileItem>) upload.parseRequest(req);

    MultipartEntity entity = new MultipartEntity();

    for (FileItem fItem : fileItems) {
        if (fItem.isFormField()) {
            LOG.log(Level.INFO, "Form field {0}", fItem.getName());

            StringBody part = new StringBody(fItem.getFieldName());
            entity.addPart(fItem.getFieldName(), part);
        } else {//from   ww  w . j a  va2  s.c om
            LOG.log(Level.INFO, "File item {0}", fItem.getName());

            InputStreamBody file = new InputStreamBody(fItem.getInputStream(), fItem.getName(),
                    fItem.getContentType());
            entity.addPart(fItem.getFieldName(), file);
        }
    }

    method.setEntity(entity);
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.localepairs.LocalePairImportHandler.java

/**
 * Upload the properties file to FilterConfigurations/import folder
 * /* w  w w .j a  v a2s  . c om*/
 * @param request
 */
private File uploadFile(HttpServletRequest request) {
    File f = null;
    try {
        String tmpDir = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight"
                + File.separator + "LocalePairs" + File.separator + "import";
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024000);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> items = upload.parseRequest(request);
            for (int i = 0; i < items.size(); i++) {
                FileItem item = (FileItem) items.get(i);
                if (!item.isFormField()) {
                    String filePath = item.getName();
                    if (filePath.contains(":")) {
                        filePath = filePath.substring(filePath.indexOf(":") + 1);
                    }
                    String originalFilePath = filePath.replace("\\", File.separator).replace("/",
                            File.separator);
                    String fileName = tmpDir + File.separator + originalFilePath;
                    f = new File(fileName);
                    f.getParentFile().mkdirs();
                    item.write(f);
                }
            }
        }
        return f;
    } catch (Exception e) {
        logger.error("File upload failed.", e);
        return null;
    }
}

From source file:com.example.web.Update_profile.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        String fileName = "";
        int f = 0;
        String user = null;//from   ww w .j  a  v  a 2 s.  co m
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("user")) {
                    user = cookie.getValue();
                }
            }
        }
        String email = request.getParameter("email");
        String First_name = request.getParameter("First_name");
        String Last_name = request.getParameter("Last_name");
        String Phone_number_1 = request.getParameter("Phone_number_1");
        String Address = request.getParameter("Address");
        String message = "";
        int valid = 1;
        String query;
        ResultSet rs;
        Connection conn;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "tworld";
        String driver = "com.mysql.jdbc.Driver";
        isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/"));
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            try {
                // Parse the request to get file items.
                List fileItems = upload.parseRequest(request);

                // Process the uploaded file items
                Iterator i = fileItems.iterator();

                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        String fieldName = fi.getFieldName();
                        fileName = fi.getName();
                        String contentType = fi.getContentType();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        String[] spliting = fileName.split("\\.");
                        // Write the file
                        System.out.println(sizeInBytes + " " + maxFileSize);
                        System.out.println(spliting[spliting.length - 1]);
                        if (!fileName.equals("")) {
                            if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg")
                                    || spliting[spliting.length - 1].equals("png")
                                    || spliting[spliting.length - 1].equals("jpeg"))) {

                                if (fileName.lastIndexOf("\\") >= 0) {
                                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                                } else {
                                    file = new File(
                                            filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                                }
                                fi.write(file);
                                System.out.println("Uploaded Filename: " + fileName + "<br>");
                            } else {
                                valid = 0;
                                message = "not a valid image";
                            }
                        }
                    }
                    BufferedReader br = null;
                    StringBuilder sb = new StringBuilder();

                    String line;
                    try {
                        br = new BufferedReader(new InputStreamReader(fi.getInputStream()));
                        while ((line = br.readLine()) != null) {
                            sb.append(line);
                        }
                    } catch (IOException e) {
                    } finally {
                        if (br != null) {
                            try {
                                br.close();
                            } catch (IOException e) {
                            }
                        }
                    }
                    if (f == 0) {
                        email = sb.toString();
                    } else if (f == 1) {
                        First_name = sb.toString();
                    } else if (f == 2) {
                        Last_name = sb.toString();
                    } else if (f == 3) {
                        Phone_number_1 = sb.toString();
                    } else if (f == 4) {
                        Address = sb.toString();
                    }
                    f++;

                }
            } catch (Exception ex) {
                System.out.println("hi");
                System.out.println(ex);

            }
        }
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, "admin", "admin");
            if (!email.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `email`=? where `Username`=?");
                pst.setString(1, email);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!First_name.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `First_name`=? where `Username`=?");
                pst.setString(1, First_name);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Last_name.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Last_name`=? where `Username`=?");
                pst.setString(1, Last_name);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Phone_number_1.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Phone_number_1`=? where `Username`=?");
                pst.setString(1, Phone_number_1);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Address.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Address`=? where `Username`=?");
                pst.setString(1, Address);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!fileName.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Fototitle`=? where `Username`=?");
                pst.setString(1, fileName);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
            System.out.println("hi mom");
        }

        request.setAttribute("s_page", "4");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

@RequestMapping(value = "EenviarMailA.htm", method = RequestMethod.POST)
public String enviarMailA_post(@ModelAttribute("correo") correoNoLeidos c, BindingResult result,
        HttpServletRequest request) {/*w w  w  .j a  va2s . co  m*/
    String mensaje = "";

    try {
        //MultipartFile multipart = c.getArchivo();
        System.out.println("olaEnviarMAILS");
        String ubicacionArchivo = "C:\\DecorakiaReportesIntranet\\archivosMail\\";
        //File file=new File(ubicacionArchivo,multipart.getOriginalFilename());
        //String ubicacionArchivo="C:\\";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024);
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> partes = upload.parseRequest(request);

        for (FileItem item : partes) {
            System.out.println("NOMBRE FOTO: " + item.getName());
            File file = new File(ubicacionArchivo, item.getName());
            item.write(file);
            arc.add(item.getName());
            System.out.println("img" + item.getName());
        }
        //c.setImagenes(arc);

    } catch (Exception ex) {

    }
    return "redirect:EenviarMail.htm";

}

From source file:it.geosolutions.servicebox.FileUploadCallback.java

/**
 * Handle a POST request/* w  w  w. ja v  a 2 s  . c  o  m*/
 * 
 * @param request
 * @param response
 * 
 * @return CallbackResult
 * 
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public ServiceBoxActionParameters onPost(HttpServletRequest request, HttpServletResponse response,
        ServiceBoxActionParameters callbackResult) throws IOException {

    // Get items if already initialized
    List<FileItem> items = null;
    if (callbackResult == null) {
        callbackResult = new ServiceBoxActionParameters();
    } else {
        items = callbackResult.getItems();
    }

    String temp = callbackConfiguration.getTempFolder();
    int buffSize = callbackConfiguration.getBuffSize();
    int itemSize = 0;
    long maxSize = 0;
    String itemName = null;
    boolean fileTypeMatch = true;

    File tempDir = new File(temp);

    try {
        if (items == null && ServletFileUpload.isMultipartContent(request) && tempDir != null
                && tempDir.exists()) {
            // items are not initialized. Read it from the request

            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

            /*
             * Set the size threshold, above which content will be stored on
             * disk.
             */
            fileItemFactory.setSizeThreshold(buffSize); // 1 MB

            /*
             * Set the temporary directory to store the uploaded files of
             * size above threshold.
             */
            fileItemFactory.setRepository(tempDir);

            ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

            /*
             * Parse the request
             */
            items = uploadHandler.parseRequest(request);

        }

        // Read items
        if (items != null) {

            itemSize = items.size();
            callbackResult.setItems(items);
            if (itemSize <= this.callbackConfiguration.getMaxItems()) {
                // only if item size not exceeded max
                for (FileItem item : items) {
                    itemName = item.getName();
                    if (item.getSize() > maxSize) {
                        maxSize = item.getSize();
                        if (maxSize > this.callbackConfiguration.getMaxSize()) {
                            // max size exceeded
                            break;
                        } else if (this.callbackConfiguration.getFileTypePatterns() != null) {
                            fileTypeMatch = false;
                            int index = 0;
                            while (!fileTypeMatch
                                    && index < this.callbackConfiguration.getFileTypePatterns().size()) {
                                Pattern pattern = this.callbackConfiguration.getFileTypePatterns().get(index++);
                                fileTypeMatch = pattern.matcher(itemName).matches();
                            }
                            if (!fileTypeMatch) {
                                break;
                            }
                        }
                    }
                }
            }
        } else {
            itemSize = 1;
            maxSize = request.getContentLength();
            // TODO: Handle file type
        }

    } catch (Exception ex) {
        if (LOGGER.isLoggable(Level.SEVERE))
            LOGGER.log(Level.SEVERE, "Error encountered while parsing the request");

        response.setContentType("text/html");

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("success", false);
        jsonObj.put("errorMessage", ex.getLocalizedMessage());

        Utilities.writeResponse(response, jsonObj.toString(), LOGGER);

    }

    // prepare and send error if exists
    boolean error = false;
    int errorCode = -1;
    String message = null;
    Map<String, Object> errorDetails = null;
    if (itemSize > this.callbackConfiguration.getMaxItems()) {
        errorDetails = new HashMap<String, Object>();
        error = true;
        errorDetails.put("expected", this.callbackConfiguration.getMaxItems());
        errorDetails.put("found", itemSize);
        errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEMS.ordinal();
        message = "Max items size exceeded (expected: '" + this.callbackConfiguration.getMaxItems()
                + "', found: '" + itemSize + "').";
    } else if (maxSize > this.callbackConfiguration.getMaxSize()) {
        errorDetails = new HashMap<String, Object>();
        error = true;
        errorDetails.put("expected", this.callbackConfiguration.getMaxSize());
        errorDetails.put("found", maxSize);
        errorDetails.put("item", itemName);
        errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEM_SIZE.ordinal();
        message = "Max item size exceeded (expected: '" + this.callbackConfiguration.getMaxSize()
                + "', found: '" + maxSize + "' on item '" + itemName + "').";
    } else if (fileTypeMatch == false) {
        errorDetails = new HashMap<String, Object>();
        error = true;
        String expected = this.callbackConfiguration.getFileTypes();
        errorDetails.put("expected", expected);
        errorDetails.put("found", itemName);
        errorDetails.put("item", itemName);
        errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.ITEM_TYPE.ordinal();
        message = "File type not maches with known file types: (expected: '" + expected + "', item '" + itemName
                + "').";
    }
    if (error) {
        callbackResult.setSuccess(false);
        Utilities.writeError(response, errorCode, errorDetails, message, LOGGER);
    } else {
        callbackResult.setSuccess(true);
    }

    return callbackResult;
}

From source file:edu.harvard.hul.ois.fits.service.servlets.FitsServlet.java

/**
 * Handles the file upload for FITS processing via streaming of the file using the
 * <code>POST</code> method.
 * Example: curl -X POST -F datafile=@<path/to/file> <host>:[<port>]/fits/examine
 * Note: "fits" in the above URL needs to be adjusted to the final name of the WAR file.
 *
 * @param request servlet request//from   ww w  . ja  v  a2  s . c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.debug("Entering doPost()");
    if (!ServletFileUpload.isMultipartContent(request)) {
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                "Missing multipart POST form data.", request.getRequestURL().toString());
        sendErrorMessageResponse(errorMessage, response);
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold((maxInMemoryFileSizeMb * (int) MB_MULTIPLIER));
    String tempDir = System.getProperty("java.io.tmpdir");
    logger.debug("Creating temp directory for storing uploaded files: " + tempDir);
    factory.setRepository(new File(tempDir));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(maxFileUploadSizeMb * MB_MULTIPLIER);
    upload.setSizeMax(maxRequestSizeMb * MB_MULTIPLIER);

    try {
        List<FileItem> formItems = upload.parseRequest(request);
        Iterator<FileItem> iter = formItems.iterator();
        Map<String, String[]> paramMap = request.getParameterMap();

        boolean includeStdMetadata = true;
        String[] vals = paramMap.get(Constants.INCLUDE_STANDARD_OUTPUT_PARAM);
        if (vals != null && vals.length > 0) {
            if (FALSE.equalsIgnoreCase(vals[0])) {
                includeStdMetadata = false;
                logger.debug("flag includeStdMetadata set to : " + includeStdMetadata);
            }
        }

        // file-specific directory path to store uploaded file
        // ensures unique sub-directory to handle rare case of duplicate file name
        String subDir = String.valueOf((new Date()).getTime());
        String uploadPath = uploadBaseDir + File.separator + subDir;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        // iterates over form's fields -- should only be one for uploaded file
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (!item.isFormField() && item.getFieldName().equals(FITS_FORM_FIELD_DATAFILE)) {

                String fileName = item.getName();
                if (StringUtils.isEmpty(fileName)) {
                    ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                            "Missing File Data.", request.getRequestURL().toString());
                    sendErrorMessageResponse(errorMessage, response);
                    return;
                }
                // ensure a unique local fine name
                String fileNameAndPath = uploadPath + File.separator + item.getName();
                File storeFile = new File(fileNameAndPath);
                item.write(storeFile); // saves the file on disk

                if (!storeFile.exists()) {
                    ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Uploaded file does not exist.", request.getRequestURL().toString());
                    sendErrorMessageResponse(errorMessage, response);
                    return;
                }
                // Send it to the FITS processor...
                try {

                    sendFitsExamineResponse(storeFile.getAbsolutePath(), includeStdMetadata, request, response);

                } catch (Exception e) {
                    logger.error("Unexpected exception: " + e.getMessage(), e);
                    ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            e.getMessage(), request.getRequestURL().toString());
                    sendErrorMessageResponse(errorMessage, response);
                    return;
                } finally {
                    // delete the uploaded file
                    if (storeFile.delete()) {
                        logger.debug(storeFile.getName() + " is deleted!");
                    } else {
                        logger.warn(storeFile.getName() + " could not be deleted!");
                    }
                    if (uploadDir.delete()) {
                        logger.debug(uploadDir.getName() + " is deleted!");
                    } else {
                        logger.warn(uploadDir.getName() + " could not be deleted!");
                    }
                }
            } else {
                ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                        "The request did not have the correct name attribute of \"datafile\" in the form processing. ",
                        request.getRequestURL().toString(), "Processing halted.");
                sendErrorMessageResponse(errorMessage, response);
                return;
            }

        }

    } catch (Exception ex) {
        logger.error("Unexpected exception: " + ex.getMessage(), ex);
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                ex.getMessage(), request.getRequestURL().toString(), "Processing halted.");
        sendErrorMessageResponse(errorMessage, response);
        return;
    }
}

From source file:at.gv.egiz.pdfas.web.servlets.ExternSignServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*from w w w .j  av  a2 s  . c o m*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //PdfAsHelper.regenerateSession(request);

    logger.debug("Post signing request");

    String errorUrl = PdfAsParameterExtractor.getInvokeErrorURL(request);
    PdfAsHelper.setErrorURL(request, response, errorUrl);

    StatisticEvent statisticEvent = new StatisticEvent();
    statisticEvent.setStartNow();
    statisticEvent.setSource(Source.WEB);
    statisticEvent.setOperation(Operation.SIGN);
    statisticEvent.setUserAgent(UserAgentFilter.getUserAgent());

    try {
        byte[] filecontent = null;

        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            // No Uploaded data!
            if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                doGet(request, response);
                return;
            } else {
                throw new PdfAsWebException("No Signature data defined!");
            }
        } else {
            // configures upload settings
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(WebConfiguration.getFilesizeThreshold());
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(WebConfiguration.getMaxFilesize());
            upload.setSizeMax(WebConfiguration.getMaxRequestsize());

            // constructs the directory path to store upload file
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            // creates the directory if it does not exist
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            List<?> formItems = upload.parseRequest(request);
            logger.debug(formItems.size() + " Items in form data");
            if (formItems.size() < 1) {
                // No Uploaded data!
                // Try do get
                // No Uploaded data!
                if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                    doGet(request, response);
                    return;
                } else {
                    throw new PdfAsWebException("No Signature data defined!");
                }
            } else {
                for (int i = 0; i < formItems.size(); i++) {
                    Object obj = formItems.get(i);
                    if (obj instanceof FileItem) {
                        FileItem item = (FileItem) obj;
                        if (item.getFieldName().equals(UPLOAD_PDF_DATA)) {
                            filecontent = item.get();
                            try {
                                File f = new File(item.getName());
                                String name = f.getName();
                                logger.debug("Got upload: " + item.getName());
                                if (name != null) {
                                    if (!(name.endsWith(".pdf") || name.endsWith(".PDF"))) {
                                        name += ".pdf";
                                    }

                                    logger.debug("Setting Filename in session: " + name);
                                    PdfAsHelper.setPDFFileName(request, name);
                                }
                            } catch (Throwable e) {
                                logger.warn("In resolving filename", e);
                            }
                            if (filecontent.length < 10) {
                                filecontent = null;
                            } else {
                                logger.debug("Found pdf Data! Size: " + filecontent.length);
                            }
                        } else {
                            request.setAttribute(item.getFieldName(), item.getString());
                            logger.debug("Setting " + item.getFieldName() + " = " + item.getString());
                        }
                    } else {
                        logger.debug(obj.getClass().getName() + " - " + obj.toString());
                    }
                }
            }
        }

        if (filecontent == null) {
            if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                filecontent = RemotePDFFetcher.fetchPdfFile(PdfAsParameterExtractor.getPdfUrl(request));
            }
        }

        if (filecontent == null) {
            Object sourceObj = request.getAttribute("source");
            if (sourceObj != null) {
                String source = sourceObj.toString();
                if (source.equals("internal")) {
                    request.setAttribute("FILEERR", true);
                    request.getRequestDispatcher("index.jsp").forward(request, response);

                    statisticEvent.setStatus(Status.ERROR);
                    statisticEvent.setException(new Exception("No file uploaded"));
                    statisticEvent.setEndNow();
                    statisticEvent.setTimestampNow();
                    StatisticFrontend.getInstance().storeEvent(statisticEvent);
                    statisticEvent.setLogged(true);

                    return;
                }
            }
            throw new PdfAsException("No Signature data available");
        }

        doSignature(request, response, filecontent, statisticEvent);
    } catch (Exception e) {
        logger.error("Signature failed", e);
        statisticEvent.setStatus(Status.ERROR);
        statisticEvent.setException(e);
        if (e instanceof PDFASError) {
            statisticEvent.setErrorCode(((PDFASError) e).getCode());
        }
        statisticEvent.setEndNow();
        statisticEvent.setTimestampNow();
        StatisticFrontend.getInstance().storeEvent(statisticEvent);
        statisticEvent.setLogged(true);

        PdfAsHelper.setSessionException(request, response, e.getMessage(), e);
        PdfAsHelper.gotoError(getServletContext(), request, response);
    }
}

From source file:it.univaq.servlet.Upload_pub.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from   w w w .  ja  v a2s.c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */

protected boolean action_upload(HttpServletRequest request) throws FileUploadException, Exception {

    HttpSession s = SecurityLayer.checkSession(request);
    if (ServletFileUpload.isMultipartContent(request)) {

        //dichiaro mappe 
        Map pubb = new HashMap();
        Map rist = new HashMap();
        Map key = new HashMap();
        Map files = new HashMap();
        int idristampa = 0;
        //La dimensione massima di ogni singolo file su system
        int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB
        //Dimensione massima della request
        int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB

        // Creo un factory per l'accesso al filesystem
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //Setto la dimensione massima di ogni file, opzionale
        factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte);

        // Istanzio la classe per l'upload
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Setto la dimensione massima della request
        upload.setSizeMax(dimensioneMassimaDellaRequestInByte);

        // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con
        // tutti i field sia di tipo file che gli altri
        List<FileItem> items = upload.parseRequest(request);

        /*
        * La classe usata non permette di riprendere i singoli campi per
        * nome quindi dovremmo scorrere la lista che ci viene ritornata con
        * il metodo parserequest
        */
        //scorro per tutti i campi inviati
        for (int i = 0; i < items.size(); i++) {
            FileItem item = items.get(i);
            // Controllo se si tratta di un campo di input normale
            if (item.isFormField()) {
                // Prendo solo il nome e il valore
                String name = item.getFieldName();
                String value = item.getString();

                if (name.equals("titolo") && !name.isEmpty() || name.equals("autore") && !name.isEmpty()
                        || name.equals("descrizione") && !name.isEmpty()) {
                    pubb.put(name, value);
                } else if (name.equals("isbn") && !name.isEmpty() || name.equals("editore") && !name.isEmpty()
                        || name.equals("lingua") && !name.isEmpty()
                        || name.equals("numpagine") && !name.isEmpty()) {
                    rist.put(name, value);
                } else if (name.equals("datapub") && !name.isEmpty()) {

                    rist.put(name, value);
                } else if (name.equals("key1") || name.equals("key2") || name.equals("key3")
                        || name.equals("key4")) {
                    key.put(name, value);
                } else
                    return false;

            } // Se si stratta invece di un file
            else {

                // Dopo aver ripreso tutti i dati disponibili name,type,size
                //String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                long sizeInBytes = item.getSize();
                if (contentType.equals("image/jpeg") && !fileName.isEmpty()) {
                    //li salvo nella mappa
                    files.put("name", fileName);
                    files.put("type", contentType);
                    files.put("size", sizeInBytes);

                    //li scrivo nel db
                    //Database.connect();
                    Database.insertRecord("files", files);
                    //Database.close();
                    ResultSet rs1 = Database.selectRecord("files", "name='" + files.get("name") + "'");
                    if (!isNull(rs1)) {
                        while (rs1.next()) {
                            rist.put("copertina", rs1.getInt("id"));

                        }
                    }

                    // Posso scriverlo direttamente su filesystem
                    if (true) {
                        File uploadedFile = new File(
                                getServletContext().getInitParameter("uploads.directory") + fileName);
                        // Solo se veramente ho inviato qualcosa
                        if (item.getSize() > 0) {
                            item.write(uploadedFile);
                        }
                    }
                } else if (!fileName.isEmpty()) {
                    files.put("name", fileName);
                    files.put("type", contentType);
                    files.put("size", sizeInBytes);

                    //li scrivo nel db
                    //Database.connect();
                    Database.insertRecord("files", files);
                    //Database.close();
                    ResultSet rs4 = Database.selectRecord("files", "name='" + files.get("name") + "'");
                    if (!isNull(rs4)) {
                        while (rs4.next()) {

                            rist.put("download", rs4.getInt("id"));
                        }
                    }
                    // Posso scriverlo direttamente su filesystem
                    if (true) {
                        File uploadedFile = new File(
                                getServletContext().getInitParameter("uploads.directory") + fileName);
                        // Solo se veramente ho inviato qualcosa
                        if (item.getSize() > 0) {
                            item.write(uploadedFile);
                        }
                    }

                }

            }
        }

        //inserisco dati  nel db
        pubb.put("idutente", s.getAttribute("userid"));
        //    Database.connect();
        //prova incremento campo inserite per utenti piu attivi
        pubb.put("idutente", s.getAttribute("userid"));
        //    Database.connect();
        int userid = (int) s.getAttribute("userid");
        //prova incremento campo inserite per utenti piu attivi

        //    inserisco parole chiave
        Database.simpleupdateRecord("utenti", "inserite=inserite+1", "id=" + userid);

        //    inserisco parole chiave
        Database.insertRecord("keyword", key);
        //seleziono id parole chiave appena inserite
        ResultSet rs2 = Database.selectRecord("keyword",
                "key1='" + key.get("key1") + "'&&" + "key2='" + key.get("key2") + "'&&" + "key3='"
                        + key.get("key3") + "'&&" + "key4='" + key.get("key4") + "'");
        if (!isNull(rs2)) {
            while (rs2.next()) { //e inserisco id keyword nella tab pubblicazione
                pubb.put("keyword", rs2.getInt("id"));
            }
        }
        //inserisco ora la pubblicazione con tutti i dati
        Database.insertRecord("pubblicazione", pubb);
        //seleziono id pubblicazione appena inserita
        ResultSet rs = Database.selectRecord("pubblicazione", "titolo='" + pubb.get("titolo") + "'");
        //e inserisco l'id nella tab ristampa e  tab files
        while (rs.next()) {
            rist.put("idpub", rs.getInt("id"));
        }

        ResultSet rs3 = Database.selectRecord("ristampa", "isbn=" + rist.get("isbn"));
        while (rs3.next()) {
            idristampa = rs3.getInt("id");
        }
        //inserisco dati in tab ristampa
        //    Database.updateRecord("ristampa", rist, "id " +idristampa);
        Database.insertRecord("ristampa", rist);
        //    Database.close();
        //vado alla pagina di corretto inserimento
        //    FreeMarker.process("home.html", pubb, response, getServletContext());
        return true;
    } else
        return false;
}

From source file:com.intbit.ServletModel.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww w  .java 2  s . com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        look = new Looks();
        //            uploadXmlPath = getServletContext().getRealPath("") + "/model";
        uploadPath = AppConstants.BASE_MODEL_PATH;

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("organization")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("users")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("categories")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("mapper")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("layout")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("mail")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("socialmedia")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("textstyle")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("containerstyle")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("element")) {
                        lookName = fi.getString();
                    }

                    String textstyleinfo = request.getParameter("textstyle");
                    String containerstyle = request.getParameter("containerstyle");
                    String mapfiledata = request.getParameter("element");
                    String textstylearray[] = textstyleinfo.split(",");
                    String containerstylearray[] = containerstyle.split(" ");
                    String mapfiledataarray[] = mapfiledata.split(",");
                    //        String image = request.getParameter("image");
                    logger.log(Level.INFO, containerstyle);

                    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

                    // root elements
                    Document doc = docBuilder.newDocument();
                    Element rootElement = doc.createElement("layout");
                    doc.appendChild(rootElement);

                    Document doc1 = docBuilder.newDocument();
                    Element rootElement1 = doc1.createElement("models");
                    doc1.appendChild(rootElement1);

                    Element container = doc.createElement("container");
                    rootElement.appendChild(container);

                    //                        for (int i = 0; i <= containerstylearray.length - 1; i++) {
                    //                            String v[] = containerstylearray[i].split(":");
                    //                            Attr attr = doc.createAttribute(v[0]);
                    //                            attr.setValue("" + v[1]);
                    //                            container.setAttributeNode(attr);
                    //                        }
                    //
                    //                        // staff elements
                    //                        for (int i = 0; i <= textstylearray.length - 1; i++) {
                    //                            Element element = doc.createElement("element");
                    //                            rootElement.appendChild(element);
                    //                            String field1[] = textstylearray[i].split(" ");
                    //                            for (int j = 0; j <= field1.length - 1; j++) {
                    //                                String field2[] = field1[j].split(":");
                    //                                for (int k = 0; k < field2.length - 1; k++) {
                    //                                    Attr attr = doc.createAttribute(field2[0]);
                    //                                    attr.setValue("" + field2[1]);
                    //                                    element.setAttributeNode(attr);
                    //                                }
                    //                            }
                    //                        }
                    //
                    //            //            for mapper xml file
                    //                        for (int i = 0; i <= mapfiledataarray.length - 1; i++) {
                    //                            Element element1 = doc1.createElement("model");
                    //                            rootElement1.appendChild(element1);
                    //                            String field1[] = mapfiledataarray[i].split(" ");
                    //                            for (int j = 0; j <= field1.length - 1; j++) {
                    //                                String field2[] = field1[j].split(":");
                    //                                for (int k = 0; k < field2.length - 1; k++) {
                    //                                    Attr attr = doc1.createAttribute(field2[k]);
                    //                                    attr.setValue("" + field2[1]);
                    //                                    element1.setAttributeNode(attr);
                    //                                }
                    //                            }
                    //                        }

                    // write the content into xml file
                    //                        TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    //                        Transformer transformer = transformerFactory.newTransformer();
                    //                        DOMSource source = new DOMSource(doc);
                    //                        StreamResult result = new StreamResult(new File(uploadPath +File.separator + layoutfilename + ".xml"));
                    //
                    //                        TransformerFactory transformerFactory1 = TransformerFactory.newInstance();
                    //                        Transformer transformer1 = transformerFactory1.newTransformer();
                    //                        DOMSource source1 = new DOMSource(doc1);
                    //                        StreamResult result1 = new StreamResult(new File(uploadPath +File.separator + mapperfilename + ".xml"));

                    // Output to console for testing
                    // StreamResult result = new StreamResult(System.out);
                    //                        transformer.transform(source, result);
                    //                        transformer1.transform(source1, result1);
                    //                        layout.addLayouts(organization_id , user_id, category_id, layoutfilename, mapperfilename, type_email, type_social);

                } else {
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }

                    int inStr = fileName.indexOf(".");
                    String Str = fileName.substring(0, inStr);

                    fileName = lookName + "_" + Str + ".png";
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    fi.write(storeFile);

                    out.println("Uploaded Filename: " + filePath + "<br>");
                }
            }
            //                look.addLooks(lookName, fileName);
            response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
            //                        request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp");
            //                        request_dispatcher.forward(request, response);
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:",
                getSqlMethodsInstance().error));
        out.println(getSqlMethodsInstance().error);
    } finally {
        out.close();
    }

}