@Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { final CacheControl oneYear = CacheControl.maxAge(365, TimeUnit.DAYS).cachePublic(); registry.addResourceHandler("/favicon.ico") .addResourceLocations("/favicon.ico") .setCacheControl(oneYear); registry.addResourceHandler("/static/**") .addResourceLocations("/static/") .setCacheControl(oneYear); registry.addResourceHandler("/frontend/**") .addResourceLocations("/frontend/") .setCacheControl(oneYear); }
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/app/**") .addResourceLocations("classpath:/app/"); CacheControl cacheControl = CacheControl .maxAge(365, TimeUnit.DAYS) .cachePublic(); registry.addResourceHandler("/assets/**") .addResourceLocations("classpath:/assets/") .setCacheControl(cacheControl); if (!registry.hasMappingForPattern("/webjars/**")) { registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCacheControl(cacheControl); } }
private final ResponseEntity.BodyBuilder newResponse(final HttpStatus status, final String etag) { ResponseEntity.BodyBuilder response = ResponseEntity.status(status) .eTag(etag) .cacheControl(CacheControl.maxAge(cacheMaxAgeSec, TimeUnit.SECONDS)); final String adLanguage = getJSONOptions().getAD_Language(); if (adLanguage != null && !adLanguage.isEmpty()) { final String contentLanguage = ADLanguageList.toHttpLanguageTag(adLanguage); response.header(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); response.header(HttpHeaders.VARY, HttpHeaders.ACCEPT_LANGUAGE); // advice browser to include ACCEPT_LANGUAGE in their caching key } return response; }
/** * Needed to serve the UI-part of swagger */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); // Set cache timeout for static resources to reduce resource burden on application registry.addResourceHandler("/static/**") .addResourceLocations("/static/") .setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS)) .resourceChain(false) .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**")); }
private static void setResponse( HttpServletResponse response, int statusCode, String message ) { response.setStatus( statusCode ); response.setContentType( CONTENT_TYPE_TEXT ); response.setHeader( HEADER_CACHE_CONTROL, CacheControl.noStore().getHeaderValue() ); PrintWriter writer = null; try { writer = response.getWriter(); writer.println( message ); writer.flush(); } catch ( IOException ex ) { // Ignore } finally { IOUtils.closeQuietly( writer ); } }
@RequestMapping( value = "/{uid}", method = RequestMethod.GET ) public @ResponseBody RootNode getObject( @PathVariable( "uid" ) String pvUid, @RequestParam Map<String, String> rpParameters, HttpServletRequest request, HttpServletResponse response ) throws Exception { User user = currentUserService.getCurrentUser(); if ( !aclService.canRead( user, getEntityClass() ) ) { throw new ReadAccessDeniedException( "You don't have the proper permissions to read objects of this type." ); } List<String> fields = Lists.newArrayList( contextService.getParameterValues( "fields" ) ); List<String> filters = Lists.newArrayList( contextService.getParameterValues( "filter" ) ); if ( fields.isEmpty() ) { fields.add( ":all" ); } response.setHeader( ContextUtils.HEADER_CACHE_CONTROL, CacheControl.noCache().cachePrivate().getHeaderValue() ); return getObjectInternal( pvUid, rpParameters, filters, fields, user ); }
@RequestMapping(value = "/{account}/{projectName}/{branchName}.svg") public ResponseEntity<String> getBadge(@PathVariable String account, @PathVariable String projectName, @PathVariable String branchName) throws Exception { QBuild b = QBuild.build; Page<Build> buildPage = buildRepository.findAll(b.branch.name.eq(branchName).and(b.branch.project.account.eq(account)).and(b.branch.project.name.eq(projectName)), new QPageRequest(0, 2, b.number.desc())); if (buildPage.getTotalPages() == 0) throw new BadgeUnknownException(); Build latest = buildPage.getContent().get(0); long current = System.currentTimeMillis(); HttpHeaders headers = new HttpHeaders(); // see #7 headers.setExpires(current); headers.setDate(current); return ResponseEntity .ok() .headers(headers) .cacheControl(CacheControl.noCache()) .lastModified(current) .eTag(Long.toString(latest.getId())) .body(FreeMarkerTemplateUtils.processTemplateIntoString(configurer.getConfiguration().getTemplate("badge/mybadge.ftl"), latest)); }
/** * Download a file from the GridFS / MongoDB by a given filename. */ @RequestMapping(value = "/files/**") public ResponseEntity<?> downloadFile(HttpServletRequest request) { String completePath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); String fileName = completePath.replaceFirst("/public/files", ""); // find file in grid fs / mongo db GridFSDBFile gridFsFile = this.fileService.findFile(fileName); if (gridFsFile == null) { return ResponseEntity.notFound().build(); } HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.CONTENT_DISPOSITION, "filename=" + removeFolders(gridFsFile.getFilename())); // Return Status 200 or 304 if not modified return ResponseEntity.ok() .headers(headers) .contentLength(gridFsFile.getLength()) .cacheControl(CacheControl.maxAge(0, TimeUnit.MILLISECONDS).mustRevalidate() .cachePrivate().cachePublic()) .eTag(String.valueOf(gridFsFile.getUploadDate().getTime())) .lastModified(gridFsFile.getUploadDate().getTime()) .contentType(MediaType.parseMediaType(gridFsFile.getContentType())) .body(new InputStreamResource(gridFsFile.getInputStream())); }
/** * Get the previous 10 versions of the study attachment metadata. * * @param studyId The id of the study * @param filename The filename of the attachment * @param limit like page size * @param skip for skipping n versions * * @return A list of previous study versions */ @RequestMapping("/studies/{studyId}/attachments/{filename:.+}/versions") public ResponseEntity<?> findPreviousStudyVersions(@PathVariable String studyId, @PathVariable String filename, @RequestParam(name = "limit", defaultValue = "10") Integer limit, @RequestParam(name = "skip", defaultValue = "0") Integer skip) { List<StudyAttachmentMetadata> studyAttachmentVersions = studyAttachmentVersionsService .findPreviousStudyAttachmentVersions(studyId, filename, limit, skip); if (studyAttachmentVersions == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok() .cacheControl(CacheControl.noStore()) .body(studyAttachmentVersions); }
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { /*registry.addResourceHandler(UploadViewController.CONTROLLER_PATH+"/**") .setCacheControl(CacheControl.maxAge(30, TimeUnit.DAYS));*/ //默认把上传目录映射 if(siteConfig.getUpload().isFileStorePathToResourceHandler()){ registry.addResourceHandler(BootWebUtils.CONTROLLER_PREFIX+"/upload/**") .addResourceLocations("file:"+FileUtils.convertDir(siteConfig.getUpload().getFileStorePath())) .setCacheControl(CacheControl.maxAge(siteConfig.getUpload().getResourceCacheInDays(), TimeUnit.DAYS)); } List<ResourceHandlerConfig> resourceHandlers = this.jfishBootConfig.getMvc().getResourceHandlers(); resourceHandlers.forEach(res->{ registry.addResourceHandler(res.getPathPatterns()) .addResourceLocations(res.getLocations()) .setCacheControl(CacheControl.maxAge(res.getCacheInDays(), TimeUnit.DAYS)); }); }
/** * Creates a SVG badge for a project with a given {@link ReleaseStatus}. * * @param projectId * @param releaseStatus * @return * @throws IOException */ private ResponseEntity<byte[]> badgeFor(String projectId, ReleaseStatus releaseStatus) throws IOException { Project project = service.getProject(projectId); if (project == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } Optional<ProjectRelease> gaRelease = getRelease(project.getProjectReleases(), projectRelease -> projectRelease.getReleaseStatus() == releaseStatus); if (!gaRelease.isPresent()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } byte[] svgBadge = versionBadgeService.createSvgBadge(project, gaRelease.get()); return ResponseEntity.ok().eTag(gaRelease.get().getVersion()).cacheControl(CacheControl.maxAge(1L, TimeUnit.HOURS)) .body(svgBadge); }
private ResponseEntity<String> serviceCapabilitiesFor( InitializrMetadataVersion version, MediaType contentType) { String appUrl = generateAppUrl(); String content = getJsonMapper(version).write(metadataProvider.get(), appUrl); return ResponseEntity.ok().contentType(contentType).eTag(createUniqueId(content)) .cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS)).body(content); }
private ResponseEntity<String> dependenciesFor(InitializrMetadataVersion version, String edorasoneVersion) { InitializrMetadata metadata = metadataProvider.get(); Version v = edorasoneVersion != null ? Version.parse(edorasoneVersion) : Version.parse(metadata.getEdorasoneVersions().getDefault().getId()); DependencyMetadata dependencyMetadata = dependencyMetadataProvider.get(metadata, v); String content = new DependencyMetadataV21JsonMapper().write(dependencyMetadata); return ResponseEntity.ok().contentType(version.getMediaType()) .eTag(createUniqueId(content)) .cacheControl(CacheControl.maxAge(7, TimeUnit.DAYS)).body(content); }
/** * Gets bootstrap. * * @return the bootstrap */ @RequestMapping(method = RequestMethod.GET) public ResponseEntity<Bootstrap> getBootstrap() { return ResponseEntity.ok() .cacheControl(CacheControl.maxAge(2, TimeUnit.HOURS)) .body(bootstrap); }
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/assets/**").addResourceLocations("file:node_modules/").setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS)); registry.addResourceHandler("/js/**").addResourceLocations("file:src/main/app/js/").setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS)); registry.addResourceHandler("/css/**").addResourceLocations("file:src/main/app/css/").setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS)); registry.addResourceHandler("/images/**").addResourceLocations("file:src/main/resources/static/images/").setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS)); super.addResourceHandlers(registry); }
private CacheControl createCacheConfig(long maxAgeSeconds) { if (maxAgeSeconds < 0) { return CacheControl.noCache(); } else { return CacheControl.maxAge(maxAgeSeconds, TimeUnit.SECONDS); } }
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCacheControl( CacheControl.maxAge(7, TimeUnit.DAYS)); registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCacheControl( CacheControl.maxAge(24, TimeUnit.HOURS)); }
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException { checkRequest(request); String lookupPath = this.urlPathHelper.getLookupPathForRequest(request); if (logger.isDebugEnabled()) { logger.debug("Looking up cache seconds for [" + lookupPath + "]"); } CacheControl cacheControl = lookupCacheControl(lookupPath); Integer cacheSeconds = lookupCacheSeconds(lookupPath); if (cacheControl != null) { if (logger.isDebugEnabled()) { logger.debug("Applying CacheControl to [" + lookupPath + "]"); } applyCacheControl(response, cacheControl); } else if (cacheSeconds != null) { if (logger.isDebugEnabled()) { logger.debug("Applying CacheControl to [" + lookupPath + "]"); } applyCacheSeconds(response, cacheSeconds); } else { if (logger.isDebugEnabled()) { logger.debug("Applying default cache seconds to [" + lookupPath + "]"); } prepareResponse(response); } return true; }
/** * Look up a {@link org.springframework.http.CacheControl} instance for the given URL path. * <p>Supports direct matches, e.g. a registered "/test" matches "/test", * and various Ant-style pattern matches, e.g. a registered "/t*" matches * both "/test" and "/team". For details, see the AntPathMatcher class. * @param urlPath URL the bean is mapped to * @return the associated {@code CacheControl}, or {@code null} if not found * @see org.springframework.util.AntPathMatcher */ protected CacheControl lookupCacheControl(String urlPath) { // Direct match? CacheControl cacheControl = this.cacheControlMappings.get(urlPath); if (cacheControl == null) { // Pattern match? for (String registeredPath : this.cacheControlMappings.keySet()) { if (this.pathMatcher.match(registeredPath, urlPath)) { cacheControl = this.cacheControlMappings.get(registeredPath); } } } return cacheControl; }
/** * Set the HTTP Cache-Control header according to the given settings. * @param response current HTTP response * @param cacheControl the pre-configured cache control settings * @since 4.2 */ protected final void applyCacheControl(HttpServletResponse response, CacheControl cacheControl) { String ccValue = cacheControl.getHeaderValue(); if (ccValue != null) { // Set computed HTTP 1.1 Cache-Control header response.setHeader(HEADER_CACHE_CONTROL, ccValue); if (response.containsHeader(HEADER_PRAGMA)) { // Reset HTTP 1.0 Pragma header if present response.setHeader(HEADER_PRAGMA, ""); } } }
/** * Apply the given cache seconds and generate corresponding HTTP headers, * i.e. allow caching for the given number of seconds in case of a positive * value, prevent caching if given a 0 value, do nothing else. * Does not tell the browser to revalidate the resource. * @param response current HTTP response * @param cacheSeconds positive number of seconds into the future that the * response should be cacheable for, 0 to prevent caching */ @SuppressWarnings("deprecation") protected final void applyCacheSeconds(HttpServletResponse response, int cacheSeconds) { if (this.useExpiresHeader || !this.useCacheControlHeader) { // Deprecated HTTP 1.0 cache behavior, as in previous Spring versions if (cacheSeconds > 0) { cacheForSeconds(response, cacheSeconds); } else if (cacheSeconds == 0) { preventCaching(response); } } else { CacheControl cControl; if (cacheSeconds > 0) { cControl = CacheControl.maxAge(cacheSeconds, TimeUnit.SECONDS); if (this.alwaysMustRevalidate) { cControl = cControl.mustRevalidate(); } } else if (cacheSeconds == 0) { cControl = (this.useCacheControlNoStore ? CacheControl.noStore() : CacheControl.noCache()); } else { cControl = CacheControl.empty(); } applyCacheControl(response, cControl); } }
private String registerResourceHandler(ParserContext parserContext, Element element, Object source) { String locationAttr = element.getAttribute("location"); if (!StringUtils.hasText(locationAttr)) { parserContext.getReaderContext().error("The 'location' attribute is required.", parserContext.extractSource(element)); return null; } ManagedList<String> locations = new ManagedList<String>(); locations.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(locationAttr))); RootBeanDefinition resourceHandlerDef = new RootBeanDefinition(ResourceHttpRequestHandler.class); resourceHandlerDef.setSource(source); resourceHandlerDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); resourceHandlerDef.getPropertyValues().add("locations", locations); String cacheSeconds = element.getAttribute("cache-period"); if (StringUtils.hasText(cacheSeconds)) { resourceHandlerDef.getPropertyValues().add("cacheSeconds", cacheSeconds); } Element cacheControlElement = DomUtils.getChildElementByTagName(element, "cache-control"); if (cacheControlElement != null) { CacheControl cacheControl = parseCacheControl(cacheControlElement); resourceHandlerDef.getPropertyValues().add("cacheControl", cacheControl); } Element resourceChainElement = DomUtils.getChildElementByTagName(element, "resource-chain"); if (resourceChainElement != null) { parseResourceChain(resourceHandlerDef, parserContext, resourceChainElement, source); } String beanName = parserContext.getReaderContext().generateBeanName(resourceHandlerDef); parserContext.getRegistry().registerBeanDefinition(beanName, resourceHandlerDef); parserContext.registerComponent(new BeanComponentDefinition(resourceHandlerDef, beanName)); return beanName; }
private CacheControl parseCacheControl(Element element) { CacheControl cacheControl = CacheControl.empty(); if ("true".equals(element.getAttribute("no-cache"))) { cacheControl = CacheControl.noCache(); } else if ("true".equals(element.getAttribute("no-store"))) { cacheControl = CacheControl.noStore(); } else if (element.hasAttribute("max-age")) { cacheControl = CacheControl.maxAge(Long.parseLong(element.getAttribute("max-age")), TimeUnit.SECONDS); } if ("true".equals(element.getAttribute("must-revalidate"))) { cacheControl = cacheControl.mustRevalidate(); } if ("true".equals(element.getAttribute("no-transform"))) { cacheControl = cacheControl.noTransform(); } if ("true".equals(element.getAttribute("cache-public"))) { cacheControl = cacheControl.cachePublic(); } if ("true".equals(element.getAttribute("cache-private"))) { cacheControl = cacheControl.cachePrivate(); } if ("true".equals(element.getAttribute("proxy-revalidate"))) { cacheControl = cacheControl.proxyRevalidate(); } if (element.hasAttribute("s-maxage")) { cacheControl = cacheControl.sMaxAge(Long.parseLong(element.getAttribute("s-maxage")), TimeUnit.SECONDS); } return cacheControl; }
@Test public void testResourcesWithResolversTransformersCustom() throws Exception { loadBeanDefinitions("mvc-config-resources-chain-no-auto.xml", 12); SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class); assertNotNull(mapping); assertNotNull(mapping.getUrlMap().get("/resources/**")); ResourceHttpRequestHandler handler = appContext.getBean((String) mapping.getUrlMap().get("/resources/**"), ResourceHttpRequestHandler.class); assertNotNull(handler); assertThat(handler.getCacheControl().getHeaderValue(), Matchers.equalTo(CacheControl.maxAge(1, TimeUnit.HOURS) .sMaxAge(30, TimeUnit.MINUTES).cachePublic().getHeaderValue())); List<ResourceResolver> resolvers = handler.getResourceResolvers(); assertThat(resolvers, Matchers.hasSize(3)); assertThat(resolvers.get(0), Matchers.instanceOf(VersionResourceResolver.class)); assertThat(resolvers.get(1), Matchers.instanceOf(GzipResourceResolver.class)); assertThat(resolvers.get(2), Matchers.instanceOf(PathResourceResolver.class)); VersionResourceResolver versionResolver = (VersionResourceResolver) resolvers.get(0); assertThat(versionResolver.getStrategyMap().get("/**/*.js"), Matchers.instanceOf(FixedVersionStrategy.class)); assertThat(versionResolver.getStrategyMap().get("/**"), Matchers.instanceOf(ContentVersionStrategy.class)); List<ResourceTransformer> transformers = handler.getResourceTransformers(); assertThat(transformers, Matchers.hasSize(2)); assertThat(transformers.get(0), Matchers.instanceOf(CachingResourceTransformer.class)); assertThat(transformers.get(1), Matchers.instanceOf(AppCacheManifestTransformer.class)); }
@Test public void cacheControl() { assertThat(getHandler("/resources/**").getCacheControl(), Matchers.nullValue()); this.registration.setCacheControl(CacheControl.noCache().cachePrivate()); assertThat(getHandler("/resources/**").getCacheControl().getHeaderValue(), Matchers.equalTo(CacheControl.noCache().cachePrivate().getHeaderValue())); }
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/") .setCacheControl(CacheControl.maxAge(72, TimeUnit.HOURS).cachePublic()) .resourceChain(true) .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**")).addTransformer(new CssLinkResourceTransformer()); }
/** * We cache names if there are more than 3 services. This helps people getting started: if we * cache empty results, users have more questions. We assume caching becomes a concern when zipkin * is in active use, and active use usually implies more than 3 services. */ ResponseEntity<List<String>> maybeCacheNames(List<String> names) { ResponseEntity.BodyBuilder response = ResponseEntity.ok(); if (serviceCount > 3) { response.cacheControl(CacheControl.maxAge(namesMaxAge, TimeUnit.SECONDS).mustRevalidate()); } return response.body(names); }
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/stockmanagement/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCacheControl(CacheControl.maxAge(7, TimeUnit.DAYS)); super.addResourceHandlers(registry); }
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { if (config.getTemplatesMinified()) { registry .addResourceHandler("/assets/" + config.getAssetsTimestamp() + "/**") .addResourceLocations("/assets/") .setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS).cachePublic()) .resourceChain(true) .addResolver(new GzipResourceResolver()) .addResolver(new PathResourceResolver()); } else { registry .addResourceHandler("/assets/" + config.getAssetsTimestamp() + "/**") .addResourceLocations("/assets/") .setCacheControl(CacheControl.noCache()) .resourceChain(true) .addResolver(new GzipResourceResolver()) .addResolver(new PathResourceResolver()); } // Always serve uploaded resources as a backup in-case we're running without an Apache in front... /* registry .addResourceHandler("/uploaded-resources/**") .addResourceLocations("file:///" + config.getResourceUploadPath()) .resourceChain(true) .addResolver(new GzipResourceResolver()) .addResolver(new PathResourceResolver()); */ }
/** * 设置Cache-Control头,缓存时间为365天 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/assets/**") .addResourceLocations("/assets/") .setCacheControl( CacheControl .maxAge(365, TimeUnit.DAYS) .cachePublic() ); }
/** * 生成JS的配置文件 */ @GetMapping("/config") public String configJs(HttpServletResponse response, Model model) throws Exception { CacheControl cacheControl = CacheControl.maxAge(30, TimeUnit.MINUTES).cachePublic(); response.addHeader("Cache-Control", cacheControl.getHeaderValue()); response.addHeader("Content-Type", "application/javascript;charset=UTF-8"); model.addAllAttributes(properties); return "config-js"; }
@Override public String intercept( ActionInvocation invocation ) throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); if ( HttpMethod.GET == HttpMethod.resolve( request.getMethod() ) ) { response.setHeader( "Cache-Control", CacheControl.maxAge( seconds, TimeUnit.SECONDS ).cachePublic().getHeaderValue() ); } return invocation.invoke(); }
@RequestMapping( value = "/{uid}/{property}", method = RequestMethod.GET ) public @ResponseBody RootNode getObjectProperty( @PathVariable( "uid" ) String pvUid, @PathVariable( "property" ) String pvProperty, @RequestParam Map<String, String> rpParameters, TranslateParams translateParams, HttpServletRequest request, HttpServletResponse response ) throws Exception { User user = currentUserService.getCurrentUser(); if ( !"translations".equals( pvProperty ) ) { setUserContext( user, translateParams ); } else { setUserContext( null, new TranslateParams( false ) ); } if ( !aclService.canRead( user, getEntityClass() ) ) { throw new ReadAccessDeniedException( "You don't have the proper permissions to read objects of this type." ); } List<String> fields = Lists.newArrayList( contextService.getParameterValues( "fields" ) ); if ( fields.isEmpty() ) { fields.add( ":all" ); } String fieldFilter = "[" + Joiner.on( ',' ).join( fields ) + "]"; response.setHeader( ContextUtils.HEADER_CACHE_CONTROL, CacheControl.noCache().cachePrivate().getHeaderValue() ); return getObjectInternal( pvUid, rpParameters, Lists.newArrayList(), Lists.newArrayList( pvProperty + fieldFilter ), user ); }
@RequestMapping( value = "/{uid}/{property}/{itemId}", method = RequestMethod.GET ) public @ResponseBody RootNode getCollectionItem( @PathVariable( "uid" ) String pvUid, @PathVariable( "property" ) String pvProperty, @PathVariable( "itemId" ) String pvItemId, @RequestParam Map<String, String> parameters, TranslateParams translateParams, HttpServletRequest request, HttpServletResponse response ) throws Exception { User user = currentUserService.getCurrentUser(); setUserContext( user, translateParams ); if ( !aclService.canRead( user, getEntityClass() ) ) { throw new ReadAccessDeniedException( "You don't have the proper permissions to read objects of this type." ); } RootNode rootNode = getObjectInternal( pvUid, parameters, Lists.newArrayList(), Lists.newArrayList( pvProperty + "[:all]" ), user ); // TODO optimize this using field filter (collection filtering) if ( !rootNode.getChildren().isEmpty() && rootNode.getChildren().get( 0 ).isCollection() ) { rootNode.getChildren().get( 0 ).getChildren().stream().filter( Node::isComplex ).forEach( node -> { node.getChildren().stream() .filter( child -> child.isSimple() && child.getName().equals( "id" ) && !((SimpleNode) child).getValue().equals( pvItemId ) ) .forEach( child -> rootNode.getChildren().get( 0 ).removeChild( node ) ); } ); } if ( rootNode.getChildren().isEmpty() || rootNode.getChildren().get( 0 ).getChildren().isEmpty() ) { throw new WebMessageException( WebMessageUtils.notFound( pvProperty + " with ID " + pvItemId + " could not be found." ) ); } response.setHeader( ContextUtils.HEADER_CACHE_CONTROL, CacheControl.noCache().cachePrivate().getHeaderValue() ); return rootNode; }
public void send( WebMessage webMessage, HttpServletResponse response, HttpServletRequest request ) { String type = request.getHeader( "Accept" ); type = !StringUtils.isEmpty( type ) ? type : request.getContentType(); type = !StringUtils.isEmpty( type ) ? type : MediaType.APPLICATION_JSON_VALUE; HttpStatus httpStatus = HttpStatus.valueOf( webMessage.getHttpStatusCode() ); if ( httpStatus.is4xxClientError() || httpStatus.is5xxServerError() ) { response.setHeader( "Cache-Control", CacheControl.noCache().cachePrivate().getHeaderValue() ); } // allow type to be overridden by path extension if ( request.getPathInfo().endsWith( ".json" ) ) { type = MediaType.APPLICATION_JSON_VALUE; } else if ( request.getPathInfo().endsWith( ".xml" ) ) { type = MediaType.APPLICATION_XML_VALUE; } if ( isCompatibleWith( type, MediaType.APPLICATION_JSON ) ) { sendJson( webMessage, response ); } else if ( isCompatibleWith( type, MediaType.APPLICATION_XML ) ) { sendXml( webMessage, response ); } else { sendJson( webMessage, response ); // default to json } }
@ExceptionHandler(BadgeUnknownException.class) public ResponseEntity<String> getBadgeForUnknown() throws IOException, TemplateException { return ResponseEntity .ok() .cacheControl(CacheControl.noCache()) .lastModified(System.currentTimeMillis()) .body(FreeMarkerTemplateUtils.processTemplateIntoString(configurer.getConfiguration().getTemplate("badge/unknown-badge.ftl"), null)); }
@RequestMapping(value = "{groupId}/{artifactId}/badge.{ext}", method = RequestMethod.GET) //todo version? //todo HTTP/HTTPS? public ResponseEntity<String> badge( @PathVariable("groupId") String groupId, @PathVariable("artifactId") String artifactId, @PathVariable("ext") String ext, @RequestParam("style") Optional<String> style, @RequestParam("color") Optional<String> color , @RequestParam("subject") Optional<String> subject , @RequestParam("prefix") Optional<String> prefix , @RequestParam("suffix") Optional<String> suffix ) { String version = versionCache.getActualVersion(groupId, artifactId); version = prefix.orElse(badgeVersionPrefix) + version + suffix.orElse(badgeVersionSuffix); UriComponentsBuilder shieldURIBuilder = ServletUriComponentsBuilder.fromHttpUrl(shieldsBaseURL); shieldURIBuilder.path("{subject}-{version}-{color}.{ext}"); if (style.isPresent()) { shieldURIBuilder.queryParam("style", style.get()); } Map<String, String> params = new HashMap<>(4); params.put("subject", badgePart(subject.orElse(badgeSubject))); params.put("version", badgePart(version)); params.put("color", badgePart(color.orElse(badgeColor))); params.put("ext", ext); UriComponents shieldURI = shieldURIBuilder.build().expand(params); Duration cacheDuration = versionCache.getExpireAfterWrite().dividedBy(2); CacheControl cacheControl = CacheControl.maxAge(cacheDuration.toMinutes(), TimeUnit.MINUTES) .cachePublic(); return ResponseEntity.status(HttpStatus.TEMPORARY_REDIRECT) .location(shieldURI.toUri()) .cacheControl(cacheControl) .header(HttpHeaders.EXPIRES, ZonedDateTime.now(GMT).plus(cacheDuration).format(EXPIRES_FORMAT)) .body(null); }
/** * Override default get by id since it does not set cache headers correctly. * * @param id a study id * @return the study or not found */ @RequestMapping(method = RequestMethod.GET, value = "/studies/{id}") public ResponseEntity<Study> findStudy(@PathVariable String id) { Study study = studyRepository.findOne(id); if (study == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok() .cacheControl(CacheControl.maxAge(0, TimeUnit.DAYS).mustRevalidate().cachePublic()) .eTag(study.getVersion().toString()) .lastModified( study.getLastModifiedDate().atZone(ZoneId.of("GMT")).toInstant().toEpochMilli()) .body(study); }
/** * Get the previous 10 versions of the study. * * @param id The id of the study * @param limit like page size * @param skip for skipping n versions * * @return A list of previous study versions */ @RequestMapping("/studies/{id}/versions") public ResponseEntity<?> findPreviousStudyVersions(@PathVariable String id, @RequestParam(name = "limit", defaultValue = "10") Integer limit, @RequestParam(name = "skip", defaultValue = "0") Integer skip) { List<Study> studyVersions = studyVersionsService.findPreviousStudyVersions(id, limit, skip); if (studyVersions == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok() .cacheControl(CacheControl.noStore()) .body(studyVersions); }
@GetMapping(value="/**") public ResponseEntity<InputStreamResource> read(WebRequest webRequest, HttpServletRequest request, HttpServletResponse response){ String accessablePath = RequestUtils.getServletPath(request); if(accessablePath.length()>CONTROLLER_PATH.length()){ accessablePath = accessablePath.substring(CONTROLLER_PATH.length()); }else{ throw new BaseException("error path: " + accessablePath); } String ext = FileUtils.getExtendName(accessablePath).toLowerCase(); MediaType mediaType = null; if(imagePostfix.contains(ext)){ mediaType = MediaType.parseMediaType("image/"+ext); }else{ mediaType = MediaType.APPLICATION_OCTET_STREAM; } if(webRequest.checkNotModified(fileStorer.getLastModified(accessablePath))){ return ResponseEntity.status(HttpStatus.NOT_MODIFIED) .build(); } return ResponseEntity.ok() .contentType(mediaType) //一起写才起作用 .cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS)) .lastModified(new Date().getTime()) .eTag(accessablePath) .body(new InputStreamResource(fileStorer.readFileStream(accessablePath))); }