KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > util > TempFileProvider


1 /*
2  * Copyright (C) 2005 Alfresco, Inc.
3  *
4  * Licensed under the Mozilla Public License version 1.1
5  * with a permitted attribution clause. You may obtain a
6  * copy of the License at
7  *
8  * http://www.alfresco.org/legal/license.txt
9  *
10  * Unless required by applicable law or agreed to in writing,
11  * software distributed under the License is distributed on an
12  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13  * either express or implied. See the License for the specific
14  * language governing permissions and limitations under the
15  * License.
16  */

17 package org.alfresco.util;
18
19 import java.io.File JavaDoc;
20 import java.io.IOException JavaDoc;
21
22 import org.alfresco.error.AlfrescoRuntimeException;
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25 import org.quartz.Job;
26 import org.quartz.JobExecutionContext;
27 import org.quartz.JobExecutionException;
28
29 /**
30  * A helper class that provides temp files, providing a common point to clean
31  * them up.
32  *
33  * @author derekh
34  */

35 public class TempFileProvider
36 {
37     /** subdirectory in the temp directory where Alfresco temporary files will go */
38     public static final String JavaDoc ALFRESCO_TEMP_FILE_DIR = "Alfresco";
39
40     /** the system property key giving us the location of the temp directory */
41     public static final String JavaDoc SYSTEM_KEY_TEMP_DIR = "java.io.tmpdir";
42
43     private static final Log logger = LogFactory.getLog(TempFileProvider.class);
44
45     /**
46      * Static class only
47      */

48     private TempFileProvider()
49     {
50     }
51
52     /**
53      * @return Returns a temporary directory, i.e. <code>isDir == true</code>
54      */

55     public static File JavaDoc getTempDir()
56     {
57         // get the temp directory
58
String JavaDoc systemTempDirPath = System.getProperty(SYSTEM_KEY_TEMP_DIR);
59         if (systemTempDirPath == null)
60         {
61             throw new AlfrescoRuntimeException("System property not available: " + SYSTEM_KEY_TEMP_DIR);
62         }
63         File JavaDoc systemTempDir = new File JavaDoc(systemTempDirPath);
64 // if (!systemTempDir.isDirectory())
65
// {
66
// throw new AlfrescoRuntimeException("System property does not point to a directory: \n" +
67
// " property: " + SYSTEM_KEY_TEMP_DIR + "\n" +
68
// " value: " + systemTempDirPath);
69
// }
70
// append the Alfresco directory
71
File JavaDoc tempDir = new File JavaDoc(systemTempDir, ALFRESCO_TEMP_FILE_DIR);
72         // ensure that the temp directory exists
73
if (tempDir.exists())
74         {
75             // nothing to do
76
} else
77         {
78             // not there yet
79
if (!tempDir.mkdirs())
80             {
81                 throw new AlfrescoRuntimeException("Failed to create temp directory: " + tempDir);
82             }
83             if (logger.isDebugEnabled())
84             {
85                 logger.debug("Created temp directory: " + tempDir);
86             }
87         }
88         // done
89
return tempDir;
90     }
91
92     /**
93      * @return Returns a temp <code>File</code> that will be located in the
94      * <b>Alfresco</b> subdirectory of the default temp directory
95      *
96      * @see #ALFRESCO_TEMP_FILE_DIR
97      * @see File#createTempFile(java.lang.String, java.lang.String)
98      */

99     public static File JavaDoc createTempFile(String JavaDoc prefix, String JavaDoc suffix)
100     {
101         File JavaDoc tempDir = TempFileProvider.getTempDir();
102         // we have the directory we want to use
103
return createTempFile(prefix, suffix, tempDir);
104     }
105
106     /**
107      * @return Returns a temp <code>File</code> that will be located in the
108      * given directory
109      *
110      * @see #ALFRESCO_TEMP_FILE_DIR
111      * @see File#createTempFile(java.lang.String, java.lang.String)
112      */

113     public static File JavaDoc createTempFile(String JavaDoc prefix, String JavaDoc suffix, File JavaDoc directory)
114     {
115         try
116         {
117             File JavaDoc tempFile = File.createTempFile(prefix, suffix, directory);
118             return tempFile;
119         } catch (IOException JavaDoc e)
120         {
121             throw new AlfrescoRuntimeException("Failed to created temp file: \n" +
122                     " prefix: " + prefix + "\n"
123                     + " suffix: " + suffix + "\n" +
124                     " directory: " + directory,
125                     e);
126         }
127     }
128
129     /**
130      * Cleans up <b>all</b> Alfresco temporary files that are older than the
131      * given number of hours. Subdirectories are emptied as well and all directories
132      * below the primary temporary subdirectory are removed.
133      * <p>
134      * The job data must include a property <tt>protectHours</tt>, which is the
135      * number of hours to protect a temporary file from deletion since its last
136      * modification.
137      *
138      * @author Derek Hulley
139      */

140     public static class TempFileCleanerJob implements Job
141     {
142         public static final String JavaDoc KEY_PROTECT_HOURS = "protectHours";
143
144         /**
145          * Gets a list of all files in the {@link TempFileProvider#ALFRESCO_TEMP_FILE_DIR temp directory}
146          * and deletes all those that are older than the given number of hours.
147          */

148         public void execute(JobExecutionContext context) throws JobExecutionException
149         {
150             // get the number of hours to protect the temp files
151
String JavaDoc strProtectHours = (String JavaDoc) context.getJobDetail().getJobDataMap().get(KEY_PROTECT_HOURS);
152             if (strProtectHours == null)
153             {
154                 throw new JobExecutionException("Missing job data: " + KEY_PROTECT_HOURS);
155             }
156             int protectHours = -1;
157             try
158             {
159                 protectHours = Integer.parseInt(strProtectHours);
160             }
161             catch (NumberFormatException JavaDoc e)
162             {
163                 throw new JobExecutionException("Invalid job data " + KEY_PROTECT_HOURS + ": " + strProtectHours);
164             }
165             if (protectHours < 0 || protectHours > 8760)
166             {
167                 throw new JobExecutionException("Hours to protect temp files must be 0 <= x <= 8760");
168             }
169
170             long now = System.currentTimeMillis();
171             long aFewHoursBack = now - (3600L * 1000L * protectHours);
172             
173             File JavaDoc tempDir = TempFileProvider.getTempDir();
174             int count = removeFiles(tempDir, aFewHoursBack, false); // don't delete this directory
175
// done
176
if (logger.isDebugEnabled())
177             {
178                 logger.debug("Removed " + count + " files from temp directory: " + tempDir);
179             }
180         }
181         
182         /**
183          * Removes all temporary files created before the given time.
184          * <p>
185          * The delete will cascade down through directories as well.
186          *
187          * @param removeBefore only remove files created <b>before</b> this time
188          * @return Returns the number of files removed
189          */

190         public static int removeFiles(long removeBefore)
191         {
192             File JavaDoc tempDir = TempFileProvider.getTempDir();
193             return removeFiles(tempDir, removeBefore, false);
194         }
195         
196         /**
197          * @param directory the directory to clean out - the directory will optionally be removed
198          * @param removeBefore only remove files created <b>before</b> this time
199          * @param removeDir true if the directory must be removed as well, otherwise false
200          * @return Returns the number of files removed
201          */

202         private static int removeFiles(File JavaDoc directory, long removeBefore, boolean removeDir)
203         {
204             if (!directory.isDirectory())
205             {
206                 throw new IllegalArgumentException JavaDoc("Expected a directory to clear: " + directory);
207             }
208             // check if there is anything to to
209
if (!directory.exists())
210             {
211                 return 0;
212             }
213             // list all files
214
File JavaDoc[] files = directory.listFiles();
215             int count = 0;
216             for (File JavaDoc file : files)
217             {
218                 if (file.isDirectory())
219                 {
220                     // enter subdirectory and clean it out and remove it
221
removeFiles(file, removeBefore, true);
222                 }
223                 else
224                 {
225                     // it is a file - check the created time
226
if (file.lastModified() > removeBefore)
227                     {
228                         // file is not old enough
229
continue;
230                     }
231                     // it is a file - attempt a delete
232
try
233                     {
234                         file.delete();
235                         count++;
236                     }
237                     catch (Throwable JavaDoc e)
238                     {
239                         logger.info("Failed to remove temp file: " + file);
240                     }
241                 }
242             }
243             // must we delete the directory we are in?
244
if (removeDir && directory.listFiles().length == 0)
245             {
246                 // the directory must be removed and is empty
247
try
248                 {
249                     directory.delete();
250                 }
251                 catch (Throwable JavaDoc e)
252                 {
253                     logger.info("Failed to remove temp directory: " + directory);
254                 }
255             }
256             // done
257
return count;
258         }
259     }
260 }
261
Popular Tags