private Response cacheAwareResponse( Request request, String entity, EntityTag etag, Date lastModified, int maxAge ) { final Response.ResponseBuilder builderLastMod = request.evaluatePreconditions(lastModified); if (builderLastMod != null) { return builderLastMod.build(); } final Response.ResponseBuilder builderEtag = request.evaluatePreconditions(etag); if (builderEtag != null) { return builderEtag.build(); } final CacheControl cc = new CacheControl(); cc.setMaxAge(maxAge); return Response.ok(entity) .tag(etag) .lastModified(lastModified) .cacheControl(cc) .build(); }
@Override @SuppressWarnings("unchecked") public <T> HeaderDelegate<T> createHeaderDelegate(final Class<T> type) { if (type == MediaType.class) { return (HeaderDelegate<T>) MEDIA_TYPE_DELEGATE; } if (type == Cookie.class) { return (HeaderDelegate<T>) COOKIE_DELEGATE; } if (type == NewCookie.class) { return (HeaderDelegate<T>) NEW_COOKIE_DELEGATE; } if (type == CacheControl.class) { return (HeaderDelegate<T>) CACHE_CONTROL_DELEGATE; } throw new IllegalArgumentException("Unrecognized header delegate: " + type); }
@GET @Path("{derivate}{path: (/[^?#]*)?}") public Response show(@Context HttpServletRequest request, @Context Request jaxReq, @Context ServletContext context, @Context ServletConfig config) 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(); }
@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()); }
@Autowired public DefaultSmartcommitsService(@ComponentImport IssueManager issueManager, @Qualifier ("smartcommitsTransitionsHandler") TransitionHandler transitionHandler, @Qualifier ("smartcommitsCommentHandler") CommentHandler commentHandler, @Qualifier ("smartcommitsWorklogHandler") WorkLogHandler workLogHandler, @ComponentImport JiraAuthenticationContext jiraAuthenticationContext, @ComponentImport CrowdService crowdService) { this.crowdService = checkNotNull(crowdService); NO_CACHE = new CacheControl(); NO_CACHE.setNoCache(true); this.issueManager = checkNotNull(issueManager); this.transitionHandler = transitionHandler; this.commentHandler = commentHandler; this.workLogHandler = workLogHandler; this.jiraAuthenticationContext = checkNotNull(jiraAuthenticationContext); }
/** * Run the CacheControl getNoStoreCacheControl() method test. * * @throws Exception * * @generatedBy CodePro at 12/16/14 4:40 PM */ @Test public void testGetNoStoreCacheControl_1() throws Exception { CacheControl result = ResponseUtil.getNoStoreCacheControl(); assertNotNull(result); assertEquals("private, no-cache, no-store, no-transform, max-age=0, s-maxage=0", result.toString()); assertEquals(true, result.isPrivate()); assertEquals(true, result.isNoTransform()); assertEquals(true, result.isNoCache()); assertEquals(true, result.isNoStore()); assertEquals(0, result.getSMaxAge()); assertEquals(false, result.isProxyRevalidate()); assertEquals(false, result.isMustRevalidate()); assertEquals(0, result.getMaxAge()); }
@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(); }
final ResponseBuilder newResponseBuilder(final Status status, @Nullable final Object entity, @Nullable final GenericType<?> type) { Preconditions.checkState(this.context.variant != null); final ResponseBuilder builder = Response.status(status); if (entity != null) { builder.entity(type == null ? entity : new GenericEntity<Object>(entity, type .getType())); builder.variant(this.context.variant); final CacheControl cacheControl = new CacheControl(); cacheControl.setNoStore(true); if ("GET".equalsIgnoreCase(this.request.getMethod()) || "HEAD".equalsIgnoreCase(this.request.getMethod())) { builder.lastModified(this.context.lastModified); builder.tag(this.context.etag); if (isCachingEnabled()) { cacheControl.setNoStore(false); cacheControl.setMaxAge(0); // always stale, must revalidate each time cacheControl.setMustRevalidate(true); cacheControl.setPrivate(getUsername() != null); cacheControl.setNoTransform(true); } } builder.cacheControl(cacheControl); } return builder; }
@Override public Response retrieveSomeSamples(final String ids) throws Exception { Integer[] keys = Util.parseAsLongArray(ids); List<SampleBean> data = new ArrayList<SampleBean>(); SampleBean one = null; for (int i = 0; i < keys.length; i++) { one = new SampleBean(keys[i], 4, "test1", "test1"); data.add(one); } CacheControl cc = new CacheControl(); cc.setMaxAge(30000); GenericEntity<List<SampleBean>> entity = new GenericEntity<List<SampleBean>>(data) { }; ResponseBuilder builder = Response.ok(entity); builder.cacheControl(cc); return builder.build(); }
/** * Get the {@link HttpHeaders#CACHE_CONTROL} header, if set. * * @return cache-control header or absent if cache-control header is not set */ public Optional<CacheControl> getCacheControl() { if (_cacheControl == null) { List<String> headerValues = _responseHeaders.get(CACHE_CONTROL); _cacheControl = Optional.absent(); if (headerValues != null) { try { _cacheControl = Optional.of(CacheControl.valueOf(HttpHeaderUtils.join(headerValues))); } catch (Exception ex) { LOG.debug("Failed to parse cache-control header: value='{}'", headerValues, ex); } } } return _cacheControl; }
@Override public Matcher<CacheControl> build() { return new TypeSafeMatcher<CacheControl>() { @Override public void describeTo(Description description) { description.appendText("is a CacheControl header "); if(noCache != null) { description.appendText("with " + (noCache?"no":"") + " cache"); } } @Override protected boolean matchesSafely(CacheControl item) { if(noCache != null) { if(item.isNoCache() != noCache) { return false; } } return true; } }; }
/** * Show a photo. * @param num ID of the user * @return PNG * @throws IOException If fails */ @GET @Path("/{id : \\d+}.png") @Produces("image/png") public Response index(@PathParam("id") final String num) throws IOException { final URN urn = URN.create(String.format("urn:aintshy:%s", num)); final byte[] png = this.base().human(urn).profile().photo(); if (png == null) { throw new WebApplicationException( Response.seeOther( URI.create("http://img.aintshy.com/no-photo.png") ).build() ); } final CacheControl cache = new CacheControl(); cache.setMaxAge((int) TimeUnit.HOURS.toSeconds(1L)); cache.setPrivate(false); return Response.ok(new ByteArrayInputStream(png)) .cacheControl(cache) .type("image/png") .build(); }
/** * Converts a {@code Cache-Control} annotation to a {@code Cache-Control} * Jersey API object. * * @param annotation the annotation * * @return the Jersey API object * * @see javax.ws.rs.core.CacheControl * @see com.github.autermann.jersey.cache.CacheControl */ private CacheControl createCacheControl( com.github.autermann.jersey.cache.CacheControl annotation) { CacheControl cacheControl = new CacheControl(); cacheControl.setPrivate(annotation._private() || annotation.privateFields().length > 0); cacheControl.getPrivateFields() .addAll(Arrays.asList(annotation.privateFields())); cacheControl.setMustRevalidate(annotation.mustRevalidate()); cacheControl.setNoCache(annotation.noCache() || annotation.noCacheFields().length > 0); cacheControl.getNoCacheFields() .addAll(Arrays.asList(annotation.noCacheFields())); cacheControl.setNoStore(annotation.noStore()); cacheControl.setNoTransform(annotation.noTransform()); cacheControl.setProxyRevalidate(annotation.proxyRevalidate()); cacheControl.setMaxAge(annotation.maxAge()); cacheControl.setSMaxAge(annotation.sMaxAge()); for (CacheControlExtension e : annotation.extensions()) { cacheControl.getCacheExtension().put(e.key(), e.value()); } return cacheControl; }
@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()); } }); }
@Override public void filter(final ContainerRequestContext req, final ContainerResponseContext res) throws IOException { if (req.getMethod().equals(GET)) { final CacheControl cc = new CacheControl(); cc.setMaxAge(cacheAge); res.getHeaders().add(CACHE_CONTROL, cc); } }
@GET @Path("version") @Produces(MediaType.APPLICATION_JSON) public Response getVersionInfo() { CacheControl cc = new CacheControl(); cc.setMaxAge(60 * 60 * 24); // seconds cc.setPrivate(true); return Response .status(Response.Status.OK) .cacheControl(cc) .entity(graphene.getVersionInfo()) .build(); }
@Override public CacheControl fromString(final String value) { if (value == null) { return null; } final CacheControl result = new CacheControl(); result.setPrivate(true); result.setNoTransform(false); for (final String directive : value.split(",\\s+")) { if (directive.startsWith("max-age=")) { result.setMaxAge(Integer.parseInt(directive.split("=")[1])); } else if (directive.equals("must-revalidate")) { result.setMustRevalidate(true); } else if (directive.equals("no-cache")) { result.setNoCache(true); } else if (directive.equals("no-store")) { result.setNoStore(true); } else if (directive.equalsIgnoreCase("no-transform")) { result.setNoTransform(true); } else if (directive.equals("private")) { result.setPrivate(true); } else if (directive.equals("proxy-revalidate")) { result.setProxyRevalidate(true); } else if (directive.equals("public")) { result.setPrivate(false); } else if (directive.startsWith("s-maxage=")) { result.setSMaxAge(Integer.parseInt(directive.split("=")[1])); } } return result; }
@Override public String toString(final CacheControl value) { if (value == null) { return null; } final StringBuilder b = new StringBuilder(); if (value.isPrivate()) { b.append("private"); } else { b.append("public"); } if (value.getMaxAge() >= 0) { b.append(", max-age=").append(value.getMaxAge()); } if (value.getSMaxAge() >= 0) { b.append(", s-maxage=").append(value.getSMaxAge()); } if (value.isMustRevalidate()) { b.append(", must-revalidate"); } if (value.isNoCache()) { b.append(", no-cache"); } if (value.isNoStore()) { b.append(", no-store"); } if (value.isNoTransform()) { b.append(", no-transform"); } if (value.isProxyRevalidate()) { b.append(", proxy-revalidate"); } return b.toString(); }
@Test public void testDeserializePublic() { final CacheControl c = d.fromString("public, max-age=31536000, s-maxage=0"); assertFalse(c.isPrivate()); assertEquals(31536000, c.getMaxAge()); assertEquals(0, c.getSMaxAge()); }
@Test public void testDeserializeNoCache() { final CacheControl c = d.fromString("private, no-cache, no-store, must-revalidate"); assertTrue(c.isPrivate()); assertTrue(c.isNoStore()); assertTrue(c.isMustRevalidate()); }
@Test public void testSerializeFull() { final CacheControl c = new CacheControl(); c.setMaxAge(100); c.setMustRevalidate(true); c.setNoCache(true); c.setNoStore(true); c.setNoTransform(false); c.setPrivate(true); c.setProxyRevalidate(true); c.setSMaxAge(200); assertEquals( "private, max-age=100, s-maxage=200, must-revalidate, no-cache, no-store, proxy-revalidate", d.toString(c)); }
@LogDuration(limit = 50) public Response getMetaDataSG1V1(UriInfo uriInfo, Request request) { EventsMetadataRepresentation em = new EventsMetadataRepresentation("", uriInfo); CacheControl cc = new CacheControl(); int maxAge = 4 * 7 * 24 * 60 * 60; cc.setMaxAge(maxAge); return Response.ok() .entity(em) .cacheControl(cc).expires(Date.from(CurrentTime.now().plusSeconds(maxAge))) .type("application/hal+json;concept=metadata;v=1") .build(); }
/** * Build a response given a concrete request. If the request contain an <code>if-modified-since</code> or * <code>if-none-match</code> header this will be checked against the entity given to the builder returning * a response with status not modified if appropriate. */ public Response build(Request req) { EntityTag eTag = new EntityTag(Integer.toString(entity.hashCode())); Date lastModified = entity instanceof AbstractAuditable ? ((AbstractAuditable) entity).getLastModifiedTime() : Date.from(Instant.now()); Response.ResponseBuilder notModifiedBuilder = req.evaluatePreconditions(lastModified, eTag); if (notModifiedBuilder != null) { return notModifiedBuilder.build(); } Map<String, String> parameters = new ConcurrentHashMap<>(); if (name != null) { parameters.put("concept", name); } if (version != null) { parameters.put("v", version); } MediaType type = getMediaType(parameters, supportsContentTypeParameter); Response.ResponseBuilder b = Response.ok(mapper.apply(entity)) .type(type) .tag(eTag) .lastModified(lastModified); if (maxAge != null) { CacheControl cc = new CacheControl(); cc.setMaxAge(maxAge); b.cacheControl(cc).expires(Date.from(Instant.now().plusSeconds(maxAge))); } return b.build(); }
/** * Edit the response headers to indicating no caching. * * @param response response * @return builder */ protected Response.ResponseBuilder noCache(final Response.ResponseBuilder response) { final CacheControl cacheControl = new CacheControl(); cacheControl.setPrivate(true); cacheControl.setNoCache(true); cacheControl.setNoStore(true); return response.cacheControl(cacheControl); }
@GET @Path("province") @Produces(MediaType.APPLICATION_JSON) public Response getProvince(){ BaseResponse<List<Province>> entity = new BaseResponse<>(areaManager.getProvince()); CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge((int)TimeUnit.DAYS.toSeconds(1)*365); return Response.status(200) .cacheControl(cacheControl) .entity(entity).build(); }
@GET @Path("city") @Produces(MediaType.APPLICATION_JSON) public Response getCity(@QueryParam(value = "provinceId") String provinceId){ BaseResponse<List<City>> entity = new BaseResponse<>(areaManager.getCity(provinceId)); CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge((int)TimeUnit.DAYS.toSeconds(1)*365); return Response.status(200) .cacheControl(cacheControl) .entity(entity).build(); }
@GET @Path("county") @Produces(MediaType.APPLICATION_JSON) public Response getCounty(@QueryParam(value = "cityId") String cityId){ BaseResponse<List<County>> entity = new BaseResponse<>(areaManager.getCounty(cityId)); CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge((int)TimeUnit.DAYS.toSeconds(1)*365); return Response.status(200) .cacheControl(cacheControl) .entity(entity).build(); }
@GET @Path("splash") @Produces(MediaType.APPLICATION_JSON) public Response getSplah(){ BaseResponse<Splash> entity = new BaseResponse<>(manager.getSplash()); CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge((int)TimeUnit.HOURS.toSeconds(1)); return Response.status(200) .cacheControl(cacheControl) .entity(entity).build(); }
@GET @Path("convenientBanner") @Produces(MediaType.APPLICATION_JSON) public Response getConvenientBanner(){ BaseResponse<List<ConvenientBanner>> entity = new BaseResponse<>(manager.getConvenientBanner()); CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge((int)TimeUnit.HOURS.toSeconds(1)); return Response.status(200) .cacheControl(cacheControl) .entity(entity).build(); }
/** * 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. * @return The response builder with the cache policy. */ private static Response.ResponseBuilder applyCachePolicyToResponse(Response.ResponseBuilder response, EntityTag eTag, Date lastModified) { CacheControl cc = new CacheControl(); cc.setMaxAge(CACHE_SECOND); cc.setNoTransform(false); cc.setPrivate(false); Calendar expirationDate = Calendar.getInstance(); expirationDate.add(Calendar.SECOND, CACHE_SECOND); return response.cacheControl(cc) .expires(expirationDate.getTime()) .lastModified(lastModified) .tag(eTag); }
@GET @Path("{fileName:.+}") @Produces("text/css") public Response getCSS(@PathParam("fileName") String name, @Context Request request) { try { MCRServletContextResourceImporter importer = new MCRServletContextResourceImporter(context); Optional<String> cssFile = MCRSassCompilerManager.getInstance() .getCSSFile(name, Stream.of(importer).collect(Collectors.toList())); if (cssFile.isPresent()) { CacheControl cc = new CacheControl(); cc.setMaxAge(SECONDS_OF_ONE_DAY); String etagString = MCRSassCompilerManager.getInstance().getLastMD5(name).get(); EntityTag etag = new EntityTag(etagString); Response.ResponseBuilder builder = request.evaluatePreconditions(etag); if (builder != null) { return builder.cacheControl(cc).tag(etag).build(); } return Response.ok().status(Response.Status.OK) .cacheControl(cc) .tag(etag) .entity(cssFile.get()) .build(); } else { return Response.status(Response.Status.NOT_FOUND) .build(); } } catch (IOException | CompilationException e) { StreamingOutput so = (OutputStream os) -> e.printStackTrace(new PrintStream(os, true, "UTF-8")); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(so).build(); } }
@GET @Path("/{username}") public Response getMostPopularPurchases( @PathParam("username") final String username, @QueryParam("limit") @DefaultValue("5") final int limit) throws UserNotFoundException { // Get the list from our service and build a Java-Generics JAX-RS friendly entity. List<PopularPurchase> purchases = service.getMostPopularPurchases(username, limit); GenericEntity<List<PopularPurchase>> entity = new GenericEntity<List<PopularPurchase>>(purchases) {}; // I can rely on the per-element dependent hashCode List contract: // http://docs.oracle.com/javase/8/docs/api/java/util/List.html#hashCode EntityTag etag = new EntityTag(Integer.toString(purchases.hashCode())); CacheControl cacheControl = new CacheControl(); cacheControl.setNoTransform(true); // I am not using age-based caching, just ETag-based. // cacheControl.setMaxAge((int) SECONDS.convert(1, DAYS)); ResponseBuilder maybeResponse = request.evaluatePreconditions(etag); if (maybeResponse == null) { return Response.ok(entity).tag(etag).cacheControl(cacheControl).build(); } else { return maybeResponse.cacheControl(cacheControl).build(); } }
private static CacheControl createCacheControl(Cacheable cacheable) { CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge(cacheable.maxAge()); cacheControl.setMustRevalidate(cacheable.mustRevalidate()); cacheControl.setNoCache(cacheable.noCache()); cacheControl.setNoStore(cacheable.noStore()); cacheControl.setNoTransform(cacheable.noTransform()); cacheControl.setPrivate(cacheable.privateFlag()); cacheControl.setProxyRevalidate(cacheable.proxyRevalidate()); cacheControl.setSMaxAge(cacheable.sMaxAge()); cacheControl.getNoCacheFields().addAll(Arrays.asList(cacheable.noCacheFields())); cacheControl.getPrivateFields().addAll(Arrays.asList(cacheable.privateFields())); return cacheControl; }
@Test public void testEntityTagSupport() { final Response response = createWebTarget().path("name").path("etag").request(MediaType.TEXT_PLAIN).get(); CacheControl cacheControl = CacheControl.valueOf(response.getHeaderString(HttpHeaders.CACHE_CONTROL)); assertEquals(600, cacheControl.getMaxAge()); assertTrue(cacheControl.isNoTransform()); assertFalse(cacheControl.isMustRevalidate()); final EntityTag entityTag = response.getEntityTag(); assertNotNull(entityTag); assertEquals("12345", entityTag.getValue()); }
@Test public void testLastUpdatedAndEtagSupport() { final Response response = createWebTarget().path("name").path("lastModifiedAndEtag").request(MediaType.TEXT_PLAIN).get(); CacheControl cacheControl = CacheControl.valueOf(response.getHeaderString(HttpHeaders.CACHE_CONTROL)); assertEquals(600, cacheControl.getMaxAge()); assertTrue(cacheControl.isNoTransform()); assertFalse(cacheControl.isMustRevalidate()); Date lastModified = response.getLastModified(); assertEquals(CacheResource.LAST_MODIFIED, lastModified); final EntityTag entityTag = response.getEntityTag(); assertNotNull(entityTag); assertEquals("12345", entityTag.getValue()); }
@Test public void testLastUpdatedSupport() { final Response response = createWebTarget().path("name").path("lastModified").request(MediaType.TEXT_PLAIN).get(); CacheControl cacheControl = CacheControl.valueOf(response.getHeaderString(HttpHeaders.CACHE_CONTROL)); assertEquals(600, cacheControl.getMaxAge()); assertTrue(cacheControl.isNoTransform()); assertFalse(cacheControl.isMustRevalidate()); Date lastModified = response.getLastModified(); assertEquals(CacheResource.LAST_MODIFIED, lastModified); }
@Test public void testWithNoState() { final Response response = createWebTarget().path("name").path("noState").request(MediaType.TEXT_PLAIN).get(); CacheControl cacheControl = CacheControl.valueOf(response.getHeaderString(HttpHeaders.CACHE_CONTROL)); assertEquals(600, cacheControl.getMaxAge()); assertTrue(cacheControl.isNoTransform()); assertFalse(cacheControl.isMustRevalidate()); assertNull(response.getLastModified()); assertNull(response.getEntityTag()); }