001/* 002 * Copyright 2002-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.reactive.resource; 018 019import reactor.core.publisher.Flux; 020import reactor.core.publisher.Mono; 021 022import org.springframework.core.io.Resource; 023import org.springframework.core.io.buffer.DataBuffer; 024import org.springframework.core.io.buffer.DataBufferFactory; 025import org.springframework.core.io.buffer.DataBufferUtils; 026import org.springframework.core.io.buffer.DefaultDataBufferFactory; 027import org.springframework.util.DigestUtils; 028import org.springframework.util.StreamUtils; 029 030/** 031 * A {@code VersionStrategy} that calculates an Hex MD5 hashes from the content 032 * of the resource and appends it to the file name, e.g. 033 * {@code "styles/main-e36d2e05253c6c7085a91522ce43a0b4.css"}. 034 * 035 * @author Rossen Stoyanchev 036 * @author Brian Clozel 037 * @since 5.0 038 * @see VersionResourceResolver 039 */ 040public class ContentVersionStrategy extends AbstractFileNameVersionStrategy { 041 042 private static final DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory(); 043 044 045 @Override 046 public Mono<String> getResourceVersion(Resource resource) { 047 Flux<DataBuffer> flux = 048 DataBufferUtils.read(resource, dataBufferFactory, StreamUtils.BUFFER_SIZE); 049 return DataBufferUtils.join(flux) 050 .map(buffer -> { 051 byte[] result = new byte[buffer.readableByteCount()]; 052 buffer.read(result); 053 DataBufferUtils.release(buffer); 054 return DigestUtils.md5DigestAsHex(result); 055 }); 056 } 057 058}