javax.ws.rs.core.CacheControl Java Examples
The following examples show how to use
javax.ws.rs.core.CacheControl.
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: CacheControlClientReaderInterceptor.java From cxf with Apache License 2.0 | 6 votes |
private long computeExpiry(CacheControl cacheControl, MultivaluedMap<String, String> responseHeaders) { // if a max-age property is set then it overrides Expires long expiry = cacheControl.getMaxAge(); if (expiry == -1) { //TODO: Review if Expires can be supported as an alternative to Cache-Control String expiresHeader = responseHeaders.getFirst(HttpHeaders.EXPIRES); if (expiresHeader.length() > 1 && expiresHeader.startsWith("'") && expiresHeader.endsWith("'")) { expiresHeader = expiresHeader.substring(1, expiresHeader.length() - 1); } try { expiry = (Headers.getHttpDateFormat().parse(expiresHeader).getTime() - System.currentTimeMillis()) / 1000L; } catch (final ParseException e) { // TODO: Revisit the possibility of supporting multiple formats } } return expiry; }
Example #2
Source File: BinaryResourceDownloadResponseBuilder.java From eplmp with Eclipse Public License 1.0 | 6 votes |
/** * Apply cache policy to a response. * * @param response The response builder. * @param eTag The ETag of the resource. * @param lastModified The last modified date of the resource. * @param isToBeCached Boolean to set whether we should define maxage of cache control * @return The response builder with the cache policy. */ private static Response.ResponseBuilder applyCachePolicyToResponse(Response.ResponseBuilder response, EntityTag eTag, Date lastModified, boolean isToBeCached) { if (isToBeCached) { CacheControl cc = new CacheControl(); cc.setMaxAge(CACHE_SECOND); cc.setNoTransform(false); cc.setPrivate(false); Calendar expirationDate = Calendar.getInstance(); expirationDate.add(Calendar.SECOND, CACHE_SECOND); response.cacheControl(cc) .expires(expirationDate.getTime()); } return response.lastModified(lastModified) .tag(eTag); }
Example #3
Source File: CacheControlHeaderDelegateTest.java From everrest with Eclipse Public License 2.0 | 6 votes |
@Test public void testToStringCacheControlWithAllArguments() throws Exception { CacheControl cacheControl = aCacheControl() .withMaxAge(60) .withMustRevalidate(true) .withNoCache(true) .withNoStore(true) .withNoTransform(true) .withPrivate(true) .withProxyRevalidate(true) .withSMaxAge(60) .withPrivateFields(newArrayList("aaa")) .withNoCacheFields(newArrayList("bbb")) .withCacheExtension(ImmutableMap.of("foo", "bar")) .build(); assertEquals("private=\"aaa\", no-cache=\"bbb\", no-store, no-transform, must-revalidate, proxy-revalidate, 60, 60, foo=bar", cacheControlHeaderDelegate.toString(cacheControl)); }
Example #4
Source File: RuntimeDelegateImplTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testCreateHeaderProvider() throws Exception { assertSame(MediaTypeHeaderProvider.class, new RuntimeDelegateImpl(). createHeaderDelegate(MediaType.class).getClass()); assertSame(EntityTagHeaderProvider.class, new RuntimeDelegateImpl(). createHeaderDelegate(EntityTag.class).getClass()); assertSame(CacheControlHeaderProvider.class, new RuntimeDelegateImpl(). createHeaderDelegate(CacheControl.class).getClass()); assertSame(CookieHeaderProvider.class, new RuntimeDelegateImpl(). createHeaderDelegate(Cookie.class).getClass()); assertSame(NewCookieHeaderProvider.class, new RuntimeDelegateImpl(). createHeaderDelegate(NewCookie.class).getClass()); }
Example #5
Source File: CustomerResourceTest.java From resteasy-examples with Apache License 2.0 | 6 votes |
@Test public void testCustomerResource() throws Exception { System.out.println("*** Create a new Customer ***"); Customer newCustomer = new Customer(); newCustomer.setFirstName("Bill"); newCustomer.setLastName("Burke"); newCustomer.setStreet("256 Clarendon Street"); newCustomer.setCity("Boston"); newCustomer.setState("MA"); newCustomer.setZip("02115"); newCustomer.setCountry("USA"); Response response = client.target("http://localhost:8080/services/customers") .request().post(Entity.xml(newCustomer)); if (response.getStatus() != 201) throw new RuntimeException("Failed to create"); String location = response.getLocation().toString(); System.out.println("Location: " + location); response.close(); System.out.println("*** GET Created Customer **"); response = client.target(location).request().get(); CacheControl cc = CacheControl.valueOf(response.getHeaderString(HttpHeaders.CACHE_CONTROL)); System.out.println("Max age: " + cc.getMaxAge()); }
Example #6
Source File: LoginStatusIframeEndpoint.java From keycloak with Apache License 2.0 | 6 votes |
@GET @Produces(MediaType.TEXT_HTML_UTF_8) public Response getLoginStatusIframe(@QueryParam("version") String version) { CacheControl cacheControl; if (version != null) { if (!version.equals(Version.RESOURCES_VERSION)) { return Response.status(Response.Status.NOT_FOUND).build(); } cacheControl = CacheControlUtil.getDefaultCacheControl(); } else { cacheControl = CacheControlUtil.noCache(); } InputStream resource = getClass().getClassLoader().getResourceAsStream("login-status-iframe.html"); if (resource != null) { P3PHelper.addP3PHeader(); session.getProvider(SecurityHeadersProvider.class).options().allowAnyFrameAncestor(); return Response.ok(resource).cacheControl(cacheControl).build(); } else { return Response.status(Response.Status.NOT_FOUND).build(); } }
Example #7
Source File: VreImage.java From timbuctoo with GNU General Public License v3.0 | 6 votes |
@GET public Response getImage(@PathParam("vreName") String vreName) { return transactionEnforcer.executeAndReturn(timbuctooActions -> { final Vre vre = timbuctooActions.getVre(vreName); if (vre == null) { return TransactionStateAndResult.commitAndReturn(Response.status(Response.Status.NOT_FOUND).build()); } final byte[] imageBlob = timbuctooActions.getVreImageBlob(vreName); final MediaType mediaType = vre.getMetadata().getImageMediaType(); if (imageBlob != null && mediaType != null) { final CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge(604800); cacheControl.setPrivate(false); return TransactionStateAndResult.commitAndReturn(Response .ok(imageBlob).type(mediaType).cacheControl(cacheControl).build()); } else { return TransactionStateAndResult.commitAndReturn(Response.status(Response.Status.NOT_FOUND).build()); } }); }
Example #8
Source File: MCRSessionFilter.java From mycore with GNU General Public License v3.0 | 6 votes |
/** * If request was authenticated via JSON Web Token add a new token if <code>aud</code> was * {@link MCRRestAPIAuthentication#AUDIENCE}. * * If the response has a status code that represents a client error (4xx), the JSON Web Token is ommited. * If the response already has a JSON Web Token no changes are made. */ private static void addJWTToResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { MCRSession currentSession = MCRSessionMgr.getCurrentSession(); boolean renewJWT = Optional.ofNullable(requestContext.getProperty(PROP_RENEW_JWT)) .map(Boolean.class::cast) .orElse(Boolean.FALSE); Optional.ofNullable(requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)) .filter(s -> s.startsWith("Bearer ")) .filter(s -> !responseContext.getStatusInfo().getFamily().equals(Response.Status.Family.CLIENT_ERROR)) .filter(s -> responseContext.getHeaderString(HttpHeaders.AUTHORIZATION) == null) .map(h -> renewJWT ? ("Bearer " + MCRRestAPIAuthentication .getToken(currentSession.getUserInformation(), currentSession.getCurrentIP()) .orElseThrow(() -> new InternalServerErrorException("Could not get JSON Web Token"))) : h) .ifPresent(h -> { responseContext.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, h); //Authorization header may never be cached in public caches Optional.ofNullable(requestContext.getHeaderString(HttpHeaders.CACHE_CONTROL)) .map(CacheControl::valueOf) .filter(cc -> !cc.isPrivate()) .ifPresent(cc -> { cc.setPrivate(true); responseContext.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, cc); }); }); }
Example #9
Source File: SearchResource.java From org.openntf.domino with Apache License 2.0 | 6 votes |
private ResponseBuilder getBuilder(final String jsonEntity, final Date lastMod, final boolean includeEtag, final Request request) { String etagSource = DominoUtils.md5(jsonEntity); EntityTag etag = new EntityTag(etagSource); ResponseBuilder berg = null; if (request != null) { berg = request.evaluatePreconditions(etag); } if (berg == null) { berg = Response.ok(); if (includeEtag) { berg.tag(etag); } berg.type(MediaType.APPLICATION_JSON_TYPE); berg.entity(jsonEntity); berg.lastModified(lastMod); CacheControl cc = new CacheControl(); cc.setMustRevalidate(true); cc.setPrivate(true); cc.setMaxAge(86400); cc.setNoTransform(true); berg.cacheControl(cc); } return berg; }
Example #10
Source File: MCRViewerResource.java From mycore with GNU General Public License v3.0 | 6 votes |
private Response showViewer(HttpServletRequest request, Request jaxReq) throws Exception { MCRContent content = getContent(request); String contentETag = content.getETag(); Response.ResponseBuilder responseBuilder = null; EntityTag eTag = contentETag == null ? null : new EntityTag(contentETag); if (eTag != null) { responseBuilder = jaxReq.evaluatePreconditions(eTag); } if (responseBuilder == null) { responseBuilder = Response.ok(content.asByteArray(), MediaType.valueOf(content.getMimeType())); } if (eTag != null) { responseBuilder.tag(eTag); } if (content.isUsingSession()) { CacheControl cc = new CacheControl(); cc.setPrivate(true); cc.setMaxAge(0); cc.setMustRevalidate(true); responseBuilder.cacheControl(cc); } return responseBuilder.build(); }
Example #11
Source File: TestClass22.java From jaxrs-analyzer with Apache License 2.0 | 6 votes |
@javax.ws.rs.GET public Response method() { Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder.header("X-Test", "Hello"); responseBuilder.cacheControl(CacheControl.valueOf("")); responseBuilder.contentLocation(URI.create("")); responseBuilder.cookie(); responseBuilder.entity(12d); responseBuilder.expires(new Date()); responseBuilder.language(Locale.ENGLISH); responseBuilder.encoding("UTF-8"); responseBuilder.lastModified(new Date()); responseBuilder.link(URI.create(""), "rel"); responseBuilder.location(URI.create("")); responseBuilder.status(433); responseBuilder.tag(new EntityTag("")); responseBuilder.type(MediaType.APPLICATION_JSON_TYPE); responseBuilder.variants(new LinkedList<>()); return responseBuilder.build(); }
Example #12
Source File: ImageController.java From jweb-cms with GNU Affero General Public License v3.0 | 6 votes |
@Path("/{s:.+}") @GET public Response image() { String requestPath = uriInfo.getPath(); Matcher matcher = IMAGE_PATTERN.matcher(requestPath); if (!matcher.matches()) { throw new NotFoundException(requestPath); } CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge(Integer.MAX_VALUE); String filePath = matcher.group(2); Optional<Resource> resource = cache.get(requestPath); if (resource.isPresent()) { return Response.ok(resource.get()).cacheControl(cacheControl).build(); } Resource file = fileRepository.get(filePath).orElseThrow(() -> new NotFoundException("missing file, requestPath=" + filePath)); java.nio.file.Path targetPath = cache.path().resolve(requestPath); imageScalar.scale(file, new ImageSize(matcher.group(1)), targetPath); resource = cache.get(requestPath); if (resource.isPresent()) { return Response.ok(resource.get()).type(MediaTypes.getMediaType(filePath)).cacheControl(cacheControl).build(); } throw new NotFoundException("missing image, requestPath=" + requestPath); }
Example #13
Source File: BookStore.java From cxf with Apache License 2.0 | 6 votes |
@GET @Path("/books/response3/{bookId}/") @Produces("application/xml") public Response getBookAsResponse3(@PathParam("bookId") String id, @HeaderParam("If-Modified-Since") String modifiedSince ) throws BookNotFoundFault { Book entity = doGetBook(id); EntityTag etag = new EntityTag(Integer.toString(entity.hashCode())); CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge(1); cacheControl.setPrivate(true); if (modifiedSince != null) { return Response.status(304).tag(etag) .cacheControl(cacheControl).lastModified(new Date()).build(); } else { return Response.ok().tag(etag).entity(entity) .cacheControl(cacheControl).lastModified(new Date()).build(); } }
Example #14
Source File: ImageController.java From jweb-cms with GNU Affero General Public License v3.0 | 6 votes |
@Path("/{s:.+}") @GET public Response image() { String requestPath = uriInfo.getPath(); Matcher matcher = IMAGE_PATTERN.matcher(requestPath); if (!matcher.matches()) { throw new NotFoundException(requestPath); } CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge(Integer.MAX_VALUE); String filePath = matcher.group(2); Optional<Resource> resource = cache.get(requestPath); if (resource.isPresent()) { return Response.ok(resource.get()).cacheControl(cacheControl).build(); } Resource file = fileRepository.get(filePath).orElseThrow(() -> new NotFoundException("missing file, requestPath=" + filePath)); java.nio.file.Path targetPath = cache.path().resolve(requestPath); imageScalar.scale(file, new ImageSize(matcher.group(1)), targetPath); resource = cache.get(requestPath); if (resource.isPresent()) { return Response.ok(resource.get()).type(MediaTypes.getMediaType(filePath)).cacheControl(cacheControl).build(); } throw new NotFoundException("missing image, requestPath=" + requestPath); }
Example #15
Source File: JsResource.java From keycloak with Apache License 2.0 | 6 votes |
private Response getJs(String name, String version) { CacheControl cacheControl; if (version != null) { if (!version.equals(Version.RESOURCES_VERSION)) { return Response.status(Response.Status.NOT_FOUND).build(); } cacheControl = CacheControlUtil.getDefaultCacheControl(); } else { cacheControl = CacheControlUtil.noCache(); } Cors cors = Cors.add(request).allowAllOrigins(); InputStream inputStream = getClass().getClassLoader().getResourceAsStream(name); if (inputStream != null) { return cors.builder(Response.ok(inputStream).type("text/javascript").cacheControl(cacheControl)).build(); } else { return cors.builder(Response.status(Response.Status.NOT_FOUND)).build(); } }
Example #16
Source File: CacheControlBuilder.java From everrest with Eclipse Public License 2.0 | 6 votes |
public CacheControl build() { CacheControl cacheControl = new CacheControl(); cacheControl.setMustRevalidate(mustRevalidate); cacheControl.setProxyRevalidate(proxyRevalidate); cacheControl.setMaxAge(maxAge); cacheControl.setSMaxAge(sMaxAge); cacheControl.setNoCache(noCache); cacheControl.setPrivate(privateFlag); cacheControl.setNoTransform(noTransform); cacheControl.setNoStore(noStore); if (privateFields != null) { cacheControl.getPrivateFields().addAll(privateFields); } if (noCacheFields != null) { cacheControl.getNoCacheFields().addAll(noCacheFields); } if (cacheExtension != null) { cacheControl.getCacheExtension().putAll(cacheExtension); } return cacheControl; }
Example #17
Source File: CacheControlHeaderProviderTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testFromComplexStringWithSemicolon() { CacheControlHeaderProvider cp = new CacheControlHeaderProvider() { protected Message getCurrentMessage() { Message m = new MessageImpl(); m.put(CacheControlHeaderProvider.CACHE_CONTROL_SEPARATOR_PROPERTY, ";"); return m; } }; CacheControl c = cp.fromString( "private=\"foo\";no-cache=\"bar\";no-store;no-transform;" + "must-revalidate;proxy-revalidate;max-age=2;s-maxage=3"); assertTrue(c.isPrivate() && c.isNoStore() && c.isMustRevalidate() && c.isProxyRevalidate() && c.isNoCache()); assertTrue(c.isNoTransform() && c.getNoCacheFields().size() == 1 && c.getPrivateFields().size() == 1); assertEquals("foo", c.getPrivateFields().get(0)); assertEquals("bar", c.getNoCacheFields().get(0)); }
Example #18
Source File: ProcessorWebUtils.java From nifi with Apache License 2.0 | 5 votes |
static Response.ResponseBuilder applyCacheControl(Response.ResponseBuilder response) { CacheControl cacheControl = new CacheControl(); cacheControl.setPrivate(true); cacheControl.setNoCache(true); cacheControl.setNoStore(true); return response.cacheControl(cacheControl); }
Example #19
Source File: ApplicationResource.java From nifi with Apache License 2.0 | 5 votes |
/** * Edit the response headers to indicating no caching. * * @param response response * @return builder */ protected ResponseBuilder noCache(final ResponseBuilder response) { final CacheControl cacheControl = new CacheControl(); cacheControl.setPrivate(true); cacheControl.setNoCache(true); cacheControl.setNoStore(true); return response.cacheControl(cacheControl); }
Example #20
Source File: RuleResource.java From nifi with Apache License 2.0 | 5 votes |
private ResponseBuilder noCache(ResponseBuilder response) { CacheControl cacheControl = new CacheControl(); cacheControl.setPrivate(true); cacheControl.setNoCache(true); cacheControl.setNoStore(true); return response.cacheControl(cacheControl); }
Example #21
Source File: CacheControlHeaderProviderTest.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testMultipleNoCacheFields() { CacheControl cc = new CacheControl(); cc.setNoCache(true); cc.getNoCacheFields().add("c"); cc.getNoCacheFields().add("d"); assertTrue(cc.toString().contains("no-cache=\"c,d\"")); }
Example #22
Source File: ClientCacheTest.java From cxf with Apache License 2.0 | 5 votes |
@GET @Produces("application/xml") public Response getJaxbBook() { Book b = new Book(); b.setId(System.currentTimeMillis()); b.setName("JCache"); return Response.ok(b).tag("123").cacheControl(CacheControl.valueOf("max-age=50000")).build(); }
Example #23
Source File: CacheControlClientReaderInterceptor.java From cxf with Apache License 2.0 | 5 votes |
protected boolean isCacheControlValid(final ReaderInterceptorContext context, final CacheControl responseControl) { boolean valid = responseControl != null && !responseControl.isNoCache() && !responseControl.isNoStore(); if (valid) { String clientHeader = (String)context.getProperty(CacheControlClientRequestFilter.CLIENT_CACHE_CONTROL); CacheControl clientControl = clientHeader == null ? null : CacheControl.valueOf(clientHeader); if (clientControl != null && clientControl.isPrivate() != responseControl.isPrivate()) { valid = false; } } return valid; }
Example #24
Source File: BookStore.java From cxf with Apache License 2.0 | 5 votes |
@GET @Path("/books/response/{bookId}/") @Produces("application/xml") public Response getBookAsResponse(@PathParam("bookId") String id) throws BookNotFoundFault { Book entity = doGetBook(id); EntityTag etag = new EntityTag(Integer.toString(entity.hashCode())); CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge(100000); cacheControl.setPrivate(true); return Response.ok().tag(etag).entity(entity).cacheControl(cacheControl).build(); }
Example #25
Source File: ResponseBuilderImplTest.java From everrest with Eclipse Public License 2.0 | 5 votes |
@Test public void removesCacheControlHeaderWithNullValue() { CacheControl cacheControl = new CacheControl(); Response response = new ResponseBuilderImpl() .cacheControl(cacheControl) .cacheControl(null) .build(); assertNull(response.getHeaders().get("Cache-Control")); }
Example #26
Source File: CacheControlHeaderProviderTest.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testFromSimpleString() { CacheControl c = CacheControl.valueOf( "public,must-revalidate"); assertFalse(c.isPrivate() && !c.isNoStore() && c.isMustRevalidate() && !c.isProxyRevalidate()); assertFalse(c.isNoCache() && !c.isNoTransform() && c.getNoCacheFields().isEmpty() && c.getPrivateFields().isEmpty()); }
Example #27
Source File: ProcessorWebUtils.java From localization_nifi with Apache License 2.0 | 5 votes |
static Response.ResponseBuilder applyCacheControl(Response.ResponseBuilder response) { CacheControl cacheControl = new CacheControl(); cacheControl.setPrivate(true); cacheControl.setNoCache(true); cacheControl.setNoStore(true); return response.cacheControl(cacheControl); }
Example #28
Source File: RuntimeDelegateImpl.java From cxf with Apache License 2.0 | 5 votes |
public RuntimeDelegateImpl() { headerProviders.put(MediaType.class, new MediaTypeHeaderProvider()); headerProviders.put(CacheControl.class, new CacheControlHeaderProvider()); headerProviders.put(EntityTag.class, new EntityTagHeaderProvider()); headerProviders.put(Cookie.class, new CookieHeaderProvider()); headerProviders.put(NewCookie.class, new NewCookieHeaderProvider()); headerProviders.put(Link.class, new LinkHeaderProvider()); headerProviders.put(Date.class, new DateHeaderProvider()); }
Example #29
Source File: BookStore.java From cxf with Apache License 2.0 | 5 votes |
@GET @Path("/books/response2/{bookId}/") @Produces("application/xml") public Response getBookAsResponse2(@PathParam("bookId") String id) throws BookNotFoundFault { Book entity = doGetBook(id); EntityTag etag = new EntityTag(Integer.toString(entity.hashCode())); CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge(1); cacheControl.setPrivate(true); return Response.ok().tag(etag).entity(entity).cacheControl(cacheControl).build(); }
Example #30
Source File: CacheControlHeaderDelegate.java From everrest with Eclipse Public License 2.0 | 5 votes |
@Override public String toString(CacheControl header) { StringBuilder buff = new StringBuilder(); if (!header.isPrivate()) { appendString(buff, "public"); } if (header.isPrivate()) { appendWithParameters(buff, "private", header.getPrivateFields()); } if (header.isNoCache()) { appendWithParameters(buff, "no-cache", header.getNoCacheFields()); } if (header.isNoStore()) { appendString(buff, "no-store"); } if (header.isNoTransform()) { appendString(buff, "no-transform"); } if (header.isMustRevalidate()) { appendString(buff, "must-revalidate"); } if (header.isProxyRevalidate()) { appendString(buff, "proxy-revalidate"); } if (header.getMaxAge() >= 0) { appendString(buff, Integer.toString(header.getMaxAge())); } if (header.getSMaxAge() >= 0) { appendString(buff, Integer.toString(header.getSMaxAge())); } for (Map.Entry<String, String> entry : header.getCacheExtension().entrySet()) { appendWithSingleParameter(buff, entry.getKey(), entry.getValue()); } return buff.toString(); }