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

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

Introduction

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

Prototype

public void setRepository(File repository) 

Source Link

Document

Sets the directory used to temporarily store files that are larger than the configured size threshold.

Usage

From source file:com.openhr.UploadFile.java

@Override
public ActionForward execute(ActionMapping map, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        writer.flush();/* ww w.  j  a  v  a2  s  . c o  m*/
        return map.findForward("masteradmin");
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

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

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

    try {
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);

                // saves the file on disk
                item.write(storeFile);

                // Read the file object contents and parse it and store it in the repos
                FileInputStream fstream = new FileInputStream(storeFile);
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;
                Company comp = null;
                Branch branch = null;
                Calendar currDtCal = Calendar.getInstance();

                // Zero out the hour, minute, second, and millisecond
                currDtCal.set(Calendar.HOUR_OF_DAY, 0);
                currDtCal.set(Calendar.MINUTE, 0);
                currDtCal.set(Calendar.SECOND, 0);
                currDtCal.set(Calendar.MILLISECOND, 0);

                Date now = currDtCal.getTime();

                //Read File Line By Line
                while ((strLine = br.readLine()) != null) {
                    System.out.print("Processing line - " + strLine);

                    String[] lineColumns = strLine.split(COMMA);

                    if (lineColumns.length < 16) {
                        br.close();
                        in.close();
                        fstream.close();
                        throw new Exception("The required columns are missing in the line - " + strLine);
                    }

                    // Format is - 
                    // CompID,BranchName,EmpID,EmpFullName,EmpNationalID,BankName,BankBranch,RoutingNo,AccountNo,NetPay,Currency,
                    // residenttype,TaxAmount,EmployerSS,EmployeeSS
                    if (comp == null || comp.getId() != Integer.parseInt(lineColumns[0])) {
                        List<Company> comps = CompanyFactory.findById(Integer.parseInt(lineColumns[0]));

                        if (comps != null && comps.size() > 0) {
                            comp = comps.get(0);
                        } else {
                            br.close();
                            in.close();
                            fstream.close();

                            throw new Exception("Unable to get the details of the company");
                        }

                        // Check for licenses
                        List<Licenses> compLicenses = LicenseFactory.findByCompanyId(comp.getId());
                        for (Licenses lis : compLicenses) {
                            if (lis.getActive() == 1) {
                                Date endDate = lis.getTodate();
                                if (!isLicenseActive(now, endDate)) {
                                    br.close();
                                    in.close();
                                    fstream.close();

                                    // License has expired and throw an error
                                    throw new Exception("License has expired");

                                    //TODO remove the below code and enable above
                                    /*List<Branch> branches = BranchFactory.findByCompanyId(comp.getId());
                                    String branchName = lineColumns[1];
                                    if(branches != null && !branches.isEmpty()) {
                                      for(Branch bb: branches) {
                                         if(branchName.equalsIgnoreCase(bb.getName())) {
                                            branch = bb;
                                            break;
                                         }
                                      }
                                              
                                      if(branch == null) {
                                         Branch bb = new Branch();
                                    bb.setName(branchName);
                                    bb.setAddress("NA");
                                    bb.setCompanyId(comp);
                                            
                                    BranchFactory.insert(bb);
                                            
                                    List<Branch> lbranches = BranchFactory.findByName(branchName);
                                    branch = lbranches.get(0);
                                      }
                                    }*/
                                    //TODO
                                } else {
                                    // License enddate is valid, so lets check the key.
                                    String compName = comp.getName();
                                    String licenseKeyStr = LicenseValidator.formStringToEncrypt(compName,
                                            endDate);
                                    if (LicenseValidator.encryptAndCompare(licenseKeyStr,
                                            lis.getLicensekey())) {
                                        // License key is valid, so proceed.
                                        List<Branch> branches = BranchFactory.findByCompanyId(comp.getId());
                                        String branchName = lineColumns[1];
                                        if (branches != null && !branches.isEmpty()) {
                                            for (Branch bb : branches) {
                                                if (branchName.equalsIgnoreCase(bb.getName())) {
                                                    branch = bb;
                                                    break;
                                                }
                                            }

                                            if (branch == null) {
                                                Branch bb = new Branch();
                                                bb.setName(branchName);
                                                bb.setAddress("NA");
                                                bb.setCompanyId(comp);

                                                BranchFactory.insert(bb);

                                                List<Branch> lbranches = BranchFactory.findByName(branchName);
                                                branch = lbranches.get(0);
                                            }
                                        }
                                        break;
                                    } else {
                                        br.close();
                                        in.close();
                                        fstream.close();

                                        throw new Exception("License is tampered. Contact Support.");
                                    }
                                }
                            }
                        }
                    }

                    // CompID,BranchName,EmpID,EmpFullName,EmpNationalID,DeptName,BankName,BankBranch,RoutingNo,AccountNo,NetPay,currency,TaxAmt,emprSS,empess,basesalary                       
                    CompanyPayroll compPayroll = new CompanyPayroll();
                    compPayroll.setBranchId(branch);
                    compPayroll.setEmployeeId(lineColumns[2]);
                    compPayroll.setEmpFullName(lineColumns[3]);
                    compPayroll.setEmpNationalID(lineColumns[4]);
                    compPayroll.setDeptName(lineColumns[5]);
                    compPayroll.setBankName(lineColumns[6]);
                    compPayroll.setBankBranch(lineColumns[7]);
                    compPayroll.setRoutingNo(lineColumns[8]);
                    compPayroll.setAccountNo(lineColumns[9]);
                    compPayroll.setNetPay(Double.parseDouble(lineColumns[10]));
                    compPayroll.setCurrencySym(lineColumns[11]);
                    compPayroll.setResidentType(lineColumns[12]);
                    compPayroll.setTaxAmount(Double.parseDouble(lineColumns[13]));
                    compPayroll.setEmprSocialSec(Double.parseDouble(lineColumns[14]));
                    compPayroll.setEmpeSocialSec(Double.parseDouble(lineColumns[15]));
                    compPayroll.setBaseSalary(Double.parseDouble(lineColumns[16]));
                    compPayroll.setProcessedDate(now);
                    CompanyPayrollFactory.insert(compPayroll);
                }

                //Close the input stream
                br.close();
                in.close();
                fstream.close();
            }
        }
        System.out.println("Upload has been done successfully!");
    } catch (Exception ex) {
        System.out.println("There was an error: " + ex.getMessage());
        ex.printStackTrace();
    }

    return map.findForward("MasterHome");
}

From source file:admin.controller.ServletAddCategories.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* ww w . java2 s  .  c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
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 {

        String uploadPath = AppConstants.ORG_CATEGORIES_HOME;

        // 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
                    field_name = fi.getFieldName();
                    if (field_name.equals("category_name")) {
                        category_name = fi.getString();
                    }
                    if (field_name.equals("organization")) {
                        organization_id = fi.getString();
                        uploadPath = uploadPath + File.separator + organization_id;
                    }

                } else {

                    field_name = fi.getFieldName();
                    file_name = fi.getName();
                    if (file_name != "") {
                        check = categories.checkAvailability(category_name, Integer.parseInt(organization_id));
                        if (check == false) {
                            File uploadDir = new File(uploadPath);
                            if (!uploadDir.exists()) {
                                uploadDir.mkdirs();
                            }

                            //we need to save file name directly
                            //                                int inStr = file_name.indexOf(".");
                            //                                String Str = file_name.substring(0, inStr);
                            //                                file_name = category_name + "_" + Str + ".jpeg";

                            file_name = category_name + "_" + file_name;
                            boolean isInMemory = fi.isInMemory();
                            long sizeInBytes = fi.getSize();

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

                            fi.write(storeFile);
                            categories.addCategories(Integer.parseInt(organization_id), category_name,
                                    file_name);

                            out.println("Uploaded Filename: " + filePath + "<br>");
                            response.sendRedirect(request.getContextPath() + "/admin/categories.jsp");
                        } else {
                            response.sendRedirect(
                                    request.getContextPath() + "/admin/categories.jsp?exist=exist");
                        }
                    }
                }
            }
            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, "Exception while adding categories", ex);
    } finally {
        out.close();
    }
}

From source file:admin.controller.ServletAddPersonality.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  w  w  .  ja va 2  s.  c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
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 {

        String uploadPath = AppConstants.BRAND_IMAGES_HOME;

        // 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("/tmp"));

            // 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
                    field_name = fi.getFieldName();
                    if (field_name.equals("brandname")) {
                        brand_name = fi.getString();
                    }
                    if (field_name.equals("look")) {
                        look_id = fi.getString();
                    }

                } else {
                    check = brand.checkAvailability(brand_name);

                    if (check == false) {
                        field_name = fi.getFieldName();
                        file_name = fi.getName();

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

                        //                                int inStr = file_name.indexOf(".");
                        //                                String Str = file_name.substring(0, inStr);
                        //                                file_name = brand_name + "_" + Str + ".jpeg";

                        file_name = brand_name + "_" + file_name;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

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

                        fi.write(storeFile);
                        brand.addBrands(brand_name, Integer.parseInt(look_id), file_name);

                        response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp");

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    } else {
                        response.sendRedirect(
                                request.getContextPath() + "/admin/brandpersonality.jsp?exist=exist");
                    }
                }
            }
            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, "", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
        }
    }

}

From source file:com.javaweb.controller.SuaTinTucServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from w  w  w. ja  v  a  2s  .co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ParseException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    //response.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();
    String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = "";
    int idloaitin = 0, idTK = 0, idtt = 0;

    TintucService tintucservice = new TintucService();

    //File upload
    String folderupload = getServletContext().getInitParameter("file-upload");
    String rootPath = getServletContext().getRealPath("/");
    filePath = rootPath + folderupload;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    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("C:\\Windows\\Temp\\"));

    // 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();

                //change file name
                fileName = FileService.ChangeFileName(fileName);

                // Write the file
                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);
                //                    out.println("Uploaded Filename: " + fileName + "<br>");
            }

            if (fi.isFormField()) {
                if (fi.getFieldName().equalsIgnoreCase("TieuDe")) {
                    TieuDe = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) {
                    NoiDung = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) {
                    ngaydang = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) {
                    GhiChu = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) {
                    idloaitin = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) {
                    idTK = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtt")) {
                    idtt = Integer.parseInt(fi.getString("UTF-8"));
                }
            }
        }

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

    Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang);

    Tintuc tt = tintucservice.GetTintucID(idtt);

    tt.setIdTaiKhoan(idTK);
    tt.setTieuDe(TieuDe);
    tt.setNoiDung(NoiDung);
    tt.setNgayDang(NgayDang);
    tt.setGhiChu(GhiChu);
    if (!fileName.equals("")) {
        if (tt.getImgLink() != null) {
            if (!tt.getImgLink().equals(fileName)) {
                tt.setImgLink(fileName);
            }
        } else {
            tt.setImgLink(fileName);
        }
    }

    boolean rs = tintucservice.InsertTintuc(tt);
    if (rs) {
        session.setAttribute("kiemtra", "1");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    } else {
        session.setAttribute("kiemtra", "0");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    }

    //        try (PrintWriter out = response.getWriter()) {
    //            /* TODO output your page here. You may use following sample code. */
    //            out.println("<!DOCTYPE html>");
    //            out.println("<html>");
    //            out.println("<head>");
    //            out.println("<title>Servlet SuaTinTucServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet SuaTinTucServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:com.jkingii.web.files.upload.java

/**
 * Processes requests for both HTTP/*from  w  w w. j a  v a 2s  .  c  om*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    FileDataBase fdb = null;
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        CSession cSession = (CSession) request.getSession().getAttribute("cSession");

        if (!isMultipart) {
            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>");
            return;
        }

        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(tempDir));

        // 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);

        // Se verifica si el usuario tiene permisos de escritura.
        ColumnasPermisos permiso = checkPermisos(request, fileItems, out);
        if (permiso == null) {
            return;
        }

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

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            MessageDigest md5 = MessageDigest.getInstance("MD5");

            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                logger.info("Prosess Request: obteniendo session: [" + cSession + "] jsessionid = ["
                        + request.getSession().getId() + "]", this);
                fdb = new FileDataBase(GenKey.newKey(), cSession.getAccessInfo().getEmpresa(),
                        cSession.getAccessInfo().getUserInfo(), new Date().getTime(), fi.getName(),
                        new MimeType().factory().getMime(fi.getName(), fi.get()), fi.get(),
                        Hexadecimal.getHex(md5.digest(fi.get())), fi.getSize(), permiso);
                fileDataBaseFacade.create(fdb);
            }
        }
        ResponseConfig config = new ResponseConfig();
        config.setTimeZone(cSession.getAccessInfo().getTimeZone());
        out.println(fdb.toJson(config));
    } catch (FileUploadException | NoSuchAlgorithmException e) {
        logger.error("Error cargando el fichero en el servidor, " + "Exception: {}", e.getMessage());
    } catch (UnknownColumnException e) {
        logger.error("Imposible la columna para el link debe existir referer[{}], " + "p[{}]",
                request.getHeader("referer"), request.getParameter(PERMISO_FIELD));
        logger.debug("referrer: " + request.getHeader("referrer"));
    } finally {
        out.close();
    }
}

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

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*from  ww w .j  a  v a  2 s.  c om*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.info("Post verify request");

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

    StatisticEvent statisticEvent = new StatisticEvent();
    statisticEvent.setStartNow();
    statisticEvent.setSource(Source.WEB);
    statisticEvent.setOperation(Operation.VERIFY);
    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(THRESHOLD_SIZE);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE);

            // 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");
        }

        doVerify(request, response, filecontent, statisticEvent);
    } catch (Throwable 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);

        logger.warn("Generic Error: ", e);
        PdfAsHelper.setSessionException(request, response, e.getMessage(), e);
        PdfAsHelper.gotoError(getServletContext(), request, response);
    }
}

From source file:com.fatih.edu.tr.NewTaskServlet.java

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

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;//from w ww. j  a  va  2  s. c o m
    }

    // 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 uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

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

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

    TaskDao taskDao = new TaskDao();
    String title = "";
    String description = "";
    String due_date = "";
    String fileName = "";
    String filePath = "";
    //taskDao.addTask(title, description, due_date, "testfile","testdizi",1);

    try {
        // Parse the request
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {

            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                fileName = new File(item.getName()).getName();
                filePath = uploadFolder + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                item.write(uploadedFile);
            } else {
                String fieldname = item.getFieldName();
                String fieldvalue = item.getString();
                if (fieldname.equals("title")) {
                    title = item.getString();
                } else if (fieldname.equals("description")) {
                    description = item.getString();

                } else if (fieldname.equals("due_date")) {
                    due_date = item.getString();
                } else {
                    System.out.println("Something goes wrong in form");
                }
            }

        }
        taskDao.addTask(title, description, due_date, fileName, filePath, 1);
        // displays done.jsp page after upload finished
        getServletContext().getRequestDispatcher("/done.jsp").forward(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}

From source file:controller.uploadProductController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   ww  w.  ja va 2 s.  c  o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    String userPath = request.getServletPath();
    if (userPath.equals("/uploadProduct")) {
        boolean success = true;
        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // sets temporary location to store files
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

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

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // constructs the directory path to store upload file
        // this path is relative to application's directory
        String uploadPath = getServletContext().getInitParameter("upload.location");
        //creates a HashMap of all inputs
        HashMap hashMap = new HashMap();
        String productId = UUID.randomUUID().toString();
        try {
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    File file = new File(item.getName());
                    File file2 = new File(productId + ".jpg");
                    String filePath = uploadPath + File.separator + file.getName();
                    // saves the file on disk
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    File rename = new File(filePath);
                    boolean flag = rename.renameTo(file2);
                } else {
                    hashMap.put(item.getFieldName(), item.getString());
                }
            }
        } catch (FileUploadException ex) {
            Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", ex.getMessage());
            success = false;
        } catch (Exception ex) {
            Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", ex.getMessage());
            success = false;
        }
        String owner = (String) session.getAttribute("customerEmail");
        if (owner == null) {
            owner = "shop";
        }

        String pName = hashMap.get("pName").toString();
        String mNo = hashMap.get("mNo").toString();
        String brand = hashMap.get("brand").toString();
        String description = hashMap.get("description").toString();
        String quantity = hashMap.get("quantity").toString();
        String price = hashMap.get("price").toString();
        String addInfo = hashMap.get("addInfo").toString();
        int categoryId = Integer.parseInt(hashMap.get("category").toString());

        ProductDAO productDAO = new ProductDAOImpl();
        Product product;

        try {
            double priceDouble = Double.parseDouble(price);
            int quantityInt = Integer.parseInt(quantity);
            Category category = (new CategoryDAOImpl()).getCategoryFromID(categoryId);
            if (owner.equals("shop")) {
                product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand,
                        description, addInfo, true, true, owner);
            } else {
                product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand,
                        description, addInfo, false, false, owner);
            }

            if (!(productDAO.addProduct(product, category.getName()))) {
                throw new Exception("update unsuccessful");
            }
        } catch (Exception e) {
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", e.getMessage());
            success = false;
        }

        request.setAttribute("pName", pName);
        request.setAttribute("mNo", mNo);
        request.setAttribute("brand", brand);
        request.setAttribute("description", description);
        request.setAttribute("quantity", quantity);
        request.setAttribute("price", price);
        request.setAttribute("addInfo", addInfo);
        request.setAttribute("categoryId", categoryId);
        request.setAttribute("success", success);
        if (success == true) {
            request.setAttribute("error", false);
            request.setAttribute("errorMessage", null);
        }
        String url;
        if (owner.equals("shop")) {
            url = "/WEB-INF/view/adminAddProducts.jsp";
        } else {
            url = "/WEB-INF/view/clientSideView/addRecycleProduct.jsp";
        }
        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (ServletException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}

From source file:dk.cphbusiness.codecheck.web.Upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request// www  .  ja  v  a  2  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 processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        String name = paramNames.nextElement();
        String value = request.getParameter(name);
        System.out.println(name + ": " + value);
    }
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        try (PrintWriter out = response.getWriter()) {
            out.println("Error: not a multipart request.");
            return;
        }
    }

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

    // Configure a repository (to ensure a secure temp location is used)
    //ServletContext servletContext = this.getServletConfig().getServletContext();
    //File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    File repository = new File(Config.UPLOAD_FOLDER);
    factory.setRepository(repository);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    int taskID = -1;
    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        FileItem ft = null;
        for (FileItem item : items) {
            if (item.isFormField()) {
                if ("TaskID".equals(item.getFieldName())) {
                    taskID = Integer.parseInt(item.getString());
                }
            } else {
                ft = item;
            }
        }
        if (taskID > 0 && ft != null) {
            int reportID = DBUtil.createReport(taskID);
            String fileName = "HandIn_" + reportID + ".jar";
            ft.write(new File(Config.UPLOAD_FOLDER + fileName));
            Task task = DBUtil.getTask(taskID);
            CodeChecker codeChecker = new CodeChecker(reportID, task, fileName);
            Thread t = new Thread(codeChecker);
            t.start();
            //codeChecker.run();
            response.sendRedirect("/CodeCheckWeb/ShowReport?ReportID=" + reportID);
        }
    } catch (FileUploadException ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:admin.controller.ServletChangeLooks.java

/**
  * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
  * methods./*from   w  ww .j  a  va2 s  . c  o m*/
  *
  * @param request servlet request
  * @param response servlet response
  * @throws ServletException if a servlet-specific error occurs
  * @throws IOException if an I/O error occurs
  */
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();
    String filePath = "";
    String fileName, fieldName, uploadPath, deletePath, file_name_to_delete = "", uploadPath1;
    Looks look;
    RequestDispatcher request_dispatcher;
    String lookname = "", lookid = "";
    Integer organization = 0;
    look = new Looks();
    boolean check = false;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        // 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("lookname")) {
                        lookname = fi.getString();
                    }
                    if (fieldName.equals("lookid")) {
                        lookid = fi.getString();
                    }
                    if (fieldName.equals("organization")) {
                        organization = Integer.parseInt(fi.getString());
                    }
                    file_name_to_delete = look.getFileName(Integer.parseInt(lookid));
                } else {

                    check = look.checkAvailabilities(Integer.parseInt(lookid), lookname, organization);

                    if (check == false) {

                        fieldName = fi.getFieldName();
                        fileName = fi.getName();

                        File uploadDir = new File(AppConstants.LOOK_IMAGES_HOME);

                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                            int inStr = fileName.indexOf(".");
                        //                            String Str = fileName.substring(0, inStr);
                        //
                        //                            fileName = lookname + "_" + Str + ".png";
                        fileName = lookname + "_" + fileName;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String file_path = AppConstants.LOOK_IMAGES_HOME + File.separator + fileName;
                        String delete_path = AppConstants.LOOK_IMAGES_HOME + File.separator
                                + file_name_to_delete;
                        File deleteFile = new File(delete_path);
                        deleteFile.delete();
                        File storeFile = new File(file_path);
                        fi.write(storeFile);
                        out.println("Uploaded Filename: " + filePath + "<br>");
                        look.changeLooks(Integer.parseInt(lookid), lookname, fileName, organization);
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
                    } else {
                        response.sendRedirect(
                                request.getContextPath() + "/admin/editlook.jsp?exist=exist&look_id=" + lookid
                                        + "&look_name=" + lookname + "&organization_id=" + organization
                                        + "&image_file_name=" + file_name_to_delete);
                    }
                }
            }
            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, "Exception while editing the looks", ex);
    } finally {
        out.close();
    }

}