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

The following examples show how to use javax.ws.rs.container.ContainerResponseContext#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: MCRSessionHookFilter.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
    MCRSessionMgr.unlock();
    MCRSession requestSession = (MCRSession) requestContext.getProperty(ATTR);
    if (responseContext.hasEntity()) {
        responseContext.setEntityStream(new ProxyOutputStream(responseContext.getEntityStream()) {
            @Override
            public void close() throws IOException {
                LOGGER.debug("Closing EntityStream");
                try {
                    super.close();
                } finally {
                    releaseSessionIfNeeded(requestSession);
                    LOGGER.debug("Closing EntityStream done");
                }
            }
        });
    } else {
        LOGGER.debug("No Entity in response, closing MCRSession");
        releaseSessionIfNeeded(requestSession);
    }
}
 
Example 2
Source File: GatewayBinaryResponseFilter.java    From jrestless with Apache License 2.0 6 votes vote down vote up
@Override
public final void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
		throws IOException {
	if (!responseContext.hasEntity()) {
		return;
	}
	boolean binaryResponse = isBinaryEntity(requestContext, responseContext);
	boolean compressedResponse = responseContext.getHeaders().containsKey(HttpHeaders.CONTENT_ENCODING);
	/*
	 * flag a response as binary if a) it is a binary response b) the
	 * "Content-Encoding" header is available (and thus will be compressed)
	 * and binaryCompressionOnly is disabled
	 */
	boolean binaryCompressionOnly = isBinaryCompressionOnly();
	if (binaryResponse || compressedResponse && !binaryCompressionOnly) {
		responseContext.getHeaders().putSingle(HEADER_BINARY_RESPONSE, true);
	}
	/*
	 * remove "Content-Encoding" for non-binary responses to disable compression unless
	 * binaryCompressionOnly is set to false
	 */
	if (compressedResponse && !binaryResponse && binaryCompressionOnly) {
		responseContext.getHeaders().remove(HttpHeaders.CONTENT_ENCODING);
	}
}
 
Example 3
Source File: LoggingFilter.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
        throws IOException {
    final long id = aid.incrementAndGet();
    final StringBuilder b = new StringBuilder();

    printResponseLine(b, "Server responded with a response", id, responseContext.getStatus());
    printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getStringHeaders());

    if (printEntity && responseContext.hasEntity()) {
        final OutputStream stream = new LoggingStream(b, responseContext.getEntityStream());
        responseContext.setEntityStream(stream);
        requestContext.setProperty(ENTITY_LOGGER_PROPERTY, stream);
        // not calling log(b) here - it will be called by the interceptor
    } else {
        log(b);
    }
}
 
Example 4
Source File: StructuredEventFilter.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
    if (BooleanUtils.isTrue((Boolean) requestContext.getProperty(LOGGING_ENABLED_PROPERTY))) {
        RestResponseDetails restResponse = createResponseDetails(responseContext);
        if (responseContext.hasEntity()) {
            OutputStream stream = new LoggingStream(responseContext.getEntityStream());
            responseContext.setEntityStream(stream);
            requestContext.setProperty(LOGGINGSTREAM_PROPERTY, stream);
            requestContext.setProperty(RESPONSE_DETAILS, restResponse);
        } else {
            Long requestTime = (Long) requestContext.getProperty(REQUEST_TIME);
            RestRequestDetails restRequest = (RestRequestDetails) requestContext.getProperty(REQUEST_DETAILS);
            Map<String, String> restParams = (Map<String, String>) requestContext.getProperty(REST_PARAMS);
            sendStructuredEvent(restRequest, restResponse, restParams, requestTime, "");
        }
    }
}
 
Example 5
Source File: DefaultSecurityHeadersProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Prevent responses without content-type unless explicitly safe to do so
 */
private boolean isEmptyMediaTypeAllowed(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
    if (!responseContext.hasEntity()) {
        if (options != null && options.isAllowEmptyContentType()) {
            return true;
        }
        int status = responseContext.getStatus();
        if (status == 201 || status == 204 ||
            status == 301 || status == 302 || status == 303 || status == 307 || status == 308 ||
            status == 400 || status == 401 || status == 403 || status == 404) {
            return true;
        }
        if (requestContext.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true;
        }
    }
    return false;
}
 
Example 6
Source File: MCRSessionFilter.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
    LOGGER.debug("ResponseFilter start");
    try {
        MCRSessionMgr.unlock();
        MCRSession currentSession = MCRSessionMgr.getCurrentSession();
        if (responseContext.getStatus() == Response.Status.FORBIDDEN.getStatusCode() && currentSession
            .getUserInformation().getUserID().equals(MCRSystemUserInformation.getGuestInstance().getUserID())) {
            LOGGER.debug("Guest detected, change response from FORBIDDEN to UNAUTHORIZED.");
            responseContext.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
            responseContext.getHeaders().putSingle(HttpHeaders.WWW_AUTHENTICATE,
                MCRRestAPIUtil.getWWWAuthenticateHeader("Basic", null, app));
        }
        if (responseContext.getStatus() == Response.Status.UNAUTHORIZED.getStatusCode()
            && doNotWWWAuthenticate(requestContext)) {
            LOGGER.debug("Remove {} header.", HttpHeaders.WWW_AUTHENTICATE);
            responseContext.getHeaders().remove(HttpHeaders.WWW_AUTHENTICATE);
        }
        addJWTToResponse(requestContext, responseContext);
        if (responseContext.hasEntity()) {
            responseContext.setEntityStream(new ProxyOutputStream(responseContext.getEntityStream()) {
                @Override
                public void close() throws IOException {
                    LOGGER.debug("Closing EntityStream");
                    try {
                        super.close();
                    } finally {
                        closeSessionIfNeeded();
                        LOGGER.debug("Closing EntityStream done");
                    }
                }
            });
        } else {
            LOGGER.debug("No Entity in response, closing MCRSession");
            closeSessionIfNeeded();
        }
    } finally {
        LOGGER.debug("ResponseFilter stop");
    }
}
 
Example 7
Source File: HealthResponseFilter.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext req, ContainerResponseContext resp) throws IOException {

    if (resp.hasEntity() && (resp.getEntity() instanceof Status)) {
        Status status = (Status) resp.getEntity();
        int code = (Status.State.UP == status.getState()) ? 200 : 503;
        resp.setStatus(code);
        resp.setEntity(status.toJson());
        resp.getHeaders().putSingle("Content-Type", MediaType.APPLICATION_JSON);
    }
}
 
Example 8
Source File: StatusMapper.java    From ameba with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void filter(ContainerRequestContext requestContext,
                   ContainerResponseContext responseContext) throws IOException {
    if (!responseContext.hasEntity()
            && !((ContainerResponse) responseContext).isMappedFromException()
            && responseContext.getStatus() >= 400
            && responseContext.getStatus() < 600) {
        throw new WebApplicationException(responseContext.getStatus());
    }

    List<MediaType> types = null;
    // 找不到 writer/reader, 提供系统有的 writer/reader 输出错误
    if (responseContext.getStatus() == 406) {
        types = workersProvider.get()
                .getMessageBodyWriterMediaTypes(
                        responseContext.getEntityClass(),
                        responseContext.getEntityType(),
                        responseContext.getEntityAnnotations());
    } else if (responseContext.getStatus() == 415) {
        types = workersProvider.get()
                .getMessageBodyReaderMediaTypes(
                        responseContext.getEntityClass(),
                        responseContext.getEntityType(),
                        responseContext.getEntityAnnotations());
    }
    if (types != null) {
        ((ContainerResponse) responseContext).setMediaType(parseMediaType(types));
    }
}
 
Example 9
Source File: LoggingFilter.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
  throws IOException {
  if (!"1".equals(requestContext.getHeaderString("Is-Healthcheck"))) {
    //Actual log is done when the response stream has finished in aroundWriteTo
    String log = "< " +
      Integer.toString(responseContext.getStatus()) + " " +
      requestContext.getMethod() + " " +
      requestContext.getUriInfo().getRequestUri().toASCIIString();

    Stopwatch stopwatch = (Stopwatch) requestContext.getProperty(STOPWATCH_PROPERTY);
    if (stopwatch == null) {
      LOG.error("Lost my stopwatch!");
    } else if (!stopwatch.isRunning()) {
      LOG.error("Stopwatch was stopped!");
      stopwatch = null;
    }

    if (responseContext.hasEntity()) {
      String contentType = responseContext.getHeaderString("Content-Type");
      boolean logResponseText = "text/plain".equals(contentType) || "application/json".equals(contentType);
      //delay logging until the responseBody has been fully written
      responseContext.setEntityStream(new LoggingOutputStream(
        responseContext.getEntityStream(),
        stopwatch,
        log,
        requestContext,
        responseContext,
        MDC.getCopyOfContextMap(),
        logResponseText
      ));
    } else {
      //log now, because the writeTo wrapper will not be called
      long duration = stopwatch != null ? stopwatch.elapsed(MILLISECONDS) : -1;
      doLog(
        log,
        0,
        duration,
        duration,
        requestContext,
        responseContext,
        MDC.getCopyOfContextMap(),
        EMPTY
      );
    }
  }
}