Example usage for javax.servlet.http HttpServletRequest getContentType

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

Introduction

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

Prototype

public String getContentType();

Source Link

Document

Returns the MIME type of the body of the request, or null if the type is not known.

Usage

From source file:org.apache.ambari.view.tez.ProxyServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String urlToRead = URLDecoder.decode(request.getParameter("url"));

    response.setContentType(request.getContentType());

    if (LOG.isDebugEnabled()) {
        LOG.debug("Requesting data from ATS, url=" + urlToRead);
    }/* w w  w. j  a v a 2s .co m*/

    InputStream resultInputStream;
    String result = "";
    // When in doubt, assume error
    int responseCode = Status.INTERNAL_SERVER_ERROR.getStatusCode();
    HttpURLConnection connection;
    try {
        // Use nullData as null string and null inputstream cannot be disambiguated
        // URL Stream Provider will automatically inject the doAs param with the current
        // user's info
        connection = urlConnectionProvider.getConnectionAsCurrent(urlToRead, HttpMethod.GET, nullData,
                emptyHeaders);
        responseCode = connection.getResponseCode();

        if (LOG.isDebugEnabled()) {
            LOG.debug("Received response from ATS, url=" + urlToRead + ", responseCode=" + responseCode);
        }

        if (responseCode >= Response.Status.BAD_REQUEST.getStatusCode()) {
            resultInputStream = connection.getErrorStream();
        } else {
            resultInputStream = connection.getInputStream();
        }

        result = IOUtils.toString(resultInputStream);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Received response from ATS, url=" + urlToRead + ", responseCode=" + responseCode
                    + ", responseBodyLen=" + result.length());
        }

    } catch (IOException e) {
        // We might kill the ambari server by logging this error every time a call fails
        if (LOG.isDebugEnabled()) {
            LOG.warn("Failed to retrieve data from ATS, url=" + urlToRead, e);
        }
        responseCode = Status.INTERNAL_SERVER_ERROR.getStatusCode();
        result = e.toString();
    } catch (Exception e) {
        LOG.warn("Unknown Exception: Failed to retrieve data from ATS, url=" + urlToRead, e);
        responseCode = Status.INTERNAL_SERVER_ERROR.getStatusCode();
        result = e.toString();
    } finally {
        // not disconnecting http conn as it might be cached/re-used internally
        // in the UrlStreamProvider
    }

    response.setStatus(responseCode);
    if (result != null) {
        PrintWriter writer = response.getWriter();
        writer.print(result);
    }
}

From source file:org.vuphone.vandyupon.media.incoming.event.ImageParser.java

public boolean isRequestValid(HttpServletRequest request) {
    boolean isValid = false;

    if (request.getParameter(ImageParser.TIME) == null) {
        logger_.log(Level.SEVERE, "Unable to get time from the request");
    } else if (request.getContentType() == null
            || !request.getContentType().equalsIgnoreCase(ImageParser.CONTENT_TYPE)) {
        logger_.log(Level.SEVERE,
                "Expected Content Type to be " + ImageParser.CONTENT_TYPE + " not " + request.getContentType());
    } else if (request.getContentLength() <= 0) {
        logger_.log(Level.SEVERE, "Expected Content Length to be greater than 0");
    } else if (request.getParameter(ImageParser.EVENTID) == null) {
        logger_.log(Level.SEVERE, "Unable to get wreckid from the request");
    } else {//  www  . ja  v a2  s .co m
        isValid = true;
    }
    return isValid;
}

From source file:org.jamwiki.servlets.UploadServlet.java

/**
 *
 */// www .j a va 2s .c om
public ModelAndView handleJAMWikiRequest(HttpServletRequest request, HttpServletResponse response,
        ModelAndView next, WikiPageInfo pageInfo) throws Exception {
    String contentType = ((request.getContentType() != null) ? request.getContentType().toLowerCase() : "");
    if (contentType.indexOf("multipart") == -1) {
        view(request, next, pageInfo);
    } else {
        upload(request, next, pageInfo);
    }
    return next;
}

From source file:org.mortbay.servlet.LLabsMultiPartFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */// ww w. j a v  a2  s .  c  o m
@SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    logger.info("Received uploadRequest:" + request);
    if (Log.isDebugEnabled())
        Log.debug(getClass().getName() + ">>> Received Request");

    HttpServletRequest srequest = (HttpServletRequest) request;
    if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) {
        chain.doFilter(request, response);
        return;
    }
    if (ServletFileUpload.isMultipartContent(srequest)) {
        // Parse the request

        List<File> tempFiles = new ArrayList<File>();
        try {

            MultiMap params = new MultiMap();

            logger.info("Parsing Request");

            List<DiskFileItem> fileItems = uploadHandler.parseRequest(srequest);

            logger.info("Done Parsing Request, got FileItems:" + fileItems);

            StringBuilder filenames = new StringBuilder();

            for (final DiskFileItem diskFileItem : fileItems) {
                if (diskFileItem.getName() == null && diskFileItem.getFieldName() != null
                        && diskFileItem.getFieldName().length() > 0) {
                    params.put(diskFileItem.getFieldName(), diskFileItem.getString());
                    continue;
                }
                if (diskFileItem.getName() == null)
                    continue;
                final File tempFile = File.createTempFile("upload" + diskFileItem.getName(), ".tmp");
                tempFiles.add(tempFile);

                diskFileItem.write(tempFile);
                request.setAttribute(diskFileItem.getName(), tempFile);
                filenames.append(diskFileItem.getName()).append(",");
            }
            params.put("Filenames", filenames.toString());
            logger.info("passing on filter");
            chain.doFilter(new Wrapper(srequest, params), response);

            for (final DiskFileItem diskFileItem : fileItems) {
                diskFileItem.delete();
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            Log.warn(getClass().getName() + "MPartRequest, ERROR:" + e.getMessage());
            logger.error("FileUpload Failed", e);
            writeResponse((HttpServletResponse) response, HttpServletResponse.SC_EXPECTATION_FAILED);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            Log.warn(getClass().getName() + "MPartRequest, ERROR:" + e.getMessage());
            e.printStackTrace();
            writeResponse((HttpServletResponse) response, HttpServletResponse.SC_EXPECTATION_FAILED);
        } finally {
            for (File tempFile : tempFiles) {
                try {
                    tempFile.delete();
                } catch (Throwable t) {
                }
            }
        }
    }

}

From source file:org.n52.iceland.service.Service.java

private MediaType getContentType(HttpServletRequest request) throws HTTPException {
    if (request.getContentType() == null) {
        // default to KVP for GET requests
        if (request.getMethod().equals(HTTPMethods.GET)) {
            return MediaTypes.APPLICATION_KVP;
        } else {/*from   ww w  . j a  v a  2  s. co  m*/
            throw new HTTPException(HTTPStatus.BAD_REQUEST);
        }
    } else {
        try {
            return MediaType.parse(request.getContentType());
        } catch (IllegalArgumentException e) {
            throw new HTTPException(HTTPStatus.BAD_REQUEST, e);
        }
    }
}

From source file:org.biokoframework.http.response.impl.AbstractHttpResponseBuilder.java

@Override
public final void build(HttpServletRequest request, HttpServletResponse response, Fields input, Fields output)
        throws IOException, RequestNotSupportedException {
    if (request.getMethod().equals("POST") || request.getMethod().equals("PUT")) {
        checkAcceptType(Arrays.asList(request.getContentType()), getRequestExtension(request.getPathInfo()));
    } else {/*from w  ww  . j  av a  2 s .c o m*/
        checkAcceptType(getAccept(request), getRequestExtension(request.getPathInfo()));
    }

    response.setStatus(HttpStatus.SC_OK);

    safelyBuild(request, response, input, output);
}

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. j a  va  2s .  c om
    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.craftercms.engine.http.impl.HttpProxyImpl.java

protected void copyOriginalRequestBody(HttpPost httpRequest, HttpServletRequest request) throws IOException {
    int contentLength = request.getContentLength();
    if (contentLength > 0) {
        String contentType = request.getContentType();
        InputStream content = request.getInputStream();

        httpRequest.setEntity(new InputStreamEntity(content, contentLength, ContentType.create(contentType)));
    }//from  w w w  .j a  v a 2  s.  c  o  m
}

From source file:de.ingrid.interfaces.csw.server.CSWServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//*from   w  w  w  .j  a v  a 2 s  . c om*/
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {
        if (request.getHeader("Keep-Alive") != null && request.getContentLength() == -1) {
            Log.debug("Ignore keep-alive request.");
        } else if (request.getContentType().toLowerCase().indexOf("application/soap+xml") != -1) {
            this.serverFacade.handleSoapRequest(request, response);
        } else {
            this.serverFacade.handlePostRequest(request, response);
        }
    } catch (Exception ex) {
        throw new ServletException("POST failed: " + ex.getMessage(), ex);
    }
}

From source file:info.magnolia.cms.filters.CosMultipartRequestFilter.java

@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    String type = null;/*from   w w  w.j  av a 2  s  . c  o  m*/
    String type1 = request.getHeader("Content-Type");
    String type2 = request.getContentType();
    if (type1 == null && type2 != null) {
        type = type2;
    } else if (type2 == null && type1 != null) {
        type = type1;
    } else if (type1 != null) {
        type = (type1.length() > type2.length() ? type1 : type2);
    }
    boolean isMultipart = (type != null) && type.toLowerCase().startsWith("multipart/form-data");
    MultipartForm mpf = null;
    try {
        if (isMultipart) {
            mpf = parseParameters(request);
            request = new MultipartRequestWrapper(request, mpf);
            MgnlContext.push(request, response);
        }
        try {
            chain.doFilter(request, response);
        } finally {
            if (isMultipart) {
                MgnlContext.pop();
            }
        }
    } finally {
        if (mpf != null) {
            Iterator<Document> keys = mpf.getDocuments().values().iterator();
            while (keys.hasNext()) {
                Document doc = keys.next();
                if (doc != null && doc.getFile() != null && doc.getFile().exists()) {
                    doc.delete();
                }
            }
        }
    }
}