001: /*
002: * Copyright Aduna (http://www.aduna-software.com/) (c) 2007.
003: *
004: * Licensed under the Aduna BSD-style license.
005: */
006: package org.openrdf.sail.nativerdf;
007:
008: import java.io.File;
009: import java.io.IOException;
010:
011: import org.openrdf.sail.nativerdf.btree.RecordIterator;
012:
013: /**
014: * A cache for fixed size byte array records. This cache uses a temporary file
015: * to store the records. This file is deleted upon calling {@link #discard()}.
016: *
017: * @author Arjohn Kampman
018: */
019: abstract class RecordCache {
020:
021: /*-----------*
022: * Constants *
023: *-----------*/
024:
025: protected final File cacheFile;
026:
027: protected final long maxRecords;
028:
029: /*-----------*
030: * Variables *
031: *-----------*/
032:
033: private long recordCount;
034:
035: /*--------------*
036: * Constructors *
037: *--------------*/
038:
039: public RecordCache(File cacheDir) throws IOException {
040: this (cacheDir, Long.MAX_VALUE);
041: }
042:
043: public RecordCache(File cacheDir, long maxRecords)
044: throws IOException {
045: this .cacheFile = File.createTempFile("records", ".tmp",
046: cacheDir);
047: this .maxRecords = maxRecords;
048: this .recordCount = 0;
049: }
050:
051: /*---------*
052: * Methods *
053: *---------*/
054:
055: public void discard() throws IOException {
056: cacheFile.delete();
057: }
058:
059: public final boolean isValid() {
060: return recordCount < maxRecords;
061: }
062:
063: public final void storeRecord(byte[] data) throws IOException {
064: if (isValid()) {
065: storeRecordInternal(data);
066: recordCount++;
067: }
068: }
069:
070: public final void storeRecords(RecordCache other)
071: throws IOException {
072: if (isValid()) {
073: RecordIterator recIter = other.getRecords();
074: try {
075: byte[] record;
076:
077: while ((record = recIter.next()) != null) {
078: storeRecordInternal(record);
079: }
080: } finally {
081: recIter.close();
082: }
083: }
084: }
085:
086: public abstract void storeRecordInternal(byte[] data)
087: throws IOException;
088:
089: public final RecordIterator getRecords() {
090: if (isValid()) {
091: return getRecordsInternal();
092: }
093:
094: throw new IllegalStateException();
095: }
096:
097: public abstract RecordIterator getRecordsInternal();
098:
099: public final long getRecordCount() {
100: if (isValid()) {
101: return recordCount;
102: }
103:
104: throw new IllegalStateException();
105: }
106: }
|