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

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

Introduction

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

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:com.funambol.json.coredb.CoreDBServlet.java

private void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String action = null;//from   www. j av a2 s .  c  o m
    String result = null;
    if (isMultipart) {
        Map<String, String> parameters = new HashMap<String, String>();
        Map<String, File> files = new HashMap<String, File>();

        try {
            // manageUpload(request, parameters, files);
        } catch (Exception ex) {
            writeError(ex, response, "Managing multi part form.");
        }

        action = parameters.get(ACTION);
        try {
            log.info("Handling multi request action [" + action + "]");
            result = doAction(parameters, files, action);
        } catch (Exception ex) {
            writeError(ex, response, action);
        }

    } else {

        try {
            log.info("Handling action [" + action + "]");
            action = getAction(request);
        } catch (Exception ex) {
            log.warn("No action found, performing default operation.");
        }

        try {
            result = doAction(request, action);
        } catch (Exception ex) {
            writeError(ex, response, action);
        }
    }
    sendHtmlPage(response, result);
}

From source file:com.ephesoft.gxt.foldermanager.server.UploadDownloadFilesServlet.java

private void uploadFile(HttpServletRequest req, HttpServletResponse resp, String currentBatchUploadFolderName)
        throws IOException {

    PrintWriter printWriter = resp.getWriter();
    File tempFile = null;/*from w  w w  . j  ava 2s  .  c  om*/
    InputStream instream = null;
    OutputStream out = null;
    String uploadFileName = "";
    try {
        if (ServletFileUpload.isMultipartContent(req)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            uploadFileName = "";
            String uploadFilePath = "";
            List<FileItem> items;
            try {
                items = upload.parseRequest(req);
                for (FileItem item : items) {
                    if (!item.isFormField()) {
                        uploadFileName = item.getName();
                        if (uploadFileName != null) {
                            uploadFileName = uploadFileName
                                    .substring(uploadFileName.lastIndexOf(File.separator) + 1);
                        }
                        uploadFilePath = currentBatchUploadFolderName + File.separator + uploadFileName;
                        try {
                            instream = item.getInputStream();
                            tempFile = new File(uploadFilePath);

                            out = new FileOutputStream(tempFile);
                            byte buf[] = new byte[1024];
                            int len;
                            while ((len = instream.read(buf)) > 0) {
                                out.write(buf, 0, len);
                            }
                        } catch (FileNotFoundException e) {
                            printWriter.write("Unable to create the upload folder.Please try again.");

                        } catch (IOException e) {
                            printWriter.write("Unable to read the file.Please try again.");
                        } finally {
                            if (out != null) {
                                out.close();
                            }
                            if (instream != null) {
                                instream.close();
                            }
                        }
                    }
                }
            } catch (FileUploadException e) {
                printWriter.write("Unable to read the form contents.Please try again.");
            }

        } else {
            printWriter.write("Request contents type is not supported.");
        }
        printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName);
        printWriter.append("|");

        printWriter.append("fileName:").append(uploadFileName);
        printWriter.append("|");
    } finally {
        printWriter.flush();
        printWriter.close();
    }
}

From source file:dk.clarin.tools.rest.register.java

public String getargs(HttpServletRequest request, List<FileItem> items) {
    String arg = "";
    /*/*  www . ja  va2  s .c o m*/
    * Parse the request
    */

    @SuppressWarnings("unchecked")
    Enumeration<String> parmNames = (Enumeration<String>) request.getParameterNames();
    boolean is_multipart_formData = ServletFileUpload.isMultipartContent(request);

    logger.debug("is_multipart_formData:" + (is_multipart_formData ? "ja" : "nej"));

    if (is_multipart_formData) {
        try {
            Iterator<FileItem> itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    arg = arg + " (" + workflow.quote(item.getFieldName()) + "."
                            + workflow.quote(item.getString("UTF-8").trim()) + ")";
                }
            }
        } catch (Exception ex) {
            logger.error("uploadHandler.parseRequest Exception");
        }
    }

    for (Enumeration<String> e = parmNames; e.hasMoreElements();) {
        String parmName = e.nextElement();
        arg = arg + " (" + workflow.quote(parmName) + ".";
        String vals[] = request.getParameterValues(parmName);
        for (int j = 0; j < vals.length; ++j) {
            arg += " " + workflow.quote(vals[j]) + "";
        }
        arg += ")";
    }
    logger.debug("arg = [" + arg + "]");
    return arg;
}

From source file:it.unipmn.di.dcs.sharegrid.web.servlet.MultipartRequestWrapper.java

/** Performs initializations stuff. */
@SuppressWarnings("unchecked") // ServletFileUpload#parseRequest() does not return generic type.
private void init(HttpServletRequest request, long maxSize, long maxFileSize, int thresholdSize,
        String repositoryPath) {/*from   www . j ava  2 s. c o  m*/
    if (!ServletFileUpload.isMultipartContent(request)) {
        String errorText = "Content-Type is not multipart/form-data but '" + request.getContentType() + "'";

        MultipartRequestWrapper.Log.severe(errorText);

        throw new FacesException(errorText);
    } else {
        this.params = new HashMap<String, String[]>();
        this.fileItems = new HashMap<String, FileItem>();

        DiskFileItemFactory factory = null;
        ServletFileUpload upload = null;

        //factory = new DiskFileItemFactory();
        factory = MultipartRequestWrapper.CreateDiskFileItemFactory(request.getSession().getServletContext(),
                thresholdSize, new File(repositoryPath));
        //factory.setRepository(new File(repositoryPath));
        //factory.setSizeThreshold(thresholdSize);

        upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxSize);
        upload.setFileSizeMax(maxFileSize);

        String charset = request.getCharacterEncoding();
        if (charset != null) {
            charset = ServletConstants.DefaultCharset;
        }
        upload.setHeaderEncoding(charset);

        List<FileItem> itemList = null;
        try {
            //itemList = (List<FileItem>) upload.parseRequest(request);
            itemList = (List<FileItem>) upload.parseRequest(request);
        } catch (FileUploadException fue) {
            MultipartRequestWrapper.Log.severe(fue.getMessage());
            throw new FacesException(fue);
        } catch (ClassCastException cce) {
            // This shouldn't happen!
            MultipartRequestWrapper.Log.severe(cce.getMessage());
            throw new FacesException(cce);
        }

        MultipartRequestWrapper.Log.fine("parametercount = " + itemList.size());

        for (FileItem item : itemList) {
            String key = item.getFieldName();

            //            {
            //               String value = item.getString();
            //               if (value.length() > 100) {
            //                  value = value.substring(0, 100) + " [...]";
            //               }
            //               MultipartRequestWrapper.Log.fine(
            //                  "Parameter : '" + key + "'='" + value + "' isFormField="
            //                  + item.isFormField() + " contentType='" + item.getContentType() + "'"
            //               );
            //            }
            if (item.isFormField()) {
                Object inStock = this.params.get(key);
                if (inStock == null) {
                    String[] values = null;
                    try {
                        // TODO: enable configuration of  'accept-charset'
                        values = new String[] { item.getString(ServletConstants.DefaultCharset) };
                    } catch (UnsupportedEncodingException uee) {
                        MultipartRequestWrapper.Log.warning("Caught: " + uee);

                        values = new String[] { item.getString() };
                    }
                    this.params.put(key, values);
                } else if (inStock instanceof String[]) {
                    // two or more parameters
                    String[] oldValues = (String[]) inStock;
                    String[] values = new String[oldValues.length + 1];

                    int i = 0;
                    while (i < oldValues.length) {
                        values[i] = oldValues[i];
                        i++;
                    }

                    try {
                        // TODO: enable configuration of  'accept-charset'
                        values[i] = item.getString(ServletConstants.DefaultCharset);
                    } catch (UnsupportedEncodingException uee) {
                        MultipartRequestWrapper.Log.warning("Caught: " + uee);

                        values[i] = item.getString();
                    }
                    this.params.put(key, values);
                } else {
                    MultipartRequestWrapper.Log
                            .severe("Program error. Unsupported class: " + inStock.getClass().getName());
                }
            } else {
                //String fieldName = item.getFieldName();
                //String fileName = item.getName();
                //String contentType = item.getContentType();
                //boolean isInMemory = item.isInMemory();
                //long sizeInBytes = item.getSize();
                //...
                this.fileItems.put(key, item);
            }
        }
    }
}

From source file:Controller.ControllerCustomers.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// w ww .ja  va  2  s  .co 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 {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    String username = (String) params.get("txtusername");
                    String password = (String) params.get("txtpassword");
                    String hoten = (String) params.get("txthoten");
                    String gioitinh = (String) params.get("txtgioitinh");
                    String email = (String) params.get("txtemail");
                    String role = (String) params.get("txtrole");
                    String anh = (String) params.get("txtanh");
                    //Update  product
                    if (fileName.equals("")) {

                        Customer Cus = new Customer(username, password, hoten, gioitinh, email, role, anh);
                        CustomerDAO.SuaThongTinKhachHang(Cus);
                        RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
                        rd.forward(request, response);

                    } else {
                        // bat dau ghi file
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                        //ket thuc ghi

                        Customer Cus = new Customer(username, password, hoten, gioitinh, email, role,
                                "upload\\" + fileName);
                        CustomerDAO.SuaThongTinKhachHang(Cus);

                        RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
                        rd.forward(request, response);
                    }

                } catch (Exception e) {
                    System.out.println(e);
                    RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp");
                    rd.forward(request, response);
                }
            }

        }
    }

}

From source file:com.glaf.core.web.servlet.FileUploadServlet.java

public void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html;charset=UTF-8");
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    if (loginContext == null) {
        return;//from www  . j  a v  a2 s.com
    }
    String serviceKey = request.getParameter("serviceKey");
    String type = request.getParameter("type");
    if (StringUtils.isEmpty(type)) {
        type = "0";
    }
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap:" + paramMap);
    String rootDir = SystemProperties.getConfigRootPath();

    InputStream inputStream = null;
    try {
        DiskFileItemFactory diskFactory = new DiskFileItemFactory();
        // threshold ???? 8M
        diskFactory.setSizeThreshold(8 * FileUtils.MB_SIZE);
        // repository 
        diskFactory.setRepository(new File(rootDir + "/temp"));
        ServletFileUpload upload = new ServletFileUpload(diskFactory);
        int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0);
        if (maxUploadSize == 0) {
            maxUploadSize = conf.getInt("upload.maxUploadSize", 50);// 50MB
        }
        maxUploadSize = maxUploadSize * FileUtils.MB_SIZE;
        logger.debug("maxUploadSize:" + maxUploadSize);

        upload.setHeaderEncoding("UTF-8");
        upload.setSizeMax(maxUploadSize);
        upload.setFileSizeMax(maxUploadSize);
        String uploadDir = Constants.UPLOAD_PATH;

        if (ServletFileUpload.isMultipartContent(request)) {
            logger.debug("#################start upload process#########################");
            FileItemIterator iter = upload.getItemIterator(request);
            PrintWriter out = response.getWriter();
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    // ????
                    String autoCreatedDateDirByParttern = "yyyy/MM/dd";
                    String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(),
                            autoCreatedDateDirByParttern);

                    File savePath = new File(rootDir + uploadDir + autoCreatedDateDir);
                    if (!savePath.exists()) {
                        savePath.mkdirs();
                    }

                    String fileId = UUID32.getUUID();
                    String fileName = savePath + "/" + fileId;

                    BlobItem dataFile = new BlobItemEntity();
                    dataFile.setLastModified(System.currentTimeMillis());
                    dataFile.setCreateBy(loginContext.getActorId());
                    dataFile.setFileId(fileId);
                    dataFile.setPath(uploadDir + autoCreatedDateDir + "/" + fileId);
                    dataFile.setFilename(item.getName());
                    dataFile.setName(item.getName());
                    dataFile.setContentType(item.getContentType());
                    dataFile.setType(type);
                    dataFile.setStatus(0);
                    dataFile.setServiceKey(serviceKey);
                    getBlobService().insertBlob(dataFile);

                    inputStream = item.openStream();

                    FileUtils.save(fileName, inputStream);

                    logger.debug(fileName + " save ok.");

                    out.print(fileId);
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        IOUtils.close(inputStream);
    }
}

From source file:com.ikon.servlet.admin.ReportServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = "";
    String userId = request.getRemoteUser();
    updateSessionManager(request);/*from  ww w .java  2 s.  c o m*/

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Report rp = new Report();

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("rp_id")) {
                        rp.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("rp_name")) {
                        rp.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("rp_active")) {
                        rp.setActive(true);
                    }
                } else {
                    is = item.getInputStream();
                    rp.setFileName(FilenameUtils.getName(item.getName()));
                    rp.setFileMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    rp.setFileContent(SecureStore.b64Encode(IOUtils.toByteArray(is)));
                    is.close();
                }
            }

            if (action.equals("create")) {
                long id = ReportDAO.create(rp);

                // Activity log
                UserActivity.log(userId, "ADMIN_REPORT_CREATE", Long.toString(id), null, rp.toString());
                list(userId, request, response);
            } else if (action.equals("edit")) {
                Report tmp = ReportDAO.findByPk(rp.getId());
                tmp.setActive(rp.isActive());
                tmp.setFileContent(rp.getFileContent());
                tmp.setFileMime(rp.getFileMime());
                tmp.setFileName(rp.getFileName());
                tmp.setName(rp.getName());
                ReportDAO.update(tmp);

                // Activity log
                UserActivity.log(userId, "ADMIN_REPORT_EDIT", Long.toString(rp.getId()), null, rp.toString());
                list(userId, request, response);
            } else if (action.equals("delete")) {
                ReportDAO.delete(rp.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_REPORT_DELETE", Long.toString(rp.getId()), null, null);
                list(userId, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:com.ephesoft.dcma.gwt.admin.bm.server.ImportBatchClassUploadServlet.java

private void attachFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService,
        DeploymentService deploymentService, BatchClassService bcService, ImportBatchService imService)
        throws IOException {
    PrintWriter printWriter = resp.getWriter();
    File tempZipFile = null;//from   w w w  .j  a va 2  s .  com
    InputStream instream = null;
    OutputStream out = null;
    String zipWorkFlowName = BatchClassManagementConstants.EMPTY_STRING,
            tempOutputUnZipDir = BatchClassManagementConstants.EMPTY_STRING,
            systemFolderPath = BatchClassManagementConstants.EMPTY_STRING;
    BatchClass importBatchClass = null;
    if (ServletFileUpload.isMultipartContent(req)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();
        File exportSerailizationFolder = new File(exportSerailizationFolderPath);
        if (!exportSerailizationFolder.exists()) {
            exportSerailizationFolder.mkdir();
        }
        String zipFileName = BatchClassManagementConstants.EMPTY_STRING;
        String zipPathname = BatchClassManagementConstants.EMPTY_STRING;
        List<FileItem> items;
        try {
            items = (List<FileItem>) upload.parseRequest(req);
            for (FileItem item : items) {
                if (!item.isFormField() && "importFile".equals(item.getFieldName())) {
                    zipFileName = item.getName();
                    if (zipFileName != null) {
                        zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1);
                    }
                    zipPathname = exportSerailizationFolderPath + File.separator + zipFileName;
                    if (zipFileName != null) {
                        zipFileName = FilenameUtils.getName(zipFileName);
                    }
                    try {
                        instream = item.getInputStream();
                        tempZipFile = new File(zipPathname);
                        if (tempZipFile.exists()) {
                            tempZipFile.delete();
                        }
                        out = new FileOutputStream(tempZipFile);
                        byte buf[] = new byte[BatchClassManagementConstants.BUFFER_SIZE];
                        int len = instream.read(buf);
                        while ((len) > 0) {
                            out.write(buf, 0, len);
                            len = instream.read(buf);
                        }
                    } catch (FileNotFoundException e) {
                        LOG.error("Unable to create the export folder." + e, e);
                        printWriter.write("Unable to create the export folder.Please try again.");

                    } catch (IOException e) {
                        LOG.error("Unable to read the file." + e, e);
                        printWriter.write("Unable to read the file.Please try again.");
                    } finally {
                        IOUtils.closeQuietly(out);
                        IOUtils.closeQuietly(instream);
                    }
                }
            }
        } catch (FileUploadException e) {
            LOG.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
        }
        tempOutputUnZipDir = exportSerailizationFolderPath + File.separator
                + zipFileName.substring(0, zipFileName.lastIndexOf('.'));
        try {
            FileUtils.unzip(tempZipFile, tempOutputUnZipDir);
        } catch (Exception e) {
            LOG.error("Unable to unzip the file." + e, e);
            printWriter.write("Unable to unzip the file.Please try again.");
            tempZipFile.delete();
        }
        String serializableFilePath = FileUtils.getFileNameOfTypeFromFolder(tempOutputUnZipDir,
                SERIALIZATION_EXT);
        InputStream serializableFileStream = null;
        try {
            serializableFileStream = new FileInputStream(serializableFilePath);
            importBatchClass = (BatchClass) SerializationUtils.deserialize(serializableFileStream);
            zipWorkFlowName = importBatchClass.getName();
            systemFolderPath = importBatchClass.getSystemFolder();
            if (systemFolderPath == null) {
                systemFolderPath = BatchClassManagementConstants.EMPTY_STRING;
            }
        } catch (Exception e) {
            tempZipFile.delete();
            LOG.error("Error while importing" + e, e);
            printWriter.write("Error while importing.Please try again.");
        } finally {
            IOUtils.closeQuietly(serializableFileStream);
        }
    } else {
        LOG.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }
    if (tempZipFile != null) {
        tempZipFile.delete();
    }
    List<String> uncList = bcService.getAssociatedUNCList(zipWorkFlowName);
    boolean isWorkflowDeployed = deploymentService.isDeployed(zipWorkFlowName);
    boolean isWorkflowEqual = imService.isImportWorkflowEqualDeployedWorkflow(importBatchClass,
            importBatchClass.getName());
    printWriterMethod(printWriter, zipWorkFlowName, tempOutputUnZipDir, systemFolderPath, uncList,
            isWorkflowDeployed, isWorkflowEqual);
}

From source file:com.cognitivabrasil.repositorio.web.FileController.java

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody/*from  ww  w  .  j a v  a2 s .  c o  m*/
public String upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, org.apache.commons.fileupload.FileUploadException {
    if (file == null) {
        file = new Files();
        file.setSizeInBytes(0L);
    }

    Integer docId = null;
    String docPath = null;
    String responseString = RESP_SUCCESS;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        try {
            ServletFileUpload x = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> items = x.parseRequest(request);

            for (FileItem item : items) {
                InputStream input = item.getInputStream();

                // Handle a form field.
                if (item.isFormField()) {
                    String attribute = item.getFieldName();
                    String value = Streams.asString(input);

                    switch (attribute) {
                    case "chunks":
                        this.chunks = Integer.parseInt(value);
                        break;
                    case "chunk":
                        this.chunk = Integer.parseInt(value);
                        break;
                    case "filename":
                        file.setName(value);
                        break;
                    case "docId":
                        if (value.isEmpty()) {
                            throw new org.apache.commons.fileupload.FileUploadException(
                                    "No foi informado o id do documento.");
                        }
                        docId = Integer.parseInt(value);
                        docPath = Config.FILE_PATH + "/" + docId;
                        File documentPath = new File(docPath);
                        // cria o diretorio
                        documentPath.mkdirs();

                        break;
                    default:
                        break;
                    }

                } // Handle a multi-part MIME encoded file.
                else {
                    try {

                        File uploadFile = new File(docPath, item.getName());
                        BufferedOutputStream bufferedOutput;
                        bufferedOutput = new BufferedOutputStream(new FileOutputStream(uploadFile, true));

                        byte[] data = item.get();
                        bufferedOutput.write(data);
                        bufferedOutput.close();
                    } catch (Exception e) {
                        LOG.error("Erro ao salvar o arquivo.", e);
                        file = null;
                        throw e;
                    } finally {
                        if (input != null) {
                            try {
                                input.close();
                            } catch (IOException e) {
                                LOG.error("Erro ao fechar o ImputStream", e);
                            }
                        }

                        file.setName(item.getName());
                        file.setContentType(item.getContentType());
                        file.setPartialSize(item.getSize());
                    }
                }
            }

            if ((this.chunk == this.chunks - 1) || this.chunks == 0) {
                file.setLocation(docPath + "/" + file.getName());
                if (docId != null) {
                    file.setDocument(documentsService.get(docId));
                }
                fileService.save(file);
                file = null;
            }
        } catch (org.apache.commons.fileupload.FileUploadException | IOException | NumberFormatException e) {
            responseString = RESP_ERROR;
            LOG.error("Erro ao salvar o arquivo", e);
            file = null;
            throw e;
        }
    } // Not a multi-part MIME request.
    else {
        responseString = RESP_ERROR;
    }

    response.setContentType("application/json");
    byte[] responseBytes = responseString.getBytes();
    response.setContentLength(responseBytes.length);
    ServletOutputStream output = response.getOutputStream();
    output.write(responseBytes);
    output.flush();
    return responseString;
}

From source file:com.aaasec.sigserv.csspserver.SpServlet.java

/**
 * Processes requests for both HTTP//w w w .j  a va 2 s .co m
 * <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 {

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");

    SpSession session = getSession(request, response);

    RequestModel req = reqFactory.getRequestModel(request, session);
    AuthData authdata = req.getAuthData();

    // Supporting devmode login
    if (SpModel.isDevmode()) {
        authdata = TestIdentities.getTestID(request, req);
        req.setAuthData(authdata);
        if (authdata.getAuthType().length() == 0) {
            authdata.setAuthType("devlogin");
        }
        session.setIdpEntityId(authdata.getIdpEntityID());
        session.setSignerAttribute(RequestModelFactory.getAttrOidString(authdata.getIdAttribute()));
        session.setSignerId(authdata.getId());
    }

    //Terminate if no valid request data
    if (req == null) {
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        response.getWriter().write("");
        return;
    }

    // Handle form post from web page
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        response.getWriter().write(SpServerLogic.processFileUpload(request, response, req));
        return;
    }

    // Handle auth data request 
    if (req.getAction().equals("authdata")) {
        response.setContentType("application/json");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write(gson.toJson(authdata));
        return;
    }

    // Get list of serverstored xml documents
    if (req.getAction().equals("doclist")) {
        response.setContentType("application/json");
        response.getWriter().write(SpServerLogic.getDocList());
        return;
    }

    // Provide info about the session for logout handling
    if (req.getAction().equals("logout")) {
        response.setContentType("application/json");
        Logout lo = new Logout();
        lo.authType = (request.getAuthType() == null) ? "" : request.getAuthType();
        lo.devmode = String.valueOf(SpModel.isDevmode());
        response.getWriter().write(gson.toJson(lo));
        return;
    }

    // Respons to a client alive check to test if the server session is alive
    if (req.getAction().equals("alive")) {
        response.setContentType("application/json");
        response.getWriter().write("[]");
        return;
    }

    // Handle sign request and return Xhtml form with post data to the signature server
    if (req.getAction().equals("sign")) {
        boolean addSignMessage = (req.getParameter().equals("message"));
        String xhtml = SpServerLogic.prepareSignRedirect(req, addSignMessage);
        response.getWriter().write(xhtml);
        return;
    }

    // Get status data about the current session
    if (req.getAction().equals("status")) {
        response.setContentType("application/json");
        response.getWriter().write(gson.toJson(session.getStatus()));
        return;
    }

    // Handle a declined sign request
    if (req.getAction().equals("declined")) {
        if (SpModel.isDevmode()) {
            response.sendRedirect("index.jsp?declined=true");
            return;
        }
        response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp?declined=true");
        return;
    }

    // Return Request and response data as a file.
    if (req.getAction().equalsIgnoreCase("getReqRes")) {
        response.setContentType("text/xml;charset=UTF-8");
        byte[] data = TestCases.getRawData(req);
        BufferedInputStream fis = new BufferedInputStream(new ByteArrayInputStream(data));
        ServletOutputStream output = response.getOutputStream();
        if (req.getParameter().equalsIgnoreCase("download")) {
            response.setHeader("Content-Disposition", "attachment; filename=" + req.getId() + ".xml");
        }

        int readBytes = 0;
        byte[] buffer = new byte[10000];
        while ((readBytes = fis.read(buffer, 0, 10000)) != -1) {
            output.write(buffer, 0, readBytes);
        }
        output.flush();
        output.close();
        fis.close();
        return;
    }

    // Return the signed document
    if (req.getAction().equalsIgnoreCase("getSignedDoc")
            || req.getAction().equalsIgnoreCase("getUnsignedDoc")) {
        // If the request if for a plaintext document, or only if the document has a valid signature
        if (session.getStatus().signedDocValid || req.getAction().equalsIgnoreCase("getUnsignedDoc")) {
            response.setContentType(session.getDocumentType().getMimeType());
            switch (session.getDocumentType()) {
            case XML:
                response.getWriter().write(new String(session.getSignedDoc(), Charset.forName("UTF-8")));
                return;
            case PDF:
                File docFile = session.getDocumentFile();
                if (req.getAction().equalsIgnoreCase("getSignedDoc") && session.getStatus().signedDocValid) {
                    docFile = session.getSigFile();
                }
                FileInputStream fis = new FileInputStream(docFile);
                ServletOutputStream output = response.getOutputStream();
                if (req.getParameter().equalsIgnoreCase("download")) {
                    response.setHeader("Content-Disposition", "attachment; filename=" + "signedPdf.pdf");
                }

                int readBytes = 0;
                byte[] buffer = new byte[10000];
                while ((readBytes = fis.read(buffer, 0, 10000)) != -1) {
                    output.write(buffer, 0, readBytes);
                }
                output.flush();
                output.close();
                fis.close();
                return;
            }
            return;
        } else {
            if (SpModel.isDevmode()) {
                response.sendRedirect("index.jsp");
                return;
            }
            response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp");
            return;
        }
    }

    // Process a sign response from the signature server
    if (req.getSigResponse().length() > 0) {
        try {
            byte[] sigResponse = Base64Coder.decode(req.getSigResponse().trim());

            // Handle response
            SpServerLogic.completeSignedDoc(sigResponse, req);

        } catch (Exception ex) {
        }
        if (SpModel.isDevmode()) {
            response.sendRedirect("index.jsp");
            return;
        }
        response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp");
        return;
    }

    // Handle testcases
    if (req.getAction().equals("test")) {
        boolean addSignMessage = (req.getParameter().equals("message"));
        String xhtml = TestCases.prepareTestRedirect(request, response, req, addSignMessage);
        respond(response, xhtml);
        return;
    }

    // Get test data for display such as request data, response data, certificates etc.
    if (req.getAction().equals("info")) {
        switch (session.getDocumentType()) {
        case PDF:
            File returnFile = null;
            if (req.getId().equalsIgnoreCase("document")) {
                respond(response, getDocIframe("getUnsignedDoc", needPdfDownloadButton(request)));
            }
            if (req.getId().equalsIgnoreCase("formSigDoc")) {
                respond(response, getDocIframe("getSignedDoc", needPdfDownloadButton(request)));
            }
            respond(response, TestCases.getTestData(req));
            return;
        default:
            respond(response, TestCases.getTestData(req));
            return;
        }
    }

    if (req.getAction().equals("verify")) {
        response.setContentType("text/xml;charset=UTF-8");
        String sigVerifyReport = TestCases.getTestData(req);
        if (sigVerifyReport != null) {
            respond(response, sigVerifyReport);
            return;
        }
    }

    nullResponse(response);
}