KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > meshcms > core > DirectoryCleaner


1 /*
2  * MeshCMS - A simple CMS based on SiteMesh
3  * Copyright (C) 2004-2007 Luciano Vernaschi
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  *
19  * You can contact the author at http://www.cromoteca.com
20  * and at info@cromoteca.com
21  */

22
23 package org.meshcms.core;
24
25 import java.io.*;
26 import org.meshcms.util.*;
27
28 /**
29  * Deletes old files from a directory.
30  */

31 public class DirectoryCleaner extends DirectoryParser {
32   private long currentTime;
33   private long maxLife;
34
35   /**
36    * Creates a repository cleaner for the given web application.
37    */

38   public DirectoryCleaner(File directory, long maxLifeMillis) {
39     setInitialDir(directory);
40     maxLife = maxLifeMillis;
41     setRecursive(true);
42     setDaemon(true);
43     setName("DirectoryCleaner for \"" + Utils.getFilePath(directory) + '"');
44     setPriority(Thread.MIN_PRIORITY);
45   }
46
47   protected boolean preProcess() {
48     currentTime = System.currentTimeMillis();
49     return true;
50   }
51
52   protected void postProcessDirectory(File file, Path path) {
53     // try to delete the folder: this will succeed if the folder is empty
54
// so we can get rid of useless folders.
55
file.delete();
56   }
57
58   protected void processFile(File file, Path path) {
59     String JavaDoc name = file.getName();
60
61     // process files whose file name is in the form
62
// something_lastmodified.extension
63
// for example _bak_admin_20060128093159.html is a backup of a page
64
int us = name.lastIndexOf('_');
65
66     if (us >= 0) {
67       try {
68         if (currentTime - WebUtils.numericDateFormatter.parse(name.substring(us + 1, us + 15)).getTime() > maxLife) {
69           Utils.forceDelete(file);
70         }
71
72         return;
73       } catch (Exception JavaDoc ex) {}
74     }
75
76     // other files are deleted when too old based on last modified date.
77
if (currentTime - file.lastModified() > (long) (maxLife * (1.0 + Math.random() / 2.0))) {
78       Utils.forceDelete(file);
79     }
80   }
81 }
82
Popular Tags