001/* 002 * Copyright 2010 Anyware Services 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 * http://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 */ 016package org.ametys.site; 017 018import java.io.File; 019import java.io.FilenameFilter; 020import java.util.Map; 021 022import org.apache.avalon.framework.parameters.Parameters; 023import org.apache.avalon.framework.service.ServiceException; 024import org.apache.avalon.framework.service.ServiceManager; 025import org.apache.avalon.framework.thread.ThreadSafe; 026import org.apache.cocoon.acting.ServiceableAction; 027import org.apache.cocoon.environment.Redirector; 028import org.apache.commons.io.FileUtils; 029import org.slf4j.Logger; 030import org.slf4j.LoggerFactory; 031 032/** 033 * Invalidates cached data for a given site. 034 */ 035public class InvalidateImagesAction extends ServiceableAction implements ThreadSafe 036{ 037 private Logger _logger = LoggerFactory.getLogger("site.cache.log"); 038 private CacheAccessManager _cacheAccess; 039 040 @Override 041 public void service(ServiceManager sManager) throws ServiceException 042 { 043 super.service(sManager); 044 _cacheAccess = (CacheAccessManager) sManager.lookup(CacheAccessManager.ROLE); 045 } 046 047 @Override 048 public Map act(Redirector redirector, org.apache.cocoon.environment.SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception 049 { 050 String path = parameters.getParameter("path"); 051 052 File root = SiteCacheHelper.getRootCache(); 053 054 // files to delete are like path/to/file_100x200.jpg 055 056 int j = path.lastIndexOf('/'); 057 String folder = j != -1 ? path.substring(0, j) : ""; 058 final String fileName = j != -1 ? path.substring(j + 1) : path; 059 060 int i = fileName.lastIndexOf('.'); 061 final String ext = i != -1 ? fileName.substring(i) : ""; 062 final String prefix = i != -1 ? fileName.substring(0, i) : fileName; 063 064 File parentFolder = new File(root, folder); 065 066 File[] files = parentFolder.listFiles(new FilenameFilter() 067 { 068 @Override 069 public boolean accept(File dir, String name) 070 { 071 return name.matches("^" + prefix + "_[0-9]+x[0-9]+" + ext + "$"); 072 } 073 }); 074 075 if (files != null) 076 { 077 for (File file : files) 078 { 079 FileUtils.forceDelete(file); 080 081 _logger.info("Invalidate cache for file '" + file + "'"); 082 } 083 } 084 085 _cacheAccess.resetPage(path); 086 087 return EMPTY_MAP; 088 } 089}