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

The following examples show how to use javax.ws.rs.container.ContainerRequestContext#hasEntity() . 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: 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 2
Source File: JweContainerRequestFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    if (isMethodWithNoContent(context.getMethod())
        || isCheckEmptyStream() && !context.hasEntity()) {
        return;
    }
    final byte[] encryptedContent = IOUtils.readBytesFromStream(context.getEntityStream());
    if (encryptedContent.length == 0) {
        return;
    }
    JweDecryptionOutput out = decrypt(encryptedContent);
    byte[] bytes = out.getContent();
    context.setEntityStream(new ByteArrayInputStream(bytes));
    context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));
    String ct = JoseUtils.checkContentType(out.getHeaders().getContentType(), getDefaultMediaType());
    if (ct != null) {
        context.getHeaders().putSingle("Content-Type", ct);
    }
    if (super.isValidateHttpHeaders()) {
        super.validateHttpHeadersIfNeeded(context.getHeaders(), out.getHeaders());
    }
}
 
Example 3
Source File: AuditFilter.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    if (auditService() != null) {
        String requestBody = (requestContext.hasEntity() ?
                (readTreeFromStream(mapper, requestContext.getEntityStream()).toString()) : "");
        requestContext.setProperty("requestBody", requestBody);
        // FIXME: audit message should be better structured
        requestContext.setProperty("auditMessage", "{\"Path" + logCompSeperator
                + requestContext.getUriInfo().getPath() + separator + "Method"
                + logCompSeperator + requestContext.getMethod() + separator
                + (requestContext.getMethod().equals("PUT") ?
                // FIXME: is there really a need to differentiate based on method?
                ("Path_Parameters" + logCompSeperator + requestContext.getUriInfo().getPathParameters().toString()
                        + separator + "Query_Parameters" + logCompSeperator
                        + requestContext.getUriInfo().getQueryParameters().toString()
                        + separator + "Request_Body" + logCompSeperator + requestBody) : ""));
        requestContext.setEntityStream(IOUtils.toInputStream(requestBody));
    }
}
 
Example 4
Source File: LoggingFilter.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext context) throws IOException {
  final Stopwatch stopwatch = Stopwatch.createStarted();
  final UUID id = UUID.randomUUID();
  MDC.put(MDC_ID, id.toString());
  MDC.put(MDC_RELEASE_HASH, releaseHash);

  MDC.put(MDC_PRE_LOG, "true");
  //Log a very minimal message. Mostly to make sure that we notice requests that never log in the response filter
  LOG.info(">     " + context.getMethod() + " " + context.getUriInfo().getRequestUri().toASCIIString());
  MDC.remove(MDC_PRE_LOG);
  context.setProperty(STOPWATCH_PROPERTY, stopwatch);

  if (context.hasEntity()) {
    context.setEntityStream(
      addInboundEntityToMdc(context.getEntityStream(), MessageUtils.getCharset(context.getMediaType()))
    );
  }
}
 
Example 5
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 6
Source File: LoggingFilter.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(final ContainerRequestContext context) throws IOException {
    final long id = aid.incrementAndGet();
    final StringBuilder b = new StringBuilder();

    printRequestLine(b, "Server has received a request", id, context.getMethod(), context.getUriInfo()
            .getRequestUri());
    printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getHeaders());

    if (printEntity && context.hasEntity()) {
        context.setEntityStream(logInboundEntity(b, context.getEntityStream()));
    }

    log(b);
}
 
Example 7
Source File: JwsContainerRequestFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    if (isMethodWithNoContent(context.getMethod())
        || isCheckEmptyStream() && !context.hasEntity()) {
        return;
    }
    final String content = IOUtils.readStringFromStream(context.getEntityStream());
    if (StringUtils.isEmpty(content)) {
        return;
    }
    JwsCompactConsumer p = new JwsCompactConsumer(content);
    JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier(p.getJwsHeaders());
    if (!p.verifySignatureWith(theSigVerifier)) {
        context.abortWith(JAXRSUtils.toResponse(400));
        return;
    }
    JoseUtils.validateRequestContextProperty(p.getJwsHeaders());
    
    byte[] bytes = p.getDecodedJwsPayloadBytes();
    context.setEntityStream(new ByteArrayInputStream(bytes));
    context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));

    String ct = JoseUtils.checkContentType(p.getJwsHeaders().getContentType(), getDefaultMediaType());
    if (ct != null) {
        context.getHeaders().putSingle("Content-Type", ct);
    }

    if (super.isValidateHttpHeaders()) {
        super.validateHttpHeadersIfNeeded(context.getHeaders(), p.getJwsHeaders());
    }
    
    Principal currentPrincipal = context.getSecurityContext().getUserPrincipal();
    if (currentPrincipal == null || currentPrincipal.getName() == null) {
        SecurityContext securityContext = configureSecurityContext(theSigVerifier);
        if (securityContext != null) {
            JAXRSUtils.getCurrentMessage().put(SecurityContext.class, securityContext);
        }
    }
}
 
Example 8
Source File: JwsJsonContainerRequestFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    if (isMethodWithNoContent(context.getMethod())
        || isCheckEmptyStream() && !context.hasEntity()) {
        return;
    }
    final String content = IOUtils.readStringFromStream(context.getEntityStream());
    if (StringUtils.isEmpty(content)) {
        return;
    }
    JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier();
    JwsJsonConsumer c = new JwsJsonConsumer(content);
    try {
        validate(c, theSigVerifier);
    } catch (JwsException ex) {
        context.abortWith(JAXRSUtils.toResponse(400));
        return;
    }

    byte[] bytes = c.getDecodedJwsPayloadBytes();
    context.setEntityStream(new ByteArrayInputStream(bytes));
    context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));

    // the list is guaranteed to be non-empty
    JwsJsonSignatureEntry sigEntry = c.getSignatureEntries().get(0);
    String ct = JoseUtils.checkContentType(sigEntry.getUnionHeader().getContentType(), getDefaultMediaType());
    if (ct != null) {
        context.getHeaders().putSingle("Content-Type", ct);
    }
    if (super.isValidateHttpHeaders()) {
        super.validateHttpHeadersIfNeeded(context.getHeaders(), sigEntry.getProtectedHeader());
    }
}
 
Example 9
Source File: JweJsonContainerRequestFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    if (isMethodWithNoContent(context.getMethod())
        || isCheckEmptyStream() && !context.hasEntity()) {
        return;
    }
    final byte[] encryptedContent = IOUtils.readBytesFromStream(context.getEntityStream());
    if (encryptedContent.length == 0) {
        return;
    }
    try {
        JweDecryptionOutput out = decrypt(encryptedContent);
        byte[] bytes = out.getContent();
        context.setEntityStream(new ByteArrayInputStream(bytes));
        context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));
        String ct = JoseUtils.checkContentType(out.getHeaders().getContentType(), getDefaultMediaType());
        if (ct != null) {
            context.getHeaders().putSingle("Content-Type", ct);
        }
        if (super.isValidateHttpHeaders()) {
            super.validateHttpHeadersIfNeeded(context.getHeaders(), out.getHeaders());
        }
    } catch (JweException ex) {
        context.abortWith(JAXRSUtils.toResponse(400));
        return;
    }
}
 
Example 10
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");
    }
}