Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance
Java decentralizedintranet-searchintranet-search-enginep2pp2p-networkprivacyprivacy-protectionsearch-enginesearchenginewebweb-search-enginewebsearchwebseearch-engine
completed migration of BLOBTree to BLOBHeaps: - removed migration code - removed BLOBTree after the removal of the BLOBTree, a lot of dead code appeared: - removed dead code that was needed for BLOBTree Some more classes may have not much use any more after the removal of BLOBTree, but still have some component that are needed elsewhere. Additional Refactoring steps are needed to clean up dependencies and then more code may appear that is unused and can be removed as well.
orbiterc5122d6836cb
diff --git a/source/dbtest.java b/source/dbtest.javaindex 17d957deb..13abff7a4 100644--- a/source/dbtest.java+++ b/source/dbtest.java@@ -20,7 +20,6 @@ import de.anomic.kelondro.order.Base64Order;import de.anomic.kelondro.order.CloneableIterator;import de.anomic.kelondro.order.NaturalOrder;import de.anomic.kelondro.table.EcoTable;-import de.anomic.kelondro.table.Tree;import de.anomic.kelondro.table.SQLTable;import de.anomic.kelondro.table.SplitTable;import de.anomic.kelondro.util.MemoryControl;@@ -390,7 +389,6 @@ public class dbtest {if (command.equals("list")) {CloneableIterator<Row.Entry> i = null;- if (table_test instanceof Tree) i = ((Tree) table_test).rows();if (table_test instanceof SQLTable) i = ((SQLTable) table_test).rows();if(i != null) {Row.Entry row;diff --git a/source/de/anomic/crawler/CrawlQueues.java b/source/de/anomic/crawler/CrawlQueues.javaindex 25ec451c1..8b226714d 100644--- a/source/de/anomic/crawler/CrawlQueues.java+++ b/source/de/anomic/crawler/CrawlQueues.java@@ -38,7 +38,7 @@ import java.util.concurrent.ConcurrentHashMap;import de.anomic.content.RSSMessage;import de.anomic.http.httpClient;-import de.anomic.kelondro.table.FlexWidthArray;+import de.anomic.kelondro.table.SplitTable;import de.anomic.kelondro.util.DateFormatter;import de.anomic.kelondro.util.FileUtils;import de.anomic.plasma.plasmaParser;@@ -79,7 +79,7 @@ public class CrawlQueues {if (errorDBFile.exists()) {// delete the error db to get a fresh each time on startup// this is useful because there is currently no re-use of the data in this table.- if (errorDBFile.isDirectory()) FlexWidthArray.delete(plasmaPath, "urlError2.db"); else FileUtils.deletedelete(errorDBFile);+ if (errorDBFile.isDirectory()) SplitTable.delete(plasmaPath, "urlError2.db"); else FileUtils.deletedelete(errorDBFile);}errorURL = new ZURL(plasmaPath, "urlError3.db", false);delegatedURL = new ZURL(plasmaPath, "urlDelegated3.db", true);diff --git a/source/de/anomic/crawler/ZURL.java b/source/de/anomic/crawler/ZURL.javaindex f74d141e4..fd40a14d8 100755--- a/source/de/anomic/crawler/ZURL.java+++ b/source/de/anomic/crawler/ZURL.java@@ -37,7 +37,7 @@ import de.anomic.kelondro.index.RowSet;import de.anomic.kelondro.index.ObjectIndex;import de.anomic.kelondro.order.Base64Order;import de.anomic.kelondro.table.EcoTable;-import de.anomic.kelondro.table.FlexWidthArray;+import de.anomic.kelondro.table.SplitTable;import de.anomic.kelondro.util.FileUtils;import de.anomic.yacy.yacySeedDB;import de.anomic.yacy.yacyURL;@@ -67,7 +67,7 @@ public class ZURL {final File f = new File(cachePath, tablename);if (startWithEmptyFile) {if (f.exists()) {- if (f.isDirectory()) FlexWidthArray.delete(cachePath, tablename); else FileUtils.deletedelete(f);+ if (f.isDirectory()) SplitTable.delete(cachePath, tablename); else FileUtils.deletedelete(f);}}this.urlIndex = new EcoTable(f, rowdef, EcoTable.tailCacheDenyUsage, EcoFSBufferSize, 0);diff --git a/source/de/anomic/data/URLFetcherStack.java b/source/de/anomic/data/URLFetcherStack.javadeleted file mode 100644index 9d819719c..000000000--- a/source/de/anomic/data/URLFetcherStack.java+++ /dev/null@@ -1,116 +0,0 @@-// URLFetcherStack.java-// --------------------------------------// part of YACY-//-// (C) 2007 by Franz Brausze-//-// last change: $LastChangedDate: $ by $LastChangedBy: $-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.data;--import java.io.File;-import java.io.IOException;-import java.net.MalformedURLException;-import java.util.ArrayList;-import java.util.Iterator;--import de.anomic.kelondro.index.Row;-import de.anomic.kelondro.index.Row.EntryIndex;-import de.anomic.kelondro.order.Base64Order;-import de.anomic.kelondro.table.Stack;-import de.anomic.kelondro.util.kelondroException;-import de.anomic.yacy.yacyURL;-import de.anomic.yacy.logging.Log;--public class URLFetcherStack {-- public static final String DBFILE = "urlRemote2.stack";-- private static final Row rowdef = new Row(- "String urlstring-256",- Base64Order.enhancedCoder );- private final Stack db;- private final Log log;-- private int popped = 0;- private int pushed = 0;-- public URLFetcherStack(final File path) throws IOException {- this.db = new Stack(new File(path, DBFILE), rowdef);- this.log = new Log("URLFETCHERSTACK");- }-- public int getPopped() { return this.popped; }- public int getPushed() { return this.pushed; }- public void clearStat() { this.popped = 0; this.pushed = 0; }-- protected void finalize() throws Throwable {- this.db.close();- }-- public boolean push(final yacyURL url) {- try {- this.db.push(this.db.row().newEntry(- new byte[][] { url.toNormalform(true, true).getBytes("UTF-8") }- ));- this.pushed++;- return true;- } catch (final IOException e) {- this.log.logSevere("error storing entry", e);- return false;- }- }-- public yacyURL pop() {- try {- final Row.Entry r = this.db.pop();- if (r == null) return null;- final String url = r.getColString(0, null);- try {- this.popped++;- return new yacyURL(url, null);- } catch (final MalformedURLException e) {- this.log.logSevere("found invalid URL-entry: " + url);- return null;- }- } catch (final IOException e) {- this.log.logSevere("error retrieving entry", e);- return null;- }- }-- public String[] top(final int count) {- try {- final ArrayList<String> ar = new ArrayList<String>();- final Iterator<EntryIndex> it = db.contentRows(500);- Row.EntryIndex ei;- for (int i=0; i<count && it.hasNext(); i++) {- ei = it.next();- if (ei == null) continue;- ar.add(ei.getColString(0, null));- }- return ar.toArray(new String[ar.size()]);- } catch (final kelondroException e) {- this.log.logSevere("error retrieving entry", e);- return null;- }- }-- public int size() {- return this.db.size();- }-}diff --git a/source/de/anomic/data/blogBoard.java b/source/de/anomic/data/blogBoard.javaindex f3e190840..188b0236e 100644--- a/source/de/anomic/data/blogBoard.java+++ b/source/de/anomic/data/blogBoard.java@@ -48,7 +48,7 @@ import org.w3c.dom.NodeList;import org.xml.sax.SAXException;import de.anomic.data.wiki.wikiBoard;-import de.anomic.kelondro.blob.BLOBTree;+import de.anomic.kelondro.blob.Heap;import de.anomic.kelondro.blob.MapView;import de.anomic.kelondro.order.Base64Order;import de.anomic.kelondro.order.NaturalOrder;@@ -59,15 +59,14 @@ import de.anomic.yacy.logging.Log;public class blogBoard {public static final int keyLength = 64;- private static final int recordSize = 512;MapView database = null;- public blogBoard(final File actpath, final File newFile) throws IOException {+ public blogBoard(final File actpath) throws IOException {new File(actpath.getParent()).mkdir();- new File(newFile.getParent()).mkdir();if (database == null) {- database = new MapView(BLOBTree.toHeap(actpath, true, true, keyLength, recordSize, '_', NaturalOrder.naturalOrder, newFile), 500, '_');+ //database = new MapView(BLOBTree.toHeap(actpath, true, true, keyLength, recordSize, '_', NaturalOrder.naturalOrder, newFile), 500, '_');+ database = new MapView(new Heap(actpath, keyLength, NaturalOrder.naturalOrder, 1024 * 64), 500, '_');}}diff --git a/source/de/anomic/data/blogBoardComments.java b/source/de/anomic/data/blogBoardComments.javaindex 1f28b38da..30cf33491 100644--- a/source/de/anomic/data/blogBoardComments.java+++ b/source/de/anomic/data/blogBoardComments.java@@ -47,7 +47,7 @@ import org.w3c.dom.NodeList;import org.xml.sax.SAXException;import de.anomic.data.wiki.wikiBoard;-import de.anomic.kelondro.blob.BLOBTree;+import de.anomic.kelondro.blob.Heap;import de.anomic.kelondro.blob.MapView;import de.anomic.kelondro.order.Base64Order;import de.anomic.kelondro.order.NaturalOrder;@@ -57,7 +57,6 @@ public class blogBoardComments {public static final int keyLength = 64;private static final String dateFormat = "yyyyMMddHHmmss";- private static final int recordSize = 512;static SimpleDateFormat SimpleFormatter = new SimpleDateFormat(dateFormat);static {@@ -66,11 +65,11 @@ public class blogBoardComments {private MapView database = null;- public blogBoardComments(final File actpath, final File newFile) throws IOException {+ public blogBoardComments(final File actpath) throws IOException {new File(actpath.getParent()).mkdir();- new File(newFile.getParent()).mkdir();if (database == null) {- database = new MapView(BLOBTree.toHeap(actpath, true, true, keyLength, recordSize, '_', NaturalOrder.naturalOrder, newFile), 500, '_');+ //database = new MapView(BLOBTree.toHeap(actpath, true, true, keyLength, recordSize, '_', NaturalOrder.naturalOrder, newFile), 500, '_');+ database = new MapView(new Heap(actpath, keyLength, NaturalOrder.naturalOrder, 1024 * 64), 500, '_');}}diff --git a/source/de/anomic/data/bookmarksDB.java b/source/de/anomic/data/bookmarksDB.javaindex c6a1e5462..a5705a4f5 100644--- a/source/de/anomic/data/bookmarksDB.java+++ b/source/de/anomic/data/bookmarksDB.java@@ -65,7 +65,7 @@ import de.anomic.crawler.CrawlEntry;import de.anomic.crawler.CrawlProfile;import de.anomic.htmlFilter.htmlFilterContentScraper;import de.anomic.htmlFilter.htmlFilterWriter;-import de.anomic.kelondro.blob.BLOBTree;+import de.anomic.kelondro.blob.Heap;import de.anomic.kelondro.blob.MapView;import de.anomic.kelondro.order.CloneableIterator;import de.anomic.kelondro.order.NaturalOrder;@@ -108,25 +108,25 @@ public class bookmarksDB {// bookmarksDB's class constructor// ------------------------------------- public bookmarksDB(- final File bookmarksFile, final File bookmarksFileNew,- final File tagsFile, final File tagsFileNew,- final File datesFile, final File datesFileNew) throws IOException {+ public bookmarksDB(final File bookmarksFile, final File tagsFile, final File datesFile) throws IOException {// bookmarkstagCache=new TreeMap<String, Tag>();bookmarksFile.getParentFile().mkdirs();//this.bookmarksTable = new kelondroMap(kelondroDyn.open(bookmarksFile, bufferkb * 1024, preloadTime, 12, 256, '_', true, false));- this.bookmarksTable = new MapView(BLOBTree.toHeap(bookmarksFile, true, true, 12, 256, '_', NaturalOrder.naturalOrder, bookmarksFileNew), 1000, '_');-+ //this.bookmarksTable = new MapView(BLOBTree.toHeap(bookmarksFile, true, true, 12, 256, '_', NaturalOrder.naturalOrder, bookmarksFileNew), 1000, '_');+ this.bookmarksTable = new MapView(new Heap(bookmarksFile, 12, NaturalOrder.naturalOrder, 1024 * 64), 1000, '_');+// tagstagsFile.getParentFile().mkdirs();final boolean tagsFileExisted = tagsFile.exists();- this.tagsTable = new MapView(BLOBTree.toHeap(tagsFile, true, true, 12, 256, '_', NaturalOrder.naturalOrder, tagsFileNew), 500, '_');+ //this.tagsTable = new MapView(BLOBTree.toHeap(tagsFile, true, true, 12, 256, '_', NaturalOrder.naturalOrder, tagsFileNew), 500, '_');+ this.tagsTable = new MapView(new Heap(tagsFile, 12, NaturalOrder.naturalOrder, 1024 * 64), 500, '_');if (!tagsFileExisted) rebuildTags();// datesfinal boolean datesExisted = datesFile.exists();- this.datesTable = new MapView(BLOBTree.toHeap(datesFile, true, true, 20, 256, '_', NaturalOrder.naturalOrder, datesFileNew), 500, '_');+ //this.datesTable = new MapView(BLOBTree.toHeap(datesFile, true, true, 20, 256, '_', NaturalOrder.naturalOrder, datesFileNew), 500, '_');+ this.datesTable = new MapView(new Heap(datesFile, 20, NaturalOrder.naturalOrder, 1024 * 64), 500, '_');if (!datesExisted) rebuildDates();// autoReCrawldiff --git a/source/de/anomic/data/messageBoard.java b/source/de/anomic/data/messageBoard.javaindex a7645f614..a4ffa5e17 100644--- a/source/de/anomic/data/messageBoard.java+++ b/source/de/anomic/data/messageBoard.java@@ -31,7 +31,7 @@ import java.util.Iterator;import java.util.Map;import java.util.TimeZone;-import de.anomic.kelondro.blob.BLOBTree;+import de.anomic.kelondro.blob.Heap;import de.anomic.kelondro.blob.MapView;import de.anomic.kelondro.order.Base64Order;import de.anomic.kelondro.order.NaturalOrder;@@ -40,7 +40,6 @@ public class messageBoard {private static final int categoryLength = 12;private static final String dateFormat = "yyyyMMddHHmmss";- private static final int recordSize = 512;static SimpleDateFormat SimpleFormatter = new SimpleDateFormat(dateFormat);@@ -51,11 +50,11 @@ public class messageBoard {MapView database = null;private int sn = 0;- public messageBoard(final File path, final File pathNew) throws IOException {+ public messageBoard(final File path) throws IOException {new File(path.getParent()).mkdir();- new File(pathNew.getParent()).mkdir();if (database == null) {- database = new MapView(BLOBTree.toHeap(path, true, true, categoryLength + dateFormat.length() + 2, recordSize, '_', NaturalOrder.naturalOrder, pathNew), 500, '_');+ //database = new MapView(BLOBTree.toHeap(path, true, true, categoryLength + dateFormat.length() + 2, recordSize, '_', NaturalOrder.naturalOrder, pathNew), 500, '_');+ database = new MapView(new Heap(path, categoryLength + dateFormat.length() + 2, NaturalOrder.naturalOrder, 1024 * 64), 500, '_');}sn = 0;}diff --git a/source/de/anomic/data/userDB.java b/source/de/anomic/data/userDB.javaindex 2c1d39865..abf8c4d63 100644--- a/source/de/anomic/data/userDB.java+++ b/source/de/anomic/data/userDB.java@@ -37,7 +37,6 @@ import java.util.Random;import de.anomic.http.httpRequestHeader;import de.anomic.kelondro.blob.Heap;-import de.anomic.kelondro.blob.BLOBTree;import de.anomic.kelondro.blob.MapView;import de.anomic.kelondro.order.Base64Order;import de.anomic.kelondro.order.CloneableIterator;@@ -56,11 +55,11 @@ public final class userDB {HashMap<String, String> ipUsers = new HashMap<String, String>();HashMap<String, Object> cookieUsers = new HashMap<String, Object>();- public userDB(final File userTableFile, final File userTableFileNew) throws IOException {- this.userTableFile = userTableFileNew;+ public userDB(final File userTableFile) throws IOException {+ this.userTableFile = userTableFile;userTableFile.getParentFile().mkdirs();- userTableFileNew.getParentFile().mkdirs();- this.userTable = new MapView(BLOBTree.toHeap(userTableFile, true, true, 128, 256, '_', NaturalOrder.naturalOrder, userTableFile), 10, '_');+ //this.userTable = new MapView(BLOBTree.toHeap(userTableFile, true, true, 128, 256, '_', NaturalOrder.naturalOrder, userTableFile), 10, '_');+ this.userTable = new MapView(new Heap(userTableFile, 128, NaturalOrder.naturalOrder, 1024 * 64), 10, '_');}void resetDatabase() {diff --git a/source/de/anomic/data/wiki/wikiBoard.java b/source/de/anomic/data/wiki/wikiBoard.javaindex 13bd3cd1c..16ece63fa 100644--- a/source/de/anomic/data/wiki/wikiBoard.java+++ b/source/de/anomic/data/wiki/wikiBoard.java@@ -31,7 +31,7 @@ import java.util.Iterator;import java.util.Map;import java.util.TimeZone;-import de.anomic.kelondro.blob.BLOBTree;+import de.anomic.kelondro.blob.Heap;import de.anomic.kelondro.blob.MapView;import de.anomic.kelondro.order.Base64Order;import de.anomic.kelondro.order.NaturalOrder;@@ -40,7 +40,6 @@ public class wikiBoard {public static final int keyLength = 64;private static final String dateFormat = "yyyyMMddHHmmss";- private static final int recordSize = 512;static SimpleDateFormat SimpleFormatter = new SimpleDateFormat(dateFormat);@@ -52,16 +51,16 @@ public class wikiBoard {MapView bkpbase = null;static HashMap<String, String> authors = new HashMap<String, String>();- public wikiBoard(- final File actpath, final File actpathNew,- final File bkppath, final File bkppathNew) throws IOException {+ public wikiBoard( final File actpath, final File bkppath) throws IOException {new File(actpath.getParent()).mkdirs();if (datbase == null) {- datbase = new MapView(BLOBTree.toHeap(actpath, true, true, keyLength, recordSize, '_', NaturalOrder.naturalOrder, actpathNew), 500, '_');+ //datbase = new MapView(BLOBTree.toHeap(actpath, true, true, keyLength, recordSize, '_', NaturalOrder.naturalOrder, actpathNew), 500, '_');+ datbase = new MapView(new Heap(actpath, keyLength, NaturalOrder.naturalOrder, 1024 * 64), 500, '_');}new File(bkppath.getParent()).mkdirs();if (bkpbase == null) {- bkpbase = new MapView(BLOBTree.toHeap(bkppath, true, true, keyLength + dateFormat.length(), recordSize, '_', NaturalOrder.naturalOrder, bkppathNew), 500, '_');+ //bkpbase = new MapView(BLOBTree.toHeap(bkppath, true, true, keyLength + dateFormat.length(), recordSize, '_', NaturalOrder.naturalOrder, bkppathNew), 500, '_');+ bkpbase = new MapView(new Heap(bkppath, keyLength + dateFormat.length(), NaturalOrder.naturalOrder, 1024 * 64), 500, '_');}}diff --git a/source/de/anomic/kelondro/blob/BLOBTree.java b/source/de/anomic/kelondro/blob/BLOBTree.javadeleted file mode 100644index 12dd3080b..000000000--- a/source/de/anomic/kelondro/blob/BLOBTree.java+++ /dev/null@@ -1,430 +0,0 @@-// kelondroBLOBTree.java-// (C) 2004 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 09.02.2004 (as "kelondroDyn.java") on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $-// $LastChangedRevision: 1986 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--/*- This class extends the kelondroTree and adds dynamic data handling- A dynamic content is created, by using several tree nodes and- combining them over a set of associated keys.- Example: a byte[] of length 1000 shall be stored in a kelondroTree- with node size 256. The key for the entry is 'entry'.- Then kelondroDyn stores the first part of four into the entry- 'entry00', the second into 'entry01', and so on.--*/--package de.anomic.kelondro.blob;--import java.io.File;-import java.io.IOException;-import java.io.UnsupportedEncodingException;-import java.util.Iterator;--import de.anomic.kelondro.index.Cache;-import de.anomic.kelondro.index.Row;-import de.anomic.kelondro.index.ObjectIndex;-import de.anomic.kelondro.io.AbstractRandomAccess;-import de.anomic.kelondro.io.RandomAccessInterface;-import de.anomic.kelondro.order.ByteOrder;-import de.anomic.kelondro.order.CloneableIterator;-import de.anomic.kelondro.order.RotateIterator;-import de.anomic.kelondro.table.EcoTable;-import de.anomic.kelondro.table.Tree;-import de.anomic.kelondro.util.FileUtils;-import de.anomic.kelondro.util.kelondroException;--public class BLOBTree {-- private static final int counterlen = 8;-- protected int keylen;- private final int reclen;- //private int segmentCount;- private final char fillChar;- private final ObjectIndex index;- private ObjectBuffer buffer;- private final Row rowdef;-- /**- * Deprecated Class. Please use Heap instead- */- private BLOBTree(final File file, final boolean useNodeCache, final boolean useObjectCache, final int key,- final int nodesize, final char fillChar, final ByteOrder objectOrder) {- // creates or opens a dynamic tree- rowdef = new Row("byte[] key-" + (key + counterlen) + ", byte[] node-" + nodesize, objectOrder);- ObjectIndex fbi;- try {- fbi = new Tree(file, useNodeCache, 0, rowdef, 1, 8);- } catch (final IOException e) {- e.printStackTrace();- FileUtils.deletedelete(file);- throw new kelondroException(e.getMessage());- }- this.index = ((useObjectCache) && (!(fbi instanceof EcoTable))) ? (ObjectIndex) new Cache(fbi) : fbi;- this.keylen = key;- this.reclen = nodesize;- this.fillChar = fillChar;- //this.segmentCount = 0;- //if (!(tree.fileExisted)) writeSegmentCount();- buffer = new ObjectBuffer(file.toString());- }-- public static Heap toHeap(final File file, final boolean useNodeCache, final boolean useObjectCache, final int key,- final int nodesize, final char fillChar, final ByteOrder objectOrder, final File blob) throws IOException {- if (blob.exists() || !file.exists()) {- // open the blob file and ignore the tree- return new Heap(blob, key, objectOrder, 1024 * 64);- }- // open a Tree and migrate everything to a Heap- BLOBTree tree = new BLOBTree(file, useNodeCache, useObjectCache, key, nodesize, fillChar, objectOrder);- Heap heap = new Heap(blob, key, objectOrder, 1024 * 64);- Iterator<byte[]> i = tree.keys(true, false);- byte[] k, kk = new byte[key], v;- String s;- while (i.hasNext()) {- k = i.next();- //assert k.length == key : "k.length = " + k.length + ", key = " + key;- if (k == null) continue;- v = tree.get(k);- if (v == null) continue;- s = new String(v, "UTF-8").trim();- // enlarge entry key to fit into the given key length- if (k.length == key) {- heap.put(k, s.getBytes("UTF-8"));- } else {- System.arraycopy(k, 0, kk, 0, k.length);- for (int j = k.length; j < key; j++) kk[j] = (byte) fillChar;- heap.put(kk, s.getBytes("UTF-8"));- }- }- tree.close(false);- return heap;- }-- private static String counter(final int c) {- String s = Integer.toHexString(c);- while (s.length() < counterlen) s = "0" + s;- return s;- }-- private byte[] elementKey(String key, final int record) {- if (key.length() > keylen) throw new RuntimeException("key len (" + key.length() + ") out of limit (" + keylen + "): '" + key + "'");- while (key.length() < keylen) key = key + fillChar;- key = key + counter(record);- try {- return key.getBytes("UTF-8");- } catch (UnsupportedEncodingException e) {- return key.getBytes();- }- }-- private String origKey(final byte[] rawKey) {- int n = keylen - 1;- if (n >= rawKey.length) n = rawKey.length - 1;- while ((n > 0) && (rawKey[n] == (byte) fillChar)) n--;- try {- return new String(rawKey, 0, n + 1, "UTF-8");- } catch (UnsupportedEncodingException e) {- return new String(rawKey, 0, n + 1);- }- }-- private class keyIterator implements CloneableIterator<byte[]> {- // the iterator iterates all keys- CloneableIterator<Row.Entry> ri;- String nextKey;-- private keyIterator(final CloneableIterator<Row.Entry> iter) {- ri = iter;- nextKey = n();- }-- public keyIterator clone(final Object modifier) {- return new keyIterator(ri.clone(modifier));- }-- public boolean hasNext() {- return nextKey != null;- }-- public byte[] next() {- final String result = nextKey;- nextKey = n();- try {- return origKey(result.getBytes("UTF-8")).getBytes("UTF-8");- } catch (UnsupportedEncodingException e) {- return origKey(result.getBytes()).getBytes();- }- }-- public void remove() {- throw new UnsupportedOperationException("no remove in RawKeyIterator");- }-- private String n() {- byte[] g;- String k;- String v;- int c;- Row.Entry nt;- while (ri.hasNext()) {- nt = ri.next();- if (nt == null) return null;- g = nt.getColBytes(0);- if (g == null) return null;- try {- k = new String(g, 0, keylen, "UTF-8");- } catch (UnsupportedEncodingException e1) {- k = new String(g, 0, keylen);- }- try {- v = new String(g, keylen, counterlen, "UTF-8");- } catch (UnsupportedEncodingException e1) {- v = new String(g, keylen, counterlen);- }- try {- c = Integer.parseInt(v, 16);- } catch (final NumberFormatException e) {- c = -1;- }- if (c == 0) return k;- }- return null;- }-- }-- private synchronized CloneableIterator<byte[]> keys(final boolean up, final boolean rotating) throws IOException {- // iterates only the keys of the Nodes- // enumerated objects are of type String- final keyIterator i = new keyIterator(index.rows(up, null));- if (rotating) return new RotateIterator<byte[]>(i, null, index.size());- return i;- }-- private byte[] getValueCached(final byte[] key) throws IOException {-- // read from buffer- final byte[] buffered = (byte[]) buffer.get(key);- if (buffered != null) return buffered;-- // read from db- final Row.Entry result = index.get(key);- if (result == null) return null;-- // return result- return result.getColBytes(1);- }-- private synchronized void setValueCached(final byte[] key, final byte[] value) throws IOException {- // update storage- synchronized (this) {- index.put(rowdef.newEntry(new byte[][]{key, value}));- buffer.put(key, value);- }- }-- private synchronized int get(final String key, final int pos) throws IOException {- final int reccnt = pos / reclen;- // read within a single record- final byte[] buf = getValueCached(elementKey(key, reccnt));- if (buf == null) return -1;- final int recpos = pos % reclen;- if (buf.length <= recpos) return -1;- return buf[recpos] & 0xFF;- }-- private synchronized byte[] get(final byte[] key) throws IOException {- final RandomAccessInterface ra = getRA(new String(key, "UTF-8"));- if (ra == null) return null;- return ra.readFully();- }-- private synchronized byte[] get(final String key, final int pos, final int len) throws IOException {- final int recpos = pos % reclen;- final int reccnt = pos / reclen;- byte[] segment1;- // read first within a single record- if ((recpos == 0) && (reclen == len)) {- segment1 = getValueCached(elementKey(key, reccnt));- if (segment1 == null) return null;- } else {- byte[] buf = getValueCached(elementKey(key, reccnt));- if (buf == null) return null;- if (buf.length < reclen) {- byte[] buff = new byte[reclen];- System.arraycopy(buf, 0, buff, 0, buf.length);- buf = buff;- buff = null;- }- // System.out.println("read:- // buf.length="+buf.length+",recpos="+recpos+",len="+len);- if (recpos + len <= reclen) {- segment1 = new byte[len];- System.arraycopy(buf, recpos, segment1, 0, len);- } else {- segment1 = new byte[reclen - recpos];- System.arraycopy(buf, recpos, segment1, 0, reclen - recpos);- }- }- // if this is all, return- if (recpos + len <= reclen) return segment1;- // read from several records- // we combine recursively all participating records- // we have two segments: the one in the starting record, and the remaining- // segment 1 in record <reccnt> : start = recpos, length = reclen - recpos- // segment 2 in record <reccnt>+1: start = 0, length = len - reclen + recpos- // recursively step further- final byte[] segment2 = get(key, pos + segment1.length, len - segment1.length);- if (segment2 == null) return segment1;- // now combine the two segments into the result- final byte[] result = new byte[segment1.length + segment2.length];- System.arraycopy(segment1, 0, result, 0, segment1.length);- System.arraycopy(segment2, 0, result, segment1.length, segment2.length);- return result;- }-- private synchronized void put(final String key, final int pos, final byte[] b, final int off, final int len) throws IOException {- final int recpos = pos % reclen;- final int reccnt = pos / reclen;- byte[] buf;- // first write current record- if ((recpos == 0) && (reclen == len)) {- if (off == 0) {- setValueCached(elementKey(key, reccnt), b);- } else {- buf = new byte[len];- System.arraycopy(b, off, buf, 0, len);- setValueCached(elementKey(key, reccnt), b);- }- } else {- buf = getValueCached(elementKey(key, reccnt));- if (buf == null) {- buf = new byte[reclen];- } else if (buf.length < reclen) {- byte[] buff = new byte[reclen];- System.arraycopy(buf, 0, buff, 0, buf.length);- buf = buff;- }- // System.out.println("write:- // b.length="+b.length+",off="+off+",len="+(reclen-recpos));- if (len < (reclen - recpos))- System.arraycopy(b, off, buf, recpos, len);- else- System.arraycopy(b, off, buf, recpos, reclen - recpos);- setValueCached(elementKey(key, reccnt), buf);- }- // if more records are necessary, write to them also recursively- if (recpos + len > reclen) {- put(key, pos + reclen - recpos, b, off + reclen - recpos, len - reclen + recpos);- }- }-- private synchronized void put(final String key, final int pos, final int b) throws IOException {- final int recpos = pos % reclen;- final int reccnt = pos / reclen;- byte[] buf;- // first write current record- buf = getValueCached(elementKey(key, reccnt));- if (buf == null) {- buf = new byte[reclen];- } else if (buf.length < reclen) {- byte[] buff = new byte[reclen];- System.arraycopy(buf, 0, buff, 0, buf.length);- buf = buff;- }- buf[recpos] = (byte) b;- setValueCached(elementKey(key, reccnt), buf);- }-- private synchronized RandomAccessInterface getRA(final String filekey) {- // this returns always a RARecord, even if no existed bevore- //return new kelondroBufferedRA(new RARecord(filekey), 512, 0);- return new RARecord(filekey);- }-- private class RARecord extends AbstractRandomAccess implements RandomAccessInterface {-- int seekpos = 0;- int compLength = -1;-- String filekey;-- private RARecord(final String filekey) {- this.filekey = filekey;- }-- public long length() throws IOException {- if (compLength >= 0) return compLength;- int p = 0;- while (get(filekey, p, reclen) != null) p+= reclen;- compLength = p-1;- return p-1;- }-- public void setLength(long length) throws IOException {- throw new UnsupportedOperationException();- }-- public long available() throws IOException {- return length() - seekpos;- }-- public int read() throws IOException {- return get(filekey, seekpos++);- }-- public void write(final int i) throws IOException {- put(filekey, seekpos++, i);- }-- public void readFully(final byte[] b, final int off, final int len) throws IOException {- int l = Math.min(b.length - off, len);- final byte[] buf = get(filekey, seekpos, l);- if (buf == null) throw new IOException("record at off " + off + ", len " + len + " not found");- l = Math.min(buf.length, l);- System.arraycopy(buf, 0, b, off, l);- seekpos += l;- }-- public void write(final byte[] b, final int off, final int len) throws IOException {- put(filekey, seekpos, b, off, len);- seekpos += len;- }-- public void seek(final long pos) throws IOException {- seekpos = (int) pos;- }-- public void close() throws IOException {- // no need to do anything here- }-- }-- private synchronized void close(boolean writeIDX) {- index.close();- }-}\ No newline at end of filediff --git a/source/de/anomic/kelondro/index/Cache.java b/source/de/anomic/kelondro/index/Cache.javaindex 1bba254a0..25902b5e0 100644--- a/source/de/anomic/kelondro/index/Cache.java+++ b/source/de/anomic/kelondro/index/Cache.java@@ -37,7 +37,6 @@ import java.util.Map;import java.util.TreeMap;import de.anomic.kelondro.order.CloneableIterator;-import de.anomic.kelondro.table.CachedRecords;import de.anomic.kelondro.util.MemoryControl;public class Cache implements ObjectIndex {@@ -141,10 +140,7 @@ public class Cache implements ObjectIndex {// future feature .. map.put("objectElderTimeRead", index.profile().)return map;}-- private int cacheGrowStatus(long available) {- return CachedRecords.cacheGrowStatus(MemoryControl.available(), memStopGrow, memStartShrink);- }+private boolean checkMissSpace() {// returns true if it is allowed to write into this cache@@ -155,12 +151,6 @@ public class Cache implements ObjectIndex {}return false;}- if (cacheGrowStatus(available) < 1) {- if (readMissCache != null) {- readMissCache.clear();- }- return false;- }return true;}@@ -173,16 +163,6 @@ public class Cache implements ObjectIndex {}return false;}- final int status = cacheGrowStatus(available);- if (status < 1) {- if (readHitCache != null) {- readHitCache.clear();- }- return false;- }- if (status < 2) {- if (readHitCache != null) readHitCache.clear();- }return true;}diff --git a/source/de/anomic/kelondro/table/CachedRecords.java b/source/de/anomic/kelondro/table/CachedRecords.javadeleted file mode 100644index 36461aaef..000000000--- a/source/de/anomic/kelondro/table/CachedRecords.java+++ /dev/null@@ -1,573 +0,0 @@-// kelondroCachedRecords.java-// (C) 2003 - 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 2003 on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2009-01-30 15:33:00 +0000 (Fr, 30 Jan 2009) $-// $LastChangedRevision: 5540 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.table;--import java.io.File;-import java.io.IOException;-import java.util.Iterator;-import java.util.TreeMap;--import de.anomic.kelondro.index.Row;-import de.anomic.kelondro.index.ObjectArrayCache;-import de.anomic.kelondro.io.RandomAccessRecords;-import de.anomic.kelondro.util.MemoryControl;-import de.anomic.kelondro.util.kelondroException;--public class CachedRecords extends AbstractRecords implements RandomAccessRecords {-- // static supervision objects: recognize and coordinate all activites- private static final TreeMap<String, CachedRecords> recordTracker = new TreeMap<String, CachedRecords>();- private static final long memStopGrow = 40 * 1024 * 1024; // a limit for the node cache to stop growing if less than this memory amount is available- private static final long memStartShrink = 20 * 1024 * 1024; // a limit for the node cache to start with shrinking if less than this memory amount is available-- // caching buffer- private ObjectArrayCache cacheHeaders; // the cache; holds overhead values and key element- private int readHit;- private int readMiss;- private int writeUnique;- private int writeDouble;- private int cacheDelete;- private int cacheFlush;--- public CachedRecords(- final File file, final boolean useNodeCache, final long preloadTime,- final short ohbytec, final short ohhandlec,- final Row rowdef, final int FHandles, final int txtProps, final int txtPropWidth) throws IOException {- super(file, useNodeCache, ohbytec, ohhandlec, rowdef, FHandles, txtProps, txtPropWidth);- initCache(useNodeCache, preloadTime);- if (useNodeCache) recordTracker.put(this.filename, this);- }-- private void initCache(final boolean useNodeCache, final long preloadTime) {- if (useNodeCache) {- this.cacheHeaders = new ObjectArrayCache(this.headchunksize, 0);- } else {- this.cacheHeaders = null;- }- this.readHit = 0;- this.readMiss = 0;- this.writeUnique = 0;- this.writeDouble = 0;- this.cacheDelete = 0;- this.cacheFlush = 0;- // pre-load node cache- if ((preloadTime > 0) && (useNodeCache)) {- final long stop = System.currentTimeMillis() + preloadTime;- int count = 0;- try {- final Iterator<Node> i = contentNodes(preloadTime);- CacheNode n;- while ((System.currentTimeMillis() < stop) && (cacheGrowStatus() == 2) && (i.hasNext())) {- n = (CacheNode) i.next();- cacheHeaders.addb(n.handle().index, n.headChunk);- count++;- }- cacheHeaders.flush();- logFine("preloaded " + count + " records into cache");- } catch (final kelondroException e) {- // the contentNodes iterator had a time-out; we don't do a preload- logFine("could not preload records: " + e.getMessage());- }-- }- }-- private int cacheGrowStatus() {- final long available = MemoryControl.available();- if ((cacheHeaders != null) && (available - 2 * 1024 * 1024 < cacheHeaders.memoryNeededForGrow())) return 0;- return cacheGrowStatus(available, memStopGrow, memStartShrink);- }-- public static final int cacheGrowStatus(final long available, final long stopGrow, final long startShrink) {- // returns either 0, 1 or 2:- // 0: cache is not allowed to grow, but shall shrink- // 1: cache is allowed to grow, but need not to shrink- // 2: cache is allowed to grow and must not shrink- if (available > stopGrow) return 2;- if (available > startShrink) {- MemoryControl.gc(60000, "kelendroCacheRecords.cacheGrowStatus(...) 1"); // thq- return 1;- }- MemoryControl.gc(30000, "kelendroCacheRecords.cacheGrowStatus(...) 0"); // thq- return 0;- }-- protected synchronized void deleteNode(final RecordHandle handle) throws IOException {- if (cacheHeaders == null) {- super.deleteNode(handle);- } else synchronized (cacheHeaders) {- if (cacheHeaders.size() == 0) {- super.deleteNode(handle);- } else {- cacheHeaders.removeb(handle.index);- cacheDelete++;- super.deleteNode(handle);- }- }- }-- protected void printCache() {- if (cacheHeaders == null) {- System.out.println("### file report: " + size() + " entries");- for (int i = 0; i < USAGE.allCount(); i++) {- // print from file to compare- System.out.print("#F " + i + ": ");- try {- for (int j = 0; j < headchunksize; j++)- System.out.print(Integer.toHexString(0xff & entryFile.readByte(j + seekpos(new RecordHandle(i)))) + " ");- } catch (final IOException e) {}-- System.out.println();- }- } else {- System.out.println("### cache report: " + cacheHeaders.size() + " entries");-- final Iterator<Row.Entry> i = cacheHeaders.rows();- Row.Entry entry;- while (i.hasNext()) {- entry = i.next();-- // print from cache- System.out.print("#C ");- printChunk(entry);- System.out.println();-- // print from file to compare- /*- System.out.print("#F " + cp + " " + ((Handle) entry.getKey()).index + ": ");- try {- for (int j = 0; j < headchunksize; j++)- System.out.print(entryFile.readByte(j + seekpos((Handle) entry.getKey())) + ",");- } catch (IOException e) {}- */- System.out.println();- }- }- System.out.println("### end report");- }-- public synchronized void close() {- if (cacheHeaders == null) {- if (recordTracker.get(this.filename) != null) {- theLogger.severe("close(): file '" + this.filename + "' was tracked with record tracker, but it should not.");- }- } else {- if (recordTracker.remove(this.filename) == null) {- theLogger.severe("close(): file '" + this.filename + "' was not tracked with record tracker.");- }- }- super.close();- this.cacheHeaders = null;- }-- public void print() throws IOException {- super.print();-- // print also all records- System.out.println("CACHE");- printCache();- System.out.println("--");- System.out.println("NODES");- final Iterator<Node> i = new contentNodeIterator(-1);- Node n;- while (i.hasNext()) {- n = i.next();- System.out.println("NODE: " + n.toString());- }- }-- public Node newNode(final RecordHandle handle, final byte[] bulk, final int offset) throws IOException {- return new CacheNode(handle, bulk, offset);- }-- public final class CacheNode implements Node {- // an Node holds all information of one row of data. This includes the key to the entry- // which is stored as entry element at position 0- // an Node object can be created in two ways:- // 1. instantiation with an index number. After creation the Object does not hold any- // value information until such is retrieved using the getValue() method- // 2. instantiation with a value array. the values are not directly written into the- // file. Expanding the tree structure is then done using the save() method. at any- // time it is possible to verify the save state using the saved() predicate.- // Therefore an entry object has three modes:- // a: holding an index information only (saved() = true)- // b: holding value information only (saved() = false)- // c: holding index and value information at the same time (saved() = true)- // which can be the result of one of the two processes as follow:- // (i) created with index and after using the getValue() method, or- // (ii) created with values and after calling the save() method- // the method will therefore throw an IllegalStateException when the following- // process step is performed:- // - create the Node with index and call then the save() method- // this case can be decided with- // ((index != NUL) && (values == null))- // The save() method represents the insert function for the tree. Balancing functions- // are applied automatically. While balancing, the Node does never change its index key,- // but its parent/child keys.- //private byte[] ohBytes = null; // the overhead bytes, OHBYTEC values- //private Handle[] ohHandle= null; // the overhead handles, OHHANDLEC values- //private byte[][] values = null; // an array of byte[] nodes is the value vector- private RecordHandle handle = null; // index of the entry, by default NUL means undefined- byte[] headChunk = null; // contains ohBytes, ohHandles and the key value- private byte[] tailChunk = null; // contains all values except the key value- private boolean headChanged = false;- private boolean tailChanged = false;-- public CacheNode(final byte[] rowinstance) throws IOException {- // this initializer is used to create nodes from bulk-read byte arrays- assert ((rowinstance == null) || (rowinstance.length == ROW.objectsize)) : "bulkchunk.length = " + (rowinstance == null ? "null" : rowinstance.length) + ", ROW.width(0) = " + ROW.width(0);- this.handle = new RecordHandle(USAGE.allocatePayload(rowinstance));-- // create empty chunks- this.headChunk = new byte[headchunksize];- this.tailChunk = new byte[tailchunksize];-- // write content to chunks- if (rowinstance == null) {- for (int i = headchunksize - 1; i >= 0; i--) this.headChunk[i] = (byte) 0xff;- for (int i = tailchunksize - 1; i >= 0; i--) this.tailChunk[i] = (byte) 0xff;- } else {- for (int i = overhead - 1; i >= 0; i--) this.headChunk[i] = (byte) 0xff;- System.arraycopy(rowinstance, 0, this.headChunk, overhead, ROW.width(0));- System.arraycopy(rowinstance, ROW.width(0), this.tailChunk, 0, tailchunksize);- }-- if (cacheHeaders != null) synchronized (cacheHeaders) {- updateNodeCache();- }-- // mark chunks as changed- // if the head/tail chunks come from a file system read, setChanged should be false- // if the chunks come from a overwrite attempt, it should be true- this.headChanged = false; // we wrote the head already during allocate- this.tailChanged = false; // we write the tail already during allocate- }-- public CacheNode(final RecordHandle handle, final byte[] bulkchunk, final int offset) throws IOException {- // this initializer is used to create nodes from bulk-read byte arrays- // if write is true, then the chunk in bulkchunk is written to the file- // othervise it is considered equal to what is stored in the file- // (that is ensured during pre-loaded enumeration)- this.handle = handle;- boolean changed;- if (handle.index >= USAGE.allCount()) {- // this causes only a write action if we create a node beyond the end of the file- USAGE.allocateRecord(handle.index, bulkchunk, offset);- changed = false; // we have already wrote the record, so it is considered as unchanged- } else {- changed = true;- }- assert ((bulkchunk == null) || (bulkchunk.length - offset >= recordsize)) : "bulkchunk.length = " + (bulkchunk == null ? "null" : bulkchunk.length) + ", offset = " + offset + ", recordsize = " + recordsize;-- // create empty chunks- this.headChunk = new byte[headchunksize];- this.tailChunk = new byte[tailchunksize];-- // write content to chunks- if (bulkchunk != null) {- System.arraycopy(bulkchunk, offset, this.headChunk, 0, headchunksize);- System.arraycopy(bulkchunk, offset + headchunksize, this.tailChunk, 0, tailchunksize);- }-- // mark chunks as changed- this.headChanged = changed;- this.tailChanged = changed;- }-- public CacheNode(final RecordHandle handle, final boolean fillTail) throws IOException {- this(handle, null, 0, fillTail);- }-- public CacheNode(final RecordHandle handle, final CacheNode parentNode, final int referenceInParent, boolean fillTail) throws IOException {- // this creates an entry with an pre-reserved entry position.- // values can be written using the setValues() method,- // but we expect that values are already there in the file.- assert (handle != null): "node handle is null";- assert (handle.index >= 0): "node handle too low: " + handle.index;- //assert (handle.index < USAGE.allCount()) : "node handle too high: " + handle.index + ", USEDC=" + USAGE.USEDC + ", FREEC=" + USAGE.FREEC;-- // the parentNode can be given if an auto-fix in the following case is wanted- if (handle == null) throw new kelondroException(filename, "INTERNAL ERROR: node handle is null.");- if (handle.index >= USAGE.allCount()) {- if (parentNode == null) throw new kelondroException(filename, "INTERNAL ERROR, Node/init: node handle index " + handle.index + " exceeds size. No auto-fix node was submitted. This is a serious failure.");- try {- parentNode.setOHHandle(referenceInParent, null);- parentNode.commit();- logWarning("INTERNAL ERROR, Node/init in " + filename + ": node handle index " + handle.index + " exceeds size. The bad node has been auto-fixed");- } catch (final IOException ee) {- throw new kelondroException(filename, "INTERNAL ERROR, Node/init: node handle index " + handle.index + " exceeds size. It was tried to fix the bad node, but failed with an IOException: " + ee.getMessage());- }- }-- // use given handle- this.handle = new RecordHandle(handle.index);-- // check for memory availability when fillTail is requested- if ((fillTail) && (tailchunksize > 10000)) fillTail = false; // this is a fail-safe 'short version' of a memory check-- // init the content- // create chunks; read them from file or cache- this.tailChunk = null;- if (cacheHeaders == null) {- if (fillTail) {- // read complete record- byte[] chunkbuffer = new byte[recordsize];- entryFile.readFully(seekpos(this.handle), chunkbuffer, 0, recordsize);- this.headChunk = new byte[headchunksize];- this.tailChunk = new byte[tailchunksize];- System.arraycopy(chunkbuffer, 0, this.headChunk, 0, headchunksize);- System.arraycopy(chunkbuffer, headchunksize, this.tailChunk, 0, tailchunksize);- } else {- // read overhead and key- this.headChunk = new byte[headchunksize];- this.tailChunk = null;- entryFile.readFully(seekpos(this.handle), this.headChunk, 0, headchunksize);- }- } else synchronized(cacheHeaders) {- byte[] cacheEntry = null;- cacheEntry = cacheHeaders.getb(this.handle.index);- if (cacheEntry == null) {- // cache miss, we read overhead and key from file- readMiss++;- if (fillTail) {- // read complete record- byte[] chunkbuffer = new byte[recordsize];- entryFile.readFully(seekpos(this.handle), chunkbuffer, 0, recordsize);- this.headChunk = new byte[headchunksize];- this.tailChunk = new byte[tailchunksize];- System.arraycopy(chunkbuffer, 0, this.headChunk, 0, headchunksize);- System.arraycopy(chunkbuffer, headchunksize, this.tailChunk, 0, tailchunksize);- } else {- // read overhead and key- this.headChunk = new byte[headchunksize];- this.tailChunk = null;- entryFile.readFully(seekpos(this.handle), this.headChunk, 0, headchunksize);- }-- // if space left in cache, copy these value to the cache- updateNodeCache();- } else {- readHit++;- this.headChunk = cacheEntry;- }- }- }-- private void setValue(final byte[] value, final int valueoffset, int valuewidth, final byte[] targetarray, int targetoffset) {- if (value == null) {- while (valuewidth-- > 0) targetarray[targetoffset++] = 0;- } else {- assert ((valueoffset >= 0) && (valueoffset < value.length)) : "valueoffset = " + valueoffset;- assert ((valueoffset + valuewidth <= value.length)) : "valueoffset = " + valueoffset + ", valuewidth = " + valuewidth + ", value.length = " + value.length;- assert ((targetoffset >= 0) && (targetoffset < targetarray.length)) : "targetoffset = " + targetoffset;- assert ((targetoffset + valuewidth <= targetarray.length)) : "targetoffset = " + targetoffset + ", valuewidth = " + valuewidth + ", targetarray.length = " + targetarray.length;- System.arraycopy(value, valueoffset, targetarray, targetoffset, Math.min(value.length, valuewidth)); // error?- while (valuewidth-- > value.length) targetarray[targetoffset + valuewidth] = 0;- }- }-- public RecordHandle handle() {- // if this entry has an index, return it- if (this.handle.index == RecordHandle.NUL) throw new kelondroException(filename, "the entry has no index assigned");- return this.handle;- }-- public void setOHByte(final int i, final byte b) {- if (i >= OHBYTEC) throw new IllegalArgumentException("setOHByte: wrong index " + i);- if (this.handle.index == RecordHandle.NUL) throw new kelondroException(filename, "setOHByte: no handle assigned");- this.headChunk[i] = b;- this.headChanged = true;- }-- public void setOHHandle(final int i, final RecordHandle otherhandle) {- assert (i < OHHANDLEC): "setOHHandle: wrong array size " + i;- assert (this.handle.index != RecordHandle.NUL): "setOHHandle: no handle assigned ind file" + filename;- if (otherhandle == null) {- NUL2bytes(this.headChunk, OHBYTEC + 4 * i);- } else {- if (otherhandle.index >= USAGE.allCount()) throw new kelondroException(filename, "INTERNAL ERROR, setOHHandles: handle " + i + " exceeds file size (" + handle.index + " >= " + USAGE.allCount() + ")");- int2bytes(otherhandle.index, this.headChunk, OHBYTEC + 4 * i);- }- this.headChanged = true;- }-- public byte getOHByte(final int i) {- if (i >= OHBYTEC) throw new IllegalArgumentException("getOHByte: wrong index " + i);- if (this.handle.index == RecordHandle.NUL) throw new kelondroException(filename, "Cannot load OH values");- return this.headChunk[i];- }-- public RecordHandle getOHHandle(final int i) {- if (this.handle.index == RecordHandle.NUL) throw new kelondroException(filename, "Cannot load OH values");- assert (i < OHHANDLEC): "handle index out of bounds: " + i + " in file " + filename;- final int h = bytes2int(this.headChunk, OHBYTEC + 4 * i);- return (h == RecordHandle.NUL) ? null : new RecordHandle(h);- }-- public synchronized void setValueRow(final byte[] row) throws IOException {- // if the index is defined, then write values directly to the file, else only to the object- if ((row != null) && (row.length != ROW.objectsize)) throw new IOException("setValueRow with wrong (" + row.length + ") row length instead correct: " + ROW.objectsize);-- // set values- if (this.handle.index != RecordHandle.NUL) {- setValue(row, 0, ROW.width(0), headChunk, overhead);- if (ROW.columns() > 1) setValue(row, ROW.width(0), tailchunksize, tailChunk, 0);- }- this.headChanged = true;- this.tailChanged = true;- }-- public synchronized boolean valid() {- // returns true if the key starts with non-zero byte- // this may help to detect deleted entries- return (headChunk[overhead] != 0) && ((headChunk[overhead] != -128) || (headChunk[overhead + 1] != 0));- }-- public synchronized byte[] getKey() {- // read key- return trimCopy(headChunk, overhead, ROW.width(0));- }-- public synchronized byte[] getValueRow() throws IOException {-- if (this.tailChunk == null) {- // load all values from the database file- this.tailChunk = new byte[tailchunksize];- // read values- entryFile.readFully(seekpos(this.handle) + headchunksize, this.tailChunk, 0, this.tailChunk.length);- }-- // create return value- final byte[] row = new byte[ROW.objectsize];-- // read key- System.arraycopy(headChunk, overhead, row, 0, ROW.width(0));-- // read remaining values- System.arraycopy(tailChunk, 0, row, ROW.width(0), tailchunksize);-- return row;- }-- public synchronized void commit() throws IOException {- // this must be called after all write operations to the node are- // finished-- // place the data to the file-- if (this.headChunk == null) {- // there is nothing to save- throw new kelondroException(filename, "no values to save (header missing)");- }-- final boolean doCommit = this.headChanged || this.tailChanged;-- // save head- synchronized (entryFile) {- if (this.headChanged) {- //System.out.println("WRITEH(" + filename + ", " + seekpos(this.handle) + ", " + this.headChunk.length + ")");- assert (headChunk == null) || (headChunk.length == headchunksize);- entryFile.write(seekpos(this.handle), (this.headChunk == null) ? new byte[headchunksize] : this.headChunk);- updateNodeCache();- this.headChanged = false;- }-- // save tail- if ((this.tailChunk != null) && (this.tailChanged)) {- //System.out.println("WRITET(" + filename + ", " + (seekpos(this.handle) + headchunksize) + ", " + this.tailChunk.length + ")");- assert (tailChunk == null) || (tailChunk.length == tailchunksize);- entryFile.write(seekpos(this.handle) + headchunksize, (this.tailChunk == null) ? new byte[tailchunksize] : this.tailChunk);- this.tailChanged = false;- }-- if (doCommit) entryFile.commit();- }- }-- public String toString() {- if (this.handle.index == RecordHandle.NUL) return "NULL";- String s = Integer.toHexString(this.handle.index);- RecordHandle h;- while (s.length() < 4) s = "0" + s;- try {- for (int i = 0; i < OHBYTEC; i++) s = s + ":b" + getOHByte(i);- for (int i = 0; i < OHHANDLEC; i++) {- h = getOHHandle(i);- if (h == null) s = s + ":hNULL"; else s = s + ":h" + h.toString();- }- final Row.Entry content = row().newEntry(getValueRow());- for (int i = 0; i < row().columns(); i++) s = s + ":" + ((content.empty(i)) ? "NULL" : content.getColString(i, "UTF-8").trim());- } catch (final IOException e) {- s = s + ":***LOAD ERROR***:" + e.getMessage();- }- return s;- }-- private boolean cacheSpace() {- // check for space in cache- // should be only called within a synchronized(cacheHeaders) environment- // returns true if it is allowed to add another entry to the cache- // returns false if the cache is considered to be full- if (cacheHeaders == null) return false; // no caching- if (cacheHeaders.size() == 0) return true; // nothing there to flush- if (cacheGrowStatus() == 2) return true; // no need to flush cache space-- // just delete any of the entries- if (cacheGrowStatus() <= 1) synchronized (cacheHeaders) {- cacheHeaders.removeoneb();- cacheFlush++;- }- return cacheGrowStatus() > 0;- }-- private void updateNodeCache() {- if (this.handle == null) return; // wrong access- if (this.headChunk == null) return; // nothing there to cache- if (cacheHeaders == null) return; // we do not use the cache- if (cacheSpace()) synchronized (cacheHeaders) {- // generate cache entry- //byte[] cacheEntry = new byte[headchunksize];- //System.arraycopy(headChunk, 0, cacheEntry, 0, headchunksize);-- // store the cache entry- boolean upd = false;- upd = (cacheHeaders.putb(this.handle.index, headChunk) != null);- if (upd) writeDouble++; else writeUnique++;-- //System.out.println("kelondroRecords cache4" + filename + ": cache record size = " + (memBefore - Runtime.getRuntime().freeMemory()) + " bytes" + ((newentry) ? " new" : ""));- //printCache();- } else {- // there shall be no entry in the cache. If one exists, we remove it- boolean rem = false;- rem = (cacheHeaders.removeb(this.handle.index) != null);- if (rem) cacheDelete++;- }- }- }--}diff --git a/source/de/anomic/kelondro/table/EcoTable.java b/source/de/anomic/kelondro/table/EcoTable.javaindex 22a8d9e26..59ecce13e 100644--- a/source/de/anomic/kelondro/table/EcoTable.java+++ b/source/de/anomic/kelondro/table/EcoTable.java@@ -698,14 +698,40 @@ public class EcoTable implements ObjectIndex {}- public static ObjectIndex testTable(final File f, final String testentities, final int testcase) throws IOException {+ private static byte[] testWord(final char c) {+ return new byte[]{(byte) c, 32, 32, 32};+ }++ private static String[] permutations(final int letters) {+ String p = "";+ for (int i = 0; i < letters; i++) p = p + ((char) (('A') + i));+ return permutations(p);+ }++ private static String[] permutations(final String source) {+ if (source.length() == 0) return new String[0];+ if (source.length() == 1) return new String[]{source};+ final char c = source.charAt(0);+ final String[] recres = permutations(source.substring(1));+ final String[] result = new String[source.length() * recres.length];+ for (int perm = 0; perm < recres.length; perm++) {+ result[perm * source.length()] = c + recres[perm];+ for (int pos = 1; pos < source.length() - 1; pos++) {+ result[perm * source.length() + pos] = recres[perm].substring(0, pos) + c + recres[perm].substring(pos);+ }+ result[perm * source.length() + source.length() - 1] = recres[perm] + c;+ }+ return result;+ }++ private static ObjectIndex testTable(final File f, final String testentities, final int testcase) throws IOException {if (f.exists()) FileUtils.deletedelete(f);final Row rowdef = new Row("byte[] a-4, byte[] b-4", NaturalOrder.naturalOrder);final ObjectIndex tt = new EcoTable(f, rowdef, testcase, 100, 0);byte[] b;final Row.Entry row = rowdef.newEntry();for (int i = 0; i < testentities.length(); i++) {- b = Tree.testWord(testentities.charAt(i));+ b = testWord(testentities.charAt(i));row.setCol(0, b);row.setCol(1, b);tt.put(row);@@ -713,17 +739,34 @@ public class EcoTable implements ObjectIndex {return tt;}- public static void bigtest(final int elements, final File testFile, final int testcase) {+ private static int countElements(final ObjectIndex t) {+ int count = 0;+ try {+ final Iterator<Row.Entry> iter = t.rows();+ Row.Entry row;+ while (iter.hasNext()) {+ count++;+ row = iter.next();+ if (row == null) System.out.println("ERROR! null element found");+ // else System.out.println("counted element: " + new+ // String(n.getKey()));+ }+ } catch (final IOException e) {+ }+ return count;+ }++ public static void bigtest(final int elements, final File testFile, final int testcase) {System.out.println("starting big test with " + elements + " elements:");final long start = System.currentTimeMillis();- final String[] s = Tree.permutations(elements);+ final String[] s = permutations(elements);ObjectIndex tt;try {for (int i = 0; i < s.length; i++) {System.out.println("*** probing tree " + i + " for permutation " + s[i]);// generate tree and delete elementstt = testTable(testFile, s[i], testcase);- if (Tree.countElements(tt) != tt.size()) {+ if (countElements(tt) != tt.size()) {System.out.println("wrong size for " + s[i]);}tt.close();@@ -731,8 +774,8 @@ public class EcoTable implements ObjectIndex {tt = testTable(testFile, s[i], testcase);// delete by permutation jfor (int elt = 0; elt < s[j].length(); elt++) {- tt.remove(Tree.testWord(s[j].charAt(elt)));- if (Tree.countElements(tt) != tt.size()) {+ tt.remove(testWord(s[j].charAt(elt)));+ if (countElements(tt) != tt.size()) {System.out.println("ERROR! wrong size for probe tree " + s[i] + "; probe delete " + s[j] + "; position " + elt);}}diff --git a/source/de/anomic/kelondro/table/FixedWidthArray.java b/source/de/anomic/kelondro/table/FixedWidthArray.javadeleted file mode 100644index 4fac433c1..000000000--- a/source/de/anomic/kelondro/table/FixedWidthArray.java+++ /dev/null@@ -1,227 +0,0 @@-// kelondroArray.java-// -------------------// part of the Kelondro Database-// (C) by Michael Peter Christen; [email protected]-// first published on http://www.anomic.de-// Frankfurt, Germany, 2005-// last major change: 20.06.2005-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--/*- This class extends the kelondroRecords and adds a array structure-*/--package de.anomic.kelondro.table;---import java.io.File;-import java.io.IOException;-import java.util.Iterator;-import java.util.Map;-import java.util.TreeMap;--import de.anomic.kelondro.index.ObjectArray;-import de.anomic.kelondro.index.Row;-import de.anomic.kelondro.io.RandomAccessInterface;-import de.anomic.kelondro.order.NaturalOrder;-import de.anomic.kelondro.util.FileUtils;--public class FixedWidthArray extends FullRecords implements ObjectArray {-- // define the Over-Head-Array- private static short thisOHBytes = 0; // our record definition does not need extra bytes- private static short thisOHHandles = 0; // and no handles-- public FixedWidthArray(final File file, final Row rowdef, final int intprops) throws IOException {- // this creates a new array- //super(file, true, -1, thisOHBytes, thisOHHandles, rowdef, intprops, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */);- super(file, thisOHBytes, thisOHHandles, rowdef, intprops, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */);- if (!(super.fileExisted)) {- for (int i = 0; i < intprops; i++) {- setHandle(i, new RecordHandle(RecordHandle.NUL));- }- // store column description- for (int i = 0; i < rowdef.columns(); i++) {- try {super.setText(i, rowdef.column(i).toString().getBytes());} catch (final IOException e) {}- }- }- }-- public FixedWidthArray(final RandomAccessInterface ra, final String filename, final Row rowdef, final int intprops) throws IOException {- // this creates a new array- //super(ra, filename, true, -1, thisOHBytes, thisOHHandles, rowdef, intprops, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */, false);- super(ra, filename, thisOHBytes, thisOHHandles, rowdef, intprops, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */, false);- for (int i = 0; i < intprops; i++) {- setHandle(i, new RecordHandle(0));- }- // store column description- for (int i = 0; i < rowdef.columns(); i++) {- try {super.setText(i, rowdef.column(i).toString().getBytes());} catch (final IOException e) {}- }- }-- public static FixedWidthArray open(final File file, final Row rowdef, final int intprops) {- try {- return new FixedWidthArray(file, rowdef, intprops);- } catch (final IOException e) {- FileUtils.deletedelete(file);- try {- return new FixedWidthArray(file, rowdef, intprops);- } catch (final IOException ee) {- e.printStackTrace();- ee.printStackTrace();- System.exit(-1);- return null;- }- }- }-- public synchronized void set(final int index, final Row.Entry rowentry) throws IOException {- // this writes a row without reading the row from the file system first-- // create a node at position index with rowentry- final RecordHandle h = new RecordHandle(index);- (new EcoNode(h, (rowentry == null) ? null : rowentry.bytes(), 0)).commit();- // attention! this newNode call wants that the OH bytes are passed within the bulkchunk- // field. Here, only the rowentry.bytes() raw payload is passed. This is valid, because- // the OHbytes and OHhandles are zero.- }-- public synchronized void setMultiple(final TreeMap<Integer, Row.Entry> rows) throws IOException {- final Iterator<Map.Entry<Integer, Row.Entry>> i = rows.entrySet().iterator();- Map.Entry<Integer, Row.Entry> entry;- int k;- while (i.hasNext()) {- entry = i.next();- k = entry.getKey().intValue();- set(k, entry.getValue());- }- }-- public synchronized Row.Entry getIfValid(final int index) throws IOException {- final byte[] b = (new EcoNode(new RecordHandle(index))).getValueRow();- if (b[0] == 0) return null;- if ((b[0] == -128) && (b[1] == 0)) return null;- return row().newEntry(b);- }-- public synchronized Row.Entry get(final int index) throws IOException {- return row().newEntry(new EcoNode(new RecordHandle(index)).getValueRow());- }-- protected synchronized int seti(final int index, final int value) throws IOException {- final int before = getHandle(index).hashCode();- setHandle(index, new RecordHandle(value));- return before;- }-- protected synchronized int geti(final int index) {- return getHandle(index).hashCode();- }-- public synchronized int add(final Row.Entry rowentry) throws IOException {- // adds a new rowentry, but re-uses a previously as-deleted marked entry- final Node n = new EcoNode(rowentry.bytes());- n.commit();- return n.handle().hashCode();- }-- public synchronized void remove(final int index) throws IOException {- assert (index < (super.free() + super.size())) : "remove: index " + index + " out of bounds " + (super.free() + super.size());-- // get the node at position index- final RecordHandle h = new RecordHandle(index);- final Node n = new EcoNode(h);-- // erase the row- n.setValueRow(null);- n.commit();-- // mark row as deleted so it can be re-used- deleteNode(h);- }-- public void print() throws IOException {- System.out.println("PRINTOUT of table, length=" + size());- Row.Entry row;- for (int i = 0; i < (super.free() + super.size()); i++) {- System.out.print("row " + i + ": ");- row = get(i);- for (int j = 0; j < row.columns(); j++) System.out.print(((row.empty(j)) ? "NULL" : row.getColString(j, "UTF-8")) + ", ");- System.out.println();- }- System.out.println("EndOfTable");- }-- public static void main(final String[] args) {- //File f = new File("d:\\\\mc\\privat\\fixtest.db");- final File f = new File("/Users/admin/fixtest.db");- final Row rowdef = new Row("byte[] a-12, byte[] b-4", NaturalOrder.naturalOrder);- try {- System.out.println("erster Test");- f.delete();- FixedWidthArray k = new FixedWidthArray(f, rowdef, 6);- k.set(3, k.row().newEntry(new byte[][]{- "test123".getBytes(), "abcd".getBytes()}));- k.add(k.row().newEntry(new byte[][]{- "test456".getBytes(), "efgh".getBytes()}));- k.close();-- k = new FixedWidthArray(f, rowdef, 6);- System.out.println(k.get(2).toString());- System.out.println(k.get(3).toString());- k.close();-- System.out.println("zweiter Test");- f.delete();- k = new FixedWidthArray(f, rowdef, 6);- k.add(k.row().newEntry(new byte[][]{"a".getBytes(), "xxxx".getBytes()}));- k.add(k.row().newEntry(new byte[][]{"b".getBytes(), "xxxx".getBytes()}));- k.remove(0);-- k.add(k.row().newEntry(new byte[][]{"c".getBytes(), "xxxx".getBytes()}));- k.add(k.row().newEntry(new byte[][]{"d".getBytes(), "xxxx".getBytes()}));- k.add(k.row().newEntry(new byte[][]{"e".getBytes(), "xxxx".getBytes()}));- k.add(k.row().newEntry(new byte[][]{"f".getBytes(), "xxxx".getBytes()}));- k.remove(0);- k.remove(1);-- k.print();- k.print();- k.close();--- System.out.println("dritter Test");- f.delete();- k = new FixedWidthArray(f, rowdef, 6);- for (int i = 1; i <= 200; i = i * 2) {- for (int j = 0; j < i*2; j++) {- k.add(k.row().newEntry(new byte[][]{(Integer.toString(i) + "-" + Integer.toString(j)).getBytes(), "xxxx".getBytes()}));- }- for (int j = 0; j < i; j++) {- k.remove(j);- }- }- k.print();- k.print();- k.close();-- } catch (final IOException e) {- e.printStackTrace();- }- }--}diff --git a/source/de/anomic/kelondro/table/FlexWidthArray.java b/source/de/anomic/kelondro/table/FlexWidthArray.javadeleted file mode 100644index 7bf363ace..000000000--- a/source/de/anomic/kelondro/table/FlexWidthArray.java+++ /dev/null@@ -1,430 +0,0 @@-// kelondroFlexWidthArray.java-// (C) 2006 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 01.06.2006 on http://www.anomic.de-//-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $-// $LastChangedRevision: 1986 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA---package de.anomic.kelondro.table;--import java.io.File;-import java.io.IOException;-import java.util.Iterator;-import java.util.List;-import java.util.Map;-import java.util.TreeMap;--import de.anomic.kelondro.index.ObjectArray;-import de.anomic.kelondro.index.Column;-import de.anomic.kelondro.index.Row;-import de.anomic.kelondro.order.NaturalOrder;-import de.anomic.kelondro.util.FileUtils;-import de.anomic.kelondro.util.kelondroException;-import de.anomic.yacy.logging.Log;--public class FlexWidthArray implements ObjectArray {-- protected FixedWidthArray[] col;- protected Row rowdef;- protected File path;- protected String tablename;- protected String filename;-- public FlexWidthArray(final File path, final String tablename, final Row rowdef, final boolean resetOnFail) {- this.path = path;- this.rowdef = rowdef;- this.tablename = tablename;- try {- init();- } catch (final IOException e) {- if (resetOnFail) {- Log.logSevere("kelondroFlexWidthArray", "IOException during initialization of " + new File(path, tablename).toString() + ": reset");- delete(path, tablename);- try {- init();- } catch (final IOException e1) {- e1.printStackTrace();- throw new kelondroException("IOException during initialization of " + new File(path, tablename).toString() + ": cannot reset: " + e1.getMessage());- }- } else {- throw new kelondroException("IOException during initialization of " + new File(path, tablename).toString() + ": not allowed to reset: " + e.getMessage());- }- } catch (final kelondroException e) {- if (resetOnFail) {- Log.logSevere("kelondroFlexWidthArray", "kelondroException during initialization of " + new File(path, tablename).toString() + ": reset");- delete(path, tablename);- try {- init();- } catch (final IOException e1) {- e1.printStackTrace();- throw new kelondroException("kelondroException during initialization of " + new File(path, tablename).toString() + ": cannot reset: " + e1.getMessage());- }- } else {- throw new kelondroException("kelondroException during initialization of " + new File(path, tablename).toString() + ": not allowed to reset: " + e.getMessage());- }- }- }-- public void init() throws IOException {-- // initialize columns- col = new FixedWidthArray[rowdef.columns()];- String check = "";- for (int i = 0; i < rowdef.columns(); i++) {- col[i] = null;- check += '_';- }-- // check if table directory exists- final File tabledir = new File(path, tablename);- if (tabledir.exists()) {- if (!(tabledir.isDirectory())) throw new IOException("path " + tabledir.toString() + " must be a directory");- } else {- tabledir.mkdirs();- tabledir.mkdir();- }- this.filename = tabledir.getCanonicalPath();-- // save/check property file for this array- /*- final File propfile = new File(tabledir, "properties");- Map<String, String> props = new HashMap<String, String>();- if (propfile.exists()) {- props = serverFileUtils.loadMap(propfile);- final String stored_rowdef = props.get("rowdef");- if ((stored_rowdef != null) && (!(rowdef.subsumes(new Row(stored_rowdef, rowdef.objectOrder, 0))))) {- System.out.println("FATAL ERROR: stored rowdef '" + stored_rowdef + "' does not match with new rowdef '" +- rowdef + "' for flex table '" + path + "', table " + tablename);- System.exit(-1);- }- }- props.put("rowdef", rowdef.toString());- serverFileUtils.saveMap(propfile, props, "FlexWidthArray properties");- */-- // open existing files- final String[] files = tabledir.list();- for (int i = 0; i < files.length; i++) {- if ((files[i].startsWith("col.") && (files[i].endsWith(".list")))) {- final int colstart = Integer.parseInt(files[i].substring(4, 7));- final int colend = (files[i].charAt(7) == '-') ? Integer.parseInt(files[i].substring(8, 11)) : colstart;-- final Column columns[] = new Column[colend - colstart + 1];- for (int j = colstart; j <= colend; j++) columns[j-colstart] = rowdef.column(j);- col[colstart] = new FixedWidthArray(new File(tabledir, files[i]), new Row(columns, (colstart == 0) ? rowdef.objectOrder : NaturalOrder.naturalOrder), 16);- for (int j = colstart; j <= colend; j++) check = check.substring(0, j) + "X" + check.substring(j + 1);- }- }-- // check if all columns are there- int p, q;- while ((p = check.indexOf('_')) >= 0) {- q = p;- if (p != 0) {- while ((q <= check.length() - 1) && (check.charAt(q) == '_')) q++;- q--;- }- // create new array file- final Column[] columns = new Column[q - p + 1];- for (int j = p; j <= q; j++) {- columns[j - p] = rowdef.column(j);- check = check.substring(0, j) + "X" + check.substring(j + 1);- }- col[p] = new FixedWidthArray(new File(tabledir, colfilename(p, q)), new Row(columns, (p == 0) ? rowdef.objectOrder : NaturalOrder.naturalOrder), 16);- }- }-- public final String filename() {- return this.filename;- }-- public static int staticsize(final File path, final String tablename) {-- // check if table directory exists- final File tabledir = new File(path, tablename);- if (tabledir.exists()) {- if (!(tabledir.isDirectory())) return 0;- } else {- return 0;- }-- // open existing files- final File file = new File(tabledir, "col.000.list");- return AbstractRecords.staticsize(file);- }-- public static void delete(final File path, final String tablename) {- final File tabledir = new File(path, tablename);- if (!(tabledir.exists())) return;- if ((!(tabledir.isDirectory()))) {- FileUtils.deletedelete(tabledir);- return;- }-- final String[] files = tabledir.list();- for (int i = 0; i < files.length; i++) {- FileUtils.deletedelete(new File(tabledir, files[i]));- }-- FileUtils.deletedelete(tabledir);- }-- public void reset() throws IOException {- this.close();- delete(path, tablename);- this.init();- }-- public synchronized void close() {- if (col != null) {- for (int i = 0; i < col.length; i++) {- if (col[i] != null) {- // a column can be null, this is normal- col[i].close();- col[i] = null;- }- }- }- }-- protected static final String colfilename(final int start, final int end) {- String f = Integer.toString(end);- while (f.length() < 3) f = "0" + f;- if (start == end) return "col." + f + ".list";- f = Integer.toString(start) + "-" + f;- while (f.length() < 7) f = "0" + f;- return "col." + f + ".list";- }--- public Row row() {- return rowdef;- }-- public int size() {- //assert ((rowdef.columns() == 1) || (col[0].size() == col[1].size())) : "col[0].size() = " + col[0].size() + ", col[1].size() = " + col[1].size() + ", file = " + filename;- return col[0].size();- }-- public synchronized void setMultiple(final TreeMap<Integer, Row.Entry> entries) throws IOException {- // a R/W head path-optimized option to write a set of entries- Iterator<Map.Entry<Integer, Row.Entry>> i;- Map.Entry<Integer, Row.Entry> entry;- Row.Entry rowentry, e;- int c = 0, index;- // go across each file- while (c < rowdef.columns()) {- i = entries.entrySet().iterator();- while (i.hasNext()) {- entry = i.next();- index = entry.getKey().intValue();- rowentry = entry.getValue();- assert rowentry.objectsize() == this.rowdef.objectsize;-- e = col[c].row().newEntry(rowentry.bytes(), rowdef.colstart[c], false);- col[c].set(index, e);- }- c = c + col[c].row().columns();- }- }-- public synchronized void set(final int index, final Row.Entry rowentry) throws IOException {- assert rowentry.objectsize() == this.rowdef.objectsize;- int c = 0;- Row.Entry e;- final byte[] reb = rowentry.bytes();- while (c < rowdef.columns()) {- e = col[c].row().newEntry(reb, rowdef.colstart[c], false);- col[c].set(index, e);- c = c + col[c].row().columns();- }- }-- public synchronized int add(final Row.Entry rowentry) throws IOException {- assert rowentry.objectsize() == this.rowdef.objectsize;- int index = -1;- final byte[] reb = rowentry.bytes();- index = col[0].add(col[0].row().newEntry(reb, 0, false));- int c = col[0].row().columns();-- while (c < rowdef.columns()) {- col[c].set(index, col[c].row().newEntry(reb, rowdef.colstart[c], false));- c = c + col[c].row().columns();- }- return index;- }-- @SuppressWarnings("unchecked")- protected synchronized TreeMap<Integer, byte[]> addMultiple(final List<Row.Entry> rows) throws IOException {- // result is a Integer/byte[] relation- // of newly added rows (index, key)- final TreeMap<Integer, byte[]> indexref = new TreeMap<Integer, byte[]>();- Iterator<Row.Entry> i;- Row.Entry rowentry;- // prepare storage for other columns- final TreeMap<Integer, Row.Entry>[] colm = new TreeMap[col.length];- for (int j = 0; j < col.length; j++) {- if (col[j] == null) colm[j] = null; else colm[j] = new TreeMap<Integer, Row.Entry>();- }- i = rows.iterator();- while (i.hasNext()) {- rowentry = i.next();- assert rowentry.objectsize() == this.rowdef.objectsize;-- Row.Entry e;- int index = -1;- final byte[] reb = rowentry.bytes();- e = col[0].row().newEntry(reb, 0, false);- index = col[0].add(e);- int c = col[0].row().columns();-- while (c < rowdef.columns()) {- e = col[c].row().newEntry(reb, rowdef.colstart[c], false);- // remember write to column, but do not write directly- colm[c].put(Integer.valueOf(index), e); // col[c].set(index,e);- c = c + col[c].row().columns();- }- indexref.put(Integer.valueOf(index), rowentry.getColBytes(0));- }- // write the other columns- for (int j = 1; j < col.length; j++) {- if (col[j] != null) col[j].setMultiple(colm[j]);- }- // return references to entries with key- return indexref;- }-- public synchronized Row.Entry get(final int index) throws IOException {- Row.Entry e = col[0].getIfValid(index);- //assert e != null;- if (e == null) return null; // probably a deleted entry- final Row.Entry p = rowdef.newEntry();- p.setCol(0, e.getColBytes(0));- int r = col[0].row().columns();- while (r < rowdef.columns()) {- e = col[r].get(index);- for (int i = 0; i < col[r].row().columns(); i++) {- p.setCol(r + i, e.getColBytes(i));- }- r = r + col[r].row().columns();- }- return p;- }-- public synchronized Row.Entry getOmitCol0(final int index, final byte[] col0) throws IOException {- assert col[0].row().columns() == 1;- final Row.Entry p = rowdef.newEntry();- Row.Entry e;- p.setCol(0, col0);- int r = 1;- while (r < rowdef.columns()) {- e = col[r].get(index);- for (int i = 0; i < col[r].row().columns(); i++) {- p.setCol(r + i, e.getColBytes(i));- }- r = r + col[r].row().columns();- }- return p;- }-- public synchronized void remove(final int index) throws IOException {- int r = 0;-- // remove only from the first column- col[0].remove(index);- r = r + col[r].row().columns();-- // the other columns will be blanked out only- while (r < rowdef.columns()) {- col[r].set(index, null);- r = r + col[r].row().columns();- }- }-- public void print() throws IOException {- System.out.println("PRINTOUT of table, length=" + size());- Row.Entry row;- for (int i = 0; i < (col[0].free() + col[0].size()); i++) {- System.out.print("row " + i + ": ");- row = get(i);- System.out.println(row.toString());- //for (int j = 0; j < row().columns(); j++) System.out.print(((row.empty(j)) ? "NULL" : row.getColString(j, "UTF-8")) + ", ");- //System.out.println();- }- System.out.println("EndOfTable");- }-- public static void main(final String[] args) {- //File f = new File("d:\\\\mc\\privat\\fixtest.db");- final File f = new File("/Users/admin/");- final Row rowdef = new Row("byte[] a-12, byte[] b-4", NaturalOrder.naturalOrder);- final String testname = "flextest";- try {- System.out.println("erster Test");- FlexWidthArray.delete(f, testname);- FlexWidthArray k = new FlexWidthArray(f, "flextest", rowdef, true);- k.add(k.row().newEntry(new byte[][]{"a".getBytes(), "xxxx".getBytes()}));- k.add(k.row().newEntry(new byte[][]{"b".getBytes(), "xxxx".getBytes()}));- k.remove(0);-- k.add(k.row().newEntry(new byte[][]{"c".getBytes(), "xxxx".getBytes()}));- k.add(k.row().newEntry(new byte[][]{"d".getBytes(), "xxxx".getBytes()}));- k.add(k.row().newEntry(new byte[][]{"e".getBytes(), "xxxx".getBytes()}));- k.add(k.row().newEntry(new byte[][]{"f".getBytes(), "xxxx".getBytes()}));- k.remove(0);- k.remove(1);-- k.print();- k.col[0].print();- k.col[1].print();- k.close();--- System.out.println("zweiter Test");- FlexWidthArray.delete(f, testname);- //k = kelondroFlexWidthArray.open(f, "flextest", rowdef);- for (int i = 1; i <= 20; i = i * 2) {- System.out.println("LOOP: " + i);- k = new FlexWidthArray(f, "flextest", rowdef, true);- for (int j = 0; j < i*2; j++) {- k.add(k.row().newEntry(new byte[][]{(Integer.toString(i) + "-" + Integer.toString(j)).getBytes(), "xxxx".getBytes()}));- }- k.close();- k = new FlexWidthArray(f, "flextest", rowdef, true);- for (int j = 0; j < i; j++) {- k.remove(i*2 - j - 1);- }- k.close();- }- k = new FlexWidthArray(f, "flextest", rowdef, true);- k.print();- k.col[0].print();- k.close();-- } catch (final IOException e) {- e.printStackTrace();- }- }-- public void deleteOnExit() {- for (int i = 0; i < this.col.length; i++) this.col[i].deleteOnExit();- }-}diff --git a/source/de/anomic/kelondro/table/FullRecords.java b/source/de/anomic/kelondro/table/FullRecords.javaindex ead62d49b..69d46e460 100644--- a/source/de/anomic/kelondro/table/FullRecords.java+++ b/source/de/anomic/kelondro/table/FullRecords.java@@ -56,12 +56,6 @@ public class FullRecords extends AbstractRecords {super(ra, filename, true, ohbytec, ohhandlec, rowdef, FHandles, txtProps, txtPropWidth, exitOnFail);recordTracker.put(this.filename, this);}-- public FullRecords(- final RandomAccessInterface ra, final String filename) throws IOException{- super(ra, filename, true);- recordTracker.put(this.filename, this);- }public static final Iterator<String> filenames() {// iterates string objects; all file names from record trackerdiff --git a/source/de/anomic/kelondro/table/Hashtable.java b/source/de/anomic/kelondro/table/Hashtable.javadeleted file mode 100644index 1f074d655..000000000--- a/source/de/anomic/kelondro/table/Hashtable.java+++ /dev/null@@ -1,253 +0,0 @@-// kelondroHashtable.java-// -------------------// part of the Kelondro Database-// (C) by Michael Peter Christen; [email protected]-// first published on http://www.anomic.de-// Frankfurt, Germany, 2005-// last major change: 21.06.2005-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--/*-- we implement a hashtable based on folded binary trees- each hight in these binary trees represents one step of rehasing- the re-hashing is realised by extending the number of relevant bits in the given hash- We construct the binary tree as follows- - there exists no root node- - at height-1 are 2 nodes, and can be accessed by using only the least significant bit of the hash- - at height-2 are 4 nodes, addresses by (hash & 3) - mapping the 2 lsb of the hash- - at height-3 are 8 nodes, addresses by (hash & 7)- - .. and so on.- The number of nodes N(k) that are needed for a tree of height-k is-- N(k) = 2**k + N(k-1) = 2**(k + 1) - 2 [where k > 0]-- We fold this tree by putting all heights of the tree in a sequence-- Computation of the position (the index) of a node:- given:- hash h, with k significant bits (representing a height-k): h|k- then the position of a node node(h,k) is-- node(h,k) = N(k - 1) + h|k [where k > 0]-- We use these nodes to sequentially store a hash h at position node(h, 1), and- if that fails on node(h, 2), node(h, 3) and so on.-- This is highly inefficient for the most heights k = 1, ..., (?)- The 'inefficient-border' depends on the number of elements that we want to store.-- We therefore introduce an offset o which is the number of bits that are not used- at the beginning of (re-)hashing. But even if these o re-hasing steps are not done,- all bits of the hash are relevant.- Now the number of nodes N(k) that are needed is computed by N(k,o):-- N(k,o) = N(k) - N(o) = 2**(k + 1) - 2**(o + 1) [where k > o, o >= 0]-- When o=0 then this is equivalent to N(k).-- The node-formula must be adopted as well-- node(h,k,o) = N(k - 1, o) + h|k [where k > o, o >= 0]-- So if you set an offset o, this leads to a minimum number of nodes- at level k=o+1: node(0,o + 1,o) = N(o, o) = 0 (position of the first entry)-- Computatiion of the maxlen 'maxk', the maximum height of the tree for a given- number of maximum entries 'maxsize' in the hashtable:- maxk shall be computed in such a way, that N(k,o) <= maxsize, for any o or k- This means paricualary, that-- node(h,k,o) < maxsize-- for h|k we must consider the worst case:-- h|k (by maxk) = 2**k - 1-- therefore-- node(h,maxk,o) < maxsize- N(maxk - 1, o) + h|maxk < maxsize [where maxk > o, o >= 0]- 2**maxk - 2**(o + 1) + 2**maxk - 1 < maxsize [where maxk > o, o >= 0]- 2**maxk - 2**(o + 1) + 2**maxk < maxsize + 1 [where maxk > o, o >= 0]- 2**maxk + 2**maxk < maxsize + 2**(o + 1) + 1 [where maxk > o, o >= 0]- 2**(maxk+1) < maxsize + 2**(o + 1) + 1 [where maxk > o, o >= 0]- maxk < log2(maxsize + 2**(o + 1) + 1) [where maxk > o, o >= 0]-- setting maxk to-- maxk = log2(maxsize)-- will make this relation true in any case, even if maxk = log2(maxsize) + 1- would also be correct in some cases-- Now we can use the following formula to create the folded binary hash tree:-- node(h,k,o) = 2**k - 2**(o + 1) + h|k-- to compute the node index and-- maxk = log2(maxsize)-- to compute the upper limit of re-hashing--- */--package de.anomic.kelondro.table;---import java.io.File;-import java.io.IOException;--import de.anomic.kelondro.index.Column;-import de.anomic.kelondro.index.Row;-import de.anomic.kelondro.order.Base64Order;-import de.anomic.kelondro.util.SetTools;--public class Hashtable {-- private final FixedWidthArray hashArray;- protected int offset;- protected int maxk;- private int maxrehash;- private Row.Entry dummyRow;-- private static final byte[] dummyKey = Base64Order.enhancedCoder.encodeLong(0, 5).getBytes();-- public Hashtable(final File file, final Row rowdef, final int offset, final int maxsize, final int maxrehash) throws IOException {- // this creates a new hashtable- // the key element is not part of the columns array- // this is unlike the kelondroTree, where the key is part of a row- // the offset is a number of bits that is omitted in the folded tree hierarchy- // a good number for offset is 8- // the maxsize number is the maximum number of elements in the hashtable- // this number is needed to omit grow of the table in case of re-hashing- // the maxsize is re-computed to a virtual folding height and will result in a tablesize- // less than the given maxsize. The actual maxsize can be retrieved by maxsize()- final boolean fileExisted = file.exists();- this.hashArray = new FixedWidthArray(file, extCol(rowdef), 6);- if (fileExisted) {- this.offset = hashArray.geti(0);- this.maxk = hashArray.geti(1);- this.maxrehash = hashArray.geti(2);- } else {- this.offset = offset;- this.maxk = SetTools.log2a(maxsize); // equal to |log2(maxsize)| + 1- if (this.maxk >= SetTools.log2a(maxsize + power2(offset + 1) + 1) - 1) this.maxk--;- this.maxrehash = maxrehash;- dummyRow = this.hashArray.row().newEntry();- dummyRow.setCol(0, dummyKey);- //for (int i = 0; i < hashArray.row().columns(); i++)- hashArray.seti(0, this.offset);- hashArray.seti(1, this.maxk);- hashArray.seti(2, this.maxrehash);- }- }-- private Row extCol(final Row rowdef) {- final Column[] newCol = new Column[rowdef.columns() + 1];- newCol[0] = new Column("Cardinal key-4 {b256}");- for (int i = 0; i < rowdef.columns(); i++) newCol[i + 1] = rowdef.column(i);- return new Row(newCol, rowdef.objectOrder);- }-- public static int power2(int x) {- int p = 1;- while (x > 0) {p = p << 1; x--;}- return p;- }-- public synchronized byte[][] get(final int key) throws IOException {- final Object[] search = search(new Hash(key));- if (search[1] == null) return null;- final byte[][] row = (byte[][]) search[1];- final byte[][] result = new byte[row.length - 1][];- System.arraycopy(row, 1, result, 0, row.length - 1);- return result;- }-- public synchronized Row.Entry put(final int key, final Row.Entry rowentry) throws IOException {- final Hash hash = new Hash(key);-- // find row- final Object[] search = search(hash);- Row.Entry oldhkrow;- final int rowNumber = ((Integer) search[0]).intValue();- if (search[1] == null) {- oldhkrow = null;- } else {- oldhkrow = (Row.Entry) search[1];- }-- // make space- while (rowNumber >= hashArray.size()) hashArray.set(hashArray.size(), dummyRow);-- // write row- final Row.Entry newhkrow = hashArray.row().newEntry();- newhkrow.setCol(0, hash.key());- newhkrow.setCol(1, rowentry.bytes());- hashArray.set(rowNumber, newhkrow);- return (oldhkrow == null ? null : hashArray.row().newEntry(oldhkrow.getColBytes(1)));- }-- private Object[] search(final Hash hash) throws IOException {- Row.Entry hkrow;- int rowKey;- int rowNumber;- do {- rowNumber = hash.node();- if (rowNumber >= hashArray.size()) return new Object[]{Integer.valueOf(rowNumber), null};- hkrow = hashArray.get(rowNumber);- rowKey = (int) hkrow.getColLong(0);- if (rowKey == 0) return new Object[]{Integer.valueOf(rowNumber), null};- hash.rehash();- } while (rowKey != hash.key());- return new Object[]{Integer.valueOf(rowNumber), hkrow};- }--- private class Hash {- int key;- int hash;- int depth;- public Hash(final int key) {- this.key = key;- this.hash = key;- this.depth = offset + 1;- }- public int key() {- return key;- }- private int hash() {- return hash & (power2(depth) - 1); // apply mask- }- public int depth() {- return depth;- }- public void rehash() {- depth++;- if (depth > maxk) {- depth = offset + 1;- hash = (int) ((5 * (long) hash - 7) / 3 + 13);- }- }- public int node() {- // node(h,k,o) = 2**k - 2**(o + 1) + h|k- return power2(depth) - power2(offset + 1) + hash();- }- }-}diff --git a/source/de/anomic/kelondro/table/SplitTable.java b/source/de/anomic/kelondro/table/SplitTable.javaindex b2e04adfd..cf1077b27 100644--- a/source/de/anomic/kelondro/table/SplitTable.java+++ b/source/de/anomic/kelondro/table/SplitTable.java@@ -209,12 +209,28 @@ public class SplitTable implements ObjectIndex {for (int i = 0; i < l.length; i++) {if (l[i].startsWith(prefix)) {final File f = new File(path, l[i]);- if (f.isDirectory()) FlexWidthArray.delete(path, l[i]); else FileUtils.deletedelete(f);+ if (f.isDirectory()) delete(path, l[i]); else FileUtils.deletedelete(f);}}init(true);}+ public static void delete(final File path, final String tablename) {+ final File tabledir = new File(path, tablename);+ if (!(tabledir.exists())) return;+ if ((!(tabledir.isDirectory()))) {+ FileUtils.deletedelete(tabledir);+ return;+ }++ final String[] files = tabledir.list();+ for (int i = 0; i < files.length; i++) {+ FileUtils.deletedelete(new File(tabledir, files[i]));+ }++ FileUtils.deletedelete(tabledir);+ }+public String filename() {return new File(path, prefix).toString();}diff --git a/source/de/anomic/kelondro/table/Tree.java b/source/de/anomic/kelondro/table/Tree.javadeleted file mode 100644index 94293ed6f..000000000--- a/source/de/anomic/kelondro/table/Tree.java+++ /dev/null@@ -1,1626 +0,0 @@-// kelondroTree.java-// ------------------------// part of The Kelondro Database-// (C) by Michael Peter Christen; [email protected]-// first published on http://www.anomic.de-// Frankfurt, Germany, 2004-// last major change: 07.02.2005-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--/*- This class extends the kelondroRecords and adds a tree structure-*/--package de.anomic.kelondro.table;--import java.io.BufferedReader;-import java.io.File;-import java.io.FileReader;-import java.io.IOException;-import java.io.RandomAccessFile;-import java.util.ArrayList;-import java.util.Comparator;-import java.util.HashSet;-import java.util.Iterator;-import java.util.LinkedList;-import java.util.List;-import java.util.Map;-import java.util.StringTokenizer;-import java.util.TreeMap;-import java.util.TreeSet;-import java.util.Vector;-import java.util.logging.Logger;--import de.anomic.kelondro.index.Row;-import de.anomic.kelondro.index.RowCollection;-import de.anomic.kelondro.index.ObjectIndex;-import de.anomic.kelondro.order.ByteOrder;-import de.anomic.kelondro.order.CloneableIterator;-import de.anomic.kelondro.order.NaturalOrder;-import de.anomic.kelondro.util.FileUtils;-import de.anomic.kelondro.util.kelondroException;-import de.anomic.yacy.logging.Log;--public class Tree extends CachedRecords implements ObjectIndex {-- // logging (This probably needs someone to initialize the java.util.logging.* facilities);- public static final Logger log = Logger.getLogger("KELONDRO");-- // define the Over-Head-Array- protected static final short thisOHBytes = 2; // our record definition of two bytes- protected static final short thisOHHandles = 3; // and three handles overhead- protected static final short thisFHandles = 1; // file handles: one for a root pointer-- // define pointers for OH array access- protected static final int magic = 0; // pointer for OHByte-array: marker for Node purpose; defaults to 1- protected static final int balance = 1; // pointer for OHByte-array: balance value of tree node; balanced = 0-- protected static final int parent = 0; // pointer for OHHandle-array: handle()-Value of parent Node- protected static final int leftchild = 1; // pointer for OHHandle-array: handle()-Value of left child Node- protected static final int rightchild = 2; // pointer for OHHandle-array: handle()-Value of right child Node-- protected static final int root = 0; // pointer for FHandles-array: pointer to root node-- // class variables- private final Search writeSearchObj = new Search();- protected Comparator<String> loopDetectionOrder;- protected int readAheadChunkSize = 100;- protected long lastIteratorCount = readAheadChunkSize;-- /**- * Deprecated Class. Please use kelondroEcoTable instead- */- @Deprecated- public Tree(final File file, final boolean useNodeCache, final long preloadTime, final Row rowdef) throws IOException {- this(file, useNodeCache, preloadTime, rowdef, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */);- }-- @Deprecated- public Tree(final File file, final boolean useNodeCache, final long preloadTime, final Row rowdef, final int txtProps, final int txtPropsWidth) throws IOException {- // opens an existing tree file or creates a new tree file- super(file, useNodeCache, preloadTime,- thisOHBytes, thisOHHandles, rowdef,- thisFHandles, txtProps, txtPropsWidth);- if (!fileExisted) {- // create new file structure- setHandle(root, null); // define the root value- }- super.setLogger(log);- this.loopDetectionOrder = new ByteOrder.StringOrder(rowdef.objectOrder);- }-- @Deprecated- public static final Tree open(final File file, final boolean useNodeCache, final long preloadTime, final Row rowdef, final int txtProps, final int txtPropsWidth) {- // opens new or existing file; in case that any error occur the file is deleted again and it is tried to create the file again- // if that fails, the method returns null- try {- return new Tree(file, useNodeCache, preloadTime, rowdef, txtProps, txtPropsWidth);- } catch (final IOException e) {- FileUtils.deletedelete(file);- try {- return new Tree(file, useNodeCache, preloadTime, rowdef, txtProps, txtPropsWidth);- } catch (final IOException ee) {- log.severe("cannot open or create file " + file.toString());- e.printStackTrace();- ee.printStackTrace();- return null;- }- }- }-- public void clear() throws IOException {- super.clear();- setHandle(root, null);- }-- private void commitNode(final Node n) throws IOException {- //kelondroHandle left = n.getOHHandle(leftchild);- //kelondroHandle right = n.getOHHandle(rightchild);- n.commit();- }-- // the has-property in kelondroTree should not be used, because it has the effect of doubling the IO activity in case that- // the result is 'true'. Whenever possible, please use the get method, store the result in a dummy value and test the result- // by comparing it with null.- public boolean has(final byte[] key) {- boolean result;- synchronized (writeSearchObj) {- try {- writeSearchObj.process(key);- result = writeSearchObj.found();- } catch (final IOException e) {- result = false;- }- }- return result;- }-- // Returns the value to which this map maps the specified key.- public Row.Entry get(final byte[] key) throws IOException {- Row.Entry result;- synchronized (writeSearchObj) {- writeSearchObj.process(key);- if (writeSearchObj.found()) {- result = row().newEntry(writeSearchObj.getMatcher().getValueRow());- } else {- result = null;- }- }- return result;- }-- public ArrayList<RowCollection> removeDoubles() {- // this data structure cannot have doubles; return empty array- return new ArrayList<RowCollection>();- }-- public class Search {-- // a search object combines the results of a search in the tree, which are- // - the searched object is found, an index pointing to the node can be returned- // - the object was not found, an index pointing to an appropriate possible parent node- // can be returned, together with the information wether the new key shall- // be left or right child.-- private CacheNode thenode, parentnode;- private boolean found; // property if node was found- private byte child; // -1: left child; 0: root node; 1: right child-- // temporary variables- private RecordHandle thisHandle;- String keybuffer;-- protected Search() {- }-- protected void process(final byte[] key) throws IOException {- // searchs the database for the key and stores the result in the thisHandle- // if the key was found, then found=true, thisHandle and leftchild is set;- // else found=false and thisHandle and leftchild is undefined- thisHandle = getHandle(root);- parentnode = null;- if (key == null) {- throw new kelondroException("startet search process with key == null");- /*- child = 0;- if (thisHandle == null) {- thenode = null;- found = false;- } else {- thenode = getNode(thisHandle, null, 0);- found = true;- }- return;- */- }- thenode = null;- child = 0;- found = false;- int c;-- final TreeSet<String> visitedNodeKeys = new TreeSet<String>(loopDetectionOrder); // to detect loops- // System.out.println("Starting Compare Loop in Database " + filename); // debug- while (thisHandle != null) {- try {- parentnode = thenode;- thenode = new CacheNode(thisHandle, thenode, (child == -1) ? leftchild : rightchild, true);- } catch (final IllegalArgumentException e) {- logWarning("kelondroTree.Search.process: fixed a broken handle");- found = false;- return;- }- if (thenode == null) throw new kelondroException(filename, "kelondroTree.Search.process: thenode==null");-- keybuffer = new String(thenode.getKey());- if (keybuffer == null) {- // this is an error. distinguish two cases:- // 1. thenode is a leaf node. Then this error can be fixed if we can consider this node as a good node to be replaced with a new value- // 2. thenode is not a leaf node. An exception must be thrown- if ((thenode.getOHHandle(leftchild) == null) && (thenode.getOHHandle(rightchild) == null)) {- // case 1: recover- deleteNode(thisHandle);- thenode = parentnode;- found = false;- return;- } else {- // case 2: fail- throw new kelondroException("found key during search process with key == null");- }- }- if (visitedNodeKeys.contains(keybuffer)) {- // we have loops in the database.- // to fix this, all affected nodes must be patched- thenode.setOHByte(magic, (byte) 1);- thenode.setOHByte(balance, (byte) 0);- thenode.setOHHandle(parent, null);- thenode.setOHHandle(leftchild, null);- thenode.setOHHandle(rightchild, null);- thenode.commit();- logWarning("kelondroTree.Search.process: database contains loops; the loop-nodes have been auto-fixed");- found = false;- return;- }- // System.out.println("Comparing key = '" + new String(key) + "' with '" + otherkey + "':"); // debug- c = row().objectOrder.compare(key, keybuffer.getBytes());- // System.out.println(c); // debug- if (c == 0) {- found = true;- // System.out.println("DEBUG: search for " + new String(key) + " ended with status=" + ((found) ? "found" : "not-found") + ", node=" + ((thenode == null) ? "NULL" : thenode.toString()) + ", parent=" + ((parentnode == null) ? "NULL" : parentnode.toString()));- return;- } else if (c < 0) {- child = -1;- thisHandle = thenode.getOHHandle(leftchild);- } else {- child = 1;- thisHandle = thenode.getOHHandle(rightchild);- }- visitedNodeKeys.add(keybuffer);- }- // System.out.println("DEBUG: search for " + new String(key) + " ended with status=" + ((found) ? "found" : "not-found") + ", node=" + ((thenode == null) ? "NULL" : thenode.toString()) + ", parent=" + ((parentnode == null) ? "NULL" : parentnode.toString()));- // we reached a node where we must insert the new value- // the parent of this new value can be obtained by getParent()- // all values are set, just return- }-- public boolean found() {- return found;- }-- public CacheNode getMatcher() {- if (found) return thenode;- throw new IllegalArgumentException("wrong access of matcher");- }-- public CacheNode getParent() {- if (found) return parentnode;- return thenode;- }-- public boolean isRoot() {- if (found) throw new IllegalArgumentException("wrong access of isRoot");- return (child == 0);- }-- public boolean isLeft() {- if (found) throw new IllegalArgumentException("wrong access of leftchild");- return (child == -1);- }-- public boolean isRight() {- if (found) throw new IllegalArgumentException("wrong access of leftchild");- return (child == 1);- }- }-- public synchronized boolean isChild(final Node childn, final Node parentn, final int child) {- if (childn == null) throw new IllegalArgumentException("isLeftChild: Node parameter is NULL");- final RecordHandle lc = parentn.getOHHandle(child);- if (lc == null) return false;- return (lc.equals(childn.handle()));- }-- public void put(final Row.Entry newrow) throws IOException {- replace(newrow);- }-- public Row.Entry replace(final Row.Entry newrow) throws IOException {- assert (newrow != null);- assert (newrow.columns() == row().columns());- assert (!(Log.allZero(newrow.getPrimaryKeyBytes())));- assert newrow.objectsize() <= super.row().objectsize;- // Associates the specified value with the specified key in this map- Row.Entry result = null;- //writeLock.stay(2000, 1000);- // first try to find the key element in the database- synchronized(writeSearchObj) {- writeSearchObj.process(newrow.getColBytes(0));- if (writeSearchObj.found()) {- // a node with this key exist. simply overwrite the content and return old content- final Node e = writeSearchObj.getMatcher();- result = row().newEntry(e.getValueRow());- e.setValueRow(newrow.bytes());- commitNode(e);- } else if (writeSearchObj.isRoot()) {- // a node with this key does not exist and there is no node at all- // this therefore creates the root node if an only if there was no root Node yet- if (getHandle(root) != null)- throw new kelondroException(filename, "tried to create root node twice");- // we dont have any Nodes in the file, so start here to create one- final Node e = new CacheNode(newrow.bytes());- // write the propetries- e.setOHByte(magic, (byte) 1);- e.setOHByte(balance, (byte) 0);- e.setOHHandle(parent, null);- e.setOHHandle(leftchild, null);- e.setOHHandle(rightchild, null);- // do updates- e.commit();- setHandle(root, e.handle());- result = null;- } else {- // a node with this key does not exist- // this creates a new node if there is already at least a root node- // to create the new node, it is necessary to assign it to a parent- // it must also be defined weather this new node is a left child of the- // parent or not. It is checked if the parent node already has a child on- // that side, but not if the assigned position is appropriate.-- // create new node and assign values- CacheNode parentNode = writeSearchObj.getParent();- CacheNode theNode = new CacheNode(newrow.bytes());- theNode.setOHByte(0, (byte) 1); // fresh magic- theNode.setOHByte(1, (byte) 0); // fresh balance- theNode.setOHHandle(parent, parentNode.handle());- theNode.setOHHandle(leftchild, null);- theNode.setOHHandle(rightchild, null);- theNode.commit();-- // check consistency and link new node to parent node- byte parentBalance;- if (writeSearchObj.isLeft()) {- if (parentNode.getOHHandle(leftchild) != null) throw new kelondroException(filename, "tried to create leftchild node twice. parent=" + new String(parentNode.getKey()) + ", leftchild=" + new String(new CacheNode(parentNode.getOHHandle(leftchild), (CacheNode) null, 0, true).getKey()));- parentNode.setOHHandle(leftchild, theNode.handle());- } else if (writeSearchObj.isRight()) {- if (parentNode.getOHHandle(rightchild) != null) throw new kelondroException(filename, "tried to create rightchild node twice. parent=" + new String(parentNode.getKey()) + ", rightchild=" + new String(new CacheNode(parentNode.getOHHandle(rightchild), (CacheNode) null, 0, true).getKey()));- parentNode.setOHHandle(rightchild, theNode.handle());- } else {- throw new kelondroException(filename, "neither left nor right child");- }- commitNode(parentNode);-- // now update recursively the node balance of the parentNode- // what do we have:- // - new Node, called 'theNode'- // - parent Node-- // set balance factor in parent node(s)- boolean increasedHight = true;- String path = "";- byte prevHight;- RecordHandle parentSideHandle;- while (increasedHight) {-- // update balance- parentBalance = parentNode.getOHByte(balance); // {magic, balance}- prevHight = parentBalance;- parentSideHandle = parentNode.getOHHandle(leftchild);- if ((parentSideHandle != null) && (parentSideHandle.equals(theNode.handle()))) {- // is left child- parentBalance++;- path = "L" + path;- }- parentSideHandle =parentNode.getOHHandle(rightchild);- if ((parentSideHandle != null) && (parentSideHandle.equals(theNode.handle()))) {- // is right child- parentBalance--;- path = "R" + path;- }- increasedHight = ((java.lang.Math.abs(parentBalance) - java.lang.Math.abs(prevHight)) > 0);- parentNode.setOHByte(balance, parentBalance);- commitNode(parentNode);-- // here we either stop because we had no increased hight,- // or we have a balance greater then 1 or less than -1 and we do rotation- // or we crawl up the tree and change the next balance- if (!(increasedHight)) break; // finished-- // check rotation need- if (java.lang.Math.abs(parentBalance) > 1) {- // rotate and stop then- //System.out.println("* DB DEBUG: " + path.substring(0,2) + " ROTATION AT NODE " + parentNode.handle().toString() + ": BALANCE=" + parentOHByte[balance]);- if (path.startsWith("LL")) {- LL_RightRotation(parentNode, theNode);- break;- }- if (path.startsWith("RR")) {- RR_LeftRotation(parentNode, theNode);- break;- }- if (path.startsWith("RL")) {- final RecordHandle parentHandle = parentNode.handle();- LL_RightRotation(theNode, new CacheNode(theNode.getOHHandle(leftchild), theNode, leftchild, false));- parentNode = new CacheNode(parentHandle, null, 0, false); // reload the parent node- RR_LeftRotation(parentNode, new CacheNode(parentNode.getOHHandle(rightchild), parentNode, rightchild, false));- break;- }- if (path.startsWith("LR")) {- final RecordHandle parentHandle = parentNode.handle();- RR_LeftRotation(theNode, new CacheNode(theNode.getOHHandle(rightchild), theNode, rightchild, false));- parentNode = new CacheNode(parentHandle, null, 0, false); // reload the parent node- LL_RightRotation(parentNode, new CacheNode(parentNode.getOHHandle(leftchild), parentNode, leftchild, false));- break;- }- break;- }- // crawl up the tree- if (parentNode.getOHHandle(parent) == null) break; // root reached: stop- theNode = parentNode;- parentNode = new CacheNode(parentNode.getOHHandle(parent), null, 0, false);- }-- result = null; // that means: no previous stored value present- }- }- //writeLock.release();- return result;- }-- public synchronized void addUnique(final Row.Entry row) throws IOException {- this.put(row);- }-- public synchronized void addUnique(final List<Row.Entry> rows) throws IOException {- final Iterator<Row.Entry> i = rows.iterator();- while (i.hasNext()) addUnique(i.next());- }-- private void assignChild(final Node parentNode, final Node childNode, final int childType) throws IOException {- parentNode.setOHHandle(childType, childNode.handle());- childNode.setOHHandle(parent, parentNode.handle());- commitNode(parentNode);- commitNode(childNode);- }-- private void replace(final Node oldNode, final Node oldNodeParent, final Node newNode) throws IOException {- // this routine looks where the oldNode is connected to, and replaces- // the anchor's link to the oldNode by the newNode-link- // the new link gets the anchor as parent link assigned- // the oldNode will not be updated, so this must be done outside this routine- // distinguish case where the oldNode is the root node- if (oldNodeParent == null) {- // this is the root, update root- setHandle(root, newNode.handle());- // update new Node- newNode.setOHHandle(parent, null);- commitNode(newNode);- } else {- // not the root, find parent- // ok, we have the parent, but for updating the child link we must know- // if the oldNode was left or right child- RecordHandle parentSideHandle = oldNodeParent.getOHHandle(leftchild);- if ((parentSideHandle != null) && (parentSideHandle.equals(oldNode.handle()))) {- // update left node from parent- oldNodeParent.setOHHandle(leftchild, newNode.handle());- }- parentSideHandle = oldNodeParent.getOHHandle(rightchild);- if ((parentSideHandle != null) && (parentSideHandle.equals(oldNode.handle()))) {- // update right node from parent- oldNodeParent.setOHHandle(rightchild, newNode.handle());- }- commitNode(oldNodeParent);- // update new Node- newNode.setOHHandle(parent, oldNodeParent.handle());- commitNode(newNode);- }- // finished. remember that we did not set the links to the oldNode- // we have also not set the children of the newNode.- // this must be done somewhere outside this function.- // if the oldNode is not needed any more, it can be disposed (check childs first).- }-- private static byte max0(final byte b) {- if (b > 0) return b;- return 0;- }-- private static byte min0(final byte b) {- if (b < 0) return b;- return 0;- }-- private void LL_RightRotation(final Node parentNode, final CacheNode childNode) throws IOException {- // replace the parent node; the parent is afterwards unlinked- final RecordHandle p2Handle = parentNode.getOHHandle(parent);- final Node p2Node = (p2Handle == null) ? null : new CacheNode(p2Handle, null, 0, false);- replace(parentNode, p2Node, childNode);-- // set the left son of the parent to the right son of the childNode- final RecordHandle childOfChild = childNode.getOHHandle(rightchild);- if (childOfChild == null) {- parentNode.setOHHandle(leftchild, null);- } else {- assignChild(parentNode, new CacheNode(childOfChild, childNode, rightchild, false), leftchild);- }-- // link the old parent node as the right child of childNode- assignChild(childNode, parentNode, rightchild);-- // - newBal(parent) = oldBal(parent) - 1 - max(oldBal(leftChild), 0)- // - newBal(leftChild) = oldBal(leftChild) - 1 + min(newBal(parent), 0)- byte parentBalance = parentNode.getOHByte(balance);- byte childBalance = childNode.getOHByte(balance);- final byte oldBalParent = parentBalance;- final byte oldBalChild = childBalance;- parentBalance = (byte) (oldBalParent - 1 - max0(oldBalChild));- childBalance = (byte) (oldBalChild - 1 + min0(parentBalance));- parentNode.setOHByte(balance, parentBalance);- childNode.setOHByte(balance, childBalance);- commitNode(parentNode);- commitNode(childNode);- }-- private void RR_LeftRotation(final Node parentNode, final CacheNode childNode) throws IOException {- // replace the parent node; the parent is afterwards unlinked- final RecordHandle p2Handle = parentNode.getOHHandle(parent);- final Node p2Node = (p2Handle == null) ? null : new CacheNode(p2Handle, null, 0, false);- replace(parentNode, p2Node, childNode);-- // set the left son of the parent to the right son of the childNode- final RecordHandle childOfChild = childNode.getOHHandle(leftchild);- if (childOfChild == null) {- parentNode.setOHHandle(rightchild, null);- } else {- assignChild(parentNode, new CacheNode(childOfChild, childNode, leftchild, false), rightchild);- }-- // link the old parent node as the left child of childNode- assignChild(childNode, parentNode, leftchild);-- // - newBal(parent) = oldBal(parent) + 1 - min(oldBal(rightChild), 0)- // - newBal(rightChild) = oldBal(rightChild) + 1 + max(newBal(parent), 0)- byte parentBalance = parentNode.getOHByte(balance);- byte childBalance = childNode.getOHByte(balance);- final byte oldBalParent = parentBalance;- final byte oldBalChild = childBalance;- parentBalance = (byte) (oldBalParent + 1 - min0(oldBalChild));- childBalance = (byte) (oldBalChild + 1 + max0(parentBalance));- parentNode.setOHByte(balance, parentBalance);- childNode.setOHByte(balance, childBalance);- commitNode(parentNode);- commitNode(childNode);- }-- // Associates the specified value with the specified key in this map- public byte[] put(final byte[] key, final byte[] value) throws IOException {- final Row.Entry row = row().newEntry(new byte[][]{key, value});- final Row.Entry ret = replace(row);- if (ret == null) return null;- return ret.getColBytes(0);- }-- // Removes the mapping for this key from this map if present (optional operation).- public Row.Entry remove(final byte[] key) throws IOException {- // the order inside the database file cannot be maintained, but iteration over objects will always maintain the object order- // therefore keepOrder should be true, because the effect is always given, while the data structure does not maintain order- // delete from database- synchronized(writeSearchObj) {- writeSearchObj.process(key);- if (writeSearchObj.found()) {- final CacheNode result = writeSearchObj.getMatcher();- final Row.Entry values = row().newEntry(result.getValueRow());- remove(result, writeSearchObj.getParent());- return values;- }- return null;- }- }-- public Row.Entry removeOne() throws IOException {- // removes just any entry and removes that entry- synchronized(writeSearchObj) {- final CacheNode theOne = lastNode();- final Row.Entry values = row().newEntry(theOne.getValueRow());- remove(theOne, null);- return values;- }- }-- public synchronized void removeAll() throws IOException {- while (size() > 0) remove(lastNode(), null);- }-- private void remove(CacheNode node, final Node parentOfNode) throws IOException {- // there are three cases when removing a node- // - the node is a leaf - it can be removed easily- // - the node has one child - the child replaces the node- // - the node has two childs - it can be replaced either- // by the greatest node of the left child or the smallest- // node of the right child-- Node childnode;- if ((node.getOHHandle(leftchild) == null) && (node.getOHHandle(rightchild) == null)) {- // easy case: the node is a leaf- if (parentOfNode == null) {- // this is the root!- setHandle(root, null);- } else {- RecordHandle h = parentOfNode.getOHHandle(leftchild);- if ((h != null) && (h.equals(node.handle()))) parentOfNode.setOHHandle(leftchild, null);- h = parentOfNode.getOHHandle(rightchild);- if ((h != null) && (h.equals(node.handle()))) parentOfNode.setOHHandle(rightchild, null);- commitNode(parentOfNode);- }- } else if ((node.getOHHandle(leftchild) != null) && (node.getOHHandle(rightchild) == null)) {- replace(node, parentOfNode, new CacheNode(node.getOHHandle(leftchild), node, leftchild, false));- } else if ((node.getOHHandle(leftchild) == null) && (node.getOHHandle(rightchild) != null)) {- replace(node, parentOfNode, new CacheNode(node.getOHHandle(rightchild), node, rightchild, false));- } else {- // difficult case: node has two children- final CacheNode repl = lastNode(new CacheNode(node.getOHHandle(leftchild), node, leftchild, false));- //System.out.println("last node is " + repl.toString());- // we remove that replacement node and put it where the node was- // this seems to be recursive, but is not since the replacement- // node cannot have two children (it would not have been the smallest or greatest)- Node n;- RecordHandle h;- // remove leaf- if ((repl.getOHHandle(leftchild) == null) && (repl.getOHHandle(rightchild) == null)) {- // the replacement cannot be the root, so simply remove from parent node- n = new CacheNode(repl.getOHHandle(parent), null, 0, false); // parent node of replacement node- h = n.getOHHandle(leftchild);- if ((h != null) && (h.equals(repl.handle()))) n.setOHHandle(leftchild, null);- h = n.getOHHandle(rightchild);- if ((h != null) && (h.equals(repl.handle()))) n.setOHHandle(rightchild, null);- commitNode(n);- } else if ((repl.getOHHandle(leftchild) != null) && (repl.getOHHandle(rightchild) == null)) {- try {- childnode = new CacheNode(repl.getOHHandle(leftchild), repl, leftchild, false);- replace(repl, new CacheNode(repl.getOHHandle(parent), null, 0, false), childnode);- } catch (final IllegalArgumentException e) {- // now treat the situation as if that link had been null before- n = new CacheNode(repl.getOHHandle(parent), null, 0, false); // parent node of replacement node- h = n.getOHHandle(leftchild);- if ((h != null) && (h.equals(repl.handle()))) n.setOHHandle(leftchild, null);- h = n.getOHHandle(rightchild);- if ((h != null) && (h.equals(repl.handle()))) n.setOHHandle(rightchild, null);- commitNode(n);- }- } else if ((repl.getOHHandle(leftchild) == null) && (repl.getOHHandle(rightchild) != null)) {- try {- childnode = new CacheNode(repl.getOHHandle(rightchild), repl, rightchild, false);- replace(repl, new CacheNode(repl.getOHHandle(parent), null, 0, false), childnode);- } catch (final IllegalArgumentException e) {- // now treat the situation as if that link had been null before- n = new CacheNode(repl.getOHHandle(parent), null, 0, false); // parent node of replacement node- h = n.getOHHandle(leftchild);- if ((h != null) && (h.equals(repl.handle()))) n.setOHHandle(leftchild, null);- h = n.getOHHandle(rightchild);- if ((h != null) && (h.equals(repl.handle()))) n.setOHHandle(rightchild, null);- commitNode(n);- }- }- //System.out.println("node before reload is " + node.toString());- node = new CacheNode(node.handle(), null, 0, false); // reload the node, it is possible that it has been changed- //System.out.println("node after reload is " + node.toString());-- // now plant in the replha node- final byte b = node.getOHByte(balance); // save balance of disappearing node- final RecordHandle parentHandle = node.getOHHandle(parent);- final RecordHandle leftchildHandle = node.getOHHandle(leftchild);- final RecordHandle rightchildHandle = node.getOHHandle(rightchild);- replace(node, parentOfNode, repl);- repl.setOHByte(balance, b); // restore balance- repl.setOHHandle(parent, parentHandle); // restore handles- repl.setOHHandle(leftchild, leftchildHandle);- repl.setOHHandle(rightchild, rightchildHandle);- commitNode(repl);- // last thing to do: change uplinks of children to this new node- if (leftchildHandle != null) {- n = new CacheNode(leftchildHandle, node, leftchild, false);- n.setOHHandle(parent, repl.handle());- commitNode(n);- }- if (rightchildHandle != null) {- n = new CacheNode(rightchildHandle, node, rightchild, false);- n.setOHHandle(parent, repl.handle());- commitNode(n);- }- }- // move node to recycling queue- synchronized (this) {- deleteNode(node.handle());- }- }-- protected CacheNode firstNode() throws IOException {- final RecordHandle h = getHandle(root);- if (h == null) return null;- return firstNode(new CacheNode(h, null, 0, true));- }-- protected CacheNode firstNode(CacheNode node) throws IOException {- if (node == null) throw new IllegalArgumentException("firstNode: node=null");- RecordHandle h = node.getOHHandle(leftchild);- final HashSet<String> visitedNodeKeys = new HashSet<String>(); // to detect loops- String nodeKey;- while (h != null) {- try {- node = new CacheNode(h, node, leftchild, true);- nodeKey = new String(node.getKey());- if (visitedNodeKeys.contains(nodeKey)) throw new kelondroException(this.filename, "firstNode: database contains loops: '" + nodeKey + "' appears twice.");- visitedNodeKeys.add(nodeKey);- } catch (final IllegalArgumentException e) {- // return what we have- return node;- }- h = node.getOHHandle(leftchild);- }- return node;- }-- protected CacheNode lastNode() throws IOException {- final RecordHandle h = getHandle(root);- if (h == null) return null;- return lastNode(new CacheNode(h, null, 0, true));- }-- protected CacheNode lastNode(CacheNode node) throws IOException {- if (node == null) throw new IllegalArgumentException("lastNode: node=null");- RecordHandle h = node.getOHHandle(rightchild);- final HashSet<String> visitedNodeKeys = new HashSet<String>(); // to detect loops- String nodeKey;- while (h != null) {- try {- node = new CacheNode(h, node, rightchild, true);- nodeKey = new String(node.getKey());- if (visitedNodeKeys.contains(nodeKey)) throw new kelondroException(this.filename, "lastNode: database contains loops: '" + nodeKey + "' appears twice.");- visitedNodeKeys.add(nodeKey);- } catch (final IllegalArgumentException e) {- // return what we have- return node;- }- h = node.getOHHandle(rightchild);- }- return node;- }-- private class nodeIterator implements Iterator<CacheNode> {- // we implement an iteration! (not a recursive function as the structure would suggest...)- // the iterator iterates Node objects- CacheNode nextNode = null;- boolean up, rot;- LinkedList<Object[]> nodeStack;- int count;-- public nodeIterator(final boolean up, final boolean rotating) throws IOException {- this.count = 0;- this.up = up;- this.rot = rotating;-- // initialize iterator- init((up) ? firstNode() : lastNode());- }-- public nodeIterator(final boolean up, final boolean rotating, final byte[] firstKey, final boolean including) throws IOException {- this.count = 0;- this.up = up;- this.rot = rotating;-- final Search search = new Search();- search.process(firstKey);- if (search.found()) {- init(search.getMatcher());- } else {- final CacheNode nn = search.getParent();- if (nn == null) {- this.nextNode = null;- } else {- // the node nn may be greater or smaller than the firstKey- // depending on the ordering direction,- // we must find the next smaller or greater node- // this is corrected in the initializer of nodeIterator- init(nn);- }- }-- // correct nextNode upon start- // this happens, if the start node was not proper, or could not be found- while ((nextNode != null) && (nextNode.getKey() != null)) {- final int c = row().objectOrder.compare(firstKey, nextNode.getKey());- if (c == 0) {- if (including) {- break; // correct + finished- }- if (hasNext()) next(); else nextNode = null;- break; // corrected + finished- } else if (c < 0) {- if (up) {- break; // correct + finished- }- // firstKey < nextNode.getKey(): correct once- if (hasNext()) next(); else nextNode = null;- } else if (c > 0) {- if (up) {- // firstKey > nextNode.getKey(): correct once- if (hasNext()) next(); else nextNode = null;- } else {- break; // correct + finished- }- }- }- }-- private void init(final CacheNode start) throws IOException {- this.nextNode = start;-- // fill node stack for start node- nodeStack = new LinkedList<Object[]>();-- RecordHandle searchHandle = getHandle(root);- if (searchHandle == null) {nextNode = null; return;}-- CacheNode searchNode = new CacheNode(searchHandle, null, 0, false);- final byte[] startKey = start.getKey();- int c, ct;- while ((c = row().objectOrder.compare(startKey, searchNode.getKey())) != 0) {- // the current 'thisNode' is not the start node, put it on the stack- ct = (c < 0) ? leftchild : rightchild;- nodeStack.addLast(new Object[]{searchNode, Integer.valueOf(ct)});-- // go to next node- searchHandle = searchNode.getOHHandle(ct);- if (searchHandle == null) throw new kelondroException(filename, "nodeIterator.init: start node does not exist (handle null)");- searchNode = new CacheNode(searchHandle, searchNode, ct, false);- if (searchNode == null) throw new kelondroException(filename, "nodeIterator.init: start node does not exist (node null)");- }- // now every parent node to the start node is on the stack- }-- public boolean hasNext() {- return (rot && (size() > 0)) || (nextNode != null);- }-- public CacheNode next() {- count++;- if ((rot) && (nextNode == null)) try {- init((up) ? firstNode() : lastNode());- } catch (final IOException e) {- throw new kelondroException(filename, "io-error while rot");- }- if (nextNode == null) throw new kelondroException(filename, "nodeIterator.next: no more entries available");- if ((count > size()) && (!(rot))) throw new kelondroException(filename, "nodeIterator.next: internal loopback; database corrupted");- final CacheNode ret = nextNode;-- // middle-case- try {- int childtype = (up) ? rightchild : leftchild;- RecordHandle childHandle = nextNode.getOHHandle(childtype);- if (childHandle != null) {- //System.out.println("go to other leg, stack size=" + nodeStack.size());- // we have walked one leg of the tree; now go to the other one: step down to next child- final HashSet<RecordHandle> visitedNodeHandles = new HashSet<RecordHandle>(); // to detect loops- nodeStack.addLast(new Object[]{nextNode, Integer.valueOf(childtype)});- nextNode = new CacheNode(childHandle, nextNode, childtype, false);- childtype = (up) ? leftchild : rightchild;- while ((childHandle = nextNode.getOHHandle(childtype)) != null) {- if (visitedNodeHandles.contains(childHandle)) {- // try to repair the nextNode- nextNode.setOHHandle(childtype, null);- nextNode.commit();- logWarning("nodeIterator.next: internal loopback; fixed loop and try to go on");- break;- }- visitedNodeHandles.add(childHandle);- try {- nodeStack.addLast(new Object[]{nextNode, Integer.valueOf(childtype)});- nextNode = new CacheNode(childHandle, nextNode, childtype, false);- } catch (final IllegalArgumentException e) {- // return what we have- nodeStack.removeLast();- return ret;- }- }- // thats it: we are at a place where we can't go further- // nextNode is correct- } else {- //System.out.println("go up");- // we have walked along both legs of the child-trees.-- // Now step up.- if (nodeStack.size() == 0) {- nextNode = null;- } else {- Object[] stacktop;- CacheNode parentNode = null;- int parentpointer = (up) ? rightchild : leftchild;- while ((nodeStack.size() != 0) && (parentpointer == ((up) ? rightchild : leftchild))) {- //System.out.println("step up");- // go on, walk up further- stacktop = nodeStack.removeLast(); // top of stack: Node/parentpointer pair- parentNode = (CacheNode) stacktop[0];- parentpointer = ((Integer) stacktop[1]).intValue();- }- if ((nodeStack.size() == 0) && (parentpointer == ((up) ? rightchild : leftchild))) {- nextNode = null;- } else {- nextNode = parentNode;- }- }- }- } catch (final IOException e) {- nextNode = null;- }-- return ret;- }-- public void remove() {- throw new java.lang.UnsupportedOperationException("kelondroTree: remove in kelondro node iterator not yet supported");- }- }-- public TreeMap<String, Row.Entry> rowMap(final boolean up, final byte[] firstKey, final boolean including, final int count) throws IOException {- // returns an ordered map of keys/row relations; key objects are of type String, value objects are of type byte[][]- final ByteOrder setOrder = (ByteOrder) row().objectOrder.clone();- setOrder.direction(up);- setOrder.rotate(firstKey);- final TreeMap<String, Row.Entry> rows = new TreeMap<String, Row.Entry>(this.loopDetectionOrder);- CacheNode n;- String key;- synchronized (this) {- final Iterator<CacheNode> i = (firstKey == null) ? new nodeIterator(up, false) : new nodeIterator(up, false, firstKey, including);- while ((rows.size() < count) && (i.hasNext())) {- n = i.next();- if (n == null) return rows;- key = new String(n.getKey());- if (rows.put(key, row().newEntry(n.getValueRow())) != null) return rows; // protection against loops- }- }- return rows;- }-- public TreeSet<String> keySet(final boolean up, final boolean rotating, final byte[] firstKey, final boolean including, final int count) throws IOException {- // returns an ordered set of keys; objects are of type String- final ByteOrder setOrder = (ByteOrder) row().objectOrder.clone();- setOrder.direction(up);- setOrder.rotate(firstKey);- final TreeSet<String> set = new TreeSet<String>(this.loopDetectionOrder);- Node n;- synchronized (this) {- final Iterator<CacheNode> i = (firstKey == null) ? new nodeIterator(up, rotating) : new nodeIterator(up, rotating, firstKey, including);- while ((set.size() < count) && (i.hasNext())) {- n = i.next();- if ((n != null) && (n.getKey() != null)) set.add(new String(n.getKey()));- }- }- return set;- }-- public CloneableIterator<Row.Entry> rows(final boolean up, final byte[] firstKey) throws IOException {- // iterates the rows of the Nodes- // enumerated objects are of type byte[][]- // iterates the elements in a sorted way.- // if iteration should start at smallest element, set firstKey to null- return new rowIterator(up, firstKey, this.size());- }-- public CloneableIterator<Row.Entry> rows() throws IOException {- return new rowIterator(true, null, this.size());- }-- public class rowIterator implements CloneableIterator<Row.Entry> {-- int chunkSize;- boolean inc;- long count;- byte[] lastKey;- TreeMap<String, Row.Entry> rowBuffer;- Iterator<Map.Entry<String, Row.Entry>> bufferIterator;- long guessedCountLimit;-- public rowIterator(final boolean up, final byte[] firstKey, final long guessedCountLimit) throws IOException {- this.guessedCountLimit = guessedCountLimit;- inc = up;- count = 0;- lastKey = null;- //System.out.println("*** rowIterator: " + filename + ": readAheadChunkSize = " + readAheadChunkSize + ", lastIteratorCount = " + lastIteratorCount);- readAheadChunkSize = Math.min(1000, 3 + (int) ((3 * readAheadChunkSize + lastIteratorCount) / 4));- chunkSize = (int) Math.min(readAheadChunkSize / 3, guessedCountLimit);- rowBuffer = rowMap(inc, firstKey, true, chunkSize);- bufferIterator = rowBuffer.entrySet().iterator();- lastIteratorCount = 0;- }-- public rowIterator clone(final Object secondStart) {- try {- return new rowIterator(inc, (byte[]) secondStart, guessedCountLimit);- } catch (final IOException e) {- return null;- }- }-- public boolean hasNext() {- return ((bufferIterator != null) && (bufferIterator.hasNext()) && (count < size()));- }-- public Row.Entry next() {- if (!(bufferIterator.hasNext())) return null;- final Map.Entry<String, Row.Entry> entry = bufferIterator.next();- lastKey = entry.getKey().getBytes();-- // check if this was the last entry in the rowBuffer- if (!(bufferIterator.hasNext())) {- // assign next buffer chunk- try {- lastKey[lastKey.length - 1]++; // ***BUG??? FIXME- rowBuffer = rowMap(inc, lastKey, false, chunkSize);- bufferIterator = rowBuffer.entrySet().iterator();- } catch (final IOException e) {- rowBuffer = null;- bufferIterator = null;- }- }-- // return the row- count++;- lastIteratorCount++;- return entry.getValue();- }-- public void remove() {- if (lastKey != null) try {- Tree.this.remove(lastKey);- } catch (final IOException e) {- // do nothing- }- }-- }-- public CloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {- return new keyIterator(up, firstKey, this.size());- }-- public class keyIterator implements CloneableIterator<byte[]> {-- int chunkSize;- boolean inc;- long count;- byte[] lastKey;- TreeSet<String> keyBuffer;- Iterator<String> bufferIterator;- long guessedCountLimit;-- public keyIterator(final boolean up, final byte[] firstKey, final long guessedCountLimit) throws IOException {- this.guessedCountLimit = guessedCountLimit;- inc = up;- count = 0;- lastKey = null;- //System.out.println("*** rowIterator: " + filename + ": readAheadChunkSize = " + readAheadChunkSize + ", lastIteratorCount = " + lastIteratorCount);- readAheadChunkSize = Math.min(1000, 3 + (int) ((3 * readAheadChunkSize + lastIteratorCount) / 4));- chunkSize = (int) Math.min(readAheadChunkSize / 3, guessedCountLimit);- keyBuffer = keySet(inc, false, firstKey, true, chunkSize);- bufferIterator = keyBuffer.iterator();- lastIteratorCount = 0;- }-- public keyIterator clone(final Object secondStart) {- try {- return new keyIterator(inc, (byte[]) secondStart, guessedCountLimit);- } catch (final IOException e) {- return null;- }- }-- public boolean hasNext() {- return ((bufferIterator != null) && (bufferIterator.hasNext()) && (count < size()));- }-- public byte[] next() {- if (!(bufferIterator.hasNext())) return null;- lastKey = bufferIterator.next().getBytes();-- // check if this was the last entry in the rowBuffer- if (!(bufferIterator.hasNext())) {- // assign next buffer chunk- try {- lastKey[lastKey.length - 1]++; // ***BUG??? FIXME- keyBuffer = keySet(inc, false, lastKey, false, chunkSize);- bufferIterator = keyBuffer.iterator();- } catch (final IOException e) {- keyBuffer = null;- bufferIterator = null;- }- }-- // return the row- count++;- lastIteratorCount++;- return lastKey;- }-- public void remove() {- if (lastKey != null) try {- Tree.this.remove(lastKey);- } catch (final IOException e) {- // do nothing- }- }-- }-- public int imp(final File file, final String separator) throws IOException {- // imports a value-separated file, returns number of records that have been read-- final RandomAccessFile f = new RandomAccessFile(file,"r");- String s;- StringTokenizer st;- int recs = 0;- final Row.Entry buffer = row().newEntry();- int c;- int line = 0;- while ((s = f.readLine()) != null) {- s = s.trim();- line++;- if ((s.length() > 0) && (!(s.startsWith("#")))) {- st = new StringTokenizer(s, separator);- // buffer the entry- c = 0;- while ((c < row().columns()) && (st.hasMoreTokens())) {- buffer.setCol(c++, st.nextToken().trim().getBytes());- }- if ((st.hasMoreTokens()) || (c != row().columns())) {- System.err.println("inapropriate number of entries in line " + line);- } else {- put(buffer);- recs++;- }-- }- }- return recs;- }-- public synchronized int height() {- try {- final RecordHandle h = getHandle(root);- if (h == null) return 0;- return height(new CacheNode(h, null, 0, false));- } catch (final IOException e) {- return 0;- }- }-- private int height(final CacheNode node) throws IOException {- if (node == null) return 0;- RecordHandle h = node.getOHHandle(leftchild);- final int hl = (h == null) ? 0 : height(new CacheNode(h, node, leftchild, false));- h = node.getOHHandle(rightchild);- final int hr = (h == null) ? 0 : height(new CacheNode(h, node, rightchild, false));- if (hl > hr) return hl + 1;- return hr + 1;- }-- public void print() throws IOException {- super.print();- final int height = height();- System.out.println("HEIGHT = " + height);- Vector<RecordHandle> thisline = new Vector<RecordHandle>();- thisline.add(getHandle(root));- Vector<RecordHandle> nextline;- RecordHandle handle;- Node node;- int linelength;- final int width = (1 << (height - 1)) * (row().width(0) + 1);- String key;- for (int h = 1; h < height; h++) {- linelength = width / (thisline.size() * 2);- nextline = new Vector<RecordHandle>();- for (int i = 0; i < thisline.size(); i++) {- handle = thisline.elementAt(i);- if (handle == null) {- node = null;- key = "[..]";- } else {- node = new CacheNode(handle, null, 0, false);- if (node == null) key = "NULL"; else key = new String(node.getKey());- }- System.out.print(key);- for (int j = 0; j < (linelength - key.length()); j++) System.out.print("-");- System.out.print("+");- for (int j = 0; j < (linelength - 1); j++) System.out.print(" ");- if (node == null) {- nextline.add(null);- nextline.add(null);- } else {- nextline.add(node.getOHHandle(leftchild));- nextline.add(node.getOHHandle(rightchild));- }- }- System.out.println();- for (int i = 0; i < thisline.size(); i++) {- System.out.print("|");- for (int j = 0; j < (linelength - 1); j++) System.out.print(" ");- System.out.print("|");- for (int j = 0; j < (linelength - 1); j++) System.out.print(" ");- }- System.out.println();- thisline = nextline;- nextline = null;- }- // now print last line- if ((thisline != null) && (width >= 0)) {- linelength = width / thisline.size();- for (int i = 0; i < thisline.size(); i++) {- handle = thisline.elementAt(i);- if (handle == null) {- node = null;- key = "NULL";- } else {- node = new CacheNode(handle, null, 0, false);- if (node == null) key = "NULL"; else key = new String(node.getKey());- }- System.out.print(key);- for (int j = 0; j < (linelength - key.length()); j++) System.out.print(" ");- }- }- System.out.println();- }-- public static void cmd(final String[] args) {- System.out.print("kelondroTree ");- for (int i = 0; i < args.length; i++) System.out.print(args[i] + " ");- System.out.println("");- byte[] ret = null;- try {- if ((args.length > 4) || (args.length < 1)) {- System.err.println("usage: kelondroTree -c|-u|-v|-g|-d|-i|-s [file]|[key [value]] <db-file>");- System.err.println("( create, update, view, get, delete, imp, shell)");- System.exit(0);- } else if (args.length == 1) {- if (args[0].equals("-t")) {- // test script- final File testFile = new File("test.db");- while (testFile.exists()) testFile.delete();- final Tree fm = new Tree(testFile, true, 10, new Row("byte[] a-4, byte[] b-4", NaturalOrder.naturalOrder));- final byte[] dummy = "".getBytes();- fm.put("abc0".getBytes(), dummy); fm.put("bcd0".getBytes(), dummy);- fm.put("def0".getBytes(), dummy); fm.put("bab0".getBytes(), dummy);- fm.put("abc1".getBytes(), dummy); fm.put("bcd1".getBytes(), dummy);- fm.put("def1".getBytes(), dummy); fm.put("bab1".getBytes(), dummy);- fm.put("abc2".getBytes(), dummy); fm.put("bcd2".getBytes(), dummy);- fm.put("def2".getBytes(), dummy); fm.put("bab2".getBytes(), dummy);- fm.put("abc3".getBytes(), dummy); fm.put("bcd3".getBytes(), dummy);- fm.put("def3".getBytes(), dummy); fm.put("bab3".getBytes(), dummy);- fm.print();- fm.remove("def1".getBytes()); fm.remove("bab1".getBytes());- fm.remove("abc2".getBytes()); fm.remove("bcd2".getBytes());- fm.remove("def2".getBytes()); fm.remove("bab2".getBytes());- fm.put("def1".getBytes(), dummy); fm.put("bab1".getBytes(), dummy);- fm.put("abc2".getBytes(), dummy); fm.put("bcd2".getBytes(), dummy);- fm.put("def2".getBytes(), dummy); fm.put("bab2".getBytes(), dummy);- fm.print();- fm.close();- ret = null;- }- } else if (args.length == 2) {- final Tree fm = new Tree(new File(args[1]), true, 10, new Row("byte[] a-4, byte[] b-4", NaturalOrder.naturalOrder));- if (args[0].equals("-v")) {- fm.print();- ret = null;- }- fm.close();- } else if (args.length == 3) {- if (args[0].equals("-d")) {- final Tree fm = new Tree(new File(args[1]), true, 10, new Row("byte[] a-4, byte[] b-4", NaturalOrder.naturalOrder));- fm.remove(args[2].getBytes());- fm.close();- } else if (args[0].equals("-i")) {- final Tree fm = new Tree(new File(args[1]), true, 10, new Row("byte[] a-4, byte[] b-4", NaturalOrder.naturalOrder));- final int i = fm.imp(new File(args[1]),";");- fm.close();- ret = (i + " records imported").getBytes();- } else if (args[0].equals("-s")) {- final String db = args[2];- BufferedReader f = null;- try {- f = new BufferedReader(new FileReader(args[1]));- String m;- while (true) {- m = f.readLine();- if (m == null) break;- if ((m.length() > 1) && (!m.startsWith("#"))) {- m = m + " " + db;- cmd(line2args(m));- }- }- ret = null;- } finally {- if (f != null) try {f.close();}catch(final Exception e){}- }- } else if (args[0].equals("-g")) {- final Tree fm = new Tree(new File(args[1]), true, 10, new Row("byte[] a-4, byte[] b-4", NaturalOrder.naturalOrder));- final Row.Entry ret2 = fm.get(args[2].getBytes());- ret = ((ret2 == null) ? null : ret2.getColBytes(1));- fm.close();- } else if (args[0].equals("-n")) {- final Tree fm = new Tree(new File(args[1]), true, 10, new Row("byte[] a-4, byte[] b-4", NaturalOrder.naturalOrder));- //byte[][] keys = fm.getSequentialKeys(args[2].getBytes(), 500, true);- final Iterator<Row.Entry> rowIt = fm.rows(true, (args[2].length() == 0) ? null : args[2].getBytes());- final Vector<String> v = new Vector<String>();- while (rowIt.hasNext()) v.add(rowIt.next().getColString(0, null));- ret = v.toString().getBytes();- fm.close();- }- } else if (args.length == 4) {- if (args[0].equals("-c")) {- // create <keylen> <valuelen> <filename>- final File f = new File(args[3]);- if (f.exists()) FileUtils.deletedelete(f);- final Row lens = new Row("byte[] key-" + Integer.parseInt(args[1]) + ", byte[] value-" + Integer.parseInt(args[2]), NaturalOrder.naturalOrder);- final Tree fm = new Tree(f, true, 10, lens);- fm.close();- } else if (args[0].equals("-u")) {- final Tree fm = new Tree(new File(args[1]), true, 10, new Row("byte[] a-4, byte[] b-4", NaturalOrder.naturalOrder));- ret = fm.put(args[1].getBytes(), args[2].getBytes());- fm.close();- }- }- if (ret == null)- System.out.println("NULL");- else- System.out.println(new String(ret));- } catch (final Exception e) {- e.printStackTrace();- }- }-- public static void main(final String[] args) {- //cmd(args);- //iterationtest();- bigtest(Integer.parseInt(args[0]));- //randomtest(Integer.parseInt(args[0]));- //smalltest();- }-- public static String[] permutations(final int letters) {- String p = "";- for (int i = 0; i < letters; i++) p = p + ((char) (('A') + i));- return permutations(p);- }- public static String[] permutations(final String source) {- if (source.length() == 0) return new String[0];- if (source.length() == 1) return new String[]{source};- final char c = source.charAt(0);- final String[] recres = permutations(source.substring(1));- final String[] result = new String[source.length() * recres.length];- for (int perm = 0; perm < recres.length; perm++) {- result[perm * source.length()] = c + recres[perm];- for (int pos = 1; pos < source.length() - 1; pos++) {- result[perm * source.length() + pos] = recres[perm].substring(0, pos) + c + recres[perm].substring(pos);- }- result[perm * source.length() + source.length() - 1] = recres[perm] + c;- }- return result;- }-- public static byte[] testWord(final char c) {- return new byte[]{(byte) c, 32, 32, 32};- }-- public static void randomtest(final int elements) {- System.out.println("random " + elements + ":");- final String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".substring(0, elements);- String t, d;- char c;- Tree tt = null;- final File testFile = new File("test.db");- byte[] b;- try {- int steps = 0;- while (true) {- if (testFile.exists()) FileUtils.deletedelete(testFile);- tt = new Tree(testFile, true, 10, new Row("byte[] a-4, byte[] b-4", NaturalOrder.naturalOrder));- steps = 10 + ((int) System.currentTimeMillis() % 7) * (((int) System.currentTimeMillis() + 17) % 11);- t = s;- d = "";- System.out.println("NEW SESSION");- for (int i = 0; i < steps; i++) {- if ((d.length() < 3) || ((t.length() > 0) && (((int) System.currentTimeMillis() % 7) < 2))) {- // add one- c = t.charAt((int) (System.currentTimeMillis() % t.length()));- b = testWord(c);- tt.put(b, b);- d = d + c;- t = t.substring(0, t.indexOf(c)) + t.substring(t.indexOf(c) + 1);- System.out.println("added " + new String(b));- } else {- // delete one- c = d.charAt((int) (System.currentTimeMillis() % d.length()));- b = testWord(c);- tt.remove(b);- d = d.substring(0, d.indexOf(c)) + d.substring(d.indexOf(c) + 1);- t = t + c;- System.out.println("removed " + new String(b));- }- //tt.printCache();- //tt.print();-- if (countElements(tt) != tt.size()) {- System.out.println("wrong size for this table:");- tt.print();- }-- // check all words within- for (int j = 0; j < d.length(); j++) {- if (tt.get(testWord(d.charAt(j))) == null) {- System.out.println("missing entry " + d.charAt(j) + " in this table:");- tt.print();- }- }- // check all words outside- for (int j = 0; j < t.length(); j++) {- if (tt.get(testWord(t.charAt(j))) != null) {- System.out.println("superfluous entry " + t.charAt(j) + " in this table:");- tt.print();- }- }- if (tt.get(testWord('z')) != null) {- System.out.println("superfluous entry z in this table:");- tt.print();- }-- }- //tt.print();- tt.close();- }-- } catch (final Exception e) {- e.printStackTrace();- if (tt != null) try {tt.print();} catch (final IOException ee) {}- System.out.println("TERMINATED");- }- }-- public static void smalltest() {- final File f = new File("test.db");- if (f.exists()) FileUtils.deletedelete(f);- try {- final Tree tt = new Tree(f, true, 10, new Row("byte[] a-4, byte[] b-4", NaturalOrder.naturalOrder));- byte[] b;- b = testWord('B'); tt.put(b, b); //tt.print();- b = testWord('C'); tt.put(b, b); //tt.print();- b = testWord('D'); tt.put(b, b); //tt.print();- b = testWord('A'); tt.put(b, b); //tt.print();- b = testWord('D'); tt.remove(b); //tt.print();- b = testWord('B'); tt.remove(b); //tt.print();- b = testWord('B'); tt.put(b, b); //tt.print();- b = testWord('D'); tt.put(b, b);- b = testWord('E'); tt.put(b, b);- b = testWord('F'); tt.put(b, b);- b = testWord('G'); tt.put(b, b);- b = testWord('H'); tt.put(b, b);- b = testWord('I'); tt.put(b, b);- b = testWord('J'); tt.put(b, b);- b = testWord('K'); tt.put(b, b);- b = testWord('L'); tt.put(b, b);- final int c = countElements(tt);- System.out.println("elements: " + c);- final Iterator<Row.Entry> i = tt.rows(true, testWord('G'));- for (int j = 0; j < c; j++) {- System.out.println("Row " + j + ": " + new String((i.next()).getColBytes(0)));- }- System.out.println("TERMINATED");- } catch (final IOException e) {- e.printStackTrace();- }- }-- /*- public static void iterationtest() {- File f = new File("test.db");- if (f.exists()) f.delete();- try {- kelondroTree tt = new kelondroTree(f, 0, 0, 10, 4, 4, true);- byte[] b;- for (int i = 0; i < 100; i++) {- b = ("T" + i).getBytes(); tt.put(b, b);- }- Iterator i = tt.keys(true, false, null);- while (i.hasNext()) System.out.print((String) i.next() + ", ");- System.out.println();-- i = tt.keys(true, false, "T80".getBytes());- while (i.hasNext()) System.out.print((String) i.next() + ", ");- System.out.println();-- i = tt.keys(true, true, "T80".getBytes());- for (int j = 0; j < 40; j++) System.out.print((String) i.next() + ", ");- System.out.println();-- i = tt.keys(false, true, "T20".getBytes());- for (int j = 0; j < 40; j++) System.out.print((String) i.next() + ", ");- System.out.println();-- tt.close();- } catch (IOException e) {- e.printStackTrace();- }- }- */-- public static Tree testTree(final File f, final String testentities) throws IOException {- if (f.exists()) FileUtils.deletedelete(f);- final Tree tt = new Tree(f, false, 10, new Row("byte[] a-4, byte[] b-4", NaturalOrder.naturalOrder));- byte[] b;- for (int i = 0; i < testentities.length(); i++) {- b = testWord(testentities.charAt(i));- tt.put(b, b);- }- return tt;- }-- public static void bigtest(final int elements) {- System.out.println("starting big test with " + elements + " elements:");- final long start = System.currentTimeMillis();- final String[] s = permutations(elements);- Tree tt;- final File testFile = new File("test.db");- try {- for (int i = 0; i < s.length; i++) {- System.out.println("*** probing tree " + i + " for permutation " + s[i]);- // generate tree and delete elements- tt = testTree(testFile, s[i]);- //tt.print();- if (countElements(tt) != tt.size()) {- System.out.println("wrong size for " + s[i]);- tt.print();- }- tt.close();- for (int j = 0; j < s.length; j++) {- tt = testTree(testFile, s[i]);- //tt.print();- // delete by permutation j- for (int elt = 0; elt < s[j].length(); elt++) {- tt.remove(testWord(s[j].charAt(elt)));- //tt.print();- if (countElements(tt) != tt.size()) {- System.out.println("ERROR! wrong size for probe tree " + s[i] + "; probe delete " + s[j] + "; position " + elt);- tt.print();- }- }- // add another one- //tt.print();- /*- b = testWord('0'); tt.put(b, b);- b = testWord('z'); tt.put(b, b);- b = testWord('G'); tt.put(b, b);- b = testWord('t'); tt.put(b, b);- if (countElements(tt) != tt.size()) {- System.out.println("ERROR! wrong size for probe tree " + s[i] + "; probe delete " + s[j] + "; final add");- tt.print();- }- tt.print();- */- // close this- tt.close();- }- }- System.out.println("FINISHED test after " + ((System.currentTimeMillis() - start) / 1000) + " seconds.");- } catch (final Exception e) {- e.printStackTrace();- System.out.println("TERMINATED");- }- }-- public static int countElements(final ObjectIndex t) {- int count = 0;- try {- final Iterator<Row.Entry> iter = t.rows();- Row.Entry row;- while (iter.hasNext()) {- count++;- row = iter.next();- if (row == null) System.out.println("ERROR! null element found");- // else System.out.println("counted element: " + new- // String(n.getKey()));- }- } catch (final IOException e) {- }- return count;- }--}diff --git a/source/de/anomic/plasma/plasmaSwitchboard.java b/source/de/anomic/plasma/plasmaSwitchboard.javaindex 8f940be5a..908653b3d 100644--- a/source/de/anomic/plasma/plasmaSwitchboard.java+++ b/source/de/anomic/plasma/plasmaSwitchboard.java@@ -497,9 +497,8 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.// Init User DBthis.log.logConfig("Loading User DB");- final File userDbFileOld = new File(getRootPath(), "DATA/SETTINGS/user.db");final File userDbFile = new File(getRootPath(), "DATA/SETTINGS/user.heap");- this.userDB = new userDB(userDbFileOld, userDbFile);+ this.userDB = new userDB(userDbFile);this.log.logConfig("Loaded User DB from file " + userDbFile.getName() +", " + this.userDB.size() + " entries" +", " + ppRamString(userDbFile.length()/1024));@@ -888,9 +887,8 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.public void initMessages() throws IOException {this.log.logConfig("Starting Message Board");- final File messageDbFileOld = new File(workPath, "message.db");final File messageDbFile = new File(workPath, "message.heap");- this.messageDB = new messageBoard(messageDbFileOld, messageDbFile);+ this.messageDB = new messageBoard(messageDbFile);this.log.logConfig("Loaded Message Board DB from file " + messageDbFile.getName() +", " + this.messageDB.size() + " entries" +", " + ppRamString(messageDbFile.length()/1024));@@ -898,9 +896,8 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.public void initWiki() throws IOException {this.log.logConfig("Starting Wiki Board");- final File wikiDbFileOld = new File(workPath, "wiki.db");final File wikiDbFile = new File(workPath, "wiki.heap");- this.wikiDB = new wikiBoard(wikiDbFileOld, wikiDbFile, new File(workPath, "wiki-bkp.db"), new File(workPath, "wiki-bkp.heap"));+ this.wikiDB = new wikiBoard(wikiDbFile, new File(workPath, "wiki-bkp.heap"));this.log.logConfig("Loaded Wiki Board DB from file " + wikiDbFile.getName() +", " + this.wikiDB.size() + " entries" +", " + ppRamString(wikiDbFile.length()/1024));@@ -908,16 +905,14 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.public void initBlog() throws IOException {this.log.logConfig("Starting Blog");- final File blogDbFileOld = new File(workPath, "blog.db");final File blogDbFile = new File(workPath, "blog.heap");- this.blogDB = new blogBoard(blogDbFileOld, blogDbFile);+ this.blogDB = new blogBoard(blogDbFile);this.log.logConfig("Loaded Blog DB from file " + blogDbFile.getName() +", " + this.blogDB.size() + " entries" +", " + ppRamString(blogDbFile.length()/1024));- final File blogCommentDbFileOld = new File(workPath, "blogComment.db");final File blogCommentDbFile = new File(workPath, "blogComment.heap");- this.blogCommentDB = new blogBoardComments(blogCommentDbFileOld, blogCommentDbFile);+ this.blogCommentDB = new blogBoardComments(blogCommentDbFile);this.log.logConfig("Loaded Blog-Comment DB from file " + blogCommentDbFile.getName() +", " + this.blogCommentDB.size() + " entries" +", " + ppRamString(blogCommentDbFile.length()/1024));@@ -925,16 +920,10 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<IndexingStack.public void initBookmarks() throws IOException{this.log.logConfig("Loading Bookmarks DB");- final File bookmarksFileOld = new File(workPath, "bookmarks.db");- final File tagsFileOld = new File(workPath, "bookmarkTags.db");- final File datesFileOld = new File(workPath, "bookmarkDates.db");final File bookmarksFile = new File(workPath, "bookmarks.heap");final File tagsFile = new File(workPath, "bookmarkTags.heap");final File datesFile = new File(workPath, "bookmarkDates.heap");- this.bookmarksDB = new bookmarksDB(- bookmarksFileOld, bookmarksFile,- tagsFileOld, tagsFile,- datesFileOld, datesFile);+ this.bookmarksDB = new bookmarksDB(bookmarksFile, tagsFile, datesFile);this.log.logConfig("Loaded Bookmarks DB from files "+ bookmarksFile.getName()+ ", "+tagsFile.getName());this.log.logConfig(this.bookmarksDB.tagsSize()+" Tag, "+this.bookmarksDB.bookmarksSize()+" Bookmarks");}