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

The following examples show how to use javax.ws.rs.container.ContainerResponseContext#getEntity() . 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: QueryMetricsEnrichmentInterceptor.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
    super.filter(request, response);
    
    if (response instanceof ContainerResponseContextImpl) {
        ContainerResponseContextImpl containerResponseImpl = (ContainerResponseContextImpl) response;
        EnrichQueryMetrics e = FindAnnotation.findAnnotation(containerResponseImpl.getJaxrsResponse().getAnnotations(), EnrichQueryMetrics.class);
        if (e != null) {
            
            Object entity = response.getEntity();
            if (entity instanceof GenericResponse) {
                @SuppressWarnings("unchecked")
                GenericResponse<String> qidResponse = (GenericResponse<String>) entity;
                request.setProperty(QueryCall.class.getName(), new QueryCall(e.methodType(), qidResponse.getResult()));
            } else if (entity instanceof BaseQueryResponse) {
                BaseQueryResponse baseResponse = (BaseQueryResponse) entity;
                request.setProperty(QueryCall.class.getName(), new QueryCall(e.methodType(), baseResponse.getQueryId()));
            } else if (entity instanceof QueryExecutorBean.ExecuteStreamingOutputResponse) {
                // The ExecuteStreamingOutputResponse class updates the metrics, no need to do it here
            } else {
                log.error("Unexpected response class for metrics annotated query method " + request.getUriInfo().getPath() + ". Response class was "
                                + (entity == null ? "null response" : entity.getClass().toString()));
            }
        }
    }
}
 
Example 2
Source File: AuditLogFilter.java    From helix with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response)
    throws IOException {
  AuditLog.Builder auditLogBuilder;
  try {
    auditLogBuilder = (AuditLog.Builder) request.getProperty(AuditLog.ATTRIBUTE_NAME);
    auditLogBuilder.completeTime(new Date()).responseCode(response.getStatus());
    Object entity = response.getEntity();
    if(entity != null && entity instanceof String) {
      auditLogBuilder.responseEntity((String) response.getEntity());
    }

    AuditLog auditLog = auditLogBuilder.build();
    if (_auditLoggers != null) {
      for (AuditLogger logger : _auditLoggers) {
        logger.write(auditLog);
      }
    }
  } catch (Exception ex) {
    _logger.error("Failed to add audit log " + ex);
  }
}
 
Example 3
Source File: AddETagFilter.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext reqCtx, final ContainerResponseContext resCtx) throws IOException {
    if (resCtx.getEntityTag() == null) {
        Date lastModified = null;
        if (resCtx.getEntity() instanceof SCIMUser) {
            lastModified = ((SCIMUser) resCtx.getEntity()).getMeta().getLastModified();
            if (resCtx.getEntity() instanceof SCIMGroup) {
                lastModified = ((SCIMGroup) resCtx.getEntity()).getMeta().getLastModified();
            }

            if (lastModified != null) {
                String etagValue = String.valueOf(lastModified.getTime());
                if (StringUtils.isNotBlank(etagValue)) {
                    resCtx.getHeaders().add(HttpHeaders.ETAG, new EntityTag(etagValue, true).toString());
                }
            }
        }
    }
}
 
Example 4
Source File: AddETagFilter.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext reqCtx, final ContainerResponseContext resCtx) throws IOException {
    if (resCtx.getEntityTag() == null) {
        AnyTO annotated = null;
        if (resCtx.getEntity() instanceof AnyTO) {
            annotated = (AnyTO) resCtx.getEntity();
        } else if (resCtx.getEntity() instanceof ProvisioningResult) {
            EntityTO entity = ((ProvisioningResult<?>) resCtx.getEntity()).getEntity();
            if (entity instanceof AnyTO) {
                annotated = (AnyTO) entity;
            }
        }
        if (annotated != null) {
            String etagValue = annotated.getETagValue();
            if (StringUtils.isNotBlank(etagValue)) {
                resCtx.getHeaders().add(HttpHeaders.ETAG, new EntityTag(etagValue).toString());
            }
        }
    }
}
 
Example 5
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 6
Source File: ResponseWrapperHandler.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
@Override
public void processResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext,
		ResourceInfo resourceInfo) {
	MediaType mediaType = responseContext.getMediaType();
	if (mediaType != null && MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
		Object responseData = responseContext.getEntity();
		WrapperResponseEntity jsonResponse;

		if (responseData instanceof WrapperResponseEntity) {
			jsonResponse = (WrapperResponseEntity) responseData;
		} else {
			jsonResponse = new WrapperResponseEntity(ResponseCode.OK);
			jsonResponse.setData(responseData);
		}
		responseContext.setStatus(ResponseCode.OK.getCode());

		responseContext.setEntity(jsonResponse);

	}
}
 
Example 7
Source File: TemplateResponseFilter.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
		throws IOException {
	if(responseContext.getEntityClass() == Template.class) {
		SuspendableContainerResponseContext ctx = (SuspendableContainerResponseContext) responseContext;
		ctx.suspend();
		Template template = (Template) responseContext.getEntity();
		try {
			template.render(requestContext.getRequest())
			.subscribe(resp -> {
				// make sure we avoid setting a null media type because that causes
				// an NPE further down
				if(resp.getMediaType() != null)
					ctx.setEntity(resp.getEntity(), null, resp.getMediaType());
				else
					ctx.setEntity(resp.getEntity());
				ctx.setStatus(resp.getStatus());
				ctx.resume();
			}, err -> {
				ctx.resume(err);
			});
		}catch(Throwable t) {
			ctx.resume(t);
		}
	}
}
 
Example 8
Source File: JsonApiResponseFilter.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Creates JSON API responses for custom JAX-RS actions returning Katharsis resources.
 */
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
	Object response = responseContext.getEntity();
	if (response == null) {
		return;
	}
	
	// only modify responses which contain a single or a list of Katharsis resources
	if (isResourceResponse(response)) {
		KatharsisBoot boot = feature.getBoot();
		ResourceRegistry resourceRegistry = boot.getResourceRegistry();
		DocumentMapper documentMapper = boot.getDocumentMapper();
		
		ServiceUrlProvider serviceUrlProvider = resourceRegistry.getServiceUrlProvider();
		try {
			UriInfo uriInfo = requestContext.getUriInfo();
			if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) {
				((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestStarted(uriInfo);
			}

			JsonApiResponse jsonApiResponse = new JsonApiResponse();
			jsonApiResponse.setEntity(response);
			// use the Katharsis document mapper to create a JSON API response
			responseContext.setEntity(documentMapper.toDocument(jsonApiResponse, null));
			responseContext.getHeaders().put("Content-Type", Arrays.asList((Object)JsonApiMediaType.APPLICATION_JSON_API));
			
		}
		finally {
			if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) {
				((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestFinished();
			}
		}
	}
}
 
Example 9
Source File: BookServer20.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext,
                   ContainerResponseContext responseContext) throws IOException {
    responseContext.getHeaders().add("Custom", "custom");
    if (!"Postmatch filter error".equals(responseContext.getEntity())) {
        Book book = (Book)responseContext.getEntity();
        responseContext.setEntity(new Book(book.getName(), 1 + book.getId()), null, null);
    }
}
 
Example 10
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 11
Source File: RestResponseFilter.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
  Object entity = response.getEntity();
  if (entity instanceof AbstractRestResponse) {
    AbstractRestResponse restResponse = (AbstractRestResponse) entity;
    response.setStatus(restResponse.getHttpStatusCode());
  }
}
 
Example 12
Source File: CreateSignatureInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
    throws IOException {
    // Only sign the response if we have no Body.
    if (responseContext.getEntity() == null) {
        // We don't pass the HTTP method + URI for the response case
        performSignature(responseContext.getHeaders(), "", "");
    }
}
 
Example 13
Source File: SparseFieldSetFilter.java    From alchemy with MIT License 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext response) {
    if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(response.getMediaType())) {
        return;
    }

    final List<String> fieldsParam = requestContext.getHeaders().get("fields");
    if (fieldsParam == null) {
        return;
    }

    final Object entity = response.getEntity();

    if (entity == null) {
        return;
    }

    final JsonNode tree = mapper.convertValue(entity, JsonNode.class);
    final Set<String> fields = expandFields(fieldsParam);

    if (tree.isObject()) {
        filterFields("", (ObjectNode) tree, fields);
        response.setEntity(tree);
    } else if (tree.isArray()) {
        filterFields("", (ArrayNode) tree, fields);
        response.setEntity(tree);
    }
}
 
Example 14
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 15
Source File: BookServer20.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext,
                   ContainerResponseContext responseContext) throws IOException {
    if (responseContext.getMediaType() != null) {
        String ct = responseContext.getMediaType().toString();
        if (requestContext.getProperty("filterexception") != null) {
            if (!"text/plain".equals(ct)) {
                throw new RuntimeException();
            }
            responseContext.getHeaders().putSingle("FilterException",
                                                   requestContext.getProperty("filterexception"));
        }
    
        Object entity = responseContext.getEntity();
        Type entityType = responseContext.getEntityType();
        if (entity instanceof GenericHandler && InjectionUtils.getActualType(entityType) == Book.class) {
            ct += ";charset=ISO-8859-1";
            if ("getGenericBook2".equals(rInfo.getResourceMethod().getName())) {
                Annotation[] anns = responseContext.getEntityAnnotations();
                if (anns.length == 4 && anns[3].annotationType() == Context.class) {
                    responseContext.getHeaders().addFirst("Annotations", "OK");
                }
            } else {
                responseContext.setEntity(new Book("book", 124L));
            }
        } else {
            ct += ";charset=";
        }
        responseContext.getHeaders().putSingle("Content-Type", ct);
        responseContext.getHeaders().add("Response", "OK");
    }
}
 
Example 16
Source File: LoggingResponseFilter.java    From demo-restWS-spring-jersey-jpa2-hibernate with MIT License 5 votes vote down vote up
public void filter(ContainerRequestContext requestContext,
		ContainerResponseContext responseContext) throws IOException {
	String method = requestContext.getMethod();

	logger.debug("Requesting " + method + " for path " + requestContext.getUriInfo().getPath());
	Object entity = responseContext.getEntity();
	if (entity != null) {
		logger.debug("Response " + new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(entity));
	}
	
}
 
Example 17
Source File: DefaultFormatFilter.java    From amforeas with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Adds the DATE and Content-MD5 headers to the given 
 * {@linkplain com.sun.jersey.spi.container.ContainerResponse}
 * @param cr1 a {@linkplain com.sun.jersey.spi.container.ContainerResponse}.
 * @param entity the response body. Used to generate the Content-Length, Content-MD5 headers.
 * @param mime a {@linkplain javax.ws.rs.core.MediaType} used to normalize the Content-Type header.
 */
private void setHeadersToResponse (ContainerResponseContext cr) {
    Object entity = cr.getEntity();
    if (entity == null) {
        return;
    }

    cr.getHeaders().add("Content-MD5", AmforeasUtils.getMD5Base64(entity.toString()));
}
 
Example 18
Source File: ReqResLogHandler.java    From azeroth with Apache License 2.0 4 votes vote down vote up
public void processResponse(ContainerRequestContext requestContext,
                            ContainerResponseContext responseContext,
                            ResourceInfo resourceInfo) {
    Object responseData = responseContext.getEntity();
    logger.info("response:\n", JsonUtils.toJson(responseData));
}
 
Example 19
Source File: ReqResLogHandler.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
public void processResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext,
		ResourceInfo resourceInfo) {
	Object responseData = responseContext.getEntity();
	logger.info("response:\n",JsonUtils.toJson(responseData));
}
 
Example 20
Source File: BookServer20.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext,
                   ContainerResponseContext responseContext) throws IOException {
    Book book = (Book)responseContext.getEntity();
    responseContext.setEntity(new Book(book.getName(), book.getId() + supplement));
}