Example usage for javax.servlet ServletRequest getContentType

List of usage examples for javax.servlet ServletRequest getContentType

Introduction

In this page you can find the example usage for javax.servlet ServletRequest 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.teiid.olingo.web.ODataFilter.java

static void writeError(ServletRequest request, TeiidProcessingException e, HttpServletResponse httpResponse,
        int statusCode) throws IOException {
    httpResponse.setStatus(statusCode);// www. j av a2s .  c  om
    ContentType contentType = ContentType.parse(request.getContentType());
    PrintWriter writer = httpResponse.getWriter();
    String code = e.getCode() == null ? "" : e.getCode(); //$NON-NLS-1$
    String message = e.getMessage() == null ? "" : e.getMessage(); //$NON-NLS-1$
    if (contentType == null || contentType.isCompatible(ContentType.APPLICATION_JSON)) {
        httpResponse.setHeader(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_JSON.toContentTypeString());
        writer.write("{ \"error\": { \"code\": \"" + StringEscapeUtils.escapeJson(code) + "\", \"message\": \"" //$NON-NLS-1$//$NON-NLS-2$
                + StringEscapeUtils.escapeJson(message) + "\" } }"); //$NON-NLS-1$
    } else {
        httpResponse.setHeader(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_XML.toContentTypeString());
        writer.write("<m:error xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\"><m:code>" //$NON-NLS-1$
                + StringEscapeUtils.escapeXml10(code) + "</m:code><m:message>" //$NON-NLS-1$
                + StringEscapeUtils.escapeXml10(message) + "</m:message></m:error>"); //$NON-NLS-1$
    }
    writer.close();
}

From source file:org.expath.servlex.tools.ContentType.java

/**
 * Parse the Content-Type header value of the request.
 * // w w w  .  j av a2s  .c om
 * @throws TechnicalException If the format of the value is not correct.
 */
public ContentType(ServletRequest request) throws TechnicalException {
    this(request.getContentType());
}

From source file:org.apache.oltu.oauth2.ext.dynamicreg.server.request.JSONHttpServletRequestWrapper.java

/**
 * Lazily read JSON from request//from   w  w  w.j  a v a 2  s  . c o m
 *
 * @throws OAuthProblemException
 */
private String readJsonBody() {
    try {
        final ServletRequest request = getRequest();
        String contentType = request.getContentType();
        final String expectedContentType = OAuth.ContentType.JSON;
        if (!OAuthUtils.hasContentType(contentType, expectedContentType)) {
            return "";
        }

        final ServletInputStream inputStream = request.getInputStream();
        if (inputStream == null) {
            return "";
        }

        bodyRead = true;
        return OAuthUtils.saveStreamAsString(inputStream);
    } catch (Exception e) {
        log.error("Dynamic client registration error: ", e);
        throw new OAuthRuntimeException("OAuth server error");
    }
}

From source file:com.github.achatain.nopasswordauthentication.di.filters.JsonFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (HTTPMethod.GET.name().equals(((HttpServletRequest) request).getMethod())) {
        chain.doFilter(request, response);
        return;/*from   www.  ja  va 2  s  . co m*/
    }

    String contentType = request.getContentType();

    if (JSON_TYPES.contains(StringUtils.lowerCase(contentType))) {
        chain.doFilter(request, response);
    } else {
        throw new UnsupportedContentTypeException(
                String.format("Expected a JSON content type but got [%s]", contentType));
    }
}

From source file:org.zilverline.web.RequestDumperFilter.java

/**
 * Time the processing that is performed by all subsequent filters in the current filter stack, including the ultimately invoked
 * servlet.//www  .j  a  va  2  s.c  om
 * 
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param chain The filter chain we are processing
 * 
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    if (filterConfig == null) {
        return;
    }

    log.debug("Request Received at " + (new Timestamp(System.currentTimeMillis())));
    log.debug(" characterEncoding=" + request.getCharacterEncoding());
    log.debug("     contentLength=" + request.getContentLength());
    log.debug("       contentType=" + request.getContentType());
    log.debug("            locale=" + request.getLocale());
    Enumeration locales = request.getLocales();
    StringBuffer localesBuffer = new StringBuffer("           locales=");
    boolean first = true;
    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        if (first) {
            first = false;
        } else {
            localesBuffer.append(", ");
        }
        localesBuffer.append(locale.toString());
    }
    log.debug(localesBuffer);
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        StringBuffer paramsBuffer = new StringBuffer();
        paramsBuffer.append("         parameter=" + name + "=");
        String[] values = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                paramsBuffer.append(", ");
            }
            paramsBuffer.append(values[i]);
        }
        log.debug(paramsBuffer);
    }
    log.debug("          protocol=" + request.getProtocol());
    log.debug("        remoteAddr=" + request.getRemoteAddr());
    log.debug("        remoteHost=" + request.getRemoteHost());
    log.debug("            scheme=" + request.getScheme());
    log.debug("        serverName=" + request.getServerName());
    log.debug("        serverPort=" + request.getServerPort());
    log.debug("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        log.debug("---------------------------------------------");
        HttpServletRequest hrequest = (HttpServletRequest) request;
        log.debug("       contextPath=" + hrequest.getContextPath());
        Cookie[] cookies = hrequest.getCookies();
        if (cookies == null) {
            cookies = new Cookie[0];
        }
        for (int i = 0; i < cookies.length; i++) {
            log.debug("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }
        names = hrequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = hrequest.getHeader(name);
            log.debug("            header=" + name + "=" + value);
        }
        log.debug("            method=" + hrequest.getMethod());
        log.debug("          pathInfo=" + hrequest.getPathInfo());
        log.debug("       queryString=" + hrequest.getQueryString());
        log.debug("        remoteUser=" + hrequest.getRemoteUser());
        log.debug("requestedSessionId=" + hrequest.getRequestedSessionId());
        log.debug("        requestURI=" + hrequest.getRequestURI());
        log.debug("       servletPath=" + hrequest.getServletPath());
    }
    log.debug("=============================================");

    // Pass control on to the next filter
    chain.doFilter(request, response);

}

From source file:org.soaplab.clients.spinet.filters.RequestDumperFilter.java

/**
 * Time the processing that is performed by all subsequent filters in the
 * current filter stack, including the ultimately invoked servlet.
 *
 * @param request The servlet request we are processing
 * @param result The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 *///from   w  ww  . j a v  a  2  s .c om
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (filterConfig == null)
        return;

    // Render the generic servlet request properties
    StringWriter sw = new StringWriter();
    PrintWriter writer = new PrintWriter(sw);
    writer.println("Request Received at " + (new Timestamp(System.currentTimeMillis())));
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");
    Enumeration locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        if (first)
            first = false;
        else
            writer.print(", ");
        writer.print(locale.toString());
    }
    writer.println();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        writer.print("         parameter=" + name + "=");
        String values[] = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0)
                writer.print(", ");
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        writer.println("---------------------------------------------");
        HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());
        Cookie cookies[] = hrequest.getCookies();
        if (cookies == null)
            cookies = new Cookie[0];
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }
        names = hrequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());
    }
    writer.println("=============================================");

    // Log the resulting string
    writer.flush();
    filterConfig.getServletContext().log(sw.getBuffer().toString());
    log.info(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(request, response);

}

From source file:edu.vt.middleware.servlet.filter.RequestDumperFilter.java

/** {@inheritDoc} */
@SuppressWarnings(value = "unchecked")
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (this.config == null) {
        return;//from   w  w  w . j  a v a2 s .c o m
    }

    // Just pass through to next filter if we're not at TRACE level
    if (!logger.isTraceEnabled()) {
        chain.doFilter(request, response);
        return;
    }

    // Create a variable to hold the (possibly different) request
    // passed to downstream filters
    ServletRequest downstreamRequest = request;

    // Render the generic servlet request properties
    final StringWriter sw = new StringWriter();
    final PrintWriter writer = new PrintWriter(sw);
    writer.println("Dumping request...");
    writer.println("-----------------------------------------------------");
    writer.println("REQUEST received " + Calendar.getInstance().getTime());
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");

    final Enumeration<Locale> locales = request.getLocales();
    for (int i = 0; locales.hasMoreElements(); i++) {
        if (i > 0) {
            writer.print(", ");
        }
        writer.print(locales.nextElement());
    }
    writer.println();

    final Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        final String name = paramNames.nextElement();
        writer.print("         parameter=" + name + "=");

        final String[] values = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                writer.print(", ");
            }
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        final HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());

        Cookie[] cookies = hrequest.getCookies();
        if (cookies == null) {
            cookies = new Cookie[0];
        }
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }

        final Enumeration<String> headerNames = hrequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String name = headerNames.nextElement();
            final String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());

        // Create a wrapped request that contains the request body
        // and that we will pass to downstream filters
        final ByteArrayRequestWrapper wrappedRequest = new ByteArrayRequestWrapper(hrequest);
        downstreamRequest = wrappedRequest;
        writer.println(wrappedRequest.getRequestBodyAsString());
    }
    writer.println("-----------------------------------------------------");

    // Log the resulting string
    writer.flush();
    logger.trace(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(downstreamRequest, response);
}

From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.TunnelServlet.java

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    monitor.fireOnRequest(request, response);
    if (response.isCommitted())
        return;//from  w  ww  .j  a va  2  s  .com

    ExtendedHttpMethod postMethod;

    // for this create ui server and port, properties.
    InetSocketAddress inetAddress = new InetSocketAddress(sslEndPoint, sslPort);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET"))
        postMethod = new ExtendedGetMethod();
    else
        postMethod = new ExtendedPostMethod();

    JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getRemoteHost());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setTargetURL(this.prot + inetAddress.getHostName());

    CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream());

    // copy headers
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hdr = (String) headerNames.nextElement();
        String lhdr = hdr.toLowerCase();

        if ("host".equals(lhdr)) {
            Enumeration<?> vals = httpRequest.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val.startsWith("127.0.0.1")) {
                    postMethod.addRequestHeader(hdr, sslEndPoint);
                }
            }
            continue;
        }

        Enumeration<?> vals = httpRequest.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                postMethod.addRequestHeader(hdr, val);
            }
        }

    }

    if (postMethod instanceof ExtendedPostMethod)
        ((ExtendedPostMethod) postMethod)
                .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType()));

    HostConfiguration hostConfiguration = new HostConfiguration();

    httpRequest.getProtocol();
    hostConfiguration.getParams().setParameter(SoapUIHostConfiguration.SOAPUI_SSL_CONFIG,
            settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPATH, "") + " "
                    + settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPASSWORD, ""));
    hostConfiguration.setHost(new URI(this.prot + sslEndPoint, true));

    hostConfiguration = ProxyUtils.initProxySettings(settings, httpState, hostConfiguration, prot + sslEndPoint,
            new DefaultPropertyExpansionContext(project));

    if (sslEndPoint.indexOf("/") < 0)
        postMethod.setPath("/");
    else
        postMethod.setPath(sslEndPoint.substring(sslEndPoint.indexOf("/"), sslEndPoint.length()));

    monitor.fireBeforeProxy(request, response, postMethod, hostConfiguration);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
        if (httpState == null)
            httpState = new HttpState();
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod, httpState);
    } else {
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod);
    }
    capturedData.stopCapture();

    capturedData.setRequest(capture.getCapturedData());
    capturedData.setRawResponseBody(postMethod.getResponseBody());
    capturedData.setResponseHeader(postMethod);
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), postMethod, capture));
    capturedData.setRawResponseData(
            getResponseToBytes(response.toString(), postMethod, capturedData.getRawResponseBody()));

    monitor.fireAfterProxy(request, response, postMethod, capturedData);

    StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
    // copy headers to response
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    for (String name : responseHeaders.keySet()) {
        for (String header : responseHeaders.get(name))
            httpResponse.addHeader(name, header);

    }

    IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream());

    postMethod.releaseConnection();

    synchronized (this) {
        monitor.addMessageExchange(capturedData);
    }

    capturedData = null;
}