javax.ws.rs.container.ContainerResponseContext Java Examples
The following examples show how to use
javax.ws.rs.container.ContainerResponseContext.
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: MetricsFilter.java From keycloak-metrics-spi with Apache License 2.0 | 6 votes |
@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 #2
Source File: CorsFilterTest.java From jrestless with Apache License 2.0 | 6 votes |
@Test public void corsResponseFilter_OriginAndAllowCredentialsGiven_AddsPassedOriginAndVaryHeader() throws IOException { CorsFilter filter = new CorsFilter.Builder() .allowOrigin(DEFAULT_ORIGIN) .allowCredentials() .build(); ContainerRequestContext request = createActualRequestMock(DEFAULT_HOST, DEFAULT_ORIGIN, HttpMethod.GET); ContainerResponseContext response = mock(ContainerResponseContext.class); MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); when(response.getHeaders()).thenReturn(headers); filter.filter(request, response); assertEquals(DEFAULT_ORIGIN, headers.getFirst(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertEquals(CorsHeaders.ORIGIN, headers.getFirst(HttpHeaders.VARY)); verify(response).getHeaders(); verifyZeroInteractions(response); }
Example #3
Source File: CorsFilterTest.java From jrestless with Apache License 2.0 | 6 votes |
@Test public void corsResponseFilter_AnyOriginAndAllowCredentialsGiven_AddsPassedOriginAndVaryHeader() throws IOException { CorsFilter filter = new CorsFilter.Builder() .allowCredentials() .build(); ContainerRequestContext request = createActualRequestMock(DEFAULT_HOST, DEFAULT_ORIGIN, HttpMethod.GET); ContainerResponseContext response = mock(ContainerResponseContext.class); MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); when(response.getHeaders()).thenReturn(headers); filter.filter(request, response); assertEquals(DEFAULT_ORIGIN, headers.getFirst(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertEquals(CorsHeaders.ORIGIN, headers.getFirst(HttpHeaders.VARY)); verify(response).getHeaders(); verifyZeroInteractions(response); }
Example #4
Source File: CorsDomainResponseFilter.java From tessera with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { final String origin = requestContext.getHeaderString("Origin"); if (originMatchUtil.matches(origin)) { MultivaluedMap<String, Object> headers = responseContext.getHeaders(); headers.add("Access-Control-Allow-Origin", origin); headers.add("Access-Control-Allow-Credentials", String.valueOf(corsConfig.getAllowCredentials())); headers.add("Access-Control-Allow-Methods", String.join(",", corsConfig.getAllowedMethods())); final String allowedHeaders; if (corsConfig.getAllowedHeaders() != null) { allowedHeaders = String.join(",", corsConfig.getAllowedHeaders()); } else { allowedHeaders = requestContext.getHeaderString("Access-Control-Request-Headers"); } headers.add("Access-Control-Allow-Headers", allowedHeaders); } }
Example #5
Source File: TemplateResponseFilter.java From redpipe with Apache License 2.0 | 6 votes |
@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 #6
Source File: CharsetResponseFilterTest.java From Cheddar with Apache License 2.0 | 6 votes |
@Test public void shouldNotSetContentTypeOnResponseWithoutMediaType_onFilter() throws Exception { // Given final ContainerRequestContext mockContainerRequestContext = mock(ContainerRequestContext.class); final ContainerResponseContext mockContainerResponseContext = mock(ContainerResponseContext.class); when(mockContainerResponseContext.getMediaType()).thenReturn(null); final MultivaluedMap<String, Object> mockHeadersMap = mock(MultivaluedMap.class); when(mockContainerResponseContext.getHeaders()).thenReturn(mockHeadersMap); final CharsetResponseFilter charsetResponseFilter = new CharsetResponseFilter(); // When charsetResponseFilter.filter(mockContainerRequestContext, mockContainerResponseContext); // Then verifyZeroInteractions(mockHeadersMap); }
Example #7
Source File: CorsFilterTest.java From jrestless with Apache License 2.0 | 6 votes |
@Test public void corsResponseFilter_ExposedHeadersGiven_AddsExposeHeadersHeader() throws IOException { CorsFilter filter = new CorsFilter.Builder() .exposeHeader("h1") .exposeHeader("h2") .build(); ContainerRequestContext request = createActualRequestMock(DEFAULT_HOST, DEFAULT_ORIGIN, HttpMethod.GET); ContainerResponseContext response = mock(ContainerResponseContext.class); MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); when(response.getHeaders()).thenReturn(headers); filter.filter(request, response); assertEquals("h1,h2", headers.getFirst(CorsHeaders.ACCESS_CONTROL_EXPOSE_HEADERS)); verify(response).getHeaders(); verifyZeroInteractions(response); }
Example #8
Source File: ResponseWrapperHandler.java From azeroth with Apache License 2.0 | 6 votes |
@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 #9
Source File: LoggingResourceFilter.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { Long requestTime = requestTimestamps.remove(servletRequest); Duration requestDuration = null; if (requestTime != null) { long responseTime = System.nanoTime(); requestDuration = Duration.nanos(responseTime - requestTime); } String method = requestContext.getMethod(); boolean isInteresting = !UNINTERESTING_METHODS.contains(method.toUpperCase()) || (requestDuration != null && requestDuration.isLongerThan(REQUEST_DURATION_LOG_POINT)); LogLevel logLevel = isInteresting ? LogLevel.DEBUG : LogLevel.TRACE; logResponse(requestContext, responseContext, requestDuration, logLevel); }
Example #10
Source File: SecurityManagerAssociatingFilter.java From aries-jax-rs-whiteboard with Apache License 2.0 | 6 votes |
/** * Clean up after the request */ @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { _LOG.debug("Cleaning up the Shiro Security Context"); Subject subject = ThreadContext.getSubject(); ThreadContext.unbindSecurityManager(); ThreadContext.unbindSubject(); if(subject != null && !subject.isAuthenticated()) { // Not authenticated. Check for incoming session cookie Cookie cookie = requestContext.getCookies().get(SESSION_COOKIE_NAME); // If we have a session cookie then it should be deleted if(cookie != null) { _LOG.debug("The subject associated with this request is not authenticated, removing the session cookie"); responseContext.getHeaders().add(SET_COOKIE, getDeletionCookie(requestContext)); } } }
Example #11
Source File: JsonWrapperResponseFilter.java From attic-rave with Apache License 2.0 | 6 votes |
@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 #12
Source File: CorsFilterTest.java From jrestless with Apache License 2.0 | 6 votes |
@Test public void corsResponseFilter_AnyOriginAndDisallowCredentialsGiven_AddsAnyOriginAndNoVaryHeader() throws IOException { CorsFilter filter = new CorsFilter.Builder() .disallowCredentials() .build(); ContainerRequestContext request = createActualRequestMock(DEFAULT_HOST, DEFAULT_ORIGIN, HttpMethod.GET); ContainerResponseContext response = mock(ContainerResponseContext.class); MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); when(response.getHeaders()).thenReturn(headers); filter.filter(request, response); assertEquals("*", headers.getFirst(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); assertNull(headers.getFirst(HttpHeaders.VARY)); verify(response).getHeaders(); verifyZeroInteractions(response); }
Example #13
Source File: ETagFilterTest.java From athenz with Apache License 2.0 | 5 votes |
ContainerResponseContext getContext(String tag) { ContainerResponseContext context = Mockito.mock(ContainerResponseContext.class); MultivaluedMap<String, Object> mvMap = new MultivaluedHashMap<>(); mvMap.add(HttpHeaders.ETAG, tag); Mockito.when(context.getHeaders()).thenReturn(mvMap); return context; }
Example #14
Source File: ETagFilter.java From athenz with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext request, ContainerResponseContext response) { // if our response object has a string ETag header value we're going // to replace it with its corresponding EntityTag object since the // the jersey GZIPResponse handler expects that object. // We could be either setting the in the container response (this is when // we're returning not-modified response since we're creating the container // response directly) or in the servlet response (this is where we're just // returning our data set with the header included). // So we'll check in the container response first and if we don't have // anything there we'll check in the servlet response. If we find the // header in the servlet response, we're going to remove it and set a new // entity tag object in the container response String etagStr = null; if (response.getHeaders().containsKey(HttpHeaders.ETAG)) { etagStr = (String) response.getHeaders().getFirst(HttpHeaders.ETAG); } if (etagStr == null && servletResponse != null) { etagStr = servletResponse.getHeader(HttpHeaders.ETAG); if (etagStr != null) { servletResponse.setHeader(HttpHeaders.ETAG, null); } } if (etagStr != null) { etagStr = removeLeadingAndTrailingQuotes(etagStr); response.getHeaders().putSingle("ETag", new EntityTag(etagStr)); } }
Example #15
Source File: CorsFilter.java From smarthome with Eclipse Public License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (isEnabled && !processPreflight(requestContext, responseContext)) { processRequest(requestContext, responseContext); } }
Example #16
Source File: ServerHeaderFilter.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException { MultivaluedMap<String, Object> headers = response.getHeaders(); headers.putSingle(Header.Server.toString(), "GRZLY"); // The same as raw // Grizzly test // implementation headers.putSingle(Header.Date.toString(), FastHttpDateFormat.getCurrentDate()); }
Example #17
Source File: DPCXFNonSpringJaxrsServlet.java From JaxRSProviders with Apache License 2.0 | 5 votes |
@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 #18
Source File: ApiOriginFilter.java From cxf with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { MultivaluedMap<String, Object> headers = responseContext.getHeaders(); headers.add("Access-Control-Allow-Origin", "*"); headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); headers.add("Access-Control-Allow-Headers", "Content-Type"); }
Example #19
Source File: CharsetResponseFilter.java From Cheddar with Apache License 2.0 | 5 votes |
@Override public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) throws IOException { final MediaType type = responseContext.getMediaType(); if (type != null && !type.getParameters().containsKey(MediaType.CHARSET_PARAMETER)) { responseContext.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, type.withCharset(DEFAULT_CHARSET)); } }
Example #20
Source File: GatewayBinaryResponseFilterTest.java From jrestless with Apache License 2.0 | 5 votes |
private ContainerResponseContext createResponseMock(Object entity, MultivaluedMap<String, Object> headers) { ContainerResponseContext response = mock(ContainerResponseContext.class); when(response.hasEntity()).thenReturn(entity != null); when(response.getEntity()).thenReturn(entity); when(response.getHeaders()).thenReturn(headers); return response; }
Example #21
Source File: ServerModule.java From digdag with Apache License 2.0 | 5 votes |
@Override public void filter( ContainerRequestContext request, ContainerResponseContext response) { response.getHeaders().add("Access-Control-Allow-Origin", "*"); response.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization"); response.getHeaders().add("Access-Control-Allow-Credentials", "true"); response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); response.getHeaders().add("Access-Control-Max-Age", "1209600"); }
Example #22
Source File: JSONPrettyPrintFilter.java From dremio-oss with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { UriInfo info = requestContext.getUriInfo(); if (!info.getQueryParameters().containsKey("pretty")) { return; } ObjectWriterInjector.set(new PrettyPrintWriter(ObjectWriterInjector.getAndClear())); }
Example #23
Source File: CorsFilterTest.java From jrestless with Apache License 2.0 | 5 votes |
@Test public void responseFilter_CustomAlwaysSameOriginPolicyGiven_NoCorsHeadersAdded() throws IOException, URISyntaxException { CorsFilter filter = new CorsFilter.Builder() .sameOriginPolicy((requestContext, origin) -> true) .build(); ContainerRequestContext request = createActualRequestMock(DEFAULT_HOST, DEFAULT_ORIGIN, HttpMethod.GET); ContainerResponseContext response = mock(ContainerResponseContext.class); filter.filter(request, response); verifyZeroInteractions(response); }
Example #24
Source File: CorsFilterTest.java From minnal with Apache License 2.0 | 5 votes |
@Test public void shouldAddCorsHeaders() { CorsFilter filter = new CorsFilter(); ContainerRequestContext reqContext = mock(ContainerRequestContext.class); ContainerResponseContext resContext = mock(ContainerResponseContext.class); MultivaluedMap<String, Object> headers = mock(MultivaluedMap.class); when(resContext.getHeaders()).thenReturn(headers); filter.filter(reqContext, resContext); verify(headers).add("Access-Control-Allow-Origin", "*"); verify(headers).add("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); }
Example #25
Source File: ResponseStatusFilter.java From agrest with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { Object entity = responseContext.getEntity(); if (entity instanceof AgResponse) { AgResponse response = (AgResponse) entity; if (response.getStatus() != null) { responseContext.setStatus(response.getStatus().getStatusCode()); } } }
Example #26
Source File: TestFilterAndExceptionMapper.java From aries-jax-rs-whiteboard with Apache License 2.0 | 5 votes |
@Override public void filter( ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { MultivaluedMap<String, Object> headers = responseContext.getHeaders(); headers.put("Filtered", Collections.singletonList("true")); }
Example #27
Source File: CorsFilter.java From Java-EE-8-and-Angular with MIT License | 5 votes |
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { MultivaluedMap<String, Object> headers = responseContext.getHeaders(); headers.add("Access-Control-Allow-Origin", "*"); headers.add("Access-Control-Allow-Credentials", "true"); headers.add("Access-Control-Allow-Headers", "Cache-Control, Origin, X-Requested-With, Content-Type, Accept, Authorization"); headers.add("Access-Control-Allow-Methods", "HEAD, OPTIONS, GET, POST, DELETE, PUT"); }
Example #28
Source File: CallbackInterceptor.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { logger.debug("IN"); if (httpRequest.getParameter("callback") != null && !httpRequest.getParameter("callback").equals("")) { String callback = httpRequest.getParameter("callback"); logger.debug("Add callback to entity response: " + callback); // String entity = httpResponse.getEntity().toString(); // String entityModified = callback + "(" + entity + ");"; // httpResponse.setEntity(entityModified); } ; logger.debug("OUT"); }
Example #29
Source File: CORSResponseFilter.java From play-with-hexagonal-architecture with Do What The F*ck You Want To Public License | 5 votes |
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { MultivaluedMap<String, Object> headers = responseContext.getHeaders(); headers.add("Access-Control-Allow-Origin", "*"); //headers.add("Access-Control-Allow-Origin", "http://podcastpedia.org"); //allows CORS requests only coming from podcastpedia.org headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia"); }
Example #30
Source File: CorsRespFilter1.java From Java-EE-8-and-Angular with MIT License | 5 votes |
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { System.out.println("CorsRespFilter1"); System.out.println("Request filters have added " + requestContext.getPropertyNames()); responseContext.getHeaders() .add("Access-Control-Allow-Origin", "http://bar.example.com"); }