1
2
3
4
5
6
7
8
9
10
11 package org.astrogrid.common.namegen;
12
13
14 import org.apache.commons.logging.Log;
15 import org.apache.commons.logging.LogFactory;
16 import org.apache.commons.transaction.file.FileSequence;
17 import org.apache.commons.transaction.file.ResourceManagerException;
18
19 import java.io.File;
20
21 /*** Implementation of name generator using the FileSequence from commons-transactions -
22 * provides a stream of unique identifiers, in a thread-safe, persistent manner.
23 * @author Noel Winstanley nw@jb.man.ac.uk 24-Feb-2005
24 */
25 public class FileNameGen implements NameGen {
26 /***
27 * Commons Logger for this class
28 */
29 private static final Log logger = LogFactory.getLog(FileNameGen.class);
30
31 protected final FileSequence seq;
32 protected final String sequenceName;
33 /*** Construct a new FileNameGen
34 * @throws ResourceManagerException
35 *
36 */
37 public FileNameGen(File workingDir, String sequenceName) throws ResourceManagerException, IllegalArgumentException {
38 super();
39 this.sequenceName = sequenceName;
40 verifyWorkingDir(workingDir);
41 seq = new FileSequence(workingDir.toString(),new CommonsLoggingFacade(logger));
42
43 if (!seq.exists(sequenceName)) {
44 seq.create(sequenceName,100L);
45 }
46 }
47 /*** Verify that working directory exists, is readable, etc.
48 * will create working directory if it is missing, and is able to.
49 * @param workingDir
50 * @throws IllegalArgumentException
51 */
52 private final void verifyWorkingDir(File workingDir) throws IllegalArgumentException {
53 if (! workingDir.exists()) {
54 logger.info("creating storage for id generator");
55 workingDir.mkdirs();
56 }
57 if (!workingDir.exists()) {
58 String msg = "Base directory for id generator does not exist, and cannot be created";
59 logger.fatal(msg);
60 throw new IllegalArgumentException(msg);
61 }
62 if (!workingDir.isDirectory()) {
63 String msg = "Base for id generator must be a directory";
64 logger.fatal(msg);
65 throw new IllegalArgumentException(msg);
66 }
67 if (! (workingDir.canRead() && workingDir.canWrite())) {
68 String msg = "Must be able to read and write to base directory for id generator";
69 logger.fatal(msg);
70 throw new IllegalArgumentException(msg);
71 }
72
73
74 logger.info("storage locations seem ok");
75 }
76
77
78
79 /***
80 * @throws FileManagerFault
81 * @throws ResourceManagerException
82 * @throws ResourceManagerException
83 * @see org.astrogrid.common.namegen.NameGen#next()
84 */
85 public String next() throws ResourceManagerException {
86 return Long.toString(seq.nextSequenceValueBottom(sequenceName,1L));
87
88 }
89
90 public String toString() {
91 StringBuffer buffer = new StringBuffer();
92 buffer.append("[FileNameGen:");
93 buffer.append(" seq: ");
94 buffer.append(seq);
95 buffer.append("]");
96 return buffer.toString();
97 }
98 }
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125