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:com.cloudera.oryx.app.serving.AbstractOryxResource.java

protected static InputStream maybeDecompress(Part item) throws IOException {
    InputStream in = item.getInputStream();
    String contentType = item.getContentType();
    if (contentType != null) {
        switch (contentType) {
        case "application/zip":
            in = new ZipInputStream(in);
            break;
        case "application/gzip":
        case "application/x-gzip":
            in = new GZIPInputStream(in);
            break;
        }//from   w  ww.  j  a  v a2s  . c  om
    }
    return in;
}

From source file:com.playright.servlet.DataController.java

private static CoverageData getCoverageDateFromRequest(HttpServletRequest request) throws ServletException {
    CoverageData cd = new CoverageData();
    try {//from  w w w. j  av  a  2 s .c o  m
        if (!"".equalsIgnoreCase(request.getParameter("id")) && request.getParameter("id") != null) {
            cd.setId(Integer.parseInt(request.getParameter("id")));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        java.util.Date ud = sdf.parse(request.getParameter("newsDate"));
        cd.setNewsDate(new java.sql.Date(ud.getTime()));
        cd.setNewspaper(request.getParameter("newspaper"));
        cd.setHeadline(request.getParameter("headline"));
        cd.setLanguage(request.getParameter("language"));
        cd.setEdition(request.getParameter("edition"));
        cd.setSupplement(request.getParameter("supplement"));
        cd.setSource(request.getParameter("source"));
        if (!"".equalsIgnoreCase(request.getParameter("pageNo")) && request.getParameter("pageNo") != null) {
            cd.setPageNo(Integer.parseInt(request.getParameter("pageNo")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("height")) && request.getParameter("height") != null) {
            cd.setHeight(Integer.parseInt(request.getParameter("height")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("width")) && request.getParameter("width") != null) {
            cd.setWidth(Integer.parseInt(request.getParameter("width")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("totalArticleSize"))
                && request.getParameter("totalArticleSize") != null) {
            cd.setTotalArticleSize(Integer.parseInt(request.getParameter("totalArticleSize")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("circulationFigure"))
                && request.getParameter("circulationFigure") != null) {
            cd.setCirculationFigure(Integer.parseInt(request.getParameter("circulationFigure")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("journalistFactor"))
                && request.getParameter("journalistFactor") != null) {
            cd.setJournalistFactor(Integer.parseInt(request.getParameter("journalistFactor")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("quantitativeAve"))
                && request.getParameter("quantitativeAve") != null) {
            cd.setQuantitativeAve(new BigDecimal(request.getParameter("quantitativeAve")));
        }
        if (!"".equalsIgnoreCase(request.getParameter("imageExists"))
                && request.getParameter("imageExists") != null) {
            cd.setImageExists(request.getParameter("imageExists"));
        }
        Blob b = null;
        String fileName = "";
        String contentType = "";
        try {
            Part filePart = request.getPart("image");
            InputStream fileContent = filePart.getInputStream();
            byte[] bytes = IOUtils.toByteArray(fileContent);
            b = new SerialBlob(bytes);
            fileName = filePart.getSubmittedFileName();
            contentType = filePart.getContentType();
        } catch (IOException ex) {
            Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (b != null && b.length() != 0) {
            cd.setImageBlob(b);
            cd.setImageFileName(fileName);
            cd.setImageType(contentType);
        }
    } catch (ParseException ex) {
        Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return cd;
}

From source file:com.sishuok.chapter4.web.servlet.UploadServlet.java

private String getFileName(final Part part) {
    if (part == null) {
        return null;
    }//from w w w.  j  a  v a2s  . c  om

    if (part.getContentType() == null) {
        return null;
    }

    String contentDisposition = part.getHeader("content-disposition");

    if (StringUtils.isEmpty(contentDisposition)) {
        return null;
    }
    // form-data; name="file1"; filename="TODO.txt"
    return StringUtils.substringBetween(contentDisposition, "filename=\"", "\"");

}

From source file:net.myrrix.web.servlets.IngestServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    MyrrixRecommender recommender = getRecommender();

    boolean fromBrowserUpload = request.getContentType().startsWith("multipart/form-data");

    Reader reader;// ww  w  .  ja va  2s . co  m
    if (fromBrowserUpload) {

        Collection<Part> parts = request.getParts();
        if (parts == null || parts.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No form data");
            return;
        }
        Part part = parts.iterator().next();
        String partContentType = part.getContentType();
        InputStream in = part.getInputStream();
        if ("application/zip".equals(partContentType)) {
            in = new ZipInputStream(in);
        } else if ("application/gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/x-gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        } else if ("application/x-bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        }
        reader = new InputStreamReader(in, Charsets.UTF_8);

    } else {

        String charEncodingName = request.getCharacterEncoding();
        Charset charEncoding = charEncodingName == null ? Charsets.UTF_8 : Charset.forName(charEncodingName);
        String contentEncoding = request.getHeader(HttpHeaders.CONTENT_ENCODING);
        if (contentEncoding == null) {
            reader = request.getReader();
        } else if ("gzip".equals(contentEncoding)) {
            reader = new InputStreamReader(new GZIPInputStream(request.getInputStream()), charEncoding);
        } else if ("zip".equals(contentEncoding)) {
            reader = new InputStreamReader(new ZipInputStream(request.getInputStream()), charEncoding);
        } else if ("bzip2".equals(contentEncoding)) {
            reader = new InputStreamReader(new BZip2CompressorInputStream(request.getInputStream()),
                    charEncoding);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported Content-Encoding");
            return;
        }

    }

    try {
        recommender.ingest(reader);
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
        return;
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    } catch (TasteException te) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
        getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
        return;
    }

    String referer = request.getHeader(HttpHeaders.REFERER);
    if (fromBrowserUpload && referer != null) {
        // Parsing avoids response splitting
        response.sendRedirect(new URL(referer).toString());
    }

}

From source file:org.apache.wicket.protocol.http.servlet.ServletPartFileItem.java

/**
 * Constructor//  ww w.  j  a  v  a  2 s  .c  om
 */
ServletPartFileItem(Part part) {
    Args.notNull(part, "part");
    this.part = part;

    String contentType = part.getContentType();
    this.isFormField = contentType == null;
}

From source file:uk.ac.dundee.computing.aec.instagrim.servlets.EditProfile.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w  w w  . ja v a 2s  .  com*/
 * @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 {
    Part part = request.getPart("upfile");
    System.out.println("Part Name " + part.getName());
    String type = part.getContentType();
    String filename = part.getSubmittedFileName();
    InputStream is = request.getPart(part.getName()).getInputStream();
    int i = is.available();
    HttpSession session = request.getSession();
    LoggedIn lg = (LoggedIn) session.getAttribute("LoggedIn");
    String username = "majed";
    if (lg.getlogedin()) {
        username = lg.getUsername();
    }
    if (i > 0) {
        byte[] b = new byte[i + 1];
        is.read(b);
        System.out.println("Length : " + b.length);
        PicModel tm = new PicModel();
        tm.setCluster(cluster);
        String message = " ";
        java.util.UUID picid = tm.insertPic(b, type, filename, username, message);
        session.setAttribute("picid", picid);
        is.close();
    }

    PrintWriter out = response.getWriter();
    User u = new User();
    u.setCluster(cluster);
    String first_name = (String) request.getParameter("first_name");
    String last_name = (String) request.getParameter("last_name");
    String interest = (String) request.getParameter("interest");
    String email = (String) request.getParameter("email");
    String address = (String) request.getParameter("address");
    out.println(first_name);
    java.util.UUID picid;
    picid = (java.util.UUID) session.getAttribute("picid");
    u.setUserProfile(username, first_name, last_name, interest, email, address, picid);
    java.util.LinkedList<String> userProfile = u.getUserProfile(username);
    session.setAttribute("profile", userProfile);
    RequestDispatcher rd = request.getRequestDispatcher("profile.jsp");
    rd.forward(request, response);
}

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 = "/";
    }/*from   w ww .  java 2s.  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:beans.DecryptFileBean.java

public void validateFile(FacesContext ctx, UIComponent comp, Object value) {
    if (getUser() != null) {
        Part file = (Part) value;
        if (file != null) {
            status = "";
            if (file.getSize() > 1024) {
                status += "- File too big.\n";
            }/*from   w  w w  .j a  v  a 2s .  co  m*/
            if (!"text/plain".equals(file.getContentType())) {
                status += "- " + file.getContentType() + " content was found in " + file.getName()
                        + ". Expected text/plain. Please select a text file.";
            }
        }
    } else {
        status = "You are not logged in.";
    }
}

From source file:com.sishuok.chapter4.web.servlet.UploadServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    try {//w w w.  j ava2  s.c o m

        //servlet?Partnull
        //9.0.4.v20130625 ??
        System.out.println(req.getParameter("name"));

        //?Part
        System.out.println("\n\n==========file1");
        Part file1Part = req.getPart("file1"); //?? ?Part
        InputStream file1PartInputStream = file1Part.getInputStream();
        System.out.println(IOUtils.toString(file1PartInputStream));
        file1PartInputStream.close();

        // ??
        System.out.println("\n\n==========file2");
        Part file2Part = req.getPart("file2");
        InputStream file2PartInputStream = file2Part.getInputStream();
        System.out.println(IOUtils.toString(file2PartInputStream));
        file2PartInputStream.close();

        System.out.println("\n\n==========parameter name");
        //????
        System.out.println(IOUtils.toString(req.getPart("name").getInputStream()));
        //Part??? jettyparameters??
        System.out.println(req.getParameter("name"));

        //?? ? req.getInputStream(); ??

        System.out.println("\n\n=============all part");
        for (Part part : req.getParts()) {
            System.out.println("\n\n=========name:::" + part.getName());
            System.out.println("=========size:::" + part.getSize());
            System.out.println("=========content-type:::" + part.getContentType());
            System.out
                    .println("=========header content-disposition:::" + part.getHeader("content-disposition"));
            System.out.println("=========file name:::" + getFileName(part));
            InputStream partInputStream = part.getInputStream();
            System.out.println("=========value:::" + IOUtils.toString(partInputStream));

            //
            partInputStream.close();
            // ? ? ?
            part.delete();

        }

    } catch (IllegalStateException ise) {
        //
        ise.printStackTrace();
        String errorMsg = ise.getMessage();
        if (errorMsg.contains("Request exceeds maxRequestSize")) {
            //?
        } else if (errorMsg.contains("Multipart Mime part file1 exceeds max filesize")) {
            //? ??
        } else {
            //
        }
    }

}

From source file:com.kirayim.homesec.service.impl.ImageManagerImpl.java

@Override
public Image handleFileUpload(long cameraId, HttpServletRequest request) {
    String extension = null;//from ww  w  .j a v a  2s.c  o m
    Date uploadTime = new Date();

    String encoding = request.getCharacterEncoding();

    if (encoding == null) {
        try {
            request.setCharacterEncoding(encoding = "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            logger.warn("Bad encoding", ex);
        }
    }

    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    Camera camera = cameraManager.get(cameraId);

    if (camera == null) {
        throw new NotAllowedException("Imvalid camera ID");
    }

    if (!camera.getOwner().equals(user)) {
        throw new NotAllowedException("Camera doesn't belong to current user");
    }

    /* -------------------------------------------------
     * Calculate output file name
     * ------------------------------------------------- */

    String name = String.format("homesec_image_%1$08d_%2$TY%2$Tm%2$Td_%2$TH%2$TM%2$TS%2$TL",
            camera.getCameraId(), uploadTime);

    /* -------------------------------------------------
     * Get uploaded file and write to destination
     * ------------------------------------------------- */

    try {
        if (request.getParts().size() > 1) {
            throw new NotAllowedException("Only one image upload per transaction");
        }

        for (Part part : request.getParts()) {
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            String contentType = part.getContentType();

            if (contentType != null) {
                try {
                    MimeTypes allTypes = MimeTypes.getDefaultMimeTypes();
                    MimeType mimeType = allTypes.forName(contentType);

                    extension = mimeType.getExtension();

                    name += extension;

                } catch (MimeTypeException mimeTypeException) {
                    logger.warn("Mime? ", mimeTypeException);
                }
            }

            File outputFile = new File(uploadDir, name);

            OutputStream out = new FileOutputStream(outputFile);

            InputStream in = part.getInputStream();

            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    } catch (IOException | ServletException e) {
        throw new BadRequestException(e);
    }

    /* -------------------------------------------------
     * If extension is unknown, re-read file to try
     * and get extension
     * ------------------------------------------------- */

    if (extension == null) {
        // TODO:
    }

    /* -------------------------------------------------
     * Save image record in DB
     * ------------------------------------------------- */

    Image image = new Image(camera, name, uploadTime);

    dao.save(image);

    return image;
}