Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance
Java decentralizedintranet-searchintranet-search-enginep2pp2p-networkprivacyprivacy-protectionsearch-enginesearchenginewebweb-search-enginewebsearchwebseearch-engine
svn attributes added
borg-0300c450e3746bda
diff --git a/source/de/anomic/kelondro/text/Document.java b/source/de/anomic/kelondro/text/Document.javaindex c0265875d..30de51799 100644--- a/source/de/anomic/kelondro/text/Document.java+++ b/source/de/anomic/kelondro/text/Document.java@@ -1,84 +1,84 @@-// indexDocumentMetadata.java-// (C) 2008 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 19.08.2008 on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $-// $LastChangedRevision: 1986 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import java.util.Date;--import de.anomic.crawler.CrawlProfile;-import de.anomic.yacy.yacyURL;--public interface Document {-- /**- * @return an anchor name; can be either the text inside the anchor tag or the- * page description after loading of the page- */- public String name();-- public yacyURL url();-- public String urlHash();-- public Date lastModified();-- public String language();-- public CrawlProfile.entry profile();-- public String initiator();-- public boolean proxy();-- public long size();-- public int depth();-- public yacyURL referrerURL();-- public void setCacheArray(final byte[] data);-- public byte[] cacheArray();-- public String getMimeType();- public Date ifModifiedSince();- public boolean requestProhibitsIndexing();- public boolean requestWithCookie();-- /**- * @return NULL if the answer is TRUE, in case of FALSE, the reason as- * String is returned- */- public String shallStoreCacheForProxy();-- /**- * decide upon header information if a specific file should be taken from- * the cache or not- *- * @return whether the file should be taken from the cache- */- public boolean shallUseCacheForProxy();-}+// indexDocumentMetadata.java+// (C) 2008 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 19.08.2008 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import java.util.Date;++import de.anomic.crawler.CrawlProfile;+import de.anomic.yacy.yacyURL;++public interface Document {++ /**+ * @return an anchor name; can be either the text inside the anchor tag or the+ * page description after loading of the page+ */+ public String name();++ public yacyURL url();++ public String urlHash();++ public Date lastModified();++ public String language();++ public CrawlProfile.entry profile();++ public String initiator();++ public boolean proxy();++ public long size();++ public int depth();++ public yacyURL referrerURL();++ public void setCacheArray(final byte[] data);++ public byte[] cacheArray();++ public String getMimeType();+ public Date ifModifiedSince();+ public boolean requestProhibitsIndexing();+ public boolean requestWithCookie();++ /**+ * @return NULL if the answer is TRUE, in case of FALSE, the reason as+ * String is returned+ */+ public String shallStoreCacheForProxy();++ /**+ * decide upon header information if a specific file should be taken from+ * the cache or not+ *+ * @return whether the file should be taken from the cache+ */+ public boolean shallUseCacheForProxy();+}diff --git a/source/de/anomic/kelondro/text/Index.java b/source/de/anomic/kelondro/text/Index.javaindex fca42eb25..01ee02a52 100644--- a/source/de/anomic/kelondro/text/Index.java+++ b/source/de/anomic/kelondro/text/Index.java@@ -1,166 +1,166 @@-// ReverseIndex.java-// ------------------------------// (C) 2005 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 6.5.2005 on http://www.anomic.de-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $-// $LastChangedRevision: 1986 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA---package de.anomic.kelondro.text;--import java.io.IOException;-import java.util.Set;-import java.util.TreeSet;--import de.anomic.kelondro.order.ByteOrder;-import de.anomic.kelondro.order.CloneableIterator;--public interface Index {-- /**- * add references to the reverse index- * if no references to the word are stored, the new Entries are added,- * if there are already references to the word that is denoted with the- * reference to be stored, then the old and the new references are merged- * @param newEntries the References to be merged with existing references- * @throws IOException- */- public void add(ReferenceContainer newEntries) throws IOException;-- /**- * add a single reference to the reverse index- * if no references to the word are stored, the a new entry is added,- * if there are already references to the word hash stored,- * then the old and the new references are merged- * @param wordHash- * @param entry- * @throws IOException- */- public void add(final String wordHash, final ReferenceRow entry) throws IOException;-- /**- * check if there are references stored to the given word hash- * @param wordHash- * @return true if references exist, false if not- */- public boolean has(String wordHash); // should only be used if in case that true is returned the getContainer is NOT called-- /**- * count the number of references for the given word- * do not use this method to check the existence of a reference by comparing- * the result with zero, use hasReferences instead.- * @param wordHash- * @return the number of references to the given word- */- public int count(final String wordHash);-- /**- * get the references to a given word.- * if referenceselection is not null, then all url references which are not- * in referenceselection are removed from the container- * @param wordHash- * @param referenceselection- * @return the references- * @throws IOException- */- public ReferenceContainer get(String wordHash, Set<String> referenceselection) throws IOException;-- /**- * delete all references for a word- * @param wordHash- * @return the deleted references- * @throws IOException- */- public ReferenceContainer delete(String wordHash) throws IOException;-- /**- * remove a specific reference entry- * @param wordHash- * @param referenceHash the key for the reference entry to be removed- * @return- * @throws IOException- */- public boolean remove(String wordHash, String referenceHash) throws IOException;-- /**- * remove a set of reference entries for a given word- * @param wordHash the key for the references- * @param referenceHash the reference entry keys- * @return- * @throws IOException- */- public int remove(String wordHash, Set<String> referenceHashes) throws IOException;-- public int remove(final Set<String> wordHashes, final String urlHash) throws IOException;-- public void remove(final Set<String> wordHashes, final Set<String> urlHashes) throws IOException;-- /**- * iterate all references from the beginning of a specific word hash- * @param startWordHash- * @param rot if true, then rotate at the end to the beginning- * @param ram- * @return- * @throws IOException- */- public CloneableIterator<ReferenceContainer> references(- String startHash,- boolean rot- ) throws IOException;--- public TreeSet<ReferenceContainer> references(- String startHash,- boolean rot,- int count- ) throws IOException;-- /**- * delete all references entries- * @throws IOException- */- public void clear() throws IOException;-- /**- * close the reverse index- */- public void close();-- /**- * the number of all references- * @return the nnumber of all references- */- public int size();-- /**- * calculate needed memory- * @return the memory needed to operate the object- */- public int minMem();-- /**- * return the order that is used for the storage of the word hashes- * @return- */- public ByteOrder ordering();-}+// ReverseIndex.java+// -----------------------------+// (C) 2005 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 6.5.2005 on http://www.anomic.de+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+++package de.anomic.kelondro.text;++import java.io.IOException;+import java.util.Set;+import java.util.TreeSet;++import de.anomic.kelondro.order.ByteOrder;+import de.anomic.kelondro.order.CloneableIterator;++public interface Index {++ /**+ * add references to the reverse index+ * if no references to the word are stored, the new Entries are added,+ * if there are already references to the word that is denoted with the+ * reference to be stored, then the old and the new references are merged+ * @param newEntries the References to be merged with existing references+ * @throws IOException+ */+ public void add(ReferenceContainer newEntries) throws IOException;++ /**+ * add a single reference to the reverse index+ * if no references to the word are stored, the a new entry is added,+ * if there are already references to the word hash stored,+ * then the old and the new references are merged+ * @param wordHash+ * @param entry+ * @throws IOException+ */+ public void add(final String wordHash, final ReferenceRow entry) throws IOException;++ /**+ * check if there are references stored to the given word hash+ * @param wordHash+ * @return true if references exist, false if not+ */+ public boolean has(String wordHash); // should only be used if in case that true is returned the getContainer is NOT called++ /**+ * count the number of references for the given word+ * do not use this method to check the existence of a reference by comparing+ * the result with zero, use hasReferences instead.+ * @param wordHash+ * @return the number of references to the given word+ */+ public int count(final String wordHash);++ /**+ * get the references to a given word.+ * if referenceselection is not null, then all url references which are not+ * in referenceselection are removed from the container+ * @param wordHash+ * @param referenceselection+ * @return the references+ * @throws IOException+ */+ public ReferenceContainer get(String wordHash, Set<String> referenceselection) throws IOException;++ /**+ * delete all references for a word+ * @param wordHash+ * @return the deleted references+ * @throws IOException+ */+ public ReferenceContainer delete(String wordHash) throws IOException;++ /**+ * remove a specific reference entry+ * @param wordHash+ * @param referenceHash the key for the reference entry to be removed+ * @return+ * @throws IOException+ */+ public boolean remove(String wordHash, String referenceHash) throws IOException;++ /**+ * remove a set of reference entries for a given word+ * @param wordHash the key for the references+ * @param referenceHash the reference entry keys+ * @return+ * @throws IOException+ */+ public int remove(String wordHash, Set<String> referenceHashes) throws IOException;++ public int remove(final Set<String> wordHashes, final String urlHash) throws IOException;++ public void remove(final Set<String> wordHashes, final Set<String> urlHashes) throws IOException;++ /**+ * iterate all references from the beginning of a specific word hash+ * @param startWordHash+ * @param rot if true, then rotate at the end to the beginning+ * @param ram+ * @return+ * @throws IOException+ */+ public CloneableIterator<ReferenceContainer> references(+ String startHash,+ boolean rot+ ) throws IOException;+++ public TreeSet<ReferenceContainer> references(+ String startHash,+ boolean rot,+ int count+ ) throws IOException;++ /**+ * delete all references entries+ * @throws IOException+ */+ public void clear() throws IOException;++ /**+ * close the reverse index+ */+ public void close();++ /**+ * the number of all references+ * @return the nnumber of all references+ */+ public int size();++ /**+ * calculate needed memory+ * @return the memory needed to operate the object+ */+ public int minMem();++ /**+ * return the order that is used for the storage of the word hashes+ * @return+ */+ public ByteOrder ordering();+}diff --git a/source/de/anomic/kelondro/text/IndexBuffer.java b/source/de/anomic/kelondro/text/IndexBuffer.javaindex 0bae39cde..23492c82a 100644--- a/source/de/anomic/kelondro/text/IndexBuffer.java+++ b/source/de/anomic/kelondro/text/IndexBuffer.java@@ -4,9 +4,9 @@//// This is a part of YaCy, a peer-to-peer based web search engine//-// $LastChangedDate: 2009-01-31 00:33:47 +0100 (Sa, 31 Jan 2009) $-// $LastChangedRevision: 5544 $-// $LastChangedBy: orbiter $+// $LastChangedDate$+// $LastChangedRevision$+// $LastChangedBy$//// LICENSE//diff --git a/source/de/anomic/kelondro/text/IndexCell.java b/source/de/anomic/kelondro/text/IndexCell.javaindex e5b82c77d..bcc7b649b 100644--- a/source/de/anomic/kelondro/text/IndexCell.java+++ b/source/de/anomic/kelondro/text/IndexCell.java@@ -1,316 +1,316 @@-// ReverseIndexCell.java-// (C) 2009 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 1.3.2009 on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2009-01-02 12:38:20 +0100 (Fr, 02 Jan 2009) $-// $LastChangedRevision: 5432 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import java.io.File;-import java.io.IOException;-import java.util.HashSet;-import java.util.Set;--import de.anomic.kelondro.index.Row;-import de.anomic.kelondro.order.ByteOrder;-import de.anomic.kelondro.order.CloneableIterator;-import de.anomic.kelondro.order.MergeIterator;-import de.anomic.kelondro.order.Order;-import de.anomic.server.serverProfiling;--/*- * an index cell is a part of the horizontal index in the new segment-oriented index- * data structure of YaCy. If there is no filter in front of a cell, it might also be- * the organization for a complete segment index. Each cell consists of a number of BLOB files, that- * must be merged to represent a single index. In fact these index files are only merged on demand- * if there are too many of them. An index merge can be done with a stream read and stream write operation.- * in normal operation, there are only a number of read-only BLOB files and a single RAM cache that is- * kept in the RAM as long as a given limit of entries is reached. Then the cache is flushed and becomes- * another BLOB file in the index array.- */--public final class IndexCell extends AbstractBufferedIndex implements BufferedIndex {-- // class variables- private ReferenceContainerArray array;- private ReferenceContainerCache ram;- private int maxRamEntries, maxArrayFiles;-- public IndexCell(- final File cellPath,- final ByteOrder wordOrder,- final Row payloadrow,- final int maxRamEntries,- final int maxArrayFiles,- ReferenceContainerMerger merger- ) throws IOException {- this.array = new ReferenceContainerArray(cellPath, wordOrder, payloadrow, merger);- this.ram = new ReferenceContainerCache(payloadrow, wordOrder);- this.ram.initWriteMode();- this.maxRamEntries = maxRamEntries;- this.maxArrayFiles = maxArrayFiles;- }--- /*- * methods to implement Index- */-- /**- * add entries to the cell: this adds the new entries always to the RAM part, never to BLOBs- * @throws IOException- * @throws IOException- */- public synchronized void add(ReferenceContainer newEntries) throws IOException {- this.ram.add(newEntries);- serverProfiling.update("wordcache", Long.valueOf(this.ram.size()), true);- if (this.ram.size() > this.maxRamEntries) cacheDump();- }-- public synchronized void add(String hash, ReferenceRow entry) throws IOException {- this.ram.add(hash, entry);- serverProfiling.update("wordcache", Long.valueOf(this.ram.size()), true);- if (this.ram.size() > this.maxRamEntries) cacheDump();- }-- /**- * checks if there is any container for this wordHash, either in RAM or any BLOB- */- public boolean has(String wordHash) {- if (this.ram.has(wordHash)) return true;- return this.array.has(wordHash);- }-- public int count(String wordHash) {- ReferenceContainer c0 = this.ram.get(wordHash, null);- ReferenceContainer c1;- try {- c1 = this.array.get(wordHash);- } catch (IOException e) {- c1 = null;- }- if (c1 == null) {- if (c0 == null) return 0;- return c0.size();- }- if (c0 == null) return c1.size();- return c1.size() + c0.size();- }-- /**- * all containers in the BLOBs and the RAM are merged and returned- * @throws IOException- */- public ReferenceContainer get(String wordHash, Set<String> urlselection) throws IOException {- ReferenceContainer c0 = this.ram.get(wordHash, null);- ReferenceContainer c1 = this.array.get(wordHash);- if (c1 == null) {- if (c0 == null) return null;- return c0;- }- if (c0 == null) return c1;- return c1.merge(c0);- }-- /**- * deleting a container affects the containers in RAM and all the BLOB files- * the deleted containers are merged and returned as result of the method- * @throws IOException- */- public ReferenceContainer delete(String wordHash) throws IOException {- ReferenceContainer c0 = this.ram.delete(wordHash);- ReferenceContainer c1 = this.array.get(wordHash);- if (c1 == null) {- if (c0 == null) return null;- return c0;- }- this.array.delete(wordHash);- if (c0 == null) return c1;- return c1.merge(c0);- }-- /**- * remove url references from a selected word hash. this deletes also in the BLOB- * files, which means that there exists new gap entries after the deletion- * The gaps are never merged in place, but can be eliminated when BLOBs are merged into- * new BLOBs. This returns the sum of all url references that have been removed- * @throws IOException- */- public int remove(String wordHash, Set<String> urlHashes) throws IOException {- int reduced = this.array.replace(wordHash, new RemoveRewriter(urlHashes));- return reduced / this.array.rowdef().objectsize;- }-- public boolean remove(String wordHash, String urlHash) throws IOException {- int reduced = this.array.replace(wordHash, new RemoveRewriter(urlHash));- return reduced > 0;- }-- private static class RemoveRewriter implements ReferenceContainerArray.ContainerRewriter {-- Set<String> urlHashes;-- public RemoveRewriter(Set<String> urlHashes) {- this.urlHashes = urlHashes;- }-- public RemoveRewriter(String urlHash) {- this.urlHashes = new HashSet<String>();- this.urlHashes.add(urlHash);- }-- public ReferenceContainer rewrite(ReferenceContainer container) {- container.removeEntries(urlHashes);- return container;- }-- }-- public CloneableIterator<ReferenceContainer> references(String startWordHash, boolean rot) {- final Order<ReferenceContainer> containerOrder = new ReferenceContainerOrder(this.ram.rowdef().getOrdering().clone());- containerOrder.rotate(new ReferenceContainer(startWordHash, this.ram.rowdef(), 0));- return new MergeIterator<ReferenceContainer>(- this.ram.references(startWordHash, rot),- new MergeIterator<ReferenceContainer>(- this.ram.references(startWordHash, false),- this.array.wordContainerIterator(startWordHash, false, false),- containerOrder,- ReferenceContainer.containerMergeMethod,- true),- containerOrder,- ReferenceContainer.containerMergeMethod,- true);- }-- public CloneableIterator<ReferenceContainer> references(String startWordHash, boolean rot, boolean ram) {- final Order<ReferenceContainer> containerOrder = new ReferenceContainerOrder(this.ram.rowdef().getOrdering().clone());- containerOrder.rotate(new ReferenceContainer(startWordHash, this.ram.rowdef(), 0));- if (ram) {- return this.ram.references(startWordHash, rot);- }- return new MergeIterator<ReferenceContainer>(- this.ram.references(startWordHash, false),- this.array.wordContainerIterator(startWordHash, false, false),- containerOrder,- ReferenceContainer.containerMergeMethod,- true);- }-- /**- * clear the RAM and BLOB part, deletes everything in the cell- * @throws IOException- */- public synchronized void clear() throws IOException {- this.ram.clear();- this.array.clear();- }-- /**- * when a cell is closed, the current RAM is dumped to a file which will be opened as- * BLOB file the next time a cell is opened. A name for the dump is automatically generated- * and is composed of the current date and the cell salt- */- public synchronized void close() {- // dump the ram- try {- this.ram.dump(this.array.newContainerBLOBFile(), true);- } catch (IOException e) {- e.printStackTrace();- }- // close all- this.ram.close();- this.array.close();- }-- public int size() {- return this.ram.size() + this.array.size();- }-- public int minMem() {- return 10 * 1024 * 1024;- }-- public ByteOrder ordering() {- return this.array.ordering();- }--- /*- * cache control methods- */-- private synchronized void cacheDump() throws IOException {- // dump the ram- File dumpFile = this.array.newContainerBLOBFile();- this.ram.dump(dumpFile, true);- // get a fresh ram cache- this.ram = new ReferenceContainerCache(this.array.rowdef(), this.array.ordering());- this.ram.initWriteMode();- // add the dumped indexContainerBLOB to the array- this.array.mountBLOBContainer(dumpFile);- int c = 0;- while (this.array.entries() > this.maxArrayFiles && c++ < 3) {- if (!this.array.merge(true)) break;- }- }-- public void cleanupBuffer(int time) {- // do nothing- }--- public int getBackendSize() {- return this.array.size();- }--- public long getBufferMaxAge() {- return System.currentTimeMillis();- }--- public int getBufferMaxReferences() {- return this.ram.maxReferences();- }--- public long getBufferMinAge() {- return System.currentTimeMillis();- }--- public int getBufferSize() {- return this.ram.size();- }--- public long getBufferSizeBytes() {- return 10000 * this.ram.size(); // guessed; we don't know that exactly because there is no statistics here (expensive, not necessary)- }--- public void setBufferMaxWordCount(int maxWords) {- this.maxRamEntries = maxWords;- }--}+// ReverseIndexCell.java+// (C) 2009 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 1.3.2009 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import java.io.File;+import java.io.IOException;+import java.util.HashSet;+import java.util.Set;++import de.anomic.kelondro.index.Row;+import de.anomic.kelondro.order.ByteOrder;+import de.anomic.kelondro.order.CloneableIterator;+import de.anomic.kelondro.order.MergeIterator;+import de.anomic.kelondro.order.Order;+import de.anomic.server.serverProfiling;++/*+ * an index cell is a part of the horizontal index in the new segment-oriented index+ * data structure of YaCy. If there is no filter in front of a cell, it might also be+ * the organization for a complete segment index. Each cell consists of a number of BLOB files, that+ * must be merged to represent a single index. In fact these index files are only merged on demand+ * if there are too many of them. An index merge can be done with a stream read and stream write operation.+ * in normal operation, there are only a number of read-only BLOB files and a single RAM cache that is+ * kept in the RAM as long as a given limit of entries is reached. Then the cache is flushed and becomes+ * another BLOB file in the index array.+ */++public final class IndexCell extends AbstractBufferedIndex implements BufferedIndex {++ // class variables+ private ReferenceContainerArray array;+ private ReferenceContainerCache ram;+ private int maxRamEntries, maxArrayFiles;++ public IndexCell(+ final File cellPath,+ final ByteOrder wordOrder,+ final Row payloadrow,+ final int maxRamEntries,+ final int maxArrayFiles,+ ReferenceContainerMerger merger+ ) throws IOException {+ this.array = new ReferenceContainerArray(cellPath, wordOrder, payloadrow, merger);+ this.ram = new ReferenceContainerCache(payloadrow, wordOrder);+ this.ram.initWriteMode();+ this.maxRamEntries = maxRamEntries;+ this.maxArrayFiles = maxArrayFiles;+ }+++ /*+ * methods to implement Index+ */++ /**+ * add entries to the cell: this adds the new entries always to the RAM part, never to BLOBs+ * @throws IOException+ * @throws IOException+ */+ public synchronized void add(ReferenceContainer newEntries) throws IOException {+ this.ram.add(newEntries);+ serverProfiling.update("wordcache", Long.valueOf(this.ram.size()), true);+ if (this.ram.size() > this.maxRamEntries) cacheDump();+ }++ public synchronized void add(String hash, ReferenceRow entry) throws IOException {+ this.ram.add(hash, entry);+ serverProfiling.update("wordcache", Long.valueOf(this.ram.size()), true);+ if (this.ram.size() > this.maxRamEntries) cacheDump();+ }++ /**+ * checks if there is any container for this wordHash, either in RAM or any BLOB+ */+ public boolean has(String wordHash) {+ if (this.ram.has(wordHash)) return true;+ return this.array.has(wordHash);+ }++ public int count(String wordHash) {+ ReferenceContainer c0 = this.ram.get(wordHash, null);+ ReferenceContainer c1;+ try {+ c1 = this.array.get(wordHash);+ } catch (IOException e) {+ c1 = null;+ }+ if (c1 == null) {+ if (c0 == null) return 0;+ return c0.size();+ }+ if (c0 == null) return c1.size();+ return c1.size() + c0.size();+ }++ /**+ * all containers in the BLOBs and the RAM are merged and returned+ * @throws IOException+ */+ public ReferenceContainer get(String wordHash, Set<String> urlselection) throws IOException {+ ReferenceContainer c0 = this.ram.get(wordHash, null);+ ReferenceContainer c1 = this.array.get(wordHash);+ if (c1 == null) {+ if (c0 == null) return null;+ return c0;+ }+ if (c0 == null) return c1;+ return c1.merge(c0);+ }++ /**+ * deleting a container affects the containers in RAM and all the BLOB files+ * the deleted containers are merged and returned as result of the method+ * @throws IOException+ */+ public ReferenceContainer delete(String wordHash) throws IOException {+ ReferenceContainer c0 = this.ram.delete(wordHash);+ ReferenceContainer c1 = this.array.get(wordHash);+ if (c1 == null) {+ if (c0 == null) return null;+ return c0;+ }+ this.array.delete(wordHash);+ if (c0 == null) return c1;+ return c1.merge(c0);+ }++ /**+ * remove url references from a selected word hash. this deletes also in the BLOB+ * files, which means that there exists new gap entries after the deletion+ * The gaps are never merged in place, but can be eliminated when BLOBs are merged into+ * new BLOBs. This returns the sum of all url references that have been removed+ * @throws IOException+ */+ public int remove(String wordHash, Set<String> urlHashes) throws IOException {+ int reduced = this.array.replace(wordHash, new RemoveRewriter(urlHashes));+ return reduced / this.array.rowdef().objectsize;+ }++ public boolean remove(String wordHash, String urlHash) throws IOException {+ int reduced = this.array.replace(wordHash, new RemoveRewriter(urlHash));+ return reduced > 0;+ }++ private static class RemoveRewriter implements ReferenceContainerArray.ContainerRewriter {++ Set<String> urlHashes;++ public RemoveRewriter(Set<String> urlHashes) {+ this.urlHashes = urlHashes;+ }++ public RemoveRewriter(String urlHash) {+ this.urlHashes = new HashSet<String>();+ this.urlHashes.add(urlHash);+ }++ public ReferenceContainer rewrite(ReferenceContainer container) {+ container.removeEntries(urlHashes);+ return container;+ }++ }++ public CloneableIterator<ReferenceContainer> references(String startWordHash, boolean rot) {+ final Order<ReferenceContainer> containerOrder = new ReferenceContainerOrder(this.ram.rowdef().getOrdering().clone());+ containerOrder.rotate(new ReferenceContainer(startWordHash, this.ram.rowdef(), 0));+ return new MergeIterator<ReferenceContainer>(+ this.ram.references(startWordHash, rot),+ new MergeIterator<ReferenceContainer>(+ this.ram.references(startWordHash, false),+ this.array.wordContainerIterator(startWordHash, false, false),+ containerOrder,+ ReferenceContainer.containerMergeMethod,+ true),+ containerOrder,+ ReferenceContainer.containerMergeMethod,+ true);+ }++ public CloneableIterator<ReferenceContainer> references(String startWordHash, boolean rot, boolean ram) {+ final Order<ReferenceContainer> containerOrder = new ReferenceContainerOrder(this.ram.rowdef().getOrdering().clone());+ containerOrder.rotate(new ReferenceContainer(startWordHash, this.ram.rowdef(), 0));+ if (ram) {+ return this.ram.references(startWordHash, rot);+ }+ return new MergeIterator<ReferenceContainer>(+ this.ram.references(startWordHash, false),+ this.array.wordContainerIterator(startWordHash, false, false),+ containerOrder,+ ReferenceContainer.containerMergeMethod,+ true);+ }++ /**+ * clear the RAM and BLOB part, deletes everything in the cell+ * @throws IOException+ */+ public synchronized void clear() throws IOException {+ this.ram.clear();+ this.array.clear();+ }++ /**+ * when a cell is closed, the current RAM is dumped to a file which will be opened as+ * BLOB file the next time a cell is opened. A name for the dump is automatically generated+ * and is composed of the current date and the cell salt+ */+ public synchronized void close() {+ // dump the ram+ try {+ this.ram.dump(this.array.newContainerBLOBFile(), true);+ } catch (IOException e) {+ e.printStackTrace();+ }+ // close all+ this.ram.close();+ this.array.close();+ }++ public int size() {+ return this.ram.size() + this.array.size();+ }++ public int minMem() {+ return 10 * 1024 * 1024;+ }++ public ByteOrder ordering() {+ return this.array.ordering();+ }+++ /*+ * cache control methods+ */++ private synchronized void cacheDump() throws IOException {+ // dump the ram+ File dumpFile = this.array.newContainerBLOBFile();+ this.ram.dump(dumpFile, true);+ // get a fresh ram cache+ this.ram = new ReferenceContainerCache(this.array.rowdef(), this.array.ordering());+ this.ram.initWriteMode();+ // add the dumped indexContainerBLOB to the array+ this.array.mountBLOBContainer(dumpFile);+ int c = 0;+ while (this.array.entries() > this.maxArrayFiles && c++ < 3) {+ if (!this.array.merge(true)) break;+ }+ }++ public void cleanupBuffer(int time) {+ // do nothing+ }+++ public int getBackendSize() {+ return this.array.size();+ }+++ public long getBufferMaxAge() {+ return System.currentTimeMillis();+ }+++ public int getBufferMaxReferences() {+ return this.ram.maxReferences();+ }+++ public long getBufferMinAge() {+ return System.currentTimeMillis();+ }+++ public int getBufferSize() {+ return this.ram.size();+ }+++ public long getBufferSizeBytes() {+ return 10000 * this.ram.size(); // guessed; we don't know that exactly because there is no statistics here (expensive, not necessary)+ }+++ public void setBufferMaxWordCount(int maxWords) {+ this.maxRamEntries = maxWords;+ }++}diff --git a/source/de/anomic/kelondro/text/IndexReader.java b/source/de/anomic/kelondro/text/IndexReader.javaindex 196838914..f3cd005cb 100644--- a/source/de/anomic/kelondro/text/IndexReader.java+++ b/source/de/anomic/kelondro/text/IndexReader.java@@ -1,41 +1,41 @@-// IndexReader.java-// (C) 2008 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 2.4.2008 on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2008-03-14 01:16:04 +0100 (Fr, 14 Mrz 2008) $-// $LastChangedRevision: 4558 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import java.util.Set;--import de.anomic.kelondro.order.CloneableIterator;--public interface IndexReader {-- public int size();- public boolean has(String wordHash); // should only be used if in case that true is returned the getContainer is NOT called- public ReferenceContainer get(String wordHash, Set<String> urlselection);- public CloneableIterator<ReferenceContainer> references(String startWordHash, boolean rot);- public void close();--}+// IndexReader.java+// (C) 2008 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 2.4.2008 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import java.util.Set;++import de.anomic.kelondro.order.CloneableIterator;++public interface IndexReader {++ public int size();+ public boolean has(String wordHash); // should only be used if in case that true is returned the getContainer is NOT called+ public ReferenceContainer get(String wordHash, Set<String> urlselection);+ public CloneableIterator<ReferenceContainer> references(String startWordHash, boolean rot);+ public void close();++}diff --git a/source/de/anomic/kelondro/text/MetadataRowContainer.java b/source/de/anomic/kelondro/text/MetadataRowContainer.javaindex e636c3175..0e035ee03 100644--- a/source/de/anomic/kelondro/text/MetadataRowContainer.java+++ b/source/de/anomic/kelondro/text/MetadataRowContainer.java@@ -1,490 +1,490 @@-// URLMetadata.java-// (C) 2006 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 2006 on http://www.anomic.de-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $-// $LastChangedRevision: 1986 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import java.io.UnsupportedEncodingException;-import java.net.MalformedURLException;-import java.text.ParseException;-import java.util.ArrayList;-import java.util.Date;-import java.util.Properties;--import de.anomic.crawler.CrawlEntry;-import de.anomic.kelondro.index.Row;-import de.anomic.kelondro.order.Base64Order;-import de.anomic.kelondro.order.Bitfield;-import de.anomic.kelondro.order.Digest;-import de.anomic.kelondro.order.NaturalOrder;-import de.anomic.kelondro.util.DateFormatter;-import de.anomic.kelondro.util.FileUtils;-import de.anomic.kelondro.util.kelondroException;-import de.anomic.plasma.plasmaSearchQuery;-import de.anomic.server.serverCharBuffer;-import de.anomic.server.serverCodings;-import de.anomic.tools.crypt;-import de.anomic.yacy.yacyURL;--public class MetadataRowContainer {-- // this object stores attributes for URL entries-- public static final Row rowdef = new Row(- "String hash-12, " + // the url's hash- "String comp-360, " + // components: the url, description, author and tags. As 5th element, an ETag is possible- "Cardinal mod-4 {b256}, " + // last-modified from the httpd- "Cardinal load-4 {b256}, " + // time when the url was loaded- "Cardinal fresh-4 {b256}, " + // time until this url is fresh- "String referrer-12, " + // (one of) the url's referrer hash(es)- "byte[] md5-8, " + // the md5 of the url content (to identify changes)- "Cardinal size-6 {b256}, " + // size of file in bytes- "Cardinal wc-3 {b256}, " + // size of file by number of words; for video and audio: seconds- "byte[] dt-1, " + // doctype, taken from extension or any other heuristic- "Bitfield flags-4, " + // flags; any stuff (see Word-Entity definition)- "String lang-2, " + // language- "Cardinal llocal-2 {b256}, " + // # of outlinks to same domain; for video and image: width- "Cardinal lother-2 {b256}, " + // # of outlinks to outside domain; for video and image: height- "Cardinal limage-2 {b256}, " + // # of embedded image links- "Cardinal laudio-2 {b256}, " + // # of embedded audio links; for audio: track number; for video: number of audio tracks- "Cardinal lvideo-2 {b256}, " + // # of embedded video links- "Cardinal lapp-2 {b256}", // # of embedded links to applications- Base64Order.enhancedCoder- );-- /* ===========================================================================- * Constants to access the various columns of an URL entry- * =========================================================================== */- /** the url's hash */- private static final int col_hash = 0;- /** components: the url, description, author and tags. As 5th element, an ETag is possible */- private static final int col_comp = 1;- /** components: the url, description, author and tags. As 5th element, an ETag is possible */- private static final int col_mod = 2;- /** time when the url was loaded */- private static final int col_load = 3;- /** time until this url is fresh */- private static final int col_fresh = 4;- /** time when the url was loaded */- private static final int col_referrer = 5;- /** the md5 of the url content (to identify changes) */- private static final int col_md5 = 6;- /** size of file in bytes */- private static final int col_size = 7;- /** size of file by number of words; for video and audio: seconds */- private static final int col_wc = 8;- /** doctype, taken from extension or any other heuristic */- private static final int col_dt = 9;- /** flags; any stuff (see Word-Entity definition) */- private static final int col_flags = 10;- /** language */- private static final int col_lang = 11;- /** of outlinks to same domain; for video and image: width */- private static final int col_llocal = 12;- /** of outlinks to outside domain; for video and image: height */- private static final int col_lother = 13;- /** of embedded image links */- private static final int col_limage = 14;- /** of embedded audio links; for audio: track number; for video: number of audio tracks */- private static final int col_laudio = 15;- /** of embedded video links */- private static final int col_lvideo = 16;- /** of embedded links to applications */- private static final int col_lapp = 17;-- private final Row.Entry entry;- private final String snippet;- private Reference word; // this is only used if the url is transported via remote search requests- private final long ranking; // during generation of a search result this value is set-- public MetadataRowContainer(- final yacyURL url,- final String dc_title,- final String dc_creator,- final String dc_subject,- final String ETag,- final Date mod,- final Date load,- final Date fresh,- final String referrer,- final byte[] md5,- final long size,- final int wc,- final char dt,- final Bitfield flags,- final String lang,- final int llocal,- final int lother,- final int laudio,- final int limage,- final int lvideo,- final int lapp) {- // create new entry and store it into database- this.entry = rowdef.newEntry();- this.entry.setCol(col_hash, url.hash(), null);- this.entry.setCol(col_comp, encodeComp(url, dc_title, dc_creator, dc_subject, ETag));- encodeDate(col_mod, mod);- encodeDate(col_load, load);- encodeDate(col_fresh, fresh);- try {- this.entry.setCol(col_referrer, (referrer == null) ? null : referrer.getBytes("UTF-8"));- } catch (UnsupportedEncodingException e) {- this.entry.setCol(col_referrer, (referrer == null) ? null : referrer.getBytes());- }- this.entry.setCol(col_md5, md5);- this.entry.setCol(col_size, size);- this.entry.setCol(col_wc, wc);- this.entry.setCol(col_dt, new byte[]{(byte) dt});- this.entry.setCol(col_flags, flags.bytes());- try {- this.entry.setCol(col_lang, lang.getBytes("UTF-8"));- } catch (UnsupportedEncodingException e) {- this.entry.setCol(col_lang, lang.getBytes());- }- this.entry.setCol(col_llocal, llocal);- this.entry.setCol(col_lother, lother);- this.entry.setCol(col_limage, limage);- this.entry.setCol(col_laudio, laudio);- this.entry.setCol(col_lvideo, lvideo);- this.entry.setCol(col_lapp, lapp);- //System.out.println("===DEBUG=== " + load.toString() + ", " + decodeDate(col_load).toString());- this.snippet = null;- this.word = null;- this.ranking = 0;- }-- private void encodeDate(final int col, final Date d) {- // calculates the number of days since 1.1.1970 and returns this as 4-byte array- this.entry.setCol(col, NaturalOrder.encodeLong(d.getTime() / 86400000, 4));- }-- private Date decodeDate(final int col) {- return new Date(86400000 * this.entry.getColLong(col));- }-- public static byte[] encodeComp(final yacyURL url, final String dc_title, final String dc_creator, final String dc_subject, final String ETag) {- final serverCharBuffer s = new serverCharBuffer(200);- s.append(url.toNormalform(false, true)).append(10);- s.append(dc_title).append(10);- s.append(dc_creator).append(10);- s.append(dc_subject).append(10);- s.append(ETag).append(10);- try {- return s.toString().getBytes("UTF-8");- } catch (UnsupportedEncodingException e) {- return s.toString().getBytes();- }- }-- public MetadataRowContainer(final Row.Entry entry, final Reference searchedWord, final long ranking) {- this.entry = entry;- this.snippet = null;- this.word = searchedWord;- this.ranking = ranking;- }-- public MetadataRowContainer(final Properties prop) {- // generates an plasmaLURLEntry using the properties from the argument- // the property names must correspond to the one from toString- //System.out.println("DEBUG-ENTRY: prop=" + prop.toString());- yacyURL url;- try {- url = new yacyURL(crypt.simpleDecode(prop.getProperty("url", ""), null), prop.getProperty("hash"));- } catch (final MalformedURLException e) {- url = null;- }- String descr = crypt.simpleDecode(prop.getProperty("descr", ""), null); if (descr == null) descr = "";- String dc_creator = crypt.simpleDecode(prop.getProperty("author", ""), null); if (dc_creator == null) dc_creator = "";- String tags = crypt.simpleDecode(prop.getProperty("tags", ""), null); if (tags == null) tags = "";- String ETag = crypt.simpleDecode(prop.getProperty("ETag", ""), null); if (ETag == null) ETag = "";-- this.entry = rowdef.newEntry();- this.entry.setCol(col_hash, url.hash(), null); // FIXME potential null pointer access- this.entry.setCol(col_comp, encodeComp(url, descr, dc_creator, tags, ETag));- try {- encodeDate(col_mod, DateFormatter.parseShortDay(prop.getProperty("mod", "20000101")));- } catch (final ParseException e) {- encodeDate(col_mod, new Date());- }- try {- encodeDate(col_load, DateFormatter.parseShortDay(prop.getProperty("load", "20000101")));- } catch (final ParseException e) {- encodeDate(col_load, new Date());- }- try {- encodeDate(col_fresh, DateFormatter.parseShortDay(prop.getProperty("fresh", "20000101")));- } catch (final ParseException e) {- encodeDate(col_fresh, new Date());- }- try {- this.entry.setCol(col_referrer, prop.getProperty("referrer", "").getBytes("UTF-8"));- } catch (UnsupportedEncodingException e1) {- this.entry.setCol(col_referrer, prop.getProperty("referrer", "").getBytes());- }- this.entry.setCol(col_md5, Digest.decodeHex(prop.getProperty("md5", "")));- this.entry.setCol(col_size, Integer.parseInt(prop.getProperty("size", "0")));- this.entry.setCol(col_wc, Integer.parseInt(prop.getProperty("wc", "0")));- this.entry.setCol(col_dt, new byte[]{(byte) prop.getProperty("dt", "t").charAt(0)});- final String flags = prop.getProperty("flags", "AAAAAA");- this.entry.setCol(col_flags, (flags.length() > 6) ? plasmaSearchQuery.empty_constraint.bytes() : (new Bitfield(4, flags)).bytes());- try {- this.entry.setCol(col_lang, prop.getProperty("lang", "uk").getBytes("UTF-8"));- } catch (UnsupportedEncodingException e) {- this.entry.setCol(col_lang, prop.getProperty("lang", "uk").getBytes());- }- this.entry.setCol(col_llocal, Integer.parseInt(prop.getProperty("llocal", "0")));- this.entry.setCol(col_lother, Integer.parseInt(prop.getProperty("lother", "0")));- this.entry.setCol(col_limage, Integer.parseInt(prop.getProperty("limage", "0")));- this.entry.setCol(col_laudio, Integer.parseInt(prop.getProperty("laudio", "0")));- this.entry.setCol(col_lvideo, Integer.parseInt(prop.getProperty("lvideo", "0")));- this.entry.setCol(col_lapp, Integer.parseInt(prop.getProperty("lapp", "0")));- this.snippet = crypt.simpleDecode(prop.getProperty("snippet", ""), null);- this.word = null;- if (prop.containsKey("word")) throw new kelondroException("old database structure is not supported");- if (prop.containsKey("wi")) {- this.word = new ReferenceRow(Base64Order.enhancedCoder.decodeString(prop.getProperty("wi", ""), "de.anomic.index.indexURLEntry.indexURLEntry()"));- }- this.ranking = 0;- }-- public static MetadataRowContainer importEntry(final String propStr) {- if (propStr == null || !propStr.startsWith("{") || !propStr.endsWith("}")) {- return null;- }- try {- return new MetadataRowContainer(serverCodings.s2p(propStr.substring(1, propStr.length() - 1)));- } catch (final kelondroException e) {- // wrong format- return null;- }- }-- private StringBuilder corePropList() {- // generate a parseable string; this is a simple property-list- final URLMetadata metadata = this.metadata();- final StringBuilder s = new StringBuilder(300);- //System.out.println("author=" + comp.author());- try {- s.append("hash=").append(hash());- s.append(",url=").append(crypt.simpleEncode(metadata.url().toNormalform(false, true)));- s.append(",descr=").append(crypt.simpleEncode(metadata.dc_title()));- s.append(",author=").append(crypt.simpleEncode(metadata.dc_creator()));- s.append(",tags=").append(crypt.simpleEncode(metadata.dc_subject()));- s.append(",ETag=").append(crypt.simpleEncode(metadata.ETag()));- s.append(",mod=").append(DateFormatter.formatShortDay(moddate()));- s.append(",load=").append(DateFormatter.formatShortDay(loaddate()));- s.append(",fresh=").append(DateFormatter.formatShortDay(freshdate()));- s.append(",referrer=").append(referrerHash());- s.append(",md5=").append(md5());- s.append(",size=").append(size());- s.append(",wc=").append(wordCount());- s.append(",dt=").append(doctype());- s.append(",flags=").append(flags().exportB64());- s.append(",lang=").append(language());- s.append(",llocal=").append(llocal());- s.append(",lother=").append(lother());- s.append(",limage=").append(limage());- s.append(",laudio=").append(laudio());- s.append(",lvideo=").append(lvideo());- s.append(",lapp=").append(lapp());-- if (this.word != null) {- // append also word properties- s.append(",wi=").append(Base64Order.enhancedCoder.encodeString(word.toPropertyForm()));- }- return s;-- } catch (final Exception e) {- // serverLog.logFailure("plasmaLURL.corePropList", e.getMessage());- // if (moddate == null) serverLog.logFailure("plasmaLURL.corePropList", "moddate=null");- // if (loaddate == null) serverLog.logFailure("plasmaLURL.corePropList", "loaddate=null");- e.printStackTrace();- return null;- }- }-- public Row.Entry toRowEntry() {- return this.entry;- }-- public String hash() {- // return a url-hash, based on the md5 algorithm- // the result is a String of 12 bytes within a 72-bit space- // (each byte has an 6-bit range)- // that should be enough for all web pages on the world- return this.entry.getColString(col_hash, null);- }-- public long ranking() {- return this.ranking;- }-- public URLMetadata metadata() {- final ArrayList<String> cl = FileUtils.strings(this.entry.getCol("comp", null), "UTF-8");- return new URLMetadata(- (cl.size() > 0) ? (cl.get(0)).trim() : "",- hash(),- (cl.size() > 1) ? (cl.get(1)).trim() : "",- (cl.size() > 2) ? (cl.get(2)).trim() : "",- (cl.size() > 3) ? (cl.get(3)).trim() : "",- (cl.size() > 4) ? (cl.get(4)).trim() : "");- }-- public Date moddate() {- return decodeDate(col_mod);- }-- public Date loaddate() {- return decodeDate(col_load);- }-- public Date freshdate() {- return decodeDate(col_fresh);- }-- public String referrerHash() {- // return the creator's hash- return entry.getColString(col_referrer, null);- }-- public String md5() {- // returns the md5 in hex representation- return Digest.encodeHex(entry.getColBytes(col_md5));- }-- public char doctype() {- return (char) entry.getColByte(col_dt);- }-- public String language() {- return this.entry.getColString(col_lang, null);- }-- public int size() {- return (int) this.entry.getColLong(col_size);- }-- public Bitfield flags() {- return new Bitfield(this.entry.getColBytes(col_flags));- }-- public int wordCount() {- return (int) this.entry.getColLong(col_wc);- }-- public int llocal() {- return (int) this.entry.getColLong(col_llocal);- }-- public int lother() {- return (int) this.entry.getColLong(col_lother);- }-- public int limage() {- return (int) this.entry.getColLong(col_limage);- }-- public int laudio() {- return (int) this.entry.getColLong(col_laudio);- }-- public int lvideo() {- return (int) this.entry.getColLong(col_lvideo);- }-- public int lapp() {- return (int) this.entry.getColLong(col_lapp);- }-- public String snippet() {- // the snippet may appear here if the url was transported in a remote search- // it will not be saved anywhere, but can only be requested here- return snippet;- }-- public Reference word() {- return word;- }-- public boolean isOlder(final MetadataRowContainer other) {- if (other == null) return false;- final Date tmoddate = moddate();- final Date omoddate = other.moddate();- if (tmoddate.before(omoddate)) return true;- if (tmoddate.equals(omoddate)) {- final Date tloaddate = loaddate();- final Date oloaddate = other.loaddate();- if (tloaddate.before(oloaddate)) return true;- if (tloaddate.equals(oloaddate)) return true;- }- return false;- }-- public String toString(final String snippet) {- // add information needed for remote transport- final StringBuilder core = corePropList();- if (core == null)- return null;-- core.ensureCapacity(core.length() + snippet.length() * 2);- core.insert(0, "{");- core.append(",snippet=").append(crypt.simpleEncode(snippet));- core.append("}");-- return new String(core);- //return "{" + core + ",snippet=" + crypt.simpleEncode(snippet) + "}";- }-- public CrawlEntry toBalancerEntry(final String initiatorHash) {- return new CrawlEntry(- initiatorHash,- metadata().url(),- referrerHash(),- metadata().dc_title(),- null,- loaddate(),- null,- 0,- 0,- 0);- }-- /**- * @return the object as String.<br>- * This e.g. looks like this:- * <pre>{hash=jmqfMk7Y3NKw,referrer=------------,mod=20050610,load=20051003,size=51666,wc=1392,cc=0,local=true,q=AEn,dt=h,lang=uk,url=b|aHR0cDovL3d3dy50cmFuc3BhcmVuY3kub3JnL3N1cnZleXMv,descr=b|S25vd2xlZGdlIENlbnRyZTogQ29ycnVwdGlvbiBTdXJ2ZXlzIGFuZCBJbmRpY2Vz}</pre>- */- public String toString() {- final StringBuilder core = corePropList();- if (core == null) return null;-- core.insert(0, "{");- core.append("}");-- return new String(core);- //return "{" + core + "}";- }--}\ No newline at end of file+// URLMetadata.java+// (C) 2006 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 2006 on http://www.anomic.de+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import java.io.UnsupportedEncodingException;+import java.net.MalformedURLException;+import java.text.ParseException;+import java.util.ArrayList;+import java.util.Date;+import java.util.Properties;++import de.anomic.crawler.CrawlEntry;+import de.anomic.kelondro.index.Row;+import de.anomic.kelondro.order.Base64Order;+import de.anomic.kelondro.order.Bitfield;+import de.anomic.kelondro.order.Digest;+import de.anomic.kelondro.order.NaturalOrder;+import de.anomic.kelondro.util.DateFormatter;+import de.anomic.kelondro.util.FileUtils;+import de.anomic.kelondro.util.kelondroException;+import de.anomic.plasma.plasmaSearchQuery;+import de.anomic.server.serverCharBuffer;+import de.anomic.server.serverCodings;+import de.anomic.tools.crypt;+import de.anomic.yacy.yacyURL;++public class MetadataRowContainer {++ // this object stores attributes for URL entries++ public static final Row rowdef = new Row(+ "String hash-12, " + // the url's hash+ "String comp-360, " + // components: the url, description, author and tags. As 5th element, an ETag is possible+ "Cardinal mod-4 {b256}, " + // last-modified from the httpd+ "Cardinal load-4 {b256}, " + // time when the url was loaded+ "Cardinal fresh-4 {b256}, " + // time until this url is fresh+ "String referrer-12, " + // (one of) the url's referrer hash(es)+ "byte[] md5-8, " + // the md5 of the url content (to identify changes)+ "Cardinal size-6 {b256}, " + // size of file in bytes+ "Cardinal wc-3 {b256}, " + // size of file by number of words; for video and audio: seconds+ "byte[] dt-1, " + // doctype, taken from extension or any other heuristic+ "Bitfield flags-4, " + // flags; any stuff (see Word-Entity definition)+ "String lang-2, " + // language+ "Cardinal llocal-2 {b256}, " + // # of outlinks to same domain; for video and image: width+ "Cardinal lother-2 {b256}, " + // # of outlinks to outside domain; for video and image: height+ "Cardinal limage-2 {b256}, " + // # of embedded image links+ "Cardinal laudio-2 {b256}, " + // # of embedded audio links; for audio: track number; for video: number of audio tracks+ "Cardinal lvideo-2 {b256}, " + // # of embedded video links+ "Cardinal lapp-2 {b256}", // # of embedded links to applications+ Base64Order.enhancedCoder+ );++ /* ===========================================================================+ * Constants to access the various columns of an URL entry+ * =========================================================================== */+ /** the url's hash */+ private static final int col_hash = 0;+ /** components: the url, description, author and tags. As 5th element, an ETag is possible */+ private static final int col_comp = 1;+ /** components: the url, description, author and tags. As 5th element, an ETag is possible */+ private static final int col_mod = 2;+ /** time when the url was loaded */+ private static final int col_load = 3;+ /** time until this url is fresh */+ private static final int col_fresh = 4;+ /** time when the url was loaded */+ private static final int col_referrer = 5;+ /** the md5 of the url content (to identify changes) */+ private static final int col_md5 = 6;+ /** size of file in bytes */+ private static final int col_size = 7;+ /** size of file by number of words; for video and audio: seconds */+ private static final int col_wc = 8;+ /** doctype, taken from extension or any other heuristic */+ private static final int col_dt = 9;+ /** flags; any stuff (see Word-Entity definition) */+ private static final int col_flags = 10;+ /** language */+ private static final int col_lang = 11;+ /** of outlinks to same domain; for video and image: width */+ private static final int col_llocal = 12;+ /** of outlinks to outside domain; for video and image: height */+ private static final int col_lother = 13;+ /** of embedded image links */+ private static final int col_limage = 14;+ /** of embedded audio links; for audio: track number; for video: number of audio tracks */+ private static final int col_laudio = 15;+ /** of embedded video links */+ private static final int col_lvideo = 16;+ /** of embedded links to applications */+ private static final int col_lapp = 17;++ private final Row.Entry entry;+ private final String snippet;+ private Reference word; // this is only used if the url is transported via remote search requests+ private final long ranking; // during generation of a search result this value is set++ public MetadataRowContainer(+ final yacyURL url,+ final String dc_title,+ final String dc_creator,+ final String dc_subject,+ final String ETag,+ final Date mod,+ final Date load,+ final Date fresh,+ final String referrer,+ final byte[] md5,+ final long size,+ final int wc,+ final char dt,+ final Bitfield flags,+ final String lang,+ final int llocal,+ final int lother,+ final int laudio,+ final int limage,+ final int lvideo,+ final int lapp) {+ // create new entry and store it into database+ this.entry = rowdef.newEntry();+ this.entry.setCol(col_hash, url.hash(), null);+ this.entry.setCol(col_comp, encodeComp(url, dc_title, dc_creator, dc_subject, ETag));+ encodeDate(col_mod, mod);+ encodeDate(col_load, load);+ encodeDate(col_fresh, fresh);+ try {+ this.entry.setCol(col_referrer, (referrer == null) ? null : referrer.getBytes("UTF-8"));+ } catch (UnsupportedEncodingException e) {+ this.entry.setCol(col_referrer, (referrer == null) ? null : referrer.getBytes());+ }+ this.entry.setCol(col_md5, md5);+ this.entry.setCol(col_size, size);+ this.entry.setCol(col_wc, wc);+ this.entry.setCol(col_dt, new byte[]{(byte) dt});+ this.entry.setCol(col_flags, flags.bytes());+ try {+ this.entry.setCol(col_lang, lang.getBytes("UTF-8"));+ } catch (UnsupportedEncodingException e) {+ this.entry.setCol(col_lang, lang.getBytes());+ }+ this.entry.setCol(col_llocal, llocal);+ this.entry.setCol(col_lother, lother);+ this.entry.setCol(col_limage, limage);+ this.entry.setCol(col_laudio, laudio);+ this.entry.setCol(col_lvideo, lvideo);+ this.entry.setCol(col_lapp, lapp);+ //System.out.println("===DEBUG=== " + load.toString() + ", " + decodeDate(col_load).toString());+ this.snippet = null;+ this.word = null;+ this.ranking = 0;+ }++ private void encodeDate(final int col, final Date d) {+ // calculates the number of days since 1.1.1970 and returns this as 4-byte array+ this.entry.setCol(col, NaturalOrder.encodeLong(d.getTime() / 86400000, 4));+ }++ private Date decodeDate(final int col) {+ return new Date(86400000 * this.entry.getColLong(col));+ }++ public static byte[] encodeComp(final yacyURL url, final String dc_title, final String dc_creator, final String dc_subject, final String ETag) {+ final serverCharBuffer s = new serverCharBuffer(200);+ s.append(url.toNormalform(false, true)).append(10);+ s.append(dc_title).append(10);+ s.append(dc_creator).append(10);+ s.append(dc_subject).append(10);+ s.append(ETag).append(10);+ try {+ return s.toString().getBytes("UTF-8");+ } catch (UnsupportedEncodingException e) {+ return s.toString().getBytes();+ }+ }++ public MetadataRowContainer(final Row.Entry entry, final Reference searchedWord, final long ranking) {+ this.entry = entry;+ this.snippet = null;+ this.word = searchedWord;+ this.ranking = ranking;+ }++ public MetadataRowContainer(final Properties prop) {+ // generates an plasmaLURLEntry using the properties from the argument+ // the property names must correspond to the one from toString+ //System.out.println("DEBUG-ENTRY: prop=" + prop.toString());+ yacyURL url;+ try {+ url = new yacyURL(crypt.simpleDecode(prop.getProperty("url", ""), null), prop.getProperty("hash"));+ } catch (final MalformedURLException e) {+ url = null;+ }+ String descr = crypt.simpleDecode(prop.getProperty("descr", ""), null); if (descr == null) descr = "";+ String dc_creator = crypt.simpleDecode(prop.getProperty("author", ""), null); if (dc_creator == null) dc_creator = "";+ String tags = crypt.simpleDecode(prop.getProperty("tags", ""), null); if (tags == null) tags = "";+ String ETag = crypt.simpleDecode(prop.getProperty("ETag", ""), null); if (ETag == null) ETag = "";++ this.entry = rowdef.newEntry();+ this.entry.setCol(col_hash, url.hash(), null); // FIXME potential null pointer access+ this.entry.setCol(col_comp, encodeComp(url, descr, dc_creator, tags, ETag));+ try {+ encodeDate(col_mod, DateFormatter.parseShortDay(prop.getProperty("mod", "20000101")));+ } catch (final ParseException e) {+ encodeDate(col_mod, new Date());+ }+ try {+ encodeDate(col_load, DateFormatter.parseShortDay(prop.getProperty("load", "20000101")));+ } catch (final ParseException e) {+ encodeDate(col_load, new Date());+ }+ try {+ encodeDate(col_fresh, DateFormatter.parseShortDay(prop.getProperty("fresh", "20000101")));+ } catch (final ParseException e) {+ encodeDate(col_fresh, new Date());+ }+ try {+ this.entry.setCol(col_referrer, prop.getProperty("referrer", "").getBytes("UTF-8"));+ } catch (UnsupportedEncodingException e1) {+ this.entry.setCol(col_referrer, prop.getProperty("referrer", "").getBytes());+ }+ this.entry.setCol(col_md5, Digest.decodeHex(prop.getProperty("md5", "")));+ this.entry.setCol(col_size, Integer.parseInt(prop.getProperty("size", "0")));+ this.entry.setCol(col_wc, Integer.parseInt(prop.getProperty("wc", "0")));+ this.entry.setCol(col_dt, new byte[]{(byte) prop.getProperty("dt", "t").charAt(0)});+ final String flags = prop.getProperty("flags", "AAAAAA");+ this.entry.setCol(col_flags, (flags.length() > 6) ? plasmaSearchQuery.empty_constraint.bytes() : (new Bitfield(4, flags)).bytes());+ try {+ this.entry.setCol(col_lang, prop.getProperty("lang", "uk").getBytes("UTF-8"));+ } catch (UnsupportedEncodingException e) {+ this.entry.setCol(col_lang, prop.getProperty("lang", "uk").getBytes());+ }+ this.entry.setCol(col_llocal, Integer.parseInt(prop.getProperty("llocal", "0")));+ this.entry.setCol(col_lother, Integer.parseInt(prop.getProperty("lother", "0")));+ this.entry.setCol(col_limage, Integer.parseInt(prop.getProperty("limage", "0")));+ this.entry.setCol(col_laudio, Integer.parseInt(prop.getProperty("laudio", "0")));+ this.entry.setCol(col_lvideo, Integer.parseInt(prop.getProperty("lvideo", "0")));+ this.entry.setCol(col_lapp, Integer.parseInt(prop.getProperty("lapp", "0")));+ this.snippet = crypt.simpleDecode(prop.getProperty("snippet", ""), null);+ this.word = null;+ if (prop.containsKey("word")) throw new kelondroException("old database structure is not supported");+ if (prop.containsKey("wi")) {+ this.word = new ReferenceRow(Base64Order.enhancedCoder.decodeString(prop.getProperty("wi", ""), "de.anomic.index.indexURLEntry.indexURLEntry()"));+ }+ this.ranking = 0;+ }++ public static MetadataRowContainer importEntry(final String propStr) {+ if (propStr == null || !propStr.startsWith("{") || !propStr.endsWith("}")) {+ return null;+ }+ try {+ return new MetadataRowContainer(serverCodings.s2p(propStr.substring(1, propStr.length() - 1)));+ } catch (final kelondroException e) {+ // wrong format+ return null;+ }+ }++ private StringBuilder corePropList() {+ // generate a parseable string; this is a simple property-list+ final URLMetadata metadata = this.metadata();+ final StringBuilder s = new StringBuilder(300);+ //System.out.println("author=" + comp.author());+ try {+ s.append("hash=").append(hash());+ s.append(",url=").append(crypt.simpleEncode(metadata.url().toNormalform(false, true)));+ s.append(",descr=").append(crypt.simpleEncode(metadata.dc_title()));+ s.append(",author=").append(crypt.simpleEncode(metadata.dc_creator()));+ s.append(",tags=").append(crypt.simpleEncode(metadata.dc_subject()));+ s.append(",ETag=").append(crypt.simpleEncode(metadata.ETag()));+ s.append(",mod=").append(DateFormatter.formatShortDay(moddate()));+ s.append(",load=").append(DateFormatter.formatShortDay(loaddate()));+ s.append(",fresh=").append(DateFormatter.formatShortDay(freshdate()));+ s.append(",referrer=").append(referrerHash());+ s.append(",md5=").append(md5());+ s.append(",size=").append(size());+ s.append(",wc=").append(wordCount());+ s.append(",dt=").append(doctype());+ s.append(",flags=").append(flags().exportB64());+ s.append(",lang=").append(language());+ s.append(",llocal=").append(llocal());+ s.append(",lother=").append(lother());+ s.append(",limage=").append(limage());+ s.append(",laudio=").append(laudio());+ s.append(",lvideo=").append(lvideo());+ s.append(",lapp=").append(lapp());++ if (this.word != null) {+ // append also word properties+ s.append(",wi=").append(Base64Order.enhancedCoder.encodeString(word.toPropertyForm()));+ }+ return s;++ } catch (final Exception e) {+ // serverLog.logFailure("plasmaLURL.corePropList", e.getMessage());+ // if (moddate == null) serverLog.logFailure("plasmaLURL.corePropList", "moddate=null");+ // if (loaddate == null) serverLog.logFailure("plasmaLURL.corePropList", "loaddate=null");+ e.printStackTrace();+ return null;+ }+ }++ public Row.Entry toRowEntry() {+ return this.entry;+ }++ public String hash() {+ // return a url-hash, based on the md5 algorithm+ // the result is a String of 12 bytes within a 72-bit space+ // (each byte has an 6-bit range)+ // that should be enough for all web pages on the world+ return this.entry.getColString(col_hash, null);+ }++ public long ranking() {+ return this.ranking;+ }++ public URLMetadata metadata() {+ final ArrayList<String> cl = FileUtils.strings(this.entry.getCol("comp", null), "UTF-8");+ return new URLMetadata(+ (cl.size() > 0) ? (cl.get(0)).trim() : "",+ hash(),+ (cl.size() > 1) ? (cl.get(1)).trim() : "",+ (cl.size() > 2) ? (cl.get(2)).trim() : "",+ (cl.size() > 3) ? (cl.get(3)).trim() : "",+ (cl.size() > 4) ? (cl.get(4)).trim() : "");+ }++ public Date moddate() {+ return decodeDate(col_mod);+ }++ public Date loaddate() {+ return decodeDate(col_load);+ }++ public Date freshdate() {+ return decodeDate(col_fresh);+ }++ public String referrerHash() {+ // return the creator's hash+ return entry.getColString(col_referrer, null);+ }++ public String md5() {+ // returns the md5 in hex representation+ return Digest.encodeHex(entry.getColBytes(col_md5));+ }++ public char doctype() {+ return (char) entry.getColByte(col_dt);+ }++ public String language() {+ return this.entry.getColString(col_lang, null);+ }++ public int size() {+ return (int) this.entry.getColLong(col_size);+ }++ public Bitfield flags() {+ return new Bitfield(this.entry.getColBytes(col_flags));+ }++ public int wordCount() {+ return (int) this.entry.getColLong(col_wc);+ }++ public int llocal() {+ return (int) this.entry.getColLong(col_llocal);+ }++ public int lother() {+ return (int) this.entry.getColLong(col_lother);+ }++ public int limage() {+ return (int) this.entry.getColLong(col_limage);+ }++ public int laudio() {+ return (int) this.entry.getColLong(col_laudio);+ }++ public int lvideo() {+ return (int) this.entry.getColLong(col_lvideo);+ }++ public int lapp() {+ return (int) this.entry.getColLong(col_lapp);+ }++ public String snippet() {+ // the snippet may appear here if the url was transported in a remote search+ // it will not be saved anywhere, but can only be requested here+ return snippet;+ }++ public Reference word() {+ return word;+ }++ public boolean isOlder(final MetadataRowContainer other) {+ if (other == null) return false;+ final Date tmoddate = moddate();+ final Date omoddate = other.moddate();+ if (tmoddate.before(omoddate)) return true;+ if (tmoddate.equals(omoddate)) {+ final Date tloaddate = loaddate();+ final Date oloaddate = other.loaddate();+ if (tloaddate.before(oloaddate)) return true;+ if (tloaddate.equals(oloaddate)) return true;+ }+ return false;+ }++ public String toString(final String snippet) {+ // add information needed for remote transport+ final StringBuilder core = corePropList();+ if (core == null)+ return null;++ core.ensureCapacity(core.length() + snippet.length() * 2);+ core.insert(0, "{");+ core.append(",snippet=").append(crypt.simpleEncode(snippet));+ core.append("}");++ return new String(core);+ //return "{" + core + ",snippet=" + crypt.simpleEncode(snippet) + "}";+ }++ public CrawlEntry toBalancerEntry(final String initiatorHash) {+ return new CrawlEntry(+ initiatorHash,+ metadata().url(),+ referrerHash(),+ metadata().dc_title(),+ null,+ loaddate(),+ null,+ 0,+ 0,+ 0);+ }++ /**+ * @return the object as String.<br>+ * This e.g. looks like this:+ * <pre>{hash=jmqfMk7Y3NKw,referrer=------------,mod=20050610,load=20051003,size=51666,wc=1392,cc=0,local=true,q=AEn,dt=h,lang=uk,url=b|aHR0cDovL3d3dy50cmFuc3BhcmVuY3kub3JnL3N1cnZleXMv,descr=b|S25vd2xlZGdlIENlbnRyZTogQ29ycnVwdGlvbiBTdXJ2ZXlzIGFuZCBJbmRpY2Vz}</pre>+ */+ public String toString() {+ final StringBuilder core = corePropList();+ if (core == null) return null;++ core.insert(0, "{");+ core.append("}");++ return new String(core);+ //return "{" + core + "}";+ }++}diff --git a/source/de/anomic/kelondro/text/Phrase.java b/source/de/anomic/kelondro/text/Phrase.javaindex 96b4ba248..8c91189b6 100644--- a/source/de/anomic/kelondro/text/Phrase.java+++ b/source/de/anomic/kelondro/text/Phrase.java@@ -1,61 +1,61 @@-// indexPhrase.java-// (C) 2008 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 26.03.2008 on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $-// $LastChangedRevision: 1986 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import java.util.HashSet;--public class Phrase {- // object carries statistics for words and sentences-- private int count; // number of occurrences- private final int handle; // unique handle, is initialized with sentence counter- private final HashSet<Integer> hash; //-- public Phrase(final int handle) {- this.count = 1;- this.handle = handle;- this.hash = new HashSet<Integer>();- }-- public int handle() {- return this.handle;- }-- public int occurrences() {- return count;- }-- public void inc() {- count++;- }-- public void check(final int i) {- hash.add(Integer.valueOf(i));- }---}+// indexPhrase.java+// (C) 2008 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 26.03.2008 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import java.util.HashSet;++public class Phrase {+ // object carries statistics for words and sentences++ private int count; // number of occurrences+ private final int handle; // unique handle, is initialized with sentence counter+ private final HashSet<Integer> hash; //++ public Phrase(final int handle) {+ this.count = 1;+ this.handle = handle;+ this.hash = new HashSet<Integer>();+ }++ public int handle() {+ return this.handle;+ }++ public int occurrences() {+ return count;+ }++ public void inc() {+ count++;+ }++ public void check(final int i) {+ hash.add(Integer.valueOf(i));+ }+++}diff --git a/source/de/anomic/kelondro/text/Reference.java b/source/de/anomic/kelondro/text/Reference.javaindex 0ef2fd643..bd8b3386e 100644--- a/source/de/anomic/kelondro/text/Reference.java+++ b/source/de/anomic/kelondro/text/Reference.java@@ -1,90 +1,90 @@-// Reference.java-// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 07.11.2007 on http://www.anomic.de-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $-// $LastChangedRevision: 1986 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import de.anomic.kelondro.order.Bitfield;--public interface Reference {-- // appearance flags, used in RWI entry- // some names are derived from the Dublin Core Metadata tag set- // the flags 0..23 are identical to the category flags in plasmaCondenser- public static final int flag_app_dc_description= 24; // word appears in anchor description text (the reference to an url), or any alternative text field of a link- public static final int flag_app_dc_title = 25; // word appears in title or headline or any description part- public static final int flag_app_dc_creator = 26; // word appears in author- public static final int flag_app_dc_subject = 27; // word appears in header tags or other descriptive part- public static final int flag_app_dc_identifier = 28; // word appears in url or document identifier- public static final int flag_app_emphasized = 29; // word is emphasized in text (i.e. bold, italics, special size)-- public String toPropertyForm();-- public String urlHash();-- public int virtualAge();-- public long lastModified();-- public long freshUntil();-- public int hitcount();-- public int posintext();-- public int posinphrase();-- public int posofphrase();-- public int wordsintext();-- public int phrasesintext();-- public String getLanguage();-- public char getType();-- public int wordsintitle();-- public int llocal();-- public int lother();-- public int urllength();-- public int urlcomps();-- public Bitfield flags();-- public double termFrequency();-- public String toString();-- public boolean isNewer(Reference other);-- public boolean isOlder(Reference other);-- public int hashCode();-}\ No newline at end of file+// Reference.java+// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 07.11.2007 on http://www.anomic.de+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import de.anomic.kelondro.order.Bitfield;++public interface Reference {++ // appearance flags, used in RWI entry+ // some names are derived from the Dublin Core Metadata tag set+ // the flags 0..23 are identical to the category flags in plasmaCondenser+ public static final int flag_app_dc_description= 24; // word appears in anchor description text (the reference to an url), or any alternative text field of a link+ public static final int flag_app_dc_title = 25; // word appears in title or headline or any description part+ public static final int flag_app_dc_creator = 26; // word appears in author+ public static final int flag_app_dc_subject = 27; // word appears in header tags or other descriptive part+ public static final int flag_app_dc_identifier = 28; // word appears in url or document identifier+ public static final int flag_app_emphasized = 29; // word is emphasized in text (i.e. bold, italics, special size)++ public String toPropertyForm();++ public String urlHash();++ public int virtualAge();++ public long lastModified();++ public long freshUntil();++ public int hitcount();++ public int posintext();++ public int posinphrase();++ public int posofphrase();++ public int wordsintext();++ public int phrasesintext();++ public String getLanguage();++ public char getType();++ public int wordsintitle();++ public int llocal();++ public int lother();++ public int urllength();++ public int urlcomps();++ public Bitfield flags();++ public double termFrequency();++ public String toString();++ public boolean isNewer(Reference other);++ public boolean isOlder(Reference other);++ public int hashCode();+}diff --git a/source/de/anomic/kelondro/text/ReferenceContainer.java b/source/de/anomic/kelondro/text/ReferenceContainer.javaindex f5e796b08..db31052d7 100644--- a/source/de/anomic/kelondro/text/ReferenceContainer.java+++ b/source/de/anomic/kelondro/text/ReferenceContainer.java@@ -4,9 +4,9 @@//// This is a part of YaCy, a peer-to-peer based web search engine//-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $-// $LastChangedRevision: 1986 $-// $LastChangedBy: orbiter $+// $LastChangedDate$+// $LastChangedRevision$+// $LastChangedBy$//// LICENSE//diff --git a/source/de/anomic/kelondro/text/ReferenceContainerArray.java b/source/de/anomic/kelondro/text/ReferenceContainerArray.javaindex 255e74910..cd1782e15 100644--- a/source/de/anomic/kelondro/text/ReferenceContainerArray.java+++ b/source/de/anomic/kelondro/text/ReferenceContainerArray.java@@ -1,255 +1,255 @@-// ReferenceContainerArray.java-// (C) 2009 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 04.01.2009 on http://yacy.net-//-// $LastChangedDate: 2008-03-14 01:16:04 +0100 (Fr, 14 Mrz 2008) $-// $LastChangedRevision: 4558 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import java.io.File;-import java.io.IOException;-import java.util.Date;-import java.util.Iterator;-import java.util.List;--import de.anomic.kelondro.blob.BLOB;-import de.anomic.kelondro.blob.BLOBArray;-import de.anomic.kelondro.index.Row;-import de.anomic.kelondro.index.RowSet;-import de.anomic.kelondro.order.ByteOrder;-import de.anomic.kelondro.order.CloneableIterator;--public final class ReferenceContainerArray {-- private final Row payloadrow;- private final BLOBArray array;- private final ReferenceContainerMerger merger;-- /**- * open a index container based on a BLOB dump. The content of the BLOB will not be read- * unless a .idx file exists. Only the .idx file is opened to get a fast read access to- * the BLOB. This class provides no write methods, because BLOB files should not be- * written in random access. To support deletion, a write access to the BLOB for deletion- * is still possible- * @param payloadrow- * @param log- * @throws IOException- */- public ReferenceContainerArray(- final File heapLocation,- final ByteOrder wordOrder,- final Row payloadrow,- ReferenceContainerMerger merger) throws IOException {- this.payloadrow = payloadrow;- this.array = new BLOBArray(- heapLocation,- "index",- payloadrow.primaryKeyLength,- wordOrder,- 0);- this.merger = merger;- }-- public synchronized void close() {- this.array.close(true);- }-- public synchronized void clear() throws IOException {- this.array.clear();- }-- public synchronized int size() {- return (this.array == null) ? 0 : this.array.size();- }-- public ByteOrder ordering() {- return this.array.ordering();- }-- public File newContainerBLOBFile() {- return this.array.newBLOB(new Date());- }-- public void mountBLOBContainer(File location) throws IOException {- this.array.mountBLOB(location);- }-- public Row rowdef() {- return this.payloadrow;- }-- /**- * return an iterator object that creates top-level-clones of the indexContainers- * in the cache, so that manipulations of the iterated objects do not change- * objects in the cache.- * @throws IOException- */- public synchronized CloneableIterator<ReferenceContainer> wordContainerIterator(final String startWordHash, final boolean rot, final boolean ram) {- try {- return new heapCacheIterator(startWordHash, rot);- } catch (IOException e) {- e.printStackTrace();- return null;- }- }-- /**- * cache iterator: iterates objects within the heap cache. This can only be used- * for write-enabled heaps, read-only heaps do not have a heap cache- */- public class heapCacheIterator implements CloneableIterator<ReferenceContainer>, Iterable<ReferenceContainer> {-- // this class exists, because the wCache cannot be iterated with rotation- // and because every indexContainer Object that is iterated must be returned as top-level-clone- // so this class simulates wCache.tailMap(startWordHash).values().iterator()- // plus the mentioned features-- private final boolean rot;- private CloneableIterator<byte[]> iterator;-- public heapCacheIterator(final String startWordHash, final boolean rot) throws IOException {- this.rot = rot;- this.iterator = array.keys(true, startWordHash.getBytes());- // The collection's iterator will return the values in the order that their corresponding keys appear in the tree.- }-- public heapCacheIterator clone(final Object secondWordHash) {- try {- return new heapCacheIterator((String) secondWordHash, rot);- } catch (IOException e) {- e.printStackTrace();- return null;- }- }-- public boolean hasNext() {- if (rot) return true;- return iterator.hasNext();- }-- public ReferenceContainer next() {- try {- if (iterator.hasNext()) {- return get(new String(iterator.next()));- }- // rotation iteration- if (!rot) {- return null;- }- iterator = array.keys(true, null);- return get(new String(iterator.next()));- } catch (IOException e) {- e.printStackTrace();- return null;- }- }-- public void remove() {- iterator.remove();- }-- public Iterator<ReferenceContainer> iterator() {- return this;- }-- }-- /**- * test if a given key is in the heap- * this works with heaps in write- and read-mode- * @param key- * @return true, if the key is used in the heap; false othervise- * @throws IOException- */- public synchronized boolean has(final String key) {- return this.array.has(key.getBytes());- }-- /**- * get a indexContainer from a heap- * @param key- * @return the indexContainer if one exist, null otherwise- * @throws IOException- */- public synchronized ReferenceContainer get(final String key) throws IOException {- List<byte[]> entries = this.array.getAll(key.getBytes());- if (entries == null || entries.size() == 0) return null;- byte[] a = entries.remove(0);- ReferenceContainer c = new ReferenceContainer(key, RowSet.importRowSet(a, payloadrow));- while (entries.size() > 0) {- c = c.merge(new ReferenceContainer(key, RowSet.importRowSet(entries.remove(0), payloadrow)));- }- return c;- }-- /**- * delete a indexContainer from the heap cache. This can only be used for write-enabled heaps- * @param wordHash- * @return the indexContainer if the cache contained the container, null othervise- * @throws IOException- */- public synchronized void delete(final String wordHash) throws IOException {- // returns the index that had been deleted- array.remove(wordHash.getBytes());- }-- public synchronized int replace(final String wordHash, ContainerRewriter rewriter) throws IOException {- return array.replace(wordHash.getBytes(), new BLOBRewriter(wordHash, rewriter));- }-- public class BLOBRewriter implements BLOB.Rewriter {-- ContainerRewriter rewriter;- String wordHash;-- public BLOBRewriter(String wordHash, ContainerRewriter rewriter) {- this.rewriter = rewriter;- this.wordHash = wordHash;- }-- public byte[] rewrite(byte[] b) {- if (b == null) return null;- ReferenceContainer c = rewriter.rewrite(new ReferenceContainer(this.wordHash, RowSet.importRowSet(b, payloadrow)));- if (c == null) return null;- return c.exportCollection();- }- }-- public interface ContainerRewriter {-- public ReferenceContainer rewrite(ReferenceContainer container);-- }-- public int entries() {- return this.array.entries();- }-- public synchronized boolean merge(boolean similar) throws IOException {- if (this.array.entries() < 2) return false;- File f1 = this.array.unmountOldestBLOB(similar);- File f2 = (similar) ? this.array.unmountSimilarSizeBLOB(f1.length()) : this.array.unmountOldestBLOB(false);- merger.merge(f1, f2, this.array, this.payloadrow, newContainerBLOBFile());- return true;- }---}+// ReferenceContainerArray.java+// (C) 2009 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 04.01.2009 on http://yacy.net+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import java.io.File;+import java.io.IOException;+import java.util.Date;+import java.util.Iterator;+import java.util.List;++import de.anomic.kelondro.blob.BLOB;+import de.anomic.kelondro.blob.BLOBArray;+import de.anomic.kelondro.index.Row;+import de.anomic.kelondro.index.RowSet;+import de.anomic.kelondro.order.ByteOrder;+import de.anomic.kelondro.order.CloneableIterator;++public final class ReferenceContainerArray {++ private final Row payloadrow;+ private final BLOBArray array;+ private final ReferenceContainerMerger merger;++ /**+ * open a index container based on a BLOB dump. The content of the BLOB will not be read+ * unless a .idx file exists. Only the .idx file is opened to get a fast read access to+ * the BLOB. This class provides no write methods, because BLOB files should not be+ * written in random access. To support deletion, a write access to the BLOB for deletion+ * is still possible+ * @param payloadrow+ * @param log+ * @throws IOException+ */+ public ReferenceContainerArray(+ final File heapLocation,+ final ByteOrder wordOrder,+ final Row payloadrow,+ ReferenceContainerMerger merger) throws IOException {+ this.payloadrow = payloadrow;+ this.array = new BLOBArray(+ heapLocation,+ "index",+ payloadrow.primaryKeyLength,+ wordOrder,+ 0);+ this.merger = merger;+ }++ public synchronized void close() {+ this.array.close(true);+ }++ public synchronized void clear() throws IOException {+ this.array.clear();+ }++ public synchronized int size() {+ return (this.array == null) ? 0 : this.array.size();+ }++ public ByteOrder ordering() {+ return this.array.ordering();+ }++ public File newContainerBLOBFile() {+ return this.array.newBLOB(new Date());+ }++ public void mountBLOBContainer(File location) throws IOException {+ this.array.mountBLOB(location);+ }++ public Row rowdef() {+ return this.payloadrow;+ }++ /**+ * return an iterator object that creates top-level-clones of the indexContainers+ * in the cache, so that manipulations of the iterated objects do not change+ * objects in the cache.+ * @throws IOException+ */+ public synchronized CloneableIterator<ReferenceContainer> wordContainerIterator(final String startWordHash, final boolean rot, final boolean ram) {+ try {+ return new heapCacheIterator(startWordHash, rot);+ } catch (IOException e) {+ e.printStackTrace();+ return null;+ }+ }++ /**+ * cache iterator: iterates objects within the heap cache. This can only be used+ * for write-enabled heaps, read-only heaps do not have a heap cache+ */+ public class heapCacheIterator implements CloneableIterator<ReferenceContainer>, Iterable<ReferenceContainer> {++ // this class exists, because the wCache cannot be iterated with rotation+ // and because every indexContainer Object that is iterated must be returned as top-level-clone+ // so this class simulates wCache.tailMap(startWordHash).values().iterator()+ // plus the mentioned features++ private final boolean rot;+ private CloneableIterator<byte[]> iterator;++ public heapCacheIterator(final String startWordHash, final boolean rot) throws IOException {+ this.rot = rot;+ this.iterator = array.keys(true, startWordHash.getBytes());+ // The collection's iterator will return the values in the order that their corresponding keys appear in the tree.+ }++ public heapCacheIterator clone(final Object secondWordHash) {+ try {+ return new heapCacheIterator((String) secondWordHash, rot);+ } catch (IOException e) {+ e.printStackTrace();+ return null;+ }+ }++ public boolean hasNext() {+ if (rot) return true;+ return iterator.hasNext();+ }++ public ReferenceContainer next() {+ try {+ if (iterator.hasNext()) {+ return get(new String(iterator.next()));+ }+ // rotation iteration+ if (!rot) {+ return null;+ }+ iterator = array.keys(true, null);+ return get(new String(iterator.next()));+ } catch (IOException e) {+ e.printStackTrace();+ return null;+ }+ }++ public void remove() {+ iterator.remove();+ }++ public Iterator<ReferenceContainer> iterator() {+ return this;+ }++ }++ /**+ * test if a given key is in the heap+ * this works with heaps in write- and read-mode+ * @param key+ * @return true, if the key is used in the heap; false othervise+ * @throws IOException+ */+ public synchronized boolean has(final String key) {+ return this.array.has(key.getBytes());+ }++ /**+ * get a indexContainer from a heap+ * @param key+ * @return the indexContainer if one exist, null otherwise+ * @throws IOException+ */+ public synchronized ReferenceContainer get(final String key) throws IOException {+ List<byte[]> entries = this.array.getAll(key.getBytes());+ if (entries == null || entries.size() == 0) return null;+ byte[] a = entries.remove(0);+ ReferenceContainer c = new ReferenceContainer(key, RowSet.importRowSet(a, payloadrow));+ while (entries.size() > 0) {+ c = c.merge(new ReferenceContainer(key, RowSet.importRowSet(entries.remove(0), payloadrow)));+ }+ return c;+ }++ /**+ * delete a indexContainer from the heap cache. This can only be used for write-enabled heaps+ * @param wordHash+ * @return the indexContainer if the cache contained the container, null othervise+ * @throws IOException+ */+ public synchronized void delete(final String wordHash) throws IOException {+ // returns the index that had been deleted+ array.remove(wordHash.getBytes());+ }++ public synchronized int replace(final String wordHash, ContainerRewriter rewriter) throws IOException {+ return array.replace(wordHash.getBytes(), new BLOBRewriter(wordHash, rewriter));+ }++ public class BLOBRewriter implements BLOB.Rewriter {++ ContainerRewriter rewriter;+ String wordHash;++ public BLOBRewriter(String wordHash, ContainerRewriter rewriter) {+ this.rewriter = rewriter;+ this.wordHash = wordHash;+ }++ public byte[] rewrite(byte[] b) {+ if (b == null) return null;+ ReferenceContainer c = rewriter.rewrite(new ReferenceContainer(this.wordHash, RowSet.importRowSet(b, payloadrow)));+ if (c == null) return null;+ return c.exportCollection();+ }+ }++ public interface ContainerRewriter {++ public ReferenceContainer rewrite(ReferenceContainer container);++ }++ public int entries() {+ return this.array.entries();+ }++ public synchronized boolean merge(boolean similar) throws IOException {+ if (this.array.entries() < 2) return false;+ File f1 = this.array.unmountOldestBLOB(similar);+ File f2 = (similar) ? this.array.unmountSimilarSizeBLOB(f1.length()) : this.array.unmountOldestBLOB(false);+ merger.merge(f1, f2, this.array, this.payloadrow, newContainerBLOBFile());+ return true;+ }+++}diff --git a/source/de/anomic/kelondro/text/ReferenceContainerCache.java b/source/de/anomic/kelondro/text/ReferenceContainerCache.javaindex 95bf937b6..b77078d84 100644--- a/source/de/anomic/kelondro/text/ReferenceContainerCache.java+++ b/source/de/anomic/kelondro/text/ReferenceContainerCache.java@@ -1,453 +1,453 @@-// indexContainerCache.java-// (C) 2008 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 30.03.2008 on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2008-03-14 01:16:04 +0100 (Fr, 14 Mrz 2008) $-// $LastChangedRevision: 4558 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import java.io.File;-import java.io.IOException;-import java.util.ArrayList;-import java.util.Collections;-import java.util.Iterator;-import java.util.Map;-import java.util.Set;-import java.util.SortedMap;-import java.util.TreeMap;--import de.anomic.kelondro.blob.HeapReader;-import de.anomic.kelondro.blob.HeapWriter;-import de.anomic.kelondro.order.CloneableIterator;-import de.anomic.kelondro.order.Base64Order;-import de.anomic.kelondro.order.ByteOrder;-import de.anomic.kelondro.util.Log;-import de.anomic.kelondro.index.Row;-import de.anomic.kelondro.index.RowSet;--public final class ReferenceContainerCache extends AbstractIndex implements Index, IndexReader, Iterable<ReferenceContainer> {-- private final Row payloadrow;- private final ByteOrder wordOrder;- private SortedMap<String, ReferenceContainer> cache;-- /**- * opens an existing heap file in undefined mode- * after this a initialization should be made to use the heap:- * either a read-only or read/write mode initialization- * @param payloadrow- * @param log- */- public ReferenceContainerCache(final Row payloadrow, ByteOrder wordOrder) {- this.payloadrow = payloadrow;- this.wordOrder = wordOrder;- this.cache = null;- }-- public Row rowdef() {- return this.payloadrow;- }-- public void clear() {- if (cache != null) cache.clear();- initWriteMode();- }-- public void close() {- this.cache = null;- }-- /**- * initializes the heap in read/write mode without reading of a dump first- * another dump reading afterwards is not possible- */- public void initWriteMode() {- this.cache = Collections.synchronizedSortedMap(new TreeMap<String, ReferenceContainer>(new ByteOrder.StringOrder(this.wordOrder)));- }-- /**- * this is the new cache file format initialization- * @param heapFile- * @throws IOException- */- public void initWriteModeFromBLOB(final File blobFile) throws IOException {- Log.logInfo("indexContainerRAMHeap", "restoring rwi blob dump '" + blobFile.getName() + "'");- final long start = System.currentTimeMillis();- this.cache = Collections.synchronizedSortedMap(new TreeMap<String, ReferenceContainer>(new ByteOrder.StringOrder(this.wordOrder)));- int urlCount = 0;- synchronized (cache) {- for (final ReferenceContainer container : new blobFileEntries(blobFile, this.payloadrow)) {- // TODO: in this loop a lot of memory may be allocated. A check if the memory gets low is necessary. But what do when the memory is low?- if (container == null) break;- //System.out.println("***DEBUG indexContainerHeap.initwriteModeFromBLOB*** container.size = " + container.size() + ", container.sorted = " + container.sorted());- cache.put(container.getWordHash(), container);- urlCount += container.size();- }- }- // remove idx and gap files if they exist here- HeapWriter.deleteAllFingerprints(blobFile);- Log.logInfo("indexContainerRAMHeap", "finished rwi blob restore: " + cache.size() + " words, " + urlCount + " word/URL relations in " + (System.currentTimeMillis() - start) + " milliseconds");- }-- public void dump(final File heapFile, boolean writeIDX) throws IOException {- assert this.cache != null;- Log.logInfo("indexContainerRAMHeap", "creating rwi heap dump '" + heapFile.getName() + "', " + cache.size() + " rwi's");- if (heapFile.exists()) heapFile.delete();- HeapWriter dump = new HeapWriter(heapFile, payloadrow.primaryKeyLength, Base64Order.enhancedCoder);- final long startTime = System.currentTimeMillis();- long wordcount = 0, urlcount = 0;- String wordHash = null, lwh;- ReferenceContainer container;-- // write wCache- synchronized (cache) {- for (final Map.Entry<String, ReferenceContainer> entry: cache.entrySet()) {- // get entries- lwh = wordHash;- wordHash = entry.getKey();- container = entry.getValue();-- // check consistency: entries must be ordered- assert (lwh == null || this.ordering().compare(wordHash.getBytes(), lwh.getBytes()) > 0);-- // put entries on heap- if (container != null && wordHash.length() == payloadrow.primaryKeyLength) {- //System.out.println("Dump: " + wordHash);- dump.add(wordHash.getBytes(), container.exportCollection());- urlcount += container.size();- }- wordcount++;- }- }- dump.close(writeIDX);- dump = null;- Log.logInfo("indexContainerRAMHeap", "finished alternative rwi heap dump: " + wordcount + " words, " + urlcount + " word/URL relations in " + (System.currentTimeMillis() - startTime) + " milliseconds");- }-- public int size() {- return (this.cache == null) ? 0 : this.cache.size();- }-- /**- * static iterator of BLOBHeap files: is used to import heap dumps into a write-enabled index heap- */- public static class blobFileEntries implements CloneableIterator<ReferenceContainer>, Iterable<ReferenceContainer> {- Iterator<Map.Entry<String, byte[]>> blobs;- Row payloadrow;- File blobFile;-- public blobFileEntries(final File blobFile, final Row payloadrow) throws IOException {- this.blobs = new HeapReader.entries(blobFile, payloadrow.primaryKeyLength);- this.payloadrow = payloadrow;- this.blobFile = blobFile;- }-- public boolean hasNext() {- return blobs.hasNext();- }-- /**- * return an index container- * because they may get very large, it is wise to deallocate some memory before calling next()- */- public ReferenceContainer next() {- Map.Entry<String, byte[]> entry = blobs.next();- byte[] payload = entry.getValue();- return new ReferenceContainer(entry.getKey(), RowSet.importRowSet(payload, payloadrow));- }-- public void remove() {- throw new UnsupportedOperationException("heap dumps are read-only");- }-- public Iterator<ReferenceContainer> iterator() {- return this;- }-- public void close() {- blobs = null;- }-- protected void finalize() {- this.close();- }-- public CloneableIterator<ReferenceContainer> clone(Object modifier) {- try {- return new blobFileEntries(this.blobFile, this.payloadrow);- } catch (IOException e) {- e.printStackTrace();- return null;- }- }- }-- public synchronized int maxReferences() {- // iterate to find the max score- int max = 0;- for (ReferenceContainer container : cache.values()) {- if (container.size() > max) max = container.size();- }- return max;- }-- public synchronized String maxReferencesHash() {- // iterate to find the max score- int max = 0;- String hash = null;- for (ReferenceContainer container : cache.values()) {- if (container.size() > max) {- max = container.size();- hash = container.getWordHash();- }- }- return hash;- }-- public synchronized ArrayList<String> maxReferencesHash(int bound) {- // iterate to find the max score- ArrayList<String> hashes = new ArrayList<String>();- for (ReferenceContainer container : cache.values()) {- if (container.size() >= bound) {- hashes.add(container.getWordHash());- }- }- return hashes;- }-- public synchronized ReferenceContainer latest() {- ReferenceContainer c = null;- for (ReferenceContainer container : cache.values()) {- if (c == null) {c = container; continue;}- if (container.lastWrote() > c.lastWrote()) {c = container; continue;}- }- return c;- }-- public synchronized ReferenceContainer first() {- ReferenceContainer c = null;- for (ReferenceContainer container : cache.values()) {- if (c == null) {c = container; continue;}- if (container.lastWrote() < c.lastWrote()) {c = container; continue;}- }- return c;- }-- public synchronized ArrayList<String> overAge(long maxage) {- ArrayList<String> hashes = new ArrayList<String>();- long limit = System.currentTimeMillis() - maxage;- for (ReferenceContainer container : cache.values()) {- if (container.lastWrote() < limit) hashes.add(container.getWordHash());- }- return hashes;- }-- /**- * return an iterator object that creates top-level-clones of the indexContainers- * in the cache, so that manipulations of the iterated objects do not change- * objects in the cache.- */- public synchronized CloneableIterator<ReferenceContainer> references(final String startWordHash, final boolean rot) {- return new heapCacheIterator(startWordHash, rot);- }--- public Iterator<ReferenceContainer> iterator() {- return references(null, false);- }--- /**- * cache iterator: iterates objects within the heap cache. This can only be used- * for write-enabled heaps, read-only heaps do not have a heap cache- */- public class heapCacheIterator implements CloneableIterator<ReferenceContainer>, Iterable<ReferenceContainer> {-- // this class exists, because the wCache cannot be iterated with rotation- // and because every indexContainer Object that is iterated must be returned as top-level-clone- // so this class simulates wCache.tailMap(startWordHash).values().iterator()- // plus the mentioned features-- private final boolean rot;- private Iterator<ReferenceContainer> iterator;-- public heapCacheIterator(final String startWordHash, final boolean rot) {- this.rot = rot;- this.iterator = (startWordHash == null) ? cache.values().iterator() : cache.tailMap(startWordHash).values().iterator();- // The collection's iterator will return the values in the order that their corresponding keys appear in the tree.- }-- public heapCacheIterator clone(final Object secondWordHash) {- return new heapCacheIterator((String) secondWordHash, rot);- }-- public boolean hasNext() {- if (rot) return true;- return iterator.hasNext();- }-- public ReferenceContainer next() {- if (iterator.hasNext()) {- return (iterator.next()).topLevelClone();- }- // rotation iteration- if (!rot) {- return null;- }- iterator = cache.values().iterator();- return (iterator.next()).topLevelClone();- }-- public void remove() {- iterator.remove();- }-- public Iterator<ReferenceContainer> iterator() {- return this;- }-- }-- /**- * test if a given key is in the heap- * this works with heaps in write- and read-mode- * @param key- * @return true, if the key is used in the heap; false othervise- */- public boolean has(final String key) {- return this.cache.containsKey(key);- }-- /**- * get a indexContainer from a heap- * @param key- * @return the indexContainer if one exist, null otherwise- */- public ReferenceContainer get(final String key, Set<String> urlselection) {- if (urlselection == null) return this.cache.get(key);- ReferenceContainer c = this.cache.get(key);- if (c == null) return null;- // because this is all in RAM, we must clone the entries (flat)- ReferenceContainer c1 = new ReferenceContainer(c.getWordHash(), c.row(), c.size());- Iterator<ReferenceRow> e = c.entries();- ReferenceRow ee;- while (e.hasNext()) {- ee = e.next();- if (urlselection.contains(ee.urlHash())) c1.add(ee);- }- return c1;- }-- /**- * return the size of the container with corresponding key- * @param key- * @return- */- public int count(final String key) {- ReferenceContainer c = this.cache.get(key);- if (c == null) return 0;- return c.size();- }-- /**- * delete a indexContainer from the heap cache. This can only be used for write-enabled heaps- * @param wordHash- * @return the indexContainer if the cache contained the container, null othervise- */- public synchronized ReferenceContainer delete(final String wordHash) {- // returns the index that had been deleted- assert this.cache != null;- return cache.remove(wordHash);- }-- public synchronized boolean remove(final String wordHash, final String urlHash) {- assert this.cache != null;- final ReferenceContainer c = cache.get(wordHash);- if ((c != null) && (c.remove(urlHash) != null)) {- // removal successful- if (c.size() == 0) {- delete(wordHash);- } else {- cache.put(wordHash, c);- }- return true;- }- return false;- }-- public synchronized int remove(final String wordHash, final Set<String> urlHashes) {- assert this.cache != null;- if (urlHashes.size() == 0) return 0;- final ReferenceContainer c = cache.get(wordHash);- int count;- if ((c != null) && ((count = c.removeEntries(urlHashes)) > 0)) {- // removal successful- if (c.size() == 0) {- delete(wordHash);- } else {- cache.put(wordHash, c);- }- return count;- }- return 0;- }-- public synchronized void add(final ReferenceContainer container) {- // this puts the entries into the cache- int added = 0;- if ((container == null) || (container.size() == 0)) return;- assert this.cache != null;-- // put new words into cache- final String wordHash = container.getWordHash();- ReferenceContainer entries = cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null- if (entries == null) {- entries = container.topLevelClone();- added = entries.size();- } else {- added = entries.putAllRecent(container);- }- if (added > 0) {- cache.put(wordHash, entries);- }- entries = null;- return;- }-- public synchronized void add(final String wordHash, final ReferenceRow newEntry) {- assert this.cache != null;- ReferenceContainer container = cache.get(wordHash);- if (container == null) container = new ReferenceContainer(wordHash, this.payloadrow, 1);- container.put(newEntry);- cache.put(wordHash, container);- }-- public int minMem() {- return 0;- }-- public ByteOrder ordering() {- return this.wordOrder;- }--}+// indexContainerCache.java+// (C) 2008 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 30.03.2008 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import java.io.File;+import java.io.IOException;+import java.util.ArrayList;+import java.util.Collections;+import java.util.Iterator;+import java.util.Map;+import java.util.Set;+import java.util.SortedMap;+import java.util.TreeMap;++import de.anomic.kelondro.blob.HeapReader;+import de.anomic.kelondro.blob.HeapWriter;+import de.anomic.kelondro.order.CloneableIterator;+import de.anomic.kelondro.order.Base64Order;+import de.anomic.kelondro.order.ByteOrder;+import de.anomic.kelondro.util.Log;+import de.anomic.kelondro.index.Row;+import de.anomic.kelondro.index.RowSet;++public final class ReferenceContainerCache extends AbstractIndex implements Index, IndexReader, Iterable<ReferenceContainer> {++ private final Row payloadrow;+ private final ByteOrder wordOrder;+ private SortedMap<String, ReferenceContainer> cache;++ /**+ * opens an existing heap file in undefined mode+ * after this a initialization should be made to use the heap:+ * either a read-only or read/write mode initialization+ * @param payloadrow+ * @param log+ */+ public ReferenceContainerCache(final Row payloadrow, ByteOrder wordOrder) {+ this.payloadrow = payloadrow;+ this.wordOrder = wordOrder;+ this.cache = null;+ }++ public Row rowdef() {+ return this.payloadrow;+ }++ public void clear() {+ if (cache != null) cache.clear();+ initWriteMode();+ }++ public void close() {+ this.cache = null;+ }++ /**+ * initializes the heap in read/write mode without reading of a dump first+ * another dump reading afterwards is not possible+ */+ public void initWriteMode() {+ this.cache = Collections.synchronizedSortedMap(new TreeMap<String, ReferenceContainer>(new ByteOrder.StringOrder(this.wordOrder)));+ }++ /**+ * this is the new cache file format initialization+ * @param heapFile+ * @throws IOException+ */+ public void initWriteModeFromBLOB(final File blobFile) throws IOException {+ Log.logInfo("indexContainerRAMHeap", "restoring rwi blob dump '" + blobFile.getName() + "'");+ final long start = System.currentTimeMillis();+ this.cache = Collections.synchronizedSortedMap(new TreeMap<String, ReferenceContainer>(new ByteOrder.StringOrder(this.wordOrder)));+ int urlCount = 0;+ synchronized (cache) {+ for (final ReferenceContainer container : new blobFileEntries(blobFile, this.payloadrow)) {+ // TODO: in this loop a lot of memory may be allocated. A check if the memory gets low is necessary. But what do when the memory is low?+ if (container == null) break;+ //System.out.println("***DEBUG indexContainerHeap.initwriteModeFromBLOB*** container.size = " + container.size() + ", container.sorted = " + container.sorted());+ cache.put(container.getWordHash(), container);+ urlCount += container.size();+ }+ }+ // remove idx and gap files if they exist here+ HeapWriter.deleteAllFingerprints(blobFile);+ Log.logInfo("indexContainerRAMHeap", "finished rwi blob restore: " + cache.size() + " words, " + urlCount + " word/URL relations in " + (System.currentTimeMillis() - start) + " milliseconds");+ }++ public void dump(final File heapFile, boolean writeIDX) throws IOException {+ assert this.cache != null;+ Log.logInfo("indexContainerRAMHeap", "creating rwi heap dump '" + heapFile.getName() + "', " + cache.size() + " rwi's");+ if (heapFile.exists()) heapFile.delete();+ HeapWriter dump = new HeapWriter(heapFile, payloadrow.primaryKeyLength, Base64Order.enhancedCoder);+ final long startTime = System.currentTimeMillis();+ long wordcount = 0, urlcount = 0;+ String wordHash = null, lwh;+ ReferenceContainer container;++ // write wCache+ synchronized (cache) {+ for (final Map.Entry<String, ReferenceContainer> entry: cache.entrySet()) {+ // get entries+ lwh = wordHash;+ wordHash = entry.getKey();+ container = entry.getValue();++ // check consistency: entries must be ordered+ assert (lwh == null || this.ordering().compare(wordHash.getBytes(), lwh.getBytes()) > 0);++ // put entries on heap+ if (container != null && wordHash.length() == payloadrow.primaryKeyLength) {+ //System.out.println("Dump: " + wordHash);+ dump.add(wordHash.getBytes(), container.exportCollection());+ urlcount += container.size();+ }+ wordcount++;+ }+ }+ dump.close(writeIDX);+ dump = null;+ Log.logInfo("indexContainerRAMHeap", "finished alternative rwi heap dump: " + wordcount + " words, " + urlcount + " word/URL relations in " + (System.currentTimeMillis() - startTime) + " milliseconds");+ }++ public int size() {+ return (this.cache == null) ? 0 : this.cache.size();+ }++ /**+ * static iterator of BLOBHeap files: is used to import heap dumps into a write-enabled index heap+ */+ public static class blobFileEntries implements CloneableIterator<ReferenceContainer>, Iterable<ReferenceContainer> {+ Iterator<Map.Entry<String, byte[]>> blobs;+ Row payloadrow;+ File blobFile;++ public blobFileEntries(final File blobFile, final Row payloadrow) throws IOException {+ this.blobs = new HeapReader.entries(blobFile, payloadrow.primaryKeyLength);+ this.payloadrow = payloadrow;+ this.blobFile = blobFile;+ }++ public boolean hasNext() {+ return blobs.hasNext();+ }++ /**+ * return an index container+ * because they may get very large, it is wise to deallocate some memory before calling next()+ */+ public ReferenceContainer next() {+ Map.Entry<String, byte[]> entry = blobs.next();+ byte[] payload = entry.getValue();+ return new ReferenceContainer(entry.getKey(), RowSet.importRowSet(payload, payloadrow));+ }++ public void remove() {+ throw new UnsupportedOperationException("heap dumps are read-only");+ }++ public Iterator<ReferenceContainer> iterator() {+ return this;+ }++ public void close() {+ blobs = null;+ }++ protected void finalize() {+ this.close();+ }++ public CloneableIterator<ReferenceContainer> clone(Object modifier) {+ try {+ return new blobFileEntries(this.blobFile, this.payloadrow);+ } catch (IOException e) {+ e.printStackTrace();+ return null;+ }+ }+ }++ public synchronized int maxReferences() {+ // iterate to find the max score+ int max = 0;+ for (ReferenceContainer container : cache.values()) {+ if (container.size() > max) max = container.size();+ }+ return max;+ }++ public synchronized String maxReferencesHash() {+ // iterate to find the max score+ int max = 0;+ String hash = null;+ for (ReferenceContainer container : cache.values()) {+ if (container.size() > max) {+ max = container.size();+ hash = container.getWordHash();+ }+ }+ return hash;+ }++ public synchronized ArrayList<String> maxReferencesHash(int bound) {+ // iterate to find the max score+ ArrayList<String> hashes = new ArrayList<String>();+ for (ReferenceContainer container : cache.values()) {+ if (container.size() >= bound) {+ hashes.add(container.getWordHash());+ }+ }+ return hashes;+ }++ public synchronized ReferenceContainer latest() {+ ReferenceContainer c = null;+ for (ReferenceContainer container : cache.values()) {+ if (c == null) {c = container; continue;}+ if (container.lastWrote() > c.lastWrote()) {c = container; continue;}+ }+ return c;+ }++ public synchronized ReferenceContainer first() {+ ReferenceContainer c = null;+ for (ReferenceContainer container : cache.values()) {+ if (c == null) {c = container; continue;}+ if (container.lastWrote() < c.lastWrote()) {c = container; continue;}+ }+ return c;+ }++ public synchronized ArrayList<String> overAge(long maxage) {+ ArrayList<String> hashes = new ArrayList<String>();+ long limit = System.currentTimeMillis() - maxage;+ for (ReferenceContainer container : cache.values()) {+ if (container.lastWrote() < limit) hashes.add(container.getWordHash());+ }+ return hashes;+ }++ /**+ * return an iterator object that creates top-level-clones of the indexContainers+ * in the cache, so that manipulations of the iterated objects do not change+ * objects in the cache.+ */+ public synchronized CloneableIterator<ReferenceContainer> references(final String startWordHash, final boolean rot) {+ return new heapCacheIterator(startWordHash, rot);+ }+++ public Iterator<ReferenceContainer> iterator() {+ return references(null, false);+ }+++ /**+ * cache iterator: iterates objects within the heap cache. This can only be used+ * for write-enabled heaps, read-only heaps do not have a heap cache+ */+ public class heapCacheIterator implements CloneableIterator<ReferenceContainer>, Iterable<ReferenceContainer> {++ // this class exists, because the wCache cannot be iterated with rotation+ // and because every indexContainer Object that is iterated must be returned as top-level-clone+ // so this class simulates wCache.tailMap(startWordHash).values().iterator()+ // plus the mentioned features++ private final boolean rot;+ private Iterator<ReferenceContainer> iterator;++ public heapCacheIterator(final String startWordHash, final boolean rot) {+ this.rot = rot;+ this.iterator = (startWordHash == null) ? cache.values().iterator() : cache.tailMap(startWordHash).values().iterator();+ // The collection's iterator will return the values in the order that their corresponding keys appear in the tree.+ }++ public heapCacheIterator clone(final Object secondWordHash) {+ return new heapCacheIterator((String) secondWordHash, rot);+ }++ public boolean hasNext() {+ if (rot) return true;+ return iterator.hasNext();+ }++ public ReferenceContainer next() {+ if (iterator.hasNext()) {+ return (iterator.next()).topLevelClone();+ }+ // rotation iteration+ if (!rot) {+ return null;+ }+ iterator = cache.values().iterator();+ return (iterator.next()).topLevelClone();+ }++ public void remove() {+ iterator.remove();+ }++ public Iterator<ReferenceContainer> iterator() {+ return this;+ }++ }++ /**+ * test if a given key is in the heap+ * this works with heaps in write- and read-mode+ * @param key+ * @return true, if the key is used in the heap; false othervise+ */+ public boolean has(final String key) {+ return this.cache.containsKey(key);+ }++ /**+ * get a indexContainer from a heap+ * @param key+ * @return the indexContainer if one exist, null otherwise+ */+ public ReferenceContainer get(final String key, Set<String> urlselection) {+ if (urlselection == null) return this.cache.get(key);+ ReferenceContainer c = this.cache.get(key);+ if (c == null) return null;+ // because this is all in RAM, we must clone the entries (flat)+ ReferenceContainer c1 = new ReferenceContainer(c.getWordHash(), c.row(), c.size());+ Iterator<ReferenceRow> e = c.entries();+ ReferenceRow ee;+ while (e.hasNext()) {+ ee = e.next();+ if (urlselection.contains(ee.urlHash())) c1.add(ee);+ }+ return c1;+ }++ /**+ * return the size of the container with corresponding key+ * @param key+ * @return+ */+ public int count(final String key) {+ ReferenceContainer c = this.cache.get(key);+ if (c == null) return 0;+ return c.size();+ }++ /**+ * delete a indexContainer from the heap cache. This can only be used for write-enabled heaps+ * @param wordHash+ * @return the indexContainer if the cache contained the container, null othervise+ */+ public synchronized ReferenceContainer delete(final String wordHash) {+ // returns the index that had been deleted+ assert this.cache != null;+ return cache.remove(wordHash);+ }++ public synchronized boolean remove(final String wordHash, final String urlHash) {+ assert this.cache != null;+ final ReferenceContainer c = cache.get(wordHash);+ if ((c != null) && (c.remove(urlHash) != null)) {+ // removal successful+ if (c.size() == 0) {+ delete(wordHash);+ } else {+ cache.put(wordHash, c);+ }+ return true;+ }+ return false;+ }++ public synchronized int remove(final String wordHash, final Set<String> urlHashes) {+ assert this.cache != null;+ if (urlHashes.size() == 0) return 0;+ final ReferenceContainer c = cache.get(wordHash);+ int count;+ if ((c != null) && ((count = c.removeEntries(urlHashes)) > 0)) {+ // removal successful+ if (c.size() == 0) {+ delete(wordHash);+ } else {+ cache.put(wordHash, c);+ }+ return count;+ }+ return 0;+ }++ public synchronized void add(final ReferenceContainer container) {+ // this puts the entries into the cache+ int added = 0;+ if ((container == null) || (container.size() == 0)) return;+ assert this.cache != null;++ // put new words into cache+ final String wordHash = container.getWordHash();+ ReferenceContainer entries = cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null+ if (entries == null) {+ entries = container.topLevelClone();+ added = entries.size();+ } else {+ added = entries.putAllRecent(container);+ }+ if (added > 0) {+ cache.put(wordHash, entries);+ }+ entries = null;+ return;+ }++ public synchronized void add(final String wordHash, final ReferenceRow newEntry) {+ assert this.cache != null;+ ReferenceContainer container = cache.get(wordHash);+ if (container == null) container = new ReferenceContainer(wordHash, this.payloadrow, 1);+ container.put(newEntry);+ cache.put(wordHash, container);+ }++ public int minMem() {+ return 0;+ }++ public ByteOrder ordering() {+ return this.wordOrder;+ }++}diff --git a/source/de/anomic/kelondro/text/ReferenceContainerMerger.java b/source/de/anomic/kelondro/text/ReferenceContainerMerger.javaindex f620c589f..585cdd296 100644--- a/source/de/anomic/kelondro/text/ReferenceContainerMerger.java+++ b/source/de/anomic/kelondro/text/ReferenceContainerMerger.java@@ -1,263 +1,263 @@-// ReferenceContainerArray.java-// (C) 2009 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 20.03.2009 on http://yacy.net-//-// $LastChangedDate: 2008-03-14 01:16:04 +0100 (Fr, 14 Mrz 2008) $-// $LastChangedRevision: 4558 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import java.io.File;-import java.io.IOException;-import java.util.concurrent.ArrayBlockingQueue;--import de.anomic.kelondro.blob.BLOBArray;-import de.anomic.kelondro.blob.HeapWriter;-import de.anomic.kelondro.index.Row;-import de.anomic.kelondro.order.ByteOrder;-import de.anomic.kelondro.order.CloneableIterator;-import de.anomic.kelondro.text.ReferenceContainerCache.blobFileEntries;--/**- * merger class for files from ReferenceContainerArray.- * this is a concurrent merger that can merge single files that are queued for merging.- * when several ReferenceContainerArray classes host their ReferenceContainer file arrays,- * they may share a single ReferenceContainerMerger object which does the sharing for all- * of them. This is the best way to do the merging, because it does heavy IO access and- * such access should not be performed concurrently, but queued. This class is the- * manaagement class for queueing of merge jobs.- *- * to use this class, first instantiate a object and then start the concurrent execution- * of merging with a call to the start() - method. To shut down all mergings, call terminate()- * only once.- */-public class ReferenceContainerMerger extends Thread {-- private Job poison;- private ArrayBlockingQueue<Job> queue;- private ArrayBlockingQueue<Job> termi;-- public ReferenceContainerMerger(int queueLength) {- this.poison = new Job();- this.queue = new ArrayBlockingQueue<Job>(queueLength);- this.termi = new ArrayBlockingQueue<Job>(1);- }-- public synchronized void terminate() {- if (queue == null || !this.isAlive()) return;- try {- queue.put(poison);- } catch (InterruptedException e) {- e.printStackTrace();- }- // await termination- try {- termi.take();- } catch (InterruptedException e) {- e.printStackTrace();- }- }-- public synchronized void merge(File f1, File f2, BLOBArray array, Row payloadrow, File newFile) {- if (queue == null || !this.isAlive()) {- try {- mergeMount(f1, f2, array, payloadrow, newFile);- } catch (IOException e) {- e.printStackTrace();- }- } else {- Job job = new Job(f1, f2, array, payloadrow, newFile);- try {- queue.put(job);- } catch (InterruptedException e) {- e.printStackTrace();- try {- mergeMount(f1, f2, array, payloadrow, newFile);- } catch (IOException ee) {- ee.printStackTrace();- }- }- }- }-- public void run() {- Job job;- try {- while ((job = queue.take()) != poison) {- job.merge();- }- } catch (InterruptedException e) {- e.printStackTrace();- } finally {- try {- termi.put(poison);- } catch (InterruptedException e) {- e.printStackTrace();- }- }- }-- public class Job {-- File f1, f2, newFile;- BLOBArray array;- Row payloadrow;-- public Job() {- this.f1 = null;- this.f2 = null;- this.newFile = null;- this.array = null;- this.payloadrow = null;- }-- public Job(File f1, File f2, BLOBArray array, Row payloadrow, File newFile) {- this.f1 = f1;- this.f2 = f2;- this.newFile = newFile;- this.array = array;- this.payloadrow = payloadrow;- }-- public File merge() {- try {- return mergeMount(f1, f2, array, payloadrow, newFile);- } catch (IOException e) {- e.printStackTrace();- }- return null;- }- }-- public static File mergeMount(File f1, File f2, BLOBArray array, Row payloadrow, File newFile) throws IOException {- System.out.println("*** DEBUG mergeOldest: vvvvvvvvv array has " + array.entries() + " entries vvvvvvvvv");- System.out.println("*** DEBUG mergeOldest: unmounted " + f1.getName());- System.out.println("*** DEBUG mergeOldest: unmounted " + f2.getName());- File resultFile = mergeWorker(f1, f2, array, payloadrow, newFile);- if (resultFile == null) return null;- array.mountBLOB(resultFile);- System.out.println("*** DEBUG mergeOldest: mounted " + newFile.getName());- System.out.println("*** DEBUG mergeOldest: ^^^^^^^^^^^ array has " + array.entries() + " entries ^^^^^^^^^^^");- return resultFile;- }-- private static File mergeWorker(File f1, File f2, BLOBArray array, Row payloadrow, File newFile) throws IOException {- // iterate both files and write a new one-- CloneableIterator<ReferenceContainer> i1 = new blobFileEntries(f1, payloadrow);- CloneableIterator<ReferenceContainer> i2 = new blobFileEntries(f2, payloadrow);- if (!i1.hasNext()) {- if (i2.hasNext()) {- if (!f1.delete()) f1.deleteOnExit();- if (f2.renameTo(newFile)) return newFile;- return f2;- } else {- if (!f1.delete()) f1.deleteOnExit();- if (!f2.delete()) f2.deleteOnExit();- return null;- }- } else if (!i2.hasNext()) {- if (!f2.delete()) f2.deleteOnExit();- if (f1.renameTo(newFile)) return newFile;- return f1;- }- assert i1.hasNext();- assert i2.hasNext();- HeapWriter writer = new HeapWriter(newFile, array.keylength(), array.ordering());- merge(i1, i2, array.ordering(), writer);- writer.close(true);- // we don't need the old files any more- if (!f1.delete()) f1.deleteOnExit();- if (!f2.delete()) f2.deleteOnExit();- return newFile;- }-- private static void merge(CloneableIterator<ReferenceContainer> i1, CloneableIterator<ReferenceContainer> i2, ByteOrder ordering, HeapWriter writer) throws IOException {- assert i1.hasNext();- assert i2.hasNext();- ReferenceContainer c1, c2, c1o, c2o;- c1 = i1.next();- c2 = i2.next();- int e;- while (true) {- assert c1 != null;- assert c2 != null;- e = ordering.compare(c1.getWordHash().getBytes(), c2.getWordHash().getBytes());- if (e < 0) {- writer.add(c1.getWordHash().getBytes(), c1.exportCollection());- if (i1.hasNext()) {- c1o = c1;- c1 = i1.next();- assert ordering.compare(c1.getWordHash().getBytes(), c1o.getWordHash().getBytes()) > 0;- continue;- }- break;- }- if (e > 0) {- writer.add(c2.getWordHash().getBytes(), c2.exportCollection());- if (i2.hasNext()) {- c2o = c2;- c2 = i2.next();- assert ordering.compare(c2.getWordHash().getBytes(), c2o.getWordHash().getBytes()) > 0;- continue;- }- break;- }- assert e == 0;- // merge the entries- writer.add(c1.getWordHash().getBytes(), (c1.merge(c2)).exportCollection());- if (i1.hasNext() && i2.hasNext()) {- c1 = i1.next();- c2 = i2.next();- continue;- }- if (i1.hasNext()) c1 = i1.next();- if (i2.hasNext()) c2 = i2.next();- break;-- }- // catch up remaining entries- assert !(i1.hasNext() && i2.hasNext());- while (i1.hasNext()) {- //System.out.println("FLUSH REMAINING 1: " + c1.getWordHash());- writer.add(c1.getWordHash().getBytes(), c1.exportCollection());- if (i1.hasNext()) {- c1o = c1;- c1 = i1.next();- assert ordering.compare(c1.getWordHash().getBytes(), c1o.getWordHash().getBytes()) > 0;- continue;- }- break;- }- while (i2.hasNext()) {- //System.out.println("FLUSH REMAINING 2: " + c2.getWordHash());- writer.add(c2.getWordHash().getBytes(), c2.exportCollection());- if (i2.hasNext()) {- c2o = c2;- c2 = i2.next();- assert ordering.compare(c2.getWordHash().getBytes(), c2o.getWordHash().getBytes()) > 0;- continue;- }- break;- }- // finished with writing- }--}+// ReferenceContainerArray.java+// (C) 2009 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 20.03.2009 on http://yacy.net+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import java.io.File;+import java.io.IOException;+import java.util.concurrent.ArrayBlockingQueue;++import de.anomic.kelondro.blob.BLOBArray;+import de.anomic.kelondro.blob.HeapWriter;+import de.anomic.kelondro.index.Row;+import de.anomic.kelondro.order.ByteOrder;+import de.anomic.kelondro.order.CloneableIterator;+import de.anomic.kelondro.text.ReferenceContainerCache.blobFileEntries;++/**+ * merger class for files from ReferenceContainerArray.+ * this is a concurrent merger that can merge single files that are queued for merging.+ * when several ReferenceContainerArray classes host their ReferenceContainer file arrays,+ * they may share a single ReferenceContainerMerger object which does the sharing for all+ * of them. This is the best way to do the merging, because it does heavy IO access and+ * such access should not be performed concurrently, but queued. This class is the+ * manaagement class for queueing of merge jobs.+ *+ * to use this class, first instantiate a object and then start the concurrent execution+ * of merging with a call to the start() - method. To shut down all mergings, call terminate()+ * only once.+ */+public class ReferenceContainerMerger extends Thread {++ private Job poison;+ private ArrayBlockingQueue<Job> queue;+ private ArrayBlockingQueue<Job> termi;++ public ReferenceContainerMerger(int queueLength) {+ this.poison = new Job();+ this.queue = new ArrayBlockingQueue<Job>(queueLength);+ this.termi = new ArrayBlockingQueue<Job>(1);+ }++ public synchronized void terminate() {+ if (queue == null || !this.isAlive()) return;+ try {+ queue.put(poison);+ } catch (InterruptedException e) {+ e.printStackTrace();+ }+ // await termination+ try {+ termi.take();+ } catch (InterruptedException e) {+ e.printStackTrace();+ }+ }++ public synchronized void merge(File f1, File f2, BLOBArray array, Row payloadrow, File newFile) {+ if (queue == null || !this.isAlive()) {+ try {+ mergeMount(f1, f2, array, payloadrow, newFile);+ } catch (IOException e) {+ e.printStackTrace();+ }+ } else {+ Job job = new Job(f1, f2, array, payloadrow, newFile);+ try {+ queue.put(job);+ } catch (InterruptedException e) {+ e.printStackTrace();+ try {+ mergeMount(f1, f2, array, payloadrow, newFile);+ } catch (IOException ee) {+ ee.printStackTrace();+ }+ }+ }+ }++ public void run() {+ Job job;+ try {+ while ((job = queue.take()) != poison) {+ job.merge();+ }+ } catch (InterruptedException e) {+ e.printStackTrace();+ } finally {+ try {+ termi.put(poison);+ } catch (InterruptedException e) {+ e.printStackTrace();+ }+ }+ }++ public class Job {++ File f1, f2, newFile;+ BLOBArray array;+ Row payloadrow;++ public Job() {+ this.f1 = null;+ this.f2 = null;+ this.newFile = null;+ this.array = null;+ this.payloadrow = null;+ }++ public Job(File f1, File f2, BLOBArray array, Row payloadrow, File newFile) {+ this.f1 = f1;+ this.f2 = f2;+ this.newFile = newFile;+ this.array = array;+ this.payloadrow = payloadrow;+ }++ public File merge() {+ try {+ return mergeMount(f1, f2, array, payloadrow, newFile);+ } catch (IOException e) {+ e.printStackTrace();+ }+ return null;+ }+ }++ public static File mergeMount(File f1, File f2, BLOBArray array, Row payloadrow, File newFile) throws IOException {+ System.out.println("*** DEBUG mergeOldest: vvvvvvvvv array has " + array.entries() + " entries vvvvvvvvv");+ System.out.println("*** DEBUG mergeOldest: unmounted " + f1.getName());+ System.out.println("*** DEBUG mergeOldest: unmounted " + f2.getName());+ File resultFile = mergeWorker(f1, f2, array, payloadrow, newFile);+ if (resultFile == null) return null;+ array.mountBLOB(resultFile);+ System.out.println("*** DEBUG mergeOldest: mounted " + newFile.getName());+ System.out.println("*** DEBUG mergeOldest: ^^^^^^^^^^^ array has " + array.entries() + " entries ^^^^^^^^^^^");+ return resultFile;+ }++ private static File mergeWorker(File f1, File f2, BLOBArray array, Row payloadrow, File newFile) throws IOException {+ // iterate both files and write a new one++ CloneableIterator<ReferenceContainer> i1 = new blobFileEntries(f1, payloadrow);+ CloneableIterator<ReferenceContainer> i2 = new blobFileEntries(f2, payloadrow);+ if (!i1.hasNext()) {+ if (i2.hasNext()) {+ if (!f1.delete()) f1.deleteOnExit();+ if (f2.renameTo(newFile)) return newFile;+ return f2;+ } else {+ if (!f1.delete()) f1.deleteOnExit();+ if (!f2.delete()) f2.deleteOnExit();+ return null;+ }+ } else if (!i2.hasNext()) {+ if (!f2.delete()) f2.deleteOnExit();+ if (f1.renameTo(newFile)) return newFile;+ return f1;+ }+ assert i1.hasNext();+ assert i2.hasNext();+ HeapWriter writer = new HeapWriter(newFile, array.keylength(), array.ordering());+ merge(i1, i2, array.ordering(), writer);+ writer.close(true);+ // we don't need the old files any more+ if (!f1.delete()) f1.deleteOnExit();+ if (!f2.delete()) f2.deleteOnExit();+ return newFile;+ }++ private static void merge(CloneableIterator<ReferenceContainer> i1, CloneableIterator<ReferenceContainer> i2, ByteOrder ordering, HeapWriter writer) throws IOException {+ assert i1.hasNext();+ assert i2.hasNext();+ ReferenceContainer c1, c2, c1o, c2o;+ c1 = i1.next();+ c2 = i2.next();+ int e;+ while (true) {+ assert c1 != null;+ assert c2 != null;+ e = ordering.compare(c1.getWordHash().getBytes(), c2.getWordHash().getBytes());+ if (e < 0) {+ writer.add(c1.getWordHash().getBytes(), c1.exportCollection());+ if (i1.hasNext()) {+ c1o = c1;+ c1 = i1.next();+ assert ordering.compare(c1.getWordHash().getBytes(), c1o.getWordHash().getBytes()) > 0;+ continue;+ }+ break;+ }+ if (e > 0) {+ writer.add(c2.getWordHash().getBytes(), c2.exportCollection());+ if (i2.hasNext()) {+ c2o = c2;+ c2 = i2.next();+ assert ordering.compare(c2.getWordHash().getBytes(), c2o.getWordHash().getBytes()) > 0;+ continue;+ }+ break;+ }+ assert e == 0;+ // merge the entries+ writer.add(c1.getWordHash().getBytes(), (c1.merge(c2)).exportCollection());+ if (i1.hasNext() && i2.hasNext()) {+ c1 = i1.next();+ c2 = i2.next();+ continue;+ }+ if (i1.hasNext()) c1 = i1.next();+ if (i2.hasNext()) c2 = i2.next();+ break;++ }+ // catch up remaining entries+ assert !(i1.hasNext() && i2.hasNext());+ while (i1.hasNext()) {+ //System.out.println("FLUSH REMAINING 1: " + c1.getWordHash());+ writer.add(c1.getWordHash().getBytes(), c1.exportCollection());+ if (i1.hasNext()) {+ c1o = c1;+ c1 = i1.next();+ assert ordering.compare(c1.getWordHash().getBytes(), c1o.getWordHash().getBytes()) > 0;+ continue;+ }+ break;+ }+ while (i2.hasNext()) {+ //System.out.println("FLUSH REMAINING 2: " + c2.getWordHash());+ writer.add(c2.getWordHash().getBytes(), c2.exportCollection());+ if (i2.hasNext()) {+ c2o = c2;+ c2 = i2.next();+ assert ordering.compare(c2.getWordHash().getBytes(), c2o.getWordHash().getBytes()) > 0;+ continue;+ }+ break;+ }+ // finished with writing+ }++}diff --git a/source/de/anomic/kelondro/text/ReferenceContainerOrder.java b/source/de/anomic/kelondro/text/ReferenceContainerOrder.javaindex 9184c4810..0069ecbf6 100644--- a/source/de/anomic/kelondro/text/ReferenceContainerOrder.java+++ b/source/de/anomic/kelondro/text/ReferenceContainerOrder.java@@ -1,86 +1,86 @@-// indexContainerOrder.java-// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 2007 on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $-// $LastChangedRevision: 1986 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import de.anomic.kelondro.order.AbstractOrder;-import de.anomic.kelondro.order.Order;--public class ReferenceContainerOrder extends AbstractOrder<ReferenceContainer> implements Order<ReferenceContainer>, Cloneable {-- private final Order<byte[]> embeddedOrder;-- public ReferenceContainerOrder(final Order<byte[]> embedOrder) {- this.embeddedOrder = embedOrder;- }-- public boolean wellformed(final ReferenceContainer a) {- return embeddedOrder.wellformed(a.getWordHash().getBytes());- }-- public void direction(final boolean ascending) {- this.embeddedOrder.direction(ascending);- }-- public long partition(final byte[] key, final int forks) {- return this.embeddedOrder.partition(key, forks);- }-- public int compare(final ReferenceContainer a, final ReferenceContainer b) {- return this.embeddedOrder.compare(a.getWordHash().getBytes(), b.getWordHash().getBytes());- }-- public boolean equal(ReferenceContainer a, ReferenceContainer b) {- return this.embeddedOrder.equal(a.getWordHash().getBytes(), b.getWordHash().getBytes());- }-- public void rotate(final ReferenceContainer zero) {- this.embeddedOrder.rotate(zero.getWordHash().getBytes());- this.zero = new ReferenceContainer(new String(this.embeddedOrder.zero()), zero);- }-- public Order<ReferenceContainer> clone() {- return new ReferenceContainerOrder(this.embeddedOrder.clone());- }-- public String signature() {- return this.embeddedOrder.signature();- }-- public long cardinal(final byte[] key) {- return this.embeddedOrder.cardinal(key);- }-- public boolean equals(final Order<ReferenceContainer> otherOrder) {- if (!(otherOrder instanceof ReferenceContainerOrder)) return false;- return this.embeddedOrder.equals(((ReferenceContainerOrder) otherOrder).embeddedOrder);- }-- public long cardinal(final ReferenceContainer key) {- return this.embeddedOrder.cardinal(key.getWordHash().getBytes());- }--}+// indexContainerOrder.java+// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 2007 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import de.anomic.kelondro.order.AbstractOrder;+import de.anomic.kelondro.order.Order;++public class ReferenceContainerOrder extends AbstractOrder<ReferenceContainer> implements Order<ReferenceContainer>, Cloneable {++ private final Order<byte[]> embeddedOrder;++ public ReferenceContainerOrder(final Order<byte[]> embedOrder) {+ this.embeddedOrder = embedOrder;+ }++ public boolean wellformed(final ReferenceContainer a) {+ return embeddedOrder.wellformed(a.getWordHash().getBytes());+ }++ public void direction(final boolean ascending) {+ this.embeddedOrder.direction(ascending);+ }++ public long partition(final byte[] key, final int forks) {+ return this.embeddedOrder.partition(key, forks);+ }++ public int compare(final ReferenceContainer a, final ReferenceContainer b) {+ return this.embeddedOrder.compare(a.getWordHash().getBytes(), b.getWordHash().getBytes());+ }++ public boolean equal(ReferenceContainer a, ReferenceContainer b) {+ return this.embeddedOrder.equal(a.getWordHash().getBytes(), b.getWordHash().getBytes());+ }++ public void rotate(final ReferenceContainer zero) {+ this.embeddedOrder.rotate(zero.getWordHash().getBytes());+ this.zero = new ReferenceContainer(new String(this.embeddedOrder.zero()), zero);+ }++ public Order<ReferenceContainer> clone() {+ return new ReferenceContainerOrder(this.embeddedOrder.clone());+ }++ public String signature() {+ return this.embeddedOrder.signature();+ }++ public long cardinal(final byte[] key) {+ return this.embeddedOrder.cardinal(key);+ }++ public boolean equals(final Order<ReferenceContainer> otherOrder) {+ if (!(otherOrder instanceof ReferenceContainerOrder)) return false;+ return this.embeddedOrder.equals(((ReferenceContainerOrder) otherOrder).embeddedOrder);+ }++ public long cardinal(final ReferenceContainer key) {+ return this.embeddedOrder.cardinal(key.getWordHash().getBytes());+ }++}diff --git a/source/de/anomic/kelondro/text/ReferenceOrder.java b/source/de/anomic/kelondro/text/ReferenceOrder.javaindex bc7595a1a..e3a108bb8 100644--- a/source/de/anomic/kelondro/text/ReferenceOrder.java+++ b/source/de/anomic/kelondro/text/ReferenceOrder.java@@ -1,215 +1,215 @@-// ReferenceOrder.java-// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 07.11.2007 on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $-// $LastChangedRevision: 1986 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import java.util.ArrayList;-import java.util.HashMap;-import java.util.Iterator;-import java.util.Map;--import de.anomic.kelondro.order.Bitfield;-import de.anomic.kelondro.util.ScoreCluster;-import de.anomic.plasma.plasmaCondenser;-import de.anomic.plasma.plasmaSearchRankingProcess;-import de.anomic.plasma.plasmaSearchRankingProfile;-import de.anomic.server.serverProcessor;-import de.anomic.yacy.yacyURL;--public class ReferenceOrder {- private ReferenceVars min, max;- private final plasmaSearchRankingProfile ranking;- private final ScoreCluster<String> doms; // collected for "authority" heuristic- private int maxdomcount;- private String language;-- public ReferenceOrder(final plasmaSearchRankingProfile profile, String language) {- this.min = null;- this.max = null;- this.ranking = profile;- this.doms = new ScoreCluster<String>();- this.maxdomcount = 0;- this.language = language;- }-- public ArrayList<ReferenceVars> normalizeWith(final ReferenceContainer container) {- // normalize ranking: find minimum and maxiumum of separate ranking criteria- assert (container != null);- ArrayList<ReferenceVars> result = null;-- //long s0 = System.currentTimeMillis();- if ((serverProcessor.useCPU > 1) && (container.size() > 600)) {- // run minmax with two threads- final int middle = container.size() / 2;- final minmaxfinder mmf0 = new minmaxfinder(container, 0, middle);- mmf0.start(); // fork here- final minmaxfinder mmf1 = new minmaxfinder(container, middle, container.size());- mmf1.run(); // execute other fork in this thread- if (this.min == null) this.min = mmf1.entryMin.clone(); else this.min.min(mmf1.entryMin);- if (this.max == null) this.max = mmf1.entryMax.clone(); else this.max.max(mmf1.entryMax);- Map.Entry<String, Integer> entry;- Iterator<Map.Entry<String, Integer>> di = mmf1.domcount().entrySet().iterator();- while (di.hasNext()) {- entry = di.next();- this.doms.addScore(entry.getKey(), (entry.getValue()).intValue());- }- try {mmf0.join();} catch (final InterruptedException e) {} // wait for fork thread to finish- if (this.min == null) this.min = mmf0.entryMin.clone(); else this.min.min(mmf0.entryMin);- if (this.max == null) this.max = mmf0.entryMax.clone(); else this.max.max(mmf0.entryMax);- di = mmf0.domcount().entrySet().iterator();- while (di.hasNext()) {- entry = di.next();- this.doms.addScore(entry.getKey(), (entry.getValue()).intValue());- }- result = mmf0.decodedContainer();- result.addAll(mmf1.decodedContainer());- //long s1= System.currentTimeMillis(), sc = Math.max(1, s1 - s0);- //System.out.println("***DEBUG*** indexRWIEntry.Order (2-THREADED): " + sc + " milliseconds for " + container.size() + " entries, " + (container.size() / sc) + " entries/millisecond");- } else if (container.size() > 0) {- // run minmax in one thread- final minmaxfinder mmf = new minmaxfinder(container, 0, container.size());- mmf.run(); // execute without multi-threading- if (this.min == null) this.min = mmf.entryMin.clone(); else this.min.min(mmf.entryMin);- if (this.max == null) this.max = mmf.entryMax.clone(); else this.max.max(mmf.entryMax);- Map.Entry<String, Integer> entry;- final Iterator<Map.Entry<String, Integer>> di = mmf.domcount().entrySet().iterator();- while (di.hasNext()) {- entry = di.next();- this.doms.addScore(entry.getKey(), (entry.getValue()).intValue());- }- result = mmf.decodedContainer();- //long s1= System.currentTimeMillis(), sc = Math.max(1, s1 - s0);- //System.out.println("***DEBUG*** indexRWIEntry.Order (ONETHREAD): " + sc + " milliseconds for " + container.size() + " entries, " + (container.size() / sc) + " entries/millisecond");- }- if (this.doms.size() > 0) this.maxdomcount = this.doms.getMaxScore();- return result;- }-- public int authority(final String urlHash) {- return (doms.getScore(urlHash.substring(6)) << 8) / (1 + this.maxdomcount);- }-- public long cardinal(final ReferenceVars t) {- //return Long.MAX_VALUE - preRanking(ranking, iEntry, this.entryMin, this.entryMax, this.searchWords);- // the normalizedEntry must be a normalized indexEntry- final Bitfield flags = t.flags();- final long tf = ((max.termFrequency() == min.termFrequency()) ? 0 : (((int)(((t.termFrequency()-min.termFrequency())*256.0)/(max.termFrequency() - min.termFrequency())))) << ranking.coeff_termfrequency);- //System.out.println("tf(" + t.urlHash + ") = " + Math.floor(1000 * t.termFrequency()) + ", min = " + Math.floor(1000 * min.termFrequency()) + ", max = " + Math.floor(1000 * max.termFrequency()) + ", tf-normed = " + tf);- final long r =- ((256 - yacyURL.domLengthNormalized(t.urlHash())) << ranking.coeff_domlength)- + ((ranking.coeff_ybr > 12) ? ((256 - (plasmaSearchRankingProcess.ybr(t.urlHash()) << 4)) << ranking.coeff_ybr) : 0)- + ((max.urlcomps() == min.urlcomps() ) ? 0 : (256 - (((t.urlcomps() - min.urlcomps() ) << 8) / (max.urlcomps() - min.urlcomps()) )) << ranking.coeff_urlcomps)- + ((max.urllength() == min.urllength() ) ? 0 : (256 - (((t.urllength() - min.urllength() ) << 8) / (max.urllength() - min.urllength()) )) << ranking.coeff_urllength)- + ((max.posintext() == min.posintext() ) ? 0 : (256 - (((t.posintext() - min.posintext() ) << 8) / (max.posintext() - min.posintext()) )) << ranking.coeff_posintext)- + ((max.posofphrase() == min.posofphrase()) ? 0 : (256 - (((t.posofphrase() - min.posofphrase() ) << 8) / (max.posofphrase() - min.posofphrase()) )) << ranking.coeff_posofphrase)- + ((max.posinphrase() == min.posinphrase()) ? 0 : (256 - (((t.posinphrase() - min.posinphrase() ) << 8) / (max.posinphrase() - min.posinphrase()) )) << ranking.coeff_posinphrase)- + ((max.worddistance() == min.worddistance()) ? 0 : (256 - (((t.worddistance() - min.worddistance() ) << 8) / (max.worddistance() - min.worddistance()) )) << ranking.coeff_worddistance)- + ((max.virtualAge() == min.virtualAge()) ? 0 : (((t.virtualAge() - min.virtualAge() ) << 8) / (max.virtualAge() - min.virtualAge()) ) << ranking.coeff_date)- + ((max.wordsintitle() == min.wordsintitle()) ? 0 : (((t.wordsintitle() - min.wordsintitle() ) << 8) / (max.wordsintitle() - min.wordsintitle()) ) << ranking.coeff_wordsintitle)- + ((max.wordsintext() == min.wordsintext()) ? 0 : (((t.wordsintext() - min.wordsintext() ) << 8) / (max.wordsintext() - min.wordsintext()) ) << ranking.coeff_wordsintext)- + ((max.phrasesintext() == min.phrasesintext()) ? 0 : (((t.phrasesintext()- min.phrasesintext() ) << 8) / (max.phrasesintext()- min.phrasesintext()) ) << ranking.coeff_phrasesintext)- + ((max.llocal() == min.llocal()) ? 0 : (((t.llocal() - min.llocal() ) << 8) / (max.llocal() - min.llocal()) ) << ranking.coeff_llocal)- + ((max.lother() == min.lother()) ? 0 : (((t.lother() - min.lother() ) << 8) / (max.lother() - min.lother()) ) << ranking.coeff_lother)- + ((max.hitcount() == min.hitcount()) ? 0 : (((t.hitcount() - min.hitcount() ) << 8) / (max.hitcount() - min.hitcount()) ) << ranking.coeff_hitcount)- + tf- + ((ranking.coeff_authority > 12) ? (authority(t.urlHash()) << ranking.coeff_authority) : 0)- + ((flags.get(Reference.flag_app_dc_identifier)) ? 255 << ranking.coeff_appurl : 0)- + ((flags.get(Reference.flag_app_dc_title)) ? 255 << ranking.coeff_app_dc_title : 0)- + ((flags.get(Reference.flag_app_dc_creator)) ? 255 << ranking.coeff_app_dc_creator : 0)- + ((flags.get(Reference.flag_app_dc_subject)) ? 255 << ranking.coeff_app_dc_subject : 0)- + ((flags.get(Reference.flag_app_dc_description)) ? 255 << ranking.coeff_app_dc_description : 0)- + ((flags.get(Reference.flag_app_emphasized)) ? 255 << ranking.coeff_appemph : 0)- + ((flags.get(plasmaCondenser.flag_cat_indexof)) ? 255 << ranking.coeff_catindexof : 0)- + ((flags.get(plasmaCondenser.flag_cat_hasimage)) ? 255 << ranking.coeff_cathasimage : 0)- + ((flags.get(plasmaCondenser.flag_cat_hasaudio)) ? 255 << ranking.coeff_cathasaudio : 0)- + ((flags.get(plasmaCondenser.flag_cat_hasvideo)) ? 255 << ranking.coeff_cathasvideo : 0)- + ((flags.get(plasmaCondenser.flag_cat_hasapp)) ? 255 << ranking.coeff_cathasapp : 0)- + ((patchUK(t.language).equals(this.language)) ? 255 << ranking.coeff_language : 0)- + ((yacyURL.probablyRootURL(t.urlHash())) ? 15 << ranking.coeff_urllength : 0);- //if (searchWords != null) r += (yacyURL.probablyWordURL(t.urlHash(), searchWords) != null) ? 256 << ranking.coeff_appurl : 0;-- return Long.MAX_VALUE - r; // returns a reversed number: the lower the number the better the ranking. This is used for simple sorting with a TreeMap- }-- private static final String patchUK(String l) {- // this is to patch a bad language name setting that was used in 0.60 and before- if (l.equals("uk")) return "en"; else return l;- }-- public static class minmaxfinder extends Thread {-- ReferenceVars entryMin;- ReferenceVars entryMax;- private final ReferenceContainer container;- private final int start, end;- private final HashMap<String, Integer> doms;- private final Integer int1;- ArrayList<ReferenceVars> decodedEntries;-- public minmaxfinder(final ReferenceContainer container, final int start /*including*/, final int end /*excluding*/) {- this.container = container;- this.start = start;- this.end = end;- this.doms = new HashMap<String, Integer>();- this.int1 = 1;- this.decodedEntries = new ArrayList<ReferenceVars>();- }-- public void run() {- // find min/max to obtain limits for normalization- this.entryMin = null;- this.entryMax = null;- ReferenceVars iEntry;- int p = this.start;- String dom;- Integer count;- while (p < this.end) {- iEntry = new ReferenceVars(new ReferenceRow(container.get(p++, false)));- this.decodedEntries.add(iEntry);- // find min/max- if (this.entryMin == null) this.entryMin = iEntry.clone(); else this.entryMin.min(iEntry);- if (this.entryMax == null) this.entryMax = iEntry.clone(); else this.entryMax.max(iEntry);- // update domcount- dom = iEntry.urlHash().substring(6);- count = doms.get(dom);- if (count == null) {- doms.put(dom, int1);- } else {- doms.put(dom, Integer.valueOf(count.intValue() + 1));- }- }- }-- public ArrayList<ReferenceVars> decodedContainer() {- return this.decodedEntries;- }-- public HashMap<String, Integer> domcount() {- return this.doms;- }- }--}+// ReferenceOrder.java+// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 07.11.2007 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.Iterator;+import java.util.Map;++import de.anomic.kelondro.order.Bitfield;+import de.anomic.kelondro.util.ScoreCluster;+import de.anomic.plasma.plasmaCondenser;+import de.anomic.plasma.plasmaSearchRankingProcess;+import de.anomic.plasma.plasmaSearchRankingProfile;+import de.anomic.server.serverProcessor;+import de.anomic.yacy.yacyURL;++public class ReferenceOrder {+ private ReferenceVars min, max;+ private final plasmaSearchRankingProfile ranking;+ private final ScoreCluster<String> doms; // collected for "authority" heuristic+ private int maxdomcount;+ private String language;++ public ReferenceOrder(final plasmaSearchRankingProfile profile, String language) {+ this.min = null;+ this.max = null;+ this.ranking = profile;+ this.doms = new ScoreCluster<String>();+ this.maxdomcount = 0;+ this.language = language;+ }++ public ArrayList<ReferenceVars> normalizeWith(final ReferenceContainer container) {+ // normalize ranking: find minimum and maxiumum of separate ranking criteria+ assert (container != null);+ ArrayList<ReferenceVars> result = null;++ //long s0 = System.currentTimeMillis();+ if ((serverProcessor.useCPU > 1) && (container.size() > 600)) {+ // run minmax with two threads+ final int middle = container.size() / 2;+ final minmaxfinder mmf0 = new minmaxfinder(container, 0, middle);+ mmf0.start(); // fork here+ final minmaxfinder mmf1 = new minmaxfinder(container, middle, container.size());+ mmf1.run(); // execute other fork in this thread+ if (this.min == null) this.min = mmf1.entryMin.clone(); else this.min.min(mmf1.entryMin);+ if (this.max == null) this.max = mmf1.entryMax.clone(); else this.max.max(mmf1.entryMax);+ Map.Entry<String, Integer> entry;+ Iterator<Map.Entry<String, Integer>> di = mmf1.domcount().entrySet().iterator();+ while (di.hasNext()) {+ entry = di.next();+ this.doms.addScore(entry.getKey(), (entry.getValue()).intValue());+ }+ try {mmf0.join();} catch (final InterruptedException e) {} // wait for fork thread to finish+ if (this.min == null) this.min = mmf0.entryMin.clone(); else this.min.min(mmf0.entryMin);+ if (this.max == null) this.max = mmf0.entryMax.clone(); else this.max.max(mmf0.entryMax);+ di = mmf0.domcount().entrySet().iterator();+ while (di.hasNext()) {+ entry = di.next();+ this.doms.addScore(entry.getKey(), (entry.getValue()).intValue());+ }+ result = mmf0.decodedContainer();+ result.addAll(mmf1.decodedContainer());+ //long s1= System.currentTimeMillis(), sc = Math.max(1, s1 - s0);+ //System.out.println("***DEBUG*** indexRWIEntry.Order (2-THREADED): " + sc + " milliseconds for " + container.size() + " entries, " + (container.size() / sc) + " entries/millisecond");+ } else if (container.size() > 0) {+ // run minmax in one thread+ final minmaxfinder mmf = new minmaxfinder(container, 0, container.size());+ mmf.run(); // execute without multi-threading+ if (this.min == null) this.min = mmf.entryMin.clone(); else this.min.min(mmf.entryMin);+ if (this.max == null) this.max = mmf.entryMax.clone(); else this.max.max(mmf.entryMax);+ Map.Entry<String, Integer> entry;+ final Iterator<Map.Entry<String, Integer>> di = mmf.domcount().entrySet().iterator();+ while (di.hasNext()) {+ entry = di.next();+ this.doms.addScore(entry.getKey(), (entry.getValue()).intValue());+ }+ result = mmf.decodedContainer();+ //long s1= System.currentTimeMillis(), sc = Math.max(1, s1 - s0);+ //System.out.println("***DEBUG*** indexRWIEntry.Order (ONETHREAD): " + sc + " milliseconds for " + container.size() + " entries, " + (container.size() / sc) + " entries/millisecond");+ }+ if (this.doms.size() > 0) this.maxdomcount = this.doms.getMaxScore();+ return result;+ }++ public int authority(final String urlHash) {+ return (doms.getScore(urlHash.substring(6)) << 8) / (1 + this.maxdomcount);+ }++ public long cardinal(final ReferenceVars t) {+ //return Long.MAX_VALUE - preRanking(ranking, iEntry, this.entryMin, this.entryMax, this.searchWords);+ // the normalizedEntry must be a normalized indexEntry+ final Bitfield flags = t.flags();+ final long tf = ((max.termFrequency() == min.termFrequency()) ? 0 : (((int)(((t.termFrequency()-min.termFrequency())*256.0)/(max.termFrequency() - min.termFrequency())))) << ranking.coeff_termfrequency);+ //System.out.println("tf(" + t.urlHash + ") = " + Math.floor(1000 * t.termFrequency()) + ", min = " + Math.floor(1000 * min.termFrequency()) + ", max = " + Math.floor(1000 * max.termFrequency()) + ", tf-normed = " + tf);+ final long r =+ ((256 - yacyURL.domLengthNormalized(t.urlHash())) << ranking.coeff_domlength)+ + ((ranking.coeff_ybr > 12) ? ((256 - (plasmaSearchRankingProcess.ybr(t.urlHash()) << 4)) << ranking.coeff_ybr) : 0)+ + ((max.urlcomps() == min.urlcomps() ) ? 0 : (256 - (((t.urlcomps() - min.urlcomps() ) << 8) / (max.urlcomps() - min.urlcomps()) )) << ranking.coeff_urlcomps)+ + ((max.urllength() == min.urllength() ) ? 0 : (256 - (((t.urllength() - min.urllength() ) << 8) / (max.urllength() - min.urllength()) )) << ranking.coeff_urllength)+ + ((max.posintext() == min.posintext() ) ? 0 : (256 - (((t.posintext() - min.posintext() ) << 8) / (max.posintext() - min.posintext()) )) << ranking.coeff_posintext)+ + ((max.posofphrase() == min.posofphrase()) ? 0 : (256 - (((t.posofphrase() - min.posofphrase() ) << 8) / (max.posofphrase() - min.posofphrase()) )) << ranking.coeff_posofphrase)+ + ((max.posinphrase() == min.posinphrase()) ? 0 : (256 - (((t.posinphrase() - min.posinphrase() ) << 8) / (max.posinphrase() - min.posinphrase()) )) << ranking.coeff_posinphrase)+ + ((max.worddistance() == min.worddistance()) ? 0 : (256 - (((t.worddistance() - min.worddistance() ) << 8) / (max.worddistance() - min.worddistance()) )) << ranking.coeff_worddistance)+ + ((max.virtualAge() == min.virtualAge()) ? 0 : (((t.virtualAge() - min.virtualAge() ) << 8) / (max.virtualAge() - min.virtualAge()) ) << ranking.coeff_date)+ + ((max.wordsintitle() == min.wordsintitle()) ? 0 : (((t.wordsintitle() - min.wordsintitle() ) << 8) / (max.wordsintitle() - min.wordsintitle()) ) << ranking.coeff_wordsintitle)+ + ((max.wordsintext() == min.wordsintext()) ? 0 : (((t.wordsintext() - min.wordsintext() ) << 8) / (max.wordsintext() - min.wordsintext()) ) << ranking.coeff_wordsintext)+ + ((max.phrasesintext() == min.phrasesintext()) ? 0 : (((t.phrasesintext()- min.phrasesintext() ) << 8) / (max.phrasesintext()- min.phrasesintext()) ) << ranking.coeff_phrasesintext)+ + ((max.llocal() == min.llocal()) ? 0 : (((t.llocal() - min.llocal() ) << 8) / (max.llocal() - min.llocal()) ) << ranking.coeff_llocal)+ + ((max.lother() == min.lother()) ? 0 : (((t.lother() - min.lother() ) << 8) / (max.lother() - min.lother()) ) << ranking.coeff_lother)+ + ((max.hitcount() == min.hitcount()) ? 0 : (((t.hitcount() - min.hitcount() ) << 8) / (max.hitcount() - min.hitcount()) ) << ranking.coeff_hitcount)+ + tf+ + ((ranking.coeff_authority > 12) ? (authority(t.urlHash()) << ranking.coeff_authority) : 0)+ + ((flags.get(Reference.flag_app_dc_identifier)) ? 255 << ranking.coeff_appurl : 0)+ + ((flags.get(Reference.flag_app_dc_title)) ? 255 << ranking.coeff_app_dc_title : 0)+ + ((flags.get(Reference.flag_app_dc_creator)) ? 255 << ranking.coeff_app_dc_creator : 0)+ + ((flags.get(Reference.flag_app_dc_subject)) ? 255 << ranking.coeff_app_dc_subject : 0)+ + ((flags.get(Reference.flag_app_dc_description)) ? 255 << ranking.coeff_app_dc_description : 0)+ + ((flags.get(Reference.flag_app_emphasized)) ? 255 << ranking.coeff_appemph : 0)+ + ((flags.get(plasmaCondenser.flag_cat_indexof)) ? 255 << ranking.coeff_catindexof : 0)+ + ((flags.get(plasmaCondenser.flag_cat_hasimage)) ? 255 << ranking.coeff_cathasimage : 0)+ + ((flags.get(plasmaCondenser.flag_cat_hasaudio)) ? 255 << ranking.coeff_cathasaudio : 0)+ + ((flags.get(plasmaCondenser.flag_cat_hasvideo)) ? 255 << ranking.coeff_cathasvideo : 0)+ + ((flags.get(plasmaCondenser.flag_cat_hasapp)) ? 255 << ranking.coeff_cathasapp : 0)+ + ((patchUK(t.language).equals(this.language)) ? 255 << ranking.coeff_language : 0)+ + ((yacyURL.probablyRootURL(t.urlHash())) ? 15 << ranking.coeff_urllength : 0);+ //if (searchWords != null) r += (yacyURL.probablyWordURL(t.urlHash(), searchWords) != null) ? 256 << ranking.coeff_appurl : 0;++ return Long.MAX_VALUE - r; // returns a reversed number: the lower the number the better the ranking. This is used for simple sorting with a TreeMap+ }++ private static final String patchUK(String l) {+ // this is to patch a bad language name setting that was used in 0.60 and before+ if (l.equals("uk")) return "en"; else return l;+ }++ public static class minmaxfinder extends Thread {++ ReferenceVars entryMin;+ ReferenceVars entryMax;+ private final ReferenceContainer container;+ private final int start, end;+ private final HashMap<String, Integer> doms;+ private final Integer int1;+ ArrayList<ReferenceVars> decodedEntries;++ public minmaxfinder(final ReferenceContainer container, final int start /*including*/, final int end /*excluding*/) {+ this.container = container;+ this.start = start;+ this.end = end;+ this.doms = new HashMap<String, Integer>();+ this.int1 = 1;+ this.decodedEntries = new ArrayList<ReferenceVars>();+ }++ public void run() {+ // find min/max to obtain limits for normalization+ this.entryMin = null;+ this.entryMax = null;+ ReferenceVars iEntry;+ int p = this.start;+ String dom;+ Integer count;+ while (p < this.end) {+ iEntry = new ReferenceVars(new ReferenceRow(container.get(p++, false)));+ this.decodedEntries.add(iEntry);+ // find min/max+ if (this.entryMin == null) this.entryMin = iEntry.clone(); else this.entryMin.min(iEntry);+ if (this.entryMax == null) this.entryMax = iEntry.clone(); else this.entryMax.max(iEntry);+ // update domcount+ dom = iEntry.urlHash().substring(6);+ count = doms.get(dom);+ if (count == null) {+ doms.put(dom, int1);+ } else {+ doms.put(dom, Integer.valueOf(count.intValue() + 1));+ }+ }+ }++ public ArrayList<ReferenceVars> decodedContainer() {+ return this.decodedEntries;+ }++ public HashMap<String, Integer> domcount() {+ return this.doms;+ }+ }++}diff --git a/source/de/anomic/kelondro/text/ReferenceRow.java b/source/de/anomic/kelondro/text/ReferenceRow.javaindex 4503687c1..6d5be2679 100644--- a/source/de/anomic/kelondro/text/ReferenceRow.java+++ b/source/de/anomic/kelondro/text/ReferenceRow.java@@ -1,269 +1,269 @@-// ReferenceRow.java-// (C) 2006 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 20.05.2006 on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $-// $LastChangedRevision: 1986 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import de.anomic.kelondro.index.Column;-import de.anomic.kelondro.index.Row;-import de.anomic.kelondro.index.Row.Entry;-import de.anomic.kelondro.order.Base64Order;-import de.anomic.kelondro.order.Bitfield;-import de.anomic.kelondro.order.MicroDate;-import de.anomic.yacy.yacySeedDB;--public final class ReferenceRow implements Reference, Cloneable {-- // this object stores attributes to URL references inside RWI collections-- public static final Row urlEntryRow = new Row(new Column[]{- new Column("h", Column.celltype_string, Column.encoder_bytes, yacySeedDB.commonHashLength, "urlhash"),- new Column("a", Column.celltype_cardinal, Column.encoder_b256, 2, "lastModified"),- new Column("s", Column.celltype_cardinal, Column.encoder_b256, 2, "freshUntil"),- new Column("u", Column.celltype_cardinal, Column.encoder_b256, 1, "wordsInTitle"),- new Column("w", Column.celltype_cardinal, Column.encoder_b256, 2, "wordsInText"),- new Column("p", Column.celltype_cardinal, Column.encoder_b256, 2, "phrasesInText"),- new Column("d", Column.celltype_binary, Column.encoder_bytes, 1, "doctype"),- new Column("l", Column.celltype_string, Column.encoder_bytes, 2, "language"),- new Column("x", Column.celltype_cardinal, Column.encoder_b256, 1, "llocal"),- new Column("y", Column.celltype_cardinal, Column.encoder_b256, 1, "lother"),- new Column("m", Column.celltype_cardinal, Column.encoder_b256, 1, "urlLength"),- new Column("n", Column.celltype_cardinal, Column.encoder_b256, 1, "urlComps"),- new Column("g", Column.celltype_binary, Column.encoder_bytes, 1, "typeofword"),- new Column("z", Column.celltype_bitfield, Column.encoder_bytes, 4, "flags"),- new Column("c", Column.celltype_cardinal, Column.encoder_b256, 1, "hitcount"),- new Column("t", Column.celltype_cardinal, Column.encoder_b256, 2, "posintext"),- new Column("r", Column.celltype_cardinal, Column.encoder_b256, 1, "posinphrase"),- new Column("o", Column.celltype_cardinal, Column.encoder_b256, 1, "posofphrase"),- new Column("i", Column.celltype_cardinal, Column.encoder_b256, 1, "worddistance"),- new Column("k", Column.celltype_cardinal, Column.encoder_b256, 1, "reserve")- },- Base64Order.enhancedCoder- );- // available chars: b,e,j,q-- // static properties- private static final int col_urlhash = 0; // h 12 the url hash b64-encoded- private static final int col_lastModified = 1; // a 2 last-modified time of the document where word appears- private static final int col_freshUntil = 2; // s 2 TTL for the word, so it can be removed easily if the TTL is short- private static final int col_wordsInTitle = 3; // u 1 words in description/length (longer are better?)- private static final int col_wordsInText = 4; // w 2 total number of words in document- private static final int col_phrasesInText = 5; // p 2 total number of phrases in document- private static final int col_doctype = 6; // d 1 type of document- private static final int col_language = 7; // l 2 (guessed) language of document- private static final int col_llocal = 8; // x 1 outlinks to same domain- private static final int col_lother = 9; // y 1 outlinks to other domain- private static final int col_urlLength = 10; // m 1 byte-length of complete URL- private static final int col_urlComps = 11; // n 1 number of path components-- // dynamic properties- private static final int col_typeofword = 12; // g 1 grammatical classification- private 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- private static final int col_posintext = 15; // t 2 first appearance of word in text- private static final int col_posinphrase = 16; // r 1 position of word in its phrase- private static final int col_posofphrase = 17; // o 1 number of the phrase where word appears- private static final int col_reserve1 = 18; // i 1 reserve1- private static final int col_reserve2 = 19; // k 1 reserve2-- private final Row.Entry entry;-- public ReferenceRow(final String urlHash,- final int urlLength, // byte-length of complete URL- final int urlComps, // number of path components- final int titleLength, // length of description/length (longer are better?)- final int hitcount, // how often appears this word in the text- final int wordcount, // total number of words- final int phrasecount, // total number of phrases- final int posintext, // position of word in all words- final int posinphrase, // position of word in its phrase- final int posofphrase, // number of the phrase where word appears- final long lastmodified, // last-modified time of the document where word appears- final long updatetime, // update time; this is needed to compute a TTL for the word, so it can be removed easily if the TTL is short- final String language, // (guessed) language of document- final char doctype, // type of document- final int outlinksSame, // outlinks to same domain- final int outlinksOther, // outlinks to other domain- final Bitfield flags // attributes to the url and to the word according the url- ) {-- assert (urlHash.length() == 12) : "urlhash = " + urlHash;- this.entry = urlEntryRow.newEntry();- final int mddlm = MicroDate.microDateDays(lastmodified);- final int mddct = MicroDate.microDateDays(updatetime);- this.entry.setCol(col_urlhash, urlHash, null);- this.entry.setCol(col_lastModified, mddlm);- this.entry.setCol(col_freshUntil, Math.max(0, mddlm + (mddct - mddlm) * 2)); // TTL computation- this.entry.setCol(col_wordsInTitle, titleLength / 6); // word count estimation; TODO: change value handover to number of words- this.entry.setCol(col_wordsInText, wordcount);- this.entry.setCol(col_phrasesInText, phrasecount);- this.entry.setCol(col_doctype, new byte[]{(byte) doctype});- this.entry.setCol(col_language, ((language == null) || (language.length() != urlEntryRow.width(col_language))) ? "uk" : language, null);- this.entry.setCol(col_llocal, outlinksSame);- this.entry.setCol(col_lother, outlinksOther);- this.entry.setCol(col_urlLength, urlLength);- this.entry.setCol(col_urlComps, urlComps);- this.entry.setCol(col_typeofword, new byte[]{(byte) 0}); // TODO: grammatical classification- this.entry.setCol(col_flags, flags.bytes());- this.entry.setCol(col_hitcount, hitcount);- this.entry.setCol(col_posintext, posintext);- this.entry.setCol(col_posinphrase, posinphrase);- this.entry.setCol(col_posofphrase, posofphrase);- this.entry.setCol(col_reserve1, 0);- this.entry.setCol(col_reserve2, 0);- }-- public ReferenceRow(final String urlHash, final String code) {- // the code is the external form of the row minus the leading urlHash entry- this.entry = urlEntryRow.newEntry((urlHash + code).getBytes());- }-- public ReferenceRow(final String external) {- this.entry = urlEntryRow.newEntry(external, true);- }-- public ReferenceRow(final byte[] row) {- this.entry = urlEntryRow.newEntry(row);- }-- public ReferenceRow(final byte[] row, final int offset, final boolean clone) {- this.entry = urlEntryRow.newEntry(row, offset, clone);- }-- public ReferenceRow(final Row.Entry rentry) {- // FIXME: see if cloning is necessary- this.entry = rentry;- }-- public ReferenceRow clone() {- final byte[] b = new byte[urlEntryRow.objectsize];- System.arraycopy(entry.bytes(), 0, b, 0, urlEntryRow.objectsize);- return new ReferenceRow(b);- }-- public String toPropertyForm() {- return entry.toPropertyForm(true, true, false);- }-- public Entry toKelondroEntry() {- return this.entry;- }-- public String urlHash() {- return this.entry.getColString(col_urlhash, null);- }-- public int virtualAge() {- return (int) this.entry.getColLong(col_lastModified); // this is the time in MicoDateDays format- }-- public long lastModified() {- return MicroDate.reverseMicroDateDays((int) this.entry.getColLong(col_lastModified));- }-- public long freshUntil() {- return MicroDate.reverseMicroDateDays((int) this.entry.getColLong(col_freshUntil));- }-- public int hitcount() {- return (int) this.entry.getColLong(col_hitcount);- }-- public int posintext() {- return (int) this.entry.getColLong(col_posintext);- }-- public int posinphrase() {- return (int) this.entry.getColLong(col_posinphrase);- }-- public int posofphrase() {- return (int) this.entry.getColLong(col_posofphrase);- }-- public int wordsintext() {- return (int) this.entry.getColLong(col_wordsInText);- }-- public int phrasesintext() {- return (int) this.entry.getColLong(col_phrasesInText);- }-- public String getLanguage() {- return this.entry.getColString(col_language, null);- }-- public char getType() {- return (char) this.entry.getColByte(col_doctype);- }-- public 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));- }-- public double termFrequency() {- return (((double) this.hitcount()) / ((double) (this.wordsintext() + this.wordsintitle() + 1)));- }-- public String toString() {- return toPropertyForm();- }-- public boolean isNewer(final Reference other) {- if (other == null) return true;- if (this.lastModified() > other.lastModified()) return true;- return false;- }-- public boolean isOlder(final Reference other) {- if (other == null) return false;- if (this.lastModified() < other.lastModified()) return true;- return false;- }-- public int hashCode() {- return this.urlHash().hashCode();- }-}\ No newline at end of file+// ReferenceRow.java+// (C) 2006 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 20.05.2006 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import de.anomic.kelondro.index.Column;+import de.anomic.kelondro.index.Row;+import de.anomic.kelondro.index.Row.Entry;+import de.anomic.kelondro.order.Base64Order;+import de.anomic.kelondro.order.Bitfield;+import de.anomic.kelondro.order.MicroDate;+import de.anomic.yacy.yacySeedDB;++public final class ReferenceRow implements Reference, Cloneable {++ // this object stores attributes to URL references inside RWI collections++ public static final Row urlEntryRow = new Row(new Column[]{+ new Column("h", Column.celltype_string, Column.encoder_bytes, yacySeedDB.commonHashLength, "urlhash"),+ new Column("a", Column.celltype_cardinal, Column.encoder_b256, 2, "lastModified"),+ new Column("s", Column.celltype_cardinal, Column.encoder_b256, 2, "freshUntil"),+ new Column("u", Column.celltype_cardinal, Column.encoder_b256, 1, "wordsInTitle"),+ new Column("w", Column.celltype_cardinal, Column.encoder_b256, 2, "wordsInText"),+ new Column("p", Column.celltype_cardinal, Column.encoder_b256, 2, "phrasesInText"),+ new Column("d", Column.celltype_binary, Column.encoder_bytes, 1, "doctype"),+ new Column("l", Column.celltype_string, Column.encoder_bytes, 2, "language"),+ new Column("x", Column.celltype_cardinal, Column.encoder_b256, 1, "llocal"),+ new Column("y", Column.celltype_cardinal, Column.encoder_b256, 1, "lother"),+ new Column("m", Column.celltype_cardinal, Column.encoder_b256, 1, "urlLength"),+ new Column("n", Column.celltype_cardinal, Column.encoder_b256, 1, "urlComps"),+ new Column("g", Column.celltype_binary, Column.encoder_bytes, 1, "typeofword"),+ new Column("z", Column.celltype_bitfield, Column.encoder_bytes, 4, "flags"),+ new Column("c", Column.celltype_cardinal, Column.encoder_b256, 1, "hitcount"),+ new Column("t", Column.celltype_cardinal, Column.encoder_b256, 2, "posintext"),+ new Column("r", Column.celltype_cardinal, Column.encoder_b256, 1, "posinphrase"),+ new Column("o", Column.celltype_cardinal, Column.encoder_b256, 1, "posofphrase"),+ new Column("i", Column.celltype_cardinal, Column.encoder_b256, 1, "worddistance"),+ new Column("k", Column.celltype_cardinal, Column.encoder_b256, 1, "reserve")+ },+ Base64Order.enhancedCoder+ );+ // available chars: b,e,j,q++ // static properties+ private static final int col_urlhash = 0; // h 12 the url hash b64-encoded+ private static final int col_lastModified = 1; // a 2 last-modified time of the document where word appears+ private static final int col_freshUntil = 2; // s 2 TTL for the word, so it can be removed easily if the TTL is short+ private static final int col_wordsInTitle = 3; // u 1 words in description/length (longer are better?)+ private static final int col_wordsInText = 4; // w 2 total number of words in document+ private static final int col_phrasesInText = 5; // p 2 total number of phrases in document+ private static final int col_doctype = 6; // d 1 type of document+ private static final int col_language = 7; // l 2 (guessed) language of document+ private static final int col_llocal = 8; // x 1 outlinks to same domain+ private static final int col_lother = 9; // y 1 outlinks to other domain+ private static final int col_urlLength = 10; // m 1 byte-length of complete URL+ private static final int col_urlComps = 11; // n 1 number of path components++ // dynamic properties+ private static final int col_typeofword = 12; // g 1 grammatical classification+ private 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+ private static final int col_posintext = 15; // t 2 first appearance of word in text+ private static final int col_posinphrase = 16; // r 1 position of word in its phrase+ private static final int col_posofphrase = 17; // o 1 number of the phrase where word appears+ private static final int col_reserve1 = 18; // i 1 reserve1+ private static final int col_reserve2 = 19; // k 1 reserve2++ private final Row.Entry entry;++ public ReferenceRow(final String urlHash,+ final int urlLength, // byte-length of complete URL+ final int urlComps, // number of path components+ final int titleLength, // length of description/length (longer are better?)+ final int hitcount, // how often appears this word in the text+ final int wordcount, // total number of words+ final int phrasecount, // total number of phrases+ final int posintext, // position of word in all words+ final int posinphrase, // position of word in its phrase+ final int posofphrase, // number of the phrase where word appears+ final long lastmodified, // last-modified time of the document where word appears+ final long updatetime, // update time; this is needed to compute a TTL for the word, so it can be removed easily if the TTL is short+ final String language, // (guessed) language of document+ final char doctype, // type of document+ final int outlinksSame, // outlinks to same domain+ final int outlinksOther, // outlinks to other domain+ final Bitfield flags // attributes to the url and to the word according the url+ ) {++ assert (urlHash.length() == 12) : "urlhash = " + urlHash;+ this.entry = urlEntryRow.newEntry();+ final int mddlm = MicroDate.microDateDays(lastmodified);+ final int mddct = MicroDate.microDateDays(updatetime);+ this.entry.setCol(col_urlhash, urlHash, null);+ this.entry.setCol(col_lastModified, mddlm);+ this.entry.setCol(col_freshUntil, Math.max(0, mddlm + (mddct - mddlm) * 2)); // TTL computation+ this.entry.setCol(col_wordsInTitle, titleLength / 6); // word count estimation; TODO: change value handover to number of words+ this.entry.setCol(col_wordsInText, wordcount);+ this.entry.setCol(col_phrasesInText, phrasecount);+ this.entry.setCol(col_doctype, new byte[]{(byte) doctype});+ this.entry.setCol(col_language, ((language == null) || (language.length() != urlEntryRow.width(col_language))) ? "uk" : language, null);+ this.entry.setCol(col_llocal, outlinksSame);+ this.entry.setCol(col_lother, outlinksOther);+ this.entry.setCol(col_urlLength, urlLength);+ this.entry.setCol(col_urlComps, urlComps);+ this.entry.setCol(col_typeofword, new byte[]{(byte) 0}); // TODO: grammatical classification+ this.entry.setCol(col_flags, flags.bytes());+ this.entry.setCol(col_hitcount, hitcount);+ this.entry.setCol(col_posintext, posintext);+ this.entry.setCol(col_posinphrase, posinphrase);+ this.entry.setCol(col_posofphrase, posofphrase);+ this.entry.setCol(col_reserve1, 0);+ this.entry.setCol(col_reserve2, 0);+ }++ public ReferenceRow(final String urlHash, final String code) {+ // the code is the external form of the row minus the leading urlHash entry+ this.entry = urlEntryRow.newEntry((urlHash + code).getBytes());+ }++ public ReferenceRow(final String external) {+ this.entry = urlEntryRow.newEntry(external, true);+ }++ public ReferenceRow(final byte[] row) {+ this.entry = urlEntryRow.newEntry(row);+ }++ public ReferenceRow(final byte[] row, final int offset, final boolean clone) {+ this.entry = urlEntryRow.newEntry(row, offset, clone);+ }++ public ReferenceRow(final Row.Entry rentry) {+ // FIXME: see if cloning is necessary+ this.entry = rentry;+ }++ public ReferenceRow clone() {+ final byte[] b = new byte[urlEntryRow.objectsize];+ System.arraycopy(entry.bytes(), 0, b, 0, urlEntryRow.objectsize);+ return new ReferenceRow(b);+ }++ public String toPropertyForm() {+ return entry.toPropertyForm(true, true, false);+ }++ public Entry toKelondroEntry() {+ return this.entry;+ }++ public String urlHash() {+ return this.entry.getColString(col_urlhash, null);+ }++ public int virtualAge() {+ return (int) this.entry.getColLong(col_lastModified); // this is the time in MicoDateDays format+ }++ public long lastModified() {+ return MicroDate.reverseMicroDateDays((int) this.entry.getColLong(col_lastModified));+ }++ public long freshUntil() {+ return MicroDate.reverseMicroDateDays((int) this.entry.getColLong(col_freshUntil));+ }++ public int hitcount() {+ return (int) this.entry.getColLong(col_hitcount);+ }++ public int posintext() {+ return (int) this.entry.getColLong(col_posintext);+ }++ public int posinphrase() {+ return (int) this.entry.getColLong(col_posinphrase);+ }++ public int posofphrase() {+ return (int) this.entry.getColLong(col_posofphrase);+ }++ public int wordsintext() {+ return (int) this.entry.getColLong(col_wordsInText);+ }++ public int phrasesintext() {+ return (int) this.entry.getColLong(col_phrasesInText);+ }++ public String getLanguage() {+ return this.entry.getColString(col_language, null);+ }++ public char getType() {+ return (char) this.entry.getColByte(col_doctype);+ }++ public 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));+ }++ public double termFrequency() {+ return (((double) this.hitcount()) / ((double) (this.wordsintext() + this.wordsintitle() + 1)));+ }++ public String toString() {+ return toPropertyForm();+ }++ public boolean isNewer(final Reference other) {+ if (other == null) return true;+ if (this.lastModified() > other.lastModified()) return true;+ return false;+ }++ public boolean isOlder(final Reference other) {+ if (other == null) return false;+ if (this.lastModified() < other.lastModified()) return true;+ return false;+ }++ public int hashCode() {+ return this.urlHash().hashCode();+ }+}diff --git a/source/de/anomic/kelondro/text/ReferenceVars.java b/source/de/anomic/kelondro/text/ReferenceVars.javaindex f406c17c6..f6c4be337 100644--- a/source/de/anomic/kelondro/text/ReferenceVars.java+++ b/source/de/anomic/kelondro/text/ReferenceVars.java@@ -1,326 +1,326 @@-// ReferenceVars.java-// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 07.11.2007 on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $-// $LastChangedRevision: 1986 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import de.anomic.kelondro.order.Bitfield;-import de.anomic.kelondro.order.MicroDate;--public class ReferenceVars implements Reference, Cloneable {-- public Bitfield flags;- public long freshUntil, lastModified;- public String language, urlHash;- public char type;- public int hitcount, llocal, lother, phrasesintext, posintext,- posinphrase, posofphrase,- urlcomps, urllength, virtualAge,- worddistance, wordsintext, wordsintitle;- public double termFrequency;-- public ReferenceVars(final String urlHash,- final int urlLength, // byte-length of complete URL- final int urlComps, // number of path components- final int titleLength, // length of description/length (longer are better?)- final int hitcount, // how often appears this word in the text- final int wordcount, // total number of words- final int phrasecount, // total number of phrases- final int posintext, // position of word in all words- final int posinphrase, // position of word in its phrase- final int posofphrase, // number of the phrase where word appears- final long lastmodified, // last-modified time of the document where word appears- final long updatetime, // update time; this is needed to compute a TTL for the word, so it can be removed easily if the TTL is short- String language, // (guessed) language of document- final char doctype, // type of document- final int outlinksSame, // outlinks to same domain- final int outlinksOther, // outlinks to other domain- final Bitfield flags, // attributes to the url and to the word according the url- final int worddistance,- final double termfrequency- ) {- if ((language == null) || (language.length() != 2)) language = "uk";- final int mddlm = MicroDate.microDateDays(lastmodified);- final int mddct = MicroDate.microDateDays(updatetime);- this.flags = flags;- this.freshUntil = Math.max(0, mddlm + (mddct - mddlm) * 2);- this.lastModified = lastmodified;- this.language = language;- this.urlHash = urlHash;- this.type = doctype;- this.hitcount = hitcount;- this.llocal = outlinksSame;- this.lother = outlinksOther;- this.phrasesintext = outlinksOther;- this.posintext = posintext;- this.posinphrase = posinphrase;- this.posofphrase = posofphrase;- this.urlcomps = urlComps;- this.urllength = urlLength;- this.virtualAge = mddlm;- this.worddistance = worddistance;- this.wordsintext = wordcount;- this.wordsintitle = titleLength;- this.termFrequency = termfrequency;- }-- public ReferenceVars(final ReferenceRow e) {- this.flags = e.flags();- this.freshUntil = e.freshUntil();- this.lastModified = e.lastModified();- this.language = e.getLanguage();- this.urlHash = e.urlHash();- this.type = e.getType();- this.hitcount = e.hitcount();- this.llocal = e.llocal();- this.lother = e.lother();- this.phrasesintext = e.phrasesintext();- this.posintext = e.posintext();- this.posinphrase = e.posinphrase();- this.posofphrase = e.posofphrase();- this.urlcomps = e.urlcomps();- this.urllength = e.urllength();- this.virtualAge = e.virtualAge();- this.worddistance = 0;- this.wordsintext = e.wordsintext();- this.wordsintitle = e.wordsintitle();- this.termFrequency = e.termFrequency();- }-- public ReferenceVars clone() {- final ReferenceVars c = new ReferenceVars(- this.urlHash,- this.urllength,- this.urlcomps,- this.wordsintitle,- this.hitcount,- this.wordsintext,- this.phrasesintext,- this.posintext,- this.posinphrase,- this.posofphrase,- this.lastModified,- System.currentTimeMillis(),- this.language,- this.type,- this.llocal,- this.lother,- this.flags,- this.worddistance,- this.termFrequency);- return c;- }-- public void join(final ReferenceVars oe) {- // combine the distance- this.worddistance = this.worddistance + oe.worddistance + Math.abs(this.posintext - oe.posintext);- this.posintext = Math.min(this.posintext, oe.posintext);- this.posinphrase = (this.posofphrase == oe.posofphrase) ? Math.min(this.posinphrase, oe.posinphrase) : 0;- this.posofphrase = Math.min(this.posofphrase, oe.posofphrase);-- // combine term frequency- this.wordsintext = this.wordsintext + oe.wordsintext;- this.termFrequency = this.termFrequency + oe.termFrequency;- }-- public Bitfield flags() {- return flags;- }-- public long freshUntil() {- return freshUntil;- }-- public String getLanguage() {- return language;- }-- public char getType() {- return type;- }-- public int hitcount() {- return hitcount;- }-- public boolean isNewer(final Reference other) {- assert false; // should not be used- return false;- }-- public boolean isOlder(final Reference other) {- assert false; // should not be used- return false;- }-- public long lastModified() {- return lastModified;- }-- public int llocal() {- return llocal;- }-- public int lother() {- return lother;- }-- public int phrasesintext() {- return phrasesintext;- }-- public int posinphrase() {- return posinphrase;- }-- public int posintext() {- return posintext;- }-- public int posofphrase() {- return posofphrase;- }-- public ReferenceRow toRowEntry() {- return new ReferenceRow(- urlHash,- urllength, // byte-length of complete URL- urlcomps, // number of path components- wordsintitle, // length of description/length (longer are better?)- hitcount, // how often appears this word in the text- wordsintext, // total number of words- phrasesintext, // total number of phrases- posintext, // position of word in all words- posinphrase, // position of word in its phrase- posofphrase, // number of the phrase where word appears- lastModified, // last-modified time of the document where word appears- System.currentTimeMillis(), // update time;- language, // (guessed) language of document- type, // type of document- llocal, // outlinks to same domain- lother, // outlinks to other domain- flags // attributes to the url and to the word according the url- );- }-- public String toPropertyForm() {- return toRowEntry().toPropertyForm();- }-- public String urlHash() {- return urlHash;- }-- public int urlcomps() {- return urlcomps;- }-- public int urllength() {- return urllength;- }-- public int virtualAge() {- return virtualAge;- }-- public int worddistance() {- return worddistance;- }-- public int wordsintext() {- return wordsintext;- }-- public int wordsintitle() {- return wordsintitle;- }-- public double termFrequency() {- if (this.termFrequency == 0.0) this.termFrequency = (((double) this.hitcount()) / ((double) (this.wordsintext() + this.wordsintitle() + 1)));- return this.termFrequency;- }-- public final void min(final ReferenceVars other) {- int v;- long w;- double d;- if (this.hitcount > (v = other.hitcount)) this.hitcount = v;- if (this.llocal > (v = other.llocal)) this.llocal = v;- if (this.lother > (v = other.lother)) this.lother = v;- if (this.virtualAge > (v = other.virtualAge)) this.virtualAge = v;- if (this.wordsintext > (v = other.wordsintext)) this.wordsintext = v;- if (this.phrasesintext > (v = other.phrasesintext)) this.phrasesintext = v;- if (this.posintext > (v = other.posintext)) this.posintext = v;- if (this.posinphrase > (v = other.posinphrase)) this.posinphrase = v;- if (this.posofphrase > (v = other.posofphrase)) this.posofphrase = v;- if (this.worddistance > (v = other.worddistance)) this.worddistance = v;- if (this.lastModified > (w = other.lastModified)) this.lastModified = w;- if (this.freshUntil > (w = other.freshUntil)) this.freshUntil = w;- if (this.urllength > (v = other.urllength)) this.urllength = v;- if (this.urlcomps > (v = other.urlcomps)) this.urlcomps = v;- if (this.wordsintitle > (v = other.wordsintitle)) this.wordsintitle = v;- if (this.termFrequency > (d = other.termFrequency)) this.termFrequency = d;- }-- public final void max(final ReferenceVars other) {- int v;- long w;- double d;- if (this.hitcount < (v = other.hitcount)) this.hitcount = v;- if (this.llocal < (v = other.llocal)) this.llocal = v;- if (this.lother < (v = other.lother)) this.lother = v;- if (this.virtualAge < (v = other.virtualAge)) this.virtualAge = v;- if (this.wordsintext < (v = other.wordsintext)) this.wordsintext = v;- if (this.phrasesintext < (v = other.phrasesintext)) this.phrasesintext = v;- if (this.posintext < (v = other.posintext)) this.posintext = v;- if (this.posinphrase < (v = other.posinphrase)) this.posinphrase = v;- if (this.posofphrase < (v = other.posofphrase)) this.posofphrase = v;- if (this.worddistance < (v = other.worddistance)) this.worddistance = v;- if (this.lastModified < (w = other.lastModified)) this.lastModified = w;- if (this.freshUntil < (w = other.freshUntil)) this.freshUntil = w;- if (this.urllength < (v = other.urllength)) this.urllength = v;- if (this.urlcomps < (v = other.urlcomps)) this.urlcomps = v;- if (this.wordsintitle < (v = other.wordsintitle)) this.wordsintitle = v;- if (this.termFrequency < (d = other.termFrequency)) this.termFrequency = d;- }-- public void join(final Reference oe) {- // joins two entries into one entry-- // combine the distance- this.worddistance = Math.abs(this.posintext() - oe.posintext());- this.posintext = Math.min(this.posintext, oe.posintext());- this.posinphrase = (this.posofphrase == oe.posofphrase()) ? Math.min(this.posinphrase, oe.posinphrase()) : 0;- this.posofphrase = Math.min(this.posofphrase, oe.posofphrase());-- // combine term frequency- this.termFrequency = this.termFrequency + oe.termFrequency();- this.wordsintext = this.wordsintext + oe.wordsintext();- }-- public int hashCode() {- return this.urlHash.hashCode();- }-}+// ReferenceVars.java+// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 07.11.2007 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import de.anomic.kelondro.order.Bitfield;+import de.anomic.kelondro.order.MicroDate;++public class ReferenceVars implements Reference, Cloneable {++ public Bitfield flags;+ public long freshUntil, lastModified;+ public String language, urlHash;+ public char type;+ public int hitcount, llocal, lother, phrasesintext, posintext,+ posinphrase, posofphrase,+ urlcomps, urllength, virtualAge,+ worddistance, wordsintext, wordsintitle;+ public double termFrequency;++ public ReferenceVars(final String urlHash,+ final int urlLength, // byte-length of complete URL+ final int urlComps, // number of path components+ final int titleLength, // length of description/length (longer are better?)+ final int hitcount, // how often appears this word in the text+ final int wordcount, // total number of words+ final int phrasecount, // total number of phrases+ final int posintext, // position of word in all words+ final int posinphrase, // position of word in its phrase+ final int posofphrase, // number of the phrase where word appears+ final long lastmodified, // last-modified time of the document where word appears+ final long updatetime, // update time; this is needed to compute a TTL for the word, so it can be removed easily if the TTL is short+ String language, // (guessed) language of document+ final char doctype, // type of document+ final int outlinksSame, // outlinks to same domain+ final int outlinksOther, // outlinks to other domain+ final Bitfield flags, // attributes to the url and to the word according the url+ final int worddistance,+ final double termfrequency+ ) {+ if ((language == null) || (language.length() != 2)) language = "uk";+ final int mddlm = MicroDate.microDateDays(lastmodified);+ final int mddct = MicroDate.microDateDays(updatetime);+ this.flags = flags;+ this.freshUntil = Math.max(0, mddlm + (mddct - mddlm) * 2);+ this.lastModified = lastmodified;+ this.language = language;+ this.urlHash = urlHash;+ this.type = doctype;+ this.hitcount = hitcount;+ this.llocal = outlinksSame;+ this.lother = outlinksOther;+ this.phrasesintext = outlinksOther;+ this.posintext = posintext;+ this.posinphrase = posinphrase;+ this.posofphrase = posofphrase;+ this.urlcomps = urlComps;+ this.urllength = urlLength;+ this.virtualAge = mddlm;+ this.worddistance = worddistance;+ this.wordsintext = wordcount;+ this.wordsintitle = titleLength;+ this.termFrequency = termfrequency;+ }++ public ReferenceVars(final ReferenceRow e) {+ this.flags = e.flags();+ this.freshUntil = e.freshUntil();+ this.lastModified = e.lastModified();+ this.language = e.getLanguage();+ this.urlHash = e.urlHash();+ this.type = e.getType();+ this.hitcount = e.hitcount();+ this.llocal = e.llocal();+ this.lother = e.lother();+ this.phrasesintext = e.phrasesintext();+ this.posintext = e.posintext();+ this.posinphrase = e.posinphrase();+ this.posofphrase = e.posofphrase();+ this.urlcomps = e.urlcomps();+ this.urllength = e.urllength();+ this.virtualAge = e.virtualAge();+ this.worddistance = 0;+ this.wordsintext = e.wordsintext();+ this.wordsintitle = e.wordsintitle();+ this.termFrequency = e.termFrequency();+ }++ public ReferenceVars clone() {+ final ReferenceVars c = new ReferenceVars(+ this.urlHash,+ this.urllength,+ this.urlcomps,+ this.wordsintitle,+ this.hitcount,+ this.wordsintext,+ this.phrasesintext,+ this.posintext,+ this.posinphrase,+ this.posofphrase,+ this.lastModified,+ System.currentTimeMillis(),+ this.language,+ this.type,+ this.llocal,+ this.lother,+ this.flags,+ this.worddistance,+ this.termFrequency);+ return c;+ }++ public void join(final ReferenceVars oe) {+ // combine the distance+ this.worddistance = this.worddistance + oe.worddistance + Math.abs(this.posintext - oe.posintext);+ this.posintext = Math.min(this.posintext, oe.posintext);+ this.posinphrase = (this.posofphrase == oe.posofphrase) ? Math.min(this.posinphrase, oe.posinphrase) : 0;+ this.posofphrase = Math.min(this.posofphrase, oe.posofphrase);++ // combine term frequency+ this.wordsintext = this.wordsintext + oe.wordsintext;+ this.termFrequency = this.termFrequency + oe.termFrequency;+ }++ public Bitfield flags() {+ return flags;+ }++ public long freshUntil() {+ return freshUntil;+ }++ public String getLanguage() {+ return language;+ }++ public char getType() {+ return type;+ }++ public int hitcount() {+ return hitcount;+ }++ public boolean isNewer(final Reference other) {+ assert false; // should not be used+ return false;+ }++ public boolean isOlder(final Reference other) {+ assert false; // should not be used+ return false;+ }++ public long lastModified() {+ return lastModified;+ }++ public int llocal() {+ return llocal;+ }++ public int lother() {+ return lother;+ }++ public int phrasesintext() {+ return phrasesintext;+ }++ public int posinphrase() {+ return posinphrase;+ }++ public int posintext() {+ return posintext;+ }++ public int posofphrase() {+ return posofphrase;+ }++ public ReferenceRow toRowEntry() {+ return new ReferenceRow(+ urlHash,+ urllength, // byte-length of complete URL+ urlcomps, // number of path components+ wordsintitle, // length of description/length (longer are better?)+ hitcount, // how often appears this word in the text+ wordsintext, // total number of words+ phrasesintext, // total number of phrases+ posintext, // position of word in all words+ posinphrase, // position of word in its phrase+ posofphrase, // number of the phrase where word appears+ lastModified, // last-modified time of the document where word appears+ System.currentTimeMillis(), // update time;+ language, // (guessed) language of document+ type, // type of document+ llocal, // outlinks to same domain+ lother, // outlinks to other domain+ flags // attributes to the url and to the word according the url+ );+ }++ public String toPropertyForm() {+ return toRowEntry().toPropertyForm();+ }++ public String urlHash() {+ return urlHash;+ }++ public int urlcomps() {+ return urlcomps;+ }++ public int urllength() {+ return urllength;+ }++ public int virtualAge() {+ return virtualAge;+ }++ public int worddistance() {+ return worddistance;+ }++ public int wordsintext() {+ return wordsintext;+ }++ public int wordsintitle() {+ return wordsintitle;+ }++ public double termFrequency() {+ if (this.termFrequency == 0.0) this.termFrequency = (((double) this.hitcount()) / ((double) (this.wordsintext() + this.wordsintitle() + 1)));+ return this.termFrequency;+ }++ public final void min(final ReferenceVars other) {+ int v;+ long w;+ double d;+ if (this.hitcount > (v = other.hitcount)) this.hitcount = v;+ if (this.llocal > (v = other.llocal)) this.llocal = v;+ if (this.lother > (v = other.lother)) this.lother = v;+ if (this.virtualAge > (v = other.virtualAge)) this.virtualAge = v;+ if (this.wordsintext > (v = other.wordsintext)) this.wordsintext = v;+ if (this.phrasesintext > (v = other.phrasesintext)) this.phrasesintext = v;+ if (this.posintext > (v = other.posintext)) this.posintext = v;+ if (this.posinphrase > (v = other.posinphrase)) this.posinphrase = v;+ if (this.posofphrase > (v = other.posofphrase)) this.posofphrase = v;+ if (this.worddistance > (v = other.worddistance)) this.worddistance = v;+ if (this.lastModified > (w = other.lastModified)) this.lastModified = w;+ if (this.freshUntil > (w = other.freshUntil)) this.freshUntil = w;+ if (this.urllength > (v = other.urllength)) this.urllength = v;+ if (this.urlcomps > (v = other.urlcomps)) this.urlcomps = v;+ if (this.wordsintitle > (v = other.wordsintitle)) this.wordsintitle = v;+ if (this.termFrequency > (d = other.termFrequency)) this.termFrequency = d;+ }++ public final void max(final ReferenceVars other) {+ int v;+ long w;+ double d;+ if (this.hitcount < (v = other.hitcount)) this.hitcount = v;+ if (this.llocal < (v = other.llocal)) this.llocal = v;+ if (this.lother < (v = other.lother)) this.lother = v;+ if (this.virtualAge < (v = other.virtualAge)) this.virtualAge = v;+ if (this.wordsintext < (v = other.wordsintext)) this.wordsintext = v;+ if (this.phrasesintext < (v = other.phrasesintext)) this.phrasesintext = v;+ if (this.posintext < (v = other.posintext)) this.posintext = v;+ if (this.posinphrase < (v = other.posinphrase)) this.posinphrase = v;+ if (this.posofphrase < (v = other.posofphrase)) this.posofphrase = v;+ if (this.worddistance < (v = other.worddistance)) this.worddistance = v;+ if (this.lastModified < (w = other.lastModified)) this.lastModified = w;+ if (this.freshUntil < (w = other.freshUntil)) this.freshUntil = w;+ if (this.urllength < (v = other.urllength)) this.urllength = v;+ if (this.urlcomps < (v = other.urlcomps)) this.urlcomps = v;+ if (this.wordsintitle < (v = other.wordsintitle)) this.wordsintitle = v;+ if (this.termFrequency < (d = other.termFrequency)) this.termFrequency = d;+ }++ public void join(final Reference oe) {+ // joins two entries into one entry++ // combine the distance+ this.worddistance = Math.abs(this.posintext() - oe.posintext());+ this.posintext = Math.min(this.posintext, oe.posintext());+ this.posinphrase = (this.posofphrase == oe.posofphrase()) ? Math.min(this.posinphrase, oe.posinphrase()) : 0;+ this.posofphrase = Math.min(this.posofphrase, oe.posofphrase());++ // combine term frequency+ this.termFrequency = this.termFrequency + oe.termFrequency();+ this.wordsintext = this.wordsintext + oe.wordsintext();+ }++ public int hashCode() {+ return this.urlHash.hashCode();+ }+}diff --git a/source/de/anomic/kelondro/text/URLMetadata.java b/source/de/anomic/kelondro/text/URLMetadata.javaindex d1fe9e441..fa2df81f8 100644--- a/source/de/anomic/kelondro/text/URLMetadata.java+++ b/source/de/anomic/kelondro/text/URLMetadata.java@@ -1,3 +1,29 @@+// URLMetadata.java+// (C) 2009 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 02.03.2009 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+package de.anomic.kelondro.text;import java.net.MalformedURLException;diff --git a/source/de/anomic/kelondro/text/Word.java b/source/de/anomic/kelondro/text/Word.javaindex 804a53b21..543536f8d 100644--- a/source/de/anomic/kelondro/text/Word.java+++ b/source/de/anomic/kelondro/text/Word.java@@ -1,112 +1,112 @@-// Word.java-// (C) 2008 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany-// first published 26.03.2008 on http://yacy.net-//-// This is a part of YaCy, a peer-to-peer based web search engine-//-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $-// $LastChangedRevision: 1986 $-// $LastChangedBy: orbiter $-//-// LICENSE-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA--package de.anomic.kelondro.text;--import java.util.HashSet;-import java.util.Iterator;-import java.util.Locale;-import java.util.Set;-import java.util.TreeSet;-import java.util.concurrent.ConcurrentHashMap;--import de.anomic.kelondro.order.Base64Order;-import de.anomic.kelondro.order.Bitfield;-import de.anomic.kelondro.order.Digest;-import de.anomic.yacy.yacySeedDB;--public class Word {-- private static final ConcurrentHashMap<String, String> hashCache = new ConcurrentHashMap<String, String>(1000);-- // object carries statistics for words and sentences- public int count; // number of occurrences- public int posInText; // unique handle, is initialized with word position (excluding double occurring words)- public int posInPhrase; // position of word in phrase- public int numOfPhrase; // number of phrase. 'normal' phrases begin with number 100- HashSet<Integer> phrases; // a set of handles to all phrases where this word appears- public Bitfield flags; // the flag bits for each word-- public Word(final int handle, final int pip, final int nop) {- this.count = 1;- this.posInText = handle;- this.posInPhrase = pip;- this.numOfPhrase = nop;- this.phrases = new HashSet<Integer>();- this.flags = null;- }-- public void inc() {- count++;- }-- public int occurrences() {- return count;- }-- public void check(final int i) {- phrases.add(Integer.valueOf(i));- }-- public Iterator<Integer> phrases() {- // returns an iterator to handles of all phrases where the word appears- return phrases.iterator();- }-- // static methods-- // create a word hash- public static final String word2hash(final String word) {- String h = hashCache.get(word);- if (h != null) return h;- h = Base64Order.enhancedCoder.encode(Digest.encodeMD5Raw(word.toLowerCase(Locale.ENGLISH))).substring(0, yacySeedDB.commonHashLength);- hashCache.put(word, h); // prevent expensive MD5 computation and encoding- if (hashCache.size() > 20000) {- // prevent memory leak- hashCache.clear();- }- return h;- }-- public static final Set<String> words2hashSet(final String[] words) {- final TreeSet<String> hashes = new TreeSet<String>(Base64Order.enhancedComparator);- for (int i = 0; i < words.length; i++) hashes.add(word2hash(words[i]));- return hashes;- }-- public static final String words2hashString(final String[] words) {- final StringBuilder sb = new StringBuilder();- for (int i = 0; i < words.length; i++) sb.append(word2hash(words[i]));- return new String(sb);- }-- public static final TreeSet<String> words2hashes(final Set<String> words) {- final Iterator<String> i = words.iterator();- final TreeSet<String> hashes = new TreeSet<String>(Base64Order.enhancedComparator);- while (i.hasNext()) hashes.add(word2hash(i.next()));- return hashes;- }-}+// Word.java+// (C) 2008 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany+// first published 26.03.2008 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate$+// $LastChangedRevision$+// $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+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.kelondro.text;++import java.util.HashSet;+import java.util.Iterator;+import java.util.Locale;+import java.util.Set;+import java.util.TreeSet;+import java.util.concurrent.ConcurrentHashMap;++import de.anomic.kelondro.order.Base64Order;+import de.anomic.kelondro.order.Bitfield;+import de.anomic.kelondro.order.Digest;+import de.anomic.yacy.yacySeedDB;++public class Word {++ private static final ConcurrentHashMap<String, String> hashCache = new ConcurrentHashMap<String, String>(1000);++ // object carries statistics for words and sentences+ public int count; // number of occurrences+ public int posInText; // unique handle, is initialized with word position (excluding double occurring words)+ public int posInPhrase; // position of word in phrase+ public int numOfPhrase; // number of phrase. 'normal' phrases begin with number 100+ HashSet<Integer> phrases; // a set of handles to all phrases where this word appears+ public Bitfield flags; // the flag bits for each word++ public Word(final int handle, final int pip, final int nop) {+ this.count = 1;+ this.posInText = handle;+ this.posInPhrase = pip;+ this.numOfPhrase = nop;+ this.phrases = new HashSet<Integer>();+ this.flags = null;+ }++ public void inc() {+ count++;+ }++ public int occurrences() {+ return count;+ }++ public void check(final int i) {+ phrases.add(Integer.valueOf(i));+ }++ public Iterator<Integer> phrases() {+ // returns an iterator to handles of all phrases where the word appears+ return phrases.iterator();+ }++ // static methods++ // create a word hash+ public static final String word2hash(final String word) {+ String h = hashCache.get(word);+ if (h != null) return h;+ h = Base64Order.enhancedCoder.encode(Digest.encodeMD5Raw(word.toLowerCase(Locale.ENGLISH))).substring(0, yacySeedDB.commonHashLength);+ hashCache.put(word, h); // prevent expensive MD5 computation and encoding+ if (hashCache.size() > 20000) {+ // prevent memory leak+ hashCache.clear();+ }+ return h;+ }++ public static final Set<String> words2hashSet(final String[] words) {+ final TreeSet<String> hashes = new TreeSet<String>(Base64Order.enhancedComparator);+ for (int i = 0; i < words.length; i++) hashes.add(word2hash(words[i]));+ return hashes;+ }++ public static final String words2hashString(final String[] words) {+ final StringBuilder sb = new StringBuilder();+ for (int i = 0; i < words.length; i++) sb.append(word2hash(words[i]));+ return new String(sb);+ }++ public static final TreeSet<String> words2hashes(final Set<String> words) {+ final Iterator<String> i = words.iterator();+ final TreeSet<String> hashes = new TreeSet<String>(Base64Order.enhancedComparator);+ while (i.hasNext()) hashes.add(word2hash(i.next()));+ return hashes;+ }+}