org.springframework.http.CacheControl Java Examples

The following examples show how to use org.springframework.http.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: ContextUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void configureAnalyticsResponse( HttpServletResponse response, String contentType,
    CacheStrategy cacheStrategy, String filename, boolean attachment, Date latestEndDate )
{
    // Progressive cache will always take priority
    if ( RESPECT_SYSTEM_SETTING == cacheStrategy && webCache.isProgressiveCachingEnabled() && latestEndDate != null )
    {
        // Uses the progressive TTL
        final CacheControl cacheControl = webCache.getCacheControlFor( latestEndDate );

        configureResponse( response, contentType, filename, attachment, cacheControl );
    }
    else
    {
        // Respects the fixed (predefined) settings
        configureResponse( response, contentType, cacheStrategy, filename, attachment );
    }
}
 
Example #2
Source File: HttpIT.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void testCache() {
    startServerWithoutSecurity(CacheController.class);

    getWebTestClient()
        .get()
        .exchange()
        .expectStatus()
        .isOk()
        .expectHeader()
        .valueEquals(HttpHeaders.ETAG, "\"test\"")
        .expectHeader()
        .cacheControl(CacheControl.maxAge(1, TimeUnit.MINUTES))
        .expectBody(String.class)
        .isEqualTo("test");

    getWebTestClient()
        .get()
        .header(HttpHeaders.IF_NONE_MATCH, "\"test\"")
        .exchange()
        .expectStatus()
        .isNotModified();
}
 
Example #3
Source File: SharingController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@RequestMapping( value = "/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE )
public void searchUserGroups( @RequestParam String key, @RequestParam( required = false ) Integer pageSize,
    HttpServletResponse response ) throws IOException, WebMessageException
{
    if ( key == null )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Search key not specified" ) );
    }

    int max = pageSize != null ? pageSize : Integer.MAX_VALUE;

    List<SharingUserGroupAccess> userGroupAccesses = getSharingUserGroups( key, max );
    List<SharingUserAccess> userAccesses = getSharingUser( key, max );

    Map<String, Object> output = new HashMap<>();
    output.put( "userGroups", userGroupAccesses );
    output.put( "users", userAccesses );

    response.setContentType( MediaType.APPLICATION_JSON_VALUE );
    response.setHeader( ContextUtils.HEADER_CACHE_CONTROL, CacheControl.noCache().cachePrivate().getHeaderValue() );
    renderService.toJson( response.getOutputStream(), output );
}
 
Example #4
Source File: MvcConfiguration.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    ResourceHandlerRegistration reg = registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    boolean isLive = environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE));
    int cacheMinutes = isLive ? 15 : 0;
    reg.setCachePeriod(cacheMinutes * 60);

    //
    registry
        .addResourceHandler("/webjars/**")
        .addResourceLocations("/webjars/")
        .setCacheControl(CacheControl.maxAge(Duration.ofDays(isLive ? 10 : 0)).mustRevalidate());

    registry.addResourceHandler("/assets/**")
        .addResourceLocations("/webjars/alfio-public-frontend/" + frontendVersion + "/alfio-public-frontend/assets/");

}
 
Example #5
Source File: TestCaseController.java    From android-uiconductor with Apache License 2.0 6 votes vote down vote up
@CrossOrigin(origins = "*")
@GetMapping("/getSavedResource")
public ResponseEntity<byte[]> getSavedResource(@RequestParam(value = "path") String path) {
  HttpStatus httpStatus = HttpStatus.OK;
  byte[] media = new byte[0];
  try (InputStream in =
      new FileInputStream(Paths.get(URLDecoder.decode(path, "UTF-8")).toString())) {
    media = ByteStreams.toByteArray(in);
  } catch (IOException e) {
    httpStatus = HttpStatus.NOT_FOUND;
    logger.warning("Cannot fetch image: " + path);
  }
  HttpHeaders headers = new HttpHeaders();
  headers.setCacheControl(CacheControl.noCache().getHeaderValue());
  headers.setContentType(MediaType.IMAGE_JPEG);
  return new ResponseEntity<>(media, headers, httpStatus);
}
 
Example #6
Source File: ETagResponseEntityBuilder.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 6 votes vote down vote up
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 = getAdLanguage();
	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;
}
 
Example #7
Source File: ServiceWorkerController.java    From zhcet-web with Apache License 2.0 6 votes vote down vote up
@Cacheable("sw")
@GetMapping("/sw.js")
public ResponseEntity<String> serviceWorker() {
    ClassPathResource classPathResource = new ClassPathResource("src/sw.mjs");
    String loaded = null;
    try {
        loaded = IOUtils.toString(classPathResource.getInputStream(), "UTF-8");
    } catch (IOException e) {
        log.error("Error loading service worker", e);
    }

    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType("text/javascript"))
            .cacheControl(CacheControl
                    .maxAge(0, TimeUnit.SECONDS))
            .body(loaded);
}
 
Example #8
Source File: IconController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@RequestMapping( value="/{iconKey}/icon.svg", method = RequestMethod.GET )
public void getIconData( HttpServletResponse response, @PathVariable String iconKey ) throws WebMessageException,
    IOException
{
    Optional<Resource> icon = iconService.getIconResource( iconKey );

    if ( !icon.isPresent() )
    {
        throw new WebMessageException( WebMessageUtils.notFound( String.format( "Icon resource not found: '%s", iconKey ) ) );
    }

    response.setHeader( "Cache-Control", CacheControl.maxAge( TTL, TimeUnit.DAYS ).getHeaderValue() );
    response.setContentType( MediaType.SVG_UTF_8.toString() );

    StreamUtils.copy( icon.get().getInputStream(), response.getOutputStream() );
}
 
Example #9
Source File: WebAppConfigurer.java    From frostmourne with MIT License 6 votes vote down vote up
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/index.html")
            .addResourceLocations("classpath:/dist/index.html")
            .setCacheControl(CacheControl.noCache())
            .setCacheControl(CacheControl.noStore())
            .resourceChain(true);
    registry.addResourceHandler("/static/**")
            .addResourceLocations("classpath:/dist/static/", "classpath:/static/")
            .resourceChain(true);
    registry.addResourceHandler("/dist/**")
            .addResourceLocations("classpath:/dist/")
            .resourceChain(true);
    registry.addResourceHandler("/favicon.ico")
            .addResourceLocations("classpath:/dist/favicon.ico")
            .resourceChain(true);
}
 
Example #10
Source File: WebCache.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Defines and return a CacheControl object with the correct expiration time and
 * cacheability based on the internal system settings defined by the user. The
 * expiration time is defined through the Enum {@link CacheStrategy}
 * 
 * @param cacheStrategy
 *
 * @return a CacheControl object configured based on current system settings.
 */
public CacheControl getCacheControlFor( CacheStrategy cacheStrategy )
{
    final CacheControl cacheControl;

    if ( RESPECT_SYSTEM_SETTING == cacheStrategy )
    {
        cacheStrategy = (CacheStrategy) systemSettingManager.getSystemSetting( CACHE_STRATEGY );
    }

    final boolean cacheStrategyHasExpirationTimeSet = cacheStrategy != null && cacheStrategy != NO_CACHE;

    if ( cacheStrategyHasExpirationTimeSet )
    {
        cacheControl = maxAge( cacheStrategy.toSeconds(), SECONDS );

        setCacheabilityFor( cacheControl );
    }
    else
    {
        cacheControl = noCache();
    }

    return cacheControl;
}
 
Example #11
Source File: WebContentGenerator.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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, "");
		}
		if (response.containsHeader(HEADER_EXPIRES)) {
			// Reset HTTP 1.0 Expires header if present
			response.setHeader(HEADER_EXPIRES, "");
		}
	}
}
 
Example #12
Source File: MainController.java    From ShadowSocks-Share with Apache License 2.0 6 votes vote down vote up
/**
 * 二维码
 */
@RequestMapping(value = "/createQRCode")
@ResponseBody
public ResponseEntity<byte[]> createQRCode(long id, String text, int width, int height, WebRequest request) throws IOException, WriterException {
	// 缓存未失效时直接返回
	if (request.checkNotModified(id))
		return ResponseEntity.ok()
				.contentType(MediaType.parseMediaType(MediaType.IMAGE_PNG_VALUE))
				.cacheControl(CacheControl.maxAge(1, TimeUnit.DAYS))
				.eTag(String.valueOf(id))
				.body(null);
	return ResponseEntity.ok()
			.contentType(MediaType.parseMediaType(MediaType.IMAGE_PNG_VALUE))
			.cacheControl(CacheControl.maxAge(1, TimeUnit.DAYS))
			.eTag(String.valueOf(id))
			.body(shadowSocksSerivceImpl.createQRCodeImage(text, width, height));
}
 
Example #13
Source File: WebCacheTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testGetCacheControlForWhenCacheStrategyIsRespectSystemSetting()
{
    // Given
    final CacheStrategy theInputCacheStrategy = RESPECT_SYSTEM_SETTING;
    final CacheStrategy theCacheStrategySet = CACHE_5_MINUTES;
    final CacheControl expectedCacheControl = stubPublicCacheControl( theCacheStrategySet );

    // When
    when( systemSettingManager.getSystemSetting( CACHEABILITY ) ).thenReturn( PUBLIC );
    when( systemSettingManager.getSystemSetting( CACHE_STRATEGY ) ).thenReturn( theCacheStrategySet );
    final CacheControl actualCacheControl = webCache.getCacheControlFor( theInputCacheStrategy );

    // Then
    assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
 
Example #14
Source File: WebCacheTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testGetAnalyticsCacheControlForWhenTimeToLiveIsPositive()
{
    // Given
    final long positiveTimeToLive = 60;
    final Date aDate = new Date();
    final CacheControl expectedCacheControl = stubPublicCacheControl ( positiveTimeToLive );
    final Cacheability setCacheability = PUBLIC;

    // When
    when( systemSettingManager.getSystemSetting( CACHEABILITY ) ).thenReturn( setCacheability );
    when( analyticsCacheSettings.progressiveExpirationTimeOrDefault( aDate ) ).thenReturn( positiveTimeToLive );
    final CacheControl actualCacheControl = webCache.getCacheControlFor( aDate );

    // Then
    assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
 
Example #15
Source File: CacheWebConfig.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/")
      .setCacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)
        .noTransform()
        .mustRevalidate());
}
 
Example #16
Source File: WebCacheTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testGetCacheControlForWhenCacheStrategyIsCache30Minutes()
{
    // Given
    final CacheStrategy theCacheStrategy = CACHE_30_MINUTES;
    final CacheControl expectedCacheControl = stubPublicCacheControl( theCacheStrategy );

    // When
    when( systemSettingManager.getSystemSetting( CACHEABILITY ) ).thenReturn( PUBLIC );
    final CacheControl actualCacheControl = webCache.getCacheControlFor( theCacheStrategy );

    // Then
    assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
 
Example #17
Source File: WebContentInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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;
}
 
Example #18
Source File: ResourceEndpoint.java    From tutorials with MIT License 5 votes vote down vote up
@GetMapping("/timestamp")
public ResponseEntity<TimestampDto> getServerTimestamp() {
    return ResponseEntity
      .ok()
      .cacheControl(CacheControl.noStore())
      .body(new TimestampDto(LocalDateTime
        .now()
        .toInstant(ZoneOffset.UTC)
        .toEpochMilli()));
}
 
Example #19
Source File: WebContentGenerator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example #20
Source File: ResourcesBeanDefinitionParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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);
	}
	if (element.hasAttribute("stale-while-revalidate")) {
		cacheControl = cacheControl.staleWhileRevalidate(
				Long.parseLong(element.getAttribute("stale-while-revalidate")), TimeUnit.SECONDS);
	}
	if (element.hasAttribute("stale-if-error")) {
		cacheControl = cacheControl.staleIfError(
				Long.parseLong(element.getAttribute("stale-if-error")), TimeUnit.SECONDS);
	}
	return cacheControl;
}
 
Example #21
Source File: SpringExampleAppTests.java    From spring-qrcode-example with Apache License 2.0 5 votes vote down vote up
@Test
public void testQrCodeControllerSuccess() throws Exception {
	byte[] testImage = StreamUtils.copyToByteArray(getClass().getResourceAsStream("/test.png"));
	webClient.get().uri(SpringExampleApp.QRCODE_ENDPOINT + "?text=This is a test")
		.exchange().expectStatus().isOk()
		.expectHeader().contentType(MediaType.IMAGE_PNG)
		.expectHeader().cacheControl(CacheControl.maxAge(1800, TimeUnit.SECONDS))
		.expectBody(byte[].class).isEqualTo(testImage);
}
 
Example #22
Source File: ResourceWebHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-14005
public void doOverwriteExistingCacheControlHeaders() {
	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
	exchange.getResponse().getHeaders().setCacheControl(CacheControl.noStore().getHeaderValue());
	setPathWithinHandlerMapping(exchange, "foo.css");
	this.handler.handle(exchange).block(TIMEOUT);

	assertEquals("max-age=3600", exchange.getResponse().getHeaders().getCacheControl());
}
 
Example #23
Source File: WorldController.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@GetMapping
public ResponseEntity<WorldResult> listWorlds()
{
	if (worldResult == null)
	{
		return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
			.cacheControl(CacheControl.noCache())
			.build();
	}

	return ResponseEntity.ok()
		.cacheControl(CacheControl.maxAge(10, TimeUnit.MINUTES).cachePublic())
		.body(worldResult);
}
 
Example #24
Source File: WebCacheTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testGetCacheControlForWhenCacheStrategyIsCache1Minute()
{
    // Given
    final CacheStrategy theCacheStrategy = CACHE_1_MINUTE;
    final CacheControl expectedCacheControl = stubPublicCacheControl( theCacheStrategy );

    // When
    when( systemSettingManager.getSystemSetting( CACHEABILITY ) ).thenReturn( PUBLIC );
    final CacheControl actualCacheControl = webCache.getCacheControlFor( theCacheStrategy );

    // Then
    assertThat( actualCacheControl.toString(), is( expectedCacheControl.toString() ) );
}
 
Example #25
Source File: MvcNamespaceTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testResourcesWithResolversTransformersCustom() throws Exception {
	loadBeanDefinitions("mvc-config-resources-chain-no-auto.xml");

	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(EncodedResourceResolver.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));
}
 
Example #26
Source File: SystemSettingController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequestMapping( value = "/{key}", method = RequestMethod.GET, produces = ContextUtils.CONTENT_TYPE_TEXT )
public @ResponseBody String getSystemSettingOrTranslationAsPlainText( @PathVariable( "key" ) String key,
    @RequestParam( value = "locale", required = false ) String locale, HttpServletResponse response )
{
    response.setHeader( ContextUtils.HEADER_CACHE_CONTROL, CacheControl.noCache().cachePrivate().getHeaderValue() );

    return getSystemSettingOrTranslation( key, locale );
}
 
Example #27
Source File: ResourceHandlerRegistryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void resourceChainWithOverrides() throws Exception {
	CachingResourceResolver cachingResolver = Mockito.mock(CachingResourceResolver.class);
	VersionResourceResolver versionResolver = Mockito.mock(VersionResourceResolver.class);
	WebJarsResourceResolver webjarsResolver = Mockito.mock(WebJarsResourceResolver.class);
	PathResourceResolver pathResourceResolver = new PathResourceResolver();
	CachingResourceTransformer cachingTransformer = Mockito.mock(CachingResourceTransformer.class);
	AppCacheManifestTransformer appCacheTransformer = Mockito.mock(AppCacheManifestTransformer.class);
	CssLinkResourceTransformer cssLinkTransformer = new CssLinkResourceTransformer();

	this.registration.setCacheControl(CacheControl.maxAge(3600, TimeUnit.MILLISECONDS))
			.resourceChain(false)
				.addResolver(cachingResolver)
				.addResolver(versionResolver)
				.addResolver(webjarsResolver)
				.addResolver(pathResourceResolver)
				.addTransformer(cachingTransformer)
				.addTransformer(appCacheTransformer)
				.addTransformer(cssLinkTransformer);

	ResourceWebHandler handler = getHandler("/resources/**");
	List<ResourceResolver> resolvers = handler.getResourceResolvers();
	assertThat(resolvers.toString(), resolvers, Matchers.hasSize(4));
	assertThat(resolvers.get(0), Matchers.sameInstance(cachingResolver));
	assertThat(resolvers.get(1), Matchers.sameInstance(versionResolver));
	assertThat(resolvers.get(2), Matchers.sameInstance(webjarsResolver));
	assertThat(resolvers.get(3), Matchers.sameInstance(pathResourceResolver));

	List<ResourceTransformer> transformers = handler.getResourceTransformers();
	assertThat(transformers, Matchers.hasSize(3));
	assertThat(transformers.get(0), Matchers.sameInstance(cachingTransformer));
	assertThat(transformers.get(1), Matchers.sameInstance(appCacheTransformer));
	assertThat(transformers.get(2), Matchers.sameInstance(cssLinkTransformer));
}
 
Example #28
Source File: ResourceHandlerRegistryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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()));
}
 
Example #29
Source File: ResourcesBeanDefinitionParser.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #30
Source File: WebCacheTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSetCacheabilityWhenCacheabilityIsSetToPrivate()
{
    // Given
    final CacheStrategy theCacheStrategy = CACHE_5_MINUTES;
    final Cacheability setCacheability = PRIVATE;

    // When
    when( systemSettingManager.getSystemSetting( CACHEABILITY ) ).thenReturn( setCacheability );
    final CacheControl actualCacheControl = webCache.getCacheControlFor( theCacheStrategy );

    // Then
    assertThat( actualCacheControl.toString().toLowerCase(), containsString( "private" ) );
}