Example usage for javax.servlet.http Part getInputStream

List of usage examples for javax.servlet.http Part getInputStream

Introduction

In this page you can find the example usage for javax.servlet.http Part getInputStream.

Prototype

public InputStream getInputStream() throws IOException;

Source Link

Document

Gets the content of this part as an InputStream

Usage

From source file:org.sonar.server.ws.ServletRequest.java

@Override
@CheckForNull/*from ww  w  .  ja v  a  2 s. c om*/
public Part readPart(String key) {
    try {
        if (!isMultipartContent()) {
            return null;
        }
        javax.servlet.http.Part part = source.getPart(key);
        if (part == null || part.getSize() == 0) {
            return null;
        }
        return new PartImpl(part.getInputStream(), part.getSubmittedFileName());
    } catch (Exception e) {
        throw new IllegalStateException("Can't read file part", e);
    }
}

From source file:org.votingsystem.web.util.MultipartRequestVS.java

public MultipartRequestVS(Collection<Part> parts, Type type) throws Exception {
    switch (type) {
    case CURRENCY_REQUEST:
        for (Part part : parts) {
            if (part.getName().contains(ContextVS.CSR_FILE_NAME)) {
                csrBytes = IOUtils.toByteArray(part.getInputStream());
            } else if (part.getName().contains(ContextVS.CURRENCY_REQUEST_DATA_FILE_NAME)) {
                smime = new SMIMEMessage(part.getInputStream());
            } else {
                throw new ValidationExceptionVS(
                        "CURRENCY_REQUEST - bad request - file name: " + part.getName());
            }/*from   www  . ja v a 2s .c o  m*/
        }
        if (csrBytes == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.CSR_FILE_NAME);
        if (smime == null)
            throw new ValidationExceptionVS(
                    "ERROR - missing file: " + ContextVS.CURRENCY_REQUEST_DATA_FILE_NAME);
        break;
    case ACCESS_REQUEST:
        for (Part part : parts) {
            if (part.getName().contains(ContextVS.CSR_FILE_NAME)) {
                csrBytes = IOUtils.toByteArray(part.getInputStream());
            } else if (part.getName().contains(ContextVS.ACCESS_REQUEST_FILE_NAME)) {
                smime = new SMIMEMessage(part.getInputStream());
            } else {
                throw new ValidationExceptionVS("ACCESS_REQUEST - bad request - file name: " + part.getName());
            }
        }
        if (csrBytes == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.CSR_FILE_NAME);
        if (smime == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.ACCESS_REQUEST_FILE_NAME);
        break;
    case REPRESENTATIVE_DATA:
        for (Part part : parts) {
            if (part.getName().contains(ContextVS.IMAGE_FILE_NAME)) {
                imageBytes = IOUtils.toByteArray(part.getInputStream());
                if (imageBytes.length > ContextVS.IMAGE_MAX_FILE_SIZE) {
                    throw new ValidationExceptionVS("ERROR - imageSizeExceededMsg - received:"
                            + imageBytes.length / 1024 + " - max: " + ContextVS.IMAGE_MAX_FILE_SIZE_KB);
                }
            } else if (part.getName().contains(ContextVS.REPRESENTATIVE_DATA_FILE_NAME)) {
                smime = new SMIMEMessage(part.getInputStream());
            } else {
                throw new ValidationExceptionVS(
                        "REPRESENTATIVE_DATA - bad request - file name: " + part.getName());
            }
        }
        if (imageBytes == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.IMAGE_FILE_NAME);
        if (smime == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.REPRESENTATIVE_DATA_FILE_NAME);
        break;
    case ANONYMOUS_DELEGATION:
        for (Part part : parts) {
            if (part.getName().contains(ContextVS.CSR_FILE_NAME)) {
                csrBytes = IOUtils.toByteArray(part.getInputStream());
            } else if (part.getName().contains(ContextVS.REPRESENTATIVE_DATA_FILE_NAME)) {
                smime = new SMIMEMessage(part.getInputStream());
            } else {
                throw new ValidationExceptionVS(
                        "ANONYMOUS_DELEGATION - bad request - file name: " + part.getName());
            }
        }
        if (csrBytes == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.CSR_FILE_NAME);
        if (smime == null)
            throw new ValidationExceptionVS("ERROR - missing file: " + ContextVS.REPRESENTATIVE_DATA_FILE_NAME);
        break;
    default:
        throw new ExceptionVS("unprocessed type " + type);
    }
}

From source file:org.cirdles.webServices.calamari.CalamariServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w w  w  .j a va2s.c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    Integer accessCount;
    synchronized (session) {
        accessCount = (Integer) session.getAttribute("accessCount");
        if (accessCount == null) {
            accessCount = 0; // autobox int to Integer
        } else {
            accessCount = accessCount + 1;
        }
        session.setAttribute("accessCount", accessCount);
    }

    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=calamari-reports.zip");

    boolean useSBM = ServletRequestUtils.getBooleanParameter(request, "useSBM", true);
    boolean useLinFits = ServletRequestUtils.getBooleanParameter(request, "userLinFits", false);
    String firstLetterRM = ServletRequestUtils.getStringParameter(request, "firstLetterRM", "T");
    Part filePart = request.getPart("prawnFile");

    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
    InputStream fileStream = filePart.getInputStream();
    File myFile = new File(fileName);

    PrawnFileHandlerService handler = new PrawnFileHandlerService();
    String fileExt = FilenameUtils.getExtension(fileName);

    try {
        File report = null;
        if (fileExt.equals("zip")) {
            report = handler.generateReportsZip(fileName, fileStream, useSBM, useLinFits, firstLetterRM)
                    .toFile();
        } else if (fileExt.equals("xml")) {
            report = handler.generateReports(fileName, fileStream, useSBM, useLinFits, firstLetterRM).toFile();
        }

        response.setContentLengthLong(report.length());
        IOUtils.copy(new FileInputStream(report), response.getOutputStream());

    } catch (Exception e) {
        System.err.println(e);
    }

}

From source file:es.uma.inftel.blog.servlet.PerfilServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww  w . ja va2  s .  co 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 {

    request.setCharacterEncoding("UTF-8");

    BaseView baseView = new BaseView();
    BaseViewFacade<BaseView> baseViewFacade = new BaseViewFacade<>(postFacade);
    baseViewFacade.initView(baseView);

    RequestDispatcher requestDispatcher = request.getRequestDispatcher("perfil.jsp");
    String password = request.getParameter("password");
    if (password == null) {
        request.setAttribute("perfilView", baseView);
        requestDispatcher.forward(request, response);
    }

    String email = request.getParameter("email");

    Part filePart = request.getPart("avatar");
    byte[] avatar = null;
    if (!filePart.getSubmittedFileName().isEmpty()) {
        InputStream inputStream = filePart.getInputStream();
        avatar = IOUtils.toByteArray(inputStream);
    }

    HttpSession session = request.getSession();
    Usuario usuario = (Usuario) session.getAttribute("usuario");

    modificarUsuario(usuario, password, email, avatar);
    response.sendRedirect("perfil");

}

From source file:br.edu.ifpb.sislivros.model.ProcessadorFotos.java

public String processarArquivoCapa(HttpServletRequest request, Part partCapa, String nameToSave)
        throws IOException {

    if (partCapa != null & nameToSave != null) {
        InputStream fileContent = partCapa.getInputStream();
        String contextPath = request.getServletContext().getRealPath("/");

        if (salvarImagemCapa(contextPath + File.separator + folder, fileContent, nameToSave)) {
            return folder + "/" + nameToSave;
        }//  w w  w . jav  a 2s .  co m
    }

    return null;
}

From source file:vista.RegistroVideojuegoServlet.java

private byte[] convierteArchivo(Part filePart, int tipo) {
    InputStream fileContent = null;
    byte[] imagen = null;
    try {//from   w ww  .ja  v  a2  s  .c  om
        InputStream inputStream = filePart.getInputStream();
        String fileName = filePart.getSubmittedFileName();
        String ext = fileName.substring(fileName.indexOf("."));
        boolean validacion = tipo == 1 ? validaNombreVideo(ext)
                : tipo == 0 ? validaNombreImagen(ext) : validaNombreArchivo(ext);
        fileContent = filePart.getInputStream();
        //String nombreArchivo = validaHistorial(fileName, fileContent, usuario, email);
        if (validacion) {
            imagen = new byte[inputStream.available()];
            imagen = IOUtils.toByteArray(inputStream);
        }

    } catch (IOException ex) {
        Logger.getLogger(RegistroVideojuegoServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            fileContent.close();
            return imagen;
        } catch (IOException ex) {
            Logger.getLogger(RegistroVideojuegoServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return imagen;
}

From source file:mn.sict.krono.renders.UploadFile.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w ww.  j av a 2s.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/plain");
    response.setCharacterEncoding("UTF-8");

    String templateName = request.getParameter("demo_name");
    Part filePart = request.getPart("demo_img");
    try {
        // String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
        InputStream fileContent = filePart.getInputStream();
        System.out.println(templateName);
        File file = new File("uploads/" + templateName + ".png");
        System.out.println(file.getAbsolutePath());
        OutputStream outputStream = new FileOutputStream(file);
        IOUtils.copy(fileContent, outputStream);
        outputStream.close();

        Thumbnails.of(new File("uploads/" + templateName + ".png")).size(500, 707).outputFormat("PNG")
                .toFiles(Rename.NO_CHANGE);

    } catch (NullPointerException ex) {
        System.out.println("null param");
    }

    response.getWriter().write("uploaded lmao");

    System.out.println("fking shit");
    response.sendRedirect("init.jsp?req=" + templateName);
}

From source file:com.shoylpik.controller.AddProduct.java

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

    String SAVE_DIRECTORY = "menu_assets/ProductImage";
    String absolutePath = request.getServletContext().getRealPath("");
    String savePath = absolutePath + File.separator + SAVE_DIRECTORY;

    File imageSaveDirectory = new File(savePath);
    if (!imageSaveDirectory.exists()) {
        imageSaveDirectory.mkdir();//from  ww  w . j a  va2s .c  o  m
    }
    System.out.println("absolutePath: " + absolutePath);
    System.out.println("SavePath: " + savePath);
    //        System.out.println("imageSaveDirectory.getAbsolutePath(): " + imageSaveDirectory.getAbsolutePath());
    String fileName = null;

    try {

        Part filePart = request.getPart("IPimage");
        String filename = getFilename(filePart);
        //            System.out.println("filename: " + filename);
        InputStream imageInputStream = filePart.getInputStream();
        byte[] bytes = IOUtils.toByteArray(imageInputStream);

        Product product = new Product();
        product.setProductId(Integer.parseInt(request.getParameter("IPID")));
        product.setProductName(request.getParameter("IPname"));
        product.setProductImageName(filename);
        product.setProductCategory(request.getParameter("IPcat"));
        product.setProductPrice(Float.parseFloat(request.getParameter("IPprice")));
        product.setProductQuantity(Integer.parseInt(request.getParameter("IPQuant")));

        ProductBean pBean = new ProductBean();
        pBean.addProduct(product);

        //            String fullImagePath = "menu_assets/images/"+filename;

        String fullImagePath = savePath + File.separator + filename;
        File file = new File(fullImagePath);
        //            System.out.println("fullImagePath : " + fullImagePath);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bytes);

    } catch (SQLException ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException | ServletException | NumberFormatException ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.sendRedirect("AdministrationPage.jsp");
}

From source file:br.edu.ifpb.sislivros.model.ProcessadorFotos.java

public String processarFotoPerfil(HttpServletRequest request, Part fotoPart, String nameToSave)
        throws ServletException, IOException {

    if (fotoPart != null & nameToSave != null) {
        InputStream fileContent = fotoPart.getInputStream();
        String contextPath = request.getServletContext().getRealPath("/");

        if (salvarImagemCapa(contextPath + File.separator + folder, fileContent, nameToSave)) {
            return folder + "/" + nameToSave;
        }/*from  w ww .ja  va  2  s. co m*/
    }

    return null;
}

From source file:org.apache.servicecomb.demo.jaxrs.server.CodeFirstJaxrs.java

@Path("/upload2")
@POST//from w  ww  .j  a  v  a2s .co  m
@Produces(MediaType.TEXT_PLAIN)
public String fileUpload2(@FormParam("file1") Part file1, @FormParam("message") String message)
        throws IOException {
    try (InputStream is1 = file1.getInputStream()) {
        String content1 = IOUtils.toString(is1);
        return String.format("%s:%s:%s:%s", file1.getSubmittedFileName(), file1.getContentType(), content1,
                message);
    }
}