KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jivesoftware > util > log > output > io > rotate > RevolvingFileStrategy


1 /*
2  * Copyright (C) The Apache Software Foundation. All rights reserved.
3  *
4  * This software is published under the terms of the Apache Software License
5  * version 1.1, a copy of which has been included with this distribution in
6  * the LICENSE file.
7  */

8 package org.jivesoftware.util.log.output.io.rotate;
9
10 import java.io.File JavaDoc;
11
12 /**
13  * strategy for naming log files based on appending revolving suffix.
14  * <p/>
15  * Heavily odified by Bruce Ritchie (Jive Software) to rotate along
16  * the following strategy:
17  * <p/>
18  * current log file will always be the base File name
19  * the next oldest file will be the _1 file
20  * the next oldest file will be the _2 file
21  * etc.
22  *
23  * @author <a HREF="mailto:bh22351@i-one.at">Bernhard Huber</a>
24  */

25 public class RevolvingFileStrategy implements FileStrategy {
26
27     ///max file prefix count
28
private int maxCount;
29
30     ///the base file name.
31
private String JavaDoc baseFileName;
32
33     public RevolvingFileStrategy(final String JavaDoc baseFileName, final int maxCount) {
34
35         this.baseFileName = baseFileName;
36         this.maxCount = maxCount;
37
38         if (-1 == this.maxCount) {
39             this.maxCount = 5;
40         }
41     }
42
43     public File JavaDoc currentFile() {
44         return new File JavaDoc(baseFileName);
45     }
46
47     /**
48      * Calculate the real file name from the base filename.
49      *
50      * @return File the calculated file name
51      */

52     public File JavaDoc nextFile() {
53         // go through all the possible filenames and delete/rename as necessary
54
for (int i = maxCount; i > 0; i--) {
55             File JavaDoc test = new File JavaDoc(baseFileName.substring(0, baseFileName.lastIndexOf('.')) +
56                     "_" + i + baseFileName.substring(baseFileName.lastIndexOf('.')));
57
58             if (i == maxCount && test.exists()) {
59                 test.delete();
60             }
61
62             if (test.exists()) {
63                 File JavaDoc r = new File JavaDoc(baseFileName.substring(0, baseFileName.lastIndexOf('.')) +
64                         "_" + (i + 1) + baseFileName.substring(baseFileName.lastIndexOf('.')));
65                 test.renameTo(r);
66             }
67         }
68
69         // rename the current file
70
File JavaDoc current = new File JavaDoc(baseFileName);
71         File JavaDoc first = new File JavaDoc(baseFileName.substring(0, baseFileName.lastIndexOf('.')) +
72                 "_1" + baseFileName.substring(baseFileName.lastIndexOf('.')));
73         current.renameTo(first);
74
75         // return the base filename
76
return new File JavaDoc(baseFileName);
77     }
78 }
79
80
Popular Tags