Java Code Examples for javax.ws.rs.container.ContainerRequestContext#getMediaType()

The following examples show how to use javax.ws.rs.container.ContainerRequestContext#getMediaType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultFormEntityProvider.java    From krazo with Apache License 2.0 6 votes vote down vote up
@Override
public Form getForm(ContainerRequestContext context) throws IOException {
    final InputStream is = context.getEntityStream();

    // Ensure stream can be restored for next interceptor
    InputStream bufferedStream;
    if (is.markSupported()) {
        bufferedStream = is;
    } else {
        bufferedStream = new BufferedInputStream(is);
    }
    bufferedStream.mark(Integer.MAX_VALUE);

    final MediaType contentType = context.getMediaType();

    final String charset = contentType.getParameters().get("charset");
    final String entity = toString(bufferedStream, charset != null ? charset : DEFAULT_CHARSET);

    final Form form = parseForm(entity);

    bufferedStream.reset();
    context.setEntityStream(bufferedStream);

    return form;

}
 
Example 2
Source File: LogFilter.java    From container with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext request) throws IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("=== LogFilter BEGIN ===");
        logger.debug("Method: {}", request.getMethod());
        logger.debug("URL: {}", UriUtil.encode(request.getUriInfo().getAbsolutePath()));
        for (final String key : request.getHeaders().keySet()) {
            logger.debug(key + " : " + request.getHeaders().get(key));
        }
        final List<MediaType> mediaTypes =
            Lists.newArrayList(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE,
                MediaType.TEXT_PLAIN_TYPE, MediaType.TEXT_XML_TYPE, MediaType.TEXT_HTML_TYPE);
        if (request.getMediaType() != null && mediaTypes.contains(request.getMediaType())) {
            if (request.hasEntity()) {
                final String body = IOUtils.toString(request.getEntityStream());
                request.setEntityStream(IOUtils.toInputStream(body));
                logger.debug("Body: {}", body);
            }
        }
        logger.debug("=== LogFilter END ===");
    }
}
 
Example 3
Source File: DefaultSecurityHeadersProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void addHeaders(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
    if (options != null && options.isSkipHeaders()) {
        return;
    }

    MediaType requestType = requestContext.getMediaType();
    MediaType responseType = responseContext.getMediaType();
    MultivaluedMap<String, Object> headers = responseContext.getHeaders();

    if (responseType == null && !isEmptyMediaTypeAllowed(requestContext, responseContext)) {
        LOGGER.errorv("MediaType not set on path {0}, with response status {1}", session.getContext().getUri().getRequestUri().getPath(), responseContext.getStatus());
        throw new InternalServerErrorException();
    }

    if (isRest(requestType, responseType)) {
        addRestHeaders(headers);
    } else if (isHtml(requestType, responseType)) {
        addHtmlHeaders(headers);
    } else {
        addGenericHeaders(headers);
    }
}
 
Example 4
Source File: CsrfValidateFilter.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    // Validate if name bound or if CSRF property enabled and a POST
    final Method controller = resourceInfo.getResourceMethod();

    if (needsValidation(controller)) {

        CsrfToken token = csrfTokenManager.getToken()
                .orElseThrow(() -> new CsrfValidationException(messages.get("CsrfFailed", "missing token")));

        // First check if CSRF token is in header
        final String csrfToken = context.getHeaders().getFirst(token.getHeaderName());
        if (token.getValue().equals(csrfToken)) {
            return;
        }

        // Otherwise, it must be a form parameter
        final MediaType contentType = context.getMediaType();
        if (!isSupportedMediaType(contentType) || !context.hasEntity()) {
            throw new CsrfValidationException(messages.get("UnableValidateCsrf", context.getMediaType()));
        }

        // Validate CSRF
        final Form form = formEntityProvider.getForm(context);
        final List<String> tokenValues = form.asMap().get(token.getParamName());
        if (tokenValues == null || tokenValues.isEmpty()) {
            throw new CsrfValidationException(messages.get("CsrfFailed", "missing field"));
        }

        if (!token.getValue().equals(tokenValues.get(0))) {
            throw new CsrfValidationException(messages.get("CsrfFailed", "mismatching tokens"));
        }
    }
}
 
Example 5
Source File: MCRNoFormDataPutFilter.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    if (requestContext.getMethod().equals(HttpMethod.PUT) && requestContext.getMediaType() != null
        && requestContext.getMediaType().isCompatible(MediaType.MULTIPART_FORM_DATA_TYPE)) {
        throw new BadRequestException("Cannot PUT form data on this resource.");
    }
}
 
Example 6
Source File: StructuredEventFilter.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private RestRequestDetails createRequestDetails(ContainerRequestContext requestContext, String body) {
    RestRequestDetails restRequest = new RestRequestDetails();
    restRequest.setRequestUri(requestContext.getUriInfo().getRequestUri().toString());
    restRequest.setBody(body);
    restRequest.setCookies(requestContext.getCookies().entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> e.getValue().toString())));
    restRequest.setHeaders(requestContext.getHeaders().entrySet().stream().filter(e -> !skippedHeadersList.contains(e.getKey())).collect(
            Collectors.toMap(Entry::getKey, e -> StringUtils.join(e.getValue(), ","))));
    MediaType mediaType = requestContext.getMediaType();
    restRequest.setMediaType(mediaType != null ? mediaType.toString() : "");
    restRequest.setMethod(requestContext.getMethod());
    return restRequest;
}
 
Example 7
Source File: BookServer20.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    UriInfo ui = context.getUriInfo();
    String path = ui.getPath(false);

    if ("POST".equals(context.getMethod())
        && "bookstore/bookheaders/simple".equals(path) && !context.hasEntity()) {
        byte[] bytes = StringUtils.toBytesUTF8("<Book><name>Book</name><id>126</id></Book>");
        context.getHeaders().putSingle(HttpHeaders.CONTENT_LENGTH, Integer.toString(bytes.length));
        context.getHeaders().putSingle("Content-Type", "application/xml");
        context.getHeaders().putSingle("EmptyRequestStreamDetected", "true");
        context.setEntityStream(new ByteArrayInputStream(bytes));
    }
    if ("true".equals(context.getProperty("DynamicPrematchingFilter"))) {
        throw new RuntimeException();
    }
    context.setProperty("FirstPrematchingFilter", "true");

    if ("wrongpath".equals(path)) {
        context.setRequestUri(URI.create("/bookstore/bookheaders/simple"));
    } else if ("throwException".equals(path)) {
        context.setProperty("filterexception", "prematch");
        throw new InternalServerErrorException(
            Response.status(500).type("text/plain")
                .entity("Prematch filter error").build());
    } else if ("throwExceptionIO".equals(path)) {
        context.setProperty("filterexception", "prematch");
        throw new IOException();
    }

    MediaType mt = context.getMediaType();
    if (mt != null && "text/xml".equals(mt.toString())) {
        String method = context.getMethod();
        if ("PUT".equals(method)) {
            context.setMethod("POST");
        }
        context.getHeaders().putSingle("Content-Type", "application/xml");
    } else {
        String newMt = context.getHeaderString("newmediatype");
        if (newMt != null) {
            context.getHeaders().putSingle("Content-Type", newMt);
        }
    }
    List<MediaType> acceptTypes = context.getAcceptableMediaTypes();
    if (acceptTypes.size() == 1 && "text/mistypedxml".equals(acceptTypes.get(0).toString())) {
        context.getHeaders().putSingle("Accept", "text/xml");
    }
}