Java Code Examples for javax.ws.rs.core.CacheControl#setMaxAge()
The following examples show how to use
javax.ws.rs.core.CacheControl#setMaxAge() .
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: 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 2
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 3
Source File: TermsResource.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 4
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 5
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 6
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 7
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 8
Source File: FramedCollectionResource.java From org.openntf.domino with Apache License 2.0 | 5 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).entity(jsonEntity); berg.lastModified(lastMod); CacheControl cc = new CacheControl(); cc.setMustRevalidate(true); cc.setPrivate(true); cc.setMaxAge(86400); cc.setNoTransform(true); berg.cacheControl(cc); } else { // System.out.println("TEMP DEBUG got a hit for etag " + // etagSource); } return berg; }
Example 9
Source File: CacheControlUtil.java From keycloak with Apache License 2.0 | 5 votes |
public static CacheControl getDefaultCacheControl() { CacheControl cacheControl = new CacheControl(); cacheControl.setNoTransform(false); Integer maxAge = Config.scope("theme").getInt("staticMaxAge", 2592000); if (maxAge != null && maxAge > 0) { cacheControl.setMaxAge(maxAge); } else { cacheControl.setNoCache(true); } return cacheControl; }
Example 10
Source File: DataManagementImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 5 votes |
@Override public Response getDictItemByItemCode(HttpServletRequest request, HttpHeaders header, Company company, Locale locale, User user, ServiceContext serviceContext, String code, String itemCode) { DictcollectionInterface dictItemDataUtil = new DictCollectionActions(); long groupId = GetterUtil.getLong(header.getHeaderString("groupId")); DictItem dictItem = dictItemDataUtil.getDictItemByItemCode(code, itemCode, groupId, serviceContext); if (Validator.isNotNull(dictItem)) { DictItemModel dictItemModel = DataManagementUtils.mapperDictItemModel(dictItem, dictItemDataUtil, user.getUserId(), company.getCompanyId(), groupId, serviceContext); CacheControl cc = new CacheControl(); cc.setMaxAge(86400); cc.setPrivate(true); return Response.status(200).entity(dictItemModel).cacheControl(cc).build(); } else { ErrorMsg error = new ErrorMsg(); error.setMessage("not found!"); error.setCode(404); error.setDescription("not found!"); return Response.status(409).entity(error).build(); } }
Example 11
Source File: FileAdminController.java From jweb-cms with GNU Affero General Public License v3.0 | 5 votes |
@Path("/{s:.+}") @GET public Response file() { String path = uriInfo.getPath().substring("/admin/file".length()); Optional<Resource> resource = fileRepository.get(path); if (!resource.isPresent()) { return Response.ok().status(Response.Status.NOT_FOUND).build(); } CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge(Integer.MAX_VALUE); return Response.ok(resource.get()).type(MediaTypes.getMediaType(path)).cacheControl(cacheControl).build(); }
Example 12
Source File: SwaggerYamlApi.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * Retrieves swagger definition of Store REST API and returns * * @return swagger definition of Store REST API in yaml format */ @GET @Consumes({ "text/yaml" }) @Produces({ "text/yaml" }) @io.swagger.annotations.ApiOperation(value = "Get Swagger Definition", notes = "Get Swagger Definition of Store REST API.", response = Void.class) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nSwagger Definition is returned."), @io.swagger.annotations.ApiResponse(code = 304, message = "Not Modified.\nEmpty body because the client has already the latest version of the requested resource."), @io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported") }) public Response swaggerYamlGet() throws APIManagementException { try { if (openAPIDef == null) { synchronized (LOCK_STORE_OPENAPI_DEF) { if (openAPIDef == null) { String definition = IOUtils .toString(this.getClass().getResourceAsStream("/store-api.yaml"), "UTF-8"); openAPIDef = new OAS2Parser().removeExamplesFromSwagger(definition); } } } RESTAPICacheConfiguration restapiCacheConfiguration = APIUtil.getRESTAPICacheConfig(); if (restapiCacheConfiguration.isCacheControlHeadersEnabled()) { CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge(restapiCacheConfiguration.getCacheControlHeadersMaxAge()); cacheControl.setPrivate(true); return Response.ok().entity(openAPIDef).cacheControl(cacheControl).build(); } else { return Response.ok().entity(openAPIDef).build(); } } catch (IOException e) { String errorMessage = "Error while retrieving the swagger definition of the Store API"; RestApiUtil.handleInternalServerError(errorMessage, e, log); } return null; }
Example 13
Source File: ReferenceResource.java From org.openntf.domino with Apache License 2.0 | 5 votes |
private ResponseBuilder getBuilder(String jsonEntity, Date lastMod, boolean includeEtag, 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) { // System.out.println("TEMP DEBUG creating a new builder"); berg = Response.ok(); if (includeEtag) { berg.tag(etag); } berg.type(MediaType.APPLICATION_JSON_TYPE); berg.entity(jsonEntity); if (lastMod != null) { 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 14
Source File: FileController.java From jweb-cms with GNU Affero General Public License v3.0 | 5 votes |
@Path("/{s:.+}") @GET public Response file() { String path = uriInfo.getPath().substring("file/".length()); Optional<Resource> resource = fileRepository.get(path); if (!resource.isPresent()) { return Response.ok().status(Response.Status.NOT_FOUND).build(); } CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge(Integer.MAX_VALUE); return Response.ok(resource.get()).cacheControl(cacheControl).type(MediaTypes.getMediaType(path)).build(); }
Example 15
Source File: MCRSassResource.java From mycore with GNU General Public License v3.0 | 5 votes |
@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, StandardCharsets.UTF_8)); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(so).build(); } }
Example 16
Source File: CacheControlFilter.java From resteasy-examples with Apache License 2.0 | 5 votes |
public void filter(ContainerRequestContext req, ContainerResponseContext res) throws IOException { if (req.getMethod().equals("GET")) { CacheControl cc = new CacheControl(); cc.setMaxAge(this.maxAge); res.getHeaders().add("Cache-Control", cc); } }
Example 17
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 18
Source File: DataManagementImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 4 votes |
@SuppressWarnings("unchecked") @Override public Response getDictItems(HttpServletRequest request, HttpHeaders header, Company company, Locale locale, User user, ServiceContext serviceContext, String code, DataSearchModel query, Request requestCC) { DictcollectionInterface dictItemDataUtil = new DictCollectionActions(); DictItemResults result = new DictItemResults(); SearchContext searchContext = new SearchContext(); searchContext.setCompanyId(company.getCompanyId()); try { if (query.getEnd() == 0) { query.setStart(-1); query.setEnd(-1); } long groupId = GetterUtil.getLong(header.getHeaderString("groupId")); LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>(); if ("ADMINISTRATIVE_REGION".equalsIgnoreCase(code)) groupId = 0; params.put("groupId", groupId); params.put("keywords", query.getKeywords()); params.put("itemLv", query.getLevel()); params.put(DictItemTerm.PARENT_ITEM_CODE, query.getParent()); params.put(DictItemTerm.DICT_COLLECTION_CODE, code); Sort[] sorts = null; if (Validator.isNull(query.getSort())) { sorts = new Sort[] { SortFactoryUtil.create(DictItemTerm.SIBLING_SEARCH + "_Number_sortable", Sort.INT_TYPE, false) }; } else { sorts = new Sort[] { SortFactoryUtil.create(query.getSort() + "_sortable", Sort.STRING_TYPE, false) }; } JSONObject jsonData = dictItemDataUtil.getDictItems(user.getUserId(), company.getCompanyId(), groupId, params, sorts, query.getStart(), query.getEnd(), serviceContext); result.setTotal(jsonData.getLong("total")); result.getDictItemModel() .addAll(DataManagementUtils.mapperDictItemModelList((List<Document>) jsonData.get("data"))); EntityTag etag = new EntityTag(Integer.toString(Long.valueOf(groupId).hashCode())); ResponseBuilder builder = requestCC.evaluatePreconditions(etag); if (OpenCPSConfigUtil.isHttpCacheEnable() && builder == null) { CacheControl cc = new CacheControl(); cc.setMaxAge(OpenCPSConfigUtil.getHttpCacheMaxAge()); cc.setPrivate(true); return Response.status(200).entity(result).cacheControl(cc).build(); } else { return Response.status(200).entity(result).build(); } } catch (Exception e) { return BusinessExceptionImpl.processException(e); } }
Example 19
Source File: CacheControlHeaderProvider.java From cxf with Apache License 2.0 | 4 votes |
public CacheControl fromString(String c) { boolean isPrivate = false; List<String> privateFields = new ArrayList<>(); boolean noCache = false; List<String> noCacheFields = new ArrayList<>(); boolean noStore = false; boolean noTransform = false; boolean mustRevalidate = false; boolean proxyRevalidate = false; int maxAge = -1; int sMaxAge = -1; Map<String, String> extensions = new HashMap<>(); String[] tokens = getTokens(c); for (String rawToken : tokens) { String token = rawToken.trim(); if (token.startsWith(MAX_AGE)) { maxAge = Integer.parseInt(token.substring(MAX_AGE.length() + 1)); } else if (token.startsWith(SMAX_AGE)) { sMaxAge = Integer.parseInt(token.substring(SMAX_AGE.length() + 1)); } else if (token.startsWith(PUBLIC)) { // ignore } else if (token.startsWith(NO_STORE)) { noStore = true; } else if (token.startsWith(NO_TRANSFORM)) { noTransform = true; } else if (token.startsWith(MUST_REVALIDATE)) { mustRevalidate = true; } else if (token.startsWith(PROXY_REVALIDATE)) { proxyRevalidate = true; } else if (token.startsWith(PRIVATE)) { isPrivate = true; addFields(privateFields, token); } else if (token.startsWith(NO_CACHE)) { noCache = true; addFields(noCacheFields, token); } else { String[] extPair = token.split("="); String value = extPair.length == 2 ? extPair[1] : ""; extensions.put(extPair[0], value); } } CacheControl cc = new CacheControl(); cc.setMaxAge(maxAge); cc.setSMaxAge(sMaxAge); cc.setPrivate(isPrivate); cc.getPrivateFields().addAll(privateFields); cc.setMustRevalidate(mustRevalidate); cc.setProxyRevalidate(proxyRevalidate); cc.setNoCache(noCache); cc.getNoCacheFields().addAll(noCacheFields); cc.setNoStore(noStore); cc.setNoTransform(noTransform); cc.getCacheExtension().putAll(extensions); return cc; }
Example 20
Source File: ResponseHelper.java From render with GNU General Public License v2.0 | 4 votes |
public static Response.ResponseBuilder setDefaultMaxAge(final Response.ResponseBuilder builder) { final CacheControl cc = new CacheControl(); cc.setMaxAge(3600); // 1 hour return builder.cacheControl(cc); }