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.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  w w w. j a v a2  s. c  o m
            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:edu.emory.cci.aiw.cvrg.eureka.servlet.JobSubmitServlet.java

private Long submitJob(HttpServletRequest request, Principal principal)
        throws FileUploadException, IOException, ClientException, ParseException {

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

    /*//from www  . j  av  a 2s .  c o  m
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(5 * 1024 * 1024); //5 MB
    /*
     * Set the temporary directory to store the uploaded files of size above threshold.
     */
    fileItemFactory.setRepository(this.tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    /*
     * Parse the request
     */
    List items = uploadHandler.parseRequest(request);
    Properties fields = new Properties();
    for (Iterator itr = items.iterator(); itr.hasNext();) {
        FileItem item = (FileItem) itr.next();
        /*
         * Handle Form Fields.
         */
        if (item.isFormField()) {
            fields.setProperty(item.getFieldName(), item.getString());
        }
    }

    JobSpec jobSpec = MAPPER.readValue(fields.getProperty("jobSpec"), JobSpec.class);

    for (Iterator itr = items.iterator(); itr.hasNext();) {
        FileItem item = (FileItem) itr.next();
        if (!item.isFormField()) {
            //Handle Uploaded files.
            log("Spreadsheet upload for user " + principal.getName() + ": Field Name = " + item.getFieldName()
                    + ", File Name = " + item.getName() + ", Content type = " + item.getContentType()
                    + ", File Size = " + item.getSize());
            if (item.getSize() > 0) {
                InputStream is = item.getInputStream();
                try {
                    this.servicesClient.upload(FilenameUtils.getName(item.getName()),
                            jobSpec.getSourceConfigId(), item.getFieldName(), is);
                    log("File '" + item.getName() + "' uploaded successfully");
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
            } else {
                log("File '" + item.getName() + "' ignored because it was zero length");
            }
        }
    }

    URI uri = this.servicesClient.submitJob(jobSpec);
    String uriStr = uri.toString();
    Long jobId = Long.valueOf(uriStr.substring(uriStr.lastIndexOf("/") + 1));
    log("Job " + jobId + " submitted for user " + principal.getName());
    return jobId;
}

From source file:gov.nih.nci.queue.servlet.FileUploadServlet.java

/**
 * *************************************************
 * URL: /upload doPost(): upload the files and other parameters
 *
 * @param request/*  w  w  w  .ja va 2  s .  co  m*/
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * **************************************************
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Create an object for JSON response.
    ResponseModel rm = new ResponseModel();
    // Set response type to json
    response.setContentType("application/json");
    PrintWriter writer = response.getWriter();

    // Get property values.
    // SOCcer related.
    final Double estimatedThreshhold = Double
            .valueOf(PropertiesUtil.getProperty("gov.nih.nci.soccer.computing.time.threshhold").trim());
    // FileUpload Settings.
    final String repositoryPath = PropertiesUtil.getProperty("gov.nih.nci.queue.repository.dir");
    final String strOutputDir = PropertiesUtil.getProperty("gov.nih.cit.soccer.output.dir").trim();
    final long fileSizeMax = 10000000000L; // 10G
    LOGGER.log(Level.INFO, "repository.dir: {0}, filesize.max: {1}, time.threshhold: {2}",
            new Object[] { repositoryPath, fileSizeMax, estimatedThreshhold });

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

    // Ensuring that the request is actually a file upload request.
    if (isMultipart) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //upload file dirctory. If it does not exist, create one.
        File f = new File(repositoryPath);
        if (!f.exists()) {
            f.mkdir();
        }
        // Set factory constraints
        // factory.setSizeThreshold(yourMaxMemorySize);
        // Configure a repository
        factory.setRepository(new File(repositoryPath));

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

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

            // Process the uploaded items
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();

                if (!item.isFormField()) { // Handle file field.
                    String fileName = item.getName();
                    rm.setFileName(fileName);
                    String contentType = item.getContentType();
                    rm.setFileType(contentType);
                    long sizeInBytes = item.getSize();
                    rm.setFileSize(String.valueOf(sizeInBytes));

                    String inputFileId = new UniqueIdUtil(fileName).getInputUniqueID();
                    rm.setInputFileId(inputFileId);
                    String absoluteInputFileName = repositoryPath + File.separator + inputFileId;
                    rm.setRepositoryPath(repositoryPath);

                    // Write file to the destination folder.
                    File inputFile = new File(absoluteInputFileName);
                    item.write(inputFile);

                    // Validation.
                    InputFileValidator validator = new InputFileValidator();
                    List<String> validationErrors = validator.validateFile(inputFile);

                    if (validationErrors == null) { // Pass validation
                        // check estimatedProcessingTime.
                        SoccerServiceHelper soccerHelper = new SoccerServiceHelper(strOutputDir);
                        Double estimatedTime = soccerHelper.getEstimatedTime(absoluteInputFileName);
                        rm.setEstimatedTime(String.valueOf(estimatedTime));
                        if (estimatedTime > estimatedThreshhold) { // STATUS: QUEUE (Ask client for email)
                            // Construct Response String in JSON format.
                            rm.setStatus("queue");
                        } else { // STATUS: PASS (Ask client to confirm calculate)
                            // all good. Process the output and Go to result page directly.
                            rm.setStatus("pass");
                        }
                    } else { // STATUS: FAIL // Did not pass validation.
                        // Construct Response String in JSON format.
                        rm.setStatus("invalid");
                        rm.setDetails(validationErrors);
                    }
                } else {
                    // TODO: Handle Form Fields such as SOC_SYSTEM.
                } // End of isFormField
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "FileUploadException or FileNotFoundException. Error Message: {0}",
                    new Object[] { e.getMessage() });
            rm.setStatus("fail");
            rm.setErrorMessage(
                    "Oops! We met with problems when uploading your file. Error Message: " + e.getMessage());
        }

        // Send the response.
        ObjectMapper jsonMapper = new ObjectMapper();
        LOGGER.log(Level.INFO, "Response: {0}", new Object[] { jsonMapper.writeValueAsString(rm) });
        // Generate metadata file
        new MetadataFileUtil(rm.getInputFileId(), repositoryPath)
                .generateMetadataFile(jsonMapper.writeValueAsString(rm));
        // Responde to the client.
        writer.print(jsonMapper.writeValueAsString(rm));

    } else { // The request is NOT actually a file upload request
        writer.print("You hit the wrong file upload page. The request is NOT actually a file upload request.");
    }
}

From source file:kotys.monika.MenuCreatorJSP.LoadData.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w  w  w  .  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
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Check that we have a file upload request
    request.setCharacterEncoding("UTF-8");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    ArrayList<String> files = new ArrayList<String>();

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

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

            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadFolder + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                // saves the file to upload directory
                item.write(uploadedFile);
                files.add(filePath);
            }
        }

        // displays done.jsp page after upload finished
        request.getSession().setAttribute("uploadedFiles", files);
        processRequest(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        Logger.getLogger(LoadData.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:edu.uniminuto.servlets.GuardarDisco.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w ww  . jav  a 2s.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 {

    String nombre = "";
    long precio = 0;
    int anhio = 0;
    short genero = 1;
    int interprete = 1;

    //        String nombre = getParameter(request, "nombre");
    //        long precio = Long.valueOf(getParameter(request, "precio"));
    //        int anhio = Integer.valueOf(getParameter(request, "anhio"));
    //
    //        int genero = Integer.valueOf(getParameter(request, "genero"));
    //        int interprete = Integer.valueOf(getParameter(request, "interprete"));

    String url = "";
    try {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        String imagen = "images/";

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 4, new File("c;//tmp"));

        // 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");
        factory.setRepository(repository);

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

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                if (item.getFieldName().equals("nombre")) {
                    nombre = item.getString();
                } else if (item.getFieldName().equals("anhio")) {
                    anhio = Integer.valueOf(item.getString());
                } else if (item.getFieldName().equals("genero")) {
                    genero = Short.valueOf(item.getString());
                } else if (item.getFieldName().equals("interprete")) {
                    interprete = Integer.valueOf(item.getString());
                } else if (item.getFieldName().equals("precio")) {
                    precio = Long.valueOf(item.getString());
                }

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

                //                    InputStream uploadedStream = item.getInputStream();
                //                    uploadedStream.close();
                //                    InputStream uploadedStream = item.getInputStream();
                //                    uploadedStream.close();
                imagen = imagen + fileName;
                File uploadedFile = new File(RUTA + fileName);

                item.write(uploadedFile);
                //                    } else {
                //                        
                //                    }
            }
        }

        java.util.Calendar cl = java.util.Calendar.getInstance();
        cl.set(anhio, 0, 0, 0, 0, 0);

        Disco disco = new Disco();
        disco.setGenero(generoFacade.find(genero));
        disco.setInterprete(interpreteFacade.find(interprete));
        disco.setNombre(nombre);
        disco.setImagen(imagen);
        disco.setAnhio(cl.getTime());

        discoFacade.create(disco);

        if (disco.getId() != null) {

            Discopropietario dp = new Discopropietario();
            dp.setDisco(disco);
            dp.setPropietario((Persona) request.getSession().getAttribute("usuario"));
            dp.setPrecio(precio);
            dp.setVendido(false);

            dpFacade.create(dp);

            url = "disco?id=" + disco.getId();

        } else {
            url = "fdisco?nombre=" + nombre + "&precio=" + precio + "&anhio=" + anhio + "&genero=" + genero
                    + "&interprete=" + interprete;
        }

    } catch (FileUploadException ex) {
        Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex);
    }

    response.sendRedirect(url);

}

From source file:graphvis.webui.servlets.UploadServlet.java

/**
  * This method receives POST from the index.jsp page and uploads file, 
  * converts into the correct format then places in the HDFS.
  *///from w  w  w.j a  v  a 2  s .c o m
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) {
        response.setStatus(403);
        return;
    }

    File tempDirFileObject = new File(Configuration.tempDirectory);

    // Create/remove temp folder
    if (tempDirFileObject.exists()) {
        FileUtils.deleteDirectory(tempDirFileObject);
    }

    // (Re-)create temp directory
    tempDirFileObject.mkdir();
    FileUtils.copyFile(
            new File(getServletContext()
                    .getRealPath("giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")),
            new File(Configuration.tempDirectory
                    + "/giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar"));
    FileUtils.copyFile(new File(getServletContext().getRealPath("dist-graphvis.jar")),
            new File(Configuration.tempDirectory + "/dist-graphvis.jar"));

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

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

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

    String fileName = "";
    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();
                String filePath = Configuration.tempDirectory + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                // saves the file to upload directory
                try {
                    item.write(uploadedFile);
                } catch (Exception ex) {
                    throw new ServletException(ex);
                }
            }
        }

        String fullFilePath = Configuration.tempDirectory + File.separator + fileName;

        String extension = FilenameUtils.getExtension(fullFilePath);

        // Load Files intoHDFS
        // (This is where we do the parsing.)
        loadIntoHDFS(fullFilePath, extension);

        getServletContext().setAttribute("fileName", new File(fullFilePath).getName());
        getServletContext().setAttribute("fileExtension", extension);

        // Displays fileUploaded.jsp page after upload finished
        getServletContext().getRequestDispatcher("/fileUploaded.jsp").forward(request, response);

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

}

From source file:com.glaf.base.utils.upload.FileUploadBackGroundServlet.java

/**
 * ?/*  w  w w  .j  a v a2  s.  c o m*/
 */
private void processFileUpload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String serviceKey = request.getParameter("serviceKey");
    if (serviceKey == null) {
        serviceKey = "global";
    }

    int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0);
    if (maxUploadSize == 0) {
        maxUploadSize = conf.getInt("upload.maxUploadSize", 10);// 10MB
    }
    maxUploadSize = maxUploadSize * FileUtils.MB_SIZE;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // ?
    factory.setSizeThreshold(204800);
    File tempDir = new File(getUploadDir() + "/temp");
    if (!tempDir.exists()) {
        tempDir.mkdir();
    }

    // ?
    factory.setRepository(tempDir);
    ServletFileUpload upload = new ServletFileUpload(factory);
    // ?
    upload.setFileSizeMax(maxUploadSize);
    // request
    upload.setSizeMax(maxUploadSize);
    upload.setProgressListener(new FileUploadListener(request));
    upload.setHeaderEncoding("UTF-8");
    // ???FileUploadStatus Bean
    FileMgmtFactory.saveStatusBean(request, initStatusBean(request));

    try {
        List<?> items = upload.parseRequest(request);
        // url
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {

                break;
            }
        }
        // 
        String uploadDir = com.glaf.base.utils.StringUtil.createDir(getUploadDir());
        // ?
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            // ?
            if (FileMgmtFactory.getStatusBean(request).getCancel()) {
                deleteUploadedFile(request);
                break;
            } else if (!item.isFormField() && item.getName().length() > 0) {
                logger.debug("" + item.getName());
                // ?
                String fileId = UUID32.getUUID();
                String path = uploadDir + FileUtils.sp + fileId;
                File uploadedFile = new File(new File(getUploadDir(), uploadDir), fileId);
                item.write(uploadedFile);
                // 
                FileUploadStatus satusBean = FileMgmtFactory.getStatusBean(request);
                FileInfo fileInfo = new FileInfo();
                fileInfo.setCreateDate(new Date());
                fileInfo.setFileId(fileId);
                fileInfo.setFile(uploadedFile);
                fileInfo.setFilename(FileUtils.getFilename(item.getName()));
                fileInfo.setSize(item.getSize());
                fileInfo.setPath(path);
                satusBean.getUploadFileUrlList().add(fileInfo);
                FileMgmtFactory.saveStatusBean(request, satusBean);
                Thread.sleep(500);
            }
        }

    } catch (FileUploadException ex) {
        uploadExceptionHandle(request, "?:" + ex.getMessage());
    } catch (Exception ex) {
        uploadExceptionHandle(request, "??:" + ex.getMessage());
    }
    String forwardURL = request.getParameter("forwardURL");
    if (StringUtils.isEmpty(forwardURL)) {
        forwardURL = "/others/attachment.do?method=showResult";
    }
    request.getRequestDispatcher(forwardURL).forward(request, response);
}

From source file:edu.fullerton.ldvservlet.Upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from   w  w w . j  av  a2  s .  c om*/
 * @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 {
    long startTime = System.currentTimeMillis();

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("This action requires a multipart form with a file attached.");
    }
    ServletSupport servletSupport;

    servletSupport = new ServletSupport();
    servletSupport.init(request, viewerConfig, false);

    // 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");
    factory.setRepository(repository);

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

    ImageTable imageTable;
    String viewServletPath = request.getContextPath() + "/view";

    try {
        imageTable = new ImageTable(servletSupport.getDb());
    } catch (SQLException ex) {
        String ermsg = "Image upload: can't access the Image table: " + ex.getClass().getSimpleName() + " "
                + ex.getLocalizedMessage();
        throw new ServletException(ermsg);
    }
    try {
        HashMap<String, String> params = new HashMap<>();
        ArrayList<Integer> uploadedIds = new ArrayList<>();

        Page vpage = servletSupport.getVpage();
        vpage.setTitle("Image upload");
        try {
            servletSupport.addStandardHeader(version);
            servletSupport.addNavBar();
        } catch (WebUtilException ex) {
            throw new ServerException("Adding nav bar after upload", ex);
        }

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        int cnt = items.size();
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                if (!value.isEmpty()) {
                    params.put(name, value);
                }
            }
        }
        for (FileItem item : items) {
            if (!item.isFormField()) {
                int imgId = addFile(item, params, vpage, servletSupport.getVuser().getCn(), imageTable);
                if (imgId != 0) {
                    uploadedIds.add(imgId);
                }
            }
        }
        if (!uploadedIds.isEmpty()) {
            showImages(vpage, uploadedIds, imageTable, viewServletPath);
        }
        servletSupport.showPage(response);
    } catch (FileUploadException ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:communicator.doMove.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// www  . ja  va  2  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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = null;
    JSONObject outputObject = new JSONObject();
    try {

        HashMap<String, String> bigItemIds = new HashMap<>();
        Iterator mIterator = bigItemIds.keySet().iterator();
        out = response.getWriter();
        // 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");
        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);

        final String moveId = UUID.randomUUID().toString();
        final MovesDb movesDb = new MovesDb();
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {

                System.out.println("Form field" + item.getString());

                bigItemIds = processFormField(new JSONObject(item.getString()), out, moveId, movesDb);
                mIterator = bigItemIds.keySet().iterator();
                System.out.println("ITEM ID SIZE " + bigItemIds.size());

            } else {
                //processUploadedFile(item);
                System.out.print("Photo Field");
                String key = (String) mIterator.next();
                File mFile = new File(bigItemIds.get(key));
                item.write(mFile);

            }
        }
        new Thread() {

            public void run() {
                pushMovetoMailQueue moveToMailQueue = new pushMovetoMailQueue();
                moveToMailQueue.pushMoveToMailQueue(movesDb);
            }
        }.start();
        outputObject = new JSONObject();
        try {
            outputObject.put(Constants.JSON_STATUS, Constants.JSON_SUCCESS);
            outputObject.put(Constants.JSON_MSG, Constants.JSON_GET_QUOTE);
        } catch (JSONException ex1) {
            Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1);
        }

        out.println(outputObject.toString());

    } catch (Exception ex) {

        outputObject = new JSONObject();
        try {
            outputObject.put(Constants.JSON_STATUS, Constants.JSON_FAILURE);
            outputObject.put(Constants.JSON_MSG, Constants.JSON_EXCEPTION);
        } catch (JSONException ex1) {
            Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1);
        }

        out.println(outputObject.toString());
        Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

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

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*  ww  w.  j  a  v a 2s .  co 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);
    }
}