View Javadoc
1   /*
2    * Copyright 2002-2014 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.web.servlet.resource;
18  
19  import java.io.IOException;
20  import javax.servlet.http.HttpServletRequest;
21  
22  import org.apache.commons.logging.Log;
23  import org.apache.commons.logging.LogFactory;
24  
25  import org.springframework.cache.Cache;
26  import org.springframework.cache.CacheManager;
27  import org.springframework.core.io.Resource;
28  import org.springframework.util.Assert;
29  
30  /**
31   * A {@link org.springframework.web.servlet.resource.ResourceTransformer} that checks a
32   * {@link org.springframework.cache.Cache} to see if a previously transformed resource
33   * exists in the cache and returns it if found, and otherwise delegates to the resolver
34   * chain and saves the result in the cache.
35   *
36   * @author Rossen Stoyanchev
37   * @since 4.1
38   */
39  public class CachingResourceTransformer implements ResourceTransformer {
40  
41  	private static final Log logger = LogFactory.getLog(CachingResourceTransformer.class);
42  
43  	private final Cache cache;
44  
45  	public CachingResourceTransformer(CacheManager cacheManager, String cacheName) {
46  		this(cacheManager.getCache(cacheName));
47  	}
48  
49  	public CachingResourceTransformer(Cache cache) {
50  		Assert.notNull(cache, "'cache' is required");
51  		this.cache = cache;
52  	}
53  
54  
55  	/**
56  	 * Return the configured {@code Cache}.
57  	 */
58  	public Cache getCache() {
59  		return this.cache;
60  	}
61  
62  	@Override
63  	public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain)
64  			throws IOException {
65  
66  		Resource transformed = this.cache.get(resource, Resource.class);
67  		if (transformed != null) {
68  			if (logger.isTraceEnabled()) {
69  				logger.trace("Found match");
70  			}
71  			return transformed;
72  		}
73  
74  		transformed = transformerChain.transform(request, resource);
75  
76  		if (logger.isTraceEnabled()) {
77  			logger.trace("Putting transformed resource in cache");
78  		}
79  		this.cache.put(resource, transformed);
80  
81  		return transformed;
82  	}
83  
84  }