001/* 002 * Copyright 2002-2014 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.servlet.resource; 018 019import java.io.IOException; 020import javax.servlet.http.HttpServletRequest; 021 022import org.apache.commons.logging.Log; 023import org.apache.commons.logging.LogFactory; 024 025import org.springframework.cache.Cache; 026import org.springframework.cache.CacheManager; 027import org.springframework.core.io.Resource; 028import org.springframework.util.Assert; 029 030/** 031 * A {@link org.springframework.web.servlet.resource.ResourceTransformer} that checks a 032 * {@link org.springframework.cache.Cache} to see if a previously transformed resource 033 * exists in the cache and returns it if found, and otherwise delegates to the resolver 034 * chain and saves the result in the cache. 035 * 036 * @author Rossen Stoyanchev 037 * @since 4.1 038 */ 039public class CachingResourceTransformer implements ResourceTransformer { 040 041 private static final Log logger = LogFactory.getLog(CachingResourceTransformer.class); 042 043 private final Cache cache; 044 045 046 public CachingResourceTransformer(CacheManager cacheManager, String cacheName) { 047 this(cacheManager.getCache(cacheName)); 048 } 049 050 public CachingResourceTransformer(Cache cache) { 051 Assert.notNull(cache, "Cache is required"); 052 this.cache = cache; 053 } 054 055 056 /** 057 * Return the configured {@code Cache}. 058 */ 059 public Cache getCache() { 060 return this.cache; 061 } 062 063 064 @Override 065 public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain) 066 throws IOException { 067 068 Resource transformed = this.cache.get(resource, Resource.class); 069 if (transformed != null) { 070 if (logger.isTraceEnabled()) { 071 logger.trace("Found match: " + transformed); 072 } 073 return transformed; 074 } 075 076 transformed = transformerChain.transform(request, resource); 077 078 if (logger.isTraceEnabled()) { 079 logger.trace("Putting transformed resource in cache: " + transformed); 080 } 081 this.cache.put(resource, transformed); 082 083 return transformed; 084 } 085 086}