📄 recordstore.java
字号:
/* * @(#)RecordStore.java 1.51 01/08/22 * Copyright (c) 2000-2001 Sun Microsystems, Inc. All Rights Reserved. * * Copyright 2000 Motorola, Inc. All Rights Reserved. * This notice does not imply publication. */package javax.microedition.rms; import com.sun.midp.rms.RecordStoreFile;/** * A class representing a record store. A record store consists of a * collection of records which will remain persistent across multiple * invocations of the MIDlet. The platform is responsible for * making its best effort to maintain the integrity of the * MIDlet's record stores throughout the normal use of the * platform, including reboots, battery changes, etc. * * <p>Record stores are created in platform-dependent locations, * which are not exposed to the MIDlets. The naming space for * record stores is controlled at the MIDlet suite granularity. * MIDlets within a MIDlet suite are allowed to create multiple * record stores, as long as they are each given different names. * When a MIDlet suite is removed from a platform all the record * stores associated with its MIDlets will also be removed. These * APIs only allow the manipulation of the MIDlet suite's own * record stores, and does not provide any mechanism for record * sharing between MIDlets in different MIDlet suites. MIDlets * within a MIDlet suite can access each other's record stores * directly. * * <p>Record store names are case sensitive and may consist of * any combination of up to 32 Unicode characters. * Record store names must be unique within the scope of a given * MIDlet suite. In other words, a MIDlets within a MIDlet suite * are is not allowed to create more than one record store with * the same name, however a MIDlet in different one MIDlet suites * are is allowed to each have a record store with the same name * as a MIDlet in another MIDlet suite. In that case, the record * stores are still distinct and separate. * * <p>No locking operations are provided in this API. Record store * implementations ensure that * all individual record store operations are atomic, synchronous, * and serialized, so no corruption will occur with multiple accesses. * However, if a MIDlet uses multiple threads * to access a record store, it is the MIDlet's responsibility to * coordinate this access or unintended consequences may result. * Similarly, if a platform performs transparent synchronization of * a record store, it is the platform's responsibility to enforce * exclusive access to the record store between the MIDlet and * synchronization engine. * * <p>Records are uniquely identified within a given record store by their * recordId, which is an integer value. This recordId is used as the * primary key for the records. The first record created in a record * store will have recordId equal to one (1). Each subsequent * record added to a RecordStore will be assigned a recordId one greater * than the record added before it. That is, if two records are added * to a record store, and the first has a recordId of 'n', the next will * have a recordId of 'n + 1'. MIDlets can create other indices * by using the <code>RecordEnumeration</code> class. * * <p>This record store uses long integers for time/date stamps, in * the format used by System.currentTimeMillis(). The record store * is time stamped with the last time it was * modified. The record store also maintains a <em>version</em>, which * is an integer that is incremented for each operation that modifies * the contents of the RecordStore. These are useful * for synchronization engines as well as other things. * * @version MIDP 1.0 * @author Jim Van Peursem */ public class RecordStore { /** pre initialized RecordStore header structure */ private static final byte[] DB_INIT = { (byte)'m', (byte)'i', (byte)'d', (byte)'p', (byte)'-', (byte)'r', (byte)'m', (byte)'s', 0, 0, 0, 0, // num live records 0, 0, 0, 0, // reserved 0, 0, 0, 0, // version 0, 0, 0, 1, // next record id 0, 0, 0, 0, // first record offset 0, 0, 0, 0, // first free-space offset 0, 0, 0, 0, // last modified (1st half) 0, 0, 0, 0, // last modified (2nd half) 0, 0, 0, 0, // start of data offset 0, 0, 0, 0 // end of data offset }; /** length of the signature string in bytes */ private static final int SIGNATURE_LENGTH = 8; /** size of a per record meta-data object */ private static final int DB_RECORD_HEADER_LENGTH = 16; /** * storage space allocated in multiples of <code>DB_BLOCK_SIZE</code>, * which can not be smaller than DB_RECORD_HEADER_LENGTH and * must be a multiple of DB_RECORD_HEADER_LENGTH */ private static final int DB_BLOCK_SIZE = 16; /** size of the buffer for compacting record store */ private static final int DB_COMPACTBUFFER_SIZE = 64; /** cache of open RecordStore instances */ private static java.util.Vector dbCache = new java.util.Vector(3); /** lock to protect static dbcache state */ private static final Object dbCacheLock = new Object(); /** name of this record store */ private String recordStoreName; /** number of open instances of this record store */ private int opencount; /** RecordStoreFile where this record store is stored */ private RecordStoreFile dbraf; /** lock used to synchronize this record store */ Object rsLock; /** recordListeners of this record store */ private java.util.Vector recordListener; /** cache of record headers */ private RecordHeaderCache recHeadCache; /** number of direct mapped cache entries */ private static int CACHE_SIZE = 8; /** static buffer used in loading/storing RecordHeader data */ private static byte[] recHeadBuf = new byte[DB_RECORD_HEADER_LENGTH]; /* * This implementation assumes (and enforces) that there is only * one instance of a RecordStore object for any given database file * in the file system. This assumption is enforceable when there * is only one VM running, but will lead to data corruption problems * if multiple VM's are used to read/write into the same database. * * As a consequence of this assumption, the following database * attributes are read from the RecordStoreFile when the RecordStore * is opened, maintained in memory for performance efficiency, and * reflected back to the file only when necessary for the sake of * error resilience. */ /** next record's id */ private int dbNextRecordID = 1; /** record store version */ private int dbVersion; /** count of live records */ private int dbNumLiveRecords; /** time record store was last modified (in milliseconds */ private long dbLastModified; /** offset of first record */ private int dbFirstRecordOffset; /** offset of first free block */ private int dbFirstFreeBlockOffset; /** offset of the first data block */ private int dbDataStart = 48; /** offset of the last data block */ private int dbDataEnd = 48; /** static buffer used in loading/storing dbState */ private static byte[] dbState = new byte[DB_INIT.length]; /* * The layout of the database file is as follows: * * Bytes - Usage * 00-07 - Signature = 'midp-rms' * 08-11 - Number of live records in the database (big endian) * 12-15 - Reserved - Always nice to keep a few spare bits around * 16-19 - Database "version" - a monotonically increasing revision * number (big endian) * 20-23 - Next record ID to use (big endian) * 24-27 - First record offset (bytes from beginning of file - big endian) * 28-31 - First free-block offset (bytes from beginning of file - big * endian) * 32-39 - Last modified (64-bit long, big endian, milliseconds since * jan 1970) * 40-43 - Start of Data storage * 44-47 - End of Data storage * 48-xx - Record storage */ /** RS_SIGNATURE offset */ private static final int RS_SIGNATURE = 0; /** RS_NUM_LIVE offset */ private static final int RS_NUM_LIVE = 8; /** RS_RESERVED offset */ private static final int RS_RESERVED = 12; /** RS_VERSION offset */ private static final int RS_VERSION = 16; /** RS_NEXT_ID offset */ private static final int RS_NEXT_ID = 20; /** RS_REC_START offset */ private static final int RS_REC_START = 24; /** RS_FREE_START offset */ private static final int RS_FREE_START = 28; /** RS_LAST_MODIFIED offset */ private static final int RS_LAST_MODIFIED = 32; /** RS_START_OF_DATA offset */ private static final int RS_DATA_START = 40; /** RS_END_OF_DATA offset */ private static final int RS_DATA_END = 44; /* * RecordStore Constructors */ /** * MIDlets must use <code>openRecordStore()</code> to get * a <code>RecordStore</code> object. If this constructor * is not declared (as private scope), Javadoc (and Java) * will assume a public constructor. */ private RecordStore() { } /** * Apps must use <code>openRecordStore()</code> to get * a <code>RecordStore</code> object. This constructor * is used internally for creating RecordStore objects. * * <code>dbCacheLock</code> must be held before calling * this constructor. * * @param recordStoreName a string to name the record store. * @param create if true, create the record store if it doesn't exist. * * @exception RecordStoreException if something goes wrong setting up * the new RecordStore. * @exception RecordStoreNotFoundException if can't find the record store * and create is set to false. */ private RecordStore(String recordStoreName, boolean create) throws RecordStoreException, RecordStoreNotFoundException { this.recordStoreName = recordStoreName; recHeadCache = new RecordHeaderCache(CACHE_SIZE); rsLock = new Object(); recordListener = new java.util.Vector(3); boolean exists = RecordStoreFile.exists(recordStoreName); // Check for errors between app and record store existance. if (!create && !exists) { throw new RecordStoreNotFoundException("cannot find record " + "store file"); } // Create a RecordStoreFile for storing the record store. try { dbraf = new RecordStoreFile(recordStoreName); /* * At this point we've opened the RecordStoreFile. If we * created a new record store, initialize the db attributes. */ if (create && !exists) { // Initialize record store attributes dbraf.seek(RS_SIGNATURE); // Update the timestamp RecordStore.putLong(System.currentTimeMillis(), DB_INIT, RS_LAST_MODIFIED); RecordStore.putInt(48, DB_INIT, RS_DATA_START); RecordStore.putInt(48, DB_INIT, RS_DATA_END); dbraf.write(DB_INIT); } else { /* * Create a buffer and read the database attributes * Read the record store attributes. Set up internal state. */ byte[] buf = new byte[DB_INIT.length]; dbraf.seek(RS_SIGNATURE); dbraf.read(buf); /* * Verify that the file is actually a record store * by verifying the record store "signature." */ for (int i = 0; i < SIGNATURE_LENGTH; i++) { if (buf[i] != DB_INIT[i]) throw new RecordStoreException("invalid record "+ "store contents"); } // Convert byte array to internal state variables. dbNumLiveRecords = RecordStore.getInt(buf, RS_NUM_LIVE); dbVersion = RecordStore.getInt(buf, RS_VERSION); dbNextRecordID = RecordStore.getInt(buf, RS_NEXT_ID); dbFirstRecordOffset = RecordStore.getInt(buf, RS_REC_START); dbFirstFreeBlockOffset = RecordStore.getInt(buf, RS_FREE_START); dbLastModified = RecordStore.getLong(buf, RS_LAST_MODIFIED); dbDataStart = RecordStore.getInt(buf, RS_DATA_START); dbDataEnd = RecordStore.getInt(buf, RS_DATA_END); } } catch (java.io.IOException ioe) { try { if (dbraf != null) { dbraf.close(); } } catch (java.io.IOException ioe2) { // ignore exception within exception block } finally { dbraf = null; } throw new RecordStoreException("error opening record store " + "file"); } } /* * Public Static Methods */ /** * Open (and possibly create) a record store associated with the * given MIDlet suite. If this method is called by a MIDlet when * the record store is already open by a MIDlet in the MIDlet suite, * this method returns a reference to the same RecordStore object. * * @param recordStoreName the MIDlet suite unique name, not to exceed * 32 characters, of the record store. * @param createIfNecessary if true, the record store will be created * if necessary. * * @return the RecordStore object for this record store. * * @exception RecordStoreException if a record store related exception * occurred. * @exception RecordStoreNotFoundException if the record store could * not be found. * @exception RecordStoreFullException if the operation cannot be * completed because the record store is full. */ public static RecordStore openRecordStore(String recordStoreName, boolean createIfNecessary) throws RecordStoreException, RecordStoreFullException, RecordStoreNotFoundException { synchronized (dbCacheLock) { if (recordStoreName.length() > 32) { throw new RecordStoreException("record store name too long"); } // Cache record store objects and ensure that there is only // one record store object in memory for any given record // store file. This is good for memory use. This is NOT safe // in the situation where multiple VM's may be executing code // concurrently. In that case, you have to sync things through // file locking or something similar. // Check the record store cache for a db with the same name RecordStore db; for (int n = 0; n < dbCache.size(); n++) { db = (RecordStore)dbCache.elementAt(n); if (db.recordStoreName.equals(recordStoreName)) { db.opencount++; // times rs has been opened return db; // return ref to cached record store } } /* * Record store not found in cache. Check
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -