Example usage for javax.servlet.http HttpServletRequest getPart

List of usage examples for javax.servlet.http HttpServletRequest getPart

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getPart.

Prototype

public Part getPart(String name) throws IOException, ServletException;

Source Link

Document

Gets the Part with the given name.

Usage

From source file:fr.ybonnel.simpleweb4j.MultipartIntegrationTest.java

@Before
public void startServer() {
    resetDefaultValues();/*from  ww w .ja  v a 2  s .c  om*/
    port = Integer.getInteger("test.http.port", random.nextInt(10000) + 10000);
    setPort(port);

    resource(new RestResource<TestUploadImage>("multipart", TestUploadImage.class) {
        @Override
        public TestUploadImage getById(String id) throws HttpErrorException {
            return null;
        }

        @Override
        public List<TestUploadImage> getAll() throws HttpErrorException {
            return Collections.emptyList();
        }

        @Override
        public void update(String id, TestUploadImage resource) throws HttpErrorException {
            resource.id = id;
            lastCall = resource;
        }

        @Override
        public TestUploadImage create(TestUploadImage resource) throws HttpErrorException {
            lastCall = resource;
            return resource;
        }

        @Override
        public Route<TestUploadImage, TestUploadImage> routeCreate() {
            return new Route<TestUploadImage, TestUploadImage>("multipart", TestUploadImage.class) {
                @Override
                public Response<TestUploadImage> handle(TestUploadImage param, RouteParameters routeParams)
                        throws HttpErrorException {
                    return new Response<>(create(param), HttpServletResponse.SC_CREATED);
                }

                @Override
                protected TestUploadImage getRouteParam(HttpServletRequest request) throws IOException {
                    try {
                        Part dataPart = request.getPart("data");
                        TestUploadImage data = ContentType.GSON
                                .fromJson(new InputStreamReader(dataPart.getInputStream()), getParamType());

                        Part imagePart = request.getPart("image");
                        if (null != imagePart) {
                            data.imageName = ((MultiPartInputStreamParser.MultiPart) imagePart)
                                    .getContentDispositionFilename();
                            data.image = IOUtils.toByteArray(imagePart.getInputStream());
                        }
                        return data;
                    } catch (ServletException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            };
        }

        @Override
        public Route<TestUploadImage, Void> routeUpdate() {
            return new Route<TestUploadImage, Void>("multipart/:id", TestUploadImage.class) {
                @Override
                public Response<Void> handle(TestUploadImage param, RouteParameters routeParams)
                        throws HttpErrorException {
                    update(routeParams.getParam("id"), param);
                    return new Response<>(null);
                }

                @Override
                protected TestUploadImage getRouteParam(HttpServletRequest request) throws IOException {
                    try {
                        Part dataPart = request.getPart("data");
                        InputStreamReader dataReader = new InputStreamReader(dataPart.getInputStream());
                        TestUploadImage data = ContentType.GSON.fromJson(dataReader, getParamType());
                        dataReader.close();

                        Part imagePart = request.getPart("image");
                        if (null != imagePart) {
                            data.imageName = ((MultiPartInputStreamParser.MultiPart) imagePart)
                                    .getContentDispositionFilename();
                            data.image = IOUtils.toByteArray(imagePart.getInputStream());
                        }
                        return data;
                    } catch (ServletException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            };
        }

        @Override
        public void delete(String id) throws HttpErrorException {
        }
    });

    start(false);
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww w.j  a v  a2s  . 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.orangeandbronze.jblubble.sample.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        pathInfo = "/";
    }/*ww  w . ja  v  a2 s.c  o  m*/
    LOGGER.debug("POST {}{}", PATH, pathInfo);
    Part part = request.getPart("file");
    if (part != null) {
        BlobKey blobKey = blobstoreService.createBlob(part.getInputStream(), getFileName(part),
                part.getContentType());
        LOGGER.debug("Created blob, generated key [{}]", blobKey);
        blobKeys.add(blobKey);
    }
    response.sendRedirect(request.getServletContext().getContextPath() + "/uploads");
}

From source file:z.tool.web.servlet.AbstractServlet.java

protected Part getPart(HttpServletRequest request, String key) throws ServletError {
    try {/*from  w w w  . j a  va2 s. c  o  m*/
        return request.getPart(key);
    } catch (Exception e) {
        throw new ServletError(e);
    }
}

From source file:saludtec.admincloud.web.servicios.ArchivosWeb.java

private JSONArray guardarFotoPerfil(HttpServletRequest r) throws ServletException, IOException {
    JSONArray array = new JSONArray();
    JSONObject obj = null;/*ww  w. j av  a 2  s  . co  m*/
    String idPaciente = contenidoFormData(r.getPart("paciente").getInputStream());
    String contentType = r.getPart("archivo").getContentType();
    String extArch = extensionArchivo(contentType);
    File ruta = new File("/var/www/AdminCloud/clinicas/" + sesion.clinica(r.getSession()).getIdClinica()
            + "/pacientes/" + idPaciente);
    r.getPart("archivo").write(idPaciente + extArch);
    if (ruta.exists()) {
        File archTemp = new File("var/www/AdminCloudData/temp/" + idPaciente + extArch);
        if (archTemp.renameTo(new File(ruta + idPaciente + extArch))) {
            //aca va el guardado en la base de datos
            obj = new JSONObject();
            obj.put("ruta", archTemp);
            array.add(obj);
        }
    } else {
        obj = new JSONObject();
        obj.put("error", "no se pudo guardar la imagen");
        array.add(obj);
    }
    return array;
}

From source file:codes.thischwa.c5c.requestcycle.Context.java

/**
 * Initializes the base parameters./*from   ww w.  java2  s  . co  m*/
 * 
 * @param servletRequest
 * 
 * @throws C5CException thrown if the parameter 'mode' couldn't be resolved
 */
Context(HttpServletRequest servletRequest) throws C5CException {
    this.servletRequest = servletRequest;
    urlPath = servletRequest.getParameter("path");
    String paramMode = servletRequest.getParameter("mode");
    if (paramMode == null && servletRequest.getMethod().equals("POST")) {
        try {
            paramMode = IOUtils.toString(servletRequest.getPart("mode").getInputStream());
        } catch (Exception e) {
            logger.error("Couldn't retrieve the 'mode' parameter from multipart.");
            throw new C5CException(
                    UserObjectProxy.getFilemanagerErrorMessage(FilemanagerException.Key.ModeError));
        }
    } else {
        paramMode = servletRequest.getParameter("mode");
    }
    try {
        mode = FilemanagerAction.valueOfIgnoreCase(paramMode);
    } catch (IllegalArgumentException e) {
        logger.error("Unknown 'mode': {}", paramMode);
        throw new C5CException(UserObjectProxy.getFilemanagerErrorMessage(FilemanagerException.Key.ModeError));
    }
}

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

private void insertarImagen(HttpServletRequest request, Post idPost) throws ServletException, IOException {
    int numeroFotos, i;
    numeroFotos = Integer.parseInt(request.getParameter("numFotos"));
    for (i = 0; i < numeroFotos + 1; i++) {
        Part filePart = request.getPart("foto-" + i);
        if (filePart != null) {
            if (!filePart.getSubmittedFileName().isEmpty()) {
                Imagen imagen = new Imagen();
                InputStream inputStream = filePart.getInputStream();
                byte[] foto = IOUtils.toByteArray(inputStream);
                imagen.setPostId(idPost);
                imagen.setFoto(foto);//ww w  . j  a  v  a  2s.co  m
                imagenFacade.create(imagen);
            }
        }
    }

}

From source file:org.grible.servlets.app.imp.TableImport.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*ww w  . j a v a2 s. c  o m*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        if (Security.anyServletEntryCheckFailed(request, response)) {
            return;
        }
        Part filePart = request.getPart("file");
        String fileName = ServletHelper.getFilename(filePart);
        String tableName = StringUtils.substringBefore(fileName, ".xls");
        int categoryId = Integer.parseInt(request.getParameter("category"));
        String categoryPath = StringHelper
                .getFolderPathWithoutLastSeparator(request.getParameter("categorypath"));
        int productId = Integer.parseInt(request.getParameter("product"));

        InputStream filecontent = filePart.getInputStream();
        ExcelFile excelFile = new ExcelFile(filecontent, ServletHelper.isXlsx(fileName));

        Category category = null;
        if (ServletHelper.isJson()) {
            jDao = new JsonDao();
            category = new Category(categoryPath, TableType.TABLE, productId);
        } else {
            pDao = new PostgresDao();
            category = new Category(categoryId);
        }

        if (DataManager.getInstance().getDao().isTableInProductExist(tableName, TableType.TABLE, category)) {
            Table table = null;
            int currentKeysCount = 0;
            if (ServletHelper.isJson()) {
                table = jDao.getTable(tableName, TableType.TABLE, category);
                currentKeysCount = table.getTableJson().getKeys().length;
            } else {
                table = pDao.getTable(tableName, categoryId);
                currentKeysCount = table.getKeys().length;
            }

            int importedKeysCount = excelFile.getKeys().length;
            if (currentKeysCount != importedKeysCount) {
                throw new Exception("Parameters number is different.<br>In the current table: "
                        + currentKeysCount + ". In the Excel file: " + importedKeysCount + ".");
            }

            request.getSession(true).setAttribute("importedTable", table);
            request.getSession(false).setAttribute("importedFile", excelFile);
            String destination = "/tables/?product=" + productId + "&id=" + table.getId();
            response.sendRedirect(destination);
        } else {
            Key[] keys = excelFile.getKeys();
            String[][] values = excelFile.getValues();
            int tableId = DataManager.getInstance().getDao().insertTable(tableName, TableType.TABLE, category,
                    null, null, keys, values);

            if (excelFile.hasPreconditions()) {
                Key[] precondKeys = getKeys(excelFile.getPrecondition());
                String[][] precondValues = getValues(excelFile.getPrecondition());
                DataManager.getInstance().getDao().insertTable(null, TableType.PRECONDITION, category, tableId,
                        null, precondKeys, precondValues);
            }

            if (excelFile.hasPostconditions()) {
                Key[] postcondKeys = getKeys(excelFile.getPostcondition());
                String[][] postcondValues = getValues(excelFile.getPostcondition());
                DataManager.getInstance().getDao().insertTable(null, TableType.POSTCONDITION, category, tableId,
                        null, postcondKeys, postcondValues);
            }

            String message = "'" + tableName + "' table was successfully imported.";
            request.getSession(true).setAttribute("importResult", message);
            String destination = "/tables/?product=" + productId + "&id=" + tableId;
            response.sendRedirect(destination);
        }
    } catch (Exception e) {
        int productId = Integer.parseInt(request.getParameter("product"));
        String destination = "/tables/?product=" + productId;
        String message = Lang.get("error") + ": " + e.getMessage();
        e.printStackTrace();
        request.getSession(true).setAttribute("importResult", message);
        response.sendRedirect(destination);
    }
}

From source file:lk.studysmart.apps.BrainTeaserFileUpload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  ww  w  .java 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/html;charset=UTF-8");

    user = (User) request.getSession().getAttribute("user");
    //Get information from tha frontend of file upload
    final Part filePart = request.getPart("file");
    final String fileName = request.getParameter("filename");
    final String description = request.getParameter("description");

    InputStream filecontent = filePart.getInputStream();

    byte[] bytes = IOUtils.readFully(filecontent, Integer.valueOf(Long.toString(filePart.getSize())));

    Subject subject = em.find(Subject.class, request.getParameter("subject"));

    //Set attribute values to object 
    Internalresources resource = new Internalresources();
    resource.setUser(user);
    resource.setSubject(subject);
    resource.setFilename(fileName);
    resource.setDescription(description);
    resource.setBlob(bytes);

    try {
        utx.begin();
        em.persist(resource);
        utx.commit();
    } catch (NotSupportedException | SystemException | RollbackException | HeuristicMixedException
            | HeuristicRollbackException | SecurityException | IllegalStateException ex) {
        Logger.getLogger(BrainTeaserFileUpload.class.getName()).log(Level.SEVERE, null, ex);
        response.getWriter().write("Error: " + ex.getLocalizedMessage());
    }
    //Redirect page to the teacher's VLE main interface
    response.sendRedirect("teachVLEMUI.jsp?msg=File Uploaded");
}

From source file:org.grible.servlets.app.imp.StorageImport.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*ww w.j a  va 2 s  .co m*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        if (Security.anyServletEntryCheckFailed(request, response)) {
            return;
        }
        String className = Streams.asString(request.getPart("class").getInputStream());

        Part filePart = request.getPart("file");
        String fileName = ServletHelper.getFilename(filePart);
        String storageName = StringUtils.substringBefore(fileName, ".xls");
        int categoryId = Integer.parseInt(request.getParameter("category"));
        String categoryPath = StringHelper
                .getFolderPathWithoutLastSeparator(request.getParameter("categorypath"));
        int productId = Integer.parseInt(request.getParameter("product"));

        InputStream filecontent = filePart.getInputStream();
        ExcelFile excelFile = new ExcelFile(filecontent, ServletHelper.isXlsx(fileName));

        Category category = null;
        if (ServletHelper.isJson()) {
            jDao = new JsonDao();
            category = new Category(categoryPath, TableType.STORAGE, productId);
        } else {
            pDao = new PostgresDao();
            category = new Category(categoryId);
        }

        if (DataManager.getInstance().getDao().isTableInProductExist(storageName, TableType.STORAGE,
                category)) {

            Table table = null;
            int currentKeysCount = 0;
            if (ServletHelper.isJson()) {
                table = jDao.getTable(storageName, TableType.STORAGE, category);
                currentKeysCount = table.getTableJson().getKeys().length;
            } else {
                table = pDao.getTable(storageName, categoryId);
                currentKeysCount = table.getKeys().length;
            }
            int importedKeysCount = excelFile.getKeys().length;

            if (currentKeysCount != importedKeysCount) {
                throw new Exception("Parameters number is different.<br>In the current storage: "
                        + currentKeysCount + ". In the Excel file: " + importedKeysCount + ".");
            }

            request.getSession(true).setAttribute("importedTable", table);
            request.getSession(false).setAttribute("importedFile", excelFile);
            String destination = "/storages/?product=" + productId + "&id=" + table.getId();
            response.sendRedirect(destination);
        } else {
            int storageId = 0;
            Key[] keys = excelFile.getKeys();
            String[][] values = excelFile.getValues();
            storageId = DataManager.getInstance().getDao().insertTable(storageName, TableType.STORAGE, category,
                    null, className, keys, values);

            String message = "";
            if (className.equals("")) {
                message = "'" + storageName
                        + "' storage was successfully imported. WARNING: Class name is empty.";
            } else if (!className.endsWith("Info")) {
                message = "'" + storageName
                        + "' storage was successfully imported. WARNING: Class name does not end with 'Info'.";
            } else {
                message = "'" + storageName + "' storage was successfully imported.";
            }

            String destination = "";
            if (storageId > 0) {
                destination = "/storages/?product=" + productId + "&id=" + storageId;
            } else {
                destination = "/storages/?product=" + productId;
            }
            request.getSession(true).setAttribute("importResult", message);
            response.sendRedirect(destination);
        }
    } catch (Exception e) {
        int productId = Integer.parseInt(request.getParameter("product"));
        String destination = "/storages/?product=" + productId;
        String message = Lang.get("error") + ": " + e.getMessage();
        e.printStackTrace();
        request.getSession(true).setAttribute("importResult", message);
        response.sendRedirect(destination);
    }
}