Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance
Java decentralizedintranet-searchintranet-search-enginep2pp2p-networkprivacyprivacy-protectionsearch-enginesearchenginewebweb-search-enginewebsearchwebseearch-engine
changed handling of RowSet element retrieval: until today all elements had been copied from the underlying byte[] arrays into a new Entry object that again had a copy of a portion of that byte[] in its own bye[]. There was an option to just refer to the underlying byte[] with a pointer but that was almost never used. This commit now changes an interface to the Row class where it is now necessary to tell if a copy is always required. Fortunately the copy is only needed in very rare cases. That means that this change should cause much less memory allocation; it is expected that this happens especially during search situations.
orbiter1912d0cccc9e
diff --git a/source/de/anomic/crawler/Balancer.java b/source/de/anomic/crawler/Balancer.javaindex f2c5ec0a6..0f86767b2 100644--- a/source/de/anomic/crawler/Balancer.java+++ b/source/de/anomic/crawler/Balancer.java@@ -152,7 +152,7 @@ public class Balancer {public Request get(final byte[] urlhash) throws IOException {assert urlhash != null;if (this.urlFileIndex == null) return null; // case occurs during shutdown- final Row.Entry entry = this.urlFileIndex.get(urlhash);+ final Row.Entry entry = this.urlFileIndex.get(urlhash, false);if (entry == null) return null;return new Request(entry);}@@ -540,7 +540,7 @@ public class Balancer {Request request;while (i.hasNext()) {handle = i.next();- final Row.Entry entry = this.urlFileIndex.get(handle);+ final Row.Entry entry = this.urlFileIndex.get(handle, false);if (entry == null) continue;request = new Request(entry);host = request.url().getHost();@@ -562,7 +562,7 @@ public class Balancer {for (final byte[] n: ta) {if (n == null) break;try {- final Row.Entry rowEntry = this.urlFileIndex.get(n);+ final Row.Entry rowEntry = this.urlFileIndex.get(n, false);if (rowEntry == null) continue;final Request crawlEntry = new Request(rowEntry);cel.add(crawlEntry);@@ -580,7 +580,7 @@ public class Balancer {final byte[] n = list.getOne(depth);if (n == null) continue ll;try {- final Row.Entry rowEntry = this.urlFileIndex.get(n);+ final Row.Entry rowEntry = this.urlFileIndex.get(n, false);if (rowEntry == null) continue;final Request crawlEntry = new Request(rowEntry);cel.add(crawlEntry);diff --git a/source/de/anomic/crawler/ZURL.java b/source/de/anomic/crawler/ZURL.javaindex adf24f5b8..0b14e5e44 100755--- a/source/de/anomic/crawler/ZURL.java+++ b/source/de/anomic/crawler/ZURL.java@@ -9,7 +9,7 @@// $LastChangedBy$//// 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@@ -47,14 +47,13 @@ import net.yacy.kelondro.order.Base64Order;import net.yacy.kelondro.table.SplitTable;import net.yacy.kelondro.table.Table;import net.yacy.kelondro.util.FileUtils;-import de.anomic.crawler.retrieval.Request;public class ZURL implements Iterable<ZURL.Entry> {-+private static final int EcoFSBufferSize = 2000;private static final int maxStackSize = 1000;-+public enum FailCategory {// TEMPORARY categories are such failure cases that should be tried again// FINAL categories are such failure cases that are final and should not be tried again@@ -63,7 +62,7 @@ public class ZURL implements Iterable<ZURL.Entry> {FINAL_LOAD_CONTEXT, // the crawler configuration does not want to load the entityFINAL_ROBOTS_RULE; // a remote server denies indexing or loading}-+private final static Row rowdef = new Row("String urlhash-" + Word.commonHashLength + ", " + // the url's hash"String executor-" + Word.commonHashLength + ", " + // the crawling executor@@ -78,7 +77,7 @@ public class ZURL implements Iterable<ZURL.Entry> {private Index urlIndex;private final ConcurrentLinkedQueue<byte[]> stack;private final SolrChardingConnector solrConnector;-+public ZURL(final SolrChardingConnector solrConnector,final File cachePath,@@ -97,45 +96,45 @@ public class ZURL implements Iterable<ZURL.Entry> {}try {this.urlIndex = new Table(f, rowdef, EcoFSBufferSize, 0, useTailCache, exceed134217727);- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {try {this.urlIndex = new Table(f, rowdef, 0, 0, false, exceed134217727);- } catch (RowSpaceExceededException e1) {+ } catch (final RowSpaceExceededException e1) {Log.logException(e1);}}//urlIndex = new kelondroFlexTable(cachePath, tablename, -1, rowdef, 0, true);this.stack = new ConcurrentLinkedQueue<byte[]>();}-+public ZURL(final SolrChardingConnector solrConnector) {this.solrConnector = solrConnector;// creates a new ZUR in RAMthis.urlIndex = new RowSet(rowdef);this.stack = new ConcurrentLinkedQueue<byte[]>();}-+public void clear() throws IOException {- if (urlIndex != null) urlIndex.clear();- if (stack != null) stack.clear();+ if (this.urlIndex != null) this.urlIndex.clear();+ if (this.stack != null) this.stack.clear();}public void close() {- try {this.clear();} catch (IOException e) {}- if (urlIndex != null) urlIndex.close();+ try {clear();} catch (final IOException e) {}+ if (this.urlIndex != null) this.urlIndex.close();}public boolean remove(final byte[] hash) {if (hash == null) return false;//System.out.println("*** DEBUG ZURL " + this.urlIndex.filename() + " remove " + hash);try {- urlIndex.delete(hash);+ this.urlIndex.delete(hash);return true;} catch (final IOException e) {return false;}}-+public void push(final Request bentry,final byte[] executor,@@ -143,34 +142,34 @@ public class ZURL implements Iterable<ZURL.Entry> {final int workcount,final FailCategory failCategory,String anycause,- int httpcode) {+ final int httpcode) {// assert executor != null; // null == proxy !if (exists(bentry.url().hash())) return; // don't insert double causesif (anycause == null) anycause = "unknown";- String reason = anycause + ((httpcode >= 0) ? " (http return code = " + httpcode + ")" : "");- Entry entry = new Entry(bentry, executor, workdate, workcount, reason);+ final String reason = anycause + ((httpcode >= 0) ? " (http return code = " + httpcode + ")" : "");+ final Entry entry = new Entry(bentry, executor, workdate, workcount, reason);put(entry);- stack.add(entry.hash());+ this.stack.add(entry.hash());Log.logInfo("Rejected URL", bentry.url().toNormalform(false, false) + " - " + reason);if (this.solrConnector != null && (failCategory == FailCategory.TEMPORARY_NETWORK_FAILURE || failCategory == FailCategory.FINAL_ROBOTS_RULE)) {// send the error to solrtry {this.solrConnector.err(bentry.url(), failCategory.name() + " " + reason, httpcode);- } catch (IOException e) {+ } catch (final IOException e) {Log.logWarning("SOLR", "failed to send error " + bentry.url().toNormalform(true, false) + " to solr: " + e.getMessage());}}- while (stack.size() > maxStackSize) stack.poll();+ while (this.stack.size() > maxStackSize) this.stack.poll();}-+public Iterator<ZURL.Entry> iterator() {return new EntryIterator();}-+public ArrayList<ZURL.Entry> list(int max) {- ArrayList<ZURL.Entry> l = new ArrayList<ZURL.Entry>();+ final ArrayList<ZURL.Entry> l = new ArrayList<ZURL.Entry>();DigestURI url;- for (ZURL.Entry entry: this) {+ for (final ZURL.Entry entry: this) {if (entry == null) continue;url = entry.url();if (url == null) continue;@@ -179,31 +178,31 @@ public class ZURL implements Iterable<ZURL.Entry> {}return l;}-+private class EntryIterator implements Iterator<ZURL.Entry> {private final Iterator<byte[]> hi;public EntryIterator() {- this.hi = stack.iterator();+ this.hi = ZURL.this.stack.iterator();}public boolean hasNext() {- return hi.hasNext();+ return this.hi.hasNext();}public ZURL.Entry next() {- return get(hi.next());+ return get(this.hi.next());}public void remove() {- hi.remove();+ this.hi.remove();}-+}-+public ZURL.Entry get(final byte[] urlhash) {try {- if (urlIndex == null) return null;+ if (this.urlIndex == null) return null;// System.out.println("*** DEBUG ZURL " + this.urlIndex.filename() + " get " + urlhash);- final Row.Entry entry = urlIndex.get(urlhash);+ final Row.Entry entry = this.urlIndex.get(urlhash, false);if (entry == null) return null;return new Entry(entry);} catch (final IOException e) {@@ -216,7 +215,7 @@ public class ZURL implements Iterable<ZURL.Entry> {* private put (use push instead)* @param entry*/- private void put(Entry entry) {+ private void put(final Entry entry) {// stores the values from the object variables into the databaseif (entry.stored) return;if (entry.bentry == null) return;@@ -228,25 +227,25 @@ public class ZURL implements Iterable<ZURL.Entry> {newrow.setCol(4, UTF8.getBytes(entry.anycause));newrow.setCol(5, entry.bentry.toRow().bytes());try {- if (urlIndex != null) urlIndex.put(newrow);+ if (this.urlIndex != null) this.urlIndex.put(newrow);entry.stored = true;} catch (final Exception e) {Log.logException(e);}}-+public boolean exists(final byte[] urlHash) {- return urlIndex.has(urlHash);+ return this.urlIndex.has(urlHash);}-+public void clearStack() {- stack.clear();+ this.stack.clear();}-+public int stackSize() {- return stack.size();+ return this.stack.size();}-+public class Entry {Request bentry; // the balancer entry@@ -270,7 +269,7 @@ public class ZURL implements Iterable<ZURL.Entry> {this.workdate = (workdate == null) ? new Date() : workdate;this.workcount = workcount;this.anycause = (anycause == null) ? "" : anycause;- stored = false;+ this.stored = false;}protected Entry(final Row.Entry entry) throws IOException {@@ -280,7 +279,7 @@ public class ZURL implements Iterable<ZURL.Entry> {this.workcount = (int) entry.getColLong(3);this.anycause = entry.getColString(4);this.bentry = new Request(Request.rowdef.newEntry(entry.getColBytes(5, false)));- assert (Base64Order.enhancedCoder.equal(entry.getPrimaryKeyBytes(), bentry.url().hash()));+ assert (Base64Order.enhancedCoder.equal(entry.getPrimaryKeyBytes(), this.bentry.url().hash()));this.stored = true;return;}@@ -288,11 +287,11 @@ public class ZURL implements Iterable<ZURL.Entry> {public DigestURI url() {return this.bentry.url();}-+public byte[] initiator() {return this.bentry.initiator();}-+public byte[] hash() {// return a url-hash, based on the md5 algorithm// the result is a String of 12 bytes within a 72-bit space@@ -302,37 +301,37 @@ public class ZURL implements Iterable<ZURL.Entry> {}public Date workdate() {- return workdate;+ return this.workdate;}-+public byte[] executor() {// return the creator's hash- return executor;+ return this.executor;}-+public String anycause() {- return anycause;+ return this.anycause;}}private class kiter implements Iterator<Entry> {// enumerates entry elements- private Iterator<Row.Entry> i;+ private final Iterator<Row.Entry> i;private boolean error = false;-+private kiter(final boolean up, final String firstHash) throws IOException {- i = urlIndex.rows(up, (firstHash == null) ? null : ASCII.getBytes(firstHash));- error = false;+ this.i = ZURL.this.urlIndex.rows(up, (firstHash == null) ? null : ASCII.getBytes(firstHash));+ this.error = false;}public boolean hasNext() {- if (error) return false;- return i.hasNext();+ if (this.error) return false;+ return this.i.hasNext();}public Entry next() throws RuntimeException {- final Row.Entry e = i.next();+ final Row.Entry e = this.i.next();if (e == null) return null;try {return new Entry(e);@@ -340,11 +339,11 @@ public class ZURL implements Iterable<ZURL.Entry> {throw new RuntimeException("error '" + ex.getMessage() + "' for hash " + e.getColString(0));}}-+public void remove() {- i.remove();+ this.i.remove();}-+}public Iterator<Entry> entries(final boolean up, final String firstHash) throws IOException {diff --git a/source/de/anomic/search/MetadataRepository.java b/source/de/anomic/search/MetadataRepository.javaindex 3b5bd119b..2e27a7240 100644--- a/source/de/anomic/search/MetadataRepository.java+++ b/source/de/anomic/search/MetadataRepository.java@@ -9,7 +9,7 @@// $LastChangedBy$//// 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@@ -38,8 +38,6 @@ import java.util.Iterator;import java.util.Map;import java.util.TreeSet;-import de.anomic.crawler.CrawlStacker;-import net.yacy.cora.document.ASCII;import net.yacy.cora.document.MultiProtocolURI;import net.yacy.cora.document.UTF8;@@ -61,13 +59,14 @@ import net.yacy.kelondro.order.CloneableIterator;import net.yacy.kelondro.table.SplitTable;import net.yacy.kelondro.util.MemoryControl;import net.yacy.repository.Blacklist;+import de.anomic.crawler.CrawlStacker;public final class MetadataRepository implements Iterable<byte[]> {// class objectsprotected Index urlIndexFile;private Export exportthread; // will have a export thread assigned if exporter is running- private File location;+ private final File location;private ArrayList<HostStat> statsDump;public MetadataRepository(@@ -79,10 +78,10 @@ public final class MetadataRepository implements Iterable<byte[]> {Index backupIndex = null;try {backupIndex = new SplitTable(this.location, tablename, URIMetadataRow.rowdef, useTailCache, exceed134217727);- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {try {backupIndex = new SplitTable(this.location, tablename, URIMetadataRow.rowdef, false, exceed134217727);- } catch (RowSpaceExceededException e1) {+ } catch (final RowSpaceExceededException e1) {Log.logException(e1);}}@@ -92,34 +91,34 @@ public final class MetadataRepository implements Iterable<byte[]> {}public void clearCache() {- if (urlIndexFile instanceof Cache) ((Cache) urlIndexFile).clearCache();- statsDump = null;+ if (this.urlIndexFile instanceof Cache) ((Cache) this.urlIndexFile).clearCache();+ this.statsDump = null;}-+public void clear() throws IOException {- if (exportthread != null) exportthread.interrupt();- urlIndexFile.clear();- statsDump = null;+ if (this.exportthread != null) this.exportthread.interrupt();+ this.urlIndexFile.clear();+ this.statsDump = null;}-+public int size() {- return urlIndexFile == null ? 0 : urlIndexFile.size();+ return this.urlIndexFile == null ? 0 : this.urlIndexFile.size();}public void close() {- statsDump = null;- if (urlIndexFile != null) {- urlIndexFile.close();- urlIndexFile = null;+ this.statsDump = null;+ if (this.urlIndexFile != null) {+ this.urlIndexFile.close();+ this.urlIndexFile = null;}}public int writeCacheSize() {- if (urlIndexFile instanceof SplitTable) return ((SplitTable) urlIndexFile).writeBufferSize();- if (urlIndexFile instanceof Cache) return ((Cache) urlIndexFile).writeBufferSize();+ if (this.urlIndexFile instanceof SplitTable) return ((SplitTable) this.urlIndexFile).writeBufferSize();+ if (this.urlIndexFile instanceof Cache) return ((Cache) this.urlIndexFile).writeBufferSize();return 0;}-+/*** generates an plasmaLURLEntry using the url hash* if the url cannot be found, this returns null@@ -127,24 +126,24 @@ public final class MetadataRepository implements Iterable<byte[]> {* @return*/public URIMetadataRow load(final WeakPriorityBlockingQueue.Element<WordReferenceVars> obrwi) {- if (urlIndexFile == null) return null;+ if (this.urlIndexFile == null) return null;if (obrwi == null) return null; // all time was already wasted in takeRWI to get another element- byte[] urlHash = obrwi.getElement().urlhash();+ final byte[] urlHash = obrwi.getElement().urlhash();if (urlHash == null) return null;try {- final Row.Entry entry = urlIndexFile.get(urlHash);+ final Row.Entry entry = this.urlIndexFile.get(urlHash, false);if (entry == null) return null;return new URIMetadataRow(entry, obrwi.getElement(), obrwi.getWeight());} catch (final IOException e) {return null;}}-+public URIMetadataRow load(final byte[] urlHash) {- if (urlIndexFile == null) return null;+ if (this.urlIndexFile == null) return null;if (urlHash == null) return null;try {- final Row.Entry entry = urlIndexFile.get(urlHash);+ final Row.Entry entry = this.urlIndexFile.get(urlHash, false);if (entry == null) return null;return new URIMetadataRow(entry, null, 0);} catch (final IOException e) {@@ -155,9 +154,9 @@ public final class MetadataRepository implements Iterable<byte[]> {public void store(final URIMetadataRow entry) throws IOException {// Check if there is a more recent Entry already in the DBURIMetadataRow oldEntry;- if (urlIndexFile == null) return; // case may happen during shutdown or startup+ if (this.urlIndexFile == null) return; // case may happen during shutdown or startuptry {- Row.Entry oe = urlIndexFile.get(entry.hash());+ final Row.Entry oe = this.urlIndexFile.get(entry.hash(), false);oldEntry = (oe == null) ? null : new URIMetadataRow(oe, null, 0);} catch (final Exception e) {Log.logException(e);@@ -173,19 +172,19 @@ public final class MetadataRepository implements Iterable<byte[]> {}try {- urlIndexFile.put(entry.toRowEntry());- } catch (RowSpaceExceededException e) {+ this.urlIndexFile.put(entry.toRowEntry());+ } catch (final RowSpaceExceededException e) {throw new IOException("RowSpaceExceededException in " + this.urlIndexFile.filename() + ": " + e.getMessage());}- statsDump = null;+ this.statsDump = null;if (MemoryControl.shortStatus()) clearCache() ;}-+public boolean remove(final byte[] urlHashBytes) {if (urlHashBytes == null) return false;try {- final Row.Entry r = urlIndexFile.remove(urlHashBytes);- if (r != null) statsDump = null;+ final Row.Entry r = this.urlIndexFile.remove(urlHashBytes);+ if (r != null) this.statsDump = null;return r != null;} catch (final IOException e) {return false;@@ -193,14 +192,14 @@ public final class MetadataRepository implements Iterable<byte[]> {}public boolean exists(final byte[] urlHash) {- if (urlIndexFile == null) return false; // case may happen during shutdown- return urlIndexFile.has(urlHash);+ if (this.urlIndexFile == null) return false; // case may happen during shutdown+ return this.urlIndexFile.has(urlHash);}- public CloneableIterator<byte[]> keys(boolean up, byte[] firstKey) {+ public CloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) {try {return this.urlIndexFile.keys(up, firstKey);- } catch (IOException e) {+ } catch (final IOException e) {Log.logException(e);return null;}@@ -209,7 +208,7 @@ public final class MetadataRepository implements Iterable<byte[]> {public Iterator<byte[]> iterator() {return keys(true, null);}-+public CloneableIterator<URIMetadataRow> entries() throws IOException {// enumerates entry elementsreturn new kiter();@@ -228,24 +227,24 @@ public final class MetadataRepository implements Iterable<byte[]> {public kiter() throws IOException {this.up = true;- this.iter = urlIndexFile.rows();+ this.iter = MetadataRepository.this.urlIndexFile.rows();this.error = false;}public kiter(final boolean up, final String firstHash) throws IOException {this.up = up;- this.iter = urlIndexFile.rows(up, (firstHash == null) ? null : ASCII.getBytes(firstHash));+ this.iter = MetadataRepository.this.urlIndexFile.rows(up, (firstHash == null) ? null : ASCII.getBytes(firstHash));this.error = false;}public kiter clone(final Object secondHash) {try {- return new kiter(up, (String) secondHash);+ return new kiter(this.up, (String) secondHash);} catch (final IOException e) {return null;}}-+public final boolean hasNext() {if (this.error) return false;if (this.iter == null) return false;@@ -269,8 +268,8 @@ public final class MetadataRepository implements Iterable<byte[]> {/*** Uses an Iteration over urlHash.db to detect malformed URL-Entries.* Damaged URL-Entries will be marked in a HashSet and removed at the end of the function.- *- * @param proxyConfig+ *+ * @param proxyConfig*/public void deadlinkCleaner() {final Log log = new Log("URLDBCLEANUP");@@ -289,7 +288,7 @@ public final class MetadataRepository implements Iterable<byte[]> {log.logSevere("RuntimeException:", e);}}- log.logInfo("URLs vorher: " + urlIndexFile.size() + " Entries loaded during Iteratorloop: " + iteratorCount + " kaputte URLs: " + damagedURLS.size());+ log.logInfo("URLs vorher: " + this.urlIndexFile.size() + " Entries loaded during Iteratorloop: " + iteratorCount + " kaputte URLs: " + damagedURLS.size());final HTTPClient client = new HTTPClient();final Iterator<String> eiter2 = damagedURLS.iterator();@@ -301,7 +300,7 @@ public final class MetadataRepository implements Iterable<byte[]> {String oldUrlStr = null;try {// getting the url data as byte array- final Row.Entry entry = urlIndexFile.get(urlHashBytes);+ final Row.Entry entry = this.urlIndexFile.get(urlHashBytes, true);// getting the wrong url stringoldUrlStr = entry.getColString(1).trim();@@ -315,7 +314,7 @@ public final class MetadataRepository implements Iterable<byte[]> {if (client.HEADResponse(newUrl.toString()) != null&& client.getHttpResponse().getStatusLine().getStatusCode() == 200) {entry.setCol(1, UTF8.getBytes(newUrl.toString()));- urlIndexFile.put(entry);+ this.urlIndexFile.put(entry);if (log.isInfo()) log.logInfo("UrlDB-Entry with urlHash '" + ASCII.String(urlHashBytes) + "' corrected\n\tURL: " + oldUrlStr + " -> " + newUrlStr);} else {remove(urlHashBytes);@@ -337,7 +336,7 @@ public final class MetadataRepository implements Iterable<byte[]> {public BlacklistCleaner getBlacklistCleaner(final Blacklist blacklist, final CrawlStacker crawlStacker) {return new BlacklistCleaner(blacklist, crawlStacker);}-+public class BlacklistCleaner extends Thread {private boolean run = true;@@ -360,7 +359,7 @@ public final class MetadataRepository implements Iterable<byte[]> {try {Log.logInfo("URLDBCLEANER", "UrldbCleaner-Thread startet");final Iterator<URIMetadataRow> eiter = entries(true, null);- while (eiter.hasNext() && run) {+ while (eiter.hasNext() && this.run) {synchronized (this) {if (this.pause) {try {@@ -376,33 +375,33 @@ public final class MetadataRepository implements Iterable<byte[]> {if (entry == null) {if (Log.isFine("URLDBCLEANER")) Log.logFine("URLDBCLEANER", "entry == null");} else if (entry.hash() == null) {- if (Log.isFine("URLDBCLEANER")) Log.logFine("URLDBCLEANER", ++blacklistedUrls + " blacklisted (" + ((double) blacklistedUrls / totalSearchedUrls) * 100 + "%): " + "hash == null");+ if (Log.isFine("URLDBCLEANER")) Log.logFine("URLDBCLEANER", ++this.blacklistedUrls + " blacklisted (" + ((double) this.blacklistedUrls / this.totalSearchedUrls) * 100 + "%): " + "hash == null");} else {final URIMetadataRow.Components metadata = entry.metadata();- totalSearchedUrls++;+ this.totalSearchedUrls++;if (metadata == null) {if (Log.isFine("URLDBCLEANER")) Log.logFine("URLDBCLEANER", "corrupted entry for hash = " + ASCII.String(entry.hash()));remove(entry.hash());continue;}if (metadata.url() == null) {- if (Log.isFine("URLDBCLEANER")) Log.logFine("URLDBCLEANER", ++blacklistedUrls + " blacklisted (" + ((double) blacklistedUrls / totalSearchedUrls) * 100 + "%): " + ASCII.String(entry.hash()) + "URL == null");+ if (Log.isFine("URLDBCLEANER")) Log.logFine("URLDBCLEANER", ++this.blacklistedUrls + " blacklisted (" + ((double) this.blacklistedUrls / this.totalSearchedUrls) * 100 + "%): " + ASCII.String(entry.hash()) + "URL == null");remove(entry.hash());continue;}- if (blacklist.isListed(Blacklist.BLACKLIST_CRAWLER, metadata.url()) ||- blacklist.isListed(Blacklist.BLACKLIST_DHT, metadata.url()) ||- (crawlStacker.urlInAcceptedDomain(metadata.url()) != null)) {- lastBlacklistedUrl = metadata.url().toNormalform(true, true);- lastBlacklistedHash = ASCII.String(entry.hash());- if (Log.isFine("URLDBCLEANER")) Log.logFine("URLDBCLEANER", ++blacklistedUrls + " blacklisted (" + ((double) blacklistedUrls / totalSearchedUrls) * 100 + "%): " + ASCII.String(entry.hash()) + " " + metadata.url().toNormalform(false, true));+ if (this.blacklist.isListed(Blacklist.BLACKLIST_CRAWLER, metadata.url()) ||+ this.blacklist.isListed(Blacklist.BLACKLIST_DHT, metadata.url()) ||+ (this.crawlStacker.urlInAcceptedDomain(metadata.url()) != null)) {+ this.lastBlacklistedUrl = metadata.url().toNormalform(true, true);+ this.lastBlacklistedHash = ASCII.String(entry.hash());+ if (Log.isFine("URLDBCLEANER")) Log.logFine("URLDBCLEANER", ++this.blacklistedUrls + " blacklisted (" + ((double) this.blacklistedUrls / this.totalSearchedUrls) * 100 + "%): " + ASCII.String(entry.hash()) + " " + metadata.url().toNormalform(false, true));remove(entry.hash());- if (blacklistedUrls % 100 == 0) {- Log.logInfo("URLDBCLEANER", "Deleted " + blacklistedUrls + " URLs until now. Last deleted URL-Hash: " + lastBlacklistedUrl);+ if (this.blacklistedUrls % 100 == 0) {+ Log.logInfo("URLDBCLEANER", "Deleted " + this.blacklistedUrls + " URLs until now. Last deleted URL-Hash: " + this.lastBlacklistedUrl);}}- lastUrl = metadata.url().toNormalform(true, true);- lastHash = ASCII.String(entry.hash());+ this.lastUrl = metadata.url().toNormalform(true, true);+ this.lastHash = ASCII.String(entry.hash());}}} catch (final RuntimeException e) {@@ -411,29 +410,29 @@ public final class MetadataRepository implements Iterable<byte[]> {}else {Log.logWarning("URLDBCLEANER", "RuntimeException", e);- run = false;+ this.run = false;}} catch (final IOException e) {Log.logException(e);- run = false;+ this.run = false;} catch (final Exception e) {Log.logException(e);- run = false;+ this.run = false;}Log.logInfo("URLDBCLEANER", "UrldbCleaner-Thread stopped");}public void abort() {synchronized(this) {- run = false;- this.notifyAll();+ this.run = false;+ notifyAll();}}public void pause() {synchronized(this) {- if (!pause) {- pause = true;+ if (!this.pause) {+ this.pause = true;Log.logInfo("URLDBCLEANER", "UrldbCleaner-Thread paused");}}@@ -441,30 +440,30 @@ public final class MetadataRepository implements Iterable<byte[]> {public void endPause() {synchronized(this) {- if (pause) {- pause = false;- this.notifyAll();+ if (this.pause) {+ this.pause = false;+ notifyAll();Log.logInfo("URLDBCLEANER", "UrldbCleaner-Thread resumed");}}}}-+// export methods- public Export export(final File f, final String filter, HandleSet set, final int format, final boolean dom) {- if ((exportthread != null) && (exportthread.isAlive())) {+ public Export export(final File f, final String filter, final HandleSet set, final int format, final boolean dom) {+ if ((this.exportthread != null) && (this.exportthread.isAlive())) {Log.logWarning("LURL-EXPORT", "cannot start another export thread, already one running");- return exportthread;+ return this.exportthread;}this.exportthread = new Export(f, filter, set, format, dom);this.exportthread.start();- return exportthread;+ return this.exportthread;}-+public Export export() {return this.exportthread;}-+public class Export extends Thread {private final File f;private final String filter;@@ -473,8 +472,8 @@ public final class MetadataRepository implements Iterable<byte[]> {private final int format;private final boolean dom;private final HandleSet set;-- public Export(final File f, final String filter, HandleSet set, final int format, boolean dom) {++ public Export(final File f, final String filter, final HandleSet set, final int format, boolean dom) {// format: 0=text, 1=html, 2=rss/xmlthis.f = f;this.filter = filter;@@ -485,16 +484,16 @@ public final class MetadataRepository implements Iterable<byte[]> {this.set = set;if ((dom) && (format == 2)) dom = false;}-+public void run() {try {- File parentf = f.getParentFile();+ final File parentf = this.f.getParentFile();if (parentf != null) parentf.mkdirs();- final PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(f)));- if (format == 1) {+ final PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(this.f)));+ if (this.format == 1) {pw.println("<html><head></head><body>");}- if (format == 2) {+ if (this.format == 2) {pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");pw.println("<?xml-stylesheet type='text/xsl' href='/yacysearch.xsl' version='1.0'?>");pw.println("<rss version=\"2.0\" xmlns:yacy=\"http://www.yacy.net/\" xmlns:opensearch=\"http://a9.com/-/spec/opensearch/1.1/\" xmlns:atom=\"http://www.w3.org/2005/Atom\">");@@ -503,14 +502,14 @@ public final class MetadataRepository implements Iterable<byte[]> {pw.println("<description></description>");pw.println("<link>http://yacy.net</link>");}-- if (dom) {- TreeSet<String> set = domainNameCollector(-1, domainSampleCollector());- for (String host: set) {- if (!host.matches(filter)) continue;- if (format == 0) pw.println(host);- if (format == 1) pw.println("<a href=\"http://" + host + "\">" + host + "</a><br>");- count++;++ if (this.dom) {+ final TreeSet<String> set = domainNameCollector(-1, domainSampleCollector());+ for (final String host: set) {+ if (!host.matches(this.filter)) continue;+ if (this.format == 0) pw.println(host);+ if (this.format == 1) pw.println("<a href=\"http://" + host + "\">" + host + "</a><br>");+ this.count++;}} else {final Iterator<URIMetadataRow> i = entries(); // iterates indexURLEntry objects@@ -519,17 +518,17 @@ public final class MetadataRepository implements Iterable<byte[]> {String url;while (i.hasNext()) {entry = i.next();- if (this.set != null && !set.has(entry.hash())) continue;+ if (this.set != null && !this.set.has(entry.hash())) continue;metadata = entry.metadata();url = metadata.url().toNormalform(true, false);- if (!url.matches(filter)) continue;- if (format == 0) {+ if (!url.matches(this.filter)) continue;+ if (this.format == 0) {pw.println(url);}- if (format == 1) {+ if (this.format == 1) {pw.println("<a href=\"" + url + "\">" + CharacterCoding.unicode2xml(metadata.dc_title(), true) + "</a><br>");}- if (format == 2) {+ if (this.format == 2) {pw.println("<item>");pw.println("<title>" + CharacterCoding.unicode2xml(metadata.dc_title(), true) + "</title>");pw.println("<link>" + MultiProtocolURI.escape(url) + "</link>");@@ -540,13 +539,13 @@ public final class MetadataRepository implements Iterable<byte[]> {pw.println("<guid isPermaLink=\"false\">" + ASCII.String(entry.hash()) + "</guid>");pw.println("</item>");}- count++;+ this.count++;}}- if (format == 1) {+ if (this.format == 1) {pw.println("</body></html>");}- if (format == 2) {+ if (this.format == 2) {pw.println("</channel>");pw.println("</rss>");}@@ -560,21 +559,21 @@ public final class MetadataRepository implements Iterable<byte[]> {}// terminate process}-+public File file() {return this.f;}-+public String failed() {return this.failure;}-+public int count() {return this.count;}-+}-+/*** collect domain samples: all url hashes from the metadata database is listed and the domain part* of the url hashes is used to count how many of these domain hashes appear@@ -582,9 +581,9 @@ public final class MetadataRepository implements Iterable<byte[]> {* @throws IOException*/public Map<String, URLHashCounter> domainSampleCollector() throws IOException {- Map<String, URLHashCounter> map = new HashMap<String, URLHashCounter>();+ final Map<String, URLHashCounter> map = new HashMap<String, URLHashCounter>();// first collect all domains and calculate statistics about it- CloneableIterator<byte[]> i = this.urlIndexFile.keys(true, null);+ final CloneableIterator<byte[]> i = this.urlIndexFile.keys(true, null);String hosthash;byte[] urlhashb;URLHashCounter ds;@@ -601,22 +600,22 @@ public final class MetadataRepository implements Iterable<byte[]> {}return map;}-+/*** create a list of domain names in this database* @param count number of entries or -1 for all* @param domainSamples a map from domain hashes to hash statistics* @return a set of domain names, ordered by name of the domains*/- public TreeSet<String> domainNameCollector(int count, Map<String, URLHashCounter> domainSamples) {+ public TreeSet<String> domainNameCollector(int count, final Map<String, URLHashCounter> domainSamples) {// collect hashes from all domains-+// fetch urls from the database to determine the host in clear textURIMetadataRow urlref;if (count < 0 || count > domainSamples.size()) count = domainSamples.size();- statsDump = new ArrayList<HostStat>();- TreeSet<String> set = new TreeSet<String>();- for (URLHashCounter hs: domainSamples.values()) {+ this.statsDump = new ArrayList<HostStat>();+ final TreeSet<String> set = new TreeSet<String>();+ for (final URLHashCounter hs: domainSamples.values()) {if (hs == null) continue;urlref = this.load(hs.urlhashb);if (urlref == null || urlref.metadata() == null || urlref.metadata().url() == null || urlref.metadata().url().getHost() == null) continue;@@ -634,30 +633,30 @@ public final class MetadataRepository implements Iterable<byte[]> {* @param domainSamples a map from domain hashes to hash statistics* @return a map from url hash samples to counters*/- public ScoreMap<String> urlSampleScores(Map<String, URLHashCounter> domainSamples) {- ScoreMap<String> urlSampleScore = new ConcurrentScoreMap<String>();- for (Map.Entry<String, URLHashCounter> e: domainSamples.entrySet()) {+ public ScoreMap<String> urlSampleScores(final Map<String, URLHashCounter> domainSamples) {+ final ScoreMap<String> urlSampleScore = new ConcurrentScoreMap<String>();+ for (final Map.Entry<String, URLHashCounter> e: domainSamples.entrySet()) {urlSampleScore.inc(ASCII.String(e.getValue().urlhashb), e.getValue().count);}return urlSampleScore;}-+/*** calculate all domain names for all domain hashes* @param domainSamples a map from domain hashes to hash statistics* @return a map from domain hashes to host stats including domain names*/- public Map<String, HostStat> domainHashResolver(Map<String, URLHashCounter> domainSamples) {- HashMap<String, HostStat> hostMap = new HashMap<String, HostStat>();+ public Map<String, HostStat> domainHashResolver(final Map<String, URLHashCounter> domainSamples) {+ final HashMap<String, HostStat> hostMap = new HashMap<String, HostStat>();URIMetadataRow urlref;-- ScoreMap<String> hosthashScore = new ConcurrentScoreMap<String>();- for (Map.Entry<String, URLHashCounter> e: domainSamples.entrySet()) {++ final ScoreMap<String> hosthashScore = new ConcurrentScoreMap<String>();+ for (final Map.Entry<String, URLHashCounter> e: domainSamples.entrySet()) {hosthashScore.inc(ASCII.String(e.getValue().urlhashb, 6, 6), e.getValue().count);}URIMetadataRow.Components comps;DigestURI url;- for (Map.Entry<String, URLHashCounter> e: domainSamples.entrySet()) {+ for (final Map.Entry<String, URLHashCounter> e: domainSamples.entrySet()) {urlref = this.load(e.getValue().urlhashb);comps = urlref.metadata();url = comps.url();@@ -665,18 +664,18 @@ public final class MetadataRepository implements Iterable<byte[]> {}return hostMap;}-- public Iterator<HostStat> statistics(int count, ScoreMap<String> domainScore) {++ public Iterator<HostStat> statistics(int count, final ScoreMap<String> domainScore) {// prevent too heavy IO.- if (statsDump != null && count <= statsDump.size()) return statsDump.iterator();-+ if (this.statsDump != null && count <= this.statsDump.size()) return this.statsDump.iterator();+// fetch urls from the database to determine the host in clear text- Iterator<String> j = domainScore.keys(false); // iterate urlhash-examples in reverse order (biggest first)+ final Iterator<String> j = domainScore.keys(false); // iterate urlhash-examples in reverse order (biggest first)URIMetadataRow urlref;String urlhash;count += 10; // make some more to prevent that we have to do this again after deletions too soon.if (count < 0 || domainScore.sizeSmaller(count)) count = domainScore.size();- statsDump = new ArrayList<HostStat>();+ this.statsDump = new ArrayList<HostStat>();URIMetadataRow.Components comps;DigestURI url;while (j.hasNext()) {@@ -684,31 +683,31 @@ public final class MetadataRepository implements Iterable<byte[]> {if (urlhash == null) continue;urlref = this.load(ASCII.getBytes(urlhash));if (urlref == null || urlref.metadata() == null || urlref.metadata().url() == null || urlref.metadata().url().getHost() == null) continue;- if (statsDump == null) return new ArrayList<HostStat>().iterator(); // some other operation has destroyed the object+ if (this.statsDump == null) return new ArrayList<HostStat>().iterator(); // some other operation has destroyed the objectcomps = urlref.metadata();url = comps.url();- statsDump.add(new HostStat(url.getHost(), url.getPort(), urlhash.substring(6), domainScore.get(urlhash)));+ this.statsDump.add(new HostStat(url.getHost(), url.getPort(), urlhash.substring(6), domainScore.get(urlhash)));count--;if (count == 0) break;}// finally return an iterator for the result array- return (statsDump == null) ? new ArrayList<HostStat>().iterator() : statsDump.iterator();+ return (this.statsDump == null) ? new ArrayList<HostStat>().iterator() : this.statsDump.iterator();}-+private static class URLHashCounter {public byte[] urlhashb;public int count;- public URLHashCounter(byte[] urlhashb) {+ public URLHashCounter(final byte[] urlhashb) {this.urlhashb = urlhashb;this.count = 1;}}-+public static class HostStat {public String hostname, hosthash;public int port;public int count;- public HostStat(String host, int port, String urlhashfragment, int count) {+ public HostStat(final String host, final int port, final String urlhashfragment, final int count) {assert urlhashfragment.length() == 6;this.hostname = host;this.port = port;@@ -716,7 +715,7 @@ public final class MetadataRepository implements Iterable<byte[]> {this.count = count;}}-+/*** using a fragment of the url hash (5 bytes: bytes 6 to 10) it is possible to address all urls from a specific domain* here such a fragment can be used to delete all these domains at once@@ -724,26 +723,26 @@ public final class MetadataRepository implements Iterable<byte[]> {* @return number of deleted domains* @throws IOException*/- public int deleteDomain(String hosthash) throws IOException {+ public int deleteDomain(final String hosthash) throws IOException {// first collect all url hashes that belong to the domainassert hosthash.length() == 6;- ArrayList<String> l = new ArrayList<String>();- CloneableIterator<byte[]> i = this.urlIndexFile.keys(true, null);+ final ArrayList<String> l = new ArrayList<String>();+ final CloneableIterator<byte[]> i = this.urlIndexFile.keys(true, null);String hash;while (i != null && i.hasNext()) {hash = ASCII.String(i.next());if (hosthash.equals(hash.substring(6))) l.add(hash);}-+// then delete the urls using this listint cnt = 0;- for (String h: l) {- if (urlIndexFile.delete(ASCII.getBytes(h))) cnt++;+ for (final String h: l) {+ if (this.urlIndexFile.delete(ASCII.getBytes(h))) cnt++;}-+// finally remove the line with statistics- if (statsDump != null) {- Iterator<HostStat> hsi = statsDump.iterator();+ if (this.statsDump != null) {+ final Iterator<HostStat> hsi = this.statsDump.iterator();HostStat hs;while (hsi.hasNext()) {hs = hsi.next();@@ -753,7 +752,7 @@ public final class MetadataRepository implements Iterable<byte[]> {}}}-+return cnt;}}diff --git a/source/de/anomic/yacy/yacyNewsDB.java b/source/de/anomic/yacy/yacyNewsDB.javaindex e7fdcc473..041ee4263 100644--- a/source/de/anomic/yacy/yacyNewsDB.java+++ b/source/de/anomic/yacy/yacyNewsDB.java@@ -50,8 +50,8 @@ import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.Map;-import java.util.Properties;import java.util.Map.Entry;+import java.util.Properties;import net.yacy.cora.date.GenericFormatter;import net.yacy.cora.document.UTF8;@@ -64,8 +64,8 @@ import net.yacy.kelondro.order.Base64Order;import net.yacy.kelondro.order.NaturalOrder;import net.yacy.kelondro.table.Table;import net.yacy.kelondro.util.FileUtils;-import net.yacy.kelondro.util.kelondroException;import net.yacy.kelondro.util.MapTools;+import net.yacy.kelondro.util.kelondroException;public class yacyNewsDB {@@ -94,15 +94,15 @@ public class yacyNewsDB {"String cat-" + categoryStringLength + "," +"String rec-" + GenericFormatter.PATTERN_SHORT_SECOND.length() + "," +"short dis-2 {b64e}," +- "String att-" + attributesMaxLength,+ "String att-" + this.attributesMaxLength,NaturalOrder.naturalOrder);try {- this.news = new Table(path, rowdef, 10, 0, useTailCache, exceed134217727);- } catch (RowSpaceExceededException e) {+ this.news = new Table(path, this.rowdef, 10, 0, useTailCache, exceed134217727);+ } catch (final RowSpaceExceededException e) {try {- this.news = new Table(path, rowdef, 0, 0, false, exceed134217727);- } catch (RowSpaceExceededException e1) {+ this.news = new Table(path, this.rowdef, 0, 0, false, exceed134217727);+ } catch (final RowSpaceExceededException e1) {Log.logException(e1);}}@@ -110,21 +110,21 @@ public class yacyNewsDB {private void resetDB() {try {close();} catch (final Exception e) {}- if (path.exists()) FileUtils.deletedelete(path);+ if (this.path.exists()) FileUtils.deletedelete(this.path);try {- this.news = new Table(path, rowdef, 10, 0, false, false);- } catch (RowSpaceExceededException e) {+ this.news = new Table(this.path, this.rowdef, 10, 0, false, false);+ } catch (final RowSpaceExceededException e) {try {- this.news = new Table(path, rowdef, 0, 0, false, false);- } catch (RowSpaceExceededException e1) {+ this.news = new Table(this.path, this.rowdef, 0, 0, false, false);+ } catch (final RowSpaceExceededException e1) {Log.logException(e1);}}}-+public void close() {- if (news != null) news.close();- news = null;+ if (this.news != null) this.news.close();+ this.news = null;}@Override@@ -133,31 +133,31 @@ public class yacyNewsDB {}public int size() {- return news.size();+ return this.news.size();}public void remove(final String id) throws IOException {- news.delete(UTF8.getBytes(id));+ this.news.delete(UTF8.getBytes(id));}public synchronized Record put(final Record record) throws IOException, RowSpaceExceededException {try {- return b2r(news.replace(r2b(record)));+ return b2r(this.news.replace(r2b(record)));} catch (final Exception e) {resetDB();- return b2r(news.replace(r2b(record)));+ return b2r(this.news.replace(r2b(record)));}}public synchronized Record get(final String id) throws IOException {try {- return b2r(news.get(UTF8.getBytes(id)));+ return b2r(this.news.get(UTF8.getBytes(id), false));} catch (final kelondroException e) {resetDB();return null;}}-+// use our own formatter to prevent concurrency locks with other processesprivate final static GenericFormatter my_SHORT_SECOND_FORMATTER = new GenericFormatter(GenericFormatter.FORMAT_SHORT_SECOND, GenericFormatter.time_second);@@ -175,8 +175,8 @@ public class yacyNewsDB {private final Row.Entry r2b(final Record r) {if (r == null) return null;String attributes = r.attributes().toString();- if (attributes.length() > attributesMaxLength) {- Log.logWarning("yacyNewsDB", "attribute length=" + attributes.length() + " exceeds maximum size=" + attributesMaxLength);+ if (attributes.length() > this.attributesMaxLength) {+ Log.logWarning("yacyNewsDB", "attribute length=" + attributes.length() + " exceeds maximum size=" + this.attributesMaxLength);attributes = new HashMap<String, String>().toString();}final Row.Entry entry = this.news.row().newEntry();@@ -187,7 +187,7 @@ public class yacyNewsDB {entry.setCol(4, UTF8.getBytes(attributes));return entry;}-+public Record newRecord(final yacySeed mySeed, final String category, final Properties attributes) {try {final Map<String, String> m = new HashMap<String, String>();@@ -213,7 +213,7 @@ public class yacyNewsDB {}}- public Record newRecord(String external) {+ public Record newRecord(final String external) {try {return new Record(external);} catch (final IllegalArgumentException e) {@@ -231,22 +231,22 @@ public class yacyNewsDB {private int distributed; // counter that counts number of distributions of this news recordprivate final Map<String, String> attributes; // elements of the news for a special category-+private Record(final String newsString) {this.attributes = MapTools.string2map(newsString, ",");- if (attributes.toString().length() > attributesMaxLength) throw new IllegalArgumentException("attributes length (" + attributes.toString().length() + ") exceeds maximum (" + attributesMaxLength + ")");- this.category = (attributes.containsKey("cat")) ? attributes.get("cat") : "";- if (category.length() > yacyNewsDB.categoryStringLength) throw new IllegalArgumentException("category length (" + category.length() + ") exceeds maximum (" + yacyNewsDB.categoryStringLength + ")");- this.received = (attributes.containsKey("rec")) ? my_SHORT_SECOND_FORMATTER.parse(attributes.get("rec"), GenericFormatter.UTCDiffString()) : new Date();- this.created = (attributes.containsKey("cre")) ? my_SHORT_SECOND_FORMATTER.parse(attributes.get("cre"), GenericFormatter.UTCDiffString()) : new Date();- this.distributed = (attributes.containsKey("dis")) ? Integer.parseInt(attributes.get("dis")) : 0;- this.originator = (attributes.containsKey("ori")) ? attributes.get("ori") : "";+ if (this.attributes.toString().length() > yacyNewsDB.this.attributesMaxLength) throw new IllegalArgumentException("attributes length (" + this.attributes.toString().length() + ") exceeds maximum (" + yacyNewsDB.this.attributesMaxLength + ")");+ this.category = (this.attributes.containsKey("cat")) ? this.attributes.get("cat") : "";+ if (this.category.length() > yacyNewsDB.categoryStringLength) throw new IllegalArgumentException("category length (" + this.category.length() + ") exceeds maximum (" + yacyNewsDB.categoryStringLength + ")");+ this.received = (this.attributes.containsKey("rec")) ? my_SHORT_SECOND_FORMATTER.parse(this.attributes.get("rec"), GenericFormatter.UTCDiffString()) : new Date();+ this.created = (this.attributes.containsKey("cre")) ? my_SHORT_SECOND_FORMATTER.parse(this.attributes.get("cre"), GenericFormatter.UTCDiffString()) : new Date();+ this.distributed = (this.attributes.containsKey("dis")) ? Integer.parseInt(this.attributes.get("dis")) : 0;+ this.originator = (this.attributes.containsKey("ori")) ? this.attributes.get("ori") : "";removeStandards();}private Record(final yacySeed mySeed, final String category, final Map<String, String> attributes) {if (category.length() > yacyNewsDB.categoryStringLength) throw new IllegalArgumentException("category length (" + category.length() + ") exceeds maximum (" + yacyNewsDB.categoryStringLength + ")");- if (attributes.toString().length() > attributesMaxLength) throw new IllegalArgumentException("attributes length (" + attributes.toString().length() + ") exceeds maximum (" + attributesMaxLength + ")");+ if (attributes.toString().length() > yacyNewsDB.this.attributesMaxLength) throw new IllegalArgumentException("attributes length (" + attributes.toString().length() + ") exceeds maximum (" + yacyNewsDB.this.attributesMaxLength + ")");this.attributes = attributes;this.received = null;this.created = new Date();@@ -258,7 +258,7 @@ public class yacyNewsDB {private Record(final String id, final String category, final Date received, final int distributed, final Map<String, String> attributes) {if (category.length() > yacyNewsDB.categoryStringLength) throw new IllegalArgumentException("category length (" + category.length() + ") exceeds maximum (" + yacyNewsDB.categoryStringLength + ")");- if (attributes.toString().length() > attributesMaxLength) throw new IllegalArgumentException("attributes length (" + attributes.toString().length() + ") exceeds maximum (" + attributesMaxLength + ")");+ if (attributes.toString().length() > yacyNewsDB.this.attributesMaxLength) throw new IllegalArgumentException("attributes length (" + attributes.toString().length() + ") exceeds maximum (" + yacyNewsDB.this.attributesMaxLength + ")");this.attributes = attributes;this.received = received;this.created = my_SHORT_SECOND_FORMATTER.parse(id.substring(0, GenericFormatter.PATTERN_SHORT_SECOND.length()), GenericFormatter.UTCDiffString());@@ -269,61 +269,61 @@ public class yacyNewsDB {}private void removeStandards() {- attributes.remove("ori");- attributes.remove("cat");- attributes.remove("cre");- attributes.remove("rec");- attributes.remove("dis");+ this.attributes.remove("ori");+ this.attributes.remove("cat");+ this.attributes.remove("cre");+ this.attributes.remove("rec");+ this.attributes.remove("dis");}-+@Overridepublic String toString() {// this creates the string that shall be distributed// attention: this has no additional encoding- if (this.originator != null) attributes.put("ori", this.originator);- if (this.category != null) attributes.put("cat", this.category);- if (this.created != null) attributes.put("cre", my_SHORT_SECOND_FORMATTER.format(this.created));- if (this.received != null) attributes.put("rec", my_SHORT_SECOND_FORMATTER.format(this.received));- attributes.put("dis", Integer.toString(this.distributed));- final String theString = attributes.toString();+ if (this.originator != null) this.attributes.put("ori", this.originator);+ if (this.category != null) this.attributes.put("cat", this.category);+ if (this.created != null) this.attributes.put("cre", my_SHORT_SECOND_FORMATTER.format(this.created));+ if (this.received != null) this.attributes.put("rec", my_SHORT_SECOND_FORMATTER.format(this.received));+ this.attributes.put("dis", Integer.toString(this.distributed));+ final String theString = this.attributes.toString();removeStandards();return theString;}public String id() {- return my_SHORT_SECOND_FORMATTER.format(created) + originator;+ return my_SHORT_SECOND_FORMATTER.format(this.created) + this.originator;}public String originator() {- return originator;+ return this.originator;}public Date created() {- return created;+ return this.created;}public Date received() {- return received;+ return this.received;}public String category() {- return category;+ return this.category;}public int distributed() {- return distributed;+ return this.distributed;}public void incDistribution() {- distributed++;+ this.distributed++;}public Map<String, String> attributes() {- return attributes;+ return this.attributes;}-+public String attribute(final String key, final String dflt) {- final String s = attributes.get(key);+ final String s = this.attributes.get(key);if ((s == null) || (s.length() == 0)) return dflt;return s;}diff --git a/source/net/yacy/dbtest.java b/source/net/yacy/dbtest.javaindex 544f889ca..54cee9389 100644--- a/source/net/yacy/dbtest.java+++ b/source/net/yacy/dbtest.java@@ -39,7 +39,7 @@ public class dbtest {dummyvalue2[0] = '{';dummyvalue2[valuelength - 1] = '}';}-+public static byte[] randomHash(final long r0, final long r1) {// a long can have 64 bit, but a 12-byte hash can have 6 * 12 = 72 bits// so we construct a generic Hash using two long values@@ -47,11 +47,11 @@ public class dbtest {Base64Order.enhancedCoder.encodeLongSB(Math.abs(r1), 6).toString());return s.getBytes();}-+public static byte[] randomHash(final Random r) {return randomHash(r.nextLong(), r.nextLong());}-+public final static class STEntry {private final byte[] key;private final byte[] value;@@ -123,7 +123,7 @@ public class dbtest {}public void run() {- final STEntry entry = new STEntry(this.getSource());+ final STEntry entry = new STEntry(getSource());System.out.println("write: " + NaturalOrder.arrayList(entry.getKey(), 0, entry.getKey().length));try {getTable_test().put(getTable_test().row().newEntry(new byte[][] { entry.getKey(), entry.getValue() , entry.getValue() }));@@ -132,7 +132,7 @@ public class dbtest {System.err.println(e);Log.logException(e);System.exit(0);- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {System.err.println(e);Log.logException(e);System.exit(0);@@ -146,7 +146,7 @@ public class dbtest {}public void run() {- final STEntry entry = new STEntry(this.getSource());+ final STEntry entry = new STEntry(getSource());System.out.println("remove: " + NaturalOrder.arrayList(entry.getKey(), 0, entry.getKey().length));try {getTable_test().remove(entry.getKey());@@ -165,9 +165,9 @@ public class dbtest {}public void run() {- final STEntry entry = new STEntry(this.getSource());+ final STEntry entry = new STEntry(getSource());try {- Row.Entry entryBytes = getTable_test().get(entry.getKey());+ Row.Entry entryBytes = getTable_test().get(entry.getKey(), false);if (entryBytes != null) {final STEntry dbEntry = new STEntry(entryBytes.getPrimaryKeyBytes(), entryBytes.getColBytes(1, true));if (!dbEntry.isValid()) {@@ -178,7 +178,7 @@ public class dbtest {} */}if (getTable_reference() != null) {- entryBytes = getTable_reference().get(entry.getKey());+ entryBytes = getTable_reference().get(entry.getKey(), false);if (entryBytes != null) {final STEntry dbEntry = new STEntry(entryBytes.getPrimaryKeyBytes(), entryBytes.getColBytes(1, true));if (!dbEntry.isValid()) {@@ -196,7 +196,7 @@ public class dbtest {}}}-+public static Index selectTableType(final String dbe, final String tablename, final Row testRow) throws Exception {if (dbe.equals("kelondroRowSet")) {return new RowSet(testRow, 0);@@ -216,7 +216,7 @@ public class dbtest {}return null;}-+public static boolean checkEquivalence(final Index test, final Index reference) throws IOException {if (reference == null) return true;if (test.size() == reference.size()) {@@ -227,39 +227,39 @@ public class dbtest {}boolean eq = true;Row.Entry test_entry, reference_entry;-+Iterator<Row.Entry> i = test.rows();System.out.println("* Testing now by enumeration over test table");final long ts = System.currentTimeMillis();while (i.hasNext()) {test_entry = i.next();- reference_entry = reference.get(test_entry.getPrimaryKeyBytes());+ reference_entry = reference.get(test_entry.getPrimaryKeyBytes(), false);if (!test_entry.equals(reference_entry)) {System.out.println("* FAILED: test entry with key '" + UTF8.String(test_entry.getPrimaryKeyBytes()) + "' has no equivalent entry in reference");eq = false;}}-+i = reference.rows();System.out.println("* Testing now by enumeration over reference table");final long rs = System.currentTimeMillis();while (i.hasNext()) {reference_entry = i.next();- test_entry = test.get(reference_entry.getPrimaryKeyBytes());+ test_entry = test.get(reference_entry.getPrimaryKeyBytes(), false);if (!test_entry.equals(reference_entry)) {System.out.println("* FAILED: reference entry with key '" + UTF8.String(test_entry.getPrimaryKeyBytes()) + "' has no equivalent entry in test");eq = false;}}-+System.out.println("* finished checkEquivalence; test-enumeration = " + ((rs - ts) / 1000) + " seconds, reference-enumeration = "+ ((System.currentTimeMillis() - rs) / 1000) + " seconds");- if (eq) System.out.println("* SUCCESS! the tables are equal."); else System.out.println("* FAILED! the tables are not equal.");+ if (eq) System.out.println("* SUCCESS! the tables are equal."); else System.out.println("* FAILED! the tables are not equal.");return eq;}-+public static void main(final String[] args) {System.setProperty("java.awt.headless", "true");-+System.out.println("*** YaCy Database Test");// print out command lineboolean assertionenabled = false;@@ -271,9 +271,10 @@ public class dbtest {((assertionenabled) ? "-ea " : "") +((mb > 100) ? ("-Xmx" + (mb + 11) + "m ") : " ") +"-classpath classes dbtest ");- for (int i = 0; i < args.length; i++) System.out.print(args[i] + " ");+ for (final String arg : args)+ System.out.print(arg + " ");System.out.println();-+// read command optionsfinal String command = args[0]; // test commandfinal String dbe_test = args[1]; // the database engine that shall be tested@@ -281,32 +282,32 @@ public class dbtest {final String tablename_test = args[3]; // name of test-tableif (dbe_reference.toLowerCase().equals("null")) dbe_reference = null;final String tablename_reference = (dbe_reference == null) ? null : (tablename_test + ".reference");-+// start testfinal long startup = System.currentTimeMillis();try {// create a memory profilerfinal memprofiler profiler = new memprofiler(1024, 320, 120, new File(tablename_test + ".profile.png"));profiler.start();-+// create the database accessfinal Row testRow = new Row("byte[] key-" + keylength + ", byte[] dummy-" + keylength + ", value-" + valuelength, Base64Order.enhancedCoder);final Index table_test = selectTableType(dbe_test, tablename_test, testRow);final Index table_reference = (dbe_reference == null) ? null : selectTableType(dbe_reference, tablename_reference, testRow);-+final long afterinit = System.currentTimeMillis();System.out.println("Test for db-engine " + dbe_test + " started to create file " + tablename_test + " with test " + command);-+// execute commandif (command.equals("create")) {// do nothing, since opening of the database access must handle thisSystem.out.println("Database created");}-+if (command.equals("fill")) {// fill database with random entries;// args: <number-of-entries> <random-startpoint>- // example: java -ea -Xmx200m fill kelondroEcoTable kelondroFlexTable filldbtest 50000 0+ // example: java -ea -Xmx200m fill kelondroEcoTable kelondroFlexTable filldbtest 50000 0final long count = Long.parseLong(args[4]);final long randomstart = Long.parseLong(args[5]);final Random random = new Random(randomstart);@@ -320,7 +321,7 @@ public class dbtest {}}}-+if (command.equals("read")) {// read the database and compare with random entries;// args: <number-of-entries> <random-startpoint>@@ -331,25 +332,25 @@ public class dbtest {byte[] key;for (int i = 0; i < count; i++) {key = randomHash(random);- entry = table_test.get(key);+ entry = table_test.get(key, false);if (entry == null)System.out.println("missing value for entry " + UTF8.String(key) + " in test table");elseif (!ByteBuffer.equals(entry.getColBytes(1, false), key)) System.out.println("wrong value for entry " + UTF8.String(key) + ": " + UTF8.String(entry.getColBytes(1, false)) + " in test table");if (table_reference != null) {- entry = table_reference.get(key);+ entry = table_reference.get(key, false);if (entry == null)System.out.println("missing value for entry " + UTF8.String(key) + " in reference table");elseif (!ByteBuffer.equals(entry.getColBytes(1, false), key)) System.out.println("wrong value for entry " + UTF8.String(key) + ": " + UTF8.String(entry.getColBytes(1, false)) + " in reference table");}-+if (i % 1000 == 0) {System.out.println(i + " entries processed so far.");}}}-+if (command.equals("ramtest")) {// fill database with random entries and delete them again;// this is repeated without termination; after each loop@@ -379,7 +380,7 @@ public class dbtest {table_test.delete(key);}remove = System.currentTimeMillis() - start;-+System.out.println("Loop " + loop + ": Write = " + write + ", Remove = " + remove);System.out.println(" bevore GC: " +"free = " + MemoryControl.free() +@@ -393,7 +394,7 @@ public class dbtest {loop++;}}-+if (command.equals("list")) {CloneableIterator<Row.Entry> i = null;if (table_test instanceof SQLTable) i = ((SQLTable) table_test).rows();@@ -406,19 +407,19 @@ public class dbtest {}}}-+final long aftercommand = System.currentTimeMillis();checkEquivalence(table_test, table_reference);final long afterequiv = System.currentTimeMillis();// final reportSystem.out.println("Database size = " + table_test.size() + " unique entries.");-+// finally close the database/tabletable_test.close();if (table_reference != null) table_reference.close();-+final long afterclose = System.currentTimeMillis();-+System.out.println("Execution time: open=" + (afterinit - startup) +", command=" + (aftercommand - afterinit) +", equiv=" + (afterequiv - aftercommand) +@@ -432,34 +433,34 @@ public class dbtest {}final class memprofiler extends Thread {-+ChartPlotter memChart;boolean run;File outputFile;long start;-+public memprofiler(final int width, final int height, final int expectedTimeSeconds, final File outputFile) {this.outputFile = outputFile;final int expectedKilobytes = 20 * 1024;//(Runtime.getRuntime().totalMemory() / 1024);- memChart = new ChartPlotter(width, height, "FFFFFF", "000000", "000000", 50, 20, 20, 20, "MEMORY CHART FROM EXECUTION AT " + new Date(), null);+ this.memChart = new ChartPlotter(width, height, "FFFFFF", "000000", "000000", 50, 20, 20, 20, "MEMORY CHART FROM EXECUTION AT " + new Date(), null);final int timescale = 10; // steps with each 10 secondsfinal int memscale = 1024;- memChart.declareDimension(ChartPlotter.DIMENSION_BOTTOM, timescale, (width - 40) * timescale / expectedTimeSeconds, 0, "FFFFFF", "555555", "SECONDS");- memChart.declareDimension(ChartPlotter.DIMENSION_LEFT, memscale, (height - 40) * memscale / expectedKilobytes, 0, "FFFFFF", "555555", "KILOBYTES");- run = true;- start = System.currentTimeMillis();+ this.memChart.declareDimension(ChartPlotter.DIMENSION_BOTTOM, timescale, (width - 40) * timescale / expectedTimeSeconds, 0, "FFFFFF", "555555", "SECONDS");+ this.memChart.declareDimension(ChartPlotter.DIMENSION_LEFT, memscale, (height - 40) * memscale / expectedKilobytes, 0, "FFFFFF", "555555", "KILOBYTES");+ this.run = true;+ this.start = System.currentTimeMillis();}-+@Overridepublic void run() {try {int seconds0 = 0, kilobytes0 = 0;int seconds1 = 0, kilobytes1 = 0;- while (run) {- memChart.setColor("FF0000");- seconds1 = (int) ((System.currentTimeMillis() - start) / 1000);+ while (this.run) {+ this.memChart.setColor("FF0000");+ seconds1 = (int) ((System.currentTimeMillis() - this.start) / 1000);kilobytes1 = (int) (MemoryControl.used() / 1024);- memChart.chartLine(ChartPlotter.DIMENSION_BOTTOM, ChartPlotter.DIMENSION_LEFT, seconds0, kilobytes0, seconds1, kilobytes1);+ this.memChart.chartLine(ChartPlotter.DIMENSION_BOTTOM, ChartPlotter.DIMENSION_LEFT, seconds0, kilobytes0, seconds1, kilobytes1);seconds0 = seconds1;kilobytes0 = kilobytes1;try {Thread.sleep(100);} catch (final InterruptedException e) {}@@ -469,17 +470,17 @@ final class memprofiler extends Thread {}ImageIO.setUseCache(false);try {- ImageIO.write(memChart.getImage(), "png", outputFile);+ ImageIO.write(this.memChart.getImage(), "png", this.outputFile);} catch (final IOException e) {// do noting} catch (final Exception e) {Log.logException(e);}}-+public void terminate() {- run = false;- while (this.isAlive()) {+ this.run = false;+ while (isAlive()) {try {Thread.sleep(1000);} catch (final InterruptedException e) {}}}diff --git a/source/net/yacy/kelondro/blob/ArrayStack.java b/source/net/yacy/kelondro/blob/ArrayStack.javaindex c0dcd3b75..4e43b8713 100755--- a/source/net/yacy/kelondro/blob/ArrayStack.java+++ b/source/net/yacy/kelondro/blob/ArrayStack.java@@ -9,7 +9,7 @@// $LastChangedBy$//// 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@@ -78,10 +78,10 @@ public class ArrayStack implements BLOB {* To delete content that is out-dated, one special method is implemented that deletes content by a given* time-out. Deletions are not made automatically, they must be triggered using this method.*/-+public static final long maxFileSize = Integer.MAX_VALUE;public static final long oneMonth = 1000L * 60L * 60L * 24L * 365L / 12L;-+protected int keylength;protected ByteOrder ordering;private final File heapLocation;@@ -93,14 +93,14 @@ public class ArrayStack implements BLOB {private final String prefix;private final int buffersize;private final boolean trimall;-+// the thread pool for the keeperOf executor serviceprivate final ExecutorService executor;-+// use our own formatter to prevent concurrency locks with other processesprivate final static GenericFormatter my_SHORT_MILSEC_FORMATTER = new GenericFormatter(GenericFormatter.FORMAT_SHORT_MILSEC, 1);-+public ArrayStack(final File heapLocation,final String prefix,@@ -121,12 +121,12 @@ public class ArrayStack implements BLOB {// init the thread pool for the keeperOf executor servicethis.executor = new ThreadPoolExecutor(- Runtime.getRuntime().availableProcessors() + 1,- Runtime.getRuntime().availableProcessors() * 4, 100,- TimeUnit.MILLISECONDS,- new LinkedBlockingQueue<Runnable>(),+ Runtime.getRuntime().availableProcessors() + 1,+ Runtime.getRuntime().availableProcessors() * 4, 100,+ TimeUnit.MILLISECONDS,+ new LinkedBlockingQueue<Runnable>(),new NamePrefixThreadFactory(prefix));-+// check existence of the heap directoryif (heapLocation.exists()) {if (!heapLocation.isDirectory()) throw new IOException("the BLOBArray directory " + heapLocation.toString() + " does not exist (is blocked by a file with same name)");@@ -136,19 +136,20 @@ public class ArrayStack implements BLOB {// register all blob files inside this directoryString[] files = heapLocation.list();- HashSet<String> fh = new HashSet<String>();- for (int i = 0; i < files.length; i++) fh.add(files[i]);+ final HashSet<String> fh = new HashSet<String>();+ for (final String file : files)+ fh.add(file);// delete unused temporary filesboolean deletions = false;- for (int i = 0; i < files.length; i++) {- if (files[i].endsWith(".tmp") || files[i].endsWith(".prt")) {- FileUtils.deletedelete(new File(heapLocation, files[i]));+ for (final String file : files) {+ if (file.endsWith(".tmp") || file.endsWith(".prt")) {+ FileUtils.deletedelete(new File(heapLocation, file));deletions = true;}- if (files[i].endsWith(".idx") || files[i].endsWith(".gap")) {- String s = files[i].substring(0, files[i].length() - 17);+ if (file.endsWith(".idx") || file.endsWith(".gap")) {+ final String s = file.substring(0, file.length() - 17);if (!fh.contains(s)) {- FileUtils.deletedelete(new File(heapLocation, files[i]));+ FileUtils.deletedelete(new File(heapLocation, file));deletions = true;}}@@ -158,42 +159,42 @@ public class ArrayStack implements BLOB {Date d;long time;deletions = false;- for (int i = 0; i < files.length; i++) {- if (files[i].length() >= 19 && files[i].endsWith(".blob")) {- File f = new File(heapLocation, files[i]);+ for (final String file : files) {+ if (file.length() >= 19 && file.endsWith(".blob")) {+ final File f = new File(heapLocation, file);if (f.length() == 0) {f.delete();deletions = true;} else try {- d = GenericFormatter.SHORT_SECOND_FORMATTER.parse(files[i].substring(0, 14));+ d = GenericFormatter.SHORT_SECOND_FORMATTER.parse(file.substring(0, 14));f.renameTo(newBLOB(d));deletions = true;- } catch (ParseException e) {continue;}+ } catch (final ParseException e) {continue;}}}if (deletions) files = heapLocation.list(); // make a fresh list-+// find maximum time: the file with this time will be given a write buffer- TreeMap<Long, blobItem> sortedItems = new TreeMap<Long, blobItem>();+ final TreeMap<Long, blobItem> sortedItems = new TreeMap<Long, blobItem>();BLOB oneBlob;File f;long maxtime = 0;- for (int i = 0; i < files.length; i++) {- if (files[i].length() >= 22 && files[i].startsWith(prefix) && files[i].endsWith(".blob")) {+ for (final String file : files) {+ if (file.length() >= 22 && file.startsWith(prefix) && file.endsWith(".blob")) {try {- d = my_SHORT_MILSEC_FORMATTER.parse(files[i].substring(prefix.length() + 1, prefix.length() + 18));+ d = my_SHORT_MILSEC_FORMATTER.parse(file.substring(prefix.length() + 1, prefix.length() + 18));time = d.getTime();if (time > maxtime) maxtime = time;- } catch (ParseException e) {continue;}+ } catch (final ParseException e) {continue;}}}-+// open all blob files- for (int i = 0; i < files.length; i++) {- if (files[i].length() >= 22 && files[i].startsWith(prefix) && files[i].endsWith(".blob")) {+ for (final String file : files) {+ if (file.length() >= 22 && file.startsWith(prefix) && file.endsWith(".blob")) {try {- d = my_SHORT_MILSEC_FORMATTER.parse(files[i].substring(prefix.length() + 1, prefix.length() + 18));- f = new File(heapLocation, files[i]);+ d = my_SHORT_MILSEC_FORMATTER.parse(file.substring(prefix.length() + 1, prefix.length() + 18));+ f = new File(heapLocation, file);time = d.getTime();if (time == maxtime && !trimall) {oneBlob = new Heap(f, keylength, ordering, buffersize);@@ -202,54 +203,54 @@ public class ArrayStack implements BLOB {oneBlob.trim(); // no writings here, can be used with minimum memory}sortedItems.put(Long.valueOf(time), new blobItem(d, f, oneBlob));- } catch (ParseException e) {continue;}+ } catch (final ParseException e) {continue;}}}-+// read the blob tree in a sorted way and write them into an array- blobs = new CopyOnWriteArrayList<blobItem>();- for (blobItem bi : sortedItems.values()) {- blobs.add(bi);+ this.blobs = new CopyOnWriteArrayList<blobItem>();+ for (final blobItem bi : sortedItems.values()) {+ this.blobs.add(bi);}}-+public long mem() {long m = 0;- if (this.blobs != null) for (blobItem b: this.blobs) m += b.blob.mem();+ if (this.blobs != null) for (final blobItem b: this.blobs) m += b.blob.mem();return m;}-+public void trim() {// trim shall not be called for ArrayStacks because the characteristics of an ArrayStack is that the 'topmost' BLOB on the stack// is used for write operations and all other shall be trimmed automatically since they are not used for writing. And the// topmost BLOB must not be trimmed to support fast writings.throw new UnsupportedOperationException();}-+/*** add a blob file to the array.* note that this file must be generated with a file name from newBLOB()* @param location* @throws IOException*/- public synchronized void mountBLOB(File location, boolean full) throws IOException {+ public synchronized void mountBLOB(final File location, final boolean full) throws IOException {Date d;try {- d = my_SHORT_MILSEC_FORMATTER.parse(location.getName().substring(prefix.length() + 1, prefix.length() + 18));- } catch (ParseException e) {+ d = my_SHORT_MILSEC_FORMATTER.parse(location.getName().substring(this.prefix.length() + 1, this.prefix.length() + 18));+ } catch (final ParseException e) {throw new IOException("date parse problem with file " + location.toString() + ": " + e.getMessage());}BLOB oneBlob;- if (full && buffersize > 0 && !trimall) {- oneBlob = new Heap(location, keylength, ordering, buffersize);+ if (full && this.buffersize > 0 && !this.trimall) {+ oneBlob = new Heap(location, this.keylength, this.ordering, this.buffersize);} else {- oneBlob = new HeapModifier(location, keylength, ordering);+ oneBlob = new HeapModifier(location, this.keylength, this.ordering);oneBlob.trim();}- blobs.add(new blobItem(d, location, oneBlob));+ this.blobs.add(new blobItem(d, location, oneBlob));}-- public synchronized void unmountBLOB(File location, boolean writeIDX) {++ public synchronized void unmountBLOB(final File location, final boolean writeIDX) {blobItem b;for (int i = 0; i < this.blobs.size(); i++) {b = this.blobs.get(i);@@ -263,22 +264,22 @@ public class ArrayStack implements BLOB {}Log.logSevere("BLOBArray", "file " + location + " cannot be unmounted. The file " + ((location.exists()) ? "exists." : "does not exist."));}-- private File unmount(int idx) {- blobItem b = this.blobs.remove(idx);++ private File unmount(final int idx) {+ final blobItem b = this.blobs.remove(idx);b.blob.close(false);b.blob = null;- File f = b.location;+ final File f = b.location;b.location = null;return f;}-- public synchronized File[] unmountBestMatch(float maxq, long maxResultSize) {++ public synchronized File[] unmountBestMatch(final float maxq, long maxResultSize) {if (this.blobs.size() < 2) return null;long l, r;File lf, rf;float min = Float.MAX_VALUE;- File[] bestMatch = new File[2];+ final File[] bestMatch = new File[2];maxResultSize = maxResultSize >> 1;int loopcount = 0;mainloop: for (int i = 0; i < this.blobs.size() - 1; i++) {@@ -289,7 +290,7 @@ public class ArrayStack implements BLOB {l = 1 + (lf.length() >> 1);r = 1 + (rf.length() >> 1);if (l + r > maxResultSize) continue;- float q = Math.max((float) l, (float) r) / Math.min((float) l, (float) r);+ final float q = Math.max((float) l, (float) r) / Math.min((float) l, (float) r);if (q < min) {min = q;bestMatch[0] = lf;@@ -307,28 +308,28 @@ public class ArrayStack implements BLOB {public synchronized File unmountOldest() {if (this.blobs.size() == 0) return null;if (System.currentTimeMillis() - this.blobs.get(0).creation.getTime() < this.fileAgeLimit) return null;- File f = this.blobs.get(0).location;+ final File f = this.blobs.get(0).location;unmountBLOB(f, false);return f;}-- public synchronized File[] unmountSmallest(long maxResultSize) {++ public synchronized File[] unmountSmallest(final long maxResultSize) {if (this.blobs.size() < 2) return null;- File f0 = smallestBLOB(null, maxResultSize);+ final File f0 = smallestBLOB(null, maxResultSize);if (f0 == null) return null;- File f1 = smallestBLOB(f0, maxResultSize - f0.length());+ final File f1 = smallestBLOB(f0, maxResultSize - f0.length());if (f1 == null) return null;-+unmountBLOB(f0, false);unmountBLOB(f1, false);return new File[]{f0, f1};}-- public synchronized File unmountSmallestBLOB(long maxResultSize) {++ public synchronized File unmountSmallestBLOB(final long maxResultSize) {return smallestBLOB(null, maxResultSize);}-- public synchronized File smallestBLOB(File excluding, long maxsize) {++ public synchronized File smallestBLOB(final File excluding, final long maxsize) {if (this.blobs.isEmpty()) return null;File bestFile = null;long smallest = Long.MAX_VALUE;@@ -345,14 +346,14 @@ public class ArrayStack implements BLOB {if (smallest > maxsize) return null;return bestFile;}-- public synchronized File unmountOldestBLOB(boolean smallestFromFirst2) {++ public synchronized File unmountOldestBLOB(final boolean smallestFromFirst2) {if (this.blobs.isEmpty()) return null;int idx = 0;if (smallestFromFirst2 && this.blobs.get(1).location.length() < this.blobs.get(0).location.length()) idx = 1;return unmount(idx);}-+/*** return the number of BLOB files in this array* @return@@ -360,83 +361,83 @@ public class ArrayStack implements BLOB {public synchronized int entries() {return (this.blobs == null) ? 0 : this.blobs.size();}-+/*** generate a new BLOB file name with a given date.* This method is needed to generate a file name that matches to the name structure that is needed for parts of the array* @param creation* @return*/- public synchronized File newBLOB(Date creation) {+ public synchronized File newBLOB(final Date creation) {//return new File(heapLocation, DateFormatter.formatShortSecond(creation) + "." + blobSalt + ".blob");- return new File(heapLocation, prefix + "." + my_SHORT_MILSEC_FORMATTER.format(creation) + ".blob");+ return new File(this.heapLocation, this.prefix + "." + my_SHORT_MILSEC_FORMATTER.format(creation) + ".blob");}-+public String name() {return this.heapLocation.getName();}-- public void setMaxAge(long maxAge) {++ public void setMaxAge(final long maxAge) {this.repositoryAgeMax = maxAge;this.fileAgeLimit = Math.min(oneMonth, maxAge / 10);}-- public void setMaxSize(long maxSize) {++ public void setMaxSize(final long maxSize) {this.repositorySizeMax = maxSize;this.fileSizeLimit = Math.min(maxFileSize, maxSize / 100L);executeLimits();}-+private void executeLimits() {// check if storage limits are reached and execute consequences- if (blobs.isEmpty()) return;-+ if (this.blobs.isEmpty()) return;+// age limit:- while (!blobs.isEmpty() && System.currentTimeMillis() - blobs.get(0).creation.getTime() - this.fileAgeLimit > this.repositoryAgeMax) {+ while (!this.blobs.isEmpty() && System.currentTimeMillis() - this.blobs.get(0).creation.getTime() - this.fileAgeLimit > this.repositoryAgeMax) {// too old- blobItem oldestBLOB = blobs.remove(0);+ final blobItem oldestBLOB = this.blobs.remove(0);oldestBLOB.blob.close(false);oldestBLOB.blob = null;FileUtils.deletedelete(oldestBLOB.location);}-+// size limit- while (!blobs.isEmpty() && length() > this.repositorySizeMax) {+ while (!this.blobs.isEmpty() && length() > this.repositorySizeMax) {// too large- blobItem oldestBLOB = blobs.remove(0);+ final blobItem oldestBLOB = this.blobs.remove(0);oldestBLOB.blob.close(false);FileUtils.deletedelete(oldestBLOB.location);}}-+/** return the size of the repository (in bytes)*/public synchronized long length() {long s = 0;- for (int i = 0; i < blobs.size(); i++) s += blobs.get(i).location.length();+ for (int i = 0; i < this.blobs.size(); i++) s += this.blobs.get(i).location.length();return s;}-+public ByteOrder ordering() {return this.ordering;}-+private class blobItem {Date creation;File location;BLOB blob;- public blobItem(Date creation, File location, BLOB blob) {+ public blobItem(final Date creation, final File location, final BLOB blob) {assert blob != null;this.creation = creation;this.location = location;this.blob = blob;}- public blobItem(int buffer) throws IOException {+ public blobItem(final int buffer) throws IOException {// make a new blob file and assign it in this itemthis.creation = new Date();this.location = newBLOB(this.creation);- this.blob = (buffer == 0) ? new HeapModifier(location, keylength, ordering) : new Heap(location, keylength, ordering, buffer);+ this.blob = (buffer == 0) ? new HeapModifier(this.location, ArrayStack.this.keylength, ArrayStack.this.ordering) : new Heap(this.location, ArrayStack.this.keylength, ArrayStack.this.ordering, buffer);}}@@ -447,47 +448,47 @@ public class ArrayStack implements BLOB {public int keylength() {return this.keylength;}-+/*** clears the content of the database* @throws IOException*/public synchronized void clear() throws IOException {- for (blobItem bi: blobs) {+ for (final blobItem bi: this.blobs) {bi.blob.clear();bi.blob.close(false);HeapWriter.delete(bi.location);}- blobs.clear();+ this.blobs.clear();}-+/*** ask for the number of blob entries* @return the number of entries in the table*/public synchronized int size() {int s = 0;- for (blobItem bi: blobs) s += bi.blob.size();+ for (final blobItem bi: this.blobs) s += bi.blob.size();return s;}-+public synchronized boolean isEmpty() {- for (blobItem bi: blobs) if (!bi.blob.isEmpty()) return false;+ for (final blobItem bi: this.blobs) if (!bi.blob.isEmpty()) return false;return true;}-+/*** ask for the number of blob entries in each blob of the blob array* @return the number of entries in each blob*/public synchronized int[] sizes() {- if (blobs == null) return new int[0];- int[] s = new int[blobs.size()];+ if (this.blobs == null) return new int[0];+ final int[] s = new int[this.blobs.size()];int c = 0;- for (blobItem bi: blobs) s[c++] = bi.blob.size();+ for (final blobItem bi: this.blobs) s[c++] = bi.blob.size();return s;}-+/*** iterator over all keys* @param up@@ -495,16 +496,16 @@ public class ArrayStack implements BLOB {* @return* @throws IOException*/- public synchronized CloneableIterator<byte[]> keys(boolean up, boolean rotating) throws IOException {+ public synchronized CloneableIterator<byte[]> keys(final boolean up, final boolean rotating) throws IOException {assert rotating == false;- final List<CloneableIterator<byte[]>> c = new ArrayList<CloneableIterator<byte[]>>(blobs.size());- final Iterator<blobItem> i = blobs.iterator();+ final List<CloneableIterator<byte[]>> c = new ArrayList<CloneableIterator<byte[]>>(this.blobs.size());+ final Iterator<blobItem> i = this.blobs.iterator();while (i.hasNext()) {c.add(i.next().blob.keys(up, rotating));}return MergeIterator.cascade(c, this.ordering, MergeIterator.simpleMerge, up);}-+/*** iterate over all keys* @param up@@ -512,28 +513,28 @@ public class ArrayStack implements BLOB {* @return* @throws IOException*/- public synchronized CloneableIterator<byte[]> keys(boolean up, byte[] firstKey) throws IOException {- final List<CloneableIterator<byte[]>> c = new ArrayList<CloneableIterator<byte[]>>(blobs.size());- final Iterator<blobItem> i = blobs.iterator();+ public synchronized CloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {+ final List<CloneableIterator<byte[]>> c = new ArrayList<CloneableIterator<byte[]>>(this.blobs.size());+ final Iterator<blobItem> i = this.blobs.iterator();while (i.hasNext()) {c.add(i.next().blob.keys(up, firstKey));}return MergeIterator.cascade(c, this.ordering, MergeIterator.simpleMerge, up);}-+/*** check if a specific key is in the database* @param key the primary key* @return* @throws IOException*/- public synchronized boolean containsKey(byte[] key) {- blobItem bi = keeperOf(key);+ public synchronized boolean containsKey(final byte[] key) {+ final blobItem bi = keeperOf(key);return bi != null;//for (blobItem bi: blobs) if (bi.blob.has(key)) return true;//return false;}-+/*** find the blobItem that holds the key* if no blobItem is found, then return null@@ -541,17 +542,17 @@ public class ArrayStack implements BLOB {* @return the blobItem that holds the key or null if no blobItem is found*/private blobItem keeperOf(final byte[] key) {- if (blobs.size() == 0) return null;- if (blobs.size() == 1) {- blobItem bi = blobs.get(0);+ if (this.blobs.size() == 0) return null;+ if (this.blobs.size() == 1) {+ final blobItem bi = this.blobs.get(0);if (bi.blob.containsKey(key)) return bi;return null;}-+// start a concurrent query to database tables- final CompletionService<blobItem> cs = new ExecutorCompletionService<blobItem>(executor);+ final CompletionService<blobItem> cs = new ExecutorCompletionService<blobItem>(this.executor);int accepted = 0;- for (final blobItem bi : blobs) {+ for (final blobItem bi : this.blobs) {try {cs.submit(new Callable<blobItem>() {public blobItem call() {@@ -590,23 +591,23 @@ public class ArrayStack implements BLOB {//System.out.println("*DEBUG SplitTable fail.time = " + (System.currentTimeMillis() - start) + " ms");return null;}-+/*** retrieve the whole BLOB from the table* @param key the primary key* @return* @throws IOException*/- public byte[] get(byte[] key) throws IOException, RowSpaceExceededException {- if (blobs.size() == 0) return null;- if (blobs.size() == 1) {- blobItem bi = blobs.get(0);+ public byte[] get(final byte[] key) throws IOException, RowSpaceExceededException {+ if (this.blobs.size() == 0) return null;+ if (this.blobs.size() == 1) {+ final blobItem bi = this.blobs.get(0);return bi.blob.get(key);}-- blobItem bi = keeperOf(key);++ final blobItem bi = keeperOf(key);return (bi == null) ? null : bi.blob.get(key);-+/*byte[] b;for (blobItem bi: blobs) {@@ -616,19 +617,19 @@ public class ArrayStack implements BLOB {return null;*/}-- public byte[] get(Object key) {++ public byte[] get(final Object key) {if (!(key instanceof byte[])) return null;try {return get((byte[]) key);- } catch (IOException e) {+ } catch (final IOException e) {Log.logException(e);- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {Log.logException(e);}return null;}-+/*** get all BLOBs in the array.* this is useful when it is not clear if an entry is unique in all BLOBs in this array.@@ -636,53 +637,54 @@ public class ArrayStack implements BLOB {* @return* @throws IOException*/- public Iterable<byte[]> getAll(byte[] key) throws IOException {+ public Iterable<byte[]> getAll(final byte[] key) throws IOException {return new BlobValues(key);}-+public class BlobValues extends LookAheadIterator<byte[]> {private final Iterator<blobItem> bii;private final byte[] key;-- public BlobValues(byte[] key) {- this.bii = blobs.iterator();++ public BlobValues(final byte[] key) {+ this.bii = ArrayStack.this.blobs.iterator();this.key = key;}-+protected byte[] next0() {while (this.bii.hasNext()) {- BLOB b = this.bii.next().blob;+ final BLOB b = this.bii.next().blob;if (b == null) continue;try {- byte[] n = b.get(key);+ final byte[] n = b.get(this.key);if (n != null) return n;- } catch (IOException e) {- Log.logSevere("ArrayStack", "", e);+ } catch (final IOException e) {+ Log.logSevere("ArrayStack", "BlobValues - IOException: " + e.getMessage(), e);return null;- } catch (RowSpaceExceededException e) {- continue;+ } catch (final RowSpaceExceededException e) {+ Log.logSevere("ArrayStack", "BlobValues - RowSpaceExceededException: " + e.getMessage(), e);+ break;}}return null;- }+ }}-+/*** retrieve the size of the BLOB* @param key* @return the size of the BLOB or -1 if the BLOB does not exist* @throws IOException*/- public synchronized long length(byte[] key) throws IOException {+ public synchronized long length(final byte[] key) throws IOException {long l;- for (blobItem bi: blobs) {+ for (final blobItem bi: this.blobs) {l = bi.blob.length(key);if (l >= 0) return l;}return -1;}-+/*** get all BLOBs in the array.* this is useful when it is not clear if an entry is unique in all BLOBs in this array.@@ -690,59 +692,59 @@ public class ArrayStack implements BLOB {* @return* @throws IOException*/- public Iterable<Long> lengthAll(byte[] key) throws IOException {+ public Iterable<Long> lengthAll(final byte[] key) throws IOException {return new BlobLengths(key);}-+public class BlobLengths extends LookAheadIterator<Long> {private final Iterator<blobItem> bii;private final byte[] key;-- public BlobLengths(byte[] key) {- this.bii = blobs.iterator();++ public BlobLengths(final byte[] key) {+ this.bii = ArrayStack.this.blobs.iterator();this.key = key;}-+protected Long next0() {while (this.bii.hasNext()) {- BLOB b = this.bii.next().blob;+ final BLOB b = this.bii.next().blob;if (b == null) continue;try {- long l = b.length(key);+ final long l = b.length(this.key);if (l >= 0) return Long.valueOf(l);- } catch (IOException e) {+ } catch (final IOException e) {Log.logSevere("ArrayStack", "", e);return null;}}return null;- }+ }}-+/*** retrieve the sizes of all BLOB* @param key* @return the size of the BLOB or -1 if the BLOB does not exist* @throws IOException*/- public synchronized long lengthAdd(byte[] key) throws IOException {+ public synchronized long lengthAdd(final byte[] key) throws IOException {long l = 0;- for (blobItem bi: blobs) {+ for (final blobItem bi: this.blobs) {l += bi.blob.length(key);}return l;}-+/*** write a whole byte array as BLOB to the table* @param key the primary key* @param b* @throws IOException- * @throws RowSpaceExceededException+ * @throws RowSpaceExceededException*/- public synchronized void insert(byte[] key, byte[] b) throws IOException {- blobItem bi = (blobs.isEmpty()) ? null : blobs.get(blobs.size() - 1);+ public synchronized void insert(final byte[] key, final byte[] b) throws IOException {+ blobItem bi = (this.blobs.isEmpty()) ? null : this.blobs.get(this.blobs.size() - 1);/*if (bi == null)System.out.println("bi == null");@@ -753,87 +755,87 @@ public class ArrayStack implements BLOB {*/if ((bi == null) || (System.currentTimeMillis() - bi.creation.getTime() > this.fileAgeLimit) || (bi.location.length() > this.fileSizeLimit)) {// add a new blob to the array- bi = new blobItem(buffersize);- blobs.add(bi);+ bi = new blobItem(this.buffersize);+ this.blobs.add(bi);}assert bi.blob instanceof Heap;bi.blob.insert(key, b);executeLimits();}-+/*** replace a BLOB entry with another* @param key the primary key* @throws IOException- * @throws RowSpaceExceededException+ * @throws RowSpaceExceededException*/- public synchronized int replace(byte[] key, Rewriter rewriter) throws IOException, RowSpaceExceededException {+ public synchronized int replace(final byte[] key, final Rewriter rewriter) throws IOException, RowSpaceExceededException {int d = 0;- for (blobItem bi: blobs) {+ for (final blobItem bi: this.blobs) {d += bi.blob.replace(key, rewriter);}return d;}-+/*** replace a BLOB entry with another which must be smaller or same size* @param key the primary key* @throws IOException- * @throws RowSpaceExceededException+ * @throws RowSpaceExceededException*/- public synchronized int reduce(byte[] key, Reducer reduce) throws IOException, RowSpaceExceededException {+ public synchronized int reduce(final byte[] key, final Reducer reduce) throws IOException, RowSpaceExceededException {int d = 0;- for (blobItem bi: blobs) {+ for (final blobItem bi: this.blobs) {d += bi.blob.reduce(key, reduce);}return d;}-+/*** delete a BLOB* @param key the primary key* @throws IOException*/public synchronized void delete(final byte[] key) throws IOException {- long m = this.mem();- if (blobs.size() == 0) {+ final long m = mem();+ if (this.blobs.size() == 0) {// do nothing- } else if (blobs.size() == 1) {- blobItem bi = blobs.get(0);+ } else if (this.blobs.size() == 1) {+ final blobItem bi = this.blobs.get(0);bi.blob.delete(key);} else {- Thread[] t = new Thread[blobs.size() - 1];+ final Thread[] t = new Thread[this.blobs.size() - 1];int i = 0;- for (blobItem bi: blobs) {+ for (final blobItem bi: this.blobs) {if (i < t.length) {// run this in a concurrent threadfinal blobItem bi0 = bi;t[i] = new Thread() {public void run() {- try { bi0.blob.delete(key); } catch (IOException e) {}+ try { bi0.blob.delete(key); } catch (final IOException e) {}}};t[i].start();} else {// no additional thread, run in this thread- try { bi.blob.delete(key); } catch (IOException e) {}+ try { bi.blob.delete(key); } catch (final IOException e) {}}i++;}- for (Thread s: t) try {s.join();} catch (InterruptedException e) {}+ for (final Thread s: t) try {s.join();} catch (final InterruptedException e) {}}- assert this.mem() <= m : "m = " + m + ", mem() = " + mem();+ assert mem() <= m : "m = " + m + ", mem() = " + mem();}-+/*** close the BLOB*/- public synchronized void close(boolean writeIDX) {- for (blobItem bi: blobs) bi.blob.close(writeIDX);- blobs.clear();- blobs = null;+ public synchronized void close(final boolean writeIDX) {+ for (final blobItem bi: this.blobs) bi.blob.close(writeIDX);+ this.blobs.clear();+ this.blobs = null;}-+/*** merge two blob files into one. If the second file is given as null,* then the first file is only rewritten into a new one.@@ -845,20 +847,20 @@ public class ArrayStack implements BLOB {* @param writeBuffer* @return the target file where the given files are merged in*/- public File mergeMount(File f1, File f2,- ReferenceFactory<? extends Reference> factory,- File newFile, int writeBuffer) {+ public File mergeMount(final File f1, final File f2,+ final ReferenceFactory<? extends Reference> factory,+ final File newFile, final int writeBuffer) {if (f2 == null) {// this is a rewriteLog.logInfo("BLOBArray", "rewrite of " + f1.getName());- File resultFile = rewriteWorker(factory, this.keylength, this.ordering, f1, newFile, writeBuffer);+ final File resultFile = rewriteWorker(factory, this.keylength, this.ordering, f1, newFile, writeBuffer);if (resultFile == null) {Log.logWarning("BLOBArray", "rewrite of file " + f1 + " returned null. newFile = " + newFile);return null;}try {mountBLOB(resultFile, false);- } catch (IOException e) {+ } catch (final IOException e) {Log.logWarning("BLOBArray", "rewrite of file " + f1 + " successfull, but read failed. resultFile = " + resultFile);return null;}@@ -866,14 +868,14 @@ public class ArrayStack implements BLOB {return resultFile;} else {Log.logInfo("BLOBArray", "merging " + f1.getName() + " with " + f2.getName());- File resultFile = mergeWorker(factory, this.keylength, this.ordering, f1, f2, newFile, writeBuffer);+ final File resultFile = mergeWorker(factory, this.keylength, this.ordering, f1, f2, newFile, writeBuffer);if (resultFile == null) {Log.logWarning("BLOBArray", "merge of files " + f1 + ", " + f2 + " returned null. newFile = " + newFile);return null;}try {mountBLOB(resultFile, false);- } catch (IOException e) {+ } catch (final IOException e) {Log.logWarning("BLOBArray", "merge of files " + f1 + ", " + f2 + " successfull, but read failed. resultFile = " + resultFile);return null;}@@ -881,22 +883,22 @@ public class ArrayStack implements BLOB {return resultFile;}}-+private static <ReferenceType extends Reference> File mergeWorker(- ReferenceFactory<ReferenceType> factory,- int keylength, ByteOrder order, File f1, File f2, File newFile, int writeBuffer) {+ final ReferenceFactory<ReferenceType> factory,+ final int keylength, final ByteOrder order, final File f1, final File f2, final File newFile, final int writeBuffer) {// iterate both files and write a new one-+CloneableIterator<ReferenceContainer<ReferenceType>> i1 = null, i2 = null;try {i1 = new ReferenceIterator<ReferenceType>(f1, factory);- } catch (IOException e) {+ } catch (final IOException e) {Log.logSevere("ArrayStack", "cannot merge because input files cannot be read, f1 = " + f1.toString() + ": " + e.getMessage(), e);return null;}try {i2 = new ReferenceIterator<ReferenceType>(f2, factory);- } catch (IOException e) {+ } catch (final IOException e) {Log.logSevere("ArrayStack", "cannot merge because input files cannot be read, f2 = " + f2.toString() + ": " + e.getMessage(), e);return null;}@@ -916,17 +918,17 @@ public class ArrayStack implements BLOB {}assert i1.hasNext();assert i2.hasNext();- File tmpFile = new File(newFile.getParentFile(), newFile.getName() + ".prt");+ final File tmpFile = new File(newFile.getParentFile(), newFile.getName() + ".prt");try {- HeapWriter writer = new HeapWriter(tmpFile, newFile, keylength, order, writeBuffer);+ final HeapWriter writer = new HeapWriter(tmpFile, newFile, keylength, order, writeBuffer);merge(i1, i2, order, writer);writer.close(true);- } catch (IOException e) {+ } catch (final IOException e) {Log.logSevere("ArrayStack", "cannot writing or close writing merge, newFile = " + newFile.toString() + ", tmpFile = " + tmpFile.toString() + ": " + e.getMessage(), e);HeapWriter.delete(tmpFile);HeapWriter.delete(newFile);return null;- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {Log.logSevere("ArrayStack", "cannot merge because of memory failure: " + e.getMessage(), e);HeapWriter.delete(tmpFile);HeapWriter.delete(newFile);@@ -937,16 +939,16 @@ public class ArrayStack implements BLOB {HeapWriter.delete(f2);return newFile;}-+private static <ReferenceType extends Reference> File rewriteWorker(- ReferenceFactory<ReferenceType> factory,- int keylength, ByteOrder order, File f, File newFile, int writeBuffer) {+ final ReferenceFactory<ReferenceType> factory,+ final int keylength, final ByteOrder order, final File f, final File newFile, final int writeBuffer) {// iterate both files and write a new one-+CloneableIterator<ReferenceContainer<ReferenceType>> i = null;try {i = new ReferenceIterator<ReferenceType>(f, factory);- } catch (IOException e) {+ } catch (final IOException e) {Log.logSevere("ArrayStack", "cannot rewrite because input file cannot be read, f = " + f.toString() + ": " + e.getMessage(), e);return null;}@@ -955,17 +957,17 @@ public class ArrayStack implements BLOB {return null;}assert i.hasNext();- File tmpFile = new File(newFile.getParentFile(), newFile.getName() + ".prt");+ final File tmpFile = new File(newFile.getParentFile(), newFile.getName() + ".prt");try {- HeapWriter writer = new HeapWriter(tmpFile, newFile, keylength, order, writeBuffer);+ final HeapWriter writer = new HeapWriter(tmpFile, newFile, keylength, order, writeBuffer);rewrite(i, order, writer);writer.close(true);- } catch (IOException e) {+ } catch (final IOException e) {Log.logSevere("ArrayStack", "cannot writing or close writing rewrite, newFile = " + newFile.toString() + ", tmpFile = " + tmpFile.toString() + ": " + e.getMessage(), e);FileUtils.deletedelete(tmpFile);FileUtils.deletedelete(newFile);return null;- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {Log.logSevere("ArrayStack", "cannot rewrite because of memory failure: " + e.getMessage(), e);FileUtils.deletedelete(tmpFile);FileUtils.deletedelete(newFile);@@ -975,11 +977,11 @@ public class ArrayStack implements BLOB {FileUtils.deletedelete(f);return newFile;}-+private static <ReferenceType extends Reference> void merge(- CloneableIterator<ReferenceContainer<ReferenceType>> i1,- CloneableIterator<ReferenceContainer<ReferenceType>> i2,- ByteOrder ordering, HeapWriter writer) throws IOException, RowSpaceExceededException {+ final CloneableIterator<ReferenceContainer<ReferenceType>> i1,+ final CloneableIterator<ReferenceContainer<ReferenceType>> i2,+ final ByteOrder ordering, final HeapWriter writer) throws IOException, RowSpaceExceededException {assert i1.hasNext();assert i2.hasNext();byte[] c1lh, c2lh;@@ -1037,7 +1039,7 @@ public class ArrayStack implements BLOB {assert ordering.compare(c2.getTermHash(), c2lh) > 0;}break;-+}// catch up remaining entriesassert !(i1.hasNext() && i2.hasNext());@@ -1066,10 +1068,10 @@ public class ArrayStack implements BLOB {}// finished with writing}-+private static <ReferenceType extends Reference> void rewrite(- CloneableIterator<ReferenceContainer<ReferenceType>> i,- ByteOrder ordering, HeapWriter writer) throws IOException, RowSpaceExceededException {+ final CloneableIterator<ReferenceContainer<ReferenceType>> i,+ final ByteOrder ordering, final HeapWriter writer) throws IOException, RowSpaceExceededException {assert i.hasNext();byte[] clh;ReferenceContainer<ReferenceType> c;@@ -1099,7 +1101,7 @@ public class ArrayStack implements BLOB {heap.insert("aaaaaaaaaaac".getBytes(), "sieben acht neun".getBytes());heap.insert("aaaaaaaaaaad".getBytes(), "zehn elf zwoelf".getBytes());// iterate over keys- Iterator<byte[]> i = heap.keys(true, false);+ final Iterator<byte[]> i = heap.keys(true, false);while (i.hasNext()) {System.out.println("key_b: " + UTF8.String(i.next()));}@@ -1111,5 +1113,5 @@ public class ArrayStack implements BLOB {Log.logException(e);}}-+}diff --git a/source/net/yacy/kelondro/data/word/WordReferenceRow.java b/source/net/yacy/kelondro/data/word/WordReferenceRow.javaindex 548bfb8b7..78a610ac4 100644--- a/source/net/yacy/kelondro/data/word/WordReferenceRow.java+++ b/source/net/yacy/kelondro/data/word/WordReferenceRow.java@@ -9,7 +9,7 @@// $LastChangedBy$//// 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@@ -46,7 +46,7 @@ import net.yacy.kelondro.util.ByteArray;*/public final class WordReferenceRow extends AbstractReference implements WordReference, Cloneable {-+public static final Row urlEntryRow = new Row(new Column[]{new Column("h", Column.celltype_string, Column.encoder_bytes, Word.commonHashLength, "urlhash"),new Column("a", Column.celltype_cardinal, Column.encoder_b256, 2, "lastModified"),@@ -72,14 +72,14 @@ public final class WordReferenceRow extends AbstractReference implements WordRefBase64Order.enhancedCoder);// available chars: b,e,j,q-+/*** object for termination of concurrent blocking queue processing*/public static final Row.Entry poisonRowEntry = urlEntryRow.newEntry();public static final WordReferenceRow poison = new WordReferenceRow(poisonRowEntry);--++// static propertiesprivate static final int col_urlhash = 0; // h 12 the url hash b64-encodedprivate static final int col_lastModified = 1; // a 2 last-modified time of the document where word appears@@ -94,7 +94,7 @@ public final class WordReferenceRow extends AbstractReference implements WordRefprivate static final int col_urlLength = 10; // m 1 byte-length of complete URLprivate static final int col_urlComps = 11; // n 1 number of path components- // dynamic properties+ // dynamic propertiesprivate static final int col_typeofword = 12; // g 1 grammatical classificationprivate static final int col_flags = 13; // z 4 b64-encoded appearance flags (24 bit, see definition below)private static final int col_hitcount = 14; // c 1 number of occurrences of this word in text@@ -115,7 +115,7 @@ public final class WordReferenceRow extends AbstractReference implements WordRefpublic static final int flag_app_emphasized = 29; // word is emphasized in text (i.e. bold, italics, special size)private final Row.Entry entry;-+public WordReferenceRow(final byte[] urlHash,final int urlLength, // byte-length of complete URL@@ -161,7 +161,7 @@ public final class WordReferenceRow extends AbstractReference implements WordRefthis.entry.setCol(col_reserve1, 0);this.entry.setCol(col_reserve2, 0);}-+public WordReferenceRow(final byte[] urlHash,final int urlLength, // byte-length of complete URLfinal int urlComps, // number of path components@@ -194,7 +194,7 @@ public final class WordReferenceRow extends AbstractReference implements WordRefthis.entry.setCol(col_reserve1, 0);this.entry.setCol(col_reserve2, 0);}-+public void setWord(final Word word) {this.entry.setCol(col_typeofword, new byte[]{(byte) 0});this.entry.setCol(col_flags, word.flags.bytes());@@ -203,35 +203,35 @@ public final class WordReferenceRow extends AbstractReference implements WordRefthis.entry.setCol(col_posinphrase, word.posInPhrase);this.entry.setCol(col_posofphrase, word.numOfPhrase);}-+public WordReferenceRow(final String external) {this.entry = urlEntryRow.newEntry(external, true);}-+public WordReferenceRow(final byte[] row) {this.entry = urlEntryRow.newEntry(row);}-+public WordReferenceRow(final byte[] row, final int offset, final boolean clone) {this.entry = urlEntryRow.newEntry(row, offset, clone);}-+public WordReferenceRow(final Row.Entry rentry) {- // FIXME: see if cloning is necessary+ // no cloning is necessary since there is no further manipulation after this initial instantiationthis.entry = rentry;}-+@Overridepublic WordReferenceRow clone() {final byte[] b = new byte[urlEntryRow.objectsize];- System.arraycopy(entry.bytes(), 0, b, 0, urlEntryRow.objectsize);+ System.arraycopy(this.entry.bytes(), 0, b, 0, urlEntryRow.objectsize);return new WordReferenceRow(b);}public String toPropertyForm() {- return entry.toPropertyForm('=', true, true, false, false);+ return this.entry.toPropertyForm('=', true, true, false, false);}-+public Entry toKelondroEntry() {return this.entry;}@@ -247,7 +247,7 @@ public final class WordReferenceRow extends AbstractReference implements WordRefpublic long lastModified() {return MicroDate.reverseMicroDateDays((int) this.entry.getColLong(col_lastModified));}-+public long freshUntil() {return MicroDate.reverseMicroDateDays((int) this.entry.getColLong(col_freshUntil));}@@ -292,31 +292,31 @@ public final class WordReferenceRow extends AbstractReference implements WordRefpublic int wordsintitle() {return (int) this.entry.getColLong(col_wordsInTitle);}-+public int llocal() {return (int) this.entry.getColLong(col_llocal);}-+public int lother() {return (int) this.entry.getColLong(col_lother);}-+public int urllength() {return (int) this.entry.getColLong(col_urlLength);}-+public int urlcomps() {return (int) this.entry.getColLong(col_urlComps);}-+public Bitfield flags() {return new Bitfield(this.entry.getColBytes(col_flags, false));}-+public double termFrequency() {- return (((double) this.hitcount()) / ((double) (this.wordsintext() + this.wordsintitle() + 1)));+ return (((double) hitcount()) / ((double) (wordsintext() + wordsintitle() + 1)));}-+@Overridepublic String toString() {return toPropertyForm();@@ -327,18 +327,18 @@ public final class WordReferenceRow extends AbstractReference implements WordRefif (this == obj) return true;if (obj == null) return false;if (!(obj instanceof WordReferenceRow)) return false;- WordReferenceRow other = (WordReferenceRow) obj;- return Base64Order.enhancedCoder.equal(this.urlhash(), other.urlhash());+ final WordReferenceRow other = (WordReferenceRow) obj;+ return Base64Order.enhancedCoder.equal(urlhash(), other.urlhash());}-+@Overridepublic int hashCode() {- return ByteArray.hashCode(this.urlhash());+ return ByteArray.hashCode(urlhash());}public void join(final Reference oe) {throw new UnsupportedOperationException("");-+}-+}diff --git a/source/net/yacy/kelondro/index/BufferedObjectIndex.java b/source/net/yacy/kelondro/index/BufferedObjectIndex.javaindex 5c2ea04d7..d11620452 100644--- a/source/net/yacy/kelondro/index/BufferedObjectIndex.java+++ b/source/net/yacy/kelondro/index/BufferedObjectIndex.java@@ -2,7 +2,7 @@* BufferedObjectIndex* Copyright 2010 by Michael Peter Christen* First released 18.4.2010 at http://yacy.net- *+ ** $LastChangedDate$* $LastChangedRevision$* $LastChangedBy$@@ -11,12 +11,12 @@* modify it under the terms of the GNU Lesser General Public* License as published by the Free Software Foundation; either* version 2.1 of the License, or (at your option) any later version.- *+ ** This library 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* Lesser General Public License for more details.- *+ ** You should have received a copy of the GNU Lesser General Public License* along with this program in the file lgpl21.txt* If not, see <http://www.gnu.org/licenses/>.@@ -48,50 +48,50 @@ public class BufferedObjectIndex implements Index, Iterable<Row.Entry> {private final RowSet buffer;private final int buffersize;private final Row.EntryComparator entryComparator;-- public BufferedObjectIndex(Index backend, int buffersize) {++ public BufferedObjectIndex(final Index backend, final int buffersize) {this.backend = backend;this.buffersize = buffersize;this.buffer = new RowSet(backend.row());this.entryComparator = new Row.EntryComparator(backend.row().objectOrder);}-+public byte[] smallestKey() {if (this.buffer == null || this.buffer.isEmpty()) return this.backend.smallestKey();if (this.backend.isEmpty()) return this.buffer.smallestKey();return this.backend.row().getOrdering().smallest(this.buffer.smallestKey(), this.backend.smallestKey());}-+public byte[] largestKey() {if (this.buffer == null || this.buffer.isEmpty()) return this.backend.largestKey();if (this.backend.isEmpty()) return this.buffer.largestKey();return this.backend.row().getOrdering().largest(this.buffer.largestKey(), this.backend.largestKey());}-+private final void flushBuffer() throws IOException, RowSpaceExceededException {if (this.buffer.size() > 0) {- for (Row.Entry e: this.buffer) {+ for (final Row.Entry e: this.buffer) {this.backend.put(e);}this.buffer.clear();}}-+public long mem() {return this.backend.mem() + this.buffer.mem();}-+/*** check size of buffer in such a way that a put into the buffer is possible* afterwards without exceeding the given maximal buffersize- * @throws RowSpaceExceededException- * @throws IOException+ * @throws RowSpaceExceededException+ * @throws IOException*/private final void checkBuffer() throws IOException, RowSpaceExceededException {if (this.buffer.size() >= this.buffersize) flushBuffer();}-- public void addUnique(Entry row) throws RowSpaceExceededException, IOException {++ public void addUnique(final Entry row) throws RowSpaceExceededException, IOException {synchronized (this.backend) {checkBuffer();this.buffer.put(row);@@ -109,9 +109,9 @@ public class BufferedObjectIndex implements Index, Iterable<Row.Entry> {synchronized (this.backend) {try {flushBuffer();- } catch (IOException e) {+ } catch (final IOException e) {Log.logException(e);- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {Log.logException(e);}this.backend.close();@@ -131,26 +131,26 @@ public class BufferedObjectIndex implements Index, Iterable<Row.Entry> {return this.buffer.size() + this.backend.size();}}-- public Entry get(byte[] key) throws IOException {++ public Entry get(final byte[] key, final boolean forcecopy) throws IOException {synchronized (this.backend) {- Entry entry = this.buffer.get(key);+ final Entry entry = this.buffer.get(key, forcecopy);if (entry != null) return entry;- return this.backend.get(key);+ return this.backend.get(key, forcecopy);}}- public Map<byte[], Row.Entry> get(Collection<byte[]> keys) throws IOException, InterruptedException {- final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(this.row().objectOrder);+ public Map<byte[], Row.Entry> get(final Collection<byte[]> keys, final boolean forcecopy) throws IOException, InterruptedException {+ final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(row().objectOrder);Row.Entry entry;- for (byte[] key: keys) {- entry = get(key);+ for (final byte[] key: keys) {+ entry = get(key, forcecopy);if (entry != null) map.put(key, entry);}return map;}- public boolean has(byte[] key) {+ public boolean has(final byte[] key) {synchronized (this.backend) {return this.buffer.has(key) || this.backend.has(key);}@@ -165,28 +165,28 @@ public class BufferedObjectIndex implements Index, Iterable<Row.Entry> {/*** Adds the row to the index. The row is identified by the primary key of the row.* @param row a index row- * @return true if this set did _not_ already contain the given row.+ * @return true if this set did _not_ already contain the given row.* @throws IOException* @throws RowSpaceExceededException*/- public boolean put(Entry row) throws IOException, RowSpaceExceededException {+ public boolean put(final Entry row) throws IOException, RowSpaceExceededException {synchronized (this.backend) {checkBuffer();return this.buffer.put(row);}}- public Entry remove(byte[] key) throws IOException {+ public Entry remove(final byte[] key) throws IOException {synchronized (this.backend) {- Entry entry = this.buffer.remove(key);+ final Entry entry = this.buffer.remove(key);if (entry != null) return entry;return this.backend.remove(key);}}- public boolean delete(byte[] key) throws IOException {+ public boolean delete(final byte[] key) throws IOException {synchronized (this.backend) {- boolean b = this.buffer.delete(key);+ final boolean b = this.buffer.delete(key);if (b) return true;return this.backend.delete(key);}@@ -199,12 +199,12 @@ public class BufferedObjectIndex implements Index, Iterable<Row.Entry> {}}- public List<Row.Entry> top(int count) throws IOException {- List<Row.Entry> list = new ArrayList<Row.Entry>();+ public List<Row.Entry> top(final int count) throws IOException {+ final List<Row.Entry> list = new ArrayList<Row.Entry>();synchronized (this.backend) {- List<Row.Entry> list0 = buffer.top(count);+ List<Row.Entry> list0 = this.buffer.top(count);list.addAll(list0);- list0 = backend.top(count - list.size());+ list0 = this.backend.top(count - list.size());list.addAll(list0);}return list;@@ -213,16 +213,16 @@ public class BufferedObjectIndex implements Index, Iterable<Row.Entry> {public Entry removeOne() throws IOException {synchronized (this.backend) {if (!this.buffer.isEmpty()) {- Entry entry = this.buffer.removeOne();+ final Entry entry = this.buffer.removeOne();if (entry != null) return entry;}return this.backend.removeOne();}}- public Entry replace(Entry row) throws RowSpaceExceededException, IOException {+ public Entry replace(final Entry row) throws RowSpaceExceededException, IOException {synchronized (this.backend) {- Entry entry = this.buffer.replace(row);+ final Entry entry = this.buffer.replace(row);if (entry != null) return entry;return this.backend.replace(row);}@@ -232,7 +232,7 @@ public class BufferedObjectIndex implements Index, Iterable<Row.Entry> {return this.buffer.row();}- public CloneableIterator<byte[]> keys(boolean up, byte[] firstKey) throws IOException {+ public CloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {synchronized (this.backend) {return new MergeIterator<byte[]>(this.buffer.keys(up, firstKey),@@ -246,13 +246,13 @@ public class BufferedObjectIndex implements Index, Iterable<Row.Entry> {public Iterator<Entry> iterator() {try {return this.rows();- } catch (IOException e) {+ } catch (final IOException e) {Log.logException(e);return null;}}- public CloneableIterator<Entry> rows(boolean up, byte[] firstKey) throws IOException {+ public CloneableIterator<Entry> rows(final boolean up, final byte[] firstKey) throws IOException {synchronized (this.backend) {return new MergeIterator<Entry>(this.buffer.rows(up, firstKey),@@ -273,7 +273,7 @@ public class BufferedObjectIndex implements Index, Iterable<Row.Entry> {true);}}-+/*** special iterator for BufferedObjectIndex:* iterates only objects from the buffer. The use case for this iterator is given@@ -290,24 +290,24 @@ public class BufferedObjectIndex implements Index, Iterable<Row.Entry> {* @return an iterator of the elements in the buffer.* @throws IOException*/- public HandleSet keysFromBuffer(int load) throws IOException {+ public HandleSet keysFromBuffer(final int load) throws IOException {if (load > this.buffersize) throw new IOException("buffer load size exceeded");synchronized (this.backend) {int missing = Math.min(this.backend.size(), load - this.buffer.size());while (missing-- > 0) {try {this.buffer.put(this.backend.removeOne());- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {Log.logException(e);break;}}- HandleSet handles = new HandleSet(this.buffer.row().primaryKeyLength, this.buffer.row().objectOrder, this.buffer.size());- Iterator<byte[]> i = this.buffer.keys();+ final HandleSet handles = new HandleSet(this.buffer.row().primaryKeyLength, this.buffer.row().objectOrder, this.buffer.size());+ final Iterator<byte[]> i = this.buffer.keys();while (i.hasNext()) {try {handles.put(i.next());- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {Log.logException(e);break;}diff --git a/source/net/yacy/kelondro/index/Cache.java b/source/net/yacy/kelondro/index/Cache.javaindex 88e95efb5..c1e77155a 100644--- a/source/net/yacy/kelondro/index/Cache.java+++ b/source/net/yacy/kelondro/index/Cache.java@@ -2,7 +2,7 @@* Cache.java* Copyright 2006 by Michael Peter Christen* First released 26.10.2006 at http://yacy.net- *+ ** $LastChangedDate$* $LastChangedRevision$* $LastChangedBy$@@ -11,12 +11,12 @@* modify it under the terms of the GNU Lesser General Public* License as published by the Free Software Foundation; either* version 2.1 of the License, or (at your option) any later version.- *+ ** This library 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* Lesser General Public License for more details.- *+ ** You should have received a copy of the GNU Lesser General Public License* along with this program in the file lgpl21.txt* If not, see <http://www.gnu.org/licenses/>.@@ -32,6 +32,7 @@ import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.TreeMap;+import net.yacy.kelondro.index.Row.Entry;import net.yacy.kelondro.order.CloneableIterator;import net.yacy.kelondro.util.MemoryControl;@@ -51,7 +52,7 @@ public final class Cache implements Index, Iterable<Row.Entry> {private static final TreeMap<String, Cache> objectTracker = new TreeMap<String, Cache>();private static final long memStopGrow = 40 * 1024 * 1024; // a limit for the node cache to stop growing if less than this memory amount is availableprivate 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-+// class objectsprivate final Index index; // the back-end of the cacheprivate RowSet readHitCache; // contains a complete copy of the cached objects@@ -60,7 +61,7 @@ public final class Cache implements Index, Iterable<Row.Entry> {private int readHit, readMiss, writeUnique, writeDouble, cacheDelete, cacheFlush;private int hasnotHit, hasnotMiss, hasnotUnique, hasnotDouble, hasnotDelete;private final int hitLimit, missLimit;-+/*** create a ObjectIndex cache. The cache may either limited by a number of entries in the hit/miss cache* or the cache size can only be limited by the available RAM@@ -77,7 +78,7 @@ public final class Cache implements Index, Iterable<Row.Entry> {}private void init() {- Row row = index.row();+ final Row row = this.index.row();this.keyrow = new Row(new Column[]{row.column(0)}, row.objectOrder);this.readHitCache = new RowSet(row);this.readMissCache = new RowSet(this.keyrow);@@ -93,35 +94,35 @@ public final class Cache implements Index, Iterable<Row.Entry> {this.hasnotDouble = 0;this.hasnotDelete = 0;}-+public long mem() {return this.index.mem() + this.readHitCache.mem() + this.readMissCache.mem();}-+public final int writeBufferSize() {return 0;}-+public final static long getMemStopGrow() {return memStopGrow ;}-+public final static long getMemStartShrink() {return memStartShrink ;}-+public final int getHitLimit() {return this.hitLimit;}-+public final int getMissLimit() {return this.missLimit;}-+public byte[] smallestKey() {return this.index.smallestKey();}-+public byte[] largestKey() {return this.index.largestKey();}@@ -138,90 +139,90 @@ public final class Cache implements Index, Iterable<Row.Entry> {final Cache theObjectsCache = objectTracker.get(filename);return theObjectsCache.memoryStats();}-+private final Map<String, String> memoryStats() {// returns statistical data about this objectfinal HashMap<String, String> map = new HashMap<String, String>(20);- map.put("objectHitChunkSize", (readHitCache == null) ? "0" : Integer.toString(readHitCache.rowdef.objectsize));- map.put("objectHitCacheCount", (readHitCache == null) ? "0" : Integer.toString(readHitCache.size()));- map.put("objectHitMem", (readHitCache == null) ? "0" : Long.toString(readHitCache.rowdef.objectsize * readHitCache.size()));- map.put("objectHitCacheReadHit", Integer.toString(readHit));- map.put("objectHitCacheReadMiss", Integer.toString(readMiss));- map.put("objectHitCacheWriteUnique", Integer.toString(writeUnique));- map.put("objectHitCacheWriteDouble", Integer.toString(writeDouble));- map.put("objectHitCacheDeletes", Integer.toString(cacheDelete));- map.put("objectHitCacheFlushes", Integer.toString(cacheFlush));-- map.put("objectMissChunkSize", (readMissCache == null) ? "0" : Integer.toString(readMissCache.rowdef.objectsize));- map.put("objectMissCacheCount", (readMissCache == null) ? "0" : Integer.toString(readMissCache.size()));- map.put("objectMissMem", (readMissCache == null) ? "0" : Long.toString(readMissCache.rowdef.objectsize * readMissCache.size()));- map.put("objectMissCacheReadHit", Integer.toString(hasnotHit));- map.put("objectMissCacheReadMiss", Integer.toString(hasnotMiss));- map.put("objectMissCacheWriteUnique", Integer.toString(hasnotUnique));- map.put("objectMissCacheWriteDouble", Integer.toString(hasnotDouble));- map.put("objectMissCacheDeletes", Integer.toString(hasnotDelete));+ map.put("objectHitChunkSize", (this.readHitCache == null) ? "0" : Integer.toString(this.readHitCache.rowdef.objectsize));+ map.put("objectHitCacheCount", (this.readHitCache == null) ? "0" : Integer.toString(this.readHitCache.size()));+ map.put("objectHitMem", (this.readHitCache == null) ? "0" : Long.toString(this.readHitCache.rowdef.objectsize * this.readHitCache.size()));+ map.put("objectHitCacheReadHit", Integer.toString(this.readHit));+ map.put("objectHitCacheReadMiss", Integer.toString(this.readMiss));+ map.put("objectHitCacheWriteUnique", Integer.toString(this.writeUnique));+ map.put("objectHitCacheWriteDouble", Integer.toString(this.writeDouble));+ map.put("objectHitCacheDeletes", Integer.toString(this.cacheDelete));+ map.put("objectHitCacheFlushes", Integer.toString(this.cacheFlush));++ map.put("objectMissChunkSize", (this.readMissCache == null) ? "0" : Integer.toString(this.readMissCache.rowdef.objectsize));+ map.put("objectMissCacheCount", (this.readMissCache == null) ? "0" : Integer.toString(this.readMissCache.size()));+ map.put("objectMissMem", (this.readMissCache == null) ? "0" : Long.toString(this.readMissCache.rowdef.objectsize * this.readMissCache.size()));+ map.put("objectMissCacheReadHit", Integer.toString(this.hasnotHit));+ map.put("objectMissCacheReadMiss", Integer.toString(this.hasnotMiss));+ map.put("objectMissCacheWriteUnique", Integer.toString(this.hasnotUnique));+ map.put("objectMissCacheWriteDouble", Integer.toString(this.hasnotDouble));+ map.put("objectMissCacheDeletes", Integer.toString(this.hasnotDelete));map.put("objectMissCacheFlushes", "0"); // a miss cache flush can only happen if we have a deletion cache (which we dont have)-+// future feature .. map.put("objectElderTimeRead", index.profile().)return map;}-+/*** checks for space in the miss cache* @return true if it is allowed to write into this cache*/private final boolean checkMissSpace() {// returns true if it is allowed to write into this cache- if (readMissCache == null) return false;-+ if (this.readMissCache == null) return false;+// check given limitationif (this.missLimit > 0 && this.readMissCache.size() >= this.missLimit) return false;-+// check memorylong available = MemoryControl.available();- if (MemoryControl.shortStatus() || available - 2 * 1024 * 1024 < readMissCache.memoryNeededForGrow()) {- readMissCache.clear();+ if (MemoryControl.shortStatus() || available - 2 * 1024 * 1024 < this.readMissCache.memoryNeededForGrow()) {+ this.readMissCache.clear();}available = MemoryControl.available();- return (available - 2 * 1024 * 1024 > readMissCache.memoryNeededForGrow());+ return (available - 2 * 1024 * 1024 > this.readMissCache.memoryNeededForGrow());}-+/*** checks for space in the hit cache* @return true if it is allowed to write into this cache*/private final boolean checkHitSpace() {// returns true if it is allowed to write into this cache- if (readHitCache == null) return false;-+ if (this.readHitCache == null) return false;+// check given limitationif (this.hitLimit > 0 && this.readHitCache.size() >= this.hitLimit) return false;-+// check memorylong available = MemoryControl.available();- if (MemoryControl.shortStatus() || available - 2 * 1024 * 1024 < readHitCache.memoryNeededForGrow()) {- readHitCache.clear();+ if (MemoryControl.shortStatus() || available - 2 * 1024 * 1024 < this.readHitCache.memoryNeededForGrow()) {+ this.readHitCache.clear();}available = MemoryControl.available();- return (available - 2 * 1024 * 1024 > readHitCache.memoryNeededForGrow());+ return (available - 2 * 1024 * 1024 > this.readHitCache.memoryNeededForGrow());}-+public final synchronized void clearCache() {- if (readMissCache != null) readMissCache.clear();- if (readHitCache != null) readHitCache.clear();+ if (this.readMissCache != null) this.readMissCache.clear();+ if (this.readHitCache != null) this.readHitCache.clear();}-+public final synchronized void close() {- index.close();- readHitCache = null;- readMissCache = null;+ this.index.close();+ this.readHitCache = null;+ this.readMissCache = null;}public final synchronized boolean has(final byte[] key) {// first look into the miss cache- if (readMissCache != null) {- if (readMissCache.has(key)) {+ if (this.readMissCache != null) {+ if (this.readMissCache.has(key)) {this.hasnotHit++;return false;} else {@@ -230,23 +231,23 @@ public final class Cache implements Index, Iterable<Row.Entry> {}// then try the hit cache and the buffers- if (readHitCache != null) {- if (readHitCache.has(key)) {+ if (this.readHitCache != null) {+ if (this.readHitCache.has(key)) {this.readHit++;return true;} else {this.readMiss++;}}-+// finally ask the back-end index- return index.has(key);+ return this.index.has(key);}-- public final synchronized Row.Entry get(final byte[] key) throws IOException {++ public final synchronized Row.Entry get(final byte[] key, final boolean cachecopy) throws IOException {// first look into the miss cache- if (readMissCache != null) {- if (readMissCache.has(key)) {+ if (this.readMissCache != null) {+ if (this.readMissCache.has(key)) {this.hasnotHit++;return null;} else {@@ -255,126 +256,126 @@ public final class Cache implements Index, Iterable<Row.Entry> {}Row.Entry entry = null;-+// then try the hit cache and the buffers- if (readHitCache != null) {- entry = readHitCache.get(key);+ if (this.readHitCache != null) {+ entry = this.readHitCache.get(key, cachecopy);if (entry != null) {this.readHit++;return entry;}}-+// finally ask the back-end indexthis.readMiss++;- entry = index.get(key);+ entry = this.index.get(key, cachecopy);// learn from resultif (entry == null) {if (checkMissSpace()) try {- final Row.Entry dummy = readMissCache.replace(readMissCache.row().newEntry(key));+ final Row.Entry dummy = this.readMissCache.replace(this.readMissCache.row().newEntry(key));if (dummy == null) this.hasnotUnique++; else this.hasnotDouble++;- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {clearCache();}return null;}-+if (checkHitSpace()) try {- final Row.Entry dummy = readHitCache.replace(entry);+ final Row.Entry dummy = this.readHitCache.replace(entry);if (dummy == null) this.writeUnique++; else this.writeDouble++;- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {clearCache();}return entry;}- public Map<byte[], Row.Entry> get(Collection<byte[]> keys) throws IOException, InterruptedException {- final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(this.row().objectOrder);+ public Map<byte[], Row.Entry> get(final Collection<byte[]> keys, final boolean forcecopy) throws IOException, InterruptedException {+ final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(row().objectOrder);Row.Entry entry;- for (byte[] key: keys) {- entry = get(key);+ for (final byte[] key: keys) {+ entry = get(key, forcecopy);if (entry != null) map.put(key, entry);}return map;}-+public final synchronized boolean put(final Row.Entry row) throws IOException, RowSpaceExceededException {assert (row != null);assert (row.columns() == row().columns());//assert (!(serverLog.allZero(row.getColBytes(index.primarykey()))));-+final byte[] key = row.getPrimaryKeyBytes();checkHitSpace();-+// remove entry from miss- and hit-cache- if (readMissCache != null) {- if (readMissCache.delete(key)) {+ if (this.readMissCache != null) {+ if (this.readMissCache.delete(key)) {this.hasnotHit++;}}-+// write to the back-endboolean c;try {- c = index.put(row);- } catch (RowSpaceExceededException e1) {+ c = this.index.put(row);+ } catch (final RowSpaceExceededException e1) {// flush all caches to get more memoryclearCache();- c = index.put(row); // try again+ c = this.index.put(row); // try again}if (checkHitSpace()) try {- final Row.Entry dummy = readHitCache.replace(row); // overwrite old entry+ final Row.Entry dummy = this.readHitCache.replace(row); // overwrite old entryif (dummy == null) this.writeUnique++; else this.writeDouble++;- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {clearCache();}return c;}-+public final synchronized Row.Entry replace(final Row.Entry row) throws IOException, RowSpaceExceededException {assert (row != null);assert (row.columns() == row().columns());//assert (!(serverLog.allZero(row.getColBytes(index.primarykey()))));-+final byte[] key = row.getPrimaryKeyBytes();checkHitSpace();-+// remove entry from miss- and hit-cache- if (readMissCache != null) {- if (readMissCache.delete(key)) {+ if (this.readMissCache != null) {+ if (this.readMissCache.delete(key)) {this.hasnotHit++;// the entry does not exist beforetry {- index.put(row);- } catch (RowSpaceExceededException e1) {+ this.index.put(row);+ } catch (final RowSpaceExceededException e1) {// flush all caches to get more memoryclearCache();- index.put(row); // try again+ this.index.put(row); // try again}// write to backendif (checkHitSpace()) try {- final Row.Entry dummy = readHitCache.replace(row); // learn that entry+ final Row.Entry dummy = this.readHitCache.replace(row); // learn that entryif (dummy == null) this.writeUnique++; else this.writeDouble++;- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {clearCache();}return null;}}-+Row.Entry entry = null;// write to the back-endtry {- entry = index.replace(row);- } catch (RowSpaceExceededException e1) {+ entry = this.index.replace(row);+ } catch (final RowSpaceExceededException e1) {// flush all caches to get more memoryclearCache();- index.replace(row); // try again+ this.index.replace(row); // try again}if (checkHitSpace()) try {- final Row.Entry dummy = readHitCache.replace(row); // learn that entry+ final Row.Entry dummy = this.readHitCache.replace(row); // learn that entryif (dummy == null) this.writeUnique++; else this.writeDouble++;- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {clearCache();}return entry;@@ -384,29 +385,29 @@ public final class Cache implements Index, Iterable<Row.Entry> {assert (row != null);assert (row.columns() == row().columns());//assert (!(serverLog.allZero(row.getColBytes(index.primarykey()))));-+final byte[] key = row.getPrimaryKeyBytes();checkHitSpace();-+// remove entry from miss- and hit-cache- if (readMissCache != null) {+ if (this.readMissCache != null) {this.readMissCache.delete(key);this.hasnotDelete++;// the entry does not exist before}-+// the worst case: we must write to the back-end directlytry {- index.addUnique(row);- } catch (RowSpaceExceededException e1) {+ this.index.addUnique(row);+ } catch (final RowSpaceExceededException e1) {// flush all caches to get more memoryclearCache();- index.addUnique(row); // try again+ this.index.addUnique(row); // try again}if (checkHitSpace()) try {- final Row.Entry dummy = readHitCache.replace(row); // learn that entry+ final Row.Entry dummy = this.readHitCache.replace(row); // learn that entryif (dummy == null) this.writeUnique++; else this.writeDouble++;- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {clearCache();}}@@ -416,35 +417,35 @@ public final class Cache implements Index, Iterable<Row.Entry> {addUnique(row);return;}-+assert (row != null);assert (row.columns() == row().columns());-+final byte[] key = row.getPrimaryKeyBytes();checkHitSpace();-+// remove entry from miss- and hit-cache- if (readMissCache != null) {+ if (this.readMissCache != null) {this.readMissCache.delete(key);this.hasnotDelete++;}// the worst case: we must write to the backend directlytry {- index.addUnique(row);- } catch (RowSpaceExceededException e1) {+ this.index.addUnique(row);+ } catch (final RowSpaceExceededException e1) {// flush all caches to get more memoryclearCache();- index.addUnique(row); // try again+ this.index.addUnique(row); // try again}if (checkHitSpace()) try {- final Row.Entry dummy = readHitCache.replace(row); // learn that entry+ final Row.Entry dummy = this.readHitCache.replace(row); // learn that entryif (dummy == null) this.writeUnique++; else this.writeDouble++;- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {clearCache();}}-+public final synchronized void addUnique(final List<Row.Entry> rows) throws IOException, RowSpaceExceededException {final Iterator<Row.Entry> i = rows.iterator();Row.Entry r;@@ -452,7 +453,7 @@ public final class Cache implements Index, Iterable<Row.Entry> {r = i.next();try {addUnique(r);- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {// flush all caches to get more memoryclearCache();addUnique(r); // try again@@ -461,30 +462,30 @@ public final class Cache implements Index, Iterable<Row.Entry> {}public final synchronized List<RowCollection> removeDoubles() throws IOException, RowSpaceExceededException {- return index.removeDoubles();+ return this.index.removeDoubles();// todo: remove reported entries from the cache!!!}-+public final synchronized boolean delete(final byte[] key) throws IOException {checkMissSpace();-+// add entry to miss-cacheif (checkMissSpace()) try {// set the miss cache; if there was already an entry we know that the return value must be null- final Row.Entry dummy = readMissCache.replace(readMissCache.row().newEntry(key));+ final Row.Entry dummy = this.readMissCache.replace(this.readMissCache.row().newEntry(key));if (dummy == null) {this.hasnotUnique++;} else {this.hasnotHit++;this.hasnotDouble++;}- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {clearCache();}-+// remove entry from hit-cache- if (readHitCache != null) {- final Row.Entry entry = readHitCache.remove(key);+ if (this.readHitCache != null) {+ final Row.Entry entry = this.readHitCache.remove(key);if (entry == null) {this.readMiss++;} else {@@ -492,30 +493,30 @@ public final class Cache implements Index, Iterable<Row.Entry> {this.cacheDelete++;}}-- return index.delete(key);++ return this.index.delete(key);}public final synchronized Row.Entry remove(final byte[] key) throws IOException {checkMissSpace();-+// add entry to miss-cacheif (checkMissSpace()) try {// set the miss cache; if there was already an entry we know that the return value must be null- final Row.Entry dummy = readMissCache.replace(readMissCache.row().newEntry(key));+ final Row.Entry dummy = this.readMissCache.replace(this.readMissCache.row().newEntry(key));if (dummy == null) {this.hasnotUnique++;} else {this.hasnotHit++;this.hasnotDouble++;}- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {clearCache();}-+// remove entry from hit-cache- if (readHitCache != null) {- final Row.Entry entry = readHitCache.remove(key);+ if (this.readHitCache != null) {+ final Row.Entry entry = this.readHitCache.remove(key);if (entry == null) {this.readMiss++;} else {@@ -523,67 +524,67 @@ public final class Cache implements Index, Iterable<Row.Entry> {this.cacheDelete++;}}-- return index.remove(key);++ return this.index.remove(key);}public final synchronized Row.Entry removeOne() throws IOException {-+checkMissSpace();-- final Row.Entry entry = index.removeOne();++ final Row.Entry entry = this.index.removeOne();if (entry == null) return null;final byte[] key = entry.getPrimaryKeyBytes();if (checkMissSpace()) try {- final Row.Entry dummy = readMissCache.replace(readMissCache.row().newEntry(key));+ final Row.Entry dummy = this.readMissCache.replace(this.readMissCache.row().newEntry(key));if (dummy == null) this.hasnotUnique++; else this.hasnotDouble++;- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {clearCache();}- if (readHitCache != null) {- if (readHitCache.delete(key)) this.cacheDelete++;+ if (this.readHitCache != null) {+ if (this.readHitCache.delete(key)) this.cacheDelete++;}return entry;}- public synchronized List<Row.Entry> top(int count) throws IOException {+ public synchronized List<Row.Entry> top(final int count) throws IOException {return this.index.top(count);}public final synchronized Row row() {- return index.row();+ return this.index.row();}public final synchronized CloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {- return index.keys(up, firstKey);+ return this.index.keys(up, firstKey);}public final synchronized CloneableIterator<Row.Entry> rows(final boolean up, final byte[] firstKey) throws IOException {- return index.rows(up, firstKey);+ return this.index.rows(up, firstKey);}public final Iterator<Entry> iterator() {try {return rows();- } catch (IOException e) {+ } catch (final IOException e) {return null;}}-+public final synchronized CloneableIterator<Row.Entry> rows() throws IOException {- return index.rows();+ return this.index.rows();}public final int size() {- return index.size();+ return this.index.size();}public final boolean isEmpty() {- return index.isEmpty();+ return this.index.isEmpty();}-+public final String filename() {- return index.filename();+ return this.index.filename();}public final void clear() throws IOException {diff --git a/source/net/yacy/kelondro/index/HandleMap.java b/source/net/yacy/kelondro/index/HandleMap.javaindex e2998a6df..21d3d2f22 100644--- a/source/net/yacy/kelondro/index/HandleMap.java+++ b/source/net/yacy/kelondro/index/HandleMap.java@@ -199,7 +199,7 @@ public final class HandleMap implements Iterable<Row.Entry> {public final long get(final byte[] key) {assert (key != null);- final Row.Entry indexentry = this.index.get(key);+ final Row.Entry indexentry = this.index.get(key, false);if (indexentry == null) return -1;return indexentry.getColLong(1);}@@ -236,7 +236,7 @@ public final class HandleMap implements Iterable<Row.Entry> {assert key != null;assert a > 0; // it does not make sense to add 0. If this occurres, it is a performance issuesynchronized (this.index) {- final Row.Entry indexentry = this.index.get(key);+ final Row.Entry indexentry = this.index.get(key, true);if (indexentry == null) {final Row.Entry newentry = this.rowdef.newEntry();newentry.setCol(0, key);diff --git a/source/net/yacy/kelondro/index/Index.java b/source/net/yacy/kelondro/index/Index.javaindex 6604a5d18..da436c848 100644--- a/source/net/yacy/kelondro/index/Index.java+++ b/source/net/yacy/kelondro/index/Index.java@@ -2,7 +2,7 @@* Index* Copyright 2005 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany* First released 26.10.2005 at http://yacy.net- *+ ** $LastChangedDate$* $LastChangedRevision$* $LastChangedBy$@@ -11,12 +11,12 @@* modify it under the terms of the GNU Lesser General Public* License as published by the Free Software Foundation; either* version 2.1 of the License, or (at your option) any later version.- *+ ** This library 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* Lesser General Public License for more details.- *+ ** You should have received a copy of the GNU Lesser General Public License* along with this program in the file lgpl21.txt* If not, see <http://www.gnu.org/licenses/>.@@ -43,14 +43,14 @@ public interface Index extends Iterable<Row.Entry> {public byte[] smallestKey();public byte[] largestKey();public boolean has(byte[] key); // use this only if there is no get in case that has returns true- public Map<byte[], Row.Entry> get(final Collection<byte[]> keys) throws IOException, InterruptedException;- public Row.Entry get(byte[] key) throws IOException;+ public Map<byte[], Row.Entry> get(final Collection<byte[]> keys, boolean forcecopy) throws IOException, InterruptedException;+ public Row.Entry get(byte[] key, boolean forcecopy) throws IOException;public Row.Entry replace(Row.Entry row) throws RowSpaceExceededException, IOException;-+/*** Adds the row to the index. The row is identified by the primary key of the row.* @param row a index row- * @return true if this set did _not_ already contain the given row.+ * @return true if this set did _not_ already contain the given row.* @throws IOException* @throws RowSpaceExceededException*/diff --git a/source/net/yacy/kelondro/index/RAMIndex.java b/source/net/yacy/kelondro/index/RAMIndex.javaindex 635445782..878176d91 100644--- a/source/net/yacy/kelondro/index/RAMIndex.java+++ b/source/net/yacy/kelondro/index/RAMIndex.java@@ -2,7 +2,7 @@* RAMIndex* Copyright 2008 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany* First released 07.01.2008 at http://yacy.net- *+ ** $LastChangedDate$* $LastChangedRevision$* $LastChangedBy$@@ -11,12 +11,12 @@* modify it under the terms of the GNU Lesser General Public* License as published by the Free Software Foundation; either* version 2.1 of the License, or (at your option) any later version.- *+ ** This library 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* Lesser General Public License for more details.- *+ ** You should have received a copy of the GNU Lesser General Public License* along with this program in the file lgpl21.txt* If not, see <http://www.gnu.org/licenses/>.@@ -31,6 +31,7 @@ import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.TreeMap;+import net.yacy.kelondro.index.Row.Entry;import net.yacy.kelondro.order.CloneableIterator;import net.yacy.kelondro.order.MergeIterator;@@ -38,17 +39,17 @@ import net.yacy.kelondro.order.StackIterator;public final class RAMIndex implements Index, Iterable<Row.Entry> {-+private static final TreeMap<String, RAMIndex> objectTracker = new TreeMap<String, RAMIndex>();-+private final String name;private final Row rowdef;private RowSet index0;private RowSet index1;private final Row.EntryComparator entryComparator;//private final int spread;-- public RAMIndex(String name, final Row rowdef, final int expectedspace) {++ public RAMIndex(final String name, final Row rowdef, final int expectedspace) {this.name = name;this.rowdef = rowdef;this.entryComparator = new Row.EntryComparator(rowdef.objectOrder);@@ -56,8 +57,8 @@ public final class RAMIndex implements Index, Iterable<Row.Entry> {reset();objectTracker.put(name, this);}-- private RAMIndex(String name, final Row rowdef, RowSet index0, RowSet index1, Row.EntryComparator entryComparator) {++ private RAMIndex(final String name, final Row rowdef, final RowSet index0, final RowSet index1, final Row.EntryComparator entryComparator) {this.name = name;this.rowdef = rowdef;this.index0 = index0;@@ -69,110 +70,110 @@ public final class RAMIndex implements Index, Iterable<Row.Entry> {public static final Iterator<Map.Entry<String, RAMIndex>> objects() {return objectTracker.entrySet().iterator();}-+@Overridepublic RAMIndex clone() {- return new RAMIndex(this.name + ".clone", this.rowdef, index0.clone(), index1.clone(), entryComparator);+ return new RAMIndex(this.name + ".clone", this.rowdef, this.index0.clone(), this.index1.clone(), this.entryComparator);}-+public void clear() {reset();}-+public void trim() {if (this.index0 != null) this.index0.trim();if (this.index1 != null) this.index1.trim();}-+public final synchronized void reset() {this.index0 = null; // first flush RAM to make room- this.index0 = new RowSet(rowdef);+ this.index0 = new RowSet(this.rowdef);this.index1 = null; // to show that this is the initialization phase}-+public final synchronized void reset(final int initialspace) throws RowSpaceExceededException {this.index0 = null; // first flush RAM to make room- this.index0 = new RowSet(rowdef, initialspace);+ this.index0 = new RowSet(this.rowdef, initialspace);this.index1 = null; // to show that this is the initialization phase}-+public final Row row() {- return index0.row();+ return this.index0.row();}-+protected final void finishInitialization() {- if (index1 == null) {+ if (this.index1 == null) {// finish initialization phase- index0.sort();- index0.uniq();- index0.trim();- index1 = new RowSet(rowdef); //new RowSetArray(rowdef, spread);+ this.index0.sort();+ this.index0.uniq();+ this.index0.trim();+ this.index1 = new RowSet(this.rowdef); //new RowSetArray(rowdef, spread);}}-+public final synchronized byte[] smallestKey() {- final byte[] b0 = index0.smallestKey();+ final byte[] b0 = this.index0.smallestKey();if (b0 == null) return null;- if (index1 == null) return b0;- final byte[] b1 = index0.smallestKey();- if (b1 == null || rowdef.objectOrder.compare(b1, b0) > 0) return b0;+ if (this.index1 == null) return b0;+ final byte[] b1 = this.index0.smallestKey();+ if (b1 == null || this.rowdef.objectOrder.compare(b1, b0) > 0) return b0;return b1;}-+public final synchronized byte[] largestKey() {- final byte[] b0 = index0.largestKey();+ final byte[] b0 = this.index0.largestKey();if (b0 == null) return null;- if (index1 == null) return b0;- final byte[] b1 = index0.largestKey();- if (b1 == null || rowdef.objectOrder.compare(b0, b1) > 0) return b0;+ if (this.index1 == null) return b0;+ final byte[] b1 = this.index0.largestKey();+ if (b1 == null || this.rowdef.objectOrder.compare(b0, b1) > 0) return b0;return b1;}-- public final synchronized Row.Entry get(final byte[] key) {++ public final synchronized Row.Entry get(final byte[] key, final boolean forceclone) {assert (key != null);finishInitialization();- assert index0.isSorted();- final Row.Entry indexentry = index0.get(key);+ assert this.index0.isSorted();+ final Row.Entry indexentry = this.index0.get(key, forceclone);if (indexentry != null) return indexentry;- return index1.get(key);+ return this.index1.get(key, forceclone);}- public Map<byte[], Row.Entry> get(Collection<byte[]> keys) throws IOException, InterruptedException {- final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(this.row().objectOrder);+ public Map<byte[], Row.Entry> get(final Collection<byte[]> keys, final boolean forcecopy) throws IOException, InterruptedException {+ final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(row().objectOrder);Row.Entry entry;- for (byte[] key: keys) {- entry = get(key);+ for (final byte[] key: keys) {+ entry = get(key, forcecopy);if (entry != null) map.put(key, entry);}return map;}-+public final synchronized boolean has(final byte[] key) {assert (key != null);finishInitialization();- assert index0.isSorted();- if (index0.has(key)) return true;- return index1.has(key);+ assert this.index0.isSorted();+ if (this.index0.has(key)) return true;+ return this.index1.has(key);}-+public final synchronized Row.Entry replace(final Row.Entry entry) throws RowSpaceExceededException {assert (entry != null);finishInitialization();// if the new entry is within the initialization part, just overwrite it- assert index0.isSorted();+ assert this.index0.isSorted();final byte[] key = entry.getPrimaryKeyBytes();- if (index0.has(key)) {+ if (this.index0.has(key)) {// replace the entry- return index0.replace(entry);+ return this.index0.replace(entry);}// else place it in the index1- return index1.replace(entry);+ return this.index1.replace(entry);}-+/*** Adds the row to the index. The row is identified by the primary key of the row.* @param row a index row- * @return true if this set did _not_ already contain the given row.+ * @return true if this set did _not_ already contain the given row.* @throws IOException* @throws RowSpaceExceededException*/@@ -182,29 +183,29 @@ public final class RAMIndex implements Index, Iterable<Row.Entry> {synchronized (this) {finishInitialization();// if the new entry is within the initialization part, just overwrite it- assert index0.isSorted();+ assert this.index0.isSorted();final byte[] key = entry.getPrimaryKeyBytes();- if (index0.has(key)) {+ if (this.index0.has(key)) {// replace the entry- index0.put(entry);+ this.index0.put(entry);return false;}// else place it in the index1- return index1.put(entry);+ return this.index1.put(entry);}}-+public final void addUnique(final Row.Entry entry) throws RowSpaceExceededException {assert (entry != null);if (entry == null) return;synchronized (this) {- if (index1 == null) {+ if (this.index1 == null) {// we are in the initialization phase- index0.addUnique(entry);+ this.index0.addUnique(entry);return;}// initialization is over, add to secondary index- index1.addUnique(entry);+ this.index1.addUnique(entry);}}@@ -212,209 +213,209 @@ public final class RAMIndex implements Index, Iterable<Row.Entry> {final Iterator<Entry> i = rows.iterator();while (i.hasNext()) addUnique(i.next());}-+public final synchronized long inc(final byte[] key, final int col, final long add, final Row.Entry initrow) throws RowSpaceExceededException {assert (key != null);finishInitialization();- assert index0.isSorted();- final long l = index0.inc(key, col, add, null);+ assert this.index0.isSorted();+ final long l = this.index0.inc(key, col, add, null);if (l != Long.MIN_VALUE) return l;- return index1.inc(key, col, add, initrow);- }-+ return this.index1.inc(key, col, add, initrow);+ }+public final synchronized ArrayList<RowCollection> removeDoubles() throws RowSpaceExceededException {// finish initialization phase explicitely- index0.sort();- if (index1 == null) {- return index0.removeDoubles();+ this.index0.sort();+ if (this.index1 == null) {+ return this.index0.removeDoubles();}- final ArrayList<RowCollection> d0 = index0.removeDoubles();- final ArrayList<RowCollection> d1 = index1.removeDoubles();+ final ArrayList<RowCollection> d0 = this.index0.removeDoubles();+ final ArrayList<RowCollection> d1 = this.index1.removeDoubles();d0.addAll(d1);return d0;}-+public final synchronized boolean delete(final byte[] key) {finishInitialization();// if the new entry is within the initialization part, just delete it- boolean b = index0.delete(key);+ boolean b = this.index0.delete(key);if (b) {- assert index0.get(key) == null; // check if remove worked+ assert !this.index0.has(key); // check if remove workedreturn true;}// else remove it from the index1- b = index1.delete(key);- assert index1.get(key) == null : "removed " + ((b) ? " true" : " false") + ", and index entry still exists"; // check if remove worked+ b = this.index1.delete(key);+ assert this.index1.has(key) : "removed " + ((b) ? " true" : " false") + ", and index entry still exists"; // check if remove workedreturn b;}public final synchronized Row.Entry remove(final byte[] key) {finishInitialization();// if the new entry is within the initialization part, just delete it- int s = index0.size();- final Row.Entry indexentry = index0.remove(key);+ int s = this.index0.size();+ final Row.Entry indexentry = this.index0.remove(key);if (indexentry != null) {- assert index0.size() < s: "s = " + s + ", index0.size() = " + index0.size();- assert index0.get(key) == null; // check if remove worked+ assert this.index0.size() < s: "s = " + s + ", index0.size() = " + this.index0.size();+ assert !this.index0.has(key); // check if remove workedreturn indexentry;}// else remove it from the index1- s = index1.size();- final Row.Entry removed = index1.remove(key);- assert removed == null || index1.size() < s: "s = " + s + ", index1.size() = " + index1.size();- assert index1.get(key) == null : "removed " + ((removed == null) ? " is null" : " is not null") + ", and index entry still exists"; // check if remove worked+ s = this.index1.size();+ final Row.Entry removed = this.index1.remove(key);+ assert removed == null || this.index1.size() < s: "s = " + s + ", index1.size() = " + this.index1.size();+ assert !this.index1.has(key) : "removed " + ((removed == null) ? " is null" : " is not null") + ", and index entry still exists"; // check if remove workedreturn removed;}public final synchronized Row.Entry removeOne() {- if (index1 != null && !index1.isEmpty()) {- return index1.removeOne();+ if (this.index1 != null && !this.index1.isEmpty()) {+ return this.index1.removeOne();}- if (index0 != null && !index0.isEmpty()) {- return index0.removeOne();+ if (this.index0 != null && !this.index0.isEmpty()) {+ return this.index0.removeOne();}return null;}-- public synchronized List<Row.Entry> top(int count) throws IOException {- List<Row.Entry> list = new ArrayList<Row.Entry>();- List<Row.Entry> list0 = index1.top(count);++ public synchronized List<Row.Entry> top(final int count) throws IOException {+ final List<Row.Entry> list = new ArrayList<Row.Entry>();+ List<Row.Entry> list0 = this.index1.top(count);list.addAll(list0);- list0 = index0.top(count - list.size());+ list0 = this.index0.top(count - list.size());list.addAll(list0);return list;}-+public long mem() {- if (index0 != null && index1 == null) {- return index0.mem();+ if (this.index0 != null && this.index1 == null) {+ return this.index0.mem();}- if (index0 == null && index1 != null) {- return index1.mem();+ if (this.index0 == null && this.index1 != null) {+ return this.index1.mem();}- assert (index0 != null && index1 != null);- return index0.mem() + index1.mem();+ assert (this.index0 != null && this.index1 != null);+ return this.index0.mem() + this.index1.mem();}-+public final synchronized int size() {- if (index0 != null && index1 == null) {- return index0.size();+ if (this.index0 != null && this.index1 == null) {+ return this.index0.size();}- if (index0 == null && index1 != null) {- return index1.size();+ if (this.index0 == null && this.index1 != null) {+ return this.index1.size();}- assert (index0 != null && index1 != null);- return index0.size() + index1.size();+ assert (this.index0 != null && this.index1 != null);+ return this.index0.size() + this.index1.size();}-+public final synchronized boolean isEmpty() {- if (index0 != null && index1 == null) {- return index0.isEmpty();+ if (this.index0 != null && this.index1 == null) {+ return this.index0.isEmpty();}- if (index0 == null && index1 != null) {- return index1.isEmpty();+ if (this.index0 == null && this.index1 != null) {+ return this.index1.isEmpty();}- assert (index0 != null && index1 != null);- if (!index0.isEmpty()) return false;- if (!index1.isEmpty()) return false;+ assert (this.index0 != null && this.index1 != null);+ if (!this.index0.isEmpty()) return false;+ if (!this.index1.isEmpty()) return false;return true;}--++public final synchronized CloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) {// returns the key-iterator of the underlying kelondroIndex- if (index1 == null) {+ if (this.index1 == null) {// finish initialization phase- index0.sort();- index0.uniq();- index1 = new RowSet(rowdef); //new RowSetArray(rowdef, spread);- return index0.keys(up, firstKey);+ this.index0.sort();+ this.index0.uniq();+ this.index1 = new RowSet(this.rowdef); //new RowSetArray(rowdef, spread);+ return this.index0.keys(up, firstKey);}- assert (index1 != null);- if (index0 == null) {+ assert (this.index1 != null);+ if (this.index0 == null) {//assert consistencyAnalysis0() : "consistency problem: " + consistencyAnalysis();- return index1.keys(up, firstKey);+ return this.index1.keys(up, firstKey);}// index0 should be sorted// sort index1 to enable working of the merge iterator//assert consistencyAnalysis0() : "consistency problem: " + consistencyAnalysis();- final CloneableIterator<byte[]> k0 = index0.keys(up, firstKey);- final CloneableIterator<byte[]> k1 = index1.keys(up, firstKey);+ final CloneableIterator<byte[]> k0 = this.index0.keys(up, firstKey);+ final CloneableIterator<byte[]> k1 = this.index1.keys(up, firstKey);if (k0 == null) return k1;if (k1 == null) return k0;return new MergeIterator<byte[]>(k0,k1,- rowdef.objectOrder,+ this.rowdef.objectOrder,MergeIterator.simpleMerge,true);}public final synchronized CloneableIterator<Row.Entry> rows(final boolean up, final byte[] firstKey) {// returns the row-iterator of the underlying kelondroIndex- if (index1 == null) {+ if (this.index1 == null) {// finish initialization phase- index0.sort();- index0.uniq();- index1 = new RowSet(rowdef); //new RowSetArray(rowdef, spread);- return index0.rows(up, firstKey);+ this.index0.sort();+ this.index0.uniq();+ this.index1 = new RowSet(this.rowdef); //new RowSetArray(rowdef, spread);+ return this.index0.rows(up, firstKey);}- assert (index1 != null);- if (index0 == null) {+ assert (this.index1 != null);+ if (this.index0 == null) {//assert consistencyAnalysis0() : "consistency problem: " + consistencyAnalysis();- return index1.rows(up, firstKey);+ return this.index1.rows(up, firstKey);}// index0 should be sorted// sort index1 to enable working of the merge iterator//index1.sort();//assert consistencyAnalysis0() : "consistency problem: " + consistencyAnalysis();- final CloneableIterator<Row.Entry> k0 = index0.rows(up, firstKey);- final CloneableIterator<Row.Entry> k1 = index1.rows(up, firstKey);+ final CloneableIterator<Row.Entry> k0 = this.index0.rows(up, firstKey);+ final CloneableIterator<Row.Entry> k1 = this.index1.rows(up, firstKey);if (k0 == null) return k1;if (k1 == null) return k0;return new MergeIterator<Row.Entry>(k0,k1,- entryComparator,+ this.entryComparator,MergeIterator.simpleMerge,true);}-+public final Iterator<Entry> iterator() {return rows();}-+public final synchronized CloneableIterator<Row.Entry> rows() {// returns the row-iterator of the underlying kelondroIndex- if (index1 == null) {+ if (this.index1 == null) {// finish initialization phase- index0.sort();- index0.uniq();- index1 = new RowSet(rowdef); //new RowSetArray(rowdef, spread);- return index0.rows();+ this.index0.sort();+ this.index0.uniq();+ this.index1 = new RowSet(this.rowdef); //new RowSetArray(rowdef, spread);+ return this.index0.rows();}- assert (index1 != null);- if (index0 == null) {+ assert (this.index1 != null);+ if (this.index0 == null) {//assert consistencyAnalysis0() : "consistency problem: " + consistencyAnalysis();- return index1.rows();+ return this.index1.rows();}// index0 should be sorted// sort index1 to enable working of the merge iterator//index1.sort();//assert consistencyAnalysis0() : "consistency problem: " + consistencyAnalysis();- return new StackIterator<Row.Entry>(index0.rows(), index1.rows());+ return new StackIterator<Row.Entry>(this.index0.rows(), this.index1.rows());}-+public final synchronized void close() {- if (index0 != null) index0.close();- if (index1 != null) index1.close();+ if (this.index0 != null) this.index0.close();+ if (this.index1 != null) this.index1.close();objectTracker.remove(this.name);}public final String filename() {return null; // this does not have a file name}-+public final void deleteOnExit() {// do nothing, there is no file}diff --git a/source/net/yacy/kelondro/index/RAMIndexCluster.java b/source/net/yacy/kelondro/index/RAMIndexCluster.javaindex 2bc997c21..d8b118424 100644--- a/source/net/yacy/kelondro/index/RAMIndexCluster.java+++ b/source/net/yacy/kelondro/index/RAMIndexCluster.java@@ -2,7 +2,7 @@* RAMIndexCluster* Copyright 2009 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany* First released 12.03.2009 at http://yacy.net- *+ ** $LastChangedDate$* $LastChangedRevision$* $LastChangedBy$@@ -11,12 +11,12 @@* modify it under the terms of the GNU Lesser General Public* License as published by the Free Software Foundation; either* version 2.1 of the License, or (at your option) any later version.- *+ ** This library 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* Lesser General Public License for more details.- *+ ** You should have received a copy of the GNU Lesser General Public License* along with this program in the file lgpl21.txt* If not, see <http://www.gnu.org/licenses/>.@@ -31,6 +31,7 @@ import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.TreeMap;+import net.yacy.kelondro.index.Row.Entry;import net.yacy.kelondro.logging.Log;import net.yacy.kelondro.order.CloneableIterator;@@ -43,8 +44,8 @@ public final class RAMIndexCluster implements Index, Iterable<Row.Entry>, Cloneaprivate final String name;private final Row rowdef;private final RAMIndex[] cluster;-- public RAMIndexCluster(String name, final Row rowdef, final int clusterSize) {++ public RAMIndexCluster(final String name, final Row rowdef, final int clusterSize) {//assert arraySize < 100 : arraySize;this.name = name;this.cluster = new RAMIndex[clusterSize];@@ -53,67 +54,67 @@ public final class RAMIndexCluster implements Index, Iterable<Row.Entry>, Cloneathis.cluster[i] = new RAMIndex(name + "." + i, rowdef, 0);}}-- private RAMIndexCluster(String name, final Row rowdef, final RAMIndex[] array) {++ private RAMIndexCluster(final String name, final Row rowdef, final RAMIndex[] array) {this.name = name;this.cluster = array;this.rowdef = rowdef;}-+public void trim() {- for (RAMIndex i: this.cluster) if (i != null) i.trim();+ for (final RAMIndex i: this.cluster) if (i != null) i.trim();}-+@Overridepublic RAMIndexCluster clone() {- RAMIndex[] a = new RAMIndex[this.cluster.length];+ final RAMIndex[] a = new RAMIndex[this.cluster.length];for (int i = 0; i < this.cluster.length; i++) {a[i] = this.cluster[i].clone();}return new RAMIndexCluster(this.name + ".clone", this.rowdef, a);}-+private final int indexFor(final byte[] key) {- return (int) ((this.rowdef.objectOrder.cardinal(key) / 17) % ((long) cluster.length));+ return (int) ((this.rowdef.objectOrder.cardinal(key) / 17) % (this.cluster.length));}-+private final int indexFor(final Entry row) {- return (int) ((this.rowdef.objectOrder.cardinal(row.bytes(), 0, row.getPrimaryKeyLength()) / 17) % ((long) cluster.length));+ return (int) ((this.rowdef.objectOrder.cardinal(row.bytes(), 0, row.getPrimaryKeyLength()) / 17) % (this.cluster.length));}-+public final byte[] smallestKey() {- HandleSet keysort = new HandleSet(this.rowdef.primaryKeyLength, this.rowdef.objectOrder, this.cluster.length);+ final HandleSet keysort = new HandleSet(this.rowdef.primaryKeyLength, this.rowdef.objectOrder, this.cluster.length);synchronized (this.cluster) {- for (RAMIndex rs: this.cluster) try {+ for (final RAMIndex rs: this.cluster) try {keysort.put(rs.smallestKey());- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {Log.logException(e);}}return keysort.smallestKey();}-+public final byte[] largestKey() {- HandleSet keysort = new HandleSet(this.rowdef.primaryKeyLength, this.rowdef.objectOrder, this.cluster.length);+ final HandleSet keysort = new HandleSet(this.rowdef.primaryKeyLength, this.rowdef.objectOrder, this.cluster.length);synchronized (this.cluster) {- for (RAMIndex rs: this.cluster) try {+ for (final RAMIndex rs: this.cluster) try {keysort.put(rs.largestKey());- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {Log.logException(e);}}return keysort.largestKey();}-+private final RAMIndex accessArray(final int i) {RAMIndex r = this.cluster[i];if (r == null) synchronized (this.cluster) {- r = new RAMIndex(name + "." + i, this.rowdef, 0);+ r = new RAMIndex(this.name + "." + i, this.rowdef, 0);this.cluster[i] = r;}return r;}-+public final void addUnique(final Entry row) throws RowSpaceExceededException {final int i = indexFor(row);assert i >= 0 : "i = " + i;@@ -122,19 +123,19 @@ public final class RAMIndexCluster implements Index, Iterable<Row.Entry>, Clonea}public final void addUnique(final List<Entry> rows) throws RowSpaceExceededException {- for (Entry row: rows) addUnique(row);+ for (final Entry row: rows) addUnique(row);}public final void clear() {synchronized (this.cluster) {- for (RAMIndex c: this.cluster) if (c != null) c.clear();+ for (final RAMIndex c: this.cluster) if (c != null) c.clear();}}public final void close() {clear();synchronized (this.cluster) {- for (RAMIndex c: this.cluster) if (c != null) c.close();+ for (final RAMIndex c: this.cluster) if (c != null) c.close();}}@@ -147,19 +148,19 @@ public final class RAMIndexCluster implements Index, Iterable<Row.Entry>, Cloneareturn null;}- public final Entry get(final byte[] key) {+ public final Entry get(final byte[] key, final boolean forcecopy) {final int i = indexFor(key);if (i < 0) return null;final RAMIndex r = this.cluster[i];if (r == null) return null;- return r.get(key);+ return r.get(key, forcecopy);}- public Map<byte[], Row.Entry> get(Collection<byte[]> keys) throws IOException, InterruptedException {- final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(this.row().objectOrder);+ public Map<byte[], Row.Entry> get(final Collection<byte[]> keys, final boolean forcecopy) throws IOException, InterruptedException {+ final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(row().objectOrder);Row.Entry entry;- for (byte[] key: keys) {- entry = get(key);+ for (final byte[] key: keys) {+ entry = get(key, forcecopy);if (entry != null) map.put(key, entry);}return map;@@ -176,19 +177,19 @@ public final class RAMIndexCluster implements Index, Iterable<Row.Entry>, Cloneapublic final CloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) {synchronized (this.cluster) {final Collection<CloneableIterator<byte[]>> col = new ArrayList<CloneableIterator<byte[]>>();- for (int i = 0; i < this.cluster.length; i++) {- if (this.cluster[i] != null) {- col.add(this.cluster[i].keys(up, firstKey));+ for (final RAMIndex element : this.cluster) {+ if (element != null) {+ col.add(element.keys(up, firstKey));}}return MergeIterator.cascade(col, this.rowdef.objectOrder, MergeIterator.simpleMerge, up);- }+ }}-+/*** Adds the row to the index. The row is identified by the primary key of the row.* @param row a index row- * @return true if this set did _not_ already contain the given row.+ * @return true if this set did _not_ already contain the given row.* @throws IOException* @throws RowSpaceExceededException*/@@ -237,15 +238,15 @@ public final class RAMIndexCluster implements Index, Iterable<Row.Entry>, Cloneareturn null;}- public List<Row.Entry> top(int count) {- List<Row.Entry> list = new ArrayList<Row.Entry>();+ public List<Row.Entry> top(final int count) {+ final List<Row.Entry> list = new ArrayList<Row.Entry>();synchronized (this.cluster) {- for (int i = 0; i < this.cluster.length; i++) {- if (this.cluster[i] != null) {+ for (final RAMIndex element : this.cluster) {+ if (element != null) {try {- List<Row.Entry> list0 = this.cluster[i].top(count - list.size());+ final List<Row.Entry> list0 = element.top(count - list.size());list.addAll(list0);- } catch (IOException e) {+ } catch (final IOException e) {continue;}}@@ -254,7 +255,7 @@ public final class RAMIndexCluster implements Index, Iterable<Row.Entry>, Clonea}return list;}-+public final Entry replace(final Entry row) throws RowSpaceExceededException {final int i = indexFor(row);assert i >= 0 : "i = " + i;@@ -288,7 +289,7 @@ public final class RAMIndexCluster implements Index, Iterable<Row.Entry>, Cloneapublic final int size() {int c = 0;synchronized (this.cluster) {- for (RAMIndex i: this.cluster) if (i != null) c += i.size();+ for (final RAMIndex i: this.cluster) if (i != null) c += i.size();}return c;}@@ -296,18 +297,18 @@ public final class RAMIndexCluster implements Index, Iterable<Row.Entry>, Cloneapublic long mem() {long m = 0;synchronized (this.cluster) {- for (RAMIndex i: this.cluster) if (i != null) m += i.mem();+ for (final RAMIndex i: this.cluster) if (i != null) m += i.mem();}return m;}-+public final boolean isEmpty() {synchronized (this.cluster) {- for (RAMIndex i: this.cluster) if (i != null && !i.isEmpty()) return false;+ for (final RAMIndex i: this.cluster) if (i != null && !i.isEmpty()) return false;}return true;}-+public final Iterator<Entry> iterator() {return this.rows(true, null);}diff --git a/source/net/yacy/kelondro/index/RowCollection.java b/source/net/yacy/kelondro/index/RowCollection.javaindex aa16268e9..209aa7e17 100644--- a/source/net/yacy/kelondro/index/RowCollection.java+++ b/source/net/yacy/kelondro/index/RowCollection.java@@ -1177,7 +1177,7 @@ public class RowCollection implements Iterable<Row.Entry>, Cloneable {boolean allfound = true;for (int i = 0; i < testsize; i++) {final String rh = randomHash();- if (e.get(rh.getBytes()) == null) {+ if (e.get(rh.getBytes(), true) == null) {allfound = false;System.out.println("not found hash " + rh + " at attempt " + i);break;@@ -1187,7 +1187,7 @@ public class RowCollection implements Iterable<Row.Entry>, Cloneable {System.out.println("e allfound = " + ((allfound) ? "true" : "false") + ": " + (t13 - t12) + " nanoseconds");boolean noghosts = true;for (int i = 0; i < testsize; i++) {- if (e.get(randomHash().getBytes()) != null) {+ if (e.get(randomHash().getBytes(), true) != null) {noghosts = false;break;}diff --git a/source/net/yacy/kelondro/index/RowSet.java b/source/net/yacy/kelondro/index/RowSet.javaindex c89184056..7fd0ec157 100644--- a/source/net/yacy/kelondro/index/RowSet.java+++ b/source/net/yacy/kelondro/index/RowSet.java@@ -130,18 +130,18 @@ public class RowSet extends RowCollection implements Index, Iterable<Row.Entry>return index >= 0;}- public final synchronized Row.Entry get(final byte[] key) {+ public final synchronized Row.Entry get(final byte[] key, final boolean forcecopy) {assert key.length == this.rowdef.primaryKeyLength;final int index = find(key, 0);if (index < 0) return null;- return get(index, true);+ return get(index, forcecopy);}- public Map<byte[], Row.Entry> get(final Collection<byte[]> keys) throws IOException, InterruptedException {+ public Map<byte[], Row.Entry> get(final Collection<byte[]> keys, final boolean forcecopy) throws IOException, InterruptedException {final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(row().objectOrder);Row.Entry entry;for (final byte[] key: keys) {- entry = get(key);+ entry = get(key, forcecopy);if (entry != null) map.put(key, entry);}return map;@@ -668,7 +668,7 @@ public class RowSet extends RowCollection implements Index, Iterable<Row.Entry>for (int i = 0; i < testsize; i++) {key = randomHash(random);if (i % 5 == 0) continue;- if (c.get(key) == null) System.out.println("missing entry " + UTF8.String(key));+ if (c.get(key, true) == null) System.out.println("missing entry " + UTF8.String(key));}c.sort();System.out.println("RESULT SIZE: " + c.size());diff --git a/source/net/yacy/kelondro/rwi/ReferenceContainer.java b/source/net/yacy/kelondro/rwi/ReferenceContainer.javaindex 405344b2e..725cfaca5 100644--- a/source/net/yacy/kelondro/rwi/ReferenceContainer.java+++ b/source/net/yacy/kelondro/rwi/ReferenceContainer.java@@ -9,7 +9,7 @@// $LastChangedBy$//// 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@@ -53,14 +53,14 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSetprivate byte[] termHash;protected ReferenceFactory<ReferenceType> factory;-+public ReferenceContainer(final ReferenceFactory<ReferenceType> factory, final byte[] termHash, final RowSet collection) {super(collection);assert termHash == null || (termHash[2] != '@' && termHash.length == this.rowdef.primaryKeyLength);this.factory = factory;this.termHash = termHash;}-+public ReferenceContainer(final ReferenceFactory<ReferenceType> factory, final byte[] termHash) {super(factory.getRow());assert termHash == null || (termHash[2] != '@' && termHash.length == this.rowdef.primaryKeyLength);@@ -68,7 +68,7 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSetthis.factory = factory;this.lastTimeWrote = 0;}-+public ReferenceContainer(final ReferenceFactory<ReferenceType> factory, final byte[] termHash, final int objectCount) throws RowSpaceExceededException {super(factory.getRow(), objectCount);assert termHash == null || (termHash[2] != '@' && termHash.length == this.rowdef.primaryKeyLength);@@ -76,13 +76,13 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSetthis.factory = factory;this.lastTimeWrote = 0;}-+public ReferenceContainer<ReferenceType> topLevelClone() throws RowSpaceExceededException {- final ReferenceContainer<ReferenceType> newContainer = new ReferenceContainer<ReferenceType>(this.factory, this.termHash, this.size());+ final ReferenceContainer<ReferenceType> newContainer = new ReferenceContainer<ReferenceType>(this.factory, this.termHash, size());newContainer.addAllUnique(this);return newContainer;}-+public static <ReferenceType extends Reference> ReferenceContainer<ReferenceType> emptyContainer(final ReferenceFactory<ReferenceType> factory, final byte[] termHash) {assert termHash == null || (termHash[2] != '@' && termHash.length == factory.getRow().primaryKeyLength);return new ReferenceContainer<ReferenceType>(factory, termHash);@@ -94,7 +94,7 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSet}public void setWordHash(final byte[] newTermHash) {- assert termHash == null || (termHash[2] != '@' && termHash.length == this.rowdef.primaryKeyLength);+ assert this.termHash == null || (this.termHash[2] != '@' && this.termHash.length == this.rowdef.primaryKeyLength);this.termHash = newTermHash;}@@ -103,31 +103,31 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSet}public byte[] getTermHash() {- return termHash;+ return this.termHash;}-+public void add(final Reference entry) throws RowSpaceExceededException {// add without double-occurrence testassert entry.toKelondroEntry().objectsize() == super.rowdef.objectsize;this.addUnique(entry.toKelondroEntry());}-+public ReferenceContainer<ReferenceType> merge(final ReferenceContainer<ReferenceType> c) throws RowSpaceExceededException {return new ReferenceContainer<ReferenceType>(this.factory, this.termHash, super.merge(c));}-+public Reference replace(final Reference entry) throws RowSpaceExceededException {assert entry.toKelondroEntry().objectsize() == super.rowdef.objectsize;final Row.Entry r = super.replace(entry.toKelondroEntry());if (r == null) return null;- return factory.produceSlow(r);+ return this.factory.produceSlow(r);}-+public void put(final Reference entry) throws RowSpaceExceededException {assert entry.toKelondroEntry().objectsize() == super.rowdef.objectsize;super.put(entry.toKelondroEntry());}-+public boolean putRecent(final Reference entry) throws RowSpaceExceededException {assert entry.toKelondroEntry().objectsize() == super.rowdef.objectsize;// returns true if the new entry was added, false if it already existed@@ -135,7 +135,7 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSetif (oldEntryRow == null) {return true;}- final Reference oldEntry = factory.produceSlow(oldEntryRow);+ final Reference oldEntry = this.factory.produceSlow(oldEntryRow);if (entry.isOlder(oldEntry)) { // A more recent Entry is already in this containerthis.replace(oldEntry.toKelondroEntry()); // put it backreturn false;@@ -161,9 +161,9 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSetthis.lastTimeWrote = java.lang.Math.max(this.lastTimeWrote, c.updated());return x;}-+public ReferenceType getReference(final byte[] urlHash) {- final Row.Entry entry = super.get(urlHash);+ final Row.Entry entry = super.get(urlHash, false);if (entry == null) return null;return this.factory.produceSlow(entry);}@@ -194,33 +194,33 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSetpublic class entryIterator implements Iterator<ReferenceType> {Iterator<Row.Entry> rowEntryIterator;-+public entryIterator() {- rowEntryIterator = iterator();+ this.rowEntryIterator = iterator();}-+public boolean hasNext() {- return rowEntryIterator.hasNext();+ return this.rowEntryIterator.hasNext();}public ReferenceType next() {- final Row.Entry rentry = rowEntryIterator.next();+ final Row.Entry rentry = this.rowEntryIterator.next();if (rentry == null) return null;- return factory.produceSlow(rentry);+ return ReferenceContainer.this.factory.produceSlow(rentry);}public void remove() {- rowEntryIterator.remove();+ this.rowEntryIterator.remove();}-+}-+public static Object mergeUnique(final Object a, final Object b) throws RowSpaceExceededException {final ReferenceContainer<?> c = (ReferenceContainer<?>) a;c.addAllUnique((ReferenceContainer<?>) b);return c;}-+public static final Method containerMergeMethod;static {Method meth = null;@@ -252,15 +252,15 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSetfinal ReferenceContainer<ReferenceType> rcLocal = ReferenceContainer.joinContainers(factory, includeContainers, maxDistance);if (rcLocal == null) return ReferenceContainer.emptyContainer(factory, null, 0);excludeContainers(factory, rcLocal, excludeContainers);-+return rcLocal;}-+public static <ReferenceType extends Reference> ReferenceContainer<ReferenceType> joinContainers(final ReferenceFactory<ReferenceType> factory,final Collection<ReferenceContainer<ReferenceType>> containers,final int maxDistance) throws RowSpaceExceededException {-+// order entities by their sizefinal TreeMap<Long, ReferenceContainer<ReferenceType>> map = new TreeMap<Long, ReferenceContainer<ReferenceType>>();ReferenceContainer<ReferenceType> singleContainer;@@ -269,18 +269,18 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSetwhile (i.hasNext()) {// get next entity:singleContainer = i.next();-+// check resultif (singleContainer == null || singleContainer.isEmpty()) return null; // as this is a cunjunction of searches, we have no result if any word is not known-+// store result in order of result sizemap.put(Long.valueOf(singleContainer.size() * 1000 + count), singleContainer);count++;}-+// check if there is any resultif (map.isEmpty()) return null; // no result, nothing found-+// the map now holds the search results in order of number of hits per word// we now must pairwise build up a conjunction of these setsLong k = map.firstKey(); // the smallest, which means, the one with the least entries@@ -300,31 +300,31 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSetif (searchResult.isEmpty()) return null;return searchResult;}-+public static <ReferenceType extends Reference> ReferenceContainer<ReferenceType> excludeContainers(final ReferenceFactory<ReferenceType> factory,ReferenceContainer<ReferenceType> pivot,final Collection<ReferenceContainer<ReferenceType>> containers) {-+// check if there is any resultif (containers == null || containers.isEmpty()) return pivot; // no result, nothing found-+final Iterator<ReferenceContainer<ReferenceType>> i = containers.iterator();while (i.hasNext()) {pivot = excludeDestructive(factory, pivot, i.next());if (pivot == null || pivot.isEmpty()) return null;}-+return pivot;}-+// join methodsprivate static int log2(int x) {int l = 0;while (x > 0) {x = x >> 1; l++;}return l;}-+public static <ReferenceType extends Reference> ReferenceContainer<ReferenceType> joinConstructive(final ReferenceFactory<ReferenceType> factory,final ReferenceContainer<ReferenceType> i1,@@ -332,13 +332,13 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSetfinal int maxDistance) throws RowSpaceExceededException {if ((i1 == null) || (i2 == null)) return null;if (i1.isEmpty() || i2.isEmpty()) return null;-+// decide which method to usefinal int high = ((i1.size() > i2.size()) ? i1.size() : i2.size());final int low = ((i1.size() > i2.size()) ? i2.size() : i1.size());final int stepsEnum = 10 * (high + low - 1);final int stepsTest = 12 * log2(high) * low;-+// start most efficient methodif (stepsEnum > stepsTest) {if (i1.size() < i2.size())@@ -348,7 +348,7 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSet}return joinConstructiveByEnumeration(factory, i1, i2, maxDistance);}-+private static <ReferenceType extends Reference> ReferenceContainer<ReferenceType> joinConstructiveByTest(final ReferenceFactory<ReferenceType> factory,final ReferenceContainer<ReferenceType> small,@@ -369,7 +369,7 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSetassert (ie1.urlhash().length == keylength) : "ie0.urlHash() = " + ASCII.String(ie1.urlhash());assert (ie2.urlhash().length == keylength) : "ie1.urlHash() = " + ASCII.String(ie2.urlhash());// this is a hit. Calculate word distance:-+ie1 = factory.produceFast(ie2);ie1.join(ie2);if (ie1.distance() <= maxDistance) conj.add(ie1);@@ -377,7 +377,7 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSet}return conj;}-+private static <ReferenceType extends Reference> ReferenceContainer<ReferenceType> joinConstructiveByEnumeration(final ReferenceFactory<ReferenceType> factory,final ReferenceContainer<ReferenceType> i1,@@ -389,7 +389,7 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSetassert (keylength == i2.rowdef.width(0));final ReferenceContainer<ReferenceType> conj = new ReferenceContainer<ReferenceType>(factory, null, 0); // start with empty search resultif (!((i1.rowdef.getOrdering().signature().equals(i2.rowdef.getOrdering().signature())))) return conj; // ordering must be equal- ByteOrder ordering = i1.rowdef.getOrdering();+ final ByteOrder ordering = i1.rowdef.getOrdering();final Iterator<ReferenceType> e1 = i1.entries();final Iterator<ReferenceType> e2 = i2.entries();int c;@@ -420,7 +420,7 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSet}return conj;}-+public static <ReferenceType extends Reference> ReferenceContainer<ReferenceType> excludeDestructive(final ReferenceFactory<ReferenceType> factory,final ReferenceContainer<ReferenceType> pivot,@@ -429,20 +429,20 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSetif (excl == null) return pivot;if (pivot.isEmpty()) return null;if (excl.isEmpty()) return pivot;-+// decide which method to usefinal int high = ((pivot.size() > excl.size()) ? pivot.size() : excl.size());final int low = ((pivot.size() > excl.size()) ? excl.size() : pivot.size());final int stepsEnum = 10 * (high + low - 1);final int stepsTest = 12 * log2(high) * low;-+// start most efficient methodif (stepsEnum > stepsTest) {return excludeDestructiveByTest(pivot, excl);}return excludeDestructiveByEnumeration(factory, pivot, excl);}-+private static <ReferenceType extends Reference> ReferenceContainer<ReferenceType> excludeDestructiveByTest(final ReferenceContainer<ReferenceType> pivot,final ReferenceContainer<ReferenceType> excl) {@@ -463,7 +463,7 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSet}return pivot;}-+private static <ReferenceType extends Reference> ReferenceContainer<ReferenceType> excludeDestructiveByEnumeration(final ReferenceFactory<ReferenceType> factory,final ReferenceContainer<ReferenceType> pivot,@@ -504,11 +504,11 @@ public class ReferenceContainer<ReferenceType extends Reference> extends RowSet}public synchronized String toString() {- return "C[" + ASCII.String(termHash) + "] has " + this.size() + " entries";+ return "C[" + ASCII.String(this.termHash) + "] has " + size() + " entries";}-+public int hashCode() {return (int) Base64Order.enhancedCoder.decodeLong(this.termHash, 0, 4);}-+}diff --git a/source/net/yacy/kelondro/table/Relations.java b/source/net/yacy/kelondro/table/Relations.javaindex 4dd2e51d6..3c9618441 100755--- a/source/net/yacy/kelondro/table/Relations.java+++ b/source/net/yacy/kelondro/table/Relations.java@@ -9,7 +9,7 @@// $LastChangedBy$//// 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@@ -44,7 +44,7 @@ public class Relations {private HashMap<String, Index> relations;private final boolean useTailCache;private final boolean exceed134217727;-+public Relations(final File location,final boolean useTailCache,@@ -53,7 +53,7 @@ public class Relations {this.useTailCache = useTailCache;this.exceed134217727 = exceed134217727;}-+private static Row rowdef(String filename) {int p = filename.lastIndexOf('.');if (p >= 0) filename = filename.substring(0, p);@@ -66,7 +66,7 @@ public class Relations {final int keysize = Integer.parseInt(filename.substring(p + 1));return rowdef(keysize, payloadsize);}-+private static Row rowdef(final int keysize, final int payloadsize) {return new Row("byte[] key-" + keysize + ", " +@@ -75,17 +75,17 @@ public class Relations {"byte[] node-" + payloadsize,NaturalOrder.naturalOrder);}-+private static String filename(final String tablename, final int keysize, final int payloadsize) {return tablename + "-" + keysize + "-" + payloadsize + ".eco";}-+public void declareRelation(final String name, final int keysize, final int payloadsize) throws RowSpaceExceededException {// try to get the relation from the relation-cache- final Index relation = relations.get(name);+ final Index relation = this.relations.get(name);if (relation != null) return;// try to find the relation as stored on file- final String[] list = baseDir.list();+ final String[] list = this.baseDir.list();final String targetfilename = filename(name, keysize, payloadsize);for (int i = 0; i < list.length; i++) {if (list[i].startsWith(name)) {@@ -94,11 +94,11 @@ public class Relations {if (row.primaryKeyLength != keysize || row.column(1).cellwidth != payloadsize) continue; // a wrong tableIndex table;try {- table = new Table(new File(baseDir, list[i]), row, 1024*1024, 0, this.useTailCache, this.exceed134217727);- } catch (RowSpaceExceededException e) {- table = new Table(new File(baseDir, list[i]), row, 0, 0, false, this.exceed134217727);+ table = new Table(new File(this.baseDir, list[i]), row, 1024*1024, 0, this.useTailCache, this.exceed134217727);+ } catch (final RowSpaceExceededException e) {+ table = new Table(new File(this.baseDir, list[i]), row, 0, 0, false, this.exceed134217727);}- relations.put(name, table);+ this.relations.put(name, table);return;}}@@ -106,42 +106,42 @@ public class Relations {final Row row = rowdef(keysize, payloadsize);Index table;try {- table = new Table(new File(baseDir, targetfilename), row, 1024*1024, 0, this.useTailCache, this.exceed134217727);- } catch (RowSpaceExceededException e) {- table = new Table(new File(baseDir, targetfilename), row, 0, 0, false, this.exceed134217727);+ table = new Table(new File(this.baseDir, targetfilename), row, 1024*1024, 0, this.useTailCache, this.exceed134217727);+ } catch (final RowSpaceExceededException e) {+ table = new Table(new File(this.baseDir, targetfilename), row, 0, 0, false, this.exceed134217727);}- relations.put(name, table);+ this.relations.put(name, table);}-+public Index getRelation(final String name) throws RowSpaceExceededException {// try to get the relation from the relation-cache- final Index relation = relations.get(name);+ final Index relation = this.relations.get(name);if (relation != null) return relation;// try to find the relation as stored on file- final String[] list = baseDir.list();- for (int i = 0; i < list.length; i++) {- if (list[i].startsWith(name)) {- final Row row = rowdef(list[i]);+ final String[] list = this.baseDir.list();+ for (final String element : list) {+ if (element.startsWith(name)) {+ final Row row = rowdef(element);Index table;try {- table = new Table(new File(baseDir, list[i]), row, 1024*1024, 0, this.useTailCache, this.exceed134217727);- } catch (RowSpaceExceededException e) {- table = new Table(new File(baseDir, list[i]), row, 0, 0, false, this.exceed134217727);+ table = new Table(new File(this.baseDir, element), row, 1024*1024, 0, this.useTailCache, this.exceed134217727);+ } catch (final RowSpaceExceededException e) {+ table = new Table(new File(this.baseDir, element), row, 0, 0, false, this.exceed134217727);}- relations.put(name, table);+ this.relations.put(name, table);return table;}}// the relation does not existreturn null;}-+public String putRelation(final String name, final String key, final String value) throws IOException, RowSpaceExceededException {final byte[] r = putRelation(name, UTF8.getBytes(key), UTF8.getBytes(value));if (r == null) return null;return UTF8.String(r);}-+public byte[] putRelation(final String name, final byte[] key, final byte[] value) throws IOException, RowSpaceExceededException {final Index table = getRelation(name);if (table == null) return null;@@ -154,27 +154,27 @@ public class Relations {if (oldentry == null) return null;return oldentry.getColBytes(3, true);}-+public String getRelation(final String name, final String key) throws IOException, RowSpaceExceededException {final byte[] r = getRelation(name, UTF8.getBytes(key));if (r == null) return null;return UTF8.String(r);}-+public byte[] getRelation(final String name, final byte[] key) throws IOException, RowSpaceExceededException {final Index table = getRelation(name);if (table == null) return null;- final Row.Entry entry = table.get(key);+ final Row.Entry entry = table.get(key, false);if (entry == null) return null;return entry.getColBytes(3, true);}-+public boolean hasRelation(final String name, final byte[] key) throws RowSpaceExceededException {final Index table = getRelation(name);if (table == null) return false;return table.has(key);}-+public byte[] removeRelation(final String name, final byte[] key) throws IOException, RowSpaceExceededException {final Index table = getRelation(name);if (table == null) return null;@@ -182,7 +182,7 @@ public class Relations {if (entry == null) return null;return entry.getColBytes(3, true);}-+public static void main(final String args[]) {final Relations r = new Relations(new File("/Users/admin/"), true, true);try {@@ -192,9 +192,9 @@ public class Relations {r.putRelation(table1, "abcdefg", "eineintrag");} catch (final IOException e) {Log.logException(e);- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {Log.logException(e);}}-+}diff --git a/source/net/yacy/kelondro/table/SQLTable.java b/source/net/yacy/kelondro/table/SQLTable.javaindex ea6006ba3..4e16ea938 100644--- a/source/net/yacy/kelondro/table/SQLTable.java+++ b/source/net/yacy/kelondro/table/SQLTable.java@@ -9,7 +9,7 @@// $LastChangedBy$//// 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@@ -44,8 +44,8 @@ import net.yacy.cora.document.ASCII;import net.yacy.cora.document.UTF8;import net.yacy.kelondro.index.Index;import net.yacy.kelondro.index.Row;-import net.yacy.kelondro.index.RowCollection;import net.yacy.kelondro.index.Row.Entry;+import net.yacy.kelondro.index.RowCollection;import net.yacy.kelondro.logging.Log;import net.yacy.kelondro.order.ByteOrder;import net.yacy.kelondro.order.CloneableIterator;@@ -54,7 +54,7 @@ import net.yacy.kelondro.order.NaturalOrder;/** Commands to create a database using mysql:- *+ ** CREATE database yacy;* USE yacy;* CREATE TABLE hash CHAR(12) not null primary key, value BLOB);@@ -67,35 +67,35 @@ public class SQLTable implements Index, Iterable<Row.Entry> {private static final String db_driver_str_mysql = "org.gjt.mm.mysql.Driver";private static final String db_driver_str_pgsql = "org.postgresql.Driver";-+private static final String db_conn_str_mysql = "jdbc:mysql://192.168.0.2:3306/yacy";private static final String db_conn_str_pgsql = "jdbc:postgresql://192.168.0.2:5432";-+private static final String db_usr_str = "yacy";private static final String db_pwd_str = "yacy";-+private Connection theDBConnection = null;private static final ByteOrder order = new NaturalOrder(true);private final Row rowdef;-+public SQLTable(final String dbType, final Row rowdef) throws Exception {this.rowdef = rowdef;openDatabaseConnection(dbType);}-+private void openDatabaseConnection(final String dbType) throws Exception{- if (dbType == null) throw new IllegalArgumentException();+ if (dbType == null) throw new IllegalArgumentException();- String dbDriverStr = null, dbConnStr = null;+ String dbDriverStr = null, dbConnStr = null;if (dbType.equalsIgnoreCase("mysql")) {dbDriverStr = db_driver_str_mysql;dbConnStr = db_conn_str_mysql;} else if (dbType.equalsIgnoreCase("pgsql")) {dbDriverStr = db_driver_str_pgsql;dbConnStr = db_conn_str_pgsql;- }- try {+ }+ try {Class.forName(dbDriverStr).newInstance();} catch (final Exception e) {throw new Exception ("Unable to load the jdbc driver: " + e.getMessage(),e);@@ -105,25 +105,25 @@ public class SQLTable implements Index, Iterable<Row.Entry> {} catch (final Exception e) {throw new Exception ("Unable to establish a database connection: " + e.getMessage(),e);}-+}-+public long mem() {return 0;}-+public byte[] smallestKey() {return null;}-+public byte[] largestKey() {return null;}public String filename() {- return "dbtest." + theDBConnection.hashCode();+ return "dbtest." + this.theDBConnection.hashCode();}-+public void close() {if (this.theDBConnection != null) try {this.theDBConnection.close();@@ -132,65 +132,65 @@ public class SQLTable implements Index, Iterable<Row.Entry> {}this.theDBConnection = null;}-+public int size() {int size = -1;try {final String sqlQuery = "SELECT count(value) from test";-- final PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);++ final PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);final ResultSet result = sqlStatement.executeQuery();-+while (result.next()) {size = result.getInt(1);- }-+ }+result.close();sqlStatement.close();-+return size;} catch (final Exception e) {Log.logException(e);return -1;}}-+public boolean isEmpty() {return size() == 0;}-+public Row row() {return this.rowdef;}-+public boolean has(final byte[] key) {try {- return (get(key) != null);+ return (get(key, false) != null);} catch (final IOException e) {return false;}}-+public ArrayList<RowCollection> removeDoubles() {return new ArrayList<RowCollection>();}-- public Row.Entry get(final byte[] key) throws IOException {++ public Row.Entry get(final byte[] key, final boolean forcecopy) throws IOException {try {final String sqlQuery = "SELECT value from test where hash = ?";-- final PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);++ final PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);sqlStatement.setString(1, ASCII.String(key));-+byte[] value = null;final ResultSet result = sqlStatement.executeQuery();while (result.next()) {value = result.getBytes("value");- }-+ }+result.close();sqlStatement.close();-+if (value == null) return null;final Row.Entry entry = this.rowdef.newEntry(value);return entry;@@ -199,11 +199,11 @@ public class SQLTable implements Index, Iterable<Row.Entry> {}}- public Map<byte[], Row.Entry> get(Collection<byte[]> keys) throws IOException, InterruptedException {- final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(this.row().objectOrder);+ public Map<byte[], Row.Entry> get(final Collection<byte[]> keys, final boolean forcecopy) throws IOException, InterruptedException {+ final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(row().objectOrder);Row.Entry entry;- for (byte[] key: keys) {- entry = get(key);+ for (final byte[] key: keys) {+ entry = get(key, forcecopy);if (entry != null) map.put(key, entry);}return map;@@ -216,36 +216,36 @@ public class SQLTable implements Index, Iterable<Row.Entry> {"hash, " +"value) " +"VALUES (?,?)";-- final PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);-++ final PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);+sqlStatement.setString(1, row.getColString(0));sqlStatement.setBytes(2, row.bytes());sqlStatement.execute();-+sqlStatement.close();-+return oldEntry;} catch (final Exception e) {throw new IOException(e.getMessage());}}-+public boolean put(final Row.Entry row) throws IOException {try {final String sqlQuery = "INSERT INTO test (" +"hash, " +"value) " +- "VALUES (?,?)";-- final PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);-+ "VALUES (?,?)";++ final PreparedStatement sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);+sqlStatement.setString(1, row.getColString(0));sqlStatement.setBytes(2, row.bytes());sqlStatement.execute();-+sqlStatement.close();-+return false;} catch (final Exception e) {throw new IOException(e.getMessage());@@ -255,29 +255,29 @@ public class SQLTable implements Index, Iterable<Row.Entry> {public synchronized void addUnique(final Row.Entry row) throws IOException {throw new UnsupportedOperationException();}-+public synchronized void addUnique(final Row.Entry row, final Date entryDate) {throw new UnsupportedOperationException();}-+public synchronized void addUnique(final List<Row.Entry> rows) {throw new UnsupportedOperationException();}-+public Row.Entry remove(final byte[] key) throws IOException {PreparedStatement sqlStatement = null;try {-- final Row.Entry entry = this.get(key);++ final Row.Entry entry = this.get(key, false);if (entry == null) return null;-- final String sqlQuery = "DELETE FROM test WHERE hash = ?";--- sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);++ final String sqlQuery = "DELETE FROM test WHERE hash = ?";+++ sqlStatement = this.theDBConnection.prepareStatement(sqlQuery);sqlStatement.setString(1, UTF8.String(key));sqlStatement.execute();-+return entry;} catch (final Exception e) {throw new IOException(e.getMessage());@@ -285,34 +285,34 @@ public class SQLTable implements Index, Iterable<Row.Entry> {if(sqlStatement != null) {try {sqlStatement.close();- } catch (SQLException e) {+ } catch (final SQLException e) {Log.logException(e);}}}}-+public boolean delete(final byte[] key) throws IOException {return remove(key) != null;}-+public Row.Entry removeOne() {return null;}-- public List<Row.Entry> top(int count) throws IOException {++ public List<Row.Entry> top(final int count) throws IOException {return null;}-+public CloneableIterator<Row.Entry> rows(final boolean up, final byte[] startKey) throws IOException {// Objects are of type kelondroRow.Entryreturn null;}-+public Iterator<Entry> iterator() {try {return rows();- } catch (IOException e) {+ } catch (final IOException e) {return null;}}@@ -339,25 +339,25 @@ public class SQLTable implements Index, Iterable<Row.Entry> {public ByteOrder order() {return order;}-+public int primarykey() {return 0;}-+public final int cacheObjectChunkSize() {// dummy methodreturn -1;}-+public long[] cacheObjectStatus() {// dummy methodreturn null;}-+public final int cacheNodeChunkSize() {return -1;}-+public final int[] cacheNodeStatus() {return new int[]{0,0,0,0,0,0,0,0,0,0};}diff --git a/source/net/yacy/kelondro/table/SplitTable.java b/source/net/yacy/kelondro/table/SplitTable.javaindex d80152467..d1602f1b5 100644--- a/source/net/yacy/kelondro/table/SplitTable.java+++ b/source/net/yacy/kelondro/table/SplitTable.java@@ -9,7 +9,7 @@// $LastChangedBy$//// 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@@ -49,9 +49,9 @@ import net.yacy.kelondro.index.Cache;import net.yacy.kelondro.index.HandleSet;import net.yacy.kelondro.index.Index;import net.yacy.kelondro.index.Row;+import net.yacy.kelondro.index.Row.Entry;import net.yacy.kelondro.index.RowCollection;import net.yacy.kelondro.index.RowSpaceExceededException;-import net.yacy.kelondro.index.Row.Entry;import net.yacy.kelondro.logging.Log;import net.yacy.kelondro.order.CloneableIterator;import net.yacy.kelondro.order.MergeIterator;@@ -71,31 +71,31 @@ public class SplitTable implements Index, Iterable<Row.Entry> {// the thread pool for the keeperOf executor serviceprivate ExecutorService executor;-+private Map<String, Index> tables; // a map from a date string to a kelondroIndex objectprivate final Row rowdef;private final File path;private final String prefix;private final Order<Row.Entry> entryOrder;private String current;- private long fileAgeLimit;- private long fileSizeLimit;+ private final long fileAgeLimit;+ private final long fileSizeLimit;private boolean useTailCache;- private boolean exceed134217727;+ private final boolean exceed134217727;public SplitTable(- final File path,- final String tablename,+ final File path,+ final String tablename,final Row rowdef,final boolean useTailCache,final boolean exceed134217727) throws RowSpaceExceededException {- this(path, tablename, rowdef, ArrayStack.oneMonth, (long) Integer.MAX_VALUE, useTailCache, exceed134217727);+ this(path, tablename, rowdef, ArrayStack.oneMonth, Integer.MAX_VALUE, useTailCache, exceed134217727);}private SplitTable(- final File path,- final String tablename,- final Row rowdef,+ final File path,+ final String tablename,+ final Row rowdef,final long fileAgeLimit,final long fileSizeLimit,final boolean useTailCache,@@ -110,86 +110,86 @@ public class SplitTable implements Index, Iterable<Row.Entry> {this.entryOrder = new Row.EntryComparator(rowdef.objectOrder);init();}-+public long mem() {long m = 0;- for (Index i: tables.values()) m += i.mem();+ for (final Index i: this.tables.values()) m += i.mem();return m;}-+public final byte[] smallestKey() {- HandleSet keysort = new HandleSet(this.rowdef.primaryKeyLength, this.rowdef.objectOrder, this.tables.size());- for (Index oi: this.tables.values()) try {+ final HandleSet keysort = new HandleSet(this.rowdef.primaryKeyLength, this.rowdef.objectOrder, this.tables.size());+ for (final Index oi: this.tables.values()) try {keysort.put(oi.smallestKey());- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {Log.logException(e);}return keysort.smallestKey();}-+public final byte[] largestKey() {- HandleSet keysort = new HandleSet(this.rowdef.primaryKeyLength, this.rowdef.objectOrder, this.tables.size());- for (Index oi: this.tables.values()) try {+ final HandleSet keysort = new HandleSet(this.rowdef.primaryKeyLength, this.rowdef.objectOrder, this.tables.size());+ for (final Index oi: this.tables.values()) try {keysort.put(oi.largestKey());- } catch (RowSpaceExceededException e) {+ } catch (final RowSpaceExceededException e) {Log.logException(e);}return keysort.largestKey();}private String newFilename() {- return prefix + "." + GenericFormatter.SHORT_MILSEC_FORMATTER.format() + ".table";+ return this.prefix + "." + GenericFormatter.SHORT_MILSEC_FORMATTER.format() + ".table";}-+private void init() throws RowSpaceExceededException {- current = null;+ this.current = null;// initialized tables mapthis.tables = new HashMap<String, Index>();- if (!(path.exists())) path.mkdirs();- String[] tablefile = path.list();-+ if (!(this.path.exists())) this.path.mkdirs();+ String[] tablefile = this.path.list();+// zero pass: migrate old table namesFile f;- Random r = new Random(System.currentTimeMillis());- for (int i = 0; i < tablefile.length; i++) {- if ((tablefile[i].startsWith(prefix)) &&- (tablefile[i].charAt(prefix.length()) == '.') &&- (tablefile[i].length() == prefix.length() + 7)) {- f = new File(path, tablefile[i]);- String newname = tablefile[i] + "0100000" + (Long.toString(r.nextLong())+"00000").substring(1,5) + ".table";- f.renameTo(new File(path, newname));+ final Random r = new Random(System.currentTimeMillis());+ for (final String element : tablefile) {+ if ((element.startsWith(this.prefix)) &&+ (element.charAt(this.prefix.length()) == '.') &&+ (element.length() == this.prefix.length() + 7)) {+ f = new File(this.path, element);+ final String newname = element + "0100000" + (Long.toString(r.nextLong())+"00000").substring(1,5) + ".table";+ f.renameTo(new File(this.path, newname));}}// read new list again- tablefile = path.list();-+ tablefile = this.path.list();+// first pass: find tablesfinal HashMap<String, Long> t = new HashMap<String, Long>();long ram, time, maxtime = 0;Date d;- for (int i = 0; i < tablefile.length; i++) {- if ((tablefile[i].startsWith(prefix)) &&- (tablefile[i].charAt(prefix.length()) == '.') &&- (tablefile[i].length() == prefix.length() + 24)) {- f = new File(path, tablefile[i]);+ for (final String element : tablefile) {+ if ((element.startsWith(this.prefix)) &&+ (element.charAt(this.prefix.length()) == '.') &&+ (element.length() == this.prefix.length() + 24)) {+ f = new File(this.path, element);try {- d = GenericFormatter.SHORT_MILSEC_FORMATTER.parse(tablefile[i].substring(prefix.length() + 1, prefix.length() + 18));- } catch (ParseException e) {+ d = GenericFormatter.SHORT_MILSEC_FORMATTER.parse(element.substring(this.prefix.length() + 1, this.prefix.length() + 18));+ } catch (final ParseException e) {Log.logSevere("SplitTable", "", e);continue;}time = d.getTime();if (time > maxtime) {- current = tablefile[i];+ this.current = element;assert this.current != null;maxtime = time;}-- t.put(tablefile[i], Table.staticRAMIndexNeed(f, rowdef));++ t.put(element, Table.staticRAMIndexNeed(f, this.rowdef));}}-+// second pass: open tablesIterator<Map.Entry<String, Long>> i;Map.Entry<String, Long> entry;@@ -209,50 +209,50 @@ public class SplitTable implements Index, Iterable<Row.Entry> {maxram = ram;}}-+// open next biggest tablet.remove(maxf);- f = new File(path, maxf);+ f = new File(this.path, maxf);Log.logInfo("kelondroSplitTable", "opening partial eco table " + f);try {- table = new Table(f, rowdef, EcoFSBufferSize, 0, this.useTailCache, this.exceed134217727);- } catch (RowSpaceExceededException e) {- table = new Table(f, rowdef, 0, 0, false, this.exceed134217727);+ table = new Table(f, this.rowdef, EcoFSBufferSize, 0, this.useTailCache, this.exceed134217727);+ } catch (final RowSpaceExceededException e) {+ table = new Table(f, this.rowdef, 0, 0, false, this.exceed134217727);}- tables.put(maxf, table);+ this.tables.put(maxf, table);}assert this.current == null || this.tables.get(this.current) != null : "this.current = " + this.current;-+// init the thread pool for the keeperOf executor servicethis.executor = new ThreadPoolExecutor(- Math.max(tables.size(), Runtime.getRuntime().availableProcessors()) + 1,- Math.max(tables.size(), Runtime.getRuntime().availableProcessors()) + 1, 10,- TimeUnit.SECONDS,- new LinkedBlockingQueue<Runnable>(),- new NamePrefixThreadFactory(prefix));+ Math.max(this.tables.size(), Runtime.getRuntime().availableProcessors()) + 1,+ Math.max(this.tables.size(), Runtime.getRuntime().availableProcessors()) + 1, 10,+ TimeUnit.SECONDS,+ new LinkedBlockingQueue<Runnable>(),+ new NamePrefixThreadFactory(this.prefix));}-+public void clear() throws IOException {- this.close();- final String[] l = path.list();- for (int i = 0; i < l.length; i++) {- if (l[i].startsWith(prefix)) {- final File f = new File(path, l[i]);- if (f.isDirectory()) delete(path, l[i]); else FileUtils.deletedelete(f);+ close();+ final String[] l = this.path.list();+ for (final String element : l) {+ if (element.startsWith(this.prefix)) {+ final File f = new File(this.path, element);+ if (f.isDirectory()) delete(this.path, element); else FileUtils.deletedelete(f);}}try {init();- } catch (RowSpaceExceededException e) {- useTailCache = false;+ } catch (final RowSpaceExceededException e) {+ this.useTailCache = false;try {init();- } catch (RowSpaceExceededException e1) {+ } catch (final RowSpaceExceededException e1) {throw new IOException(e1.getMessage());}}}-+public static void delete(final File path, final String tablename) {final File tabledir = new File(path, tablename);if (!(tabledir.exists())) return;@@ -262,89 +262,89 @@ public class SplitTable implements Index, Iterable<Row.Entry> {}final String[] files = tabledir.list();- for (int i = 0; i < files.length; i++) {- FileUtils.deletedelete(new File(tabledir, files[i]));+ for (final String file : files) {+ FileUtils.deletedelete(new File(tabledir, file));}FileUtils.deletedelete(tabledir);}-+public String filename() {- return new File(path, prefix).toString();+ return new File(this.path, this.prefix).toString();}-+public int size() {- final Iterator<Index> i = tables.values().iterator();+ final Iterator<Index> i = this.tables.values().iterator();int s = 0;while (i.hasNext()) s += i.next().size();return s;}-+public boolean isEmpty() {- final Iterator<Index> i = tables.values().iterator();+ final Iterator<Index> i = this.tables.values().iterator();while (i.hasNext()) if (!i.next().isEmpty()) return false;return true;}-+public int writeBufferSize() {int s = 0;- for (final Index index : tables.values()) {+ for (final Index index : this.tables.values()) {if (index instanceof Cache) s += ((Cache) index).writeBufferSize();}return s;}-+public Row row() {return this.rowdef;}-+public boolean has(final byte[] key) {return keeperOf(key) != null;}-- public Row.Entry get(final byte[] key) throws IOException {++ public Row.Entry get(final byte[] key, final boolean forcecopy) throws IOException {final Index keeper = keeperOf(key);if (keeper == null) return null;- return keeper.get(key);+ return keeper.get(key, forcecopy);}- public Map<byte[], Row.Entry> get(Collection<byte[]> keys) throws IOException, InterruptedException {- final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(this.row().objectOrder);+ public Map<byte[], Row.Entry> get(final Collection<byte[]> keys, final boolean forcecopy) throws IOException, InterruptedException {+ final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(row().objectOrder);Row.Entry entry;- for (byte[] key: keys) {- entry = get(key);+ for (final byte[] key: keys) {+ entry = get(key, forcecopy);if (entry != null) map.put(key, entry);}return map;}-+private Index newTable() {this.current = newFilename();- final File f = new File(path, this.current);+ final File f = new File(this.path, this.current);Table table = null;try {- table = new Table(f, rowdef, EcoFSBufferSize, 0, this.useTailCache, this.exceed134217727);- } catch (RowSpaceExceededException e) {+ table = new Table(f, this.rowdef, EcoFSBufferSize, 0, this.useTailCache, this.exceed134217727);+ } catch (final RowSpaceExceededException e) {try {- table = new Table(f, rowdef, 0, 0, false, this.exceed134217727);- } catch (RowSpaceExceededException e1) {+ table = new Table(f, this.rowdef, 0, 0, false, this.exceed134217727);+ } catch (final RowSpaceExceededException e1) {Log.logException(e1);}}- tables.put(this.current, table);+ this.tables.put(this.current, table);assert this.current == null || this.tables.get(this.current) != null : "this.current = " + this.current;return table;}-- private Index checkTable(Index table) {++ private Index checkTable(final Index table) {// check size and age of given table; in case it is too large or too old// create a new tableassert table != null;- String name = new File(table.filename()).getName();+ final String name = new File(table.filename()).getName();long d;try {- d = GenericFormatter.SHORT_MILSEC_FORMATTER.parse(name.substring(prefix.length() + 1, prefix.length() + 18)).getTime();- } catch (ParseException e) {+ d = GenericFormatter.SHORT_MILSEC_FORMATTER.parse(name.substring(this.prefix.length() + 1, this.prefix.length() + 18)).getTime();+ } catch (final ParseException e) {Log.logSevere("SplitTable", "", e);d = 0;}@@ -353,7 +353,7 @@ public class SplitTable implements Index, Iterable<Row.Entry> {}return table;}-+public Row.Entry replace(final Row.Entry row) throws IOException, RowSpaceExceededException {assert row.objectsize() <= this.rowdef.objectsize;Index keeper = keeperOf(row.getPrimaryKeyBytes());@@ -365,72 +365,72 @@ public class SplitTable implements Index, Iterable<Row.Entry> {keeper.put(row);return null;}-+/*** Adds the row to the index. The row is identified by the primary key of the row.* @param row a index row- * @return true if this set did _not_ already contain the given row.+ * @return true if this set did _not_ already contain the given row.* @throws IOException* @throws RowSpaceExceededException*/public boolean put(final Row.Entry row) throws IOException, RowSpaceExceededException {assert row.objectsize() <= this.rowdef.objectsize;- byte[] key = row.getPrimaryKeyBytes();- if (tables == null) return true;+ final byte[] key = row.getPrimaryKeyBytes();+ if (this.tables == null) return true;synchronized (this.tables) {Index keeper = keeperOf(key);if (keeper != null) return keeper.put(row);assert this.current == null || this.tables.get(this.current) != null : "this.current = " + this.current;keeper = (this.current == null) ? newTable() : checkTable(this.tables.get(this.current));- boolean b = keeper.put(row);+ final boolean b = keeper.put(row);assert b;return b;}}-+private Index keeperOf(final byte[] key) {if (key == null) return null;- if (tables == null) return null;- for (Index oi: tables.values()) {+ if (this.tables == null) return null;+ for (final Index oi: this.tables.values()) {if (oi.has(key)) return oi;}return null;}-+public void addUnique(final Row.Entry row) throws IOException, RowSpaceExceededException {assert row.objectsize() <= this.rowdef.objectsize;- Index table = (this.current == null) ? null : tables.get(this.current);+ Index table = (this.current == null) ? null : this.tables.get(this.current);synchronized (this.tables) {assert this.current == null || this.tables.get(this.current) != null : "this.current = " + this.current;if (table == null) table = newTable(); else table = checkTable(table);}table.addUnique(row);}-+public List<RowCollection> removeDoubles() throws IOException, RowSpaceExceededException {- final Iterator<Index> i = tables.values().iterator();+ final Iterator<Index> i = this.tables.values().iterator();final List<RowCollection> report = new ArrayList<RowCollection>();while (i.hasNext()) {report.addAll(i.next().removeDoubles());}return report;}-+public boolean delete(final byte[] key) throws IOException {final Index table = keeperOf(key);if (table == null) return false;return table.delete(key);}-+public Row.Entry remove(final byte[] key) throws IOException {final Index table = keeperOf(key);if (table == null) return null;return table.remove(key);}-+public Row.Entry removeOne() throws IOException {- final Iterator<Index> i = tables.values().iterator();+ final Iterator<Index> i = this.tables.values().iterator();Index table, maxtable = null;int maxcount = -1;while (i.hasNext()) {@@ -445,9 +445,9 @@ public class SplitTable implements Index, Iterable<Row.Entry> {}return maxtable.removeOne();}-- public List<Row.Entry> top(int count) throws IOException {- final Iterator<Index> i = tables.values().iterator();++ public List<Row.Entry> top(final int count) throws IOException {+ final Iterator<Index> i = this.tables.values().iterator();Index table, maxtable = null;int maxcount = -1;while (i.hasNext()) {@@ -462,55 +462,55 @@ public class SplitTable implements Index, Iterable<Row.Entry> {}return maxtable.top(count);}-+public CloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {- final List<CloneableIterator<byte[]>> c = new ArrayList<CloneableIterator<byte[]>>(tables.size());- final Iterator<Index> i = tables.values().iterator();+ final List<CloneableIterator<byte[]>> c = new ArrayList<CloneableIterator<byte[]>>(this.tables.size());+ final Iterator<Index> i = this.tables.values().iterator();CloneableIterator<byte[]> k;while (i.hasNext()) {k = i.next().keys(up, firstKey);if (k != null) c.add(k);}- return MergeIterator.cascade(c, rowdef.objectOrder, MergeIterator.simpleMerge, up);+ return MergeIterator.cascade(c, this.rowdef.objectOrder, MergeIterator.simpleMerge, up);}-+public CloneableIterator<Row.Entry> rows(final boolean up, final byte[] firstKey) throws IOException {- final List<CloneableIterator<Row.Entry>> c = new ArrayList<CloneableIterator<Row.Entry>>(tables.size());- final Iterator<Index> i = tables.values().iterator();+ final List<CloneableIterator<Row.Entry>> c = new ArrayList<CloneableIterator<Row.Entry>>(this.tables.size());+ final Iterator<Index> i = this.tables.values().iterator();while (i.hasNext()) {c.add(i.next().rows(up, firstKey));}- return MergeIterator.cascade(c, entryOrder, MergeIterator.simpleMerge, up);+ return MergeIterator.cascade(c, this.entryOrder, MergeIterator.simpleMerge, up);}-+public Iterator<Entry> iterator() {try {return rows();- } catch (IOException e) {+ } catch (final IOException e) {return null;}}-+@SuppressWarnings("unchecked")public synchronized CloneableIterator<Row.Entry> rows() throws IOException {- final CloneableIterator<Row.Entry>[] c = new CloneableIterator[tables.size()];- final Iterator<Index> i = tables.values().iterator();+ final CloneableIterator<Row.Entry>[] c = new CloneableIterator[this.tables.size()];+ final Iterator<Index> i = this.tables.values().iterator();int d = 0;while (i.hasNext()) {c[d++] = i.next().rows();}return StackIterator.stack(c);}-+public synchronized void close() {- if (tables == null) return;+ if (this.tables == null) return;this.executor.shutdown();try {this.executor.awaitTermination(3, TimeUnit.SECONDS);} catch (final InterruptedException e) {}this.executor = null;- final Iterator<Index> i = tables.values().iterator();+ final Iterator<Index> i = this.tables.values().iterator();while (i.hasNext()) {i.next().close();}@@ -518,7 +518,7 @@ public class SplitTable implements Index, Iterable<Row.Entry> {}public void deleteOnExit() {- for (Index i: this.tables.values()) i.deleteOnExit();+ for (final Index i: this.tables.values()) i.deleteOnExit();}-+}diff --git a/source/net/yacy/kelondro/table/Table.java b/source/net/yacy/kelondro/table/Table.javaindex abc7474ce..eab9c1054 100644--- a/source/net/yacy/kelondro/table/Table.java+++ b/source/net/yacy/kelondro/table/Table.java@@ -446,7 +446,7 @@ public class Table implements Index, Iterable<Row.Entry> {return this.file.filename().toString();}- public Entry get(final byte[] key) throws IOException {+ public Entry get(final byte[] key, final boolean _forcecopy) throws IOException {if (this.file == null || this.index == null) return null;Entry e = get0(key);if (e != null && this.rowdef.objectOrder.equal(key, e.getPrimaryKeyBytes())) return e;@@ -479,11 +479,11 @@ public class Table implements Index, Iterable<Row.Entry> {return this.rowdef.newEntry(b);}- public Map<byte[], Row.Entry> get(final Collection<byte[]> keys) throws IOException, InterruptedException {+ public Map<byte[], Row.Entry> get(final Collection<byte[]> keys, final boolean forcecopy) throws IOException, InterruptedException {final Map<byte[], Row.Entry> map = new TreeMap<byte[], Row.Entry>(row().objectOrder);Row.Entry entry;for (final byte[] key: keys) {- entry = get(key);+ entry = get(key, forcecopy);if (entry != null) map.put(key, entry);}return map;@@ -859,7 +859,7 @@ public class Table implements Index, Iterable<Row.Entry> {if (this.key == null) return null;this.idx = (int) entry.getColLong(1);try {- return get(this.key);+ return get(this.key, false);} catch (final IOException e) {return null;}@@ -1031,7 +1031,7 @@ public class Table implements Index, Iterable<Row.Entry> {while (i.hasNext()) {System.out.print("row " + i + ": ");key = i.next();- row = get(key);+ row = get(key, false);System.out.println(row.toString());}System.out.println("EndOfTable");