@Override public Mono<Resource> transform(ServerWebExchange exchange, Resource inputResource, ResourceTransformerChain chain) { return chain.transform(exchange, inputResource) .flatMap(outputResource -> { String name = outputResource.getFilename(); if (!this.fileExtension.equals(StringUtils.getFilenameExtension(name))) { return Mono.just(outputResource); } DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory(); Flux<DataBuffer> flux = DataBufferUtils .read(outputResource, bufferFactory, StreamUtils.BUFFER_SIZE); return DataBufferUtils.join(flux) .flatMap(dataBuffer -> { CharBuffer charBuffer = DEFAULT_CHARSET.decode(dataBuffer.asByteBuffer()); DataBufferUtils.release(dataBuffer); String content = charBuffer.toString(); return transform(content, outputResource, chain, exchange); }); }); }
@Test public void noTransformIfExtensionDoesNotMatch() { MockServerWebExchange exchange = MockServerWebExchange.from(get("/static/foo.css")); Resource expected = getResource("foo.css"); Resource actual = this.transformer.transform(exchange, expected, this.chain).block(TIMEOUT); assertSame(expected, actual); }
@Test public void syntaxErrorInManifest() { MockServerWebExchange exchange = MockServerWebExchange.from(get("/static/error.appcache")); Resource expected = getResource("error.appcache"); Resource actual = this.transformer.transform(exchange, expected, this.chain).block(TIMEOUT); assertEquals(expected, actual); }
@Test public void transformManifest() throws Exception { MockServerWebExchange exchange = MockServerWebExchange.from(get("/static/test.appcache")); Resource resource = getResource("test.appcache"); Resource actual = this.transformer.transform(exchange, resource, this.chain).block(TIMEOUT); assertNotNull(actual); byte[] bytes = FileCopyUtils.copyToByteArray(actual.getInputStream()); String content = new String(bytes, "UTF-8"); assertThat("should rewrite resource links", content, containsString("/static/foo-e36d2e05253c6c7085a91522ce43a0b4.css")); assertThat("should rewrite resource links", content, containsString("/static/bar-11e16cf79faee7ac698c805cf28248d2.css")); assertThat("should rewrite resource links", content, containsString("/static/js/bar-bd508c62235b832d960298ca6c0b7645.js")); assertThat("should not rewrite external resources", content, containsString("//example.org/style.css")); assertThat("should not rewrite external resources", content, containsString("http://example.org/image.png")); // Not the same hash as Spring MVC // Hash is computed from links, and not from the linked content assertThat("should generate fingerprint", content, containsString("# Hash: 8eefc904df3bd46537fa7bdbbc5ab9fb")); }