A
download FilePersistentStore.java
Language: Java
LOC: 239
Project Info
Enhydra Server(enhydra)
Server: ObjectWeb Forge
Type: cvs
...s\Core\src\com\lutris\util\
   Base64Encoder.java
   BMByteSearch.java
   BMByteSearchStream.java
   BytesToString.java
   ChainedError.java
   ChainedException.java
   ...edRuntimeException.java
   ChainedThrowable.java
   ChainedThrowableUtil.java
   CircularQueue.java
   Convert.java
   Currency.java
   ExceptionUtils.java
   FilePersistentStore.java
   HexEncoder.java
   HtmlEncoder.java
   JavaScriptEncoder.java
   JavaVersion.java
   LRUCache.java
   ...utStreamEventQueue.java
   ...eamEventQueueEntry.java
   OutputStreamHub.java
   PersistentStore.java
   ...tentStoreException.java
   QuotedString.java
   StringEnum.java
   TmpDir.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
/*
 * Enhydra Java Application Server Project
 * 
 * The contents of this file are subject to the Enhydra Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License on
 * the Enhydra web site ( http://www.enhydra.org/ ).
 * 
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See 
 * the License for the specific terms governing rights and limitations
 * under the License.
 * 
 * The Initial Developer of the Enhydra Application Server is Lutris
 * Technologies, Inc. The Enhydra Application Server and portions created
 * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
 * All Rights Reserved.
 * 
 * Contributor(s):
 * 
 * $Id: FilePersistentStore.java,v 1.15 2005/06/13 09:26:06 draganr Exp $
 */

package com.lutris.util;
import java.io.*;
import java.util.NoSuchElementException;
import java.lang.reflect.Constructor;

/**
 * File system implementation of PersistentStore.
 *
 * @author Kyle Clark
 */
public class FilePersistentStore implements PersistentStore {

    private final String DEFAULT_DIR_PROPERTY = "user.dir";
    private final String FILE_SEPARATOR_PROPERTY = "file.separator";
    private final String SERIAL_SUFFIX = ".srl"; // suffix for serialized objects.


    /**
     * Inner class that implements keys enumeration for this object.
     */
    private class FilePersistentStoreKeys implements java.util.Enumeration {

        private String [] keys;
        private int idx = 0;

        /**
         * Constructor.
         */
        FilePersistentStoreKeys() {
            keys = new String[0];
        }

        /**
         * Constructor.
         *
         * @param keys
         *   The keys.
         */
        FilePersistentStoreKeys(String [] keys) {
            this.keys = keys;
        }


        /**
         * Tests if this enumeration contains more keys.
         *
         * @return
         *   True if it does contain more elements, false otherwise.
         */
        public boolean hasMoreElements() {
            return (idx < keys.length);
        }

        /**
         * Returns the next key of this enumeration.
         *
         * @return
         *   The next key.
         * @exception java.util.NoSuchElementException
         *   if there are no more keys in this enumeration.
         */
        public Object nextElement() throws NoSuchElementException {
            if (!hasMoreElements())
                throw new java.util.NoSuchElementException("no more elements");

            String k = keys[idx];
            idx++;
            return k;
        }
    }

    /**
     * Inner class that implements a filename filter.
     */
    private class FileStoreFilter implements FilenameFilter {
        private String suffix = "";
        FileStoreFilter(String suffix) {
            this.suffix = suffix;
        }
        public boolean accept(File dir, String name) {
            return name.endsWith(suffix);
        }
    }


    /**
     * Path separator used by operating system.
     */
    private String fileSeparator;

    /**
     * Directory (pathname) where objects are to be
     * stored/retrieved.  The default is the
     * current directory.
     */
    private String storeDirectory;

    /**
     * The class loader used when reading in serialized data.
     */
    private Constructor objectInputStreamConstructor;

    /**
     * The loader that should be used to load serialized data.
     */
    private ClassLoader loader;

    /**
     * Public constructor.  Sets the <code>storeDirectory</code>,
     * the directory (repository) where objects
     * are stored/retreived to <code>/tmp</code>.
     *
     * @exception java.io.IOException
     *   If <code>/tmp</code>
     *   already exists but is not a directory.  Or if 
     *   <code>/tmp</code> does not exist and could
     *   not be created.
     * @exception java.lang.SecurityException
     *   If a security
     *   manager is running but <code>/tmp</code>
     *   could not be created due to inappropriate
     *   permissions.
     */
    public FilePersistentStore()
        throws PersistentStoreException {
        init(null, null);
    }

    /**
     * Public constructor.  Sets the <code>storeDirectory</code>,
     * the directory (repository) where objects
     * are stored/retreived to <code>/tmp</code>.
     *
     * @param loader the class loader to use when reading
     *   in serialized data.
     * @exception java.io.IOException
     *   If <code>/tmp</code>
     *   already exists but is not a directory.  Or if 
     *   <code>/tmp</code> does not exist and could
     *   not be created.
     * @exception java.lang.SecurityException
     *   If a security
     *   manager is running but <code>/tmp</code>
     *   could not be created due to inappropriate
     *   permissions.
     */
    public FilePersistentStore(ClassLoader loader)
        throws IOException, SecurityException, PersistentStoreException {
        init(null, loader);
    }

    /**
     * Public constructor that allows one to specify
     * the directory (repository)
     * where objects are stored/retrieved.
     * If the specified directory doesn't exist then it is created.
     *
     * @param storeDirectory
     *   The repository (directory) for storing and retrieving objects.
     * @exception java.io.IOException
     *   If <code>storeDirectory</code>
     *   already exists but is not a directory.  Or if the
     *   <code>storeDirectory</code> does not exist and could
     *   not be created.
     * @exception java.lang.SecurityException
     *   If a security
     *   manager is running but <code>storeDirectory</code>
     *   could not be created due to inappropriate
     *   permissions.
     */
    public FilePersistentStore(String storeDirectory)
        throws PersistentStoreException {
        init(storeDirectory, null);
    }

    /**
     * Public constructor that allows one to specify
     * the directory (repository)
     * where objects are stored/retrieved.
     * If the specified directory doesn't exist then it is created.
     *
     * @param storeDirectory
     *   The repository (directory) for storing and retrieving objects.
     * @exception java.io.IOException
     *   If <code>storeDirectory</code>
     *   already exists but is not a directory.  Or if the
     *   <code>storeDirectory</code> does not exist and could
     *   not be created.
     * @exception java.lang.SecurityException
     *   If a security
     *   manager is running but <code>storeDirectory</code>
     *   could not be created due to inappropriate
     *   permissions.
     */
    public FilePersistentStore(String storeDirectory, ClassLoader loader)
        throws PersistentStoreException {
        init(storeDirectory, loader);
    }

    /**
     * Gets a reference to the object input stream constructor.
     *
     * @param storeDirectory
     *   The repository (directory) for storing and retrieving objects.
     * @exception java.io.IOException
     *   If <code>storeDirectory</code>
     *   already exists but is not a directory.  Or if the
     *   <code>storeDirectory</code> does not exist and could
     *   not be created.
     * @exception java.lang.SecurityException
     *   If a security
     *   manager is running but <code>storeDirectory</code>
     *   could not be created due to inappropriate
     *   permissions.
     */
    private void init(String storeDirectory, ClassLoader loader)
        throws PersistentStoreException {
        try {
            this.loader = loader;
            fileSeparator = System.getProperty(FILE_SEPARATOR_PROPERTY);
            if (storeDirectory == null) {
                setStoreDirectory(fileSeparator + "tmp");
            } else {
                setStoreDirectory(storeDirectory);
            }
        } catch (Exception e) {
            throw new PersistentStoreException(e);
        }
    }

    /**
     * Sets the location (directory) from where objects are
     * retrieved/archived.  If the specified directory doesn't
     * exist then it is created.
     *
     * @param storeDirectory The repository (directory) for
     *   storing and retrieving objects.
     * @exception java.io.IOException If <code>storeDirectory</code>
     *   already exists but is not a directory.  Or if the
     *   <code>storeDirectory</code> does not exist and could
     *   not be created.
     * @exception java.lang.SecurityException If a security
     *   manager is running but <code>storeDirectory</code>
     *   could not be created because due to inappropriate
     *   permissions.
     */
    private void setStoreDirectory(String storeDirectory)
        throws IOException, SecurityException {
        File f = new File(storeDirectory);
        if (f.exists() && !f.isDirectory())
            throw new IOException(storeDirectory +
                                  " already exists but is not a directory.");
        if (!f.exists() && !f.mkdirs())
            throw new IOException("Unable to create directory " +
                                  storeDirectory);
        this.storeDirectory = storeDirectory;
    }


    /**
     * Returns the location where objects are
     * stored/retrieved.
     *
     * @return The directory (repository) where 
     *   objects are stored/retrieved.
     */
    public String getStoreDirectory() {
        return this.storeDirectory;
    }

    /**
     * Method that calculates the absolute path to the
     * stored object.
     *
     * @param key The user for whom the archive name
     *   is calculated.
     * @return The filename associated w/ key.
     */
    private String filename(String key) {
        return storeDirectory + fileSeparator + convertKeyToHex(key) + SERIAL_SUFFIX;
    }

    /**
     * Hexadecimal characters corresponding to each half byte value.
     */
    private static final char[] HexChars = {
	'0', '1', '2', '3', '4', '5', '6', '7',
	'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };


    /**
     * Converts an arbitrary string to ASCII hexadecimal string
     * form, with two hex characters corresponding to each byte.  The
     * length of the resultant string in characters will be twice the
     * length of the original string.
     * 
     * @param key
     *   The string to convert to ASCII hex form.
     * @return
     *   An ASCII hexadecimal numeric string representing the
     * 	 original string.
     */
    private String convertKeyToHex(String key) {
        byte [] bytes = key.getBytes();
	StringBuffer sb = new StringBuffer();
	int i;
	for (i=0; i < bytes.length; i++) {
	    sb.append(HexChars[(bytes[i] >> 4) & 0xf]);
	    sb.append(HexChars[bytes[i] & 0xf]);
	}
	return new String(sb);
    }

    /**
     * Converts an arbitrary ASCII hexadecimal string,
     * with two hex characters corresponding to each byte, into
     * a string.
     * 
     * @param hex
     *   The hexadecimal encoded string to convert.
     * @return
     *   The original string.
     */
    private String convertHexToKey(String hex) {
        char [] chars = new char[hex.length()];
        hex.getChars(0, hex.length(), chars, 0);
	StringBuffer sb = new StringBuffer();
	for (int i=0; i<chars.length/2; i++) {
            int idx = 2*i;
            sb.append((char)((hexCharToByte(chars[idx])<<4) +
                             (hexCharToByte(chars[idx+1]))));
	}
	return new String(sb);
    }

    /**
     * Method that maps a hexadecimal character to a byte value.
     *
     * @param c
     *   The character to map.
     */
    private byte hexCharToByte(char c) {
        switch (c) {
        case '1':
            return (byte)1;
        case '2':
            return (byte)2;
        case '3':
            return (byte)3;
        case '4':
            return (byte)4;
        case '5':
            return (byte)5;
        case '6':
            return (byte)6;
        case '7':
            return (byte)7;
        case '8':
            return (byte)8;
        case '9':
            return (byte)9;
        case 'a':
        case 'A':
            return (byte)10;
        case 'b':
        case 'B':
            return (byte)11;
        case 'c':
        case 'C':
            return (byte)12;
        case 'd':
        case 'D':
            return (byte)13;
        case 'e':
        case 'E':
            return (byte)14;
        case 'f':
        case 'F':
            return (byte)15;
        case '0':
        default:
            return (byte)0;
        }
    }

    /**
     * Method to store and object (persistent).
     *
     * @param key
     *   The key by which to identify the stored object.
     *   The key name has some system constraints.  Its length
     *   must not exceed half the maximum file name length on
     *   the system.  If it does, an exception is thrown.
     * @param obj
     *   The serializable object to store.
     * @exception PersistentStoreException
     *   if the object cannot cannot be stored.
     */
    public void store(String key, Serializable obj)
        throws PersistentStoreException {
        if (exists(key))
            throw new
                PersistentStoreException("An object is already stored as " +
                                         key);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filename(key));
            ObjectOutputStream objOut = new ObjectOutputStream(out);
            objOut.writeObject(obj);
            objOut.flush();
            out.close();
        }
        catch (Exception ex) {
            if (out != null) {
                try { out.close(); } catch (Exception e) {}
            }
            delete(key);
            throw new PersistentStoreException(ex);
        }
    }
    

    /**
     * Method to retrieve a stored object.
     *
     * @param key
     *   The key of the object that is to be retreived.
     * @return
     *   The stored object.  If an object is not stored under key,
     *   then <code>null</code> is returned.
     * @see #remove
     * @exception PersistentStoreException
     *   if the object could not be retrieved.
     */
    public Object retrieve(String key) throws PersistentStoreException {
        if (!exists(key)) {
            return null;
        }
        try {
            FileInputStream in = new FileInputStream(filename(key));
            LoaderObjectInputStream objIn = new LoaderObjectInputStream(in, loader);
            Object obj = objIn.readObject();
            objIn.close();
            return obj;
        }
        catch (Exception ex) {
            throw new PersistentStoreException(ex);
        }
    }


    /**
     * Method to query if an an object is stored.
     *
     * @param key
     *   The key by which to identify the stored object.
     * @return
     *   True if an object is stored under key.
     * @exception PersistentStoreException
     *   If The exsitence of object could not be determined.
     */
    public boolean exists(String key)
        throws PersistentStoreException {
        File f = new File(filename(key));
        return f.exists();
    }


    /**
     * Method to simultaneously retrieve and remove an
     * object from persistent store.  If an object is not
     * stored under key, then null is returned.
     *
     * @param key
     *   The key by which to identify the stored object
     *   that is to be removed.
     * @return
     *   The object that has been removed.
     * @exception PersistentStoreException
     *   If the object could not be retrieved before being deleted.
     */
    public Object remove(String key) throws PersistentStoreException {
        Object obj = retrieve(key);
        delete(key);
        return obj;
    }


    /**
     * Method to delete a a key.  Any objects stored under
     * key are also removed.  If key is not defined, then
     * this method does nothing.
     *
     * @param key
     *   The key to remove.
     */
    public void delete(String key) {
        File f = new File(filename(key));
        if (f.exists()) {
            f.delete();
        }
    }


    /**
     * Method that returns an enumration of the keys
     * of this persistent store.
     *
     * @exception com.lutris.util.PersistentStoreException
     *   if the enumeration could not be determined.
     */
    public java.util.Enumeration keys() throws PersistentStoreException {
        File dir = new File(storeDirectory);
        FileStoreFilter filter = new FileStoreFilter(SERIAL_SUFFIX);
        String [] hexKeys = dir.list(filter);
        String [] keys = new String [hexKeys.length];
        for (int idx=0; idx<hexKeys.length; idx++) {
            // Strip off the suffix
            int suffixIdx = hexKeys[idx].lastIndexOf(SERIAL_SUFFIX);
            if (suffixIdx >= 0)
                hexKeys[idx] = hexKeys[idx].substring(0, suffixIdx);
            // Get the real key name
            keys[idx] = convertHexToKey(hexKeys[idx]);
        }

        return new FilePersistentStoreKeys(keys);
    }

}

// Internal class that can load objects with the load we specify.
class LoaderObjectInputStream extends ObjectInputStream {

    private ClassLoader loader;

    public LoaderObjectInputStream(InputStream in, ClassLoader loader)
	throws IOException, StreamCorruptedException {
        super(in);
        this.loader = loader;
    }

    /**
     * Subclasses may implement this method to allow classes to be
     * fetched from an alternate source. 
     *
     * The corresponding method in ObjectOutputStream is
     * annotateClass.  This method will be invoked only once for each
     * unique class in the stream.  This method can be implemented by
     * subclasses to use an alternate loading mechanism but must
     * return a Class object.  Once returned, the serialVersionUID of the
     * class is compared to the serialVersionUID of the serialized class.
     * If there is a mismatch, the deserialization fails and an exception
     * is raised. <p>
     *
     * By default the class name is resolved relative to the class
     * that called readObject. <p>
     *
     * @exception ClassNotFoundException If class of
     * a serialized object cannot be found.
     * @since     JDK1.1
     */
    protected Class resolveClass(ObjectStreamClass v)
	throws IOException, ClassNotFoundException {
        if (loader != null) {
            return loader.loadClass(v.getName());
        } else {
            return super.resolveClass(v);
        }
    }

}

About Koders | Resources | Downloads | Support | Black Duck | Terms of Service | DMCA | Privacy Policy | Contact Us