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

The following examples show how to use javax.ws.rs.container.ContainerResponseContext#getStatus() . 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: 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 2
Source File: MetricsFilter.java    From keycloak-metrics-spi with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext req, ContainerResponseContext res) {
    int status = res.getStatus();

    // We are only interested in recording the response status if it was an error
    // (either a 4xx or 5xx). No point in counting  the successful responses
    if (status >= 400) {
        PrometheusExporter.instance().recordResponseError(status, req.getMethod());
    }

    // Record request duration if timestamp property is present
    // and only if it is relevant (skip pictures)
    if (req.getProperty(METRICS_REQUEST_TIMESTAMP) != null &&
        contentTypeIsRelevant(res)) {
        long time = (long) req.getProperty(METRICS_REQUEST_TIMESTAMP);
        long dur = System.currentTimeMillis() - time;
        LOG.trace("Duration is calculated as " + dur + " ms.");
        PrometheusExporter.instance().recordRequestDuration(dur, req.getMethod());
    }
}
 
Example 3
Source File: JsonWrapperResponseFilter.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
    if (containerResponseContext.getStatus() == Response.Status.OK.getStatusCode()) {

        Object o = containerResponseContext.getEntity();
        JsonResponseWrapper wrapper;

        Class clazz = o.getClass();
        if (List.class.isAssignableFrom(clazz)) {
            wrapper = new JsonResponseWrapper((List) o);
        } else if (SearchResult.class.isAssignableFrom(clazz)) {
            wrapper = new JsonResponseWrapper((SearchResult) o);
        } else {
            wrapper = new JsonResponseWrapper(o);
        }

        containerResponseContext.setEntity(wrapper, containerResponseContext.getEntityAnnotations(), containerResponseContext.getMediaType());
    }
}
 
Example 4
Source File: RespondWithStatusFilter.java    From pnc with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(
        ContainerRequestContext containerRequestContext,
        ContainerResponseContext containerResponseContext) throws IOException {

    // for any 2xx status code, this gets activated
    // Skip filter for Http Method OPTIONS to not break CORS
    if (containerResponseContext.getStatus() / 100 == 2
            && containerResponseContext.getEntityAnnotations() != null) {
        for (Annotation annotation : containerResponseContext.getEntityAnnotations()) {

            if (annotation instanceof RespondWithStatus) {
                containerResponseContext.setStatus(((RespondWithStatus) annotation).value().getStatusCode());
                break;
            }
        }
    }
}
 
Example 5
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 6
Source File: ControllerResponseFilter.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
    throws IOException {
  final String method = requestContext.getMethod();
  final String uri = requestContext.getUriInfo().getRequestUri().toString();
  final int respStatus = responseContext.getStatus();
  final String reasonPhrase = responseContext.getStatusInfo().getReasonPhrase();
  final String srcIpAddr = request.get().getRemoteAddr();
  final String contentType = requestContext.getHeaderString(HttpHeaders.CONTENT_TYPE);
  LOGGER.info("Handled request from {} {} {}, content-type {} status code {} {}", srcIpAddr, method, uri, contentType,
      respStatus, reasonPhrase);
}
 
Example 7
Source File: OpenTracingProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void filter(final ContainerRequestContext requestContext,
        final ContainerResponseContext responseContext) throws IOException {
    super.stopTraceSpan(requestContext.getHeaders(), responseContext.getHeaders(),
        responseContext.getStatus(), (TraceScopeHolder<TraceScope>)requestContext.getProperty(TRACE_SPAN));
}
 
Example 8
Source File: BraveProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void filter(final ContainerRequestContext requestContext,
        final ContainerResponseContext responseContext) throws IOException {
    super.stopTraceSpan(requestContext.getHeaders(), responseContext.getHeaders(),
        responseContext.getStatus(), (TraceScopeHolder<TraceScope>)requestContext.getProperty(TRACE_SPAN));
}
 
Example 9
Source File: CreatedResponseFilter.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
    String method = containerRequestContext.getRequest().getMethod();

    if (method.equals("POST") && containerResponseContext.getStatus() == Response.Status.OK.getStatusCode()) {
        containerResponseContext.setStatus(Response.Status.CREATED.getStatusCode());
        RestEntity entity = (RestEntity) containerResponseContext.getEntity();
        String id = entity.getId();
        containerResponseContext.getHeaders().add("Location",
                containerRequestContext.getUriInfo().getAbsolutePathBuilder().path(id).build().toString());
    }

    //containerResponseContext.getHeaders().put("Location")
}
 
Example 10
Source File: NoContentResponseFilter.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
    if (containerResponseContext.getStatus() == Response.Status.OK.getStatusCode()) {

        Object o = containerResponseContext.getEntity();

        if (o == null) {
            containerResponseContext.setStatus(Response.Status.NO_CONTENT.getStatusCode());
        }
    }
}
 
Example 11
Source File: NotFoundForward.java    From ameba with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void filter(ContainerRequestContext requestContext,
                   ContainerResponseContext responseContext) throws IOException {
    int status = responseContext.getStatus();
    if (status == 404 || status == UnprocessableEntityException.STATUS) {
        String path = mappedViewPath();
        if (path != null) {
            responseContext.setEntity(Viewables.newDefaultViewable(path),
                    new Annotation[0], MediaType.TEXT_HTML_TYPE);
            responseContext.setStatus(Response.Status.OK.getStatusCode());
        }
    }
}
 
Example 12
Source File: BaseMethodStatsInterceptor.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
    // Copy the headers because they get committed before the message body writer context is
    // called, and when they are committed, the contents of the map is modified.
    ResponseMethodStats stats = new ResponseMethodStats();
    MultivaluedTreeMap.addAll(response.getHeaders(), stats.responseHeaders);
    stats.statusCode = response.getStatus();
    request.setProperty(RESPONSE_STATS_NAME, stats);
}
 
Example 13
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 14
Source File: ServerTracingDynamicFeature.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) {
  final SpanHolder spanHolder = getSpanHolder(containerRequestContext);
  if (spanHolder == null) {
    return;
  }

  final Span span = spanHolder.getSpan();
  final int responseStatus = containerResponseContext.getStatus();

  span.setTag(Tags.HTTP_STATUS.getKey(), responseStatus);
  if(responseStatus >= 400) {
    span.setTag(Tags.ERROR.getKey(), true);
  }
}
 
Example 15
Source File: StatusFilter.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext,
                   ContainerResponseContext responseContext)
                   throws IOException {
    if (responseContext.getStatus() == 200) {
        for (Annotation i : responseContext.getEntityAnnotations()) {
            if (i instanceof Status) {
                responseContext.setStatus(((Status) i).value());
                break;
            }
        }
    }
}
 
Example 16
Source File: LoggingResourceFilter.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private void logResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext, Duration requestDuration, LogLevel level) {
    if (!isLogEnabled(LOG, level)) return;
    
    int status = responseContext.getStatus();
    String method = requestContext.getMethod();
    String path = requestContext.getUriInfo().getPath();
    requestContext.getSecurityContext();
    MultivaluedMap<String, String> queryParams = requestContext.getUriInfo().getQueryParameters();
    
    SecurityContext securityContext = requestContext.getSecurityContext();
    Principal userPrincipal = (securityContext != null) ? requestContext.getSecurityContext().getUserPrincipal() : null;
    String userName = (userPrincipal != null) ? userPrincipal.getName() : "<no-user>";
    String remoteAddr = servletRequest.getRemoteAddr();
    
    boolean includeHeaders = (responseContext.getStatus() / 100 == 5) || LOG.isTraceEnabled();

    StringBuilder message = new StringBuilder("Request completed: ")
            .append("status ")
            .append(status)
            .append(" in ")
            .append(requestDuration)
            .append(", ")
            .append(method)
            .append(" ")
            .append(path)
            .append(" from ")
            .append(userName)
            .append(" @ ")
            .append(remoteAddr);

    if (!queryParams.isEmpty()) {
        message.append(", queryParams: {");
        message.append(Joiner.on(", ").withKeyValueSeparator("=").join(queryParams));
        message.append("}");
    }
    if (requestContext.getLength() > 0) {
        // TODO `getLength` is based on the presence of `Content-Length` header, rather than the measured length.
        int len = requestContext.getLength();
        message.append(", mediaType=").append(requestContext.getMediaType())
                .append(" (length=").append(len).append(")");
    }
    if (includeHeaders) {
        MultivaluedMap<String, String> headers = requestContext.getHeaders();
        message.append(", headers={");
        if (!headers.isEmpty()) {
            boolean first = true;
            for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
                if (first) {
                    first = false;
                } else {
                    message.append(", ");
                }
                String headerName = entry.getKey();
                message.append(headerName).append(": ");
                if (CENSORED_HEADERS.contains(headerName)) {
                    message.append("******");
                } else {
                    message.append(entry.getValue());
                }
            }
        }
        message.append("}");
    }

    log(LOG, level, message.toString());
}
 
Example 17
Source File: PermissionResponseInterceptor.java    From EDDI with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
    try {
        // it was most likely a CREATE request
        if (resourceInfo.getResourceMethod() != null && resourceInfo.getResourceMethod().isAnnotationPresent(POST.class)) {
            int httpStatus = response.getStatus();
            String methodName = resourceInfo.getResourceMethod().getName();
            // the resource was created successfully
            if (httpStatus == 201) {
                String respondedResourceURIString = response.getHeaderString(HttpHeaders.LOCATION);
                if (isNullOrEmpty(respondedResourceURIString)) {
                    log.info("No permission created for 201 response of method {}", methodName);
                    return;
                }
                URI respondedResourceURI = URI.create(respondedResourceURIString);
                IResourceStore.IResourceId respondedResourceId = RestUtilities.extractResourceId(respondedResourceURI);

                //if the created resource is a user, we treat it differently
                String resourceId = respondedResourceId.getId();
                if (methodName.equals(METHOD_NAME_CREATE_USER)) {
                    permissionStore.createPermissions(resourceId, PermissionUtilities.createDefaultPermissions(respondedResourceURI));
                } else if (!methodName.startsWith(METHOD_NAME_DUPLICATE_RESOURCE)) {
                    Principal userPrincipal = SecurityUtilities.getPrincipal(ThreadContext.getSubject());
                    URI userURI = UserUtilities.getUserURI(userStore, userPrincipal);

                    if (methodName.equals(METHOD_NAME_CREATE_TESTCASE)) {
                        ITestCaseStore testCaseStore = injector.getInstance(ITestCaseStore.class);
                        TestCase testCase = testCaseStore.loadTestCase(resourceId);
                        Permissions permissions = permissionStore.readPermissions(testCase.getBotId());
                        if (userURI != null) {
                            PermissionUtilities.addAuthorizedUser(permissions, IAuthorization.Type.ADMINISTRATION, new AuthorizedUser(userURI, null));
                        }
                        permissionStore.createPermissions(resourceId, permissions);
                    } else if (!methodName.equals(METHOD_NAME_START_CONVERSATION)) {
                        permissionStore.createPermissions(resourceId, PermissionUtilities.createDefaultPermissions(userURI));
                    }
                }
            }
        }
    } catch (IResourceStore.ResourceStoreException | IResourceStore.ResourceNotFoundException e) {
        throw new InternalServerErrorException(e.getLocalizedMessage(), e);
    }
}
 
Example 18
Source File: JaxrsContainerExtractor.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Override
public int getStatusCode(@Nullable ContainerResponseContext response) {
  return response != null ? response.getStatus() : 0;
}
 
Example 19
Source File: CrossOriginResourceSharingFilter.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext,
                   ContainerResponseContext responseContext) {

    Message m = JAXRSUtils.getCurrentMessage();
    String op = (String)m.getExchange().get(CrossOriginResourceSharingFilter.class.getName());
    if (op == null || PREFLIGHT_FAILED.equals(op)) {
        return;
    }
    if (responseContext.getStatus() == Response.Status.UNAUTHORIZED.getStatusCode()
        && blockCorsIfUnauthorized) {
        return;
    }

    /* Common to simple and preflight */
    responseContext.getHeaders().putSingle(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN,
                    m.getExchange().get(CorsHeaderConstants.HEADER_ORIGIN));
    responseContext.getHeaders().putSingle(CorsHeaderConstants.HEADER_AC_ALLOW_CREDENTIALS,
                    m.getExchange().get(CorsHeaderConstants.HEADER_AC_ALLOW_CREDENTIALS));

    if (SIMPLE_REQUEST.equals(op)) {
        /* 5.1.4 expose headers */
        List<String> effectiveExposeHeaders
            = getHeadersFromInput(m, CorsHeaderConstants.HEADER_AC_EXPOSE_HEADERS);
        if (effectiveExposeHeaders != null) {
            addHeaders(responseContext, CorsHeaderConstants.HEADER_AC_EXPOSE_HEADERS,
                       effectiveExposeHeaders, false);
        }
        // if someone wants to clear the cache, we can't help them.
    } else {
        // 5.2.8 max-age
        String maValue = (String)m.getExchange().get(CorsHeaderConstants.HEADER_AC_MAX_AGE);
        if (maValue != null) {
            responseContext.getHeaders().putSingle(CorsHeaderConstants.HEADER_AC_MAX_AGE, maValue);
        }
        // 5.2.9 add allowed methods
        /*
         * Currently, input side just lists the one requested method, and spec endorses that.
         */
        addHeaders(responseContext, CorsHeaderConstants.HEADER_AC_ALLOW_METHODS,
                   getHeadersFromInput(m, CorsHeaderConstants.HEADER_AC_ALLOW_METHODS), false);
        // 5.2.10 add allowed headers
        List<String> rqAllowedHeaders = getHeadersFromInput(m,
                                                            CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS);
        if (rqAllowedHeaders != null) {
            addHeaders(responseContext, CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS, rqAllowedHeaders, false);
        }
    }
}