Example usage for org.apache.commons.fileupload FileItem getInputStream

List of usage examples for org.apache.commons.fileupload FileItem getInputStream

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getInputStream.

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:br.com.bluesoft.pronto.controller.SprintController.java

@SuppressWarnings("unchecked")
private byte[] getImageBytes(final HttpServletRequest request) throws FileUploadException, IOException {
    final FileItemFactory factory = new DiskFileItemFactory();
    final ServletFileUpload upload = new ServletFileUpload(factory);
    byte bytes[] = null;
    final List<FileItem> items = upload.parseRequest(request);
    for (final FileItem fileItem : items) {
        final InputStream inputStream = fileItem.getInputStream();
        final int numberBytes = inputStream.available();
        bytes = new byte[numberBytes];
        inputStream.read(bytes);/*from w w  w .j  ava  2s.co m*/
    }
    return bytes;
}

From source file:com.osbitools.ws.shared.prj.web.EntityUtilsMgrWsSrvServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from   w  w  w.ja va2s. c o m
        super.doPost(req, resp);
    } catch (ServletException e) {
        if (e.getCause().getClass().equals(WsSrvException.class)) {
            // Authentication failed
            checkSendError(req, resp, (WsSrvException) e.getCause());
            return;
        } else {
            throw e;
        }
    }

    // Get DsMap name
    String name = req.getParameter(PrjMgrConstants.REQ_NAME_PARAM);

    // Check if rename required

    try {
        if (!ServletFileUpload.isMultipartContent(req)) {
            checkSendError(req, resp, 200, "Request is not multipart");
            return;
        }

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(getDiskFileItemFactory(req));
        InputStream in = null;
        List<FileItem> items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            checkSendError(req, resp, 201, "Error parsing request", null, e);
            return;
        }

        for (FileItem fi : items) {
            if (!fi.isFormField()) {
                in = fi.getInputStream();
                break;
            }
        }

        if (in == null) {
            checkSendError(req, resp, 202, "File Multipart section is not found");
            return;
        }

        boolean minified = isMinfied(req);
        printJson(resp, "{" + Utils.getCRT(minified) + "\"entity\":" + Utils.getSPACE(minified)
                + getEntityUtils(req).create(getPrjRootDir(req), name, in, false, minified) + "}");
        in.close();
    } catch (WsSrvException e) {
        checkSendError(req, resp, e);
    }
}

From source file:Emporium.Controle.ContrVpne.java

public static String lerVpne(FileItem item, int idCli, int idDepto, String nomeDepto, String nomeBD)
        throws UnsupportedEncodingException, IOException {
    DecimalFormat df = new DecimalFormat("0.00");

    String ret = "";

    String r_nome = "";
    String r_cpf_cnpj = "";
    String r_cep = "";
    String r_endereco = "";
    String r_numero = "";
    String r_bairro = "";
    String r_cidade = "";// se exiisteir o CEP no DNE
    String r_uf = "";

    String valor = "";

    String d_nome = "";
    String d_cpf_cnpj = "";
    String d_cep = "";
    String d_endereco = "";
    String d_numero = "";
    String d_bairro = "";

    String d_cidade = ""; // se existir na tabela movimentao
    String d_uf = "";

    String descricao = "";
    String sro = "";
    String data = "";

    BufferedReader le = new BufferedReader(new InputStreamReader(item.getInputStream(), "ISO-8859-1"));
    // LE UMA LINHA DO ARQUIVO PARA PULAR O CABEALHO   
    int lineNum = 1;
    while (le.ready()) {
        //LE UMA LINHA DO ARQUIVO 
        String aux = le.readLine();
        //ADICIONA CONTADOR DE LINHA

        if (lineNum == 1) {
            //remetente
            r_nome = aux.substring(38, 88).trim();
            r_cpf_cnpj = aux.substring(98, 112).trim();
            r_cep = aux.substring(112, 120).trim();
            r_endereco = aux.substring(130, 190).trim();
            r_numero = aux.substring(190, 198).trim();
            r_bairro = aux.substring(236, 276).trim();
            try {
                r_numero = Integer.parseInt(r_numero) + "";
            } catch (Exception ex) {
            }/* w  ww  .j  a  v  a  2 s  . c om*/
        }
        if (lineNum >= 2 && aux.startsWith("DT")) {

            if (item.getName().contains("ValesPagos")) {
                //destinatario
                d_nome = aux.substring(26, 76).trim();
                d_cpf_cnpj = aux.substring(86, 106).trim();//ate106
                d_cep = aux.substring(106, 114).trim();
                d_endereco = aux.substring(124, 184).trim();
                d_numero = aux.substring(184, 230).trim();
                d_bairro = aux.substring(230, 270).trim();
                // String d_cidade;// se exiisteir o CEP no DNE
                // String d_uf;// se exiisteir o CEP no DNE

                sro = aux.substring(306, 319).trim();
                descricao = aux.substring(319, 369).trim();
                valor = aux.substring(298, 306).trim();
                data = aux.substring(369).trim();
            } else {
                //destinatario
                d_nome = aux.substring(26, 76).trim();
                d_cpf_cnpj = aux.substring(86, 100).trim();//ate106
                d_cep = aux.substring(100, 108).trim();
                d_endereco = aux.substring(118, 178).trim();
                d_numero = aux.substring(178, 224).trim();
                d_bairro = aux.substring(224, 264).trim();
                // String d_cidade;// se exiisteir o CEP no DNE
                // String d_uf;// se exiisteir o CEP no DNE

                sro = aux.substring(300, 313).trim();
                descricao = aux.substring(313, 363).trim();
                valor = aux.substring(292, 300).trim();
                data = aux.substring(363).trim();
            }

            try {
                d_numero = Integer.parseInt(d_numero) + "";
            } catch (Exception ex) {
            }
            try {
                valor = df.format((double) Integer.parseInt(valor) / 100) + "";
            } catch (Exception ex) {
            }

            data = data.substring(4, 8) + "-" + data.substring(2, 4) + "-" + data.substring(0, 2);

            Movimentacao mv = getConsultaBySRO(sro, nomeBD);
            if (mv != null) {
                d_uf = mv.getId();// USEI O CAMPO dufF PARA COLOCAR O ID DA MOVIMENTACAO CASO EXISTA
            }
            Endereco end_cep = pesquisaCep(d_cep);
            d_cidade = end_cep.getCidade() + " / " + end_cep.getUf();

            ret += "(" + idCli + "," + idDepto + ",'" + nomeDepto + "','" + sro + "','" + descricao + "','"
                    + valor + "','" + r_nome + "','" + r_cpf_cnpj + "','" + r_endereco + "','" + r_numero
                    + "','" + r_bairro + "','" + r_cidade + "','" + r_uf + "'," + "'" + d_nome + "','"
                    + d_cpf_cnpj + "','" + d_endereco + "','" + d_numero + "','" + d_bairro + "','" + d_cidade
                    + "','" + d_cep + "','" + d_uf + "','" + data + "'),";

        }
        lineNum++;
    }
    le.close();

    return ret;
}

From source file:com.era7.bioinfo.blastxviewer7.server.servlet.UploadBlastAndGetCoverageXMLServlet.java

protected void servletLogic(HttpServletRequest request, HttpServletResponse resp)
        throws javax.servlet.ServletException, java.io.IOException {

    OutputStream out = resp.getOutputStream();

    String temp = request.getParameter(Request.TAG_NAME);

    try {/*from   www.ja va 2 s  . c o  m*/

        Request myReq = new Request(temp);

        String method = myReq.getMethod();

        if (method.equals(RequestList.UPLOAD_BLAST_AND_GET_COVERAGE_XML_REQUEST)) {

            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            if (!isMultipart) {
                Response response = new Response();
                response.setError("No file was uploaded");
                out.write(response.toString().getBytes());
            } else {

                System.out.println("all controls passed!!");

                FileItem fileItem = FileUploadUtilities.getFileItem(request);
                InputStream uploadedStream = fileItem.getInputStream();
                BufferedReader inBuff = new BufferedReader(new InputStreamReader(uploadedStream));
                String line = null;
                StringBuilder stBuilder = new StringBuilder();
                while ((line = inBuff.readLine()) != null) {
                    //System.out.println("line = " + line);
                    stBuilder.append(line);
                }

                System.out.println("before blastExporter");

                String resultExport = BlastExporter
                        .exportBlastXMLtoIsotigsCoverage(new BlastOutput(stBuilder.toString()));

                //System.out.println("resultExport = " + resultExport);

                uploadedStream.close();

                System.out.println("after blastexporter");

                String responseSt = "<response status=\"" + Response.SUCCESSFUL_RESPONSE + "\" method=\""
                        + RequestList.UPLOAD_BLAST_AND_GET_COVERAGE_XML_REQUEST + "\" >\n" + resultExport
                        + "\n</response>";

                System.out.println("writing response");

                resp.setContentType("text/html");

                byte[] byteArray = responseSt.getBytes();
                out.write(byteArray);
                resp.setContentLength(byteArray.length);

                System.out.println("doneee!!");

            }

        } else {
            Response response = new Response();
            response.setError("There is no such method");
            out.write(response.toString().getBytes());

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.alibaba.sample.petstore.biz.StoreManagerTests.java

@Test
public void addProduct() throws Exception {
    Product prod = new Product();
    final File srcfile = new File(srcdir, "resources.xml");

    prod.setProductId("myfish");
    prod.setDescription("My fish");
    prod.setName("my fish");

    FileItem fi = createMock(FileItem.class);
    expect(fi.getName()).andReturn("c:\\test\\pic.gif");
    expect(fi.getInputStream()).andAnswer(new IAnswer<InputStream>() {
        public InputStream answer() throws Throwable {
            return new FileInputStream(srcfile);
        }/*w  w w.  j  av a 2  s .com*/
    });
    replay(fi);

    storeManager.addProduct(prod, "FISH", fi);

    prod = productDao.getProductById("myfish");
    assertEquals("myfish", prod.getProductId());
    assertEquals("my fish", prod.getName());
    assertEquals("My fish", prod.getDescription());
    assertEquals("FISH", prod.getCategoryId());
    assertTrue(prod.getLogo().startsWith("image_"));
    assertTrue(prod.getLogo().endsWith(".gif"));

    File f = new File(destdir, "upload/" + prod.getLogo());
    assertTrue(f.exists());

    assertEquals(StreamUtil.readText(new FileInputStream(srcfile), "8859_1", true),
            StreamUtil.readText(new FileInputStream(f), "8859_1", true));
}

From source file:fll.web.developer.ReplaceChallengeDescriptor.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Top of ReplaceChallengeDescriptor.doPost");
    }//from w w w .  ja  v a2 s. c o  m

    final StringBuilder message = new StringBuilder();

    Connection connection = null;
    try {
        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();

        final Document curDoc = ApplicationAttributes.getChallengeDocument(application);

        // must be first to ensure the form parameters are set
        UploadProcessor.processUpload(request);

        // create a new empty database from an XML descriptor
        final FileItem xmlFileItem = (FileItem) request.getAttribute("xmldoc");

        final Document newDoc = ChallengeParser
                .parse(new InputStreamReader(xmlFileItem.getInputStream(), Utilities.DEFAULT_CHARSET));

        final String compareMessage = ChallengeParser.compareStructure(curDoc, newDoc);
        if (null == compareMessage) {
            GenerateDB.insertOrUpdateChallengeDocument(newDoc, connection);
            application.setAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT, newDoc);
            message.append("<p><i>Successfully replaced challenge descriptor</i></p>");
        } else {
            message.append("<p class='error'>");
            message.append(compareMessage);
            message.append("</p>");
        }
    } catch (final FileUploadException fue) {
        message.append("<p class='error'>Error handling the file upload: " + fue.getMessage() + "</p>");
        LOGGER.error(fue, fue);
    } catch (final SQLException sqle) {
        message.append("<p class='error'>Error talking to the database: " + sqle.getMessage() + "</p>");
        LOGGER.error(sqle, sqle);
        throw new RuntimeException("Error talking to the database", sqle);
    } finally {
        SQLFunctions.close(connection);
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Top of ReplaceChallengeDescriptor.doPost");
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL("index.jsp"));

}

From source file:br.gov.jfrj.siga.wf.servlet.UploadServlet.java

/**
 * Coloca as informaes do arquivo da definio do processo no banco de
 * dados./*w w  w  . j  a  v  a 2 s.c o m*/
 * 
 * @param fileItem
 * @return
 */
private String doDeployment(FileItem fileItem) {
    try {
        ZipInputStream zipInputStream = new ZipInputStream(fileItem.getInputStream());
        JbpmContext jbpmContext = WfContextBuilder.getJbpmContext().getJbpmContext();
        ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zipInputStream);
        jbpmContext.deployProcessDefinition(processDefinition);
        zipInputStream.close();
        long id = processDefinition.getId();

        String sReturn = "Deployed archive " + processDefinition.getName() + " successfully";

        // ProcessDefinition pi = jbpmContext.getGraphSession()
        // .loadProcessDefinition(id);

        Delegation d = new Delegation("br.gov.jfrj.siga.wf.util.WfAssignmentHandler");

        for (Swimlane s : ((Collection<Swimlane>) processDefinition.getTaskMgmtDefinition().getSwimlanes()
                .values())) {
            if (s.getTasks() != null)
                for (Object t : s.getTasks()) {
                    System.out.println(((Task) t).toString());
                }
            if (s.getAssignmentDelegation() == null)
                s.setAssignmentDelegation(d);
        }

        for (Task t : ((Collection<Task>) processDefinition.getTaskMgmtDefinition().getTasks().values())) {
            if (t.getSwimlane() == null && t.getAssignmentDelegation() == null)
                t.setAssignmentDelegation(d);
        }

        return sReturn;
    } catch (IOException e) {
        return "IOException";
    }
}

From source file:net.scran24.staff.server.services.UploadUserInfoService.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html");
    ServletOutputStream outputStream = resp.getOutputStream();
    PrintWriter writer = new PrintWriter(outputStream);

    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } else {/*from  w ww .j a va2  s  .  c o  m*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            List<FileItem> items = upload.parseRequest(req);

            InputStream file = null;
            String role = null;
            Set<String> permissions = new HashSet<String>();
            String surveyId = req.getParameter("surveyId");

            for (FileItem i : items) {
                if (i.getFieldName().equals("file"))
                    file = i.getInputStream();
                else if (i.getFieldName().equals("role"))
                    role = i.getString();
                else if (i.getFieldName().equals("permission"))
                    permissions.add(i.getString());
            }

            if (file == null)
                throw new ServletException("file field not specified");
            if (role == null)
                throw new ServletException("role field not specified");
            if (surveyId == null)
                throw new ServletException("surveyId field not specified");

            List<UserRecord> userRecords = UserRecordCSV.fromCSV(file);

            try {
                Set<String> roles = new HashSet<String>();
                roles.add(role);

                dataStore.saveUsers(surveyId, mapToSecureUserRecords(userRecords, roles, permissions));
                writer.print("OK");
            } catch (DataStoreException e) {
                writer.print("ERR:" + e.getMessage());
            } catch (DuplicateKeyException e) {
                writer.print("ERR:" + e.getMessage());
            }

        } catch (FileUploadException e) {
            writer.print("ERR:" + e.getMessage());
        } catch (IOException e) {
            writer.print("ERR:" + e.getMessage());
        }
    }

    writer.close();
}

From source file:com.origami.sgm.services.ejbs.censocat.FotosServlet.java

protected void postWithNumId(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    FotoUploadRespMod respModel = new FotoUploadRespMod(false, null);
    try {//from w w w  .  j  av  a  2s.c  o  m
        response.setContentType("application/json;charset=UTF-8");
        this.genFactory();
        Long id = Long.parseLong(request.getParameter("id"));
        uploadFotoBean.setPredioId(id);
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        ServletFileUpload upload = new ServletFileUpload(uploadFotoBean.getFactory());
        upload.setFileSizeMax(10000000); // max 10MB
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
            } else {
                InputStream is = item.getInputStream();
                Long fileId = omegaUploader.uploadFile(is, item.getName(), item.getContentType());
                uploadFotoBean.setFileId(fileId);
                uploadFotoBean.setNombre(item.getName());
                uploadFotoBean.setContentType(item.getContentType());
                uploadFotoBean.saveFotoId();
                respModel.setFotoId(uploadFotoBean.getFotoPredioId());
                respModel.setOk(true);
                is.close();
                break;
            }
        }
    } catch (FileUploadException ex) {
        Logger.getLogger(FotosServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException | IOException ex) {
        Logger.getLogger(FotosServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    ObjectMapper mapper = new ObjectMapper();
    String jsonResp = mapper.writeValueAsString(respModel);
    response.getWriter().write(jsonResp);
}

From source file:com.duroty.application.bookmark.actions.BookmarkExtractorAction.java

protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionMessages errors = new ActionMessages();

    try {/*w w  w  . j a v a2  s  . co m*/
        boolean isMultipart = FileUpload.isMultipartContent(request);

        if (isMultipart) {
            Vector links = null;

            //Parse the request
            List items = diskFileUpload.parseRequest(request);

            //Process the uploaded items
            Iterator iter = items.iterator();

            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {
                    String contents = IOUtils.toString(item.getInputStream());

                    links = Extractor.getLinks(contents, null);
                }
            }

            if ((links != null) && (links.size() > 0)) {
                Bookmark bookmarkInstance = getBookmarkInstance(request);

                bookmarkInstance.addBookmarks(links);
            }
        } else {
            errors.add("general",
                    new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", "The form is null"));
            request.setAttribute("exception", "The form is null");
            doTrace(request, DLog.ERROR, getClass(), "The form is null");
            ;
        }
    } catch (Exception ex) {
        String errorMessage = ExceptionUtilities.parseMessage(ex);

        if (errorMessage == null) {
            errorMessage = "NullPointerException";
        }

        errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage));
        request.setAttribute("exception", errorMessage);
        doTrace(request, DLog.ERROR, getClass(), errorMessage);
    }

    if (errors.isEmpty()) {
        doTrace(request, DLog.INFO, getClass(), "OK");

        return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD);
    } else {
        saveErrors(request, errors);

        return mapping.findForward(Constants.ACTION_FAIL_FORWARD);
    }
}