Debian Codegraph @

jdbm1/src/main/java/jdbm/recman/BaseRecordManager.java

raw
1 /**
2 * JDBM LICENSE v1.00
3 *
4 * Redistribution and use of this software and associated documentation
5 * ("Software"), with or without modification, are permitted provided
6 * that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain copyright
9 * statements and notices. Redistributions must also contain a
10 * copy of this document.
11 *
12 * 2. Redistributions in binary form must reproduce the
13 * above copyright notice, this list of conditions and the
14 * following disclaimer in the documentation and/or other
15 * materials provided with the distribution.
16 *
17 * 3. The name "JDBM" must not be used to endorse or promote
18 * products derived from this Software without prior written
19 * permission of Cees de Groot. For written permission,
20 * please contact [email protected].
21 *
22 * 4. Products derived from this Software may not be called "JDBM"
23 * nor may "JDBM" appear in their names without prior written
24 * permission of Cees de Groot.
25 *
26 * 5. Due credit should be given to the JDBM Project
27 * (http://jdbm.sourceforge.net/).
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE JDBM PROJECT AND CONTRIBUTORS
30 * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
31 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
32 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
33 * CEES DE GROOT OR ANY CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
34 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
35 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
36 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
38 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
40 * OF THE POSSIBILITY OF SUCH DAMAGE.
41 *
42 * Copyright 2000 (C) Cees de Groot. All Rights Reserved.
43 * Copyright 2000-2001 (C) Alex Boisvert. All Rights Reserved.
44 * Contributions are Copyright (C) 2000 by their associated contributors.
45 *
46 * $Id: BaseRecordManager.java,v 1.8 2005/06/25 23:12:32 doomdark Exp $
47 */
48
49 package jdbm.recman;
50
51
52 import java.io.IOException;
53 import java.util.HashMap;
54 import java.util.Map;
55
56 import jdbm.I18n;
57 import jdbm.RecordManager;
58 import jdbm.helper.DefaultSerializer;
59 import jdbm.helper.Serializer;
60
61
62 /**
63 * This class manages records, which are uninterpreted blobs of data. The
64 * set of operations is simple and straightforward: you communicate with
65 * the class using long "rowids" and byte[] data blocks. Rowids are returned
66 * on inserts and you can stash them away someplace safe to be able to get
67 * back to them. Data blocks can be as long as you wish, and may have
68 * lengths different from the original when updating.
69 * <p>
70 * Operations are synchronized, so that only one of them will happen
71 * concurrently even if you hammer away from multiple threads. Operations
72 * are made atomic by keeping a transaction log which is recovered after
73 * a crash, so the operations specified by this interface all have ACID
74 * properties.
75 * <p>
76 * You identify a file by just the name. The package attaches <tt>.db</tt>
77 * for the database file, and <tt>.lg</tt> for the transaction log. The
78 * transaction log is synchronized regularly and then restarted, so don't
79 * worry if you see the size going up and down.
80 *
81 * @author <a href="mailto:[email protected]">Alex Boisvert</a>
82 * @author <a href="[email protected]">Cees de Groot</a>
83 */
84 public final class BaseRecordManager
85 implements RecordManager
86 {
87
88 /** Underlying record recordFile. */
89 private RecordFile recordFile;
90
91 /** Physical row identifier manager. */
92 private PhysicalRowIdManager physMgr;
93
94 /** Logical to Physical row identifier manager. */
95 private LogicalRowIdManager logMgr;
96
97 /** Page manager. */
98 private PageManager pageMgr;
99
100 /** Reserved slot for name directory. */
101 public static final int NAME_DIRECTORY_ROOT = 0;
102
103 /** Static debugging flag */
104 public static final boolean DEBUG = false;
105
106 /**
107 * Directory of named JDBMHashtables. This directory is a persistent
108 * directory, stored as a Hashtable. It can be retrieved by using
109 * the NAME_DIRECTORY_ROOT.
110 */
111 private Map<String, Long> nameDirectory;
112
113
114 /**
115 * Creates a record manager for the indicated file
116 *
117 * @throws IOException when the file cannot be opened or is not
118 * a valid file content-wise.
119 */
120 public BaseRecordManager( String filename ) throws IOException
121 {
122 recordFile = new RecordFile( filename );
123 pageMgr = new PageManager( recordFile );
124 physMgr = new PhysicalRowIdManager( pageMgr );
125 logMgr = new LogicalRowIdManager( pageMgr );
126 }
127
128
129 /**
130 * Get the underlying Transaction Manager
131 */
132 public synchronized TransactionManager getTransactionManager() throws IOException
133 {
134 checkIfClosed();
135 return recordFile.getTxnMgr();
136 }
137
138
139 /**
140 * Switches off transactions for the record manager. This means
141 * that a) a transaction log is not kept, and b) writes aren't
142 * synch'ed after every update. This is useful when batch inserting
143 * into a new database.
144 * <p>
145 * Only call this method directly after opening the file, otherwise
146 * the results will be undefined.
147 */
148 public synchronized void disableTransactions()
149 {
150 checkIfClosed();
151 recordFile.disableTransactions();
152 }
153
154
155 /**
156 * Closes the record manager.
157 *
158 * @throws IOException when one of the underlying I/O operations fails.
159 */
160 public synchronized void close() throws IOException
161 {
162 checkIfClosed();
163
164 pageMgr.close();
165 pageMgr = null;
166
167 recordFile.close();
168 recordFile = null;
169 }
170
171
172 /**
173 * Inserts a new record using standard java object serialization.
174 *
175 * @param obj the object for the new record.
176 * @return the rowid for the new record.
177 * @throws IOException when one of the underlying I/O operations fails.
178 */
179 public long insert( Object obj ) throws IOException
180 {
181 return insert( obj, DefaultSerializer.INSTANCE );
182 }
183
184
185 /**
186 * Inserts a new record using a custom serializer.
187 *
188 * @param obj the object for the new record.
189 * @param serializer a custom serializer
190 * @return the rowid for the new record.
191 * @throws IOException when one of the underlying I/O operations fails.
192 */
193 public synchronized long insert( Object obj, Serializer serializer ) throws IOException
194 {
195 byte[] data;
196 long recid;
197 Location physRowId;
198
199 checkIfClosed();
200
201 data = serializer.serialize( obj );
202 physRowId = physMgr.insert( data, 0, data.length );
203 recid = logMgr.insert( physRowId ).toLong();
204
205 if ( DEBUG )
206 {
207 System.out.println( "BaseRecordManager.insert() recid " + recid + " length " + data.length );
208 }
209
210 return recid;
211 }
212
213
214 /**
215 * Deletes a record.
216 *
217 * @param recid the rowid for the record that should be deleted.
218 * @throws IOException when one of the underlying I/O operations fails.
219 */
220 public synchronized void delete( long recid ) throws IOException
221 {
222 checkIfClosed();
223
224 if ( recid <= 0 )
225 {
226 throw new IllegalArgumentException( I18n.err( I18n.ERR_536, recid ) );
227 }
228
229 if ( DEBUG )
230 {
231 System.out.println( "BaseRecordManager.delete() recid " + recid );
232 }
233
234 Location logRowId = new Location( recid );
235 Location physRowId = logMgr.fetch( logRowId );
236 physMgr.delete( physRowId );
237 logMgr.delete( logRowId );
238 }
239
240
241 /**
242 * Updates a record using standard java object serialization.
243 *
244 * @param recid the recid for the record that is to be updated.
245 * @param obj the new object for the record.
246 * @throws IOException when one of the underlying I/O operations fails.
247 */
248 public void update( long recid, Object obj ) throws IOException
249 {
250 update( recid, obj, DefaultSerializer.INSTANCE );
251 }
252
253
254 /**
255 * Updates a record using a custom serializer.
256 *
257 * @param recid the recid for the record that is to be updated.
258 * @param obj the new object for the record.
259 * @param serializer a custom serializer
260 * @throws IOException when one of the underlying I/O operations fails.
261 */
262 public synchronized void update( long recid, Object obj, Serializer serializer ) throws IOException
263 {
264 checkIfClosed();
265
266 if ( recid <= 0 )
267 {
268 throw new IllegalArgumentException( I18n.err( I18n.ERR_536, recid ) );
269 }
270
271 Location logRecid = new Location( recid );
272 Location physRecid = logMgr.fetch( logRecid );
273
274 byte[] data = serializer.serialize( obj );
275
276 if ( DEBUG )
277 {
278 System.out.println( "BaseRecordManager.update() recid " + recid + " length " + data.length );
279 }
280
281 Location newRecid = physMgr.update( physRecid, data, 0, data.length );
282
283 if ( !newRecid.equals( physRecid ) )
284 {
285 logMgr.update( logRecid, newRecid );
286 }
287 }
288
289
290 /**
291 * Fetches a record using standard java object serialization.
292 *
293 * @param recid the recid for the record that must be fetched.
294 * @return the object contained in the record.
295 * @throws IOException when one of the underlying I/O operations fails.
296 */
297 public Object fetch( long recid ) throws IOException
298 {
299 return fetch( recid, DefaultSerializer.INSTANCE );
300 }
301
302
303 /**
304 * Fetches a record using a custom serializer.
305 *
306 * @param recid the recid for the record that must be fetched.
307 * @param serializer a custom serializer
308 * @return the object contained in the record.
309 * @throws IOException when one of the underlying I/O operations fails.
310 */
311 public synchronized Object fetch( long recid, Serializer serializer )
312 throws IOException
313 {
314 byte[] data;
315
316 checkIfClosed();
317
318 if ( recid <= 0 )
319 {
320 throw new IllegalArgumentException( I18n.err( I18n.ERR_536, recid ) );
321 }
322
323 data = physMgr.fetch( logMgr.fetch( new Location( recid ) ) );
324
325 if ( DEBUG )
326 {
327 System.out.println( "BaseRecordManager.fetch() recid " + recid + " length " + data.length );
328 }
329 return serializer.deserialize( data );
330 }
331
332
333 /**
334 * Returns the number of slots available for "root" rowids. These slots
335 * can be used to store special rowids, like rowids that point to
336 * other rowids. Root rowids are useful for bootstrapping access to
337 * a set of data.
338 */
339 public int getRootCount()
340 {
341 return FileHeader.NROOTS;
342 }
343
344
345 /**
346 * Returns the indicated root rowid.
347 *
348 * @see #getRootCount
349 */
350 public synchronized long getRoot( int id ) throws IOException
351 {
352 checkIfClosed();
353
354 return pageMgr.getFileHeader().getRoot( id );
355 }
356
357
358 /**
359 * Sets the indicated root rowid.
360 *
361 * @see #getRootCount
362 */
363 public synchronized void setRoot( int id, long rowid ) throws IOException
364 {
365 checkIfClosed();
366
367 pageMgr.getFileHeader().setRoot( id, rowid );
368 }
369
370
371 /**
372 * Obtain the record id of a named object. Returns 0 if named object
373 * doesn't exist.
374 */
375 public long getNamedObject( String name ) throws IOException
376 {
377 checkIfClosed();
378
379 Map<String, Long> nameDirectory = getNameDirectory();
380 Long recid = nameDirectory.get( name );
381
382 if ( recid == null )
383 {
384 return 0;
385 }
386
387 return recid;
388 }
389
390
391 /**
392 * Set the record id of a named object.
393 */
394 public void setNamedObject( String name, long recid ) throws IOException
395 {
396 checkIfClosed();
397
398 if ( recid == 0 )
399 {
400 // remove from hashtable
401 getNameDirectory().remove( name );
402 }
403 else
404 {
405 getNameDirectory().put( name, recid );
406 }
407 saveNameDirectory();
408 }
409
410
411 /**
412 * Commit (make persistent) all changes since beginning of transaction.
413 */
414 public synchronized void commit()
415 throws IOException
416 {
417 checkIfClosed();
418
419 pageMgr.commit();
420 }
421
422
423 /**
424 * Rollback (cancel) all changes since beginning of transaction.
425 */
426 public synchronized void rollback() throws IOException
427 {
428 checkIfClosed();
429
430 pageMgr.rollback();
431 }
432
433
434 /**
435 * Load name directory
436 */
437 @SuppressWarnings("unchecked")
438 private Map<String, Long> getNameDirectory() throws IOException
439 {
440 // retrieve directory of named hashtable
441 long nameDirectory_recid = getRoot( NAME_DIRECTORY_ROOT );
442
443 if ( nameDirectory_recid == 0 )
444 {
445 nameDirectory = new HashMap<String, Long>();
446 nameDirectory_recid = insert( nameDirectory );
447 setRoot( NAME_DIRECTORY_ROOT, nameDirectory_recid );
448 }
449 else
450 {
451 nameDirectory = ( Map<String, Long> ) fetch( nameDirectory_recid );
452 }
453
454 return nameDirectory;
455 }
456
457
458 private void saveNameDirectory() throws IOException
459 {
460 long recid = getRoot( NAME_DIRECTORY_ROOT );
461
462 if ( recid == 0 )
463 {
464 throw new IOException( I18n.err( I18n.ERR_537 ) );
465 }
466
467 update( recid, nameDirectory );
468 }
469
470
471 /**
472 * Check if RecordManager has been closed. If so, throw an IllegalStateException.
473 */
474 private void checkIfClosed() throws IllegalStateException
475 {
476 if ( recordFile == null )
477 {
478 throw new IllegalStateException( I18n.err( I18n.ERR_538 ) );
479 }
480 }
481 }