Skip to content

Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance

*) Asynchronous queuing of crawl job URLs (stackCrawl) various checks like the blacklist check or the robots.txt disallow check are now done by a separate thread to unburden the indexer thread(s) TODO: maybe we have to introduce a threadpool here if it turn out that this single thread is a bottleneck because of the time consuming robots.txt downloads

thelia2fa75e688b5
diff --git a/htroot/Blacklist_p.java b/htroot/Blacklist_p.java
index dfbcf4ca2..58e845007 100644
--- a/htroot/Blacklist_p.java
+++ b/htroot/Blacklist_p.java
@@ -50,9 +50,9 @@
import java.io.File;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
-import java.util.Vector;
import de.anomic.data.listManager;
import de.anomic.http.httpHeader;
import de.anomic.plasma.plasmaSwitchboard;
@@ -154,7 +154,7 @@ public class Blacklist_p {
} // post != null
// Read the List
- final Vector list = listManager.getListArray(new File(listManager.listsPath, filename));
+ final ArrayList list = listManager.getListArray(new File(listManager.listsPath, filename));
final StringBuffer out = new StringBuffer(list.size() * 64);
final Iterator iter = list.iterator();
while (iter.hasNext()){
diff --git a/htroot/IndexControl_p.html b/htroot/IndexControl_p.html
index a5699b5de..14822f817 100644
--- a/htroot/IndexControl_p.html
+++ b/htroot/IndexControl_p.html
@@ -12,6 +12,7 @@
<form action="IndexControl_p.html" method="post" enctype="multipart/form-data">
<p>
The local index currently consists of (at least) #[wcount]# reverse word indexes and #[ucount]# URL references<br>
+To transfer the whole index to an other peer, click <a href="IndexTransfer_p.html">here</a>.<br>
<table border="0" cellpadding="5" cellspacing="0">
<tr valign="top" class="TableCellDark">
<td width="70">Word</td>
diff --git a/htroot/IndexControl_p.java b/htroot/IndexControl_p.java
index 3184049bf..902b91d22 100644
--- a/htroot/IndexControl_p.java
+++ b/htroot/IndexControl_p.java
@@ -127,17 +127,20 @@ public class IndexControl_p {
if (post.containsKey("keyhashdeleteall")) {
if ((delurl) || (delurlref)) {
// generate an urlx array
+ plasmaWordIndexEntity index = null;
try {
HashSet keyhashes = new HashSet();
keyhashes.add(keyhash);
- plasmaWordIndexEntity index = switchboard.searchManager.searchHashes(keyhashes, 10000);
+ index = switchboard.searchManager.searchHashes(keyhashes, 10000);
Enumeration en = index.elements(true);
int i = 0;
urlx = new String[index.size()];
while (en.hasMoreElements()) urlx[i++] = ((plasmaWordIndexEntry) en.nextElement()).getUrlHash();
- index.close();
+ index.close(); index = null;
} catch (IOException e) {
urlx = new String[0];
+ } finally {
+ if (index != null) try { index.close(); } catch (Exception e) {}
}
}
if (delurlref) for (int i = 0; i < urlx.length; i++) switchboard.removeAllUrlReferences(urlx[i], true);
@@ -233,7 +236,14 @@ public class IndexControl_p {
indexes[0].removeEntry((String) hashIter.next(), false);
} catch (IOException e) {}
// use whats remaining
- result = yacyClient.transferIndex(yacyCore.seedDB.getConnected(post.get("hostHash", "")), indexes, knownURLs);
+ String gzipBody = switchboard.getConfig("indexControl.gzipBody","false");
+ int timeout = (int) switchboard.getConfigLong("indexControl.timeout",60000);
+ result = yacyClient.transferIndex(
+ yacyCore.seedDB.getConnected(post.get("hostHash", "")),
+ indexes,
+ knownURLs,
+ "true".equalsIgnoreCase(gzipBody),
+ timeout);
prop.put("result", (result == null) ? ("Successfully transferred " + indexes[0].size() + " words in " + ((System.currentTimeMillis() - starttime) / 1000) + " seconds") : result);
try {indexes[0].close();} catch (IOException e) {}
}
@@ -370,10 +380,11 @@ public class IndexControl_p {
public static String genUrlList(plasmaSwitchboard switchboard, String keyhash, String keystring) {
// search for a word hash and generate a list of url links
+ plasmaWordIndexEntity index = null;
try {
HashSet keyhashes = new HashSet();
keyhashes.add(keyhash);
- plasmaWordIndexEntity index = switchboard.searchManager.searchHashes(keyhashes, 10000);
+ index = switchboard.searchManager.searchHashes(keyhashes, 10000);
String result = "";
if (index.size() == 0) {
result = "No URL entries related to this word hash <span class=\"tt\">" + keyhash + "</span>.";
@@ -416,10 +427,12 @@ public class IndexControl_p {
"<span class=\"small\">for every resolveable and deleted URL reference, delete the same reference at every other word where the reference exists (very extensive, but prevents further unresolved references)</span>" +
"</td></tr></table></fieldset></form>";
}
- index.close();
+ index.close(); index = null;
return result;
} catch (IOException e) {
return "";
+ } finally {
+ if (index != null) try { index.close(); } catch (Exception e) {};
}
}
diff --git a/htroot/IndexCreate_p.java b/htroot/IndexCreate_p.java
index a3f555952..d1f2674d2 100644
--- a/htroot/IndexCreate_p.java
+++ b/htroot/IndexCreate_p.java
@@ -160,7 +160,7 @@ public class IndexCreate_p {
// stack url
plasmaCrawlProfile.entry pe = switchboard.profiles.newEntry(crawlingStartURL.getHost(), crawlingStart, newcrawlingfilter, newcrawlingfilter, newcrawlingdepth, newcrawlingdepth, crawlingQ, storeHTCache, true, localIndexing, crawlOrder, xsstopw, xdstopw, xpstopw);
- String reasonString = switchboard.stackCrawl(crawlingStart, null, yacyCore.seedDB.mySeed.hash, "CRAWLING-ROOT", new Date(), 0, pe);
+ String reasonString = switchboard.sbStackCrawlThread.stackCrawl(crawlingStart, null, yacyCore.seedDB.mySeed.hash, "CRAWLING-ROOT", new Date(), 0, pe);
if (reasonString == null) {
// liftoff!
@@ -247,7 +247,7 @@ public class IndexCreate_p {
}
// enqueuing the url for crawling
- String rejectReason = switchboard.stackCrawl(nexturlstring, null, yacyCore.seedDB.mySeed.hash, (String)e.getValue(), new Date(), 1, profile);
+ String rejectReason = switchboard.sbStackCrawlThread.stackCrawl(nexturlstring, null, yacyCore.seedDB.mySeed.hash, (String)e.getValue(), new Date(), 1, profile);
// if something failed add the url into the errorURL list
if (rejectReason == null) {
diff --git a/htroot/IndexTransfer_p.html b/htroot/IndexTransfer_p.html
index 548347eb7..e85917716 100644
--- a/htroot/IndexTransfer_p.html
+++ b/htroot/IndexTransfer_p.html
@@ -1,8 +1,9 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
-<title>YaCy '#[clientname]#': Index Control</title>
+<title>YaCy '#[clientname]#': Index Transfer</title>
#[metas]#
+<meta http-equiv="REFRESH" content="30">
</head>
<body marginheight="0" marginwidth="0" leftmargin="0" topmargin="0">
#[header]#
@@ -14,18 +15,22 @@
<p>
<table border="0" cellpadding="2" cellspacing="1">
<tr class="TableHeader" valign="bottom">
+<td>&nbsp;</td>
<td class="small" >Status</td>
+<td class="small" >Chunk Size</td>
+<td class="small" >Words Range</td>
<td class="small" >Transfered Words</td>
-<td class="small" >Chunk Size: Words Range</td>
-<td class="small" >Delete Index</td>
-<td class="small" >Remote Peer</td>
+<td class="small" >Delete<br>Index</td>
+<td class="small" >Remote<br>Peer</td>
<td class="small" >Start/Stop Transfer</td>
</tr>
#(running)#
<tr valign="top" class="TableCellLight">
+<td class="TableHeader">-</td>
<td class="small">#[status]#</td>
<td class="small" align="center">-</td>
<td class="small" align="center">-</td>
+<td class="small" align="center">-</td>
<td class="small">
<select name="deleteIndex">
<option value="1">true</option>
@@ -44,19 +49,28 @@
</td>
</tr>
</table></p>
-::
+::
<tr class="TableCellLight">
- <td class="small"><font color="#(stopped)#green::red#(/stopped)#">#[status]#</font></td>
- <td class="small" align="right">#[twcount]# (#[twpercent]#%) </td>
- <td class="small" align="rigth">#[twchunk]# words: <tt>#[twrange]#</tt></td>
- <td class="small">#(deleteIndex)#false::true#(/deleteIndex)#</td>
- <td class="small">#[peerName]#</td>
- <td class="small">#(stopped)#<input type="submit" name="stopIndexTransfer" value="Stop Index Transfer">::
+ <td class="TableCellDark">Selection</td>
+ <td class="small" ><font color="#(stopped)#green::red#(/stopped)#">#[selection.status]#</font></td>
+ <td class="small" align="rigth">#[selection.twchunk]# words</td>
+ <td class="small" align="right"><tt>#[selection.twrange]#</tt></td>
+ <td class="small" rowspan="2" align="right">#[twcount]# (#[twpercent]#%)<br>#[twspeed]# words/s</td>
+ <td class="small" rowspan="2">#(deleteIndex)#false::true#(/deleteIndex)#</td>
+ <td class="small" rowspan="2">#[peerName]#</td>
+ <td class="small" rowspan="2">#(stopped)#<input type="submit" name="stopIndexTransfer" value="Stop Index Transfer">::
<input type="submit" name="newIndexTransfer" value="Start New Index Transfer">#(/stopped)#</td>
</tr>
+ <tr class="TableCellLight">
+ <td class="TableCellDark">Transfer</td>
+ <td class="small" ><font color="#(stopped)#green::red#(/stopped)#">#[transfer.status]#</font></td>
+ <td class="small" align="rigth">#[transfer.twchunk]# words</td>
+ <td class="small" align="right"><tt>#[transfer.twrange]#</tt></td>
+ </tr>
#(/running)#
</table>
</form>
+<p><font size="-3"><i>Last Refresh:</i> #[date]#</font></p>
#[footer]#
</body>
diff --git a/htroot/IndexTransfer_p.java b/htroot/IndexTransfer_p.java
index 34a160bf4..dab791d9c 100644
--- a/htroot/IndexTransfer_p.java
+++ b/htroot/IndexTransfer_p.java
@@ -46,6 +46,7 @@
//javac -classpath .:../Classes IndexControl_p.java
//if the shell's current path is HTROOT
+import java.util.Date;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.TreeMap;
@@ -58,7 +59,7 @@ import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacySeed;
-public class IndexTransfer_p {
+public final class IndexTransfer_p {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
// return variable that accumulates replacements
@@ -97,11 +98,23 @@ public class IndexTransfer_p {
prop.put("running",(transfThread==null)?0:1);
if (transfThread != null) {
int transferedIdxCount = transfThread.getTransferedIndexCount();
- prop.put("running_status",transfThread.getStatus());
+ String[] status = transfThread.getStatus();
+ String[] range = transfThread.getRange();
+ int[] chunk = transfThread.getChunkSize();
+
+ prop.put("running_selection.status",status[0]);
+ prop.put("running_selection.twrange", range[0]);
+ prop.put("running_selection.twchunk", Integer.toString(chunk[0]));
+
+ prop.put("running_transfer.status",status[1]);
+ prop.put("running_transfer.twrange", range[1]);
+ prop.put("running_transfer.twchunk", Integer.toString(chunk[1]));
+
+
prop.put("running_twcount",transferedIdxCount);
prop.put("running_twpercent",Float.toString(transfThread.getTransferedIndexPercent()));
- prop.put("running_twrange", transfThread.getRange());
- prop.put("running_twchunk", Integer.toString(transfThread.getChunkSize()));
+ prop.put("running_twspeed",Integer.toString(transfThread.getTransferedIndexSpeed()));
+
prop.put("running_deleteIndex", transfThread.deleteIndex()?1:0);
prop.put("running_peerName",transfThread.getSeed().getName());
prop.put("running_stopped",(transfThread.isFinished()) || (!transfThread.isAlive())?1:0);
@@ -136,6 +149,7 @@ public class IndexTransfer_p {
prop.put("running_hosts", "0");
}
+ prop.put("date",(new Date()).toString());
return prop;
}
diff --git a/htroot/Language_p.java b/htroot/Language_p.java
index eed851fc0..445e9c75b 100644
--- a/htroot/Language_p.java
+++ b/htroot/Language_p.java
@@ -51,15 +51,14 @@ import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
+import java.util.ArrayList;
import java.util.Iterator;
-import java.util.Vector;
import java.util.HashMap;
import de.anomic.data.listManager;
import de.anomic.http.httpHeader;
import de.anomic.http.httpc;
import de.anomic.plasma.plasmaSwitchboard;
-import de.anomic.server.serverFileUtils;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.data.translator;
@@ -132,7 +131,7 @@ public class Language_p {
//load language file from URL
} else if (post.containsKey("url")){
String url = (String)post.get("url");
- Vector langVector;
+ ArrayList langVector;
try{
langVector = httpc.wget(new URL(url), 6000, null, null, switchboard.remoteProxyHost, switchboard.remoteProxyPort);
}catch(IOException e){
diff --git a/htroot/SettingsAck_p.java b/htroot/SettingsAck_p.java
index eee824c51..f69e0dc33 100644
--- a/htroot/SettingsAck_p.java
+++ b/htroot/SettingsAck_p.java
@@ -396,11 +396,11 @@ public class SettingsAck_p {
* Loop through the available seed uploaders to see if the
* configuration of one of them has changed
*/
- Hashtable uploaders = yacyCore.getSeedUploadMethods();
- Enumeration uploaderKeys = uploaders.keys();
- while (uploaderKeys.hasMoreElements()) {
+ HashMap uploaders = yacyCore.getSeedUploadMethods();
+ Iterator uploaderKeys = uploaders.keySet().iterator();
+ while (uploaderKeys.hasNext()) {
// getting the uploader module name
- String uploaderName = (String) uploaderKeys.nextElement();
+ String uploaderName = (String) uploaderKeys.next();
// determining if the user has reconfigured the settings of this uploader
diff --git a/htroot/Settings_p.java b/htroot/Settings_p.java
index 4f2d3ac46..abe4702b5 100644
--- a/htroot/Settings_p.java
+++ b/htroot/Settings_p.java
@@ -46,6 +46,7 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
+import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
@@ -165,17 +166,17 @@ public final class Settings_p {
env.setConfig("seedUploadMethod",enabledUploader);
}
- Hashtable uploaders = yacyCore.getSeedUploadMethods();
+ HashMap uploaders = yacyCore.getSeedUploadMethods();
prop.put("seedUploadMethods", uploaders.size() + 1);
prop.put("seedUploadMethods_0_name", "none");
prop.put("seedUploadMethods_0_selected", enabledUploader.equals("none")?1:0);
prop.put("seedUploadMethods_0_file", "");
int count = 0;
- Enumeration uploaderKeys = uploaders.keys();
- while (uploaderKeys.hasMoreElements()) {
+ Iterator uploaderKeys = uploaders.keySet().iterator();
+ while (uploaderKeys.hasNext()) {
count++;
- String uploaderName = (String) uploaderKeys.nextElement();
+ String uploaderName = (String) uploaderKeys.next();
prop.put("seedUploadMethods_" +count+ "_name", uploaderName);
prop.put("seedUploadMethods_" +count+ "_selected", uploaderName.equals(enabledUploader)?1:0);
prop.put("seedUploadMethods_" +count+ "_file", new File(env.getRootPath(), "htroot/yacy/seedUpload/yacySeedUpload" + uploaderName + ".html").toString());
diff --git a/htroot/Skins_p.java b/htroot/Skins_p.java
index 701e38944..6ae0a0e90 100644
--- a/htroot/Skins_p.java
+++ b/htroot/Skins_p.java
@@ -51,8 +51,8 @@ import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
+import java.util.ArrayList;
import java.util.Iterator;
-import java.util.Vector;
import de.anomic.data.listManager;
import de.anomic.http.httpHeader;
@@ -122,7 +122,7 @@ public class Skins_p {
//load Skin from URL
} else if (post.containsKey("url")){
String url = (String)post.get("url");
- Vector skinVector;
+ ArrayList skinVector;
try{
skinVector = httpc.wget(new URL(url), 6000, null, null, switchboard.remoteProxyHost, switchboard.remoteProxyPort);
}catch(IOException e){
diff --git a/htroot/Status.java b/htroot/Status.java
index 92754534c..b24ec4eb1 100644
--- a/htroot/Status.java
+++ b/htroot/Status.java
@@ -236,8 +236,10 @@ public class Status {
prop.put("loaderQueueMax", Integer.toString(plasmaSwitchboard.crawlSlots));
prop.put("loaderPaused",sb.crawlingIsPaused()?1:0);
- prop.put("localCrawlQueueSize", Integer.toString(sb.getThread("50_localcrawl").getJobCount()));
+ prop.put("localCrawlQueueSize", Integer.toString(sb.getThread("50_localcrawl").getJobCount()));
+ prop.put("stackCrawlQueueSize", Integer.toString(sb.sbStackCrawlThread.getQueueSize()));
prop.put("remoteCrawlQueueSize", Integer.toString(sb.getThread("61_globalcrawltrigger").getJobCount()));
+
// return rewrite properties
return prop;
diff --git a/htroot/Status_p.inc b/htroot/Status_p.inc
index 2b393cf1c..abd4ca54f 100644
--- a/htroot/Status_p.inc
+++ b/htroot/Status_p.inc
@@ -31,7 +31,7 @@ Processors: #[processors]#
</td></tr>
<tr class="TableCellDark"><td>Indexing Queue</td><td>#[indexingQueueSize]# | #[indexingQueueMax]#</td></tr>
<tr class="TableCellLight"><td>Loader Queue</td><td>#[loaderQueueSize]# | #[loaderQueueMax]# #(loaderPaused)#::(paused)#(/loaderPaused)#</td></tr>
-<tr class="TableCellDark"><td>Local Crawler Queue</td><td>#[localCrawlQueueSize]#</td></tr>
+<tr class="TableCellDark"><td>Local Crawler Queue</td><td>Enqueued: #[localCrawlQueueSize]# | Pending: #[stackCrawlQueueSize]#</td></tr>
<tr class="TableCellLight"><td>Remote Crawler Queue</td><td>#[remoteCrawlQueueSize]#</td></tr>
diff --git a/htroot/ViewProfile.java b/htroot/ViewProfile.java
index b9f7dd369..d85db3ae4 100644
--- a/htroot/ViewProfile.java
+++ b/htroot/ViewProfile.java
@@ -46,10 +46,10 @@
// if the shell's current path is HTROOT
import java.io.IOException;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
-import java.util.Vector;
import de.anomic.http.httpHeader;
import de.anomic.plasma.plasmaSwitchboard;
@@ -94,7 +94,7 @@ public class ViewProfile {
Iterator i = profile.entrySet().iterator();
Map.Entry entry;
//all known keys which should be set as they are
- Vector knownKeys = new Vector();
+ ArrayList knownKeys = new ArrayList();
knownKeys.add("name");
knownKeys.add("nickname");
//knownKeys.add("homepage");//+http
diff --git a/htroot/sharedBlacklist_p.java b/htroot/sharedBlacklist_p.java
index 5672fcf28..8a16f3409 100644
--- a/htroot/sharedBlacklist_p.java
+++ b/htroot/sharedBlacklist_p.java
@@ -54,13 +54,12 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
+import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
-import java.util.Vector;
import de.anomic.http.httpHeader;
import de.anomic.http.httpc;
-import de.anomic.http.httpdProxyHandler;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverCore;
import de.anomic.server.serverObjects;
@@ -79,7 +78,7 @@ public class sharedBlacklist_p {
String line = "";
String out = "";
HashSet Blacklist = new HashSet();
- Vector otherBlacklist = new Vector();
+ ArrayList otherBlacklist = new ArrayList();
int num = 0;
int i = 0; //loop-var
int count = 0;
diff --git a/htroot/yacy/crawlOrder.java b/htroot/yacy/crawlOrder.java
index 57b962ee4..07b663caf 100644
--- a/htroot/yacy/crawlOrder.java
+++ b/htroot/yacy/crawlOrder.java
@@ -43,21 +43,19 @@
// javac -classpath .:../classes crawlOrder.java
-import java.net.URL;
+import java.util.ArrayList;
import java.util.Date;
-import java.util.Vector;
import de.anomic.http.httpHeader;
import de.anomic.plasma.plasmaCrawlLURL;
import de.anomic.plasma.plasmaSwitchboard;
-import de.anomic.plasma.plasmaURL;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.tools.crypt;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacySeed;
-public class crawlOrder {
+public final class crawlOrder {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
@@ -140,8 +138,8 @@ public class crawlOrder {
delay = "9999";
} else {
// read the urls/referrer-vector
- Vector urlv = new Vector();
- Vector refv = new Vector();
+ ArrayList urlv = new ArrayList();
+ ArrayList refv = new ArrayList();
String refencoded = (String) post.get("referrer", null);
String urlencoded = (String) post.get("url", null);
if (urlencoded != null) {
@@ -168,7 +166,7 @@ public class crawlOrder {
int count = Math.min(urlv.size(), refv.size());
if (count == 1) {
// old method: only one url
- stackresult = stack(switchboard, (String) urlv.elementAt(0), (String) refv.elementAt(0), iam, youare);
+ stackresult = stack(switchboard, (String) urlv.get(0), (String) refv.get(0), iam, youare);
response = (String) stackresult[0];
reason = (String) stackresult[1];
lurl = (String) stackresult[2];
@@ -179,7 +177,7 @@ public class crawlOrder {
int doubleCount = 0;
int rejectedCount = 0;
for (int i = 0; i < count; i++) {
- stackresult = stack(switchboard, (String) urlv.elementAt(i), (String) refv.elementAt(i), iam, youare);
+ stackresult = stack(switchboard, (String) urlv.get(i), (String) refv.get(i), iam, youare);
response = (String) stackresult[0];
prop.put("list_" + i + "_job", (String) stackresult[0] + "," + (String) stackresult[1]);
prop.put("list_" + i + "_lurl", (String) stackresult[2]);
@@ -215,7 +213,7 @@ public class crawlOrder {
private static Object[] stack(plasmaSwitchboard switchboard, String url, String referrer, String iam, String youare) {
String response, reason, lurl;
// stack url
- String reasonString = switchboard.stackCrawl(url, referrer, iam, "REMOTE-CRAWLING", new Date(), 0, switchboard.defaultRemoteProfile);
+ String reasonString = switchboard.sbStackCrawlThread.stackCrawl(url, referrer, iam, "REMOTE-CRAWLING", new Date(), 0, switchboard.defaultRemoteProfile);
if (reasonString == null) {
// liftoff!
response = "stacked";
diff --git a/htroot/yacy/crawlReceipt.java b/htroot/yacy/crawlReceipt.java
index e70010c9f..4f8fdf483 100644
--- a/htroot/yacy/crawlReceipt.java
+++ b/htroot/yacy/crawlReceipt.java
@@ -54,7 +54,7 @@ import de.anomic.tools.bitfield;
import de.anomic.tools.crypt;
import de.anomic.yacy.yacyCore;
-public class crawlReceipt {
+public final class crawlReceipt {
/*
diff --git a/htroot/yacy/hello.java b/htroot/yacy/hello.java
index 42b4fae1c..9bc59d63e 100644
--- a/htroot/yacy/hello.java
+++ b/htroot/yacy/hello.java
@@ -59,7 +59,7 @@ import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacySeed;
import de.anomic.yacy.yacyVersion;
-public class hello {
+public final class hello {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
final serverObjects prop = new serverObjects(); // return variable that accumulates replacements
diff --git a/htroot/yacy/list.java b/htroot/yacy/list.java
index 040e01ddf..18c0f337c 100644
--- a/htroot/yacy/list.java
+++ b/htroot/yacy/list.java
@@ -55,7 +55,7 @@ import de.anomic.server.serverCore;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
-public class list {
+public final class list {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
// return variable that accumulates replacements
diff --git a/htroot/yacy/message.java b/htroot/yacy/message.java
index 5f494013a..fe8b1dedd 100644
--- a/htroot/yacy/message.java
+++ b/htroot/yacy/message.java
@@ -61,7 +61,7 @@ import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacySeed;
import de.anomic.yacy.yacySeedDB;
-public class message {
+public final class message {
private static SimpleDateFormat SimpleFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
public static String dateString(Date date) {
diff --git a/htroot/yacy/profile.java b/htroot/yacy/profile.java
index 5942d0f5f..2bba3d776 100644
--- a/htroot/yacy/profile.java
+++ b/htroot/yacy/profile.java
@@ -56,7 +56,7 @@ import de.anomic.http.httpHeader;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
-public class profile {
+public final class profile {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
serverObjects prop = new serverObjects(); // return variable that accumulates replacements
diff --git a/htroot/yacy/query.java b/htroot/yacy/query.java
index ad3ac4141..d326b7345 100644
--- a/htroot/yacy/query.java
+++ b/htroot/yacy/query.java
@@ -43,7 +43,6 @@
// javac -classpath .:../../Classes query.java
// if the shell's current path is HTROOT
-import java.util.Hashtable;
import java.util.Date;
import java.io.IOException;
@@ -53,7 +52,7 @@ import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyCore;
-public class query {
+public final class query {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch sb) {
// return variable that accumulates replacements
@@ -84,12 +83,15 @@ public class query {
if (obj.equals("rwiurlcount")) {
// the total number of different urls in the rwi is returned
// <env> shall contain a word hash, the number of assigned lurls to this hash is returned
+ de.anomic.plasma.plasmaWordIndexEntity entity = null;
try {
- de.anomic.plasma.plasmaWordIndexEntity entity = switchboard.wordIndex.getEntity(env, true);
+ entity = switchboard.wordIndex.getEntity(env, true);
prop.put("response", entity.size());
entity.close();
} catch (IOException e) {
prop.put("response", -1);
+ } finally {
+ if (entity != null) try { entity.close(); } catch (Exception e) {}
}
return prop;
}
diff --git a/htroot/yacy/search.java b/htroot/yacy/search.java
index c0b34e50a..ac864b159 100644
--- a/htroot/yacy/search.java
+++ b/htroot/yacy/search.java
@@ -55,7 +55,7 @@ import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacySeed;
-public class search {
+public final class search {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
@@ -82,7 +82,7 @@ public class search {
yacyCore.peerActions.peerArrival(yacySeed.genRemoteSeed(oseed, key), true);
}
- HashSet keyhashes = new HashSet();
+ HashSet keyhashes = new HashSet(query.length() / plasmaWordIndexEntry.wordHashLength);
for (int i = 0; i < (query.length() / plasmaWordIndexEntry.wordHashLength); i++) {
keyhashes.add(query.substring(i * plasmaWordIndexEntry.wordHashLength, (i + 1) * plasmaWordIndexEntry.wordHashLength));
}
diff --git a/htroot/yacy/transferRWI.java b/htroot/yacy/transferRWI.java
index a6c2675e1..9898dfe2b 100644
--- a/htroot/yacy/transferRWI.java
+++ b/htroot/yacy/transferRWI.java
@@ -45,9 +45,10 @@
// You must compile this file with
// javac -classpath .:../classes transferRWI.java
+
+import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
-import java.util.Vector;
import de.anomic.http.httpHeader;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.plasma.plasmaWordIndexEntry;
@@ -58,17 +59,19 @@ import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacySeed;
import de.anomic.yacy.yacyDHTAction;
-public class transferRWI {
+public final class transferRWI {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch ss) {
if (post == null || ss == null) { return new serverObjects(); }
- // return variable that accumulates replacements
+ long start = System.currentTimeMillis();
+
+ // return variable that accumulates replacements
final serverObjects prop = new serverObjects();
final plasmaSwitchboard sb = (plasmaSwitchboard) ss;
if (prop == null || sb == null) { return new serverObjects(); }
- // request values
+ // request values
final String iam = (String) post.get("iam", ""); // seed hash of requester
// final String youare = (String) post.get("youare", ""); // seed hash of the target peer, needed for network stability
// final String key = (String) post.get("key", ""); // transmission key
@@ -76,21 +79,21 @@ public class transferRWI {
final int entryc = Integer.parseInt((String) post.get("entryc", "")); // number of entries in indexes
final byte[] indexes = ((String) post.get("indexes", "")).getBytes(); // the indexes, as list of word entries
final boolean granted = sb.getConfig("allowReceiveIndex", "false").equals("true");
-
+
// response values
String result = "";
StringBuffer unknownURLs = new StringBuffer();
-
+
final yacySeed otherPeer = yacyCore.seedDB.get(iam);
final String otherPeerName = iam + ":" + ((otherPeer == null) ? "NULL" : (otherPeer.getName() + "/" + otherPeer.getVersion()));
-
+
if (granted) {
// log value status (currently added to find outOfMemory error
sb.getLog().logFine("Processing " + indexes.length + " bytes / " + wordc + " words / " + entryc + " entries from " + otherPeerName);
final long startProcess = System.currentTimeMillis();
-
+
// decode request
- final Vector v = new Vector();
+ ArrayList v = new ArrayList();
int s = 0;
int e;
while (s < indexes.length) {
@@ -100,7 +103,7 @@ public class transferRWI {
}
// the value-vector should now have the same length as entryc
if (v.size() != entryc) sb.getLog().logSevere("ERROR WITH ENTRY COUNTER: v=" + v.size() + ", entryc=" + entryc);
-
+
// now parse the Strings in the value-vector and write index entries
String estring;
int p;
@@ -111,7 +114,7 @@ public class transferRWI {
String[] wordhashes = new String[v.size()];
int received = 0;
for (int i = 0; i < v.size(); i++) {
- estring = (String) v.elementAt(i);
+ estring = (String) v.get(i);
p = estring.indexOf("{");
if (p > 0) {
wordHash = estring.substring(0, p);
@@ -127,7 +130,7 @@ public class transferRWI {
}
}
yacyCore.seedDB.mySeed.incRI(received);
-
+
// finally compose the unknownURL hash list
final Iterator it = unknownURL.iterator();
while (it.hasNext()) {
@@ -145,12 +148,12 @@ public class transferRWI {
sb.getLog().logInfo("Rejecting RWIs from peer " + otherPeerName + ". Not granted.");
result = "error_not_granted";
}
-
+
prop.put("unknownURL", unknownURLs.toString());
prop.put("result", result);
-
- // return rewrite properties
- return prop;
+
+ // return rewrite properties
+ return prop;
}
-}
\ No newline at end of file
+}
diff --git a/htroot/yacy/transferURL.java b/htroot/yacy/transferURL.java
index 5e1446b1c..afcecaadb 100644
--- a/htroot/yacy/transferURL.java
+++ b/htroot/yacy/transferURL.java
@@ -43,11 +43,7 @@
// javac -classpath .:../classes transferRWI.java
-import java.net.URL;
-import java.net.MalformedURLException;
-
import de.anomic.http.httpHeader;
-import de.anomic.http.httpdProxyHandler;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.plasma.plasmaCrawlLURL;
import de.anomic.server.serverObjects;
@@ -55,9 +51,11 @@ import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacySeed;
-public class transferURL {
+public final class transferURL {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
+ long start = System.currentTimeMillis();
+
// return variable that accumulates replacements
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
@@ -92,7 +90,7 @@ public class transferURL {
} else {
lEntry = switchboard.urlPool.loadedURL.newEntry(urls, true);
if ((lEntry != null) && (blockBlacklist)) {
- if (switchboard.urlBlacklist.isListed(lEntry.url().getHost().toLowerCase(), lEntry.url().getPath())) {
+ if (plasmaSwitchboard.urlBlacklist.isListed(lEntry.url().getHost().toLowerCase(), lEntry.url().getPath())) {
yacyCore.log.logFine("transferURL: blocked blacklisted URL '" + lEntry.url() + "' from peer " + otherPeerName);
lEntry = null;
}
@@ -110,7 +108,8 @@ public class transferURL {
// return rewrite properties
int more = switchboard.urlPool.loadedURL.size() - sizeBefore;
doublevalues = Integer.toString(received - more);
- switchboard.getLog().logInfo("Received " + received + " URLs from peer " + otherPeerName);
+ switchboard.getLog().logInfo("Received " + received + " URLs from peer " + otherPeerName +
+ " in " + (System.currentTimeMillis() - start) + " ms.");
if ((received - more) > 0) switchboard.getLog().logSevere("Received " + doublevalues + " double URLs from peer " + otherPeerName);
result = "ok";
} else {
diff --git a/source/de/anomic/data/listManager.java b/source/de/anomic/data/listManager.java
index 772ad673b..855a5adb4 100644
--- a/source/de/anomic/data/listManager.java
+++ b/source/de/anomic/data/listManager.java
@@ -51,11 +51,9 @@ import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
+import java.util.ArrayList;
import java.util.Iterator;
-import java.util.TreeMap;
-import java.util.Vector;
-import de.anomic.http.httpdProxyHandler;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverCore;
@@ -118,9 +116,9 @@ public class listManager {
//================generel Lists==================
//Gets a Array of all lines(Items) of a (list)file
- public static Vector getListArray(File listFile){
+ public static ArrayList getListArray(File listFile){
String line;
- Vector list = new Vector();
+ ArrayList list = new ArrayList();
int count = 0;
BufferedReader br = null;
try{
@@ -204,7 +202,7 @@ public class listManager {
return null;
}
- public static Vector getDirsRecursive(File dir){
+ public static ArrayList getDirsRecursive(File dir){
return getDirsRecursive(dir, true);
}
/**
@@ -212,10 +210,10 @@ public class listManager {
*
* Warning: untested
*/
- public static Vector getDirsRecursive(File dir, boolean excludeDotfiles){
+ public static ArrayList getDirsRecursive(File dir, boolean excludeDotfiles){
File[] dirList = dir.listFiles();
- Vector resultList = new Vector();
- Vector recursive;
+ ArrayList resultList = new ArrayList();
+ ArrayList recursive;
Iterator it;
for(int i=0;i<dirList.length;i++){
if(dirList[i].isDirectory() && (!excludeDotfiles || !dirList[i].getName().startsWith(".")) ){
diff --git a/source/de/anomic/data/robotsParser.java b/source/de/anomic/data/robotsParser.java
index a2927e2d6..cf9c867c7 100644
--- a/source/de/anomic/data/robotsParser.java
+++ b/source/de/anomic/data/robotsParser.java
@@ -1,52 +1,51 @@
-// robotsParser.java
-// -------------------------------------
-// part of YACY
-// (C) by Michael Peter Christen; [email protected]
-// first published on http://www.anomic.de
-// Frankfurt, Germany, 2004
+//robotsParser.java
+//-------------------------------------
+//part of YACY
+//(C) by Michael Peter Christen; [email protected]
+//first published on http://www.anomic.de
+//Frankfurt, Germany, 2004
//
-// This file ist contributed by Alexander Schier
-// last major change: $LastChangedDate$ by $LastChangedBy$
-// Revision: $LastChangedRevision$
+//This file ist contributed by Alexander Schier
+//last major change: $LastChangedDate$ by $LastChangedBy$
+//Revision: $LastChangedRevision$
//
-// 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 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.
+//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
+//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
//
-// Using this software in any meaning (reading, learning, copying, compiling,
-// running) means that you agree that the Author(s) is (are) not responsible
-// for cost, loss of data or any harm that may be caused directly or indirectly
-// by usage of this softare or this documentation. The usage of this software
-// is on your own risk. The installation and usage (starting/running) of this
-// software may allow other people or application to access your computer and
-// any attached devices and is highly dependent on the configuration of the
-// software which must be done by the user of the software; the author(s) is
-// (are) also not responsible for proper configuration and usage of the
-// software, even if provoked by documentation provided together with
-// the software.
+//Using this software in any meaning (reading, learning, copying, compiling,
+//running) means that you agree that the Author(s) is (are) not responsible
+//for cost, loss of data or any harm that may be caused directly or indirectly
+//by usage of this softare or this documentation. The usage of this software
+//is on your own risk. The installation and usage (starting/running) of this
+//software may allow other people or application to access your computer and
+//any attached devices and is highly dependent on the configuration of the
+//software which must be done by the user of the software; the author(s) is
+//(are) also not responsible for proper configuration and usage of the
+//software, even if provoked by documentation provided together with
+//the software.
//
-// Any changes to this file according to the GPL as documented in the file
-// gpl.txt aside this file in the shipment you received can be done to the
-// lines that follows this copyright notice here, but changes must not be
-// done inside the copyright notive above. A re-distribution must contain
-// the intact and unchanged copyright notice.
-// Contributions and changes to the program code must be marked as such.
+//Any changes to this file according to the GPL as documented in the file
+//gpl.txt aside this file in the shipment you received can be done to the
+//lines that follows this copyright notice here, but changes must not be
+//done inside the copyright notive above. A re-distribution must contain
+//the intact and unchanged copyright notice.
+//Contributions and changes to the program code must be marked as such.
package de.anomic.data;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
@@ -78,16 +77,21 @@ import de.anomic.server.logging.serverLog;
*/
public final class robotsParser{
- /*public robotsParser(URL robotsUrl){
- }*/
- /*
- * this parses the robots.txt.
- * at the Moment it only creates a list of Deny Paths
- */
-
+ /*public robotsParser(URL robotsUrl){
+ }*/
+ /*
+ * this parses the robots.txt.
+ * at the Moment it only creates a list of Deny Paths
+ */
+
public static ArrayList parse(File robotsFile) throws IOException {
- BufferedReader reader = new BufferedReader(new FileReader(robotsFile));
- return parse(reader);
+ BufferedReader reader = null;
+ try {
+ reader = new BufferedReader(new FileReader(robotsFile));
+ return parse(reader);
+ } finally {
+ if (reader != null) try{reader.close();}catch(Exception e){}
+ }
}
public static ArrayList parse(byte[] robotsTxt) throws IOException {
@@ -97,7 +101,7 @@ public final class robotsParser{
return parse(reader);
}
- public static ArrayList parse(BufferedReader reader) throws IOException{
+ public static ArrayList parse(BufferedReader reader) throws IOException{
ArrayList deny = new ArrayList();
int pos;
@@ -135,8 +139,8 @@ public final class robotsParser{
}
return deny;
- }
-
+ }
+
public static boolean containsRobotsData(URL nexturl) {
// generating the hostname:poart string needed to do a DB lookup
String urlHostPort = nexturl.getHost() + ":" + ((nexturl.getPort()==-1)?80:nexturl.getPort());
@@ -147,15 +151,12 @@ public final class robotsParser{
// if we have not found any data or the data is older than 7 days, we need to load it from the remote server
if ((robotsTxt4Host == null) || (robotsTxt4Host.getLoadedDate() == null) ||
- (System.currentTimeMillis() - robotsTxt4Host.getLoadedDate().getTime() > 7*24*60*60*1000)) {
+ (System.currentTimeMillis() - robotsTxt4Host.getLoadedDate().getTime() > 7*24*60*60*1000)) {
return false;
}
return true;
}
-// public static boolean enqueueRobotsCheck(String nexturlString, String referrerString, String initiatorHash, String name, Date loadDate, int currentdepth, plasmaCrawlProfile.entry profile) {
-//
-// }
public static boolean isDisallowed(URL nexturl) {
if (nexturl == null) throw new IllegalArgumentException();
@@ -168,8 +169,11 @@ public final class robotsParser{
plasmaCrawlRobotsTxt.Entry robotsTxt4Host = plasmaSwitchboard.robots.getEntry(urlHostPort);
// if we have not found any data or the data is older than 7 days, we need to load it from the remote server
- if ((robotsTxt4Host == null) || (robotsTxt4Host.getLoadedDate() == null) ||
- (System.currentTimeMillis() - robotsTxt4Host.getLoadedDate().getTime() > 7*24*60*60*1000)) {
+ if (
+ (robotsTxt4Host == null) ||
+ (robotsTxt4Host.getLoadedDate() == null) ||
+ (System.currentTimeMillis() - robotsTxt4Host.getLoadedDate().getTime() > 7*24*60*60*1000)
+ ) {
URL robotsURL = null;
// generating the proper url to download the robots txt
try {
@@ -179,32 +183,42 @@ public final class robotsParser{
return false;
}
+ Object[] result = null;
boolean accessCompletelyRestricted = false;
byte[] robotsTxt = null;
+ String eTag = null;
+ Date modDate = null;
try {
- Object[] result = downloadRobotsTxt(robotsURL,5);
- accessCompletelyRestricted = ((Boolean)result[0]).booleanValue();
- robotsTxt = (byte[])result[1];
+ serverLog.logFine("ROBOTS","Trying to download the robots.txt file from URL '" + robotsURL + "'.");
+ result = downloadRobotsTxt(robotsURL,5,robotsTxt4Host);
+ if (result != null) {
+ accessCompletelyRestricted = ((Boolean)result[0]).booleanValue();
+ robotsTxt = (byte[])result[1];
+ eTag = (String) result[2];
+ modDate = (Date) result[3];
+ }
} catch (Exception e) {
serverLog.logSevere("ROBOTS","Unable to download the robots.txt file from URL '" + robotsURL + "'. " + e.getMessage());
}
- ArrayList denyPath = null;
- if (accessCompletelyRestricted) {
- denyPath = new ArrayList();
- denyPath.add("/");
- } else {
- // parsing the robots.txt Data and converting it into an arraylist
- try {
- denyPath = robotsParser.parse(robotsTxt);
- } catch (IOException e) {
- serverLog.logSevere("ROBOTS","Unable to parse the robots.txt file from URL '" + robotsURL + "'.");
- }
- }
-
- // storing the data into the robots DB
- robotsTxt4Host = plasmaSwitchboard.robots.addEntry(urlHostPort,denyPath,new Date());
+ if ((robotsTxt4Host==null)||((robotsTxt4Host!=null)&&(result!=null))) {
+ ArrayList denyPath = null;
+ if (accessCompletelyRestricted) {
+ denyPath = new ArrayList();
+ denyPath.add("/");
+ } else {
+ // parsing the robots.txt Data and converting it into an arraylist
+ try {
+ denyPath = robotsParser.parse(robotsTxt);
+ } catch (IOException e) {
+ serverLog.logSevere("ROBOTS","Unable to parse the robots.txt file from URL '" + robotsURL + "'.");
+ }
+ }
+
+ // storing the data into the robots DB
+ robotsTxt4Host = plasmaSwitchboard.robots.addEntry(urlHostPort,denyPath,new Date(),modDate,eTag);
+ }
}
if (robotsTxt4Host.isDisallowed(nexturl.getPath())) {
@@ -213,7 +227,7 @@ public final class robotsParser{
return false;
}
- private static Object[] downloadRobotsTxt(URL robotsURL, int redirectionCount) throws Exception {
+ private static Object[] downloadRobotsTxt(URL robotsURL, int redirectionCount, plasmaCrawlRobotsTxt.Entry entry) throws Exception {
if (redirectionCount < 0) return new Object[]{Boolean.FALSE,null};
redirectionCount--;
@@ -221,7 +235,11 @@ public final class robotsParser{
boolean accessCompletelyRestricted = false;
byte[] robotsTxt = null;
httpc con = null;
+ long downloadStart, downloadEnd;
+ String eTag=null, oldEtag = null;
+ Date lastMod=null;
try {
+ downloadStart = System.currentTimeMillis();
plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
if (!sb.remoteProxyUse) {
con = httpc.getInstance(robotsURL.getHost(), robotsURL.getPort(), 10000, false);
@@ -229,34 +247,57 @@ public final class robotsParser{
con = httpc.getInstance(robotsURL.getHost(), robotsURL.getPort(), 10000, false, sb.remoteProxyHost, sb.remoteProxyPort);
}
- httpc.response res = con.GET(robotsURL.getPath(), null);
+ // if we previously have downloaded this robots.txt then we can set the if-modified-since header
+ httpHeader reqHeaders = new httpHeader();
+ if (entry != null) {
+ oldEtag = entry.getETag();
+ reqHeaders = new httpHeader();
+ Date modDate = entry.getModDate();
+ if (modDate != null) reqHeaders.put(httpHeader.IF_MODIFIED_SINCE,entry.getModDate());
+ }
+
+ httpc.response res = con.GET(robotsURL.getPath(), reqHeaders);
if (res.status.startsWith("2")) {
if (!res.responseHeader.mime().startsWith("text/plain")) {
robotsTxt = null;
serverLog.logFinest("ROBOTS","Robots.txt from URL '" + robotsURL + "' has wrong mimetype '" + res.responseHeader.mime() + "'.");
} else {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- res.writeContent(bos, null);
+
+ // getting some metadata
+ eTag = res.responseHeader.containsKey(httpHeader.ETAG)?((String)res.responseHeader.get(httpHeader.ETAG)).trim():null;
+ lastMod = res.responseHeader.lastModified();
+
+ // if the robots.txt file was not changed we break here
+ if ((eTag != null) && (oldEtag != null) && (eTag.equals(oldEtag))) {
+ serverLog.logFinest("ROBOTS","Robots.txt from URL '" + robotsURL + "' was not modified. Abort downloading of new version.");
+ return null;
+ }
+
+ // downloading the content
+ robotsTxt = res.writeContent();
con.close();
- robotsTxt = bos.toByteArray();
- serverLog.logFinest("ROBOTS","Robots.txt successfully loaded from URL '" + robotsURL + "'.");
+
+ downloadEnd = System.currentTimeMillis();
+ serverLog.logFinest("ROBOTS","Robots.txt successfully loaded from URL '" + robotsURL + "' in " + (downloadEnd-downloadStart) + " ms.");
}
+ } else if (res.status.startsWith("304")) {
+ return null;
} else if (res.status.startsWith("3")) {
// getting redirection URL
String redirectionUrlString = (String) res.responseHeader.get(httpHeader.LOCATION);
redirectionUrlString = redirectionUrlString.trim();
-
+
// generating the new URL object
URL redirectionUrl = new URL(robotsURL, redirectionUrlString);
-
+
// returning the used httpc
httpc.returnInstance(con);
con = null;
// following the redirection
serverLog.logFinest("ROBOTS","Redirection detected for robots.txt with URL '" + robotsURL + "'." +
- "\nRedirecting request to: " + redirectionUrl);
- return downloadRobotsTxt(redirectionUrl,redirectionCount);
+ "\nRedirecting request to: " + redirectionUrl);
+ return downloadRobotsTxt(redirectionUrl,redirectionCount,entry);
} else if (res.status.startsWith("401") || res.status.startsWith("403")) {
accessCompletelyRestricted = true;
@@ -270,6 +311,6 @@ public final class robotsParser{
} finally {
if (con != null) httpc.returnInstance(con);
}
- return new Object[]{new Boolean(accessCompletelyRestricted),robotsTxt};
+ return new Object[]{new Boolean(accessCompletelyRestricted),robotsTxt,eTag,lastMod};
}
}
diff --git a/source/de/anomic/data/translator.java b/source/de/anomic/data/translator.java
index 509130261..6965edbec 100644
--- a/source/de/anomic/data/translator.java
+++ b/source/de/anomic/data/translator.java
@@ -51,6 +51,7 @@ import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
+import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
@@ -82,7 +83,7 @@ public class translator {
Hashtable translationList = new Hashtable(); //current Translation Table
FileInputStream fileIn = null;
- Vector list = listManager.getListArray(translationFile);
+ ArrayList list = listManager.getListArray(translationFile);
Iterator it = list.iterator();
String line = "";
String value = "";
@@ -182,7 +183,7 @@ public class translator {
}
public static boolean translateFilesRecursive(File sourceDir, File destDir, File translationFile, String extension){
- Vector dirList=listManager.getDirsRecursive(sourceDir);
+ ArrayList dirList=listManager.getDirsRecursive(sourceDir);
Iterator it=dirList.iterator();
String sourceName=sourceDir.getPath();
String destName=destDir.getPath();
diff --git a/source/de/anomic/data/wikiBoard.java b/source/de/anomic/data/wikiBoard.java
index 3004099bd..1cb1e3b43 100644
--- a/source/de/anomic/data/wikiBoard.java
+++ b/source/de/anomic/data/wikiBoard.java
@@ -47,7 +47,6 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
-import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.TimeZone;
@@ -68,7 +67,7 @@ public class wikiBoard {
private kelondroMap datbase = null;
private kelondroMap bkpbase = null;
- private Hashtable authors = new Hashtable();
+ private HashMap authors = new HashMap();
private int sn = 0;
public wikiBoard(File actpath, File bkppath, int bufferkb) throws IOException {
diff --git a/source/de/anomic/htmlFilter/htmlFilterContentTransformer.java b/source/de/anomic/htmlFilter/htmlFilterContentTransformer.java
index 2cc646ee0..6a40ba69f 100644
--- a/source/de/anomic/htmlFilter/htmlFilterContentTransformer.java
+++ b/source/de/anomic/htmlFilter/htmlFilterContentTransformer.java
@@ -44,10 +44,10 @@ import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.Collator;
+import java.util.ArrayList;
import java.util.Locale;
import java.util.Properties;
import java.util.TreeSet;
-import java.util.Vector;
import de.anomic.server.serverByteBuffer;
@@ -70,7 +70,7 @@ public class htmlFilterContentTransformer extends htmlFilterAbstractTransformer
linkTags1.add("a");
}
- private static Vector bluelist = null;
+ private static ArrayList bluelist = null;
public htmlFilterContentTransformer() {
super(linkTags0, linkTags1);
@@ -80,7 +80,7 @@ public class htmlFilterContentTransformer extends htmlFilterAbstractTransformer
//System.out.println("Transformer init: " + initarg);
if (bluelist == null) {
// here, the initarg is used to load a list of bluelisted words
- bluelist = new Vector();
+ bluelist = new ArrayList();
File f = new File(initarg);
if ((f.exists()) && (f.canRead())) try {
BufferedReader r = new BufferedReader(new FileReader(f));
@@ -111,7 +111,7 @@ public class htmlFilterContentTransformer extends htmlFilterAbstractTransformer
private boolean hit(byte[] text) {
if ((text == null) || (bluelist == null)) return false;
String lc = new String(text).toLowerCase();
- for (int i = 0; i < bluelist.size(); i++) if (lc.indexOf((String) bluelist.elementAt(i)) >= 0) return true;
+ for (int i = 0; i < bluelist.size(); i++) if (lc.indexOf((String) bluelist.get(i)) >= 0) return true;
return false;
}
diff --git a/source/de/anomic/htmlFilter/htmlFilterOutputStream.java b/source/de/anomic/htmlFilter/htmlFilterOutputStream.java
index 753cdc404..06952da56 100644
--- a/source/de/anomic/htmlFilter/htmlFilterOutputStream.java
+++ b/source/de/anomic/htmlFilter/htmlFilterOutputStream.java
@@ -56,9 +56,9 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
+import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Properties;
-import java.util.Vector;
import de.anomic.server.serverByteBuffer;
@@ -484,7 +484,7 @@ public final class htmlFilterOutputStream extends OutputStream {
byte[] buffer = new byte[512];
try {
htmlFilterContentScraper lc = new htmlFilterContentScraper(new URL("http://www.anomic.de/"));
- Vector v = new Vector();
+ ArrayList v = new ArrayList();
v.add("proxy");
htmlFilterTransformer lt = new htmlFilterContentTransformer();
InputStream is = new FileInputStream(args[0]);
diff --git a/source/de/anomic/http/httpChunkedInputStream.java b/source/de/anomic/http/httpChunkedInputStream.java
index 9c4c2addc..87211ed22 100644
--- a/source/de/anomic/http/httpChunkedInputStream.java
+++ b/source/de/anomic/http/httpChunkedInputStream.java
@@ -45,11 +45,12 @@ package de.anomic.http;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
+import de.anomic.server.serverByteBuffer;
+
/**
* Some parts of this class code was copied from <a href="http://www.devdaily.com/java/jwarehouse/commons-httpclient-2.0/src/java/org/apache/commons/httpclient/ChunkedInputStream.shtml">Apache httpclient Project.</a>
* @author theli
@@ -142,9 +143,9 @@ public final class httpChunkedInputStream extends InputStream {
private void readTrailer() throws IOException {
BufferedReader reader = null;
- ByteArrayOutputStream bout = null;
+ serverByteBuffer bout = null;
try {
- bout = new ByteArrayOutputStream();
+ bout = new serverByteBuffer();
do {
int ch;
while ((ch = this.inputStream.read()) >= 0) {
@@ -153,7 +154,7 @@ public final class httpChunkedInputStream extends InputStream {
break;
}
}
- if (bout.size() <= 2) break;
+ if (bout.length() <= 2) break;
} while(true);
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
@@ -172,7 +173,7 @@ public final class httpChunkedInputStream extends InputStream {
private static int readChunkFromStream(final InputStream in)
throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ serverByteBuffer baos = new serverByteBuffer();
int state = 0;
while (state != READ_CHUNK_STATE_FINISHED) {
int b = in.read();
diff --git a/source/de/anomic/http/httpc.java b/source/de/anomic/http/httpc.java
index 2baffc348..0a6bc2cc4 100644
--- a/source/de/anomic/http/httpc.java
+++ b/source/de/anomic/http/httpc.java
@@ -40,7 +40,6 @@
package de.anomic.http;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -60,11 +59,9 @@ import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
-import java.util.Hashtable;
import java.util.Iterator;
import java.util.Locale;
import java.util.TimeZone;
-import java.util.Vector;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
@@ -92,7 +89,7 @@ public final class httpc {
/**
* Specifies that the httpc is allowed to use gzip content encoding for
* http post requests
- * @see #POST(String, httpHeader, serverObjects, Hashtable)
+ * @see #POST(String, httpHeader, serverObjects, HashMap)
*/
public static final String GZIP_POST_BODY = "GZIP_POST_BODY";
@@ -180,7 +177,7 @@ public final class httpc {
*/
final serverByteBuffer readLineBuffer = new serverByteBuffer(100);
- private static final Hashtable openSocketLookupTable = new Hashtable();
+ private static final HashMap openSocketLookupTable = new HashMap();
/**
* Convert the status of this class into an String object to output it.
@@ -741,12 +738,12 @@ public final class httpc {
* @param path The path to the page which the post is sent to.
* @param requestHeader Prefilled httpHeader.
* @param args serverObjects with the names of the files to send.
- * @param files Hashtable with the names of the files as key and the content
+ * @param files HashMap with the names of the files as key and the content
* of the files as value.
* @return Instance of response with the content.
* @throws IOException
*/
- public response POST(String path, httpHeader requestHeader, serverObjects args, Hashtable files) throws IOException {
+ public response POST(String path, httpHeader requestHeader, serverObjects args, HashMap files) throws IOException {
// make shure, the header has a boundary information like
// CONTENT-TYPE=multipart/form-data; boundary=----------0xKhTmLbOuNdArY
if (requestHeader == null) requestHeader = new httpHeader();
@@ -771,7 +768,7 @@ public final class httpc {
OutputStream out;
GZIPOutputStream zippedOut;
- ByteArrayOutputStream buf = new ByteArrayOutputStream();
+ serverByteBuffer buf = new serverByteBuffer();
if (zipContent) {
zippedOut = new GZIPOutputStream(buf);
out = zippedOut;
@@ -791,7 +788,7 @@ public final class httpc {
out.write(serverCore.crlf);
// write value
key = (String) e.nextElement();
- value = (String) args.get(key, "");
+ value = args.get(key, "");
if ((files != null) && (files.containsKey(key))) {
// we are about to write a file
out.write(("Content-Disposition: form-data; name=" + '"' + key + '"' + "; filename=" + '"' + value + '"').getBytes());
@@ -816,6 +813,8 @@ public final class httpc {
// create body array
out.close();
byte[] body = buf.toByteArray();
+ buf = null; out = null;
+
//System.out.println("DEBUG: PUT BODY=" + new String(body));
if (zipContent) {
requestHeader.put(httpHeader.CONTENT_ENCODING, "gzip");
@@ -907,10 +906,7 @@ do upload
httpc.response res = con.GET(path, null);
if (res.status.startsWith("2")) {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- res.writeContent(bos, null);
- con.close();
- return bos.toByteArray();
+ return res.writeContent();
} else {
return res.status.getBytes();
}
@@ -964,10 +960,7 @@ do upload
//System.out.println("response=" + res.toString());
if (res.status.startsWith("2")) {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- res.writeContent(bos, null);
- con.close();
- return bos.toByteArray();
+ return res.writeContent();
} else {
return res.status.getBytes();
}
@@ -1000,13 +993,13 @@ do upload
}
}
- public static Vector wget(URL url, int timeout, String user, String password, String proxyHost, int proxyPort) throws IOException {
+ public static ArrayList wget(URL url, int timeout, String user, String password, String proxyHost, int proxyPort) throws IOException {
// splitting of the byte array into lines
byte[] a = singleGET(url, timeout, user, password, proxyHost, proxyPort);
if (a == null) return null;
int s = 0;
int e;
- Vector v = new Vector();
+ ArrayList v = new ArrayList();
while (s < a.length) {
e = s; while (e < a.length) if (a[e++] < 32) {e--; break;}
v.add(new String(a, s, e - s));
@@ -1065,13 +1058,13 @@ do upload
}
*/
- public static Vector wput(URL url, int timeout, String user, String password, String proxyHost, int proxyPort, serverObjects props) throws IOException {
+ public static ArrayList wput(URL url, int timeout, String user, String password, String proxyHost, int proxyPort, serverObjects props) throws IOException {
// splitting of the byte array into lines
byte[] a = singlePOST(url, timeout, user, password, proxyHost, proxyPort, props);
//System.out.println("wput-out=" + new String(a));
int s = 0;
int e;
- Vector v = new Vector();
+ ArrayList v = new ArrayList();
while (s < a.length) {
e = s; while (e < a.length) if (a[e++] < 32) {e--; break;}
v.add(new String(a, s, e - s));
@@ -1097,7 +1090,7 @@ do upload
System.out.println("ANOMIC.DE HTTP CLIENT v" + vDATE);
String url = args[0];
if (!(url.toUpperCase().startsWith("HTTP://"))) url = "http://" + url;
- Vector text = new Vector();
+ ArrayList text = new ArrayList();
if (args.length == 4) {
int timeout = Integer.parseInt(args[1]);
String proxyHost = args[2];
@@ -1118,8 +1111,8 @@ do upload
}
text = wput(url, post);
}*/
- Enumeration i = text.elements();
- while (i.hasMoreElements()) System.out.println((String) i.nextElement());
+ Iterator i = text.listIterator();
+ while (i.hasNext()) System.out.println((String) i.next());
}
/**
diff --git a/source/de/anomic/http/httpd.java b/source/de/anomic/http/httpd.java
index af5656f60..ebb9a85f5 100644
--- a/source/de/anomic/http/httpd.java
+++ b/source/de/anomic/http/httpd.java
@@ -49,7 +49,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
-import java.io.PushbackInputStream;
import java.lang.reflect.Constructor;
import java.net.InetAddress;
import java.net.MalformedURLException;
diff --git a/source/de/anomic/http/httpdFileHandler.java b/source/de/anomic/http/httpdFileHandler.java
index b7449e3a6..85c20808f 100644
--- a/source/de/anomic/http/httpdFileHandler.java
+++ b/source/de/anomic/http/httpdFileHandler.java
@@ -91,7 +91,6 @@ import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
@@ -114,15 +113,17 @@ public final class httpdFileHandler extends httpdAbstractHandler implements http
// class variables
private static final Properties mimeTable = new Properties();
- private serverClassLoader provider = null;
- private File htRootPath = null;
- private File htDocsPath = null;
- private File htTemplatePath = null;
+ private static final serverClassLoader provider;
private static final HashMap templates = new HashMap();
- private String[] defaultFiles = null;
- private File htDefaultPath = null;
- private File htLocalePath = null;
- private serverSwitch switchboard;
+ private static serverSwitch switchboard;
+
+ private static File htRootPath = null;
+ private static File htDocsPath = null;
+ private static File htTemplatePath = null;
+ private static String[] defaultFiles = null;
+ private static File htDefaultPath = null;
+ private static File htLocalePath = null;
+
private MessageDigest md5Digest = null;
/**
@@ -135,68 +136,71 @@ public final class httpdFileHandler extends httpdAbstractHandler implements http
static {
useTemplateCache = plasmaSwitchboard.getSwitchboard().getConfig("enableTemplateCache","true").equalsIgnoreCase("true");
+
+ // create a class loader
+ provider = new serverClassLoader(/*this.getClass().getClassLoader()*/);
}
public httpdFileHandler(serverSwitch switchboard) {
- this.switchboard = switchboard;
// creating a logger
this.theLogger = new serverLog("FILEHANDLER");
- if (mimeTable.size() == 0) {
- // load the mime table
- String mimeTablePath = switchboard.getConfig("mimeConfig","");
- FileInputStream mimeTableInputStream = null;
- try {
- serverLog.logConfig("HTTPDFiles", "Loading mime mapping file " + mimeTablePath);
- mimeTableInputStream = new FileInputStream(new File(switchboard.getRootPath(), mimeTablePath));
- mimeTable.load(mimeTableInputStream);
- } catch (Exception e) {
- serverLog.logSevere("HTTPDFiles", "ERROR: path to configuration file or configuration invalid\n" + e);
- System.exit(1);
- } finally {
- if (mimeTableInputStream != null) try { mimeTableInputStream.close(); } catch (Exception e1) {}
+ if (httpdFileHandler.switchboard == null) {
+ httpdFileHandler.switchboard = switchboard;
+
+ if (mimeTable.size() == 0) {
+ // load the mime table
+ String mimeTablePath = switchboard.getConfig("mimeConfig","");
+ BufferedInputStream mimeTableInputStream = null;
+ try {
+ serverLog.logConfig("HTTPDFiles", "Loading mime mapping file " + mimeTablePath);
+ mimeTableInputStream = new BufferedInputStream(new FileInputStream(new File(switchboard.getRootPath(), mimeTablePath)));
+ mimeTable.load(mimeTableInputStream);
+ } catch (Exception e) {
+ serverLog.logSevere("HTTPDFiles", "ERROR: path to configuration file or configuration invalid\n" + e);
+ System.exit(1);
+ } finally {
+ if (mimeTableInputStream != null) try { mimeTableInputStream.close(); } catch (Exception e1) {}
+ }
}
+
+ // create default files array
+ defaultFiles = switchboard.getConfig("defaultFiles","index.html").split(",");
+ if (defaultFiles.length == 0) defaultFiles = new String[] {"index.html"};
+
+ // create a htRootPath: system pages
+ if (htRootPath == null) {
+ htRootPath = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot"));
+ if (!(htRootPath.exists())) htRootPath.mkdir();
+ }
+
+ // create a htDocsPath: user defined pages
+ if (htDocsPath == null) {
+ htDocsPath = new File(switchboard.getRootPath(), switchboard.getConfig("htDocsPath", "htdocs"));
+ if (!(htDocsPath.exists())) htDocsPath.mkdir();
+ }
+
+ // create a htTemplatePath
+ if (htTemplatePath == null) {
+ htTemplatePath = new File(switchboard.getRootPath(), switchboard.getConfig("htTemplatePath","htroot/env/templates"));
+ if (!(htTemplatePath.exists())) htTemplatePath.mkdir();
+ }
+ if (templates.size() == 0) templates.putAll(loadTemplates(htTemplatePath));
+
+ // create htLocaleDefault, htLocalePath
+ if (htDefaultPath == null) htDefaultPath = new File(switchboard.getRootPath(), switchboard.getConfig("htDefaultPath","htroot"));
+ if (htLocalePath == null) htLocalePath = new File(switchboard.getRootPath(), switchboard.getConfig("htLocalePath","htroot/locale"));
+ //htLocaleSelection = switchboard.getConfig("htLocaleSelection","default");
}
- // create default files array
- defaultFiles = switchboard.getConfig("defaultFiles","index.html").split(",");
- if (defaultFiles.length == 0) defaultFiles = new String[] {"index.html"};
-
- // create a htRootPath: system pages
- if (htRootPath == null) {
- htRootPath = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot"));
- if (!(htRootPath.exists())) htRootPath.mkdir();
- }
-
- // create a htDocsPath: user defined pages
- if (htDocsPath == null) {
- htDocsPath = new File(switchboard.getRootPath(), switchboard.getConfig("htDocsPath", "htdocs"));
- if (!(htDocsPath.exists())) htDocsPath.mkdir();
- }
-
- // create a htTemplatePath
- if (htTemplatePath == null) {
- htTemplatePath = new File(switchboard.getRootPath(), switchboard.getConfig("htTemplatePath","htroot/env/templates"));
- if (!(htTemplatePath.exists())) htTemplatePath.mkdir();
- }
- if (templates.size() == 0) templates.putAll(loadTemplates(htTemplatePath));
+
- // create htLocaleDefault, htLocalePath
- if (htDefaultPath == null) htDefaultPath = new File(switchboard.getRootPath(), switchboard.getConfig("htDefaultPath","htroot"));
- if (htLocalePath == null) htLocalePath = new File(switchboard.getRootPath(), switchboard.getConfig("htLocalePath","htroot/locale"));
- //htLocaleSelection = switchboard.getConfig("htLocaleSelection","default");
+
- // create a class loader
- if (provider == null) {
- provider = new serverClassLoader(/*this.getClass().getClassLoader()*/);
- // debug
- /*
- Package[] ps = ((cachedClassLoader) provider).packages();
- for (int i = 0; i < ps.length; i++) System.out.println("PACKAGE IN PROVIDER: " + ps[i].toString());
- */
- }
+
+
// initialise an message digest for Content-MD5 support ...
try {
this.md5Digest = MessageDigest.getInstance("MD5");
@@ -308,11 +312,12 @@ public final class httpdFileHandler extends httpdAbstractHandler implements http
//System.out.println("HEADER: " + requestHeader.toString()); // DEBUG
if (method.equals(httpHeader.METHOD_POST)) {
+ GZIPInputStream gzipBody = null;
if (requestHeader.containsKey(httpHeader.CONTENT_LENGTH)) {
length = Integer.parseInt((String) requestHeader.get(httpHeader.CONTENT_LENGTH));
} else if (requestHeader.gzip()) {
length = -1;
- body = new GZIPInputStream(body);
+ gzipBody = new GZIPInputStream(body);
} else {
httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null);
return;
@@ -322,7 +327,7 @@ public final class httpdFileHandler extends httpdAbstractHandler implements http
if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) &&
(((String) requestHeader.get(httpHeader.CONTENT_TYPE)).toLowerCase().startsWith("multipart"))) {
// parse multipart
- HashMap files = httpd.parseMultipart(requestHeader, args, body, length);
+ HashMap files = httpd.parseMultipart(requestHeader, args, (gzipBody!=null)?gzipBody:body, length);
// integrate these files into the args
if (files != null) {
Iterator fit = files.entrySet().iterator();
@@ -335,7 +340,7 @@ public final class httpdFileHandler extends httpdAbstractHandler implements http
argc = Integer.parseInt((String) requestHeader.get("ARGC"));
} else {
// parse args in body
- argc = httpd.parseArgs(args, body, length);
+ argc = httpd.parseArgs(args, (gzipBody!=null)?gzipBody:body, length);
}
} else {
// no args
diff --git a/source/de/anomic/http/httpdProxyAccount.java b/source/de/anomic/http/httpdProxyAccount.java
index b38a02185..7af175ee5 100644
--- a/source/de/anomic/http/httpdProxyAccount.java
+++ b/source/de/anomic/http/httpdProxyAccount.java
@@ -1,3 +1,5 @@
+package de.anomic.http;
+
import java.net.InetAddress;
public final class httpdProxyAccount {
diff --git a/source/de/anomic/http/httpdProxyHandler.java b/source/de/anomic/http/httpdProxyHandler.java
index 603ff2b14..0528d3df0 100644
--- a/source/de/anomic/http/httpdProxyHandler.java
+++ b/source/de/anomic/http/httpdProxyHandler.java
@@ -543,8 +543,7 @@ public final class httpdProxyHandler extends httpdAbstractHandler implements htt
// handle file types and make (possibly transforming) output stream
if (
(!transformer.isIdentityTransformer()) &&
- (plasmaParser.supportedFileExt(url)) &&
- (plasmaParser.realtimeParsableMimeTypesContains(res.responseHeader.mime()))
+ (plasmaParser.supportedRealTimeContent(url,res.responseHeader.mime()))
) {
// make a transformer
this.theLogger.logFine("create transformer for URL " + url);
diff --git a/source/de/anomic/kelondro/kelondroStack.java b/source/de/anomic/kelondro/kelondroStack.java
index ac8e8b74e..f15240e96 100644
--- a/source/de/anomic/kelondro/kelondroStack.java
+++ b/source/de/anomic/kelondro/kelondroStack.java
@@ -52,10 +52,9 @@ import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Iterator;
-import java.util.LinkedList;
import java.util.StringTokenizer;
-public class kelondroStack extends kelondroRecords {
+public final class kelondroStack extends kelondroRecords {
// define the Over-Head-Array
private static short thisOHBytes = 0; // our record definition does not need extra bytes
diff --git a/source/de/anomic/net/natLib.java b/source/de/anomic/net/natLib.java
index 38811249d..1251fc551 100644
--- a/source/de/anomic/net/natLib.java
+++ b/source/de/anomic/net/natLib.java
@@ -42,7 +42,7 @@ package de.anomic.net;
import java.net.InetAddress;
import java.net.URL;
-import java.util.Vector;
+import java.util.ArrayList;
import de.anomic.http.httpc;
import de.anomic.server.serverCore;
@@ -60,7 +60,7 @@ public class natLib {
rm status.htm
*/
try {
- Vector x = httpc.wget(new URL("http://192.168.0.1:80/status.htm"), 5000, "admin", password, null, 0);
+ ArrayList x = httpc.wget(new URL("http://192.168.0.1:80/status.htm"), 5000, "admin", password, null, 0);
x = nxTools.grep(x, 1, "IP Address");
if ((x == null) || (x.size() == 0)) return null;
String line = nxTools.tail1(x);
@@ -72,7 +72,7 @@ public class natLib {
private static String getWhatIsMyIP() {
try {
- Vector x = httpc.wget(new URL("http://www.whatismyip.com/"), 5000, null, null, null, 0);
+ ArrayList x = httpc.wget(new URL("http://www.whatismyip.com/"), 5000, null, null, null, 0);
x = nxTools.grep(x, 0, "Your IP is");
String line = nxTools.tail1(x);
return nxTools.awk(line, " ", 4);
@@ -83,7 +83,7 @@ public class natLib {
private static String getStanford() {
try {
- Vector x = httpc.wget(new URL("http://www.slac.stanford.edu/cgi-bin/nph-traceroute.pl"), 5000, null, null, null, 0);
+ ArrayList x = httpc.wget(new URL("http://www.slac.stanford.edu/cgi-bin/nph-traceroute.pl"), 5000, null, null, null, 0);
x = nxTools.grep(x, 0, "firewall protecting your browser");
String line = nxTools.tail1(x);
return nxTools.awk(line, " ", 7);
@@ -94,7 +94,7 @@ public class natLib {
private static String getIPID() {
try {
- Vector x = httpc.wget(new URL("http://ipid.shat.net/"), 5000, null, null, null, 0);
+ ArrayList x = httpc.wget(new URL("http://ipid.shat.net/"), 5000, null, null, null, 0);
x = nxTools.grep(x, 2, "Your IP address");
String line = nxTools.tail1(x);
return nxTools.awk(nxTools.awk(nxTools.awk(line, " ", 5), ">", 2), "<", 1);
diff --git a/source/de/anomic/plasma/plasmaCrawlLURL.java b/source/de/anomic/plasma/plasmaCrawlLURL.java
index 41158d7d7..0d195dd63 100644
--- a/source/de/anomic/plasma/plasmaCrawlLURL.java
+++ b/source/de/anomic/plasma/plasmaCrawlLURL.java
@@ -69,17 +69,17 @@ import de.anomic.tools.crypt;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacySeed;
-public class plasmaCrawlLURL extends plasmaURL {
+public final class plasmaCrawlLURL extends plasmaURL {
// result stacks;
// these have all entries of form
// strings: urlHash + initiatorHash + ExecutorHash
- private LinkedList externResultStack; // 1 - remote index: retrieved by other peer
- private LinkedList searchResultStack; // 2 - partly remote/local index: result of search queries
- private LinkedList transfResultStack; // 3 - partly remote/local index: result of index transfer
- private LinkedList proxyResultStack; // 4 - local index: result of proxy fetch/prefetch
- private LinkedList lcrawlResultStack; // 5 - local index: result of local crawling
- private LinkedList gcrawlResultStack; // 6 - local index: triggered external
+ private final LinkedList externResultStack; // 1 - remote index: retrieved by other peer
+ private final LinkedList searchResultStack; // 2 - partly remote/local index: result of search queries
+ private final LinkedList transfResultStack; // 3 - partly remote/local index: result of index transfer
+ private final LinkedList proxyResultStack; // 4 - local index: result of proxy fetch/prefetch
+ private final LinkedList lcrawlResultStack; // 5 - local index: result of local crawling
+ private final LinkedList gcrawlResultStack; // 6 - local index: triggered external
public plasmaCrawlLURL(File cachePath, int bufferkb) throws IOException {
super();
@@ -170,6 +170,35 @@ public class plasmaCrawlLURL extends plasmaURL {
return new Entry(hash);
}
+ public synchronized Entry newEntry(Entry oldEntry) {
+ if (oldEntry == null) return null;
+ /*
+ * de.anomic.plasma.plasmaCrawlLURL.Entry.Entry(URL url, String descr,
+ * Date moddate, Date loaddate,
+ * String referrerHash,
+ * int copyCount,
+ * boolean localNeed,
+ * int quality,
+ * String language,
+ * char doctype,
+ * long size,
+ * int wordCount)
+ */
+ return new Entry(
+ oldEntry.url(),
+ oldEntry.descr(),
+ oldEntry.moddate(),
+ oldEntry.loaddate(),
+ oldEntry.referrerHash(),
+ oldEntry.copyCount(),
+ oldEntry.local(),
+ oldEntry.quality(),
+ oldEntry.language(),
+ oldEntry.doctype(),
+ oldEntry.size(),
+ oldEntry.wordCount());
+ }
+
public synchronized Entry newEntry(String propStr, boolean setGlobal) {
if ((propStr.startsWith("{")) && (propStr.endsWith("}"))) {
return new Entry(serverCodings.s2p(propStr.substring(1, propStr.length() - 1)), setGlobal);
@@ -516,56 +545,98 @@ public class plasmaCrawlLURL extends plasmaURL {
return snippet;
}
- private String corePropList() {
+ private StringBuffer corePropList() {
// generate a parseable string; this is a simple property-list
+ StringBuffer corePropStr = new StringBuffer(300);
try {
- return
- "hash=" + urlHash +
- ",referrer=" + referrerHash +
- ",mod=" + shortDayFormatter.format(moddate) +
- ",load=" + shortDayFormatter.format(loaddate) +
- ",size=" + size +
- ",wc=" + wordCount +
- ",cc=" + copyCount +
- ",local=" + ((local()) ? "true" : "false") +
- ",q=" + serverCodings.enhancedCoder.encodeBase64Long(quality, urlQualityLength) +
- ",dt=" + doctype +
- ",lang=" + language +
- ",url=" + crypt.simpleEncode(url.toString()) +
- ",descr=" + crypt.simpleEncode(descr);
- } catch (Exception e) {
- //serverLog.logFailure("plasmaLURL.corePropList", e.getMessage());
+ corePropStr
+ .append("hash=") .append(urlHash)
+ .append(",referrer=").append(referrerHash)
+ .append(",mod=") .append(shortDayFormatter.format(moddate))
+ .append(",load=") .append(shortDayFormatter.format(loaddate))
+ .append(",size=") .append(size)
+ .append(",wc=") .append(wordCount)
+ .append(",cc=") .append(copyCount)
+ .append(",local=") .append(((local()) ? "true" : "false"))
+ .append(",q=") .append(serverCodings.enhancedCoder.encodeBase64Long(quality, urlQualityLength))
+ .append(",dt=") .append(doctype)
+ .append(",lang=") .append(language)
+ .append(",url=") .append(crypt.simpleEncode(url.toString()))
+ .append(",descr=") .append(crypt.simpleEncode(descr));
+ return corePropStr;
+
+// return
+// "hash=" + urlHash +
+// ",referrer=" + referrerHash +
+// ",mod=" + shortDayFormatter.format(moddate) +
+// ",load=" + shortDayFormatter.format(loaddate) +
+// ",size=" + size +
+// ",wc=" + wordCount +
+// ",cc=" + copyCount +
+// ",local=" + ((local()) ? "true" : "false") +
+// ",q=" + serverCodings.enhancedCoder.encodeBase64Long(quality, urlQualityLength) +
+// ",dt=" + doctype +
+// ",lang=" + language +
+// ",url=" + crypt.simpleEncode(url.toString()) +
+// ",descr=" + crypt.simpleEncode(descr);
+ } catch (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;
- }
+ return null;
+ }
}
- public String toString(int posintext, int posinphrase, int posofphrase) {
+ public String toString(int posintext, int posinphrase, int posofphrase) {
// add information needed for remote transport
- String core = corePropList();
+ StringBuffer core = corePropList();
if (core == null) return null;
- return
- "{" + core +
- ",posintext=" + posintext +
- ",posinphrase=" + posinphrase +
- ",posofphraseint=" + posofphrase +
- "}";
- }
+
+ core.ensureCapacity(core.length() + 200);
+ core.insert(0,"{")
+ .append(",posintext=").append(posintext)
+ .append(",posinphrase=").append(posinphrase)
+ .append(",posofphraseint=").append(posofphrase)
+ .append("}");
+ return core.toString();
+
+// return
+// "{" + core +
+// ",posintext=" + posintext +
+// ",posinphrase=" + posinphrase +
+// ",posofphraseint=" + posofphrase +
+// "}";
+ }
- public String toString(String snippet) {
- // add information needed for remote transport
- String core = corePropList();
- if (core == null) return null;
- return "{" + core + ",snippet=" + crypt.simpleEncode(snippet) + "}";
- }
+ public String toString(String snippet) {
+ // add information needed for remote transport
+ StringBuffer core = corePropList();
+ if (core == null) return null;
- public String toString() {
- String core = corePropList();
- if (core == null) return null;
- return "{" + core + "}";
- }
+ core.ensureCapacity(core.length() + snippet.length()*2);
+ core.insert(0,"{");
+ core.append(",snippet=").append(crypt.simpleEncode(snippet)).append("}");
+
+ return core.toString();
+ //return "{" + core + ",snippet=" + crypt.simpleEncode(snippet) + "}";
+ }
+
+ /**
+ * Returns this 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() {
+ StringBuffer core = corePropList();
+ if (core == null) return null;
+
+ core.insert(0,"{");
+ core.append("}");
+
+ return core.toString();
+ //return "{" + core + "}";
+ }
public void print() {
System.out.println("URL : " + url);
diff --git a/source/de/anomic/plasma/plasmaCrawlNURL.java b/source/de/anomic/plasma/plasmaCrawlNURL.java
index 4c98aa24c..12461e415 100644
--- a/source/de/anomic/plasma/plasmaCrawlNURL.java
+++ b/source/de/anomic/plasma/plasmaCrawlNURL.java
@@ -69,19 +69,10 @@ public class plasmaCrawlNURL extends plasmaURL {
public static final int STACK_TYPE_MOVIE = 12; // put on movie stack
public static final int STACK_TYPE_MUSIC = 13; // put on music stack
- private plasmaCrawlBalancer coreStack; // links found by crawling to depth-1
- private plasmaCrawlBalancer limitStack; // links found by crawling at target depth
- private plasmaCrawlBalancer overhangStack; // links found by crawling at depth+1
- private plasmaCrawlBalancer remoteStack; // links from remote crawl orders
- private kelondroStack imageStack; // links pointing to image resources
- private kelondroStack movieStack; // links pointing to movie resources
- private kelondroStack musicStack; // links pointing to music resources
-
- private HashSet stackIndex; // to find out if a specific link is already on any stack
-
- public plasmaCrawlNURL(File cacheStacksPath, int bufferkb) throws IOException {
- super();
- int[] ce = {
+ /**
+ * column length definition for the {@link plasmaURL#urlHashCache} DB
+ */
+ public static final int[] ce = {
urlHashLength, // the url hash
urlHashLength, // initiator
urlStringLength, // the url as string
@@ -94,7 +85,21 @@ public class plasmaCrawlNURL extends plasmaURL {
urlForkFactorLength, // sum of anchors of all ancestors
urlFlagLength, // extra space
urlHandleLength // extra handle
- };
+ };
+
+ private final plasmaCrawlBalancer coreStack; // links found by crawling to depth-1
+ private final plasmaCrawlBalancer limitStack; // links found by crawling at target depth
+ private final plasmaCrawlBalancer overhangStack; // links found by crawling at depth+1
+ private final plasmaCrawlBalancer remoteStack; // links from remote crawl orders
+ private kelondroStack imageStack; // links pointing to image resources
+ private kelondroStack movieStack; // links pointing to movie resources
+ private kelondroStack musicStack; // links pointing to music resources
+
+ private final HashSet stackIndex; // to find out if a specific link is already on any stack
+
+ public plasmaCrawlNURL(File cacheStacksPath, int bufferkb) throws IOException {
+ super();
+
// create a stack for newly entered entries
if (!(cacheStacksPath.exists())) cacheStacksPath.mkdir(); // make the path
diff --git a/source/de/anomic/plasma/plasmaCrawlRobotsTxt.java b/source/de/anomic/plasma/plasmaCrawlRobotsTxt.java
index 292e29cf3..8dc17894d 100644
--- a/source/de/anomic/plasma/plasmaCrawlRobotsTxt.java
+++ b/source/de/anomic/plasma/plasmaCrawlRobotsTxt.java
@@ -130,8 +130,8 @@ public class plasmaCrawlRobotsTxt {
}
}
- public Entry addEntry(String hostName, ArrayList disallowPathList, Date loadedDate) {
- Entry entry = new Entry(hostName,disallowPathList,loadedDate);
+ public Entry addEntry(String hostName, ArrayList disallowPathList, Date loadedDate, Date modDate, String eTag) {
+ Entry entry = new Entry(hostName,disallowPathList,loadedDate,modDate,eTag);
addEntry(entry);
return entry;
}
@@ -149,6 +149,8 @@ public class plasmaCrawlRobotsTxt {
public class Entry {
public static final String DISALLOW_PATH_LIST = "disallow";
public static final String LOADED_DATE = "date";
+ public static final String MOD_DATE = "modDate";
+ public static final String ETAG = "etag";
// this is a simple record structure that hold all properties of a single crawl start
private Map mem;
@@ -173,7 +175,12 @@ public class plasmaCrawlRobotsTxt {
}
}
- public Entry(String hostName, ArrayList disallowPathList, Date loadedDate) {
+ public Entry(
+ String hostName,
+ ArrayList disallowPathList,
+ Date loadedDate,
+ Date modDate,
+ String eTag) {
if ((hostName == null) || (hostName.length() == 0)) throw new IllegalArgumentException();
this.hostName = hostName.trim().toLowerCase();
@@ -181,6 +188,8 @@ public class plasmaCrawlRobotsTxt {
this.mem = new HashMap();
if (loadedDate != null) this.mem.put(LOADED_DATE,Long.toString(loadedDate.getTime()));
+ if (modDate != null) this.mem.put(MOD_DATE,Long.toString(modDate.getTime()));
+ if (eTag != null) this.mem.put(ETAG,eTag);
if ((disallowPathList != null)&&(disallowPathList.size()>0)) {
this.disallowPathList.addAll(disallowPathList);
@@ -213,6 +222,20 @@ public class plasmaCrawlRobotsTxt {
return null;
}
+ public Date getModDate() {
+ if (this.mem.containsKey(MOD_DATE)) {
+ return new Date(Long.valueOf((String) this.mem.get(MOD_DATE)).longValue());
+ }
+ return null;
+ }
+
+ public String getETag() {
+ if (this.mem.containsKey(ETAG)) {
+ return (String) this.mem.get(ETAG);
+ }
+ return null;
+ }
+
public boolean isDisallowed(String path) {
if ((this.mem == null) || (this.disallowPathList.size() == 0)) return false;
if ((path == null) || (path.length() == 0)) path = "/";
diff --git a/source/de/anomic/plasma/plasmaCrawlWorker.java b/source/de/anomic/plasma/plasmaCrawlWorker.java
index 62b211665..a8572cf00 100644
--- a/source/de/anomic/plasma/plasmaCrawlWorker.java
+++ b/source/de/anomic/plasma/plasmaCrawlWorker.java
@@ -355,10 +355,7 @@ public final class plasmaCrawlWorker extends Thread {
File cacheFile = cacheManager.getCachePath(url);
try {
String error = null;
- if (
- (plasmaParser.supportedMimeTypesContains(res.responseHeader.mime())) &&
- (plasmaParser.supportedFileExt(url))
- ) {
+ if (plasmaParser.supportedContent(url,res.responseHeader.mime())) {
if (cacheFile.isFile()) {
cacheManager.deleteFile(url);
}
diff --git a/source/de/anomic/plasma/plasmaHTCache.java b/source/de/anomic/plasma/plasmaHTCache.java
index 1ca9d3073..2b8bc4d5d 100644
--- a/source/de/anomic/plasma/plasmaHTCache.java
+++ b/source/de/anomic/plasma/plasmaHTCache.java
@@ -331,7 +331,7 @@ public final class plasmaHTCache {
while ((doms.size() > 0) && (c < 50) && ((System.currentTimeMillis() - start) < 60000)) {
dom = (String) doms.getMaxObject();
ip = httpc.dnsResolve(dom);
- if (ip == null) break;
+ if (ip == null) continue;
result += ", " + dom + "=" + ip;
log.logConfig("PRE-FILLED " + dom + "=" + ip);
c++;
diff --git a/source/de/anomic/plasma/plasmaParser.java b/source/de/anomic/plasma/plasmaParser.java
index f5178d89e..dca38557d 100644
--- a/source/de/anomic/plasma/plasmaParser.java
+++ b/source/de/anomic/plasma/plasmaParser.java
@@ -498,7 +498,7 @@ public final class plasmaParser {
String mimeType = (String) mimeTypeIterator.next();
availableParserList.put(mimeType,fullClassName);
serverLog.logInfo("PARSER", "Found functional parser for mimeType '" + mimeType + "'." +
- ((neededLibxBuf.length()>0)?" Dependencies: " + neededLibxBuf.toString():""));
+ ((neededLibxBuf.length()>0)?"\nDependencies: " + neededLibxBuf.toString():""));
}
} catch (Exception e) { /* we can ignore this for the moment */
diff --git a/source/de/anomic/plasma/plasmaStackCrawlThread.java b/source/de/anomic/plasma/plasmaStackCrawlThread.java
new file mode 100644
index 000000000..953b4cde5
--- /dev/null
+++ b/source/de/anomic/plasma/plasmaStackCrawlThread.java
@@ -0,0 +1,521 @@
+package de.anomic.plasma;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.LinkedList;
+
+import de.anomic.data.robotsParser;
+import de.anomic.kelondro.kelondroTree;
+import de.anomic.kelondro.kelondroRecords.Node;
+import de.anomic.server.serverCodings;
+import de.anomic.server.serverSemaphore;
+import de.anomic.server.logging.serverLog;
+import de.anomic.tools.bitfield;
+import de.anomic.yacy.yacyCore;
+
+public final class plasmaStackCrawlThread extends Thread {
+
+ private final serverLog log = new serverLog("STACKCRAWL");
+ private final plasmaSwitchboard sb;
+ private boolean stopped = false;
+ private stackCrawlQueue queue;
+
+ public plasmaStackCrawlThread(plasmaSwitchboard sb, File dbPath, int dbCacheSize) throws IOException {
+ this.sb = sb;
+ this.setName(this.getClass().getName());
+
+ this.queue = new stackCrawlQueue(dbPath,dbCacheSize);
+ this.log.logInfo(this.queue.size() + " entries in the stackCrawl queue.");
+ this.log.logInfo("STACKCRAWL thread initialized.");
+ }
+
+ public void stopIt() {
+ this.stopped = true;
+ this.interrupt();
+ try {
+ this.join();
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ public int getQueueSize() {
+ return this.queue.size();
+ }
+
+ public void run() {
+ while ((!this.stopped) && (!Thread.currentThread().isInterrupted())) {
+
+ try {
+ // getting a new message from the crawler queue
+ stackCrawlMessage theMsg = this.queue.waitForMessage();
+
+ // process message
+ String rejectReason = stackCrawlDequeue(theMsg);
+
+ if (rejectReason != null) {
+ this.sb.urlPool.errorURL.newEntry(
+ new URL(theMsg.url()),
+ theMsg.referrerHash(),
+ theMsg.initiatorHash(),
+ yacyCore.seedDB.mySeed.hash,
+ theMsg.name,
+ rejectReason,
+ new bitfield(plasmaURL.urlFlagLength),
+ false
+ );
+ }
+
+ } catch (InterruptedException e) {
+ Thread.interrupted();
+ this.stopped = true;
+ }
+ catch (Exception e) {
+ this.log.logSevere("plasmaStackCrawlThread.run/loop", e);
+ }
+ }
+
+ try {
+ this.log.logFine("Shutdown. Closing stackCrawl queue.");
+ this.queue.close();
+ } catch (IOException e) {
+ this.log.logSevere("DB could not be closed properly.", e);
+ }
+ this.log.logInfo("Shutdown finished.");
+ }
+
+
+ public void stackCrawlEnqueue(
+ String nexturlString,
+ String referrerString,
+ String initiatorHash,
+ String name,
+ Date loadDate,
+ int currentdepth,
+ plasmaCrawlProfile.entry profile) throws MalformedURLException {
+ try {
+ this.queue.addMessage(new stackCrawlMessage(
+ initiatorHash,
+ nexturlString,
+ referrerString,
+ name,
+ loadDate,
+ profile.handle(),
+ currentdepth,
+ 0,
+ 0
+ ));
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ public String stackCrawlDequeue(stackCrawlMessage theMsg) throws InterruptedException {
+
+ plasmaCrawlProfile.entry profile = this.sb.profiles.getEntry(theMsg.profileHandle());
+ if (profile == null) {
+ String errorMsg = "LOST PROFILE HANDLE '" + theMsg.profileHandle() + "' (must be internal error) for URL " + theMsg.url();
+ this.log.logSevere(errorMsg);
+ throw new IllegalStateException(errorMsg);
+ }
+
+ return stackCrawl(
+ theMsg.url().toString(),
+ theMsg.referrerHash(),
+ theMsg.initiatorHash(),
+ theMsg.name(),
+ theMsg.loaddate(),
+ theMsg.depth(),
+ profile);
+ }
+
+ public String stackCrawl(String nexturlString, String referrerString, String initiatorHash, String name, Date loadDate, int currentdepth, plasmaCrawlProfile.entry profile) {
+ // stacks a crawl item. The position can also be remote
+ // returns null if successful, a reason string if not successful
+
+ String reason = null; // failure reason
+
+ // strange errors
+ if (nexturlString == null) {
+ reason = "denied_(url_null)";
+ this.log.logSevere("Wrong URL in stackCrawl: url=null");
+ return reason;
+ }
+ /*
+ if (profile == null) {
+ reason = "denied_(profile_null)";
+ log.logError("Wrong Profile for stackCrawl: profile=null");
+ return reason;
+ }
+ */
+ URL nexturl = null;
+ if ((initiatorHash == null) || (initiatorHash.length() == 0)) initiatorHash = plasmaURL.dummyHash;
+ String referrerHash = plasmaURL.urlHash(referrerString);
+ try {
+ nexturl = new URL(nexturlString);
+ } catch (MalformedURLException e) {
+ reason = "denied_(url_'" + nexturlString + "'_wrong)";
+ this.log.logSevere("Wrong URL in stackCrawl: " + nexturlString);
+ return reason;
+ }
+
+ // check if ip is local ip address
+ try {
+ InetAddress hostAddress = InetAddress.getByName(nexturl.getHost());
+ if (hostAddress.isSiteLocalAddress()) {
+ reason = "denied_(private_ip_address)";
+ this.log.logFine("Host in URL '" + nexturlString + "' has private ip address.");
+ return reason;
+ } else if (hostAddress.isLoopbackAddress()) {
+ reason = "denied_(loopback_ip_address)";
+ this.log.logFine("Host in URL '" + nexturlString + "' has loopback ip address.");
+ return reason;
+ }
+ } catch (UnknownHostException e) {
+ reason = "denied_(unknown_host)";
+ this.log.logFine("Unknown host in URL '" + nexturlString + "'.");
+ return reason;
+ }
+
+ // check blacklist
+ String hostlow = nexturl.getHost().toLowerCase();
+ if (plasmaSwitchboard.urlBlacklist.isListed(hostlow, nexturl.getPath())) {
+ reason = "denied_(url_in_blacklist)";
+ this.log.logFine("URL '" + nexturlString + "' is in blacklist.");
+ return reason;
+ }
+
+ // filter deny
+ if ((currentdepth > 0) && (profile != null) && (!(nexturlString.matches(profile.generalFilter())))) {
+ reason = "denied_(does_not_match_filter)";
+ /*
+ urlPool.errorURL.newEntry(nexturl, referrerHash, initiatorHash, yacyCore.seedDB.mySeed.hash,
+ name, reason, new bitfield(plasmaURL.urlFlagLength), false);*/
+ this.log.logFine("URL '" + nexturlString + "' does not match crawling filter '" + profile.generalFilter() + "'.");
+ return reason;
+ }
+
+ // deny cgi
+ if (plasmaHTCache.isCGI(nexturlString)) {
+ reason = "denied_(cgi_url)";
+ /*
+ urlPool.errorURL.newEntry(nexturl, referrerHash, initiatorHash, yacyCore.seedDB.mySeed.hash,
+ name, reason, new bitfield(plasmaURL.urlFlagLength), false);*/
+ this.log.logFine("URL '" + nexturlString + "' is cgi URL.");
+ return reason;
+ }
+
+ // deny post properties
+ if ((plasmaHTCache.isPOST(nexturlString)) && (profile != null) && (!(profile.crawlingQ()))) {
+ reason = "denied_(post_url)";
+ /*
+ urlPool.errorURL.newEntry(nexturl, referrerHash, initiatorHash, yacyCore.seedDB.mySeed.hash,
+ name, reason, new bitfield(plasmaURL.urlFlagLength), false);*/
+ this.log.logFine("URL '" + nexturlString + "' is post URL.");
+ return reason;
+ }
+
+ String nexturlhash = plasmaURL.urlHash(nexturl);
+ String dbocc = "";
+ if ((dbocc = this.sb.urlPool.exists(nexturlhash)) != null) {
+ // DISTIGUISH OLD/RE-SEARCH CASES HERE!
+ reason = "double_(registered_in_" + dbocc + ")";
+ /*
+ urlPool.errorURL.newEntry(nexturl, referrerHash, initiatorHash, yacyCore.seedDB.mySeed.hash,
+ name, reason, new bitfield(plasmaURL.urlFlagLength), false);*/
+ this.log.logFine("URL '" + nexturlString + "' is double registered in '" + dbocc + "'.");
+ return reason;
+ }
+
+ // checking robots.txt
+ if (robotsParser.isDisallowed(nexturl)) {
+ reason = "denied_(robots.txt)";
+ /*
+ urlPool.errorURL.newEntry(nexturl, referrerHash, initiatorHash, yacyCore.seedDB.mySeed.hash,
+ name, reason, new bitfield(plasmaURL.urlFlagLength), false);*/
+ this.log.logFine("Crawling of URL '" + nexturlString + "' disallowed by robots.txt.");
+ return reason;
+ }
+
+ // store information
+ boolean local = ((initiatorHash.equals(plasmaURL.dummyHash)) || (initiatorHash.equals(yacyCore.seedDB.mySeed.hash)));
+ boolean global =
+ (profile != null) &&
+ (profile.remoteIndexing()) /* granted */ &&
+ (currentdepth == profile.generalDepth()) /* leaf node */ &&
+ (initiatorHash.equals(yacyCore.seedDB.mySeed.hash)) /* not proxy */ &&
+ ((yacyCore.seedDB.mySeed.isSenior()) ||
+ (yacyCore.seedDB.mySeed.isPrincipal())) /* qualified */;
+
+ if ((!local)&&(!global)) {
+ this.log.logFine("URL '" + nexturlString + "' can neither be crawled local nor global.");
+ }
+
+ this.sb.urlPool.noticeURL.newEntry(initiatorHash, /* initiator, needed for p2p-feedback */
+ nexturl, /* url clear text string */
+ loadDate, /* load date */
+ referrerHash, /* last url in crawling queue */
+ name, /* the anchor name */
+ (profile == null) ? null : profile.handle(), // profile must not be null!
+ currentdepth, /*depth so far*/
+ 0, /*anchors, default value */
+ 0, /*forkfactor, default value */
+ ((global) ? plasmaCrawlNURL.STACK_TYPE_LIMIT :
+ ((local) ? plasmaCrawlNURL.STACK_TYPE_CORE : plasmaCrawlNURL.STACK_TYPE_REMOTE)) /*local/remote stack*/
+ );
+
+ return null;
+ }
+
+ public final class stackCrawlMessage {
+ private String initiator; // the initiator hash, is NULL or "" if it is the own proxy;
+ String urlHash; // the url's hash
+ private String referrerHash; // the url's referrer hash
+ private String url; // the url as string
+ String name; // the name of the url, from anchor tag <a>name</a>
+ private Date loaddate; // the time when the url was first time appeared
+ private String profileHandle; // the name of the prefetch profile
+ private int depth; // the prefetch depth so far, starts at 0
+ private int anchors; // number of anchors of the parent
+ private int forkfactor; // sum of anchors of all ancestors
+ private bitfield flags;
+ private int handle;
+
+ // loadParallel(URL url, String referer, String initiator, int depth, plasmaCrawlProfile.entry profile) {
+ public stackCrawlMessage(
+ String initiator,
+ String urlString,
+ String referrerUrlString,
+ String name,
+ Date loaddate,
+ String profileHandle,
+ int depth,
+ int anchors,
+ int forkfactor) {
+ try {
+ // create new entry and store it into database
+ this.urlHash = plasmaURL.urlHash(urlString);
+ this.initiator = initiator;
+ this.url = urlString;
+ this.referrerHash = (referrerUrlString == null) ? plasmaURL.dummyHash : plasmaURL.urlHash(referrerUrlString);
+ this.name = (name == null) ? "" : name;
+ this.loaddate = (loaddate == null) ? new Date() : loaddate;
+ this.profileHandle = profileHandle; // must not be null
+ this.depth = depth;
+ this.anchors = anchors;
+ this.forkfactor = forkfactor;
+ this.flags = new bitfield(plasmaURL.urlFlagLength);
+ this.handle = 0;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ public stackCrawlMessage(String urlHash, byte[][] entryBytes) {
+ if (urlHash == null) throw new NullPointerException();
+ if (entryBytes == null) throw new NullPointerException();
+
+ try {
+ this.urlHash = urlHash;
+ this.initiator = new String(entryBytes[1]);
+ this.url = new String(entryBytes[2]).trim();
+ this.referrerHash = (entryBytes[3]==null) ? plasmaURL.dummyHash : new String(entryBytes[3]);
+ this.name = (entryBytes[4] == null) ? "" : new String(entryBytes[4]).trim();
+ this.loaddate = new Date(86400000 * serverCodings.enhancedCoder.decodeBase64Long(new String(entryBytes[5])));
+ this.profileHandle = (entryBytes[6] == null) ? null : new String(entryBytes[6]).trim();
+ this.depth = (int) serverCodings.enhancedCoder.decodeBase64Long(new String(entryBytes[7]));
+ this.anchors = (int) serverCodings.enhancedCoder.decodeBase64Long(new String(entryBytes[8]));
+ this.forkfactor = (int) serverCodings.enhancedCoder.decodeBase64Long(new String(entryBytes[9]));
+ this.flags = new bitfield(entryBytes[10]);
+ this.handle = Integer.parseInt(new String(entryBytes[11]));
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new IllegalStateException();
+ }
+ }
+
+ public String url() {
+ return this.url;
+ }
+
+ public String referrerHash() {
+ return this.referrerHash;
+ }
+
+ public String initiatorHash() {
+ if (this.initiator == null) return null;
+ if (this.initiator.length() == 0) return null;
+ return this.initiator;
+ }
+
+ public Date loaddate() {
+ return this.loaddate;
+ }
+
+ public String name() {
+ return this.name;
+ }
+
+ public int depth() {
+ return this.depth;
+ }
+
+ public String profileHandle() {
+ return this.profileHandle;
+ }
+
+ public String toString() {
+ StringBuffer str = new StringBuffer();
+ str.append("urlHash: ").append(urlHash==null ? "null" : urlHash).append(" | ")
+ .append("initiator: ").append(initiator==null?"null":initiator).append(" | ")
+ .append("url: ").append(url==null?"null":url).append(" | ")
+ .append("referrer: ").append((referrerHash == null) ? plasmaURL.dummyHash : referrerHash).append(" | ")
+ .append("name: ").append((name == null) ? "null" : name).append(" | ")
+ .append("loaddate: ").append((loaddate == null) ? new Date() : loaddate).append(" | ")
+ .append("profile: ").append(profileHandle==null?"null":profileHandle).append(" | ")
+ .append("depth: ").append(Integer.toString(depth)).append(" | ")
+ .append("forkfactor: ").append(Integer.toString(forkfactor)).append(" | ")
+ .append("flags: ").append((flags==null) ? "null" : flags.toString());
+ return str.toString();
+ }
+
+ public byte[][] getBytes() {
+ // stores the values from the object variables into the database
+ String loaddatestr = serverCodings.enhancedCoder.encodeBase64Long(loaddate.getTime() / 86400000, plasmaURL.urlDateLength);
+ // store the hash in the hash cache
+
+ // even if the entry exists, we simply overwrite it
+ byte[][] entry = new byte[][] {
+ this.urlHash.getBytes(),
+ (this.initiator == null) ? "".getBytes() : this.initiator.getBytes(),
+ this.url.getBytes(),
+ this.referrerHash.getBytes(),
+ this.name.getBytes(),
+ loaddatestr.getBytes(),
+ (this.profileHandle == null) ? null : this.profileHandle.getBytes(),
+ serverCodings.enhancedCoder.encodeBase64Long(this.depth, plasmaURL.urlCrawlDepthLength).getBytes(),
+ serverCodings.enhancedCoder.encodeBase64Long(this.anchors, plasmaURL.urlParentBranchesLength).getBytes(),
+ serverCodings.enhancedCoder.encodeBase64Long(this.forkfactor, plasmaURL.urlForkFactorLength).getBytes(),
+ this.flags.getBytes(),
+ normalizeHandle(this.handle).getBytes()
+ };
+ return entry;
+ }
+
+ private String normalizeHandle(int h) {
+ String d = Integer.toHexString(h);
+ while (d.length() < plasmaURL.urlHandleLength) d = "0" + d;
+ return d;
+ }
+ }
+
+ final class stackCrawlQueue {
+
+ private final serverSemaphore readSync;
+ private final serverSemaphore writeSync;
+ private final LinkedList urlEntryHashCache;
+ private final kelondroTree urlEntryCache;
+
+ public stackCrawlQueue(File cacheStacksPath, int bufferkb) throws IOException {
+ // init the read semaphore
+ this.readSync = new serverSemaphore (0);
+
+ // init the write semaphore
+ this.writeSync = new serverSemaphore (1);
+
+ // init the message list
+ this.urlEntryHashCache = new LinkedList();
+
+ // create a stack for newly entered entries
+ if (!(cacheStacksPath.exists())) cacheStacksPath.mkdir(); // make the path
+
+ File cacheFile = new File(cacheStacksPath, "urlPreNotice.db");
+ if (cacheFile.exists()) {
+ // open existing cache
+ this.urlEntryCache = new kelondroTree(cacheFile, bufferkb * 0x400);
+
+ // loop through the list and fill the messageList with url hashs
+ Iterator iter = this.urlEntryCache.nodeIterator(true,false);
+ Node n;
+ while (iter.hasNext()) {
+ n = (Node) iter.next();
+ if (n == null) {
+ System.out.println("ERROR! null element found");
+ continue;
+ }
+ String urlHash = new String(n.getKey());
+ this.urlEntryHashCache.add(urlHash);
+ this.readSync.V();
+ }
+ } else {
+ // create new cache
+ cacheFile.getParentFile().mkdirs();
+ this.urlEntryCache = new kelondroTree(cacheFile, bufferkb * 0x400, plasmaCrawlNURL.ce);
+ }
+ }
+
+ public void close() throws IOException {
+ // closing the db
+ this.urlEntryCache.close();
+
+ // clearing the hash list
+ this.urlEntryHashCache.clear();
+ }
+
+ public void addMessage(stackCrawlMessage newMessage)
+ throws InterruptedException, IOException {
+ if (newMessage == null) throw new NullPointerException();
+
+ this.writeSync.P();
+ try {
+
+ boolean insertionDoneSuccessfully = false;
+ synchronized(this.urlEntryHashCache) {
+ byte[][] oldValue = this.urlEntryCache.put(newMessage.getBytes());
+ if (oldValue == null) {
+ insertionDoneSuccessfully = this.urlEntryHashCache.add(newMessage.urlHash);
+ }
+ }
+
+ if (insertionDoneSuccessfully) {
+ this.readSync.V();
+ }
+ } finally {
+ this.writeSync.V();
+ }
+ }
+
+ public int size() {
+ synchronized(this.urlEntryHashCache) {
+ return this.urlEntryHashCache.size();
+ }
+ }
+
+ public stackCrawlMessage waitForMessage() throws InterruptedException, IOException {
+ this.readSync.P();
+ this.writeSync.P();
+
+ String urlHash = null;
+ byte[][] entryBytes = null;
+ stackCrawlMessage newMessage = null;
+ synchronized(this.urlEntryHashCache) {
+ urlHash = (String) this.urlEntryHashCache.remove();
+ entryBytes = this.urlEntryCache.remove(urlHash.getBytes());
+ }
+
+ this.writeSync.V();
+
+ newMessage = new stackCrawlMessage(urlHash,entryBytes);
+ return newMessage;
+ }
+ }
+
+}
diff --git a/source/de/anomic/plasma/plasmaSwitchboard.java b/source/de/anomic/plasma/plasmaSwitchboard.java
index 5ef4ca990..5ad85ead6 100644
--- a/source/de/anomic/plasma/plasmaSwitchboard.java
+++ b/source/de/anomic/plasma/plasmaSwitchboard.java
@@ -106,10 +106,7 @@ package de.anomic.plasma;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
-import java.net.InetAddress;
-import java.net.MalformedURLException;
import java.net.URL;
-import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@@ -122,7 +119,6 @@ import java.util.TreeSet;
import java.util.logging.Level;
import de.anomic.data.messageBoard;
-import de.anomic.data.robotsParser;
import de.anomic.data.wikiBoard;
import de.anomic.data.userDB;
import de.anomic.htmlFilter.htmlFilterContentScraper;
@@ -152,6 +148,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
// load slots
public static int crawlSlots = 10;
public static int indexingSlots = 100;
+ public static int stackCrawlSlots = 10000;
// couloured list management
public static TreeSet blueList = null;
@@ -169,6 +166,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
public plasmaSnippetCache snippetCache;
public plasmaCrawlLoader cacheLoader;
public plasmaSwitchboardQueue sbQueue;
+ public plasmaStackCrawlThread sbStackCrawlThread;
public messageBoard messageDB;
public wikiBoard wikiDB;
public String remoteProxyHost;
@@ -263,6 +261,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
int ramWiki = (int) getConfigLong("ramCacheWiki", 1024) / 1024;
int ramRobots = (int) getConfigLong("ramCacheRobots",1024) / 1024;
int ramProfiles= (int) getConfigLong("ramCacheProfiles",1024) / 1024;
+ int ramPreNURL = (int) getConfigLong("ramCachePreNURL", 1024) / 1024;
this.log.logConfig("LURL Cache memory = " + ppRamString(ramLURL));
this.log.logConfig("NURL Cache memory = " + ppRamString(ramNURL));
this.log.logConfig("EURL Cache memory = " + ppRamString(ramEURL));
@@ -272,19 +271,24 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
this.log.logConfig("Wiki Cache memory = " + ppRamString(ramWiki));
this.log.logConfig("Robots Cache memory = " + ppRamString(ramRobots));
this.log.logConfig("Profiles Cache memory = " + ppRamString(ramProfiles));
+ this.log.logConfig("PreNURL Cache memory = " + ppRamString(ramPreNURL));
// make crawl profiles database and default profiles
this.log.logConfig("Initializing Crawl Profiles");
File profilesFile = new File(this.plasmaPath, "crawlProfiles0.db");
this.profiles = new plasmaCrawlProfile(profilesFile, ramProfiles);
initProfiles();
- log.logConfig("Loaded profiles from file " + profilesFile + ", " + this.profiles.size() + " entries");
+ log.logConfig("Loaded profiles from file " + profilesFile +
+ ", " + this.profiles.size() + " entries" +
+ ", " + ppRamString(profilesFile.length()/1024));
// loading the robots.txt db
this.log.logConfig("Initializing robots.txt DB");
File robotsDBFile = new File(this.plasmaPath, "crawlRobotsTxt.db");
this.robots = new plasmaCrawlRobotsTxt(robotsDBFile, ramRobots);
- this.log.logConfig("Loaded robots.txt DB from file " + robotsDBFile + ", " + this.robots.size() + " entries");
+ this.log.logConfig("Loaded robots.txt DB from file " + robotsDBFile +
+ ", " + this.robots.size() + " entries" +
+ ", " + ppRamString(robotsDBFile.length()/1024));
// start indexing management
log.logConfig("Starting Indexing Management");
@@ -406,6 +410,10 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
System.gc(); try{Thread.currentThread().sleep(5000);} catch (InterruptedException e) {} // for profiler
serverInstantThread.oneTimeJob(yc, "loadSeeds", yc.log, 3000);
+ // initializing the stackCrawlThread
+ this.sbStackCrawlThread = new plasmaStackCrawlThread(this,this.plasmaPath,ramPreNURL);
+ this.sbStackCrawlThread.start();
+
// deploy threads
log.logConfig("Starting Threads");
// System.gc(); // help for profiler
@@ -442,8 +450,10 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
peerPing.setSyncObject(new Object());
indexDistribution = new plasmaWordIndexDistribution(urlPool, wordIndex, log,
- getConfig("allowDistributeIndex", "false").equals("true"),
- getConfig("allowDistributeIndexWhileCrawling","false").equals("true"));
+ getConfig("allowDistributeIndex", "false").equalsIgnoreCase("true"),
+ getConfig("allowDistributeIndexWhileCrawling","false").equalsIgnoreCase("true"),
+ getConfig("indexDistribution.gzipBody","false").equalsIgnoreCase("true"),
+ (int)getConfigLong("indexDistribution.timeout",60000));
indexDistribution.setCounts(150, 1, 3, 10000);
deployThread("20_dhtdistribution", "DHT Distribution", "selection, transfer and deletion of index entries that are not searched on your peer, but on others", null,
new serverInstantThread(indexDistribution, "job", null), 600000);
@@ -574,8 +584,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
}
}
- if (plasmaParser.supportedMimeTypesContains(entry.responseHeader.mime()) ||
- plasmaParser.supportedFileExt(entry.url)) {
+ if (plasmaParser.supportedContent(entry.url,entry.responseHeader.mime())){
// registering the cachefile as in use
if (entry.cacheFile.exists()) {
@@ -614,6 +623,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
wordIndex.close(waitingBoundSeconds);
log.logConfig("SWITCHBOARD SHUTDOWN STEP 3: sending termination signal to database manager");
try {
+ sbStackCrawlThread.stopIt();
indexDistribution.close();
cacheLoader.close();
wikiDB.close();
@@ -656,6 +666,14 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
log.logFiner("deQueue: online caution, omitting resource stack processing");
return false;
}
+
+ int stackCrawlQueueSize;
+ if ((stackCrawlQueueSize = sbStackCrawlThread.getQueueSize()) >= stackCrawlSlots) {
+ log.logFine("deQueue: too many processes in stack crawl thread queue, dismissed to protect emergency case (" +
+ "stackCrawlQueue=" + stackCrawlQueueSize + ")");
+ return false;
+ }
+
plasmaSwitchboardQueue.Entry nextentry;
synchronized (sbQueue) {
if (sbQueue.size() == 0) {
@@ -995,12 +1013,12 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
// parse content
parsingStartTime = System.currentTimeMillis();
plasmaParserDocument document = null;
- if ((plasmaParser.supportedFileExt(entry.url())) ||
- ((entry.responseHeader() != null) &&
- (plasmaParser.supportedMimeTypesContains(entry.responseHeader().mime())))) {
- if (entry.cacheFile().exists()) {
+ httpHeader entryRespHeader = entry.responseHeader();
+ String mimeType = (entryRespHeader == null)?null:entryRespHeader.mime();
+ if (plasmaParser.supportedContent(entry.url(),mimeType)){
+ if ((entry.cacheFile().exists()) && (entry.cacheFile().length() > 0)) {
log.logFine("(Parser) '" + entry.normalizedURLString() + "' is not parsed yet, parsing now from File");
- document = parser.parseSource(entry.url(), (entry.responseHeader() == null) ? null : entry.responseHeader().mime(), entry.cacheFile());
+ document = parser.parseSource(entry.url(), mimeType, entry.cacheFile());
} else {
log.logFine("(Parser) '" + entry.normalizedURLString() + "' cannot be parsed, no resource available");
return;
@@ -1010,7 +1028,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
return;
}
} else {
- log.logFine("(Parser) '" + entry.normalizedURLString() + "'. Unsupported mimeType '" + ((entry.responseHeader() == null) ? "null" : entry.responseHeader().mime()) + "'.");
+ log.logFine("(Parser) '" + entry.normalizedURLString() + "'. Unsupported mimeType '" + ((mimeType == null) ? "null" : mimeType) + "'.");
return;
}
parsingEndTime = System.currentTimeMillis();
@@ -1035,17 +1053,18 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
while (i.hasNext()) {
e = (Map.Entry) i.next();
nexturlstring = (String) e.getKey();
-
- rejectReason = stackCrawl(nexturlstring, entry.normalizedURLString(), initiatorHash, (String) e.getValue(), loadDate, entry.depth() + 1, entry.profile());
- if (rejectReason == null) {
- c++;
- } else {
- urlPool.errorURL.newEntry(new URL(nexturlstring), entry.normalizedURLString(), entry.initiator(), yacyCore.seedDB.mySeed.hash,
- (String) e.getValue(), rejectReason, new bitfield(plasmaURL.urlFlagLength), false);
- }
+
+ sbStackCrawlThread.stackCrawlEnqueue(nexturlstring, entry.normalizedURLString(), initiatorHash, (String) e.getValue(), loadDate, entry.depth() + 1, entry.profile());
+
+// rejectReason = stackCrawl(nexturlstring, entry.normalizedURLString(), initiatorHash, (String) e.getValue(), loadDate, entry.depth() + 1, entry.profile());
+// if (rejectReason == null) {
+// c++;
+// } else {
+// urlPool.errorURL.newEntry(new URL(nexturlstring), entry.normalizedURLString(), entry.initiator(), yacyCore.seedDB.mySeed.hash,
+// (String) e.getValue(), rejectReason, new bitfield(plasmaURL.urlFlagLength), false);
+// }
}
- log.logInfo("CRAWL: ADDED " + c + " LINKS FROM " + entry.normalizedURLString() +
- ", " + (hl.size() - c) + " LINKS DOUBLE" +
+ log.logInfo("CRAWL: ADDED " + hl.size() + " LINKS FROM " + entry.normalizedURLString() +
", NEW CRAWL STACK SIZE IS " + urlPool.noticeURL.stackSize(plasmaCrawlNURL.STACK_TYPE_CORE));
}
stackEndTime = System.currentTimeMillis();
@@ -1108,7 +1127,60 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
// do indexing
//log.logDebug("Create Index for '" + entry.normalizedURLString() + "'");
storageStartTime = System.currentTimeMillis();
- int words = searchManager.addPageIndex(entry.url(), urlHash, loadDate, condenser, plasmaWordIndexEntry.language(entry.url()), plasmaWordIndexEntry.docType(document.getMimeType()));
+ int words = 0;
+ String storagePeerHash;
+ yacySeed seed;
+ if (((storagePeerHash = getConfig("storagePeerHash",null))== null) ||
+ (storagePeerHash.trim().length() == 0) ||
+ ((seed = yacyCore.seedDB.getConnected(storagePeerHash))==null)){
+ words = searchManager.addPageIndex(entry.url(), urlHash, loadDate, condenser, plasmaWordIndexEntry.language(entry.url()), plasmaWordIndexEntry.docType(document.getMimeType()));
+ } else {
+ HashMap urlCache = new HashMap(1);
+ urlCache.put(newEntry.hash(),newEntry);
+
+ ArrayList tmpEntities = new ArrayList(condenser.getWords().size());
+
+ int age = plasmaSearch.calcVirtualAge(lastModified);
+ int quality = 0;
+ try {
+ quality = Integer.parseInt(condenser.getAnalysis().getProperty("INFORMATION_VALUE","0"), 16);
+ } catch (NumberFormatException e) {
+ System.out.println("INTERNAL ERROR WITH CONDENSER.INFORMATION_VALUE: " + e.toString() + ": in URL " + newEntry.url().toString());
+ }
+
+ String language = plasmaWordIndexEntry.language(entry.url());
+ char doctype = plasmaWordIndexEntry.docType(document.getMimeType());
+
+ // iterate over all words
+ Iterator i = condenser.getWords().iterator();
+ int p = 0;
+ while (i.hasNext()) {
+ String word = (String) i.next();
+ int count = condenser.wordCount(word);
+ String wordHash = plasmaWordIndexEntry.word2hash(word);
+ plasmaWordIndexEntity wordIdxEntity = new plasmaWordIndexEntity(wordHash);
+ plasmaWordIndexEntry wordIdxEntry = new plasmaWordIndexEntry(urlHash, count, p++, 0, 0,
+ age, quality, language, doctype, true);
+ wordIdxEntity.addEntry(wordIdxEntry);
+ tmpEntities.add(wordIdxEntity);
+ // wordIndex.addEntries(plasmaWordIndexEntryContainer.instantContainer(wordHash, System.currentTimeMillis(), entry));
+ }
+ //System.out.println("DEBUG: plasmaSearch.addPageIndex: added " + condenser.getWords().size() + " words, flushed " + c + " entries");
+ words = condenser.getWords().size();
+
+ // transfering the index to the storage peer
+ String error = yacyClient.transferIndex(seed,(plasmaWordIndexEntity[])tmpEntities.toArray(new plasmaWordIndexEntity[tmpEntities.size()]),urlCache,true,120000);
+
+ if (error != null) {
+ words = searchManager.addPageIndex(entry.url(), urlHash, loadDate, condenser, plasmaWordIndexEntry.language(entry.url()), plasmaWordIndexEntry.docType(document.getMimeType()));
+ }
+
+ // cleanup
+ for (int j=0; j < tmpEntities.size(); j++) {
+ plasmaWordIndexEntity tmpEntity = (plasmaWordIndexEntity) tmpEntities.get(j);
+ try { tmpEntity.close(); } catch (Exception e) {}
+ }
+ }
storageEndTime = System.currentTimeMillis();
if (log.isLoggable(Level.INFO)) {
@@ -1167,143 +1239,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
}
}
- public String stackCrawl(String nexturlString, String referrerString, String initiatorHash, String name, Date loadDate, int currentdepth, plasmaCrawlProfile.entry profile) {
- // stacks a crawl item. The position can also be remote
- // returns null if successful, a reason string if not successful
-
- String reason = null; // failure reason
- // strange errors
- if (nexturlString == null) {
- reason = "denied_(url_null)";
- log.logSevere("Wrong URL in stackCrawl: url=null");
- return reason;
- }
- /*
- if (profile == null) {
- reason = "denied_(profile_null)";
- log.logError("Wrong Profile for stackCrawl: profile=null");
- return reason;
- }
- */
- URL nexturl = null;
- if ((initiatorHash == null) || (initiatorHash.length() == 0)) initiatorHash = plasmaURL.dummyHash;
- String referrerHash = plasmaURL.urlHash(referrerString);
- try {
- nexturl = new URL(nexturlString);
- } catch (MalformedURLException e) {
- reason = "denied_(url_'" + nexturlString + "'_wrong)";
- log.logSevere("Wrong URL in stackCrawl: " + nexturlString);
- return reason;
- }
-
- // check if ip is local ip address
- try {
- InetAddress hostAddress = InetAddress.getByName(nexturl.getHost());
- if (hostAddress.isSiteLocalAddress()) {
- reason = "denied_(private_ip_address)";
- log.logFine("Host in URL '" + nexturlString + "' has private ip address.");
- return reason;
- } else if (hostAddress.isLoopbackAddress()) {
- reason = "denied_(loopback_ip_address)";
- log.logFine("Host in URL '" + nexturlString + "' has loopback ip address.");
- return reason;
- }
- } catch (UnknownHostException e) {
- reason = "denied_(unknown_host)";
- log.logFine("Unknown host in URL '" + nexturlString + "'.");
- return reason;
- }
-
- // check blacklist
- String hostlow = nexturl.getHost().toLowerCase();
- if (urlBlacklist.isListed(hostlow, nexturl.getPath())) {
- reason = "denied_(url_in_blacklist)";
- log.logFine("URL '" + nexturlString + "' is in blacklist.");
- return reason;
- }
-
- // filter deny
- if ((currentdepth > 0) && (profile != null) && (!(nexturlString.matches(profile.generalFilter())))) {
- reason = "denied_(does_not_match_filter)";
- /*
- urlPool.errorURL.newEntry(nexturl, referrerHash, initiatorHash, yacyCore.seedDB.mySeed.hash,
- name, reason, new bitfield(plasmaURL.urlFlagLength), false);*/
- log.logFine("URL '" + nexturlString + "' does not match crawling filter '" + profile.generalFilter() + "'.");
- return reason;
- }
-
- // deny cgi
- if (plasmaHTCache.isCGI(nexturlString)) {
- reason = "denied_(cgi_url)";
- /*
- urlPool.errorURL.newEntry(nexturl, referrerHash, initiatorHash, yacyCore.seedDB.mySeed.hash,
- name, reason, new bitfield(plasmaURL.urlFlagLength), false);*/
- log.logFine("URL '" + nexturlString + "' is cgi URL.");
- return reason;
- }
-
- // deny post properties
- if ((plasmaHTCache.isPOST(nexturlString)) && (profile != null) && (!(profile.crawlingQ()))) {
- reason = "denied_(post_url)";
- /*
- urlPool.errorURL.newEntry(nexturl, referrerHash, initiatorHash, yacyCore.seedDB.mySeed.hash,
- name, reason, new bitfield(plasmaURL.urlFlagLength), false);*/
- log.logFine("URL '" + nexturlString + "' is post URL.");
- return reason;
- }
-
- String nexturlhash = plasmaURL.urlHash(nexturl);
- String dbocc = "";
- if ((dbocc = urlPool.exists(nexturlhash)) != null) {
- // DISTIGUISH OLD/RE-SEARCH CASES HERE!
- reason = "double_(registered_in_" + dbocc + ")";
- /*
- urlPool.errorURL.newEntry(nexturl, referrerHash, initiatorHash, yacyCore.seedDB.mySeed.hash,
- name, reason, new bitfield(plasmaURL.urlFlagLength), false);*/
- log.logFine("URL '" + nexturlString + "' is double registered in '" + dbocc + "'.");
- return reason;
- }
-
- // checking robots.txt
- if (robotsParser.isDisallowed(nexturl)) {
- reason = "denied_(robots.txt)";
- /*
- urlPool.errorURL.newEntry(nexturl, referrerHash, initiatorHash, yacyCore.seedDB.mySeed.hash,
- name, reason, new bitfield(plasmaURL.urlFlagLength), false);*/
- log.logFine("Crawling of URL '" + nexturlString + "' disallowed by robots.txt.");
- return reason;
- }
-
- // store information
- boolean local = ((initiatorHash.equals(plasmaURL.dummyHash)) || (initiatorHash.equals(yacyCore.seedDB.mySeed.hash)));
- boolean global =
- (profile != null) &&
- (profile.remoteIndexing()) /* granted */ &&
- (currentdepth == profile.generalDepth()) /* leaf node */ &&
- (initiatorHash.equals(yacyCore.seedDB.mySeed.hash)) /* not proxy */ &&
- ((yacyCore.seedDB.mySeed.isSenior()) ||
- (yacyCore.seedDB.mySeed.isPrincipal())) /* qualified */;
-
- if ((!local)&&(!global)) {
- log.logFine("URL '" + nexturlString + "' can neither be crawled local nor global.");
- }
-
- urlPool.noticeURL.newEntry(initiatorHash, /* initiator, needed for p2p-feedback */
- nexturl, /* url clear text string */
- loadDate, /* load date */
- referrerHash, /* last url in crawling queue */
- name, /* the anchor name */
- (profile == null) ? null : profile.handle(), // profile must not be null!
- currentdepth, /*depth so far*/
- 0, /*anchors, default value */
- 0, /*forkfactor, default value */
- ((global) ? plasmaCrawlNURL.STACK_TYPE_LIMIT :
- ((local) ? plasmaCrawlNURL.STACK_TYPE_CORE : plasmaCrawlNURL.STACK_TYPE_REMOTE)) /*local/remote stack*/
- );
-
- return null;
- }
private void processLocalCrawling(plasmaCrawlNURL.Entry urlEntry, plasmaCrawlProfile.entry profile, String stats) {
// work off one Crawl stack entry
@@ -1425,10 +1361,11 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
this.fetchcount = fetchcount;
}
public void run() {
+ plasmaWordIndexEntity idx = null;
try {
// search the database locally
log.logFine("presearch: started job");
- plasmaWordIndexEntity idx = searchManager.searchHashes(queryhashes, time);
+ idx = searchManager.searchHashes(queryhashes, time);
log.logFine("presearch: found " + idx.size() + " results");
plasmaSearch.result acc = searchManager.order(idx, queryhashes, stopwords, order, time, searchcount);
if (acc == null) return;
@@ -1438,6 +1375,8 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser
snippetCache.fetch(acc, queryhashes, urlmask, fetchcount);
} catch (IOException e) {
log.logSevere("presearch: failed", e);
+ } finally {
+ if (idx != null) try { idx.close(); } catch (Exception e){}
}
log.logFine("presearch: job terminated");
}
diff --git a/source/de/anomic/plasma/plasmaSwitchboardQueue.java b/source/de/anomic/plasma/plasmaSwitchboardQueue.java
index f42bedb44..e2c54c0f1 100644
--- a/source/de/anomic/plasma/plasmaSwitchboardQueue.java
+++ b/source/de/anomic/plasma/plasmaSwitchboardQueue.java
@@ -205,6 +205,19 @@ public class plasmaSwitchboardQueue {
this.referrerURL = null;
}
+ public String toString() {
+ StringBuffer str = new StringBuffer();
+ str.append("url: ") .append(this.url==null ? "null" : this.url.toString()).append(" | ")
+ .append("referrer: ") .append(this.referrerHash==null?"null":this.referrerHash).append(" | ")
+ .append("ifModifiedSince: ").append(this.ifModifiedSince==null?"null":this.ifModifiedSince.toString()).append(" | ")
+ .append("flags: ") .append(Byte.toString(this.flags)).append(" | ")
+ .append("initiator: ") .append(this.initiator==null ? "null" : this.initiator).append(" | ")
+ .append("depth: ") .append(Integer.toString(this.depth)).append(" | ")
+ .append("profile: ") .append(this.profileHandle==null?"null":this.profileHandle).append(" | ")
+ .append("anchorName: ") .append(this.anchorName==null?"null":this.anchorName);
+ return str.toString();
+ }
+
public URL url() {
return url;
}
diff --git a/source/de/anomic/plasma/plasmaURL.java b/source/de/anomic/plasma/plasmaURL.java
index 43e4ea0f3..44b06512b 100644
--- a/source/de/anomic/plasma/plasmaURL.java
+++ b/source/de/anomic/plasma/plasmaURL.java
@@ -46,8 +46,6 @@ import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Iterator;
-import java.util.Properties;
-import java.util.StringTokenizer;
import de.anomic.htmlFilter.htmlFilterContentScraper;
import de.anomic.kelondro.kelondroTree;
@@ -57,7 +55,7 @@ import de.anomic.yacy.yacySeedDB;
public class plasmaURL {
// day formatter for entry export
- protected static SimpleDateFormat shortDayFormatter = new SimpleDateFormat("yyyyMMdd");
+ protected static final SimpleDateFormat shortDayFormatter = new SimpleDateFormat("yyyyMMdd");
// statics for value lengths
public static final int urlHashLength = yacySeedDB.commonHashLength; // 12
@@ -130,13 +128,13 @@ public class plasmaURL {
} catch (IOException e) {}
}
- public static String urlHash(URL url) {
+ public static final String urlHash(URL url) {
if (url == null) return null;
String hash = serverCodings.encodeMD5B64(htmlFilterContentScraper.urlNormalform(url), true).substring(0, urlHashLength);
return hash;
}
- public static String urlHash(String url) {
+ public static final String urlHash(String url) {
if ((url == null) || (url.length() < 10)) return null;
String hash = serverCodings.encodeMD5B64(htmlFilterContentScraper.urlNormalform(url), true).substring(0, urlHashLength);
return hash;
diff --git a/source/de/anomic/plasma/plasmaURLPool.java b/source/de/anomic/plasma/plasmaURLPool.java
index 7726919b2..3a81553cf 100644
--- a/source/de/anomic/plasma/plasmaURLPool.java
+++ b/source/de/anomic/plasma/plasmaURLPool.java
@@ -47,15 +47,13 @@ package de.anomic.plasma;
import java.net.URL;
import java.io.File;
import java.io.IOException;
-import java.util.Set;
-import java.util.Iterator;
public class plasmaURLPool {
- public plasmaCrawlLURL loadedURL;
- public plasmaCrawlNURL noticeURL;
- public plasmaCrawlEURL errorURL;
+ public final plasmaCrawlLURL loadedURL;
+ public final plasmaCrawlNURL noticeURL;
+ public final plasmaCrawlEURL errorURL;
public plasmaURLPool(File plasmaPath, int ramLURL, int ramNURL, int ramEURL) throws IOException {
loadedURL = new plasmaCrawlLURL(new File(plasmaPath, "urlHash.db"), ramLURL);
diff --git a/source/de/anomic/plasma/plasmaWordIndex.java b/source/de/anomic/plasma/plasmaWordIndex.java
index 7935a551e..ad53dd971 100644
--- a/source/de/anomic/plasma/plasmaWordIndex.java
+++ b/source/de/anomic/plasma/plasmaWordIndex.java
@@ -130,7 +130,7 @@ public final class plasmaWordIndex {
return new correctedWordIterator(up, rot, startHash); // use correction until bug is found
}
- private class correctedWordIterator implements Iterator {
+ private final class correctedWordIterator implements Iterator {
Iterator iter;
String nextWord;
@@ -181,13 +181,13 @@ public final class plasmaWordIndex {
return new iterateFiles(startHash, up, deleteEmpty);
}
- public class iterateFiles implements Iterator {
+ public final class iterateFiles implements Iterator {
// Iterator of hash-strings in WORDS path
- private ArrayList hierarchy; // contains TreeSet elements, earch TreeSet contains File Entries
- private Comparator comp; // for string-compare
+ private final ArrayList hierarchy; // contains TreeSet elements, earch TreeSet contains File Entries
+ private final Comparator comp; // for string-compare
private String buffer; // the prefetch-buffer
- private boolean delete;
+ private final boolean delete;
public iterateFiles(String startHash, boolean up, boolean deleteEmpty) {
this.hierarchy = new ArrayList();
diff --git a/source/de/anomic/plasma/plasmaWordIndexCache.java b/source/de/anomic/plasma/plasmaWordIndexCache.java
index d5e56a4f5..d14eb487c 100644
--- a/source/de/anomic/plasma/plasmaWordIndexCache.java
+++ b/source/de/anomic/plasma/plasmaWordIndexCache.java
@@ -296,6 +296,7 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
public flush() {
terminate = false;
intermission = 0;
+ this.setName(this.getClass().getName());
}
public void intermission(long pause) {
@@ -534,36 +535,41 @@ public final class plasmaWordIndexCache implements plasmaWordIndexInterface {
// can be negative if some assortments have been moved to the backend
File db = plasmaWordIndexEntity.wordHash2path(databaseRoot, wordhash);
if (!(db.exists())) return 0;
- plasmaWordIndexEntity entity = new plasmaWordIndexEntity(databaseRoot, wordhash, true);
- int size = entity.size();
- if (size > assortmentCluster.clusterCapacity) {
- // this will be too big to integrate it
- entity.close();
- return 0;
- } else {
- // take out all words from the assortment to see if it fits
- // together with the extracted assortment
- plasmaWordIndexEntryContainer container = assortmentCluster.removeFromAll(wordhash);
- if (size + container.size() > assortmentCluster.clusterCapacity) {
- // this will also be too big to integrate, add to entity
- entity.addEntries(container);
- entity.close();
- return -container.size();
+ plasmaWordIndexEntity entity = null;
+ try {
+ entity = new plasmaWordIndexEntity(databaseRoot, wordhash, true);
+ int size = entity.size();
+ if (size > assortmentCluster.clusterCapacity) {
+ // this will be too big to integrate it
+ entity.close(); entity = null;
+ return 0;
} else {
- // the combined container will fit, read the container
- Enumeration entries = entity.elements(true);
- plasmaWordIndexEntry entry;
- while (entries.hasMoreElements()) {
- entry = (plasmaWordIndexEntry) entries.nextElement();
- container.add(new plasmaWordIndexEntry[]{entry}, System.currentTimeMillis());
+ // take out all words from the assortment to see if it fits
+ // together with the extracted assortment
+ plasmaWordIndexEntryContainer container = assortmentCluster.removeFromAll(wordhash);
+ if (size + container.size() > assortmentCluster.clusterCapacity) {
+ // this will also be too big to integrate, add to entity
+ entity.addEntries(container);
+ entity.close(); entity = null;
+ return -container.size();
+ } else {
+ // the combined container will fit, read the container
+ Enumeration entries = entity.elements(true);
+ plasmaWordIndexEntry entry;
+ while (entries.hasMoreElements()) {
+ entry = (plasmaWordIndexEntry) entries.nextElement();
+ container.add(new plasmaWordIndexEntry[]{entry}, System.currentTimeMillis());
+ }
+ // we have read all elements, now delete the entity
+ entity.deleteComplete();
+ entity.close(); entity = null;
+ // integrate the container into the assortments; this will work
+ assortmentCluster.storeTry(wordhash, container);
+ return size;
}
- // we have read all elements, now delete the entity
- entity.deleteComplete();
- entity.close();
- // integrate the container into the assortments; this will work
- assortmentCluster.storeTry(wordhash, container);
- return size;
}
+ } finally {
+ if (entity != null) try {entity.close();}catch(Exception e){}
}
}
diff --git a/source/de/anomic/plasma/plasmaWordIndexClassicDB.java b/source/de/anomic/plasma/plasmaWordIndexClassicDB.java
index 3db074824..7f0d96aea 100644
--- a/source/de/anomic/plasma/plasmaWordIndexClassicDB.java
+++ b/source/de/anomic/plasma/plasmaWordIndexClassicDB.java
@@ -57,8 +57,8 @@ public class plasmaWordIndexClassicDB implements plasmaWordIndexInterface {
// class variables
- private File databaseRoot;
- private serverLog log;
+ private final File databaseRoot;
+ private final serverLog log;
private int size;
public plasmaWordIndexClassicDB(File databaseRoot, serverLog log) throws IOException {
@@ -77,8 +77,8 @@ public class plasmaWordIndexClassicDB implements plasmaWordIndexInterface {
public class iterateFiles implements Iterator {
- private ArrayList hierarchy; // contains TreeSet elements, earch TreeSet contains File Entries
- private Comparator comp; // for string-compare
+ private final ArrayList hierarchy; // contains TreeSet elements, earch TreeSet contains File Entries
+ private final Comparator comp; // for string-compare
private String buffer; // the prefetch-buffer
public iterateFiles(String startHash, boolean up) {
@@ -207,9 +207,10 @@ public class plasmaWordIndexClassicDB implements plasmaWordIndexInterface {
public int removeEntries(String wordHash, String[] urlHashes, boolean deleteComplete) {
// removes all given url hashes from a single word index. Returns number of deletions.
- plasmaWordIndexEntity pi = getIndex(wordHash, true);
+ plasmaWordIndexEntity pi = null;
int count = 0;
try {
+ pi = getIndex(wordHash, true);
for (int i = 0; i < urlHashes.length; i++)
if (pi.removeEntry(urlHashes[i], deleteComplete)) count++;
int size = pi.size();
@@ -220,6 +221,8 @@ public class plasmaWordIndexClassicDB implements plasmaWordIndexInterface {
} catch (IOException e) {
log.logSevere("plasmaWordIndexClassic.removeEntries: " + e.getMessage());
return count;
+ } finally {
+ if (pi != null) try{pi.close();}catch(Exception e){}
}
}
@@ -229,17 +232,19 @@ public class plasmaWordIndexClassicDB implements plasmaWordIndexInterface {
if ((container == null) || (container.size() == 0)) return 0;
// open file
+ plasmaWordIndexEntity pi = null;
try {
- plasmaWordIndexEntity pi = new plasmaWordIndexEntity(databaseRoot, container.wordHash(), false);
+ pi = new plasmaWordIndexEntity(databaseRoot, container.wordHash(), false);
int count = pi.addEntries(container);
// close and return
- pi.close();
- pi = null;
+ pi.close(); pi = null;
return count;
} catch (IOException e) {
log.logSevere("plasmaWordIndexClassic.addEntries: " + e.getMessage());
return 0;
+ } finally {
+ if (pi != null) try{pi.close();}catch (Exception e){}
}
}
diff --git a/source/de/anomic/plasma/plasmaWordIndexDistribution.java b/source/de/anomic/plasma/plasmaWordIndexDistribution.java
index d247076ee..0b7d33403 100644
--- a/source/de/anomic/plasma/plasmaWordIndexDistribution.java
+++ b/source/de/anomic/plasma/plasmaWordIndexDistribution.java
@@ -43,8 +43,8 @@
package de.anomic.plasma;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.Enumeration;
-import java.util.Vector;
import java.util.Iterator;
import java.util.HashSet;
import java.util.HashMap;
@@ -58,7 +58,7 @@ import de.anomic.server.serverCodings;
import de.anomic.server.logging.serverLog;
import de.anomic.kelondro.kelondroException;
-public class plasmaWordIndexDistribution {
+public final class plasmaWordIndexDistribution {
// distributes parts of the index to other peers
// stops as soon as an error occurrs
@@ -67,18 +67,20 @@ public class plasmaWordIndexDistribution {
private int juniorPeerCount, seniorPeerCount;
private long maxTime;
- private plasmaURLPool urlPool;
- private plasmaWordIndex wordIndex;
- serverLog log;
+ private final plasmaURLPool urlPool;
+ private final plasmaWordIndex wordIndex;
+ final serverLog log;
boolean paused = false;
private boolean enabled;
private boolean enabledWhileCrawling;
private boolean closed;
+ private boolean gzipBody;
+ private int timeout;
public transferIndexThread transferIdxThread = null;
public plasmaWordIndexDistribution(plasmaURLPool urlPool, plasmaWordIndex wordIndex, serverLog log,
- boolean enable, boolean enabledWhileCrawling) {
+ boolean enable, boolean enabledWhileCrawling, boolean gzipBody, int timeout) {
this.urlPool = urlPool;
this.wordIndex = wordIndex;
this.enabled = enable;
@@ -86,6 +88,8 @@ public class plasmaWordIndexDistribution {
this.log = log;
this.closed = false;
setCounts(100 /*indexCount*/, 1 /*juniorPeerCount*/, 3 /*seniorPeerCount*/, 8000);
+ this.gzipBody = gzipBody;
+ this.timeout = timeout;
}
public void enable() {
@@ -112,7 +116,7 @@ public class plasmaWordIndexDistribution {
}
public boolean job() {
-
+
if (this.closed) {
log.logFine("no word distribution: closed");
return false;
@@ -159,14 +163,14 @@ public class plasmaWordIndexDistribution {
log.logFine("no word distribution: transfer failed");
return false;
}
-
+
// adopt transfer count
if ((System.currentTimeMillis() - starttime) > (maxTime * peerCount))
indexCount--;
else
indexCount++;
if (indexCount < 50) indexCount = 50;
-
+
// show success
return true;
@@ -217,15 +221,15 @@ public class plasmaWordIndexDistribution {
}
seed = (yacySeed) e.nextElement();
if ((seed != null) &&
- ((avdist = (yacyDHTAction.dhtDistance(seed.hash, indexEntities[0].wordHash()) +
+ ((avdist = (yacyDHTAction.dhtDistance(seed.hash, indexEntities[0].wordHash()) +
yacyDHTAction.dhtDistance(seed.hash, indexEntities[indexEntities.length-1].wordHash())) / 2.0) < 0.3)) {
start = System.currentTimeMillis();
- error = yacyClient.transferIndex(seed, indexEntities, urlCache);
+ error = yacyClient.transferIndex(seed, indexEntities, urlCache, this.gzipBody, this.timeout);
if (error == null) {
log.logInfo("Index transfer of " + indexCount + " words [" + indexEntities[0].wordHash() + " .. " + indexEntities[indexEntities.length-1].wordHash() + "]/" +
- avdist + " to peer " + seed.getName() + ":" + seed.hash + " in " +
- ((System.currentTimeMillis() - start) / 1000) + " seconds successfull (" +
- (1000 * indexCount / (System.currentTimeMillis() - start + 1)) + " words/s)");
+ avdist + " to peer " + seed.getName() + ":" + seed.hash + " in " +
+ ((System.currentTimeMillis() - start) / 1000) + " seconds successfull (" +
+ (1000 * indexCount / (System.currentTimeMillis() - start + 1)) + " words/s)");
peerNames += ", " + seed.getName();
hc++;
} else {
@@ -278,9 +282,9 @@ public class plasmaWordIndexDistribution {
}
Object[] /* of {plasmaWordIndexEntity[], HashMap(String, plasmaCrawlLURL.Entry)}*/
- selectTransferIndexes(String hash, int count) {
+ selectTransferIndexes(String hash, int count) {
// the hash is a start hash from where the indexes are picked
- Vector tmpEntities = new Vector();
+ ArrayList tmpEntities = new ArrayList(count);
String nexthash = "";
try {
Iterator wordHashIterator = wordIndex.wordHashes(hash, true, true);
@@ -289,22 +293,22 @@ public class plasmaWordIndexDistribution {
Iterator hashIter;
plasmaWordIndexEntry indexEntry;
plasmaCrawlLURL.Entry lurl;
- HashSet unknownURLEntries;
- HashMap knownURLs = new HashMap();
+ final HashSet unknownURLEntries = new HashSet();
+ final HashMap knownURLs = new HashMap();
while ((count > 0) && (wordHashIterator.hasNext()) &&
- ((nexthash = (String) wordHashIterator.next()) != null) && (nexthash.trim().length() > 0)) {
+ ((nexthash = (String) wordHashIterator.next()) != null) && (nexthash.trim().length() > 0)) {
indexEntity = wordIndex.getEntity(nexthash, true);
if (indexEntity.size() == 0) {
indexEntity.deleteComplete();
} else if ((indexEntity.size() <= count)|| // if we havn't exceeded the limit
- (Math.abs(indexEntity.size() - count) <= 10)){ // or there are only at most 10 entries left
+ (Math.abs(indexEntity.size() - count) <= 10)){ // or there are only at most 10 entries left
// take the whole entity
try {
// fist check if we know all urls
urlEnum = indexEntity.elements(true);
- unknownURLEntries = new HashSet();
+ unknownURLEntries.clear();
while (urlEnum.hasMoreElements()) {
- indexEntry = (plasmaWordIndexEntry) urlEnum.nextElement();
+ indexEntry = (plasmaWordIndexEntry) urlEnum.nextElement();
lurl = urlPool.loadedURL.getEntry(indexEntry.getUrlHash());
if ((lurl == null) || (lurl.toString() == null)) {
unknownURLEntries.add(indexEntry.getUrlHash());
@@ -322,12 +326,17 @@ public class plasmaWordIndexDistribution {
while (hashIter.hasNext()) {
indexEntity.removeEntry((String) hashIter.next(), false);
}
- // use whats remaining
- tmpEntities.add(indexEntity);
- log.logFine("Selected whole index (" + indexEntity.size() + " URLs, " + unknownURLEntries.size() + " not bound) for word " + indexEntity.wordHash());
- count -= indexEntity.size();
+
+ if (indexEntity.size() == 0) {
+ indexEntity.deleteComplete();
+ } else {
+ // use whats remaining
+ tmpEntities.add(indexEntity);
+ this.log.logFine("Selected whole index (" + indexEntity.size() + " URLs, " + unknownURLEntries.size() + " not bound) for word " + indexEntity.wordHash());
+ count -= indexEntity.size();
+ }
} catch (kelondroException e) {
- log.logSevere("plasmaWordIndexDistribution/1: deleted DB for word " + indexEntity.wordHash(), e);
+ this.log.logSevere("plasmaWordIndexDistribution/1: deleted DB for word " + indexEntity.wordHash(), e);
try {indexEntity.deleteComplete();} catch (IOException ee) {}
}
} else {
@@ -335,7 +344,7 @@ public class plasmaWordIndexDistribution {
tmpEntity = new plasmaWordIndexEntity(indexEntity.wordHash());
try {
urlEnum = indexEntity.elements(true);
- unknownURLEntries = new HashSet();
+ unknownURLEntries.clear();
while ((urlEnum.hasMoreElements()) && (count > 0)) {
indexEntry = (plasmaWordIndexEntry) urlEnum.nextElement();
lurl = urlPool.loadedURL.getEntry(indexEntry.getUrlHash());
@@ -370,15 +379,14 @@ public class plasmaWordIndexDistribution {
}
// transfer to array
- plasmaWordIndexEntity[] indexEntities = new plasmaWordIndexEntity[tmpEntities.size()];
- for (int i = 0; i < tmpEntities.size(); i++) indexEntities[i] = (plasmaWordIndexEntity) tmpEntities.elementAt(i);
+ plasmaWordIndexEntity[] indexEntities = (plasmaWordIndexEntity[]) tmpEntities.toArray(new plasmaWordIndexEntity[tmpEntities.size()]);
return new Object[]{indexEntities, knownURLs};
} catch (IOException e) {
log.logSevere("selectTransferIndexes IO-Error (hash=" + nexthash + "): " + e.getMessage(), e);
- return new Object[]{new plasmaWordIndexEntity[0], new HashMap()};
+ return new Object[]{new plasmaWordIndexEntity[0], new HashMap(0)};
} catch (kelondroException e) {
log.logSevere("selectTransferIndexes database corrupted: " + e.getMessage(), e);
- return new Object[]{new plasmaWordIndexEntity[0], new HashMap()};
+ return new Object[]{new plasmaWordIndexEntity[0], new HashMap(0)};
}
}
@@ -407,10 +415,10 @@ public class plasmaWordIndexDistribution {
log.logFine("Deleted partial index (" + c + " URLs) for word " + indexEntities[i].wordHash() + "; " + sz + " entries left");
// DEBUG: now try to delete the remaining index. If this works, this routine is fine
/*
- if (wordIndex.getEntity(indexEntities[i].wordHash()).deleteComplete())
- System.out.println("DEBUG: trial delete of partial word index " + indexEntities[i].wordHash() + " SUCCESSFULL");
- else
- System.out.println("DEBUG: trial delete of partial word index " + indexEntities[i].wordHash() + " FAILED");
+ if (wordIndex.getEntity(indexEntities[i].wordHash()).deleteComplete())
+ System.out.println("DEBUG: trial delete of partial word index " + indexEntities[i].wordHash() + " SUCCESSFULL");
+ else
+ System.out.println("DEBUG: trial delete of partial word index " + indexEntities[i].wordHash() + " FAILED");
*/
// end debug
indexEntities[i].close();
@@ -432,7 +440,7 @@ public class plasmaWordIndexDistribution {
return success;
}
-
+
public void startTransferWholeIndex(yacySeed seed, boolean delete) {
if (transferIdxThread == null) {
this.transferIdxThread = new transferIndexThread(seed,delete);
@@ -447,33 +455,210 @@ public class plasmaWordIndexDistribution {
} catch (InterruptedException e) { }
}
}
-
+
public void abortTransferWholeIndex(boolean wait) {
if (transferIdxThread != null) {
if (!transferIdxThread.isFinished())
try {
this.transferIdxThread.stopIt(wait);
} catch (InterruptedException e) { }
- transferIdxThread = null;
+ transferIdxThread = null;
}
}
+ private class transferIndexWorkerThread extends Thread{
+ // connection properties
+ private boolean gzipBody = false;
+ private int timeout = 60000;
+
+ // status fields
+ private boolean finished = false;
+ boolean success = false;
+ private String status = "running";
+ private long iteration = 0;
+ private long transferTime = 0;
+ private int idxCount = 0;
+ private int chunkSize = 0;
+
+ // delivery destination
+ yacySeed seed = null;
+
+ // word chunk
+ private String endPointHash;
+ private String startPointHash;
+ plasmaWordIndexEntity[] indexEntities;
+
+ // other fields
+ HashMap urlCache;
+
+ public transferIndexWorkerThread(
+ yacySeed seed,
+ plasmaWordIndexEntity[] indexEntities,
+ HashMap urlCache,
+ boolean gzipBody,
+ int timeout,
+ long iteration,
+ int idxCount,
+ int chunkSize,
+ String endPointHash,
+ String startPointHash) {
+ super(new ThreadGroup("TransferIndexThreadGroup"),"TransferIndexWorker_" + seed.getName());
+ this.gzipBody = gzipBody;
+ this.timeout = timeout;
+ this.iteration = iteration;
+ this.seed = seed;
+ this.indexEntities = indexEntities;
+ this.urlCache = urlCache;
+ this.idxCount = idxCount;
+ this.chunkSize = chunkSize;
+ this.startPointHash = startPointHash;
+ this.endPointHash = endPointHash;
+ }
+
+ public void run() {
+ try {
+ uploadIndex();
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } finally {
+
+ }
+ }
+
+ public boolean success() {
+ return this.success;
+ }
+
+ public int getChunkSize() {
+ return this.chunkSize;
+ }
+
+ public String getStatus() {
+ return this.status;
+ }
+
+ private boolean isAborted() {
+ if (finished || Thread.currentThread().isInterrupted()) {
+ return true;
+ }
+ return false;
+ }
+
+ public void stopIt() {
+ this.finished = true;
+ }
+
+ public String getRange() {
+ return "[" + startPointHash + ".." + endPointHash + "]";
+ }
+
+ public long getTransferTime() {
+ return this.transferTime;
+ }
+
+ private void uploadIndex() throws InterruptedException {
+
+ /* loop until we
+ * - have successfully transfered the words list or
+ * - the retry counter limit was exceeded
+ */
+ long retryCount = 0, start = System.currentTimeMillis();
+ while (true) {
+ // testing if we wer aborted
+ if (isAborted()) return;
+
+ // transfering seleted words to remote peer
+ this.status = "Running: Transfering chunk " + iteration;
+ String error = yacyClient.transferIndex(seed, indexEntities, urlCache, this.gzipBody, this.timeout);
+ if (error == null) {
+ // words successfully transfered
+ transferTime = System.currentTimeMillis() - start;
+ plasmaWordIndexDistribution.this.log.logInfo("Index transfer of " + idxCount + " words [" + indexEntities[0].wordHash() + " .. " + indexEntities[indexEntities.length-1].wordHash() + "]" +
+ " to peer " + seed.getName() + ":" + seed.hash + " in " + (transferTime/1000) + " seconds successfull (" +
+ (1000 * idxCount / (transferTime + 1)) + " words/s)");
+ retryCount = 0;
+
+// if (transferTime > 30000) {
+// if (chunkSize>100) chunkSize-=50;
+// } else {
+// chunkSize+=50;
+// }
+ this.success = true;
+ this.status = "Finished: Transfer of chunk " + iteration;
+ break;
+ } else {
+ // worts transfer failed
+
+ // inc retry counter
+ retryCount++;
+
+ // testing if we were aborted ...
+ if (isAborted()) return;
+
+ // we have lost the connection to the remote peer. Adding peer to disconnected list
+ plasmaWordIndexDistribution.this.log.logWarning("Index transfer to peer " + seed.getName() + ":" + seed.hash + " failed:'" + error + "', disconnecting peer");
+ yacyCore.peerActions.peerDeparture(seed);
+
+ // if the retry counter limit was not exceeded we'll retry it in a few seconds
+ this.status = "Disconnected peer: " + ((retryCount > 5)? error + ". Transfer aborted":"Retry " + retryCount);
+ if (retryCount > 5) return;
+ Thread.sleep(retryCount*5000);
+
+ /* loop until
+ * - we have successfully done a peer ping or
+ * - the retry counter limit was exceeded
+ */
+ while (true) {
+ // testing if we were aborted ...
+ if (isAborted()) return;
+
+ // doing a peer ping to the remote seed
+ int added = yacyClient.publishMySeed(seed.getAddress(), seed.hash);
+ if (added < 0) {
+ // inc. retry counter
+ retryCount++;
+ this.status = "Disconnected peer: Peer ping failed. " + ((retryCount > 5)?"Transfer aborted.":"Retry " + retryCount);
+ if (retryCount > 5) return;
+ Thread.sleep(retryCount*5000);
+ continue;
+ } else {
+ yacyCore.seedDB.getConnected(seed.hash);
+ this.status = "running";
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ }
+
public class transferIndexThread extends Thread {
private yacySeed seed = null;
private boolean delete = false;
private boolean finished = false;
+ private boolean gzipBody = false;
+ private int timeout = 60000;
private int transferedIndexCount = 0;
private String status = "Running";
private String oldStartingPointHash = "------------", startPointHash = "------------";
private int wordsDBSize = 0;
- private int chunkSize = 500;
+ private int chunkSize = 500;
+ private final long startingTime = System.currentTimeMillis();
+ private final plasmaSwitchboard sb;
+ private final Runtime rt = Runtime.getRuntime();
+ transferIndexWorkerThread worker = null;
public transferIndexThread(yacySeed seed, boolean delete) {
super(new ThreadGroup("TransferIndexThreadGroup"),"TransferIndex_" + seed.getName());
this.seed = seed;
this.delete = delete;
- this.wordsDBSize = plasmaSwitchboard.getSwitchboard().wordIndex.size();
+ this.sb = plasmaSwitchboard.getSwitchboard();
+ this.wordsDBSize = sb.wordIndex.size();
+ this.gzipBody = "true".equalsIgnoreCase(sb.getConfig("indexTransfer.gzipBody","false"));
+ this.timeout = (int) sb.getConfigLong("indexTransfer.timeout",60000);
}
public void run() {
@@ -484,7 +669,7 @@ public class plasmaWordIndexDistribution {
this.finished = true;
this.join();
}
-
+
public boolean isFinished() {
return this.finished;
}
@@ -493,8 +678,12 @@ public class plasmaWordIndexDistribution {
return this.delete;
}
- public int getChunkSize() {
- return this.chunkSize;
+ public int[] getChunkSize() {
+ transferIndexWorkerThread workerThread = this.worker;
+ if (workerThread != null) {
+ return new int[]{this.chunkSize,workerThread.getChunkSize()};
+ }
+ return new int[]{this.chunkSize,500};
}
public int getTransferedIndexCount() {
@@ -506,16 +695,28 @@ public class plasmaWordIndexDistribution {
else return (float)(this.transferedIndexCount*100/wordsDBSize);
}
+ public int getTransferedIndexSpeed() {
+ return (int) ((1000 * transferedIndexCount) / (System.currentTimeMillis()-startingTime));
+ }
+
public yacySeed getSeed() {
return this.seed;
}
- public String getStatus() {
- return this.status;
+ public String[] getStatus() {
+ transferIndexWorkerThread workerThread = this.worker;
+ if (workerThread != null) {
+ return new String[]{this.status,workerThread.getStatus()};
+ }
+ return new String[]{this.status,"Not running"};
}
- public String getRange() {
- return "[" + oldStartingPointHash + " .. " + startPointHash + "]";
+ public String[] getRange() {
+ transferIndexWorkerThread workerThread = this.worker;
+ if (workerThread != null) {
+ return new String[]{"[" + oldStartingPointHash + ".." + startPointHash + "]",workerThread.getRange()};
+ }
+ return new String[]{"[" + oldStartingPointHash + ".." + startPointHash + "]","[------------..------------]"};
}
public void performTransferWholeIndex() {
@@ -530,126 +731,100 @@ public class plasmaWordIndexDistribution {
* - detected a server shutdown or user interruption
* - detected a failure
*/
- long start, retryCount = 0, iteration = 0;
+ long selectionStart = System.currentTimeMillis(), selectionEnd = 0, selectionTime, iteration = 0;
+
+ plasmaWordIndexEntity[] newIndexEntities = null, oldIndexEntities = null;
while (!finished && !Thread.currentThread().isInterrupted()) {
iteration++;
int idxCount = 0;
- start = System.currentTimeMillis();
+ selectionStart = System.currentTimeMillis();
+ oldIndexEntities = newIndexEntities;
// selecting 500 words to transfer
- this.status = "Running: Selection of chunk " + iteration;
+ this.status = "Running: Selecting chunk " + iteration;
Object[] selectResult = selectTransferIndexes(startPointHash, chunkSize);
- plasmaWordIndexEntity[] indexEntities = (plasmaWordIndexEntity[]) selectResult[0];
+ newIndexEntities = (plasmaWordIndexEntity[]) selectResult[0];
HashMap urlCache = (HashMap) selectResult[1]; // String (url-hash) / plasmaCrawlLURL.Entry
- if ((indexEntities == null) || (indexEntities.length == 0)) {
+ if ((newIndexEntities == null) || (newIndexEntities.length == 0)) {
+ // if there are still words in the index we try it again now
+ if (sb.wordIndex.size() > 0) {
+ startPointHash = "------------";
+ continue;
+ }
+
plasmaWordIndexDistribution.this.log.logFine("No index available for index transfer, hash start-point " + startPointHash);
this.status = "Finished. " + iteration + " chunks transfered.";
- return;
+ return;
}
// count the indexes again, can be smaller as expected
- for (int i = 0; i < indexEntities.length; i++) idxCount += indexEntities[i].size();
+ for (int i = 0; i < newIndexEntities.length; i++) idxCount += newIndexEntities[i].size();
// getting start point for next DHT-selection
oldStartingPointHash = startPointHash;
- startPointHash = indexEntities[indexEntities.length - 1].wordHash(); // DHT targets must have greater hashes
+ startPointHash = newIndexEntities[newIndexEntities.length - 1].wordHash(); // DHT targets must have greater hashes
- plasmaWordIndexDistribution.this.log.logInfo("Index selection of " + idxCount + " words [" + indexEntities[0].wordHash() + " .. " + indexEntities[indexEntities.length-1].wordHash() + "]" +
+ selectionEnd = System.currentTimeMillis();
+ selectionTime = selectionEnd - selectionStart;
+ plasmaWordIndexDistribution.this.log.logInfo("Index selection of " + idxCount + " words [" + newIndexEntities[0].wordHash() + " .. " + newIndexEntities[newIndexEntities.length-1].wordHash() + "]" +
" in " +
- ((System.currentTimeMillis() - start) / 1000) + " seconds (" +
- (1000 * idxCount / (System.currentTimeMillis() - start + 1)) + " words/s)");
+ (selectionTime / 1000) + " seconds (" +
+ (1000 * idxCount / (selectionTime)) + " words/s)");
- /* loop until we
- * - have successfully transfered the words list or
- * - the retry counter limit was exceeded
- */
- start = System.currentTimeMillis();
- while (true) {
- // testing if we wer aborted
- if (isAborted()) return;
-
- // transfering seleted words to remote peer
- this.status = "Running: Transfer of chunk " + iteration;
- String error = yacyClient.transferIndex(seed, indexEntities, urlCache);
- if (error == null) {
- // words successfully transfered
- long transferTime = System.currentTimeMillis() - start;
- plasmaWordIndexDistribution.this.log.logInfo("Index transfer of " + idxCount + " words [" + indexEntities[0].wordHash() + " .. " + indexEntities[indexEntities.length-1].wordHash() + "]" +
- " to peer " + seed.getName() + ":" + seed.hash + " in " + (transferTime/1000) + " seconds successfull (" +
- (1000 * idxCount / (transferTime + 1)) + " words/s)");
- retryCount = 0;
-
- if (transferTime > 30000) {
- if (chunkSize>100) chunkSize-=50;
- } else {
- chunkSize+=50;
- }
-
- break;
+ // query status of old worker thread
+ if (worker != null) {
+ this.status = "Finished: Selecting chunk " + iteration;
+ worker.join();
+ if (!worker.success) {
+ this.status = "Aborted because of Transfer error:\n" + worker.getStatus();
+ return;
} else {
- // worts transfer failed
+ this.chunkSize = worker.getChunkSize();
+ long transferTime = worker.getTransferTime();
+ //TODO: only increase chunk Size if there is free memory left on the server
- // inc retry counter
- retryCount++;
+ // we need aprox. 73Byte per IndexEntity and an average URL length of 32 char
+ //if (ft.freeMemory() < 73*2*100)
- // testing if we were aborted ...
- if (isAborted()) return;
- // we have lost the connection to the remote peer. Adding peer to disconnected list
- plasmaWordIndexDistribution.this.log.logWarning("Index transfer to peer " + seed.getName() + ":" + seed.hash + " failed:'" + error + "', disconnecting peer");
- yacyCore.peerActions.peerDeparture(seed);
+ if (transferTime > 60*1000) {
+ if (chunkSize>200) chunkSize-=100;
+ } else if (selectionTime < transferTime){
+ this.chunkSize +=100;
+ //chunkSize+=50;
+ } else if (transferTime >= selectionTime){
+ if (chunkSize>200) chunkSize-=100;
+ }
- // if the retry counter limit was not exceeded we'll retry it in a few seconds
- this.status = "Disconnected peer: " + ((retryCount > 5)? error + ". Transfer aborted":"Retry " + retryCount);
- if (retryCount > 5) return;
- Thread.sleep(retryCount*5000);
+ selectionStart = System.currentTimeMillis();
- /* loop until
- * - we have successfully done a peer ping or
- * - the retry counter limit was exceeded
- */
- while (true) {
- // testing if we were aborted ...
- if (isAborted()) return;
-
- // doing a peer ping to the remote seed
- int added = yacyClient.publishMySeed(seed.getAddress(), seed.hash);
- if (added < 0) {
- // inc. retry counter
- retryCount++;
- this.status = "Disconnected peer: Peer ping failed. " + ((retryCount > 5)?"Transfer aborted.":"Retry " + retryCount);
- if (retryCount > 5) return;
- Thread.sleep(retryCount*5000);
- continue;
- } else {
- yacyCore.seedDB.getConnected(seed.hash);
- this.status = "running";
- break;
- }
- }
- }
- }
-
- // deleting transfered words from index
- if (delete) {
- this.status = "Running: Deletion of chunk " + iteration;
- try {
- if (deleteTransferIndexes(indexEntities)) {
- plasmaWordIndexDistribution.this.log.logFine("Deleted all " + indexEntities.length + " transferred whole-word indexes locally");
- transferedIndexCount += idxCount;
+ // deleting transfered words from index
+ if (delete) {
+ this.status = "Running: Deleting chunk " + iteration;
+ try {
+ if (deleteTransferIndexes(oldIndexEntities)) {
+ plasmaWordIndexDistribution.this.log.logFine("Deleted all " + oldIndexEntities.length + " transferred whole-word indexes locally");
+ transferedIndexCount += idxCount;
+ } else {
+ plasmaWordIndexDistribution.this.log.logSevere("Deleted not all transferred whole-word indexes");
+ }
+ } catch (IOException ee) {
+ plasmaWordIndexDistribution.this.log.logSevere("Deletion of indexes not possible:" + ee.getMessage(), ee);
+ }
} else {
- plasmaWordIndexDistribution.this.log.logSevere("Deleted not all transferred whole-word indexes");
- }
- } catch (IOException ee) {
- plasmaWordIndexDistribution.this.log.logSevere("Deletion of indexes not possible:" + ee.getMessage(), ee);
+ // simply close the indexEntities
+ for (int i = 0; i < oldIndexEntities.length; i++) try {
+ oldIndexEntities[i].close();
+ } catch (IOException ee) {}
+ transferedIndexCount += idxCount;
+ }
+
}
- } else {
- // simply close the indexEntities
- for (int i = 0; i < indexEntities.length; i++) try {
- indexEntities[i].close();
- } catch (IOException ee) {}
- transferedIndexCount += idxCount;
}
+
+ // handover chunk to transfer worker
+ worker = new transferIndexWorkerThread(seed,newIndexEntities,urlCache,gzipBody,timeout,iteration,idxCount,idxCount,startPointHash,oldStartingPointHash);
+ worker.start();
}
// if we reach this point we were aborted by the user or by server shutdown
@@ -657,7 +832,13 @@ public class plasmaWordIndexDistribution {
} catch (Exception e) {
this.status = "Error: " + e.getMessage();
plasmaWordIndexDistribution.this.log.logWarning("Index transfer to peer " + seed.getName() + ":" + seed.hash + " failed:'" + e.getMessage() + "'",e);
+
} finally {
+ if (worker != null) {
+ worker.stopIt();
+ try {worker.join();}catch(Exception e){}
+ // worker = null;
+ }
plasmaWordIndexDistribution.this.paused = false;
}
}
diff --git a/source/de/anomic/plasma/plasmaWordIndexEntity.java b/source/de/anomic/plasma/plasmaWordIndexEntity.java
index aa15978e5..b92b34d9b 100644
--- a/source/de/anomic/plasma/plasmaWordIndexEntity.java
+++ b/source/de/anomic/plasma/plasmaWordIndexEntity.java
@@ -51,9 +51,9 @@ import de.anomic.kelondro.kelondroRecords;
import de.anomic.kelondro.kelondroTree;
import de.anomic.kelondro.kelondroException;
-public class plasmaWordIndexEntity {
+public final class plasmaWordIndexEntity {
- private String theWordHash;
+ private final String theWordHash;
private kelondroTree theIndex;
private TreeMap theTmpMap;
private File theLocation;
@@ -235,7 +235,7 @@ public class plasmaWordIndexEntity {
if (theTmpMap == null) return new dbenum(up); else return new tmpenum(up);
}
- public class dbenum implements Enumeration {
+ public final class dbenum implements Enumeration {
Iterator i;
public dbenum(boolean up) {
try {
@@ -263,8 +263,8 @@ public class plasmaWordIndexEntity {
}
}
}
- public class tmpenum implements Enumeration {
- TreeMap searchTree;
+ public final class tmpenum implements Enumeration {
+ final TreeMap searchTree;
boolean up;
public tmpenum(boolean up) {
this.up = up;
diff --git a/source/de/anomic/plasma/plasmaWordIndexEntry.java b/source/de/anomic/plasma/plasmaWordIndexEntry.java
index a774f8b18..4153b7759 100644
--- a/source/de/anomic/plasma/plasmaWordIndexEntry.java
+++ b/source/de/anomic/plasma/plasmaWordIndexEntry.java
@@ -53,7 +53,7 @@ import de.anomic.server.serverCodings;
import de.anomic.yacy.yacySeedDB;
// import de.anomic.server.logging.serverLog;
-public class plasmaWordIndexEntry {
+public final class plasmaWordIndexEntry {
// an wordEntry can be filled in either of two ways:
// by the discrete values of the entry
@@ -68,7 +68,7 @@ public class plasmaWordIndexEntry {
public static final int attrSpaceLong = 18;
// the associated hash
- private String urlHash;
+ private final String urlHash;
// discrete values
private int count; // words in file
@@ -245,37 +245,57 @@ public class plasmaWordIndexEntry {
public String toEncodedForm(boolean longAttr) {
// attention: this integrates NOT the URL into the encoding
// if you need a complete dump, use toExternalForm()
- String shortAttr =
- b64save(quality, plasmaCrawlLURL.urlQualityLength) +
- b64save(age, 3) +
- b64save(count, 2) +
- new String(language) +
- doctype +
- localflag; // 3 + 3 + 2 + 2 + 1 + 1 = 12 bytes
+ StringBuffer buf = new StringBuffer(longAttr?18:12);
+
+ buf.append(b64save(this.quality, plasmaURL.urlQualityLength))
+ .append(b64save(this.age, 3))
+ .append(b64save(this.count, 2))
+ .append(new String(this.language))
+ .append(this.doctype)
+ .append(this.localflag); // 3 + 3 + 2 + 2 + 1 + 1 = 12 bytes
+
if (longAttr)
- return
- shortAttr +
- b64save(posintext, 2) +
- b64save(posinphrase, 2) +
- b64save(posofphrase, 2);
- // 12 + 3 + 2 + 2 + 1 + 1 = 12 bytes
- else
- return shortAttr;
+ buf.append(b64save(this.posintext, 2))
+ .append(b64save(this.posinphrase, 2))
+ .append(b64save(this.posofphrase, 2));
+
+ return buf.toString();
+
+// String shortAttr =
+// b64save(quality, plasmaCrawlLURL.urlQualityLength) +
+// b64save(age, 3) +
+// b64save(count, 2) +
+// new String(language) +
+// doctype +
+// localflag; // 3 + 3 + 2 + 2 + 1 + 1 = 12 bytes
+// if (longAttr)
+// return
+// shortAttr +
+// b64save(posintext, 2) +
+// b64save(posinphrase, 2) +
+// b64save(posofphrase, 2);
+// // 12 + 3 + 2 + 2 + 1 + 1 = 12 bytes
+// else
+// return shortAttr;
}
public String toExternalForm() {
- return "{" +
- "h=" + urlHash +
- ",q=" + b64save(quality, plasmaCrawlLURL.urlQualityLength) +
- ",a=" + b64save(age, 3) +
- ",c=" + b64save(count, 2) +
- ",l=" + new String(language) +
- ",d=" + doctype +
- ",f=" + localflag +
- ",t=" + b64save(posintext, 2) +
- ",r=" + b64save(posinphrase, 2) +
- ",o=" + b64save(posofphrase, 2) +
- "}";
+ StringBuffer str = new StringBuffer(61);
+
+ str.append("{")
+ .append("h=").append(this.urlHash)
+ .append(",q=").append(b64save(this.quality, plasmaURL.urlQualityLength))
+ .append(",a=").append(b64save(this.age, 3))
+ .append(",c=").append(b64save(this.count, 2))
+ .append(",l=").append(new String(this.language))
+ .append(",d=").append(this.doctype)
+ .append(",f=").append(this.localflag)
+ .append(",t=").append(b64save(this.posintext, 2))
+ .append(",r=").append(b64save(this.posinphrase, 2))
+ .append(",o=").append(b64save(this.posofphrase, 2))
+ .append("}");
+
+ return str.toString();
}
public String getUrlHash() {
diff --git a/source/de/anomic/server/serverAbstractSwitch.java b/source/de/anomic/server/serverAbstractSwitch.java
index 7b7c6d477..0b243b429 100644
--- a/source/de/anomic/server/serverAbstractSwitch.java
+++ b/source/de/anomic/server/serverAbstractSwitch.java
@@ -40,19 +40,12 @@
package de.anomic.server;
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
import java.io.IOException;
-import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.HashMap;
-import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
-import java.util.Properties;
import java.util.TreeMap;
import de.anomic.server.logging.serverLog;
diff --git a/source/de/anomic/server/serverCodings.java b/source/de/anomic/server/serverCodings.java
index fdd26c846..8dcf48f43 100644
--- a/source/de/anomic/server/serverCodings.java
+++ b/source/de/anomic/server/serverCodings.java
@@ -79,18 +79,18 @@ public final class serverCodings {
}
public String encodeBase64Long(long c, int length) {
- if (length < 0) length = 0;
- String s = "";
- if (c == 0) s = alpha[0] + s;
+ if (length < 0) length = 0;
+ StringBuffer s = new StringBuffer(length); //String s = "";
+ if (c == 0) s.insert(0,alpha[0]); //s = alpha[0] + s;
else while (c > 0) {
- s = alpha[(byte) (c & 0x3F)] + s;
+ s.insert(0,alpha[(byte) (c & 0x3F)]); //s = alpha[(byte) (c & 0x3F)] + s;
c >>= 6;
}
if ((length != 0) && (s.length() > length))
throw new RuntimeException("encodeBase64 result '" + s + "' exceeds demanded length of " + length + " digits");
if (length == 0) length = 1; // rare exception for the case that c == 0
- while (s.length() < length) s = alpha[0] + s;
- return s;
+ while (s.length() < length) s.insert(0,alpha[0]); //s = alpha[0] + s;
+ return s.toString();
}
public long decodeBase64Long(String s) {
diff --git a/source/de/anomic/server/serverCore.java b/source/de/anomic/server/serverCore.java
index 4a44a42d4..d8118246e 100644
--- a/source/de/anomic/server/serverCore.java
+++ b/source/de/anomic/server/serverCore.java
@@ -57,15 +57,8 @@ import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
-import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
import java.security.KeyStore;
-import java.util.HashMap;
-import java.util.HashSet;
import java.util.Hashtable;
import javax.net.ServerSocketFactory;
@@ -77,7 +70,6 @@ import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool.Config;
import de.anomic.http.httpc;
-import de.anomic.http.httpd;
import de.anomic.icap.icapd;
import de.anomic.server.logging.serverLog;
import de.anomic.yacy.yacyCore;
@@ -106,15 +98,12 @@ public final class serverCore extends serverAbstractThread implements serverThre
serverLog log; // log object
private int timeout; // connection time-out of the socket
- private int thresholdActive = 5000; // after that time a thread should have got a command line
private int thresholdSleep = 30000; // after that time a thread is considered as beeing sleeping (30 seconds)
- private int thresholdDead = 3600000; // after that time a thread is considered as beeing dead-locked (1 hour)
serverHandler handlerPrototype; // the command class (a serverHandler)
- private Class[] initHandlerClasses; // the init's methods arguments
- private Class[] initSessionClasses; // the init's methods arguments
+
private serverSwitch switchboard; // the command class switchboard
- private Hashtable denyHost;
- private int commandMaxLength;
+ Hashtable denyHost;
+ int commandMaxLength;
/**
* The session-object pool
@@ -122,7 +111,6 @@ public final class serverCore extends serverAbstractThread implements serverThre
final SessionPool theSessionPool;
final ThreadGroup theSessionThreadGroup = new ThreadGroup("sessionThreadGroup");
private Config cralwerPoolConfig = null;
- private Selector channelSel;
private static ServerSocketFactory getServerSocketFactory(boolean dflt, File keyfile, String passphrase) {
// see doc's at
@@ -181,9 +169,13 @@ public final class serverCore extends serverAbstractThread implements serverThre
int commandMaxLength
) throws IOException {
this.port = port;
+ this.timeout = timeout;
+
this.commandMaxLength = commandMaxLength;
this.denyHost = (blockAttack) ? new Hashtable() : null;
-
+ this.handlerPrototype = handlerPrototype;
+ this.switchboard = switchboard;
+
// initialize logger
this.log = new serverLog("SERVER");
@@ -208,15 +200,7 @@ public final class serverCore extends serverAbstractThread implements serverThre
System.out.println("FATAL ERROR: " + e.getMessage() + " - probably root access rights needed. check port number"); System.exit(0);
}
- try {
- this.handlerPrototype = handlerPrototype;
- this.switchboard = switchboard;
- this.initHandlerClasses = new Class[] {Class.forName("de.anomic.server.serverSwitch")};
- this.initSessionClasses = new Class[] {Class.forName("de.anomic.server.serverCore$Session")};
- this.timeout = timeout;
- } catch (java.lang.ClassNotFoundException e) {
- System.out.println("FATAL ERROR: " + e.getMessage() + " - Class Not Found"); System.exit(0);
- }
+
// init port forwarding
try {
@@ -303,7 +287,7 @@ public final class serverCore extends serverAbstractThread implements serverThre
return isNotLocal(url.getHost());
}
- private static boolean isNotLocal(String ip) {
+ static boolean isNotLocal(String ip) {
if ((ip.equals("localhost")) ||
(ip.startsWith("127")) ||
(ip.startsWith("192.168")) ||
@@ -315,7 +299,7 @@ public final class serverCore extends serverAbstractThread implements serverThre
public static String publicIP() {
try {
- // If port forwarding was enabled we need to return the remote IP Address
+ // if a static IP was configured, we have to return it here ...
plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();
if(sb != null){
String staticIP=sb.getConfig("staticIP", "");
@@ -323,12 +307,16 @@ public final class serverCore extends serverAbstractThread implements serverThre
return staticIP;
}
}
+
+ // If port forwarding was enabled we need to return the remote IP Address
if ((serverCore.portForwardingEnabled)&&(serverCore.portForwarding != null)) {
//does not return serverCore.portForwarding.getHost(), because hostnames are not valid, except in DebugMode
return InetAddress.getByName(serverCore.portForwarding.getHost()).getHostAddress();
- } else {
- return publicLocalIP().getHostAddress();
}
+
+ // otherwise we return the real IP address of this host
+ return publicLocalIP().getHostAddress();
+
} catch (java.net.UnknownHostException e) {
System.err.println("ERROR: (internal) " + e.getMessage());
return null;
@@ -395,7 +383,7 @@ public final class serverCore extends serverAbstractThread implements serverThre
// idleThreadCheck();
this.switchboard.handleBusyState(this.theSessionPool.getNumActive() /*activeThreads.size() */);
- log.logFine(
+ this.log.logFinest(
"* waiting for connections, " + this.theSessionPool.getNumActive() + " sessions running, " +
this.theSessionPool.getNumIdle() + " sleeping");
@@ -410,21 +398,25 @@ public final class serverCore extends serverAbstractThread implements serverThre
Integer attempts = (Integer) bfHost.get(cIP);
if (attempts == null) attempts = new Integer(1); else attempts = new Integer(attempts.intValue() + 1);
bfHost.put(cIP, attempts);
- this.log.logInfo("SLOWING DOWN ACCESS FOR BRUTE-FORCE PREVENTION FROM " + cIP + ", ATTEMPT " + attempts.intValue());
+ this.log.logWarning("SLOWING DOWN ACCESS FOR BRUTE-FORCE PREVENTION FROM " + cIP + ", ATTEMPT " + attempts.intValue());
// add a delay to make brute-force harder
announceThreadBlockApply();
try {Thread.sleep(attempts.intValue() * 2000);} catch (InterruptedException e) {}
announceThreadBlockRelease();
- if ((attempts.intValue() >= 10) && (denyHost != null)) {
- denyHost.put(cIP, "deny");
+ if ((attempts.intValue() >= 10) && (this.denyHost != null)) {
+ this.denyHost.put(cIP, "deny");
}
}
if ((this.denyHost == null) || (this.denyHost.get(cIP) == null)) {
+ // setting the timeout properly
controlSocket.setSoTimeout(this.timeout);
+
+ // getting a free session thread from the pool
Session connection = (Session) this.theSessionPool.borrowObject();
+
+ // processing the new request
connection.execute(controlSocket,this.timeout);
- //log.logDebug("* NEW SESSION: " + connection.request + " from " + clientIP);
} else {
this.log.logWarning("ACCESS FROM " + cIP + " DENIED");
}
@@ -477,8 +469,7 @@ public final class serverCore extends serverAbstractThread implements serverThre
return (this.theSessionPool.getNumActive() == 0);
}
- public final class SessionPool extends GenericObjectPool
- {
+ public final class SessionPool extends GenericObjectPool {
public boolean isClosed = false;
/**
@@ -630,12 +621,9 @@ public final class serverCore extends serverAbstractThread implements serverThre
*/
public void passivateObject(Object obj) {
//log.debug(" passivateObject..." + obj);
- if (obj instanceof Session) {
- Session theSession = (Session) obj;
-
- // Clean up the result of the execution
- theSession.setResult(null);
- }
+// if (obj instanceof Session) {
+// Session theSession = (Session) obj;
+// }
}
}
@@ -647,8 +635,6 @@ public final class serverCore extends serverAbstractThread implements serverThre
// synchronization object needed for the threadpool implementation
private Object syncObject;
- private Object processingResult = null;
-
private boolean running = false;
private boolean stopped = false;
private boolean done = false;
@@ -720,7 +706,7 @@ public final class serverCore extends serverAbstractThread implements serverThre
}
public long getTime() {
- return System.currentTimeMillis() - start;
+ return System.currentTimeMillis() - this.start;
}
public void setIdentity(String id) {
@@ -734,7 +720,7 @@ public final class serverCore extends serverAbstractThread implements serverThre
*/
public void log(boolean outgoing, String request) {
- serverCore.this.log.logFine(userAddress.getHostAddress() + "/" + this.identity + " " +
+ serverCore.this.log.logFine(this.userAddress.getHostAddress() + "/" + this.identity + " " +
"[" + ((serverCore.this.theSessionPool.isClosed)? -1 : serverCore.this.theSessionPool.getNumActive()) + ", " + this.commandCounter +
((outgoing) ? "] > " : "] < ") +
request);
@@ -746,7 +732,7 @@ public final class serverCore extends serverAbstractThread implements serverThre
}
public byte[] readLine() {
- return receive(in, this.readLineBuffer, commandMaxLength, false);
+ return receive(this.in, this.readLineBuffer, serverCore.this.commandMaxLength, false);
}
/**
@@ -766,13 +752,6 @@ public final class serverCore extends serverAbstractThread implements serverThre
return this.running;
}
- /**
- * @param object
- */
- public void setResult(Object object) {
- this.processingResult = object;
- }
-
/**
*
*/
@@ -780,6 +759,7 @@ public final class serverCore extends serverAbstractThread implements serverThre
this.done = true;
this.syncObject = null;
this.readLineBuffer.reset();
+ this.commandObj.reset();
}
/**
@@ -893,7 +873,9 @@ public final class serverCore extends serverAbstractThread implements serverThre
String reqProtocol = "HTTP";
Object[] stringParameter = new String[1];
while ((this.in != null) && ((requestBytes = readLine()) != null)) {
- this.setName("Session_" + this.userAddress.getHostAddress() + ":" + this.controlSocket.getPort() + "#" + commandCounter);
+ this.setName("Session_" + this.userAddress.getHostAddress() +
+ ":" + this.controlSocket.getPort() +
+ "#" + this.commandCounter);
this.request = new String(requestBytes);
//log.logDebug("* session " + handle + " received command '" + request + "'. time = " + (System.currentTimeMillis() - handle));
@@ -936,6 +918,8 @@ public final class serverCore extends serverAbstractThread implements serverThre
// initializing the session
this.commandObj.initSession(this);
}
+
+ // count the amount of requests that were processed by this session until yet
this.commandCounter++;
// setting the socket timeout for reading of the request content
@@ -972,7 +956,7 @@ public final class serverCore extends serverAbstractThread implements serverThre
}
writeLine((String) result);
} else if (result instanceof InputStream) {
- String tmp = send(out, (InputStream) result);
+ String tmp = send(this.out, (InputStream) result);
if ((tmp.length() > 4) && (tmp.toUpperCase().startsWith("PASS"))) {
log(true, "PASS ********");
} else {
@@ -982,32 +966,33 @@ public final class serverCore extends serverAbstractThread implements serverThre
}
if (terminate) break;
- } catch (InvocationTargetException ite) {
- System.out.println("ERROR A " + userAddress.getHostAddress());
+ } catch (InvocationTargetException ite) {
+ System.out.println("ERROR A " + this.userAddress.getHostAddress());
// we extract a target exception and let the thread survive
- writeLine((String) commandObj.error(ite.getTargetException()));
+ writeLine(this.commandObj.error(ite.getTargetException()));
} catch (NoSuchMethodException nsme) {
- System.out.println("ERROR B " + userAddress.getHostAddress());
- if (isNotLocal(userAddress.getHostAddress().toString())) {
- if (denyHost != null)
- denyHost.put((""+userAddress.getHostAddress()), "deny"); // block client: hacker attempt
+ System.out.println("ERROR B " + this.userAddress.getHostAddress());
+ if (isNotLocal(this.userAddress.getHostAddress().toString())) {
+ if (serverCore.this.denyHost != null) {
+ serverCore.this.denyHost.put((""+this.userAddress.getHostAddress()), "deny"); // block client: hacker attempt
+ }
}
break;
// the client requested a command that does not exist
//Object[] errorParameter = { nsme };
//writeLine((String) error.invoke(this.cmdObject, errorParameter));
} catch (IllegalAccessException iae) {
- System.out.println("ERROR C " + userAddress.getHostAddress());
+ System.out.println("ERROR C " + this.userAddress.getHostAddress());
// wrong parameters: this an only be an internal problem
- writeLine((String) commandObj.error(iae));
+ writeLine(this.commandObj.error(iae));
} catch (java.lang.ClassCastException e) {
- System.out.println("ERROR D " + userAddress.getHostAddress());
+ System.out.println("ERROR D " + this.userAddress.getHostAddress());
// ??
- writeLine((String) commandObj.error(e));
+ writeLine(this.commandObj.error(e));
} catch (Exception e) {
- System.out.println("ERROR E " + userAddress.getHostAddress());
+ System.out.println("ERROR E " + this.userAddress.getHostAddress());
// whatever happens: the thread has to survive!
- writeLine("UNKNOWN REASON:" + (String) commandObj.error(e));
+ writeLine("UNKNOWN REASON:" + this.commandObj.error(e));
}
} // end of while
} catch (java.lang.ClassNotFoundException e) {
diff --git a/source/de/anomic/server/serverObjects.java b/source/de/anomic/server/serverObjects.java
index 3b7ef9a74..9584ac118 100644
--- a/source/de/anomic/server/serverObjects.java
+++ b/source/de/anomic/server/serverObjects.java
@@ -61,10 +61,10 @@ import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
-import java.util.Vector;
public final class serverObjects extends Hashtable implements Cloneable {
@@ -137,7 +137,7 @@ public final class serverObjects extends Hashtable implements Cloneable {
public String[] getAll(String keyMapper) {
// the keyMapper may contain regular expressions as defined in String.matches
// this method is particulary useful when parsing the result of checkbox forms
- Vector v = new Vector();
+ ArrayList v = new ArrayList();
Enumeration e = keys();
String key;
while (e.hasMoreElements()) {
@@ -146,7 +146,7 @@ public final class serverObjects extends Hashtable implements Cloneable {
}
// make a String[]
String[] result = new String[v.size()];
- for (int i = 0; i < v.size(); i++) result[i] = (String) v.elementAt(i);
+ for (int i = 0; i < v.size(); i++) result[i] = (String) v.get(i);
return result;
}
diff --git a/source/de/anomic/tools/loaderCore.java b/source/de/anomic/tools/loaderCore.java
index 514cf44e8..c0ea0c7aa 100644
--- a/source/de/anomic/tools/loaderCore.java
+++ b/source/de/anomic/tools/loaderCore.java
@@ -41,8 +41,8 @@
package de.anomic.tools;
+import java.util.ArrayList;
import java.util.Properties;
-import java.util.Vector;
public abstract class loaderCore implements loaderProcess {
@@ -63,7 +63,7 @@ public abstract class loaderCore implements loaderProcess {
protected int completion = 0;
// steering methods
- public abstract void feed(Vector v); // returns true if process was successful; should be always synchronized
+ public abstract void feed(ArrayList v); // returns true if process was successful; should be always synchronized
public void terminate() {
// if terminated before completion, completed() shows x < 100
diff --git a/source/de/anomic/tools/loaderProcess.java b/source/de/anomic/tools/loaderProcess.java
index b4cfa09aa..531724f5f 100644
--- a/source/de/anomic/tools/loaderProcess.java
+++ b/source/de/anomic/tools/loaderProcess.java
@@ -41,13 +41,13 @@
package de.anomic.tools;
+import java.util.ArrayList;
import java.util.Properties;
-import java.util.Vector;
public interface loaderProcess {
// steering methods
- public void feed(Vector v); // returns true if process was successful; should be always synchronized
+ public void feed(ArrayList v); // returns true if process was successful; should be always synchronized
public void terminate(); // if terminated before completion, completed() shows x < 100
// feed-back methods
diff --git a/source/de/anomic/tools/loaderThreads.java b/source/de/anomic/tools/loaderThreads.java
index b4c901af1..e13fb8d94 100644
--- a/source/de/anomic/tools/loaderThreads.java
+++ b/source/de/anomic/tools/loaderThreads.java
@@ -42,8 +42,8 @@ package de.anomic.tools;
import java.net.MalformedURLException;
import java.net.URL;
+import java.util.ArrayList;
import java.util.Hashtable;
-import java.util.Vector;
import de.anomic.http.httpc;
@@ -131,7 +131,7 @@ public class loaderThreads {
private Exception error;
private long starttime;
private loaderProcess process;
- private Vector page;
+ private ArrayList page;
private boolean loaded;
public loaderThread(URL url, loaderProcess process) {
@@ -192,7 +192,7 @@ public class loaderThreads {
this.status = STATUS_READY;
}
- public synchronized void feed(Vector v) {
+ public synchronized void feed(ArrayList v) {
this.status = STATUS_RUNNING;
this.completion = 1;
int line = 0;
@@ -201,7 +201,7 @@ public class loaderThreads {
try {
while ((this.run) && (line < v.size())) {
// parse line and construct a property
- s = (String) v.elementAt(line);
+ s = (String) v.get(line);
if ((s != null) && ((p = s.indexOf('=')) > 0)) {
key = s.substring(0, p).trim();
value = s.substring(p + 1).trim();
diff --git a/source/de/anomic/tools/nxTools.java b/source/de/anomic/tools/nxTools.java
index 71f7f2cd9..283827d83 100644
--- a/source/de/anomic/tools/nxTools.java
+++ b/source/de/anomic/tools/nxTools.java
@@ -40,8 +40,10 @@
package de.anomic.tools;
+import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.Vector;
public class nxTools {
@@ -51,7 +53,7 @@ public class nxTools {
Enumeration i = list.elements();
int pos;
String line;
- HashMap props = new HashMap();
+ HashMap props = new HashMap(list.size());
while (i.hasMoreElements()) {
line = ((String) i.nextElement()).trim();
//System.out.println("NXTOOLS_PROPS - LINE:" + line);
@@ -60,6 +62,20 @@ public class nxTools {
}
return props;
}
+
+ public static HashMap table(ArrayList list) {
+ Iterator i = list.iterator();
+ int pos;
+ String line;
+ HashMap props = new HashMap(list.size());
+ while (i.hasNext()) {
+ line = ((String) i.next()).trim();
+ //System.out.println("NXTOOLS_PROPS - LINE:" + line);
+ pos = line.indexOf("=");
+ if (pos > 0) props.put(line.substring(0, pos).trim(), line.substring(pos + 1).trim());
+ }
+ return props;
+ }
public static Vector grep(Vector list, int afterContext, String pattern) {
Enumeration i = list.elements();
@@ -78,11 +94,34 @@ public class nxTools {
}
return result;
}
+
+ public static ArrayList grep(ArrayList list, int afterContext, String pattern) {
+ Iterator i = list.iterator();
+ int ac = 0;
+ String line;
+ ArrayList result = new ArrayList();
+ while (i.hasNext()) {
+ line = (String) i.next();
+ if (line.indexOf(pattern) >= 0) {
+ result.add(line);
+ ac = afterContext + 1;
+ } else if (ac > 0) {
+ result.add(line);
+ }
+ ac--;
+ }
+ return result;
+ }
public static String tail1(Vector list) {
if ((list == null) || (list.size() == 0)) return "";
return (String) list.lastElement();
}
+
+ public static String tail1(ArrayList list) {
+ if ((list == null) || (list.size() == 0)) return "";
+ return (String) list.get(list.size()-1);
+ }
public static String awk(String sentence, String separator, int count) {
// returns the nth word of sentence, where count is the counter and the first word has the number 1
diff --git a/source/de/anomic/yacy/yacyClient.java b/source/de/anomic/yacy/yacyClient.java
index a6fae0560..ad51525bf 100644
--- a/source/de/anomic/yacy/yacyClient.java
+++ b/source/de/anomic/yacy/yacyClient.java
@@ -45,10 +45,10 @@ package de.anomic.yacy;
import java.io.IOException;
import java.net.URL;
+import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
-import java.util.Vector;
import de.anomic.http.httpc;
import de.anomic.plasma.plasmaCrawlLURL;
import de.anomic.plasma.plasmaSearch;
@@ -65,7 +65,7 @@ import de.anomic.tools.nxTools;
import de.anomic.yacy.yacySeed;
import de.anomic.yacy.yacyVersion;
-public class yacyClient {
+public final class yacyClient {
public static int publishMySeed(String address, String otherHash) {
// this is called to enrich the seed information by
@@ -100,7 +100,7 @@ public class yacyClient {
*/
final URL url = new URL("http://" + address + "/yacy/hello.html");
- final serverObjects obj = new serverObjects();
+ final serverObjects obj = new serverObjects(6);
obj.put("iam", yacyCore.seedDB.mySeed.hash);
obj.put("pattern", "");
obj.put("count", "20");
@@ -302,7 +302,7 @@ public class yacyClient {
"&count=" + count + "&resource=" + ((global) ? "global" : "local") +
"&query=" + wordhashes;
*/
- final serverObjects obj = new serverObjects();
+ final serverObjects obj = new serverObjects(9);
obj.put("myseed", yacyCore.seedDB.mySeed.genSeedStr(key));
obj.put("youare", targetPeer.hash);
obj.put("key", key);
@@ -396,7 +396,7 @@ public class yacyClient {
// ask for allowed message size and attachement size
// if this replies null, the peer does not answer
if (yacyCore.seedDB == null || yacyCore.seedDB.mySeed == null) { return null; }
- final serverObjects post = new serverObjects();
+ final serverObjects post = new serverObjects(5);
final String key = crypt.randomSalt();
post.put("key", key);
post.put("process", "permission");
@@ -427,7 +427,7 @@ public class yacyClient {
public static HashMap postMessage(String targetHash, String subject, byte[] message) {
// this post a message to the remote message board
- final serverObjects post = new serverObjects();
+ final serverObjects post = new serverObjects(7);
final String key = crypt.randomSalt();
post.put("key", key);
post.put("process", "post");
@@ -445,7 +445,7 @@ public class yacyClient {
if (address == null) { address = "localhost:8080"; }
//System.out.println("DEBUG POST " + address + "/yacy/message.html" + post.toString());
try {
- final Vector v = httpc.wput(new URL("http://" + address + "/yacy/message.html"), 20000, null, null,
+ final ArrayList v = httpc.wput(new URL("http://" + address + "/yacy/message.html"), 20000, null, null,
yacyCore.seedDB.sb.remoteProxyHost, yacyCore.seedDB.sb.remoteProxyPort, post);
//System.out.println("V=" + v.toString());
return nxTools.table(v);
@@ -462,7 +462,7 @@ public class yacyClient {
if (yacyCore.seedDB.mySeed == targetSeed) { return null; }
// construct request
- final serverObjects post = new serverObjects();
+ final serverObjects post = new serverObjects(9);
final String key = crypt.randomSalt();
post.put("key", key);
post.put("process", "crawl");
@@ -550,8 +550,8 @@ public class yacyClient {
httpHeader requestHeader) throws IOException {
*/
- public static String transferIndex(yacySeed targetSeed, plasmaWordIndexEntity[] indexes, HashMap urlCache) {
- HashMap in = transferRWI(targetSeed, indexes);
+ public static String transferIndex(yacySeed targetSeed, plasmaWordIndexEntity[] indexes, HashMap urlCache, boolean gzipBody, int timeout) {
+ HashMap in = transferRWI(targetSeed, indexes, gzipBody, timeout);
if (in == null) { return "no_connection_1"; }
String result = (String) in.get("result");
if (result == null) { return "no_result_1"; }
@@ -569,7 +569,7 @@ public class yacyClient {
urls[i] = (plasmaCrawlLURL.Entry) urlCache.get(uhs[i]);
if (urls[i] == null) System.out.println("DEBUG transferIndex: error with requested url hash '" + uhs[i] + "', unknownURL='" + uhss + "'");
}
- in = transferURL(targetSeed, urls);
+ in = transferURL(targetSeed, urls, gzipBody, timeout);
if (in == null) { return "no_connection_2"; }
result = (String) in.get("result");
if (result == null) { return "no_result_2"; }
@@ -579,15 +579,15 @@ public class yacyClient {
return null;
}
- private static HashMap transferRWI(yacySeed targetSeed, plasmaWordIndexEntity[] indexes) {
+ private static HashMap transferRWI(yacySeed targetSeed, plasmaWordIndexEntity[] indexes, boolean gzipBody, int timeout) {
final String address = targetSeed.getAddress();
if (address == null) { return null; }
// prepare post values
- final serverObjects post = new serverObjects();
+ final serverObjects post = new serverObjects(7);
final String key = crypt.randomSalt();
// enabling gzip compression for post request body
- if (targetSeed.getVersion() >= yacyVersion.YACY_SUPPORTS_GZIP_POST_REQUESTS) {
+ if ((gzipBody) && (targetSeed.getVersion() >= yacyVersion.YACY_SUPPORTS_GZIP_POST_REQUESTS)) {
post.put(httpc.GZIP_POST_BODY,"true");
}
post.put("key", key);
@@ -611,7 +611,7 @@ public class yacyClient {
if (indexcount == 0) {
// nothing to do but everything ok
- final HashMap result = new HashMap();
+ final HashMap result = new HashMap(2);
result.put("result", "ok");
result.put("unknownURL", "");
return result;
@@ -620,7 +620,7 @@ public class yacyClient {
post.put("entryc", Integer.toString(indexcount));
post.put("indexes", entrypost.toString());
try {
- final Vector v = httpc.wput(new URL("http://" + address + "/yacy/transferRWI.html"), 60000, null, null,
+ final ArrayList v = httpc.wput(new URL("http://" + address + "/yacy/transferRWI.html"), timeout, null, null,
yacyCore.seedDB.sb.remoteProxyHost, yacyCore.seedDB.sb.remoteProxyPort, post);
// this should return a list of urlhashes that are unknwon
if (v != null) {
@@ -635,16 +635,16 @@ public class yacyClient {
}
}
- private static HashMap transferURL(yacySeed targetSeed, plasmaCrawlLURL.Entry[] urls) {
+ private static HashMap transferURL(yacySeed targetSeed, plasmaCrawlLURL.Entry[] urls, boolean gzipBody, int timeout) {
// this post a message to the remote message board
final String address = targetSeed.getAddress();
if (address == null) { return null; }
// prepare post values
- final serverObjects post = new serverObjects();
+ final serverObjects post = new serverObjects(5+urls.length);
final String key = crypt.randomSalt();
// enabling gzip compression for post request body
- if (targetSeed.getVersion() >= yacyVersion.YACY_SUPPORTS_GZIP_POST_REQUESTS) {
+ if ((gzipBody) && (targetSeed.getVersion() >= yacyVersion.YACY_SUPPORTS_GZIP_POST_REQUESTS)) {
post.put(httpc.GZIP_POST_BODY,"true");
}
@@ -664,7 +664,7 @@ public class yacyClient {
}
post.put("urlc", Integer.toString(urlc));
try {
- final Vector v = httpc.wput(new URL("http://" + address + "/yacy/transferURL.html"), 60000, null, null,
+ final ArrayList v = httpc.wput(new URL("http://" + address + "/yacy/transferURL.html"), timeout, null, null,
yacyCore.seedDB.sb.remoteProxyHost, yacyCore.seedDB.sb.remoteProxyPort, post);
if (v != null) {
yacyCore.seedDB.mySeed.incSU(urlc);
@@ -678,13 +678,13 @@ public class yacyClient {
public static HashMap getProfile(yacySeed targetSeed) {
// this post a message to the remote message board
- final serverObjects post = new serverObjects();
+ final serverObjects post = new serverObjects(2);
post.put("iam", yacyCore.seedDB.mySeed.hash);
post.put("youare", targetSeed.hash);
String address = targetSeed.getAddress();
if (address == null) { address = "localhost:8080"; }
try {
- final Vector v = httpc.wput(new URL("http://" + address + "/yacy/profile.html"), 20000, null, null,
+ final ArrayList v = httpc.wput(new URL("http://" + address + "/yacy/profile.html"), 20000, null, null,
yacyCore.seedDB.sb.remoteProxyHost, yacyCore.seedDB.sb.remoteProxyPort, post);
return nxTools.table(v);
} catch (Exception e) {
diff --git a/source/de/anomic/yacy/yacyCore.java b/source/de/anomic/yacy/yacyCore.java
index 614911ee3..0766620be 100644
--- a/source/de/anomic/yacy/yacyCore.java
+++ b/source/de/anomic/yacy/yacyCore.java
@@ -63,8 +63,7 @@ import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.Hashtable;
+import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.TimeZone;
@@ -84,7 +83,7 @@ public class yacyCore {
public static long startupTime = System.currentTimeMillis();
public static yacySeedDB seedDB = null;
public static yacyNewsPool newsPool = null;
- public static final Hashtable seedUploadMethods = new Hashtable();
+ public static final HashMap seedUploadMethods = new HashMap();
public static yacyPeerActions peerActions = null;
public static yacyDHTAction dhtAgent = null;
public static serverLog log;
@@ -538,9 +537,9 @@ public class yacyCore {
}
}
- public static Hashtable getSeedUploadMethods() {
+ public static HashMap getSeedUploadMethods() {
synchronized (yacyCore.seedUploadMethods) {
- return (Hashtable) yacyCore.seedUploadMethods.clone();
+ return (HashMap) yacyCore.seedUploadMethods.clone();
}
}
@@ -563,7 +562,7 @@ public class yacyCore {
}
public static void loadSeedUploadMethods() {
- Hashtable availableUploaders = new Hashtable();
+ HashMap availableUploaders = new HashMap();
try {
String uploadersPkgName = yacyCore.class.getPackage().getName() + ".seedUpload";
diff --git a/source/de/anomic/yacy/yacyPeerActions.java b/source/de/anomic/yacy/yacyPeerActions.java
index c70d83d6d..a42d3772e 100644
--- a/source/de/anomic/yacy/yacyPeerActions.java
+++ b/source/de/anomic/yacy/yacyPeerActions.java
@@ -46,11 +46,10 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
+import java.util.ArrayList;
import java.util.Date;
-import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
-import java.util.Vector;
import de.anomic.http.httpHeader;
import de.anomic.http.httpc;
@@ -139,8 +138,8 @@ public class yacyPeerActions {
yacySeed ys;
String seedListFileURL;
URL url;
- Vector seedList;
- Enumeration enu;
+ ArrayList seedList;
+ Iterator enu;
int lc;
int sc = seedDB.sizeConnected();
httpHeader header;
@@ -167,10 +166,10 @@ public class yacyPeerActions {
} else {
ssc++;
seedList = httpc.wget(url, 5000, null, null, sb.remoteProxyHost, sb.remoteProxyPort);
- enu = seedList.elements();
+ enu = seedList.iterator();
lc = 0;
- while (enu.hasMoreElements()) {
- ys = yacySeed.genRemoteSeed((String) enu.nextElement(), null);
+ while (enu.hasNext()) {
+ ys = yacySeed.genRemoteSeed((String) enu.next(), null);
if ((ys != null) && (ys.isProper() == null) &&
((seedDB.mySeed == null) || (seedDB.mySeed.hash != ys.hash))) {
if (connectPeer(ys, false)) lc++;
@@ -219,11 +218,11 @@ public class yacyPeerActions {
// read in remote file from url
try {
- Vector remote = httpc.wget(new URL(url), 5000, null, null, sb.remoteProxyHost, sb.remoteProxyPort);
+ ArrayList remote = httpc.wget(new URL(url), 5000, null, null, sb.remoteProxyHost, sb.remoteProxyPort);
if ((remote != null) && (remote.size() > 0)) {
- Enumeration e = remote.elements();
- while (e.hasMoreElements()) {
- line = (String) e.nextElement();
+ Iterator e = remote.iterator();
+ while (e.hasNext()) {
+ line = (String) e.next();
if (line != null) {
line = line.trim();
supsee.add(line);
diff --git a/source/de/anomic/yacy/yacySeedDB.java b/source/de/anomic/yacy/yacySeedDB.java
index 6d960e0bf..b0abb3052 100644
--- a/source/de/anomic/yacy/yacySeedDB.java
+++ b/source/de/anomic/yacy/yacySeedDB.java
@@ -46,12 +46,12 @@ import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
+import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
-import java.util.Vector;
import de.anomic.http.httpc;
import de.anomic.kelondro.kelondroDyn;
@@ -508,13 +508,13 @@ public final class yacySeedDB {
return null;
}
- public Vector storeCache(File seedFile) throws IOException {
+ public ArrayList storeCache(File seedFile) throws IOException {
return storeCache(seedFile, false);
}
- private Vector storeCache(File seedFile, boolean addMySeed) throws IOException {
+ private ArrayList storeCache(File seedFile, boolean addMySeed) throws IOException {
PrintWriter pw = null;
- Vector v = new Vector(seedActiveDB.size()+1);
+ ArrayList v = new ArrayList(seedActiveDB.size()+1);
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(seedFile)));
@@ -562,10 +562,10 @@ public final class yacySeedDB {
// create a seed file which for uploading ...
seedFile = new File("seedFile.txt");
serverLog.logFine("YACY","SaveSeedList: Storing seedlist into tempfile " + seedFile.toString());
- Vector uv = storeCache(seedFile, true);
+ ArrayList uv = storeCache(seedFile, true);
// uploading the seed file
- serverLog.logFine("YACY","SaveSeedList: Trying to upload seed-file ...");
+ serverLog.logFine("YACY","SaveSeedList: Trying to upload seed-file, " + seedFile.length() + " bytes, " + uv.size() + " entries.");
log = uploader.uploadSeedFile(sb,seedDB,seedFile);
// check also if the result can be retrieved again
@@ -584,7 +584,7 @@ public final class yacySeedDB {
public String copyCache(File seedFile, URL seedURL) throws IOException {
if (seedURL == null) return "COPY - Error: URL not given";
- Vector uv = storeCache(seedFile, true);
+ ArrayList uv = storeCache(seedFile, true);
try {
// check also if the result can be retrieved again
if (checkCache(uv, seedURL))
@@ -596,9 +596,9 @@ public final class yacySeedDB {
}
}
- private boolean checkCache(Vector uv, URL seedURL) throws IOException {
+ private boolean checkCache(ArrayList uv, URL seedURL) throws IOException {
// check if the result can be retrieved again
- Vector check = httpc.wget(seedURL, 10000, null, null, sb.remoteProxyHost, sb.remoteProxyPort);
+ ArrayList check = httpc.wget(seedURL, 10000, null, null, sb.remoteProxyHost, sb.remoteProxyPort);
if (check == null) {
serverLog.logFine("YACY","SaveSeedList: Testing download failed ...");
@@ -614,7 +614,7 @@ public final class yacySeedDB {
serverLog.logFine("YACY","SaveSeedList: Comparing local and uploades seed-list entries ...");
int i;
for (i = 0; i < uv.size(); i++) {
- if (!(((String) uv.elementAt(i)).equals((String) check.elementAt(i)))) return false;
+ if (!(((String) uv.get(i)).equals((String) check.get(i)))) return false;
}
if (i == uv.size()) return true;
}
diff --git a/source/yacy.java b/source/yacy.java
index 84f769807..d80add5c3 100644
--- a/source/yacy.java
+++ b/source/yacy.java
@@ -52,6 +52,7 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
+import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@@ -67,8 +68,10 @@ import de.anomic.http.httpd;
import de.anomic.http.httpdFileHandler;
import de.anomic.http.httpdProxyHandler;
import de.anomic.kelondro.kelondroMScoreCluster;
+import de.anomic.plasma.plasmaCrawlLURL;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.plasma.plasmaURL;
+import de.anomic.plasma.plasmaWordIndex;
import de.anomic.plasma.plasmaWordIndexEntity;
import de.anomic.plasma.plasmaWordIndexEntry;
import de.anomic.plasma.plasmaWordIndexClassicDB;
@@ -655,6 +658,91 @@ public final class yacy {
e.printStackTrace();
}
}
+
+ public static void minimizeUrlDB(String homePath) {
+ // run with "java -classpath classes yacy -migratewords"
+ try {serverLog.configureLogging(new File(homePath, "yacy.logging"));} catch (Exception e) {}
+ File dbroot = new File(new File(homePath), "DATA/PLASMADB");
+ try {
+ serverLog log = new serverLog("URL-CLEANUP");
+ log.logInfo("STARTING URL CLEANUP");
+
+ // db containing all currently loades urls
+ plasmaCrawlLURL currentUrlDB = new plasmaCrawlLURL(new File(dbroot, "urlHash.db"), 4194304);
+
+ // db used to hold all neede urls
+ plasmaCrawlLURL minimizedUrlDB = new plasmaCrawlLURL(new File(dbroot, "urlHash.temp.db"), 4194304);
+
+ Runtime rt = Runtime.getRuntime();
+ int cacheMem = (int)(rt.maxMemory()-rt.totalMemory())-5*1024*1024;
+ plasmaWordIndex wordIndex = new plasmaWordIndex(dbroot, cacheMem, log);
+ Iterator wordHashIterator = wordIndex.wordHashes("------------", true, true);
+
+ String wordhash;
+ long urlCounter = 0, wordCounter = 0;
+ long wordChunkStart = System.currentTimeMillis(), wordChunkEnd = 0;
+ String wordChunkStartHash = "------------", wordChunkEndHash;
+
+ while (wordHashIterator.hasNext()) {
+ plasmaWordIndexEntity wordIdxEntity = null;
+ try {
+ wordCounter++;
+ wordhash = (String) wordHashIterator.next();
+ wordIdxEntity = wordIndex.getEntity(wordhash, true);
+
+ // the combined container will fit, read the container
+ Enumeration wordIdxEntries = wordIdxEntity.elements(true);
+ plasmaWordIndexEntry wordIdxEntry;
+ while (wordIdxEntries.hasMoreElements()) {
+ wordIdxEntry = (plasmaWordIndexEntry) wordIdxEntries.nextElement();
+ String urlHash = wordIdxEntry.getUrlHash();
+ if ((currentUrlDB.exists(urlHash)) && (!minimizedUrlDB.exists(urlHash))) {
+ urlCounter++;
+ plasmaCrawlLURL.Entry urlEntry = currentUrlDB.getEntry(urlHash);
+ minimizedUrlDB.newEntry(urlEntry);
+ if (urlCounter % 500 == 0) {
+ log.logInfo(urlCounter + " URLs found so far.");
+ }
+ }
+ }
+ // we have read all elements, now delete the entity
+ wordIdxEntity.close(); wordIdxEntity = null;
+
+ if (wordCounter%500 == 0) {
+ wordChunkEndHash = wordhash;
+ wordChunkEnd = System.currentTimeMillis();
+ long duration = wordChunkEnd - wordChunkStart;
+ log.logInfo(wordCounter + " words scanned " +
+ "[" + wordChunkStartHash + " .. " + wordChunkEndHash + "]\n" +
+ "Duration: "+ 500*1000/duration + " words/s" +
+ " | Free memory: " + rt.freeMemory() +
+ " | Total memory: " + rt.totalMemory());
+ wordChunkStart = wordChunkEnd;
+ wordChunkStartHash = wordChunkEndHash;
+ }
+
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (wordIdxEntity != null) try { wordIdxEntity.close(); } catch (Exception e) {}
+ }
+ }
+ currentUrlDB.close();
+ minimizedUrlDB.close();
+ wordIndex.close(600);
+
+ log.logInfo("current LURL DB contains " + currentUrlDB.size() + " entries.");
+ log.logInfo("mimimized LURL DB contains " + minimizedUrlDB.size() + " entries.");
+
+ // TODO: rename the mimimized UrlDB to the name of the previous UrlDB
+
+ log.logInfo("FINISHED URL CLEANUP, WAIT FOR DUMP");
+ log.logInfo("TERMINATED URL CLEANUP");
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
/**
* Reads all words from the given file and creates a hashmap, where key is
@@ -818,6 +906,11 @@ public final class yacy {
// attention: this may run long and should not be interrupted!
if (args.length == 2) applicationRoot= args[1];
migrateWords(applicationRoot);
+ } else if ((args.length >= 1) && (args[0].equals("-minimizeUrlDB"))) {
+ // migrate words from DATA/PLASMADB/WORDS path to assortment cache, if possible
+ // attention: this may run long and should not be interrupted!
+ if (args.length == 2) applicationRoot= args[1];
+ minimizeUrlDB(applicationRoot);
} else if ((args.length >= 1) && (args[0].equals("-deletestopwords"))) {
// delete those words in the index that are listed in the stopwords file
if (args.length == 2) applicationRoot= args[1];
diff --git a/yacy.init b/yacy.init
index 0d62b0081..28ddc9b73 100644
--- a/yacy.init
+++ b/yacy.init
@@ -102,7 +102,7 @@ parseableMimeTypes=
# this is important to recognize <a href> - tags as not-html reference
# These files will be excluded from indexing _(Please keep extensions in alphabetical order)_
mediaExt=ace,arj,asf,avi,bin,bz2,css,deb,doc,dll,dmg,gif,gz,hqx,ico,img,iso,jar,jpe,jpg,jpeg,mpeg,mov,mp3,mpg,ogg,png,pdf,ppt,ps,ram,rar,rm,rpm,sit,so,swf,sxc,sxd,sxi,sxw,tar,tgz,torrent,wmv,xcf,xls,zip
-parseableExt=html,htm,txt,php,shtml,asp
+parseableExt=html,htm,txt,php,shtml,asp,aspx,jsp
# Promotion Strings
# These strings appear in the Web Mask of the YACY search client
@@ -470,6 +470,9 @@ ramCacheRobots = 2097152
# ram cache for crawlProfile.db
ramCacheProfiles = 8192
+# ram cache for stack crawl thread db
+ramCachePreNURL = 8192
+
# default memory settings for startup of yacy
# is only valid in unix/shell environments and
# not for first startup of YaCy
@@ -539,4 +542,26 @@ crawler.MinIdleThreads = 5
useYacyReferer = true
-enableTemplateCache = true
\ No newline at end of file
+# specifies if the httpdFileHandler should cache
+# the template-files from the htroot directory
+enableTemplateCache = true
+
+# specifies if the http post body should be transfered
+# using content-encoding gzip during index transfer
+# a) indexDistribution: which is done periodically if you have enabled
+# Index Distribution via IndexControl_p.html
+# b) indexTransfer: which can be used to transfer the whole index of a peer
+# this can be started via IndexTransfer_p.html
+# c) indexControl: which can be triggered manually via IndexControl_p.html to
+# transfer a chosen subset of the peer index
+indexDistribution.gzipBody = true
+indexTransfer.gzipBody = true
+indexControl.gzipBody = true
+
+# defining timeouts for index- transfer/distribution/control
+indexControl.timeout = 60000
+indexDistribution.timeout = 60000
+indexTransfer.timeout = 120000
+
+#
+storagePeerHash =