2 * Copyright (C) 2007-2012 Argeo GmbH
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org
.argeo
.server
.backup
;
18 import java
.text
.DateFormat
;
19 import java
.util
.Date
;
20 import java
.util
.SortedMap
;
21 import java
.util
.TreeMap
;
23 import org
.apache
.commons
.logging
.Log
;
24 import org
.apache
.commons
.logging
.LogFactory
;
25 import org
.apache
.commons
.vfs
.FileObject
;
26 import org
.apache
.commons
.vfs
.FileSystemManager
;
27 import org
.apache
.commons
.vfs
.FileSystemOptions
;
28 import org
.apache
.commons
.vfs
.Selectors
;
29 import org
.argeo
.ArgeoException
;
30 import org
.joda
.time
.DateTime
;
31 import org
.joda
.time
.Period
;
33 /** Simple backup purge which keeps backups only for a given number of days */
34 public class SimpleBackupPurge
implements BackupPurge
{
35 private final static Log log
= LogFactory
.getLog(SimpleBackupPurge
.class);
37 private Integer daysKept
= 30;
40 public void purge(FileSystemManager fileSystemManager
, String base
,
41 String name
, DateFormat dateFormat
, FileSystemOptions opts
) {
43 DateTime nowDt
= new DateTime();
44 FileObject baseFo
= fileSystemManager
.resolveFile(
45 base
+ '/' + name
, opts
);
47 SortedMap
<DateTime
, FileObject
> toDelete
= new TreeMap
<DateTime
, FileObject
>();
50 // make sure base dir exists
51 baseFo
.createFolder();
53 // scan backups and list those which should be deleted
54 for (FileObject backupFo
: baseFo
.getChildren()) {
55 String backupName
= backupFo
.getName().getBaseName();
56 Date backupDate
= dateFormat
.parse(backupName
);
59 DateTime backupDt
= new DateTime(backupDate
.getTime());
60 Period sinceThen
= new Period(backupDt
, nowDt
);
61 int days
= sinceThen
.getDays();
62 // int days = sinceThen.getMinutes();
63 if (days
> daysKept
) {
64 toDelete
.put(backupDt
, backupFo
);
68 if (toDelete
.size() != 0 && toDelete
.size() == backupCount
) {
69 // all backups would be deleted
70 // but we want to keep at least one
71 DateTime lastBackupDt
= toDelete
.firstKey();
72 FileObject keptFo
= toDelete
.remove(lastBackupDt
);
73 log
.warn("Backup " + keptFo
74 + " kept although it is older than " + daysKept
79 for (FileObject backupFo
: toDelete
.values()) {
80 backupFo
.delete(Selectors
.SELECT_ALL
);
81 if (log
.isDebugEnabled())
82 log
.debug("Deleted backup " + backupFo
);
84 } catch (Exception e
) {
85 throw new ArgeoException("Could not purge previous backups", e
);