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

The following examples show how to use javax.ws.rs.container.ContainerResponseContext#setEntity() . 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: ResponseWrapperHandler.java    From azeroth 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 2
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 3
Source File: ServiceNameResponseFilter.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
    throws IOException {

  final String svcName =
      StringUtils.substringBefore(StringUtils.substringAfter(requestContext.getUriInfo().getPath(), "/"), "/");

  if ("OAuth2.svc".equals(svcName) && responseContext.getEntity() != null) {
    final String content = IOUtils.toString((InputStream) responseContext.getEntity(), Constants.ENCODING).
        replaceAll("Static\\.svc", svcName);

    final InputStream toBeStreamedBack = IOUtils.toInputStream(content, Constants.ENCODING);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(toBeStreamedBack, baos);
    IOUtils.closeQuietly(toBeStreamedBack);

    responseContext.setEntity(new ByteArrayInputStream(baos.toByteArray()));
  }
}
 
Example 4
Source File: JaxRsContext.java    From jax-rs-pac4j with Apache License 2.0 6 votes vote down vote up
public void populateResponse(ContainerResponseContext responseContext) {
    if (hasResponseContent) {
        responseContext.setEntity(responseContent);
    }
    if (hasResponseContentType) {
        responseContext.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, responseContentType);
    }
    if (hasResponseStatus) {
        responseContext.setStatus(responseStatus);
    }
    for (Entry<String, String> headers : responseHeaders.entrySet()) {
        responseContext.getHeaders().putSingle(headers.getKey(), headers.getValue());
    }
    for (NewCookie cookie : responseCookies) {
        responseContext.getHeaders().add(HttpHeaders.SET_COOKIE, cookie);
    }
}
 
Example 5
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 6
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 7
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 8
Source File: DPCXFNonSpringJaxrsServlet.java    From JaxRSProviders with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
		throws IOException {
	Object entity = responseContext.getEntity();
	if (entity instanceof AsyncResponse) {
		AsyncResponse asyncResponse = (AsyncResponse) entity;
		Class<?> returnType = asyncResponse.returnType;
		MultivaluedMap<String, Object> httpHeaders = responseContext.getHeaders();
		if (AsyncUtil.isOSGIAsync(registration.getReference()) && AsyncReturnUtil.isAsyncType(returnType)) {
			httpHeaders.add(JaxRSConstants.JAXRS_RESPHEADER_ASYNC_TYPE, returnType.getName());
		}
		responseContext.setEntity(asyncResponse.response);
	}
}
 
Example 9
Source File: TokenBasedAuthResponseFilter.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Checks the expiration date of token.
 * Renews and puts at header of response.
 *
 * @param requestContext
 * @param responseContext
 * @return
 */
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
    String authToken = extractAuthTokenFromCookieList(requestContext.getHeaders().getFirst("Cookie"));
    if (authToken != null && authToken.length() != 0) {
        try {
            BasicToken token = new BasicToken(authToken);
            if (token.isExpired()) {
                LOGGER.debug("ExpireDate : " + token.getExpirationDate().toString());
                LOGGER.debug("Now: " + DateTime.now().toDate().toString());
                responseContext.getHeaders().putSingle("Set-Cookie", getTokenSentence(null));
                responseContext.setStatusInfo(Response.Status.UNAUTHORIZED);
                responseContext.setEntity("Token expired. Please login again.");
                LOGGER.info("Token expired. Please login again.");
            } else {
                token.setExpiration(token.getMaxAge());
                if (!logoutPath.equals(requestContext.getUriInfo().getPath())) {
                    String cookie = getTokenSentence(token);
                    responseContext.getHeaders().putSingle("Set-Cookie", cookie);
                }
            }

        } catch (Exception e) {
            LOGGER.error("Token re-creation failed", e.getMessage());
            responseContext.setStatusInfo(Response.Status.UNAUTHORIZED);

        }
    }
}
 
Example 10
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 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: InternationalResponseFilter.java    From Qualitis with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
    Object responseEntity = responseContext.getEntity();
    if (responseEntity instanceof GeneralResponse) {
        GeneralResponse generalResponse = (GeneralResponse) responseContext.getEntity();
        String message = generalResponse.getMessage();

        String localeStr = requestContext.getHeaderString("Content-Language");
        message = localeParser.replacePlaceHolderByLocale(message, localeStr);

        generalResponse.setMessage(message);
        responseContext.setEntity(generalResponse);
    }
}
 
Example 13
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 14
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 15
Source File: JwsMultipartContainerResponseFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext reqCtx, ContainerResponseContext respCtx) throws IOException {
    MediaType contentType = respCtx.getMediaType();
    if (contentType != null && "multipart".equals(contentType.getType())) {
        List<Object> parts = getAttachmentParts(respCtx.getEntity());
        respCtx.setEntity(parts);
    }
    
}
 
Example 16
Source File: SwaggerToOpenApiConversionFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext reqCtx, ContainerResponseContext respCtx) throws IOException {
    if (Boolean.TRUE == reqCtx.getProperty(OPEN_API_PROPERTY)) {
        final Object entity = respCtx.getEntity();
        // Right before 1.5.18, the entity was always a String but became a model object
        // (io.swagger.models.Swagger) after. For now, let us serialize it to JSON manually.
        String swaggerJson = entity instanceof String ? (String)entity : Json.pretty(entity);
        String openApiJson = SwaggerToOpenApiConversionUtils.getOpenApiFromSwaggerJson(
                createMessageContext(), swaggerJson, openApiConfig);
        respCtx.setEntity(openApiJson);
    }
}
 
Example 17
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));
}
 
Example 18
Source File: JaxRsServerWithProviderTest.java    From testfun with Apache License 2.0 4 votes vote down vote up
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
    responseContext.setStatus(Response.Status.ACCEPTED.getStatusCode());
    responseContext.setEntity(new JaxRsTestObject("kuki", 2323));
}