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
|
package suncertify.db.file;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Logger;
import suncertify.db.DatabaseManager;
import suncertify.db.DbException;
import suncertify.db.RecordNotFoundException;
import suncertify.db.utils.ArraysUtils;
import suncertify.db.utils.Check;
/**
* Implementation of DatabaseManager.
*
* It can handle any file database having the proper magic cookie.
* FileDatabaseManager reads the schema description and enforces it afterwards.
*
* The actual file operations are handled by the FileDatabaseOperator class, in
* order to ensure the consistent use of DbException, a generic exception type
* to avoid file database specific exceptions, hence making future changes
* easier.
*
* The records are put in memory for faster read operations, which are expected
* to be the most common, especially for find operations.
*
* The class makes no assumption about its context and thus ensures itself the
* whole synchronization strategy.
*
* @See DatabaseManager
* @See FileDatabaseOperator
*/
public class FileDatabaseManager implements DatabaseManager {
/**
* Length of the status field on the file.
*/
private static final int STATUS_LENGTH = 4;
/**
* Encoding of the content of the file.
*/
private static final String ENCODING = "UTF";
/**
* The magic cookie which is required in the file for it to be a proper file
* database.
*/
private static final int MAGIC_COOKIE = 798;
/**
* The logger used by the instance: all logs in the class uses it.
*/
private final Logger log = Logger.getLogger("suncertify.db");
/**
* Does the physical operations on the file (read & write) with
* synchronization handled by the current class. Wraps errors in
* DbExceptions.
*/
private final FileDatabaseOperator database;
/**
* The maximal length of a record, computed from the schema description read
* at the beginning of the file database.
*/
private final int recordLength;
/**
* List of Field describing the schema, each Field having a name and a
* length.
*
* @See Field
*/
private final List<Field> schema;
/**
* The records cache. Each record is accessed by its record number. This
* records map is populated at startup and then maintained afterwards.
*
* Access to the map is guarded by the recordsLock field.
*
* @See Record
*/
private final Map<Long, Record> records = new HashMap<Long, Record>();
/**
* Allows multiple reads at the same time but only one write at a time,
* hence used to ensure the records map integrity: none can modify it while
* others are reading it, as well as only one thread can modify it a time.
*
* The lock is reentrant in case the same thread requires it twice in a row.
*/
private final ReadWriteLock recordsLock = new ReentrantReadWriteLock();
/**
* The record number generator. Must be used while holding the write lock on
* the recordsLock.
*/
private Long recordNumberGenerator = 0L;
/**
* The currently free locations on the file database.
*
* The freeLocation queue is populated at startup and then maintained
* afterwards. It should be accessed through the recordsLock, with a write lock.
*/
private final LinkedList<Long> freeLocations = new LinkedList<Long>();
/**
* An empty record, useful when converting record's array to the
* corresponding string to avoid rebuilding it all every time. See
* convertToRawData for more details.
*/
private final String emptyRecord;
/**
* Creates a new FileDatabaseManager from the path provided.
*
* @param path
* path to the file database.
* @throws DbException
* in case of exception during creation.
*/
public FileDatabaseManager(final String path) throws DbException {
log.entering("FileDatabaseManager", "FileDatabaseManager", path);
database = new FileDatabaseOperator(path);
// TODO : either always lock or never
checkMagicCookie();
int offset = database.readInt("offset");
schema = readSchema();
recordLength = computeRecordLength();
emptyRecord = new String(new byte[recordLength]);
populateRecords(offset);
log.exiting("FileDatabaseManager", "FileDatabaseManager");
}
/**
* Compute the record length based on the schema read from the file.
* Includes the status length.
*
* @return The size in integers.
*/
private int computeRecordLength() {
log.entering("FileDatabaseManager", "computeRecordLength");
int length = 0;
for (final Field field : schema) {
length += field.getLength();
}
log.exiting("FileDatabaseManager", "computeRecordLength", length);
return length;
}
/**
* Read the record schema from the file database.
*
* @return The schema read in the form of a list of Field.
* @See Field.
*/
private List<Field> readSchema() {
log.entering("FileDatabaseManager", "readSchema");
final short numberOfField = database.readShort("numberOfField");
final List<Field> readFields = new ArrayList<Field>(numberOfField);
for (int i = 0; i < numberOfField; i++) {
short nameLenght = database.readShort("field name length n°" + i);
byte[] fieldNameByteArray = new byte[nameLenght];
database.readBytes(fieldNameByteArray, "fieldName");
String fieldName;
try {
fieldName = new String(fieldNameByteArray, ENCODING);
} catch (UnsupportedEncodingException e) {
throw new DbException(
"Error while converting byte[] of length '"
+ fieldNameByteArray.length + "' and content '"
+ fieldNameByteArray.toString()
+ "' with encoding '" + ENCODING
+ "' when reading schema.", e);
}
short fieldLength = database.readShort("field length n°" + i);
readFields.add(new Field(fieldName, fieldLength));
}
log.exiting("FileDatabaseManager", "readSchema", readFields);
return Collections.unmodifiableList(readFields);
}
/**
* Read the magic cookie and checks it has the expected value. If not,
* throws a DbException.
*
* @throws DbException
* if the magic cookie isn't valid
*/
private void checkMagicCookie() throws DbException {
log.entering("FileDatabaseManager", "checkMagicCookie");
int readMagicCookie = database.readInt("magicCookie");
if (readMagicCookie != MAGIC_COOKIE) {
throw new DbException(
"Not a data file. Expected the magic cookie '"
+ MAGIC_COOKIE + "', read '" + readMagicCookie
+ "'.");
}
log.exiting("FileDatabaseManager", "checkMagicCookie");
}
/**
* Read the locations and content of each database record, putting them in
* the records map. If a record isn't valid, populate the freeLocations
* queue.
*
* @param offset
* where to start in the file database.
*
*/
private void populateRecords(final int offset) {
log.entering("FileDatabaseManager", "populateRecords", offset);
recordsLock.writeLock().lock();
try {
long databaseLength = database.getDatabaseLength();
for (long locationInFile = offset; locationInFile < databaseLength; locationInFile += recordLength
+ STATUS_LENGTH) {
String[] rawRecord = readRawRecord(locationInFile);
if (rawRecord != null) {
records.put(recordNumberGenerator++, new Record(
locationInFile, rawRecord));
} else {
freeLocations.offer(locationInFile);
}
}
} finally {
recordsLock.writeLock().unlock();
}
log.exiting("FileDatabaseManager", "populateRecords");
}
/**
* Checks that provided record matches the schema definition of the current
* file.
*
* @param record
* @throws IllegalStateException
* if the record isn't valid
*/
private void checkRecord(final String[] record)
throws IllegalStateException {
log.entering("FileDatabaseManager", "checkRecord", record);
Check.notNull(record, "record");
Check.areEquals(schema.size(), record.length, "record length");
for (int i = 0; i < record.length; i++) {
String fieldContent = record[i];
Field fieldDescription = schema.get(i);
Check.notNull(fieldContent, "Content for field "
+ fieldDescription.getName());
Check
.isValid(fieldContent.length() <= fieldDescription
.getLength(), "Lenght of content for field "
+ fieldDescription.getName());
}
}
/**
* Read the raw record content.
*
* @param location
* in the file where to read from.
* @return Array of String, being the raw content.
*/
private String[] readRawRecord(final Long location) {
log.entering("FileDatabaseManager", "readRawRecord", location);
byte[] rawRecord = new byte[recordLength];
boolean valid = false;
database.seek(location, "record to read");
if (isStatusValid(database.readShort("status"))) {
valid = true;
database.readFully(rawRecord, "rawRecord");
}
String[] readRecord = null;
if (valid) {
readRecord = convertBytesToRecord(rawRecord);
} else {
freeLocations.offer(location);
}
log.exiting("FileDatabaseManager", "readRecord", readRecord);
return readRecord;
}
/**
* Test if the given status is valid.
*
* @param status
* The status to check.
* @return boolean indicating whether the status is valid or not.
*/
private boolean isStatusValid(final short status) {
log.entering("FileDatabaseManager", "isStatusValid", status);
return (status == 0);
}
} |