Example usage for javax.servlet.http Part getContentType

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

Introduction

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

Prototype

public String getContentType();

Source Link

Document

Gets the content type of this part.

Usage

From source file:org.mhi.servlets.ImageUpload.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    // Service Class for DB - Actions
    ServiceQuery query = new ServiceQuery();
    ServiceUpdate update = new ServiceUpdate();

    String imgName = request.getParameter("name");
    String imgDesc = request.getParameter("desc");
    String imgCat = request.getParameter("category");
    String fileSize = null;/*from   w  w w.  j ava 2  s . c  o  m*/
    String fileName = null;
    String contentType = null;
    String[] parts = null;

    InputStream inputStream = null; // input stream of the upload file

    // obtains the upload file part in this multipart request
    Part filePart = request.getPart("files");

    if (filePart != null) {
        // Fill up Information extract from File
        fileSize = "" + filePart.getSize();
        parts = filePart.getSubmittedFileName().split("\\.");
        contentType = filePart.getContentType();

        // obtains input stream of the upload file
        inputStream = filePart.getInputStream();

        // new Image
        Images img = new Images();
        // Set Parameters
        img.setFileName(imgName + "." + parts[1]);
        img.setName(imgName);
        img.setDescription(imgDesc);
        img.setFileBlob(IOUtils.toByteArray(inputStream));
        img.setFileSize(fileSize);
        img.setcTyp(contentType);
        // Relationship to Category
        ImgCat cat = query.getCategoryByID(Long.valueOf(imgCat));
        img.setCategory(cat);
        // Persist to Database
        update.insertImage(img);
    }
    response.sendRedirect(request.getServletContext().getContextPath() + "/admin/upload");

}

From source file:servlets.post.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w w w.  j a v  a  2s.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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    JsonObject resp = new JsonObject();
    try {
        String tipo = request.getParameter("tipo") == null ? "" : request.getParameter("tipo");
        String titulo = request.getParameter("titulo") == null ? "" : request.getParameter("titulo");
        String descripcion = request.getParameter("descripcion") == null ? ""
                : request.getParameter("descripcion");
        int categoria = request.getParameter("categoria") == null ? -1
                : Integer.parseInt(request.getParameter("categoria"));

        //Si los campos estan vacios: error de validacion
        if (tipo.equals("") || titulo.equals("") || descripcion.equals("") || categoria == -1) {
            throw new Exception("W::No puedes dejar campos vacios. Intentalo nuevamente");
        }

        Part imagen = request.getPart("contenido");
        Part audio = request.getPart("audio");
        String cabeceraI = "";
        String cabeceraA = "";

        boolean siimagen = false;
        if (imagen != null && !imagen.getContentType().equals("application/octet-stream")) {
            cabeceraI = request.getParameter("cabeceraI") == null ? "" : request.getParameter("cabeceraI");
            if (cabeceraI.equals(""))
                throw new Exception("W::tu imagen no tiene cabecera. Agregale una antes de enviar los datos");
            else
                siimagen = true;
        }
        boolean siaudio = false;
        if (audio != null && !audio.getContentType().equals("application/octet-stream")) {
            cabeceraA = request.getParameter("cabeceraA") == null ? "" : request.getParameter("cabeceraA");
            if (cabeceraA.equals(""))
                throw new Exception("W::tu archivo no tiene cabecera. Agregale uno antes de enviar los datos");
            else
                siaudio = true;
        }

        HttpSession ss = request.getSession();
        int db = ss.getAttribute("bd") == null ? -1 : Integer.parseInt(ss.getAttribute("bd").toString());
        int id = ss.getAttribute("id") == null ? -1 : Integer.parseInt(ss.getAttribute("id").toString());
        if (db == -1 || id == -1)
            throw new Exception("Problemas con la base de datos. Por favor, intentalo mas tarde");

        ldn.cPost post = new ldn.cPost(db);
        String msg = post.nuevoPost(id, categoria, titulo, descripcion);
        if (post.getIdP() == -1)
            throw new Exception(msg);
        //msg se manda como error si idP = -1

        String result = "";
        if (siimagen) {
            String extension = FilenameUtils.getExtension(imagen.getSubmittedFileName());
            result = Clases.Utilities.saveFile(imagen, "imagenPost", "imagen", "." + extension);
            if (result.startsWith("/"))
                result = post.registraContenidoP(Integer.toString(post.getIdP()), result, cabeceraI);
            else
                throw new Exception(result);
            msg += "\n" + result;
        }
        if (siaudio) {
            String extension = FilenameUtils.getExtension(audio.getSubmittedFileName());
            System.out.println(extension);
            result = Clases.Utilities.saveFile(audio, "audioPost", "audio", "." + extension);
            if (result.startsWith("/"))
                result = post.registraContenidoP(Integer.toString(post.getIdP()), result, cabeceraA);
            else
                throw new Exception(result);
            msg += "\n" + result;
        }
        resp.addProperty("status", "OK");
        resp.addProperty("msg", msg);
    } catch (Exception e) {
        if (e.getMessage().startsWith("W::")) {
            resp.addProperty("status", "WARNING");
            resp.addProperty("msg", e.getMessage().substring(3));
        } else {
            resp.addProperty("status", "ERROR");
            resp.addProperty("msg", e.getMessage());
        }
    }
    out.print(resp.toString());
}

From source file:org.apache.servicecomb.foundation.vertx.http.TestVertxServerResponseToHttpServletResponse.java

@Test
public void prepareSendPartHeader_update(@Mocked Part part) {
    new Expectations() {
        {/*from w  ww. j  a  v a2s .c  o m*/
            part.getContentType();
            result = "type";
            part.getSubmittedFileName();
            result = "     ";
        }
    };
    DownloadUtils.prepareDownloadHeader(response, part);

    Assert.assertTrue(serverResponse.isChunked());
    Assert.assertEquals("type", response.getHeader(HttpHeaders.CONTENT_TYPE));
    Assert.assertEquals(
            "attachment;filename=%E6%B5%8B%20%20%20%20%20%E8%AF%95;filename*=utf-8''%E6%B5%8B%20%20%20%20%20%E8%AF%95",
            response.getHeader(HttpHeaders.CONTENT_DISPOSITION));
}

From source file:net.voidfunction.rm.master.AdminServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Date", HTTPUtils.getServerTime(0));
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);

    Part uploadFile = request.getPart("uploadfile");
    if (uploadFile == null)
        throw new ServletException("Uploaded file is null.");

    // Get some info about the file
    String filename = getFilename(uploadFile);
    String contentType = uploadFile.getContentType();
    long size = uploadFile.getSize();
    byte[] hash = FileUtils.sha256Hash(uploadFile.getInputStream());

    // Create a new file object, add it to the database, and store data
    RMFile newFile = new RMFile(filename, contentType, size, hash);
    node.getFileRepository().addFile(newFile, uploadFile.getInputStream());

    // Output data for interested parties
    Template tpl = new Template(new File(templateDir + "uploadsuccess.tpl"));
    tpl.assign("FILENAME", filename);
    tpl.assign("SIZE", String.valueOf(size));
    tpl.assign("TYPE", contentType);
    tpl.assign("HASH", Hex.encodeHexString(hash));
    tpl.assign("FILEID", newFile.getId());
    tpl.parse("main");
    response.getWriter().print(tpl.out());

    // Delete temp file
    uploadFile.delete();//from  ww w . j  av  a 2  s. co m

    // Log
    node.getLog().info("New file added (via web): " + newFile.getId() + " (" + newFile.getName() + ")");
}

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

@Path("/upload2")
@POST//from  w ww.  j  a v a  2  s.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);
    }
}

From source file:edu.lternet.pasta.portal.HarvesterServlet.java

/**
 * Process the uploaded EML file// w w w .jav a 2  s  .  c o  m
 * 
 * @param part The multipart form file data.
 * 
 * @return The uploaded EML file as File object.
 * 
 * @throws Exception
 */
private File processUploadedFile(Part part) throws Exception {

    File eml = null;

    if (part.getContentType() != null) {
        // save file Part to disk
        String fileName = getFilename(part);
        if (fileName != null && !fileName.isEmpty()) {
            long timestamp = new Date().getTime();
            String tmpDir = String.format("%s/%d", System.getProperty("java.io.tmpdir"), timestamp);
            Harvester.createDirectory(tmpDir);
            String tmpPath = String.format("%s/%s", tmpDir, fileName);
            part.write(tmpPath);
            eml = new File(tmpPath);
        }
    }

    return eml;
}

From source file:edu.lternet.pasta.portal.HarvesterServlet.java

/**
 * Process the uploaded data file//w ww . j  av  a  2 s.  c o  m
 * 
 * @param part The multipart form file data.
 * 
 * @return The uploaded data file as File object.
 * 
 * @throws Exception
 */
private String processDataFile(Part part, String harvestDir, String objectName) throws Exception {
    String fileName = null;

    if (part.getContentType() != null) {
        // save the data file to disk where it can be harvested
        fileName = getFilename(part);

        if (fileName != null && !fileName.isEmpty()) {

            if (!fileName.equals(objectName)) {
                String msg = String.format("Filename \"%s\" does not match objectName \"%s\".", fileName,
                        objectName);
                throw new UserErrorException(msg);
            }

            Harvester.createDirectory(harvestDir);
            String filePath = String.format("%s/%s", harvestDir, fileName);
            part.write(filePath);
        }
    }

    return fileName;
}

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

@Path("/upload1")
@POST//from   ww  w. java2 s.  co m
@Produces(MediaType.TEXT_PLAIN)
public String fileUpload1(@FormParam("file1") Part file1, @FormParam("file2") Part file2) throws IOException {
    if (file1 == null || file2 == null) {
        return "null file";
    }
    try (InputStream is1 = file1.getInputStream(); InputStream is2 = file2.getInputStream()) {
        String content1 = IOUtils.toString(is1);
        String content2 = IOUtils.toString(is2);
        return String.format("%s:%s:%s\n" + "%s:%s:%s", file1.getSubmittedFileName(), file1.getContentType(),
                content1, file2.getSubmittedFileName(), file2.getContentType(), content2);
    }
}

From source file:com.imagelake.uploads.Servlet_Upload.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Date d = new Date();
    SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
    String date = sm.format(d);/*from   www.j  av  a  2  s. co m*/

    String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
    UserDAOImp udi = new UserDAOImp();
    // gets values of text fields
    PrintWriter out = response.getWriter();

    String cat, imgtit, imgname, dominate, price, dimention, col1, col2, col3, col4, col5, col6, col7, col8,
            col9, size_string, uid;
    System.out.println("server name====" + request.getServerName());

    uid = request.getParameter("uid");
    imgname = request.getParameter("imgname");
    imgtit = request.getParameter("tit");
    cat = request.getParameter("cat");
    dimention = request.getParameter("dimention");
    dominate = request.getParameter("dominate");
    col1 = request.getParameter("col-1");
    col2 = request.getParameter("col-2");
    col3 = request.getParameter("col-3");
    col4 = request.getParameter("col-4");
    col5 = request.getParameter("col-5");
    col6 = request.getParameter("col-6");
    col7 = request.getParameter("col-7");
    col8 = request.getParameter("col-8");
    col9 = request.getParameter("col-9");
    size_string = request.getParameter("size");
    long size = 0;

    System.out.println(cat + " " + imgname + " " + col1 + " " + col2 + " " + col3 + " " + col4 + " " + col5
            + " " + col6 + " " + col7 + " " + col8 + " " + col9 + " //" + dominate + " " + size_string);
    System.out.println(request.getParameter("tit") + "bbbbb" + request.getParameter("cat"));
    InputStream inputStream = null; // input stream of the upload file

    System.out.println("woooooooooo" + imgtit.trim() + "hooooooooo");

    if (imgtit.equals("") || imgtit.equals(null) || cat.equals("") || cat.equals(null) || cat.equals("0")
            || dimention.equals("") || dimention.equals(null) && dominate.equals("")
            || dominate.equals(null) && col1.equals("") || col1.equals(null) && col2.equals("")
            || col2.equals(null) && col3.equals("") || col3.equals(null) && col4.equals("")
            || col4.equals(null) && col5.equals("") && col5.equals(null) && col6.equals("")
            || col6.equals(null) && col7.equals("") || col7.equals(null) && col8.equals("")
            || col8.equals(null) && col9.equals("") || col9.equals(null)) {
        System.out.println("error");

        out.write("error");
    } else {

        // obtains the upload file part in this multipart request 
        try {
            Part filePart = request.getPart("photo");

            if (filePart != null) {
                // prints out some information for debugging
                System.out.println("NAME:" + filePart.getName());
                System.out.println(filePart.getSize());
                size = filePart.getSize();
                System.out.println(filePart.getContentType());

                // obtains input stream of the upload file
                inputStream = filePart.getInputStream();
                System.out.println(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Connection conn = null; // connection to the database
        String message = null; // message will be sent back to client
        String fileName = null;
        try {

            // gets absolute path of the web application
            String applicationPath = request.getServletContext().getRealPath("");
            // constructs path of the directory to save uploaded file
            String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;

            // creates the save directory if it does not exists
            File fileSaveDir = new File(uploadFilePath);
            if (!fileSaveDir.exists()) {
                fileSaveDir.mkdirs();
            }
            System.out.println("Upload File Directory=" + fileSaveDir.getAbsolutePath());
            System.out.println("Upload File Directory2=" + fileSaveDir.getAbsolutePath() + "/" + imgname);

            //Get all the parts from request and write it to the file on server
            for (Part part : request.getParts()) {
                fileName = getFileName(part);
                if (!fileName.equals(null) || !fileName.equals("")) {
                    try {
                        part.write(uploadFilePath + File.separator + fileName);
                    } catch (Exception e) {
                        break;
                    }
                }

            }

            //GlassFish File Upload

            System.out.println(inputStream);

            if (inputStream != null) {

                // int id=new ImagesDAOImp().checkImagesId(dominate, col1, col2, col3, col4, col5, col6, col7, col8, col9);
                //   if(id==0){
                boolean sliceImage = new CreateImages().sliceImages(col1, col2, col3, col4, col5, col6, col7,
                        col8, col9, dominate, imgname, dimention, imgtit, cat, uid, date);
                if (sliceImage) {
                    AdminNotification a = new AdminNotification();
                    a.setUser_id(Integer.parseInt(uid));
                    a.setDate(timeStamp);

                    a.setShow(1);
                    a.setType(1);
                    String not = "New Image has uploaded by " + udi.getUn(Integer.parseInt(uid));
                    a.setNotification(not);

                    int an = new AdminNotificationDAOImp().insertNotificaation(a);
                    System.out.println("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP " + an);

                    boolean kl = new AdminHasNotificationDAOImp().insertNotification(udi.listAdminsIDs(), an,
                            1);
                    if (kl) {
                        out.write("ok");
                    } else {
                        System.out.println("error in sliceimage");
                        out.write("error");
                    }
                } else {
                    System.out.println("error in sliceimage");
                    out.write("error");
                }
                // }
                /*else{
                              System.out.println("error in id");
                        out.write("error");
                    }*/

            }

            // sends the statement to the database server

        } catch (Exception ex) {
            message = "ERROR: " + ex.getMessage();
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                // closes the database connection
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }

        }

    }

    //out.write("ok");
    //else code          

}

From source file:edu.lternet.pasta.portal.HarvesterServlet.java

/**
 * The doPost method of the servlet. <br>
 * //from w  ww .j  a va 2  s. co m
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request
 *          the request send by the client to the server
 * @param response
 *          the response send by the server to the client
 * @throws ServletException
 *           if an error occurred
 * @throws IOException
 *           if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    ArrayList<String> documentURLs = null;
    File emlFile = null;
    String emlTextArea = null;
    Harvester harvester = null;
    String harvestId = null;
    String harvestListURL = null;
    String harvestReportId = null;
    boolean isDesktopUpload = false;
    boolean isEvaluate = false;
    String uid = (String) httpSession.getAttribute("uid");
    String urlTextArea = null;
    String warningMessage = "";

    try {
        if (uid == null) {
            throw new PastaAuthenticationException(LOGIN_WARNING);
        } else {
            /*
             * The "metadataSource" request parameter can have a value of
             * "emlText", "emlFile", "urlList", "harvestList", or
             * "desktopHarvester". It is set as a hidden input field in 
             * each of the harvester forms.
             */
            String metadataSource = request.getParameter("metadataSource");

            /*
             * "mode" can have a value of "evaluate" or "upgrade". It is set
             * as the value of the submit button in each of the harvester
             * forms.
             */
            String mode = request.getParameter("submit");
            if ((mode != null) && (mode.equalsIgnoreCase("evaluate"))) {
                isEvaluate = true;
            }

            if ((metadataSource != null) && (!metadataSource.equals("desktopHarvester"))) {
                harvestId = generateHarvestId();
                if (isEvaluate) {
                    harvestReportId = uid + "-evaluate-" + harvestId;
                } else {
                    harvestReportId = uid + "-upload-" + harvestId;
                }
            }

            if (metadataSource != null) {
                if (metadataSource.equals("emlText")) {
                    emlTextArea = request.getParameter("emlTextArea");
                    if (emlTextArea == null || emlTextArea.trim().isEmpty()) {
                        warningMessage = "<p class=\"warning\">Please enter the text of an EML document into the text area.</p>";
                    }
                } else if (metadataSource.equals("emlFile")) {
                    Collection<Part> parts = request.getParts();
                    for (Part part : parts) {
                        if (part.getContentType() != null) {
                            // save EML file to disk
                            emlFile = processUploadedFile(part);
                        } else {
                            /*
                             * Parse the request parameters.
                             */
                            String fieldName = part.getName();
                            String fieldValue = request.getParameter(fieldName);
                            if (fieldName != null && fieldValue != null) {
                                if (fieldName.equals("submit") && fieldValue.equalsIgnoreCase("evaluate")) {
                                    isEvaluate = true;
                                } else if (fieldName.equals("desktopUpload")
                                        && fieldValue.equalsIgnoreCase("1")) {
                                    isDesktopUpload = true;
                                }
                            }
                        }
                    }
                } else if (metadataSource.equals("urlList")) {
                    urlTextArea = request.getParameter("urlTextArea");
                    if (urlTextArea == null || urlTextArea.trim().isEmpty()) {
                        warningMessage = "<p class=\"warning\">Please enter one or more EML document URLs into the text area.</p>";
                    } else {
                        documentURLs = parseDocumentURLsFromTextArea(urlTextArea);
                        warningMessage = CHECK_BACK_LATER;
                    }
                } else if (metadataSource.equals("harvestList")) {
                    harvestListURL = request.getParameter("harvestListURL");
                    if (harvestListURL == null || harvestListURL.trim().isEmpty()) {
                        warningMessage = "<p class=\"warning\">Please enter the URL to a Metacat Harvest List.</p>";
                    } else {
                        documentURLs = parseDocumentURLsFromHarvestList(harvestListURL);
                        warningMessage = CHECK_BACK_LATER;
                    }
                }
                /*
                 * If the metadata source is "desktopHarvester", we already have the
                 * EML file stored in a session attribute. Now we need to retrieve
                 * the data files from the brower's form fields and write the
                 * data files to a URL accessible location.
                 */
                else if (metadataSource.equals("desktopHarvester")) {
                    emlFile = (File) httpSession.getAttribute("emlFile");
                    ArrayList<Entity> entityList = parseEntityList(emlFile);
                    harvestReportId = (String) httpSession.getAttribute("harvestReportId");
                    String dataPath = servletContext.getRealPath(DESKTOP_DATA_DIR);
                    String harvestPath = String.format("%s/%s", dataPath, harvestReportId);

                    Collection<Part> parts = request.getParts();
                    String objectName = null;
                    Part filePart = null;

                    for (Part part : parts) {
                        if (part.getContentType() != null) {
                            // save data file to disk
                            //processDataFile(part, harvestPath);
                            filePart = part;
                        } else {
                            /*
                             * Parse the request parameters.
                             */
                            String fieldName = part.getName();
                            String fieldValue = request.getParameter(fieldName);
                            if (fieldName != null && fieldValue != null) {
                                if (fieldName.equals("submit") && fieldValue.equalsIgnoreCase("evaluate")) {
                                    isEvaluate = true;
                                } else if (fieldName.startsWith("object-name-")) {
                                    objectName = fieldValue;
                                }
                            }
                        }

                        if (filePart != null && objectName != null) {
                            processDataFile(filePart, harvestPath, objectName);
                            objectName = null;
                            filePart = null;
                        }

                    }

                    emlFile = transformDesktopEML(harvestPath, emlFile, harvestReportId, entityList);
                }
            } else {
                throw new IllegalStateException("No value specified for request parameter 'metadataSource'");
            }

            if (harvester == null) {
                harvester = new Harvester(harvesterPath, harvestReportId, uid, isEvaluate);
            }

            if (emlTextArea != null) {
                harvester.processSingleDocument(emlTextArea);
            } else if (emlFile != null) {
                if (isDesktopUpload) {
                    ArrayList<Entity> entityList = parseEntityList(emlFile);
                    httpSession.setAttribute("entityList", entityList);
                    httpSession.setAttribute("emlFile", emlFile);
                    httpSession.setAttribute("harvestReportId", harvestReportId);
                    httpSession.setAttribute("isEvaluate", new Boolean(isEvaluate));
                } else {
                    harvester.processSingleDocument(emlFile);
                }
            } else if (documentURLs != null) {
                harvester.setDocumentURLs(documentURLs);
                ExecutorService executorService = Executors.newCachedThreadPool();
                executorService.execute(harvester);
                executorService.shutdown();
            }
        }
    } catch (Exception e) {
        handleDataPortalError(logger, e);
    }

    request.setAttribute("message", warningMessage);

    /*
     * If we have a new reportId, and either there is no warning message or
     * it's the "Check back later" message, set the harvestReportID session
     * attribute to the new reportId value.
     */
    if (harvestReportId != null && harvestReportId.length() > 0
            && (warningMessage.length() == 0 || warningMessage.equals(CHECK_BACK_LATER))) {
        httpSession.setAttribute("harvestReportID", harvestReportId);
    }

    if (isDesktopUpload) {
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("./desktopHarvester.jsp");
        requestDispatcher.forward(request, response);
    } else if (warningMessage.length() == 0) {
        response.sendRedirect("./harvestReport.jsp");
    } else {
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("./harvester.jsp");
        requestDispatcher.forward(request, response);
    }

}