Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance
Java decentralizedintranet-searchintranet-search-enginep2pp2p-networkprivacyprivacy-protectionsearch-enginesearchenginewebweb-search-enginewebsearchwebseearch-engine
replaced httpc with Apache Jakarta Commons HttpClient (includes some refactoring ;)
danielr5c3c1fdf41ed
diff --git a/.classpath b/.classpathindex 94731343b..8ed5f90fb 100644--- a/.classpath+++ b/.classpath@@ -38,5 +38,6 @@<classpathentry kind="lib" path="libx/FontBox-0.1.0-dev.jar"/><classpathentry kind="lib" path="libx/bcprov-jdk14-132.jar"/><classpathentry kind="lib" path="libx/commons-codec-1.3.jar"/>+ <classpathentry kind="lib" path="libx/commons-httpclient-3.1.jar"/><classpathentry kind="output" path="gen"/></classpath>diff --git a/build.xml b/build.xmlindex d404238bb..23d319828 100644--- a/build.xml+++ b/build.xml@@ -183,6 +183,7 @@<pathelement location="${lib}/tar.jar" /><pathelement location="${libx}/saaj.jar" /><pathelement location="${libx}/axis.jar" />+ <pathelement location="${libx}/commons-httpclient-3.1.jar" /></path><!-- compiling yacy.java -->diff --git a/defaults/yacy.init b/defaults/yacy.initindex 3bd1bec15..5b5b336d3 100644--- a/defaults/yacy.init+++ b/defaults/yacy.init@@ -70,7 +70,8 @@ server.maxTrackingTime = 3600000# The property here can also be a url where the definition can be loaded.# In case of privately managed networks, this configuration must be changed BEFORE it is released# to the members of the separated network peers.-network.unit.definition = defaults/yacy.network.freeworld.unit+#network.unit.definition = defaults/yacy.network.freeworld.unit+network.unit.definition = defaults/yacy.network.intranet.unitnetwork.group.definition = defaults/yacy.network.group# Update process propertiesdiff --git a/htroot/Blog.java b/htroot/Blog.javaindex cd2db62c7..f4aa7e978 100644--- a/htroot/Blog.java+++ b/htroot/Blog.java@@ -55,8 +55,8 @@ import java.util.Iterator;import de.anomic.data.blogBoard;import de.anomic.data.userDB;+import de.anomic.http.HttpClient;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverObjects;import de.anomic.server.serverSwitch;@@ -364,7 +364,7 @@ public class Blog {}prop.put("mode_entries_" + number + "_date", dateString(entry.getDate()));- prop.put("mode_entries_" + number + "_rfc822date", httpc.dateString(entry.getDate()));+ prop.put("mode_entries_" + number + "_rfc822date", HttpClient.dateString(entry.getDate()));prop.put("mode_entries_" + number + "_pageid", entry.getKey());prop.put("mode_entries_" + number + "_address", address);prop.put("mode_entries_" + number + "_ip", entry.getIp());diff --git a/htroot/Bookmarks.java b/htroot/Bookmarks.javaindex 2d4f6d47b..c47311148 100644--- a/htroot/Bookmarks.java+++ b/htroot/Bookmarks.java@@ -59,8 +59,8 @@ import de.anomic.data.bookmarksDB;import de.anomic.data.listManager;import de.anomic.data.userDB;import de.anomic.data.bookmarksDB.Tag;+import de.anomic.http.HttpClient;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.index.indexURLReference;import de.anomic.plasma.plasmaParserDocument;import de.anomic.plasma.plasmaSnippetCache;@@ -314,7 +314,7 @@ public class Bookmarks {prop.putHTML("bookmarks_"+count+"_title", bookmark.getTitle());prop.putHTML("bookmarks_"+count+"_description", bookmark.getDescription());prop.put("bookmarks_"+count+"_date", serverDate.formatISO8601(new Date(bookmark.getTimeStamp())));- prop.put("bookmarks_"+count+"_rfc822date", httpc.dateString(new Date(bookmark.getTimeStamp())));+ prop.put("bookmarks_"+count+"_rfc822date", HttpClient.dateString(new Date(bookmark.getTimeStamp())));prop.put("bookmarks_"+count+"_public", (bookmark.getPublic() ? "1" : "0"));//List Tags.diff --git a/htroot/ConfigLanguage_p.java b/htroot/ConfigLanguage_p.javaindex a82214914..74505399d 100644--- a/htroot/ConfigLanguage_p.java+++ b/htroot/ConfigLanguage_p.java@@ -56,9 +56,8 @@ import java.util.Iterator;import de.anomic.data.listManager;import de.anomic.data.translator;+import de.anomic.http.HttpClient;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;-import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverObjects;import de.anomic.server.serverSwitch;import de.anomic.tools.nxTools;@@ -70,7 +69,6 @@ public class ConfigLanguage_p {public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {//listManager.switchboard = (plasmaSwitchboard) env;serverObjects prop = new serverObjects();- plasmaSwitchboard switchboard = (plasmaSwitchboard) env;String langPath = env.getConfigPath("locale.work", "DATA/LOCALE/locales").getAbsolutePath();//Fallback@@ -98,7 +96,7 @@ public class ConfigLanguage_p {ArrayList<String> langVector;try{yacyURL u = new yacyURL(url, null);- langVector = nxTools.strings(httpc.wget(u, u.getHost(), 6000, null, null, switchboard.remoteProxyConfig, null, null), "UTF-8");+ langVector = nxTools.strings(HttpClient.wget(u.toString()), "UTF-8");}catch(IOException e){prop.put("status", "1");//unable to get urlprop.put("status_url", url);diff --git a/htroot/ConfigSkins_p.java b/htroot/ConfigSkins_p.javaindex 7a2132701..39a147c44 100644--- a/htroot/ConfigSkins_p.java+++ b/htroot/ConfigSkins_p.java@@ -54,8 +54,8 @@ import java.util.ArrayList;import java.util.Iterator;import de.anomic.data.listManager;+import de.anomic.http.HttpClient;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;@@ -127,7 +127,7 @@ public class ConfigSkins_p {ArrayList<String> skinVector;try {yacyURL u = new yacyURL(url, null);- skinVector = nxTools.strings(httpc.wget(u, u.getHost(), 6000, null, null, switchboard.remoteProxyConfig, null, null), "UTF-8");+ skinVector = nxTools.strings(HttpClient.wget(u.toString()), "UTF-8");} catch(IOException e) {prop.put("status", "1");//unable to get URLprop.put("status_url", url);diff --git a/htroot/Connections_p.html b/htroot/Connections_p.htmlindex f5ec4f3a5..47e3abd93 100644--- a/htroot/Connections_p.html+++ b/htroot/Connections_p.html@@ -36,6 +36,7 @@</table><h3>Outgoing Connections</h3>+ <p><strong>Currently not available!</strong></p><p>Showing #[clientActive]# active outgoing connections:</p><table border="0" cellpadding="2" cellspacing="1"><tr class="TableHeader" valign="bottom">diff --git a/htroot/Connections_p.java b/htroot/Connections_p.javaindex 528e6fafb..4357114e0 100644--- a/htroot/Connections_p.java+++ b/htroot/Connections_p.java@@ -49,11 +49,9 @@import java.io.UnsupportedEncodingException;import java.net.InetAddress;import java.net.URLEncoder;-import java.util.Arrays;import java.util.Properties;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.http.httpd;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverCore;@@ -229,21 +227,22 @@ public final class Connections_p {prop.putNum("numActivePending", numActivePending);// client sessions- httpc[] a = httpc.allConnections();- Arrays.sort(a, httpc.connectionTimeComparatorInstance);+ // FIXME track connections of JakartaCommons Connection Manager+// httpc[] a = httpc.allConnections();+// Arrays.sort(a, httpc.connectionTimeComparatorInstance);int c = 0;- for (int i = 0; i < a.length; i++) {- httpc clientConnection = a[i];- if (clientConnection != null) {- prop.put("clientList_" + c + "_clientProtocol", (clientConnection.ssl) ? "HTTPS" : "HTTP");- prop.putNum("clientList_" + c + "_clientLifetime", System.currentTimeMillis() - clientConnection.initTime);- prop.putNum("clientList_" + c + "_clientIdletime", System.currentTimeMillis() - clientConnection.lastIO);- prop.put("clientList_" + c + "_clientTargetHost", clientConnection.adressed_host + ":" + clientConnection.adressed_port);- prop.putHTML("clientList_" + c + "_clientCommand", (clientConnection.command == null) ? "-" : clientConnection.command);- prop.put("clientList_" + c + "_clientID", clientConnection.hashCode());- c++;- }- }+// for (int i = 0; i < a.length; i++) {+// httpc clientConnection = a[i];+// if (clientConnection != null) {+// prop.put("clientList_" + c + "_clientProtocol", (clientConnection.ssl) ? "HTTPS" : "HTTP");+// prop.putNum("clientList_" + c + "_clientLifetime", System.currentTimeMillis() - clientConnection.initTime);+// prop.putNum("clientList_" + c + "_clientIdletime", System.currentTimeMillis() - clientConnection.lastIO);+// prop.put("clientList_" + c + "_clientTargetHost", clientConnection.adressed_host + ":" + clientConnection.adressed_port);+// prop.putHTML("clientList_" + c + "_clientCommand", (clientConnection.command == null) ? "-" : clientConnection.command);+// prop.put("clientList_" + c + "_clientID", clientConnection.hashCode());+// c++;+// }+// }prop.put("clientList", c);prop.put("clientActive", c);diff --git a/htroot/CookieMonitorIncoming_p.java b/htroot/CookieMonitorIncoming_p.javaindex 5a83751d0..642f0de04 100644--- a/htroot/CookieMonitorIncoming_p.java+++ b/htroot/CookieMonitorIncoming_p.java@@ -47,8 +47,8 @@ import java.util.Date;import java.util.Iterator;import java.util.Map;+import de.anomic.http.HttpClient;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverObjects;import de.anomic.server.serverSwitch;@@ -84,7 +84,7 @@ public class CookieMonitorIncoming_p {prop.put("list_" + entCount + "_dark", dark ? "1" : "0");dark =! dark;prop.put("list_" + entCount + "_host", host);- prop.put("list_" + entCount + "_date", httpc.dateString(date));+ prop.put("list_" + entCount + "_date", HttpClient.dateString(date));prop.put("list_" + entCount + "_client", client);while (tmpCount < cookies.length){prop.putHTML("list_" + entCount + "_cookies_" + tmpCount + "_item", ((String) cookies[tmpCount]));diff --git a/htroot/CookieMonitorOutgoing_p.java b/htroot/CookieMonitorOutgoing_p.javaindex 25ea9afd5..a8e00cb6a 100644--- a/htroot/CookieMonitorOutgoing_p.java+++ b/htroot/CookieMonitorOutgoing_p.java@@ -47,8 +47,8 @@ import java.util.Date;import java.util.Iterator;import java.util.Map;+import de.anomic.http.HttpClient;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverObjects;import de.anomic.server.serverSwitch;@@ -84,7 +84,7 @@ public class CookieMonitorOutgoing_p {prop.put("list_" + entCount + "_dark", dark ? "1" : "0" );dark =! dark;prop.put("list_" + entCount + "_host", host);- prop.put("list_" + entCount + "_date", httpc.dateString(date));+ prop.put("list_" + entCount + "_date", HttpClient.dateString(date));prop.put("list_" + entCount + "_client", client);while (tmpCount < cookies.length){prop.putHTML("list_" + entCount + "_cookies_" + tmpCount + "_item", ((String) cookies[tmpCount]));diff --git a/htroot/Messages_p.java b/htroot/Messages_p.javaindex 9f6d34ddb..fd00ad64a 100644--- a/htroot/Messages_p.java+++ b/htroot/Messages_p.java@@ -52,8 +52,8 @@ import java.util.Iterator;import java.util.TreeMap;import de.anomic.data.messageBoard;+import de.anomic.http.HttpClient;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;@@ -151,7 +151,7 @@ public class Messages_p {prop.put("mode_messages_"+count+"_peerAddress", peerAddress);// set the rfc822 date- prop.put("mode_messages_"+count+"_rfc822Date",httpc.dateString(message.date()));+ prop.put("mode_messages_"+count+"_rfc822Date",HttpClient.dateString(message.date()));// also write out the message body (needed for the RSS feed)try {diff --git a/htroot/Network.java b/htroot/Network.javaindex d339ed4e5..baa883688 100644--- a/htroot/Network.java+++ b/htroot/Network.java@@ -54,8 +54,9 @@ import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.regex.PatternSyntaxException;+import de.anomic.http.HttpClient;+import de.anomic.http.HttpFactory;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverCodings;import de.anomic.server.serverDate;@@ -163,10 +164,7 @@ public class Network {prop.put("table_my-url", seed.get("seedURL", ""));// generating the location string- String location = httpc.userAgent;- int p = location.lastIndexOf(';');- location = (p > 0) ? location.substring(p + 1, location.length() - 1).trim(): "";- prop.putHTML("table_my-location", location);+ prop.putHTML("table_my-location", HttpClient.generateLocation());}// overall results: Network statistics@@ -378,12 +376,14 @@ public class Network {prop.putHTML(STR_TABLE_LIST + conCount + "_fullname", seed.get(yacySeed.NAME, "deadlink"));userAgent = null;if (seed.hash.equals(yacyCore.seedDB.mySeed().hash)) {- userAgent = httpc.userAgent;+ final HttpClient httpClient = HttpFactory.newClient();+ userAgent = httpClient.getUserAgent();+ location = HttpClient.generateLocation();} else {userAgent = yacyCore.peerActions.getUserAgent(seed.getIP());+ p = userAgent.lastIndexOf(';');+ location = (p > 0) ? userAgent.substring(p + 1, userAgent.length() - 1).trim(): "";}- p = userAgent.lastIndexOf(';');- location = (p > 0) ? userAgent.substring(p + 1, userAgent.length() - 1).trim(): "";prop.put(STR_TABLE_LIST + conCount + "_location", location);if (complete) {prop.put(STR_TABLE_LIST + conCount + "_complete", 1);diff --git a/htroot/News.java b/htroot/News.javaindex 137d4b18e..f2dd1bdc8 100644--- a/htroot/News.java+++ b/htroot/News.java@@ -47,8 +47,8 @@ import java.io.IOException;import java.util.Iterator;import java.util.Map;+import de.anomic.http.HttpClient;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverDate;import de.anomic.server.serverObjects;@@ -138,7 +138,7 @@ public class News {prop.put("table_list_" + i + "_id", record.id());prop.putHTML("table_list_" + i + "_ori", (seed == null) ? record.originator() : seed.getName());prop.put("table_list_" + i + "_cre", serverDate.formatShortSecond(record.created()));- prop.put("table_list_" + i + "_crerfcdate", httpc.dateString(record.created()));+ prop.put("table_list_" + i + "_crerfcdate", HttpClient.dateString(record.created()));prop.put("table_list_" + i + "_cat", category);prop.put("table_list_" + i + "_rec", (record.received() == null) ? "-" : serverDate.formatShortSecond(record.received()));prop.put("table_list_" + i + "_dis", record.distributed());diff --git a/htroot/SettingsAck_p.java b/htroot/SettingsAck_p.javaindex 59c140532..887aecec4 100644--- a/htroot/SettingsAck_p.java+++ b/htroot/SettingsAck_p.java@@ -414,7 +414,7 @@ public class SettingsAck_p {* Enabling settings* ==================================================================== */plasmaSwitchboard sb = (plasmaSwitchboard)env;- sb.remoteProxyConfig = httpRemoteProxyConfig.init(sb);+ httpdProxyHandler.setRemoteProxyConfig(httpRemoteProxyConfig.init(sb));// httpdProxyHandler.remoteProxyUse = post.get("remoteProxyUse", "").equals("on");// httpdProxyHandler.remoteProxyHost = post.get("remoteProxyHost", "");diff --git a/htroot/ViewFile.java b/htroot/ViewFile.javaindex 371703264..e631fae51 100644--- a/htroot/ViewFile.java+++ b/htroot/ViewFile.java@@ -44,7 +44,6 @@//javac -classpath .:../Classes Status.java//if the shell's current path is HTROOT-import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.net.MalformedURLException;@@ -55,8 +54,8 @@ import java.util.Map;import de.anomic.data.htmlTools;import de.anomic.htmlFilter.htmlFilterImageEntry;+import de.anomic.http.HttpClient;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.index.indexURLReference;import de.anomic.plasma.plasmaCondenser;import de.anomic.plasma.plasmaHTCache;@@ -159,87 +158,74 @@ public class ViewFile {long resourceLength = -1;IResourceInfo resInfo = null;String resMime = null;- try {- // trying to load the resource body- resource = plasmaHTCache.getResourceContentStream(url);- resourceLength = plasmaHTCache.getResourceContentLength(url);+ // trying to load the resource body+ resource = plasmaHTCache.getResourceContentStream(url);+ resourceLength = plasmaHTCache.getResourceContentLength(url);++ // if the resource body was not cached we try to load it from web+ if (resource == null) {+ plasmaHTCache.Entry entry = null;+ try {+ entry = sb.crawlQueues.loadResourceFromWeb(url, 5000, false, true);+ } catch (Exception e) {+ prop.put("error", "4");+ prop.putHTML("error_errorText", e.getMessage());+ prop.put("viewMode", VIEW_MODE_NO_TEXT);+ return prop;+ }++ if (entry != null) {+ resInfo = entry.getDocumentInfo();+ resource = plasmaHTCache.getResourceContentStream(url);+ resourceLength = plasmaHTCache.getResourceContentLength(url);+ }- // if the resource body was not cached we try to load it from webif (resource == null) {- plasmaHTCache.Entry entry = null;- try {- entry = sb.crawlQueues.loadResourceFromWeb(url, 5000, false, true);- } catch (Exception e) {- prop.put("error", "4");- prop.putHTML("error_errorText", e.getMessage());+ prop.put("error", "4");+ prop.put("error_errorText", "No resource available");+ prop.put("viewMode", VIEW_MODE_NO_TEXT);+ return prop;+ }+ }++ // try to load resource metadata+ if (resInfo == null) {++ // try to load the metadata from cache+ try {+ resInfo = plasmaHTCache.loadResourceInfo(url);+ } catch (Exception e) {+ /* ignore this */+ }++ // if the metadata was not cached try to load it from web+ if (resInfo == null) {+ String protocol = url.getProtocol();+ if (!((protocol.equals("http") || protocol.equals("https")))) {+ prop.put("error", "6");prop.put("viewMode", VIEW_MODE_NO_TEXT);return prop;}- if (entry != null) {- resInfo = entry.getDocumentInfo();- resource = plasmaHTCache.getResourceContentStream(url);- resourceLength = plasmaHTCache.getResourceContentLength(url);- }-- if (resource == null) {+ httpHeader responseHeader = HttpClient.whead(url.toString());+ if (responseHeader == null) {prop.put("error", "4");- prop.put("error_errorText", "No resource available");+ prop.put("error_errorText", "Unable to load resource metadata.");prop.put("viewMode", VIEW_MODE_NO_TEXT);return prop;}- }-- // try to load resource metadata- if (resInfo == null) {-- // try to load the metadata from cachetry {- resInfo = plasmaHTCache.loadResourceInfo(url);+ resInfo = plasmaHTCache.getResourceInfoFactory().buildResourceInfoObj(url, responseHeader);} catch (Exception e) {- /* ignore this */- }-- // if the metadata was not cached try to load it from web- if (resInfo == null) {- String protocol = url.getProtocol();- if (!((protocol.equals("http") || protocol.equals("https")))) {- prop.put("error", "6");- prop.put("viewMode", VIEW_MODE_NO_TEXT);- return prop;- }-- httpHeader responseHeader = httpc.whead(url, url.getHost(), 5000, null, null, sb.remoteProxyConfig);- if (responseHeader == null) {- prop.put("error", "4");- prop.put("error_errorText", "Unable to load resource metadata.");- prop.put("viewMode", VIEW_MODE_NO_TEXT);- return prop;- }- try {- resInfo = plasmaHTCache.getResourceInfoFactory().buildResourceInfoObj(url, responseHeader);- } catch (Exception e) {- prop.put("error", "4");- prop.putHTML("error_errorText", e.getMessage());- prop.put("viewMode", VIEW_MODE_NO_TEXT);- return prop;- }- resMime = responseHeader.mime();+ prop.put("error", "4");+ prop.putHTML("error_errorText", e.getMessage());+ prop.put("viewMode", VIEW_MODE_NO_TEXT);+ return prop;}- } else {- resMime = resInfo.getMimeType();+ resMime = responseHeader.mime();}- } catch (IOException e) {- if (resource != null)- try {- resource.close();- } catch (Exception ex) {- /* ignore this */- }- prop.put("error", "4");- prop.putHTML("error_errorText", e.getMessage());- prop.put("viewMode", VIEW_MODE_NO_TEXT);- return prop;+ } else {+ resMime = resInfo.getMimeType();}String[] wordArray = wordArray(post.get("words", null));diff --git a/htroot/sharedBlacklist_p.java b/htroot/sharedBlacklist_p.javaindex 197e64659..7e40081fa 100644--- a/htroot/sharedBlacklist_p.java+++ b/htroot/sharedBlacklist_p.java@@ -56,8 +56,8 @@ import java.util.Arrays;import java.util.HashSet;import de.anomic.data.listManager;+import de.anomic.http.HttpClient;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.index.indexAbstractReferenceBlacklist;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverObjects;@@ -79,7 +79,6 @@ public class sharedBlacklist_p {public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {// return variable that accumulates replacementsserverObjects prop = new serverObjects();- plasmaSwitchboard switchboard = (plasmaSwitchboard) env;// getting the name of the destination blacklistString selectedBlacklistName = "";@@ -132,7 +131,7 @@ public class sharedBlacklist_p {// get ListyacyURL u = new yacyURL(downloadURL, null);- otherBlacklist = nxTools.strings(httpc.wget(u, u.getHost(), 12000, null, null, switchboard.remoteProxyConfig,reqHeader, null), "UTF-8");+ otherBlacklist = nxTools.strings(HttpClient.wget(u.toString(), reqHeader), "UTF-8");} catch (Exception e) {prop.put("status", STATUS_PEER_UNKNOWN);prop.put("page", "1");@@ -148,7 +147,7 @@ public class sharedBlacklist_p {try {yacyURL u = new yacyURL(downloadURL, null);- otherBlacklist = nxTools.strings(httpc.wget(u, u.getHost(), 6000, null, null, switchboard.remoteProxyConfig, null, null), "UTF-8"); //get List+ otherBlacklist = nxTools.strings(HttpClient.wget(u.toString()), "UTF-8"); //get List} catch (Exception e) {prop.put("status", STATUS_URL_PROBLEM);prop.putHTML("status_address",downloadURL);diff --git a/htroot/xml/util/getpageinfo_p.java b/htroot/xml/util/getpageinfo_p.javaindex 7e6a84b9b..b20d10f02 100644--- a/htroot/xml/util/getpageinfo_p.java+++ b/htroot/xml/util/getpageinfo_p.java@@ -53,9 +53,8 @@ import java.net.MalformedURLException;import de.anomic.data.robotsParser;import de.anomic.htmlFilter.htmlFilterContentScraper;import de.anomic.htmlFilter.htmlFilterWriter;+import de.anomic.http.HttpClient;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;@@ -83,7 +82,7 @@ public class getpageinfo_p {if (actions.indexOf("title")>=0) {try {yacyURL u = new yacyURL(url, null);- String contentString=new String(httpc.wget(u, u.getHost(), 6000, null, null, ((plasmaSwitchboard) env).remoteProxyConfig, null, null)) ;+ String contentString=new String(HttpClient.wget(u.toString()));htmlFilterContentScraper scraper = new htmlFilterContentScraper(u);//OutputStream os = new htmlFilterOutputStream(null, scraper, null, false);diff --git a/htroot/yacy/ui/ymarks.java b/htroot/yacy/ui/ymarks.javaindex c73b68c3f..7da366f82 100644--- a/htroot/yacy/ui/ymarks.java+++ b/htroot/yacy/ui/ymarks.java@@ -59,8 +59,8 @@ import de.anomic.data.bookmarksDB;import de.anomic.data.listManager;import de.anomic.data.userDB;import de.anomic.data.bookmarksDB.Tag;+import de.anomic.http.HttpClient;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.index.indexURLReference;import de.anomic.plasma.plasmaParserDocument;import de.anomic.plasma.plasmaSnippetCache;@@ -314,7 +314,7 @@ public class ymarks {prop.putHTML("bookmarks_"+count+"_title", bookmark.getTitle());prop.putHTML("bookmarks_"+count+"_description", bookmark.getDescription());prop.put("bookmarks_"+count+"_date", serverDate.formatISO8601(new Date(bookmark.getTimeStamp())));- prop.put("bookmarks_"+count+"_rfc822date", httpc.dateString(new Date(bookmark.getTimeStamp())));+ prop.put("bookmarks_"+count+"_rfc822date", HttpClient.dateString(new Date(bookmark.getTimeStamp())));prop.put("bookmarks_"+count+"_public", (bookmark.getPublic() ? "1" : "0"));//List Tags.diff --git a/libx/commons-httpclient-3.1.jar b/libx/commons-httpclient-3.1.jarnew file mode 100644index 000000000..7c59774aeBinary files /dev/null and b/libx/commons-httpclient-3.1.jar differdiff --git a/source/de/anomic/data/SitemapParser.java b/source/de/anomic/data/SitemapParser.javaindex 777d4e7f1..31a65eea1 100644--- a/source/de/anomic/data/SitemapParser.java+++ b/source/de/anomic/data/SitemapParser.java@@ -1,46 +1,46 @@-//SitemapParser.java-//-------------------------//part of YaCy-//(C) by Michael Peter Christen; [email protected]-//first published on http://www.anomic.de-//Frankfurt, Germany, 2007+// SitemapParser.java+// ------------------------+// part of YaCy+// (C) by Michael Peter Christen; [email protected]+// first published on http://www.anomic.de+// Frankfurt, Germany, 2007//-//this file is contributed by Martin Thelian-//last major change: $LastChangedDate$ by $LastChangedBy$-//Revision: $LastChangedRevision$+// this file is contributed by Martin Thelian+// 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;@@ -53,11 +53,14 @@ import java.util.zip.GZIPInputStream;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;+import org.apache.commons.httpclient.protocol.Protocol;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;-import de.anomic.http.httpc;+import de.anomic.http.HttpClient;+import de.anomic.http.HttpFactory;+import de.anomic.http.HttpResponse;import de.anomic.http.httpdByteCountInputStream;import de.anomic.index.indexURLReference;import de.anomic.plasma.plasmaCrawlProfile;@@ -71,9 +74,10 @@ import de.anomic.yacy.yacyURL;/*** Class to parse a sitemap file.<br>* An example sitemap file is depicted below:<br>+ ** <pre>- * <?xml version="1.0" encoding="UTF-8"?>- * <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">+ * <?xml version="1.0" encoding="UTF-8"?>+ * <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">* <url>* <loc>http://www.example.com/</loc>* <lastmod>2005-01-01</lastmod>@@ -83,292 +87,281 @@ import de.anomic.yacy.yacyURL;* </urlset>* </pre>*- * A real example can be found here: http://www.xt-service.de/sitemap.xml- * An example robots.txt containing a sitemap URL: http://notepad.emaillink.de/robots.txt+ * A real example can be found here: http://www.xt-service.de/sitemap.xml An example robots.txt containing a sitemap+ * URL: http://notepad.emaillink.de/robots.txt** @see Protocol at sitemaps.org <a href="http://www.sitemaps.org/protocol.php">http://www.sitemaps.org/protocol.php</a>- * @see Protocol at google.com <a href="https://www.google.com/webmasters/tools/docs/en/protocol.html">https://www.google.com/webmasters/tools/docs/en/protocol.html</a>+ * @see Protocol at google.com <a+ * href="https://www.google.com/webmasters/tools/docs/en/protocol.html">https://www.google.com/webmasters/tools/docs/en/protocol.html</a>*/public class SitemapParser extends DefaultHandler {- public static final String XMLNS_SITEMAPS_ORG = "http://www.sitemaps.org/schemas/sitemap/0.9";- public static final String XMLNS_SITEMAPS_GOOGLE = "http://www.google.com/schemas/sitemap/0.84";-- public static final String SITEMAP_XMLNS = "xmlns";- public static final String SITEMAP_URLSET = "urlset";- public static final String SITEMAP_URL = "url";- public static final String SITEMAP_URL_LOC = "loc";- public static final String SITEMAP_URL_LASTMOD = "lastmod";- public static final String SITEMAP_URL_CHANGEFREQ = "changefreq";- public static final String SITEMAP_URL_PRIORITY = "priority";-- /**- * The crawling profile used to parse the URLs contained in the sitemap file- */- private plasmaCrawlProfile.entry crawlingProfile = null;-- /**- * Reference to the plasmaswitchboard.- */- private plasmaSwitchboard switchboard = null;-- /**- * Name of the current XML element- */- private String currentElement = null;-- /**- * A special stream to count how many bytes were processed so far- */- private httpdByteCountInputStream counterStream;-- /**- * The total length of the sitemap file- */- private long contentLength;-- /**- * The amount of urls processes so far- */- private int urlCounter = 0;-- /**- * the logger- */- private serverLog logger = new serverLog("SITEMAP");-- /**- * The location of the sitemap file- */- private yacyURL siteMapURL = null;-- /**- * The next URL to enqueue- */- private String nextURL = null;-- /**- * last modification date of the {@link #nextURL}- */- private Date lastMod = null;--- public SitemapParser(plasmaSwitchboard sb, yacyURL sitemap, plasmaCrawlProfile.entry theCrawlingProfile) {- if (sb == null) throw new NullPointerException("The switchboard must not be null");- if (sitemap == null) throw new NullPointerException("The sitemap URL must not be null");- this.switchboard = sb;- this.siteMapURL = sitemap;-- if (theCrawlingProfile == null) {- // create a new profile- this.crawlingProfile = createProfile(this.siteMapURL.getHost(), this.siteMapURL);- } else {- // use an existing profile- this.crawlingProfile = theCrawlingProfile;- }- }-- /**- * Function to download and parse the sitemap file- */- public void parse() {- // download document- httpc remote = null;- try {- remote = new httpc(- this.siteMapURL.getHost(),- this.siteMapURL.getHost(),- this.siteMapURL.getPort(),- 5000,- this.siteMapURL.getProtocol().equalsIgnoreCase("https"),- switchboard.remoteProxyConfig, null, null);-- httpc.response res = remote.GET(this.siteMapURL.getFile(), null);- if (res.statusCode != 200) {- this.logger.logWarning("Unable to download the sitemap file " + this.siteMapURL + "\nServer returned status: " + res.status);- return;- }-- // getting some metadata- String contentMimeType = res.responseHeader.mime();- this.contentLength = res.responseHeader.contentLength();-- InputStream contentStream = res.getContentInputStream();- if ((contentMimeType != null) && (- contentMimeType.equals("application/x-gzip") ||- contentMimeType.equals("application/gzip")- )) {- this.logger.logFine("Sitemap file has mimetype " + contentMimeType);- contentStream = new GZIPInputStream(contentStream);- }-- this.counterStream = new httpdByteCountInputStream(contentStream,null);-- // parse it- this.logger.logInfo("Start parsing sitemap file " + this.siteMapURL- + "\n\tMimeType: " + contentMimeType- + "\n\tLength: " + this.contentLength);- SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();- saxParser.parse(this.counterStream, this);- remote.close();- } catch (Exception e) {- this.logger.logWarning("Unable to parse sitemap file " + this.siteMapURL,e);- }- }-- /**- * @return the total length of the sitemap file in bytes or <code>-1</code> if the length is unknown- */- public long getTotalLength() {- return this.contentLength;- }-- /**- * @return the amount of bytes of the sitemap file that were downloaded so far- */- public long getProcessedLength() {- return (this.counterStream==null)?0:this.counterStream.getCount();- }-- /**- * @return the amount of URLs that were successfully enqueued so far- */- public long getUrlcount() {- return this.urlCounter;- }-- /**- * @param localName local name- * @param qName qualified name- * @see DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)- */- public void startElement(- String namespaceURI,- String localName,- String qName,- Attributes attrs) throws SAXException {- this.currentElement = qName;-- // testing if the namespace is known- if (qName.equalsIgnoreCase(SITEMAP_URLSET)) {- String namespace = attrs.getValue(SITEMAP_XMLNS);- if ((namespace == null) ||- ((!namespace.equals(XMLNS_SITEMAPS_ORG)) &&- (!namespace.equals(XMLNS_SITEMAPS_GOOGLE)))- ) throw new SAXException("Unknown sitemap namespace: " + namespace);- }- }-- /**- * @param localName local name- * @param qName qualified name- * @throws SAXException- * @see DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)- */- public void endElement(- String namespaceURI,- String localName,- String qName ) throws SAXException {- this.currentElement = "";-- if (qName.equalsIgnoreCase(SITEMAP_URL)) {- if (this.nextURL == null) return;-- // get the url hash- String nexturlhash = null;+ public static final String XMLNS_SITEMAPS_ORG = "http://www.sitemaps.org/schemas/sitemap/0.9";+ public static final String XMLNS_SITEMAPS_GOOGLE = "http://www.google.com/schemas/sitemap/0.84";++ public static final String SITEMAP_XMLNS = "xmlns";+ public static final String SITEMAP_URLSET = "urlset";+ public static final String SITEMAP_URL = "url";+ public static final String SITEMAP_URL_LOC = "loc";+ public static final String SITEMAP_URL_LASTMOD = "lastmod";+ public static final String SITEMAP_URL_CHANGEFREQ = "changefreq";+ public static final String SITEMAP_URL_PRIORITY = "priority";++ /**+ * The crawling profile used to parse the URLs contained in the sitemap file+ */+ private plasmaCrawlProfile.entry crawlingProfile = null;++ /**+ * Reference to the plasmaswitchboard.+ */+ private plasmaSwitchboard switchboard = null;++ /**+ * Name of the current XML element+ */+ private String currentElement = null;++ /**+ * A special stream to count how many bytes were processed so far+ */+ private int streamCounter = 0;++ /**+ * The total length of the sitemap file+ */+ private long contentLength;++ /**+ * The amount of urls processes so far+ */+ private int urlCounter = 0;++ /**+ * the logger+ */+ private serverLog logger = new serverLog("SITEMAP");++ /**+ * The location of the sitemap file+ */+ private yacyURL siteMapURL = null;++ /**+ * The next URL to enqueue+ */+ private String nextURL = null;++ /**+ * last modification date of the {@link #nextURL}+ */+ private Date lastMod = null;++ public SitemapParser(plasmaSwitchboard sb, yacyURL sitemap, plasmaCrawlProfile.entry theCrawlingProfile) {+ if (sb == null)+ throw new NullPointerException("The switchboard must not be null");+ if (sitemap == null)+ throw new NullPointerException("The sitemap URL must not be null");+ this.switchboard = sb;+ this.siteMapURL = sitemap;++ if (theCrawlingProfile == null) {+ // create a new profile+ this.crawlingProfile = createProfile(this.siteMapURL.getHost(), this.siteMapURL);+ } else {+ // use an existing profile+ this.crawlingProfile = theCrawlingProfile;+ }+ }++ /**+ * Function to download and parse the sitemap file+ */+ public void parse() {+ // download document+ HttpClient client = HttpFactory.newClient();+ client.setTimeout(5000);+ HttpResponse res = null;+ try {+ res = client.GET(siteMapURL.toString());+ if (res.getStatusCode() != 200) {+ this.logger.logWarning("Unable to download the sitemap file " + this.siteMapURL ++ "\nServer returned status: " + res.getStatusLine());+ return;+ }++ // getting some metadata+ String contentMimeType = res.getResponseHeader().mime();+ this.contentLength = res.getResponseHeader().contentLength();++ try {+ InputStream contentStream = res.getDataAsStream();+ if ((contentMimeType != null) &&+ (contentMimeType.equals("application/x-gzip") || contentMimeType.equals("application/gzip"))) {+ this.logger.logFine("Sitemap file has mimetype " + contentMimeType);+ contentStream = new GZIPInputStream(contentStream);+ }++ httpdByteCountInputStream counterStream = new httpdByteCountInputStream(contentStream, null);+ // parse it+ this.logger.logInfo("Start parsing sitemap file " + this.siteMapURL + "\n\tMimeType: " + contentMimeType ++ "\n\tLength: " + this.contentLength);+ SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();+ saxParser.parse(counterStream, this);+ streamCounter += counterStream.getCount();+ } finally {+ res.closeStream();+ }+ } catch (Exception e) {+ this.logger.logWarning("Unable to parse sitemap file " + this.siteMapURL, e);+ } finally {+ if (res != null) {+ // release connection+ res.closeStream();+ }+ }+ }++ /**+ * @return the total length of the sitemap file in bytes or <code>-1</code> if the length is unknown+ */+ public long getTotalLength() {+ return this.contentLength;+ }++ /**+ * @return the amount of bytes of the sitemap file that were downloaded so far+ */+ public long getProcessedLength() {+ return streamCounter;+ }++ /**+ * @return the amount of URLs that were successfully enqueued so far+ */+ public long getUrlcount() {+ return this.urlCounter;+ }++ /**+ * @param localName local name+ * @param qName qualified name+ * @see DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)+ */+ public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException {+ this.currentElement = qName;++ // testing if the namespace is known+ if (qName.equalsIgnoreCase(SITEMAP_URLSET)) {+ String namespace = attrs.getValue(SITEMAP_XMLNS);+ if ((namespace == null) ||+ ((!namespace.equals(XMLNS_SITEMAPS_ORG)) && (!namespace.equals(XMLNS_SITEMAPS_GOOGLE))))+ throw new SAXException("Unknown sitemap namespace: " + namespace);+ }+ }++ /**+ * @param localName local name+ * @param qName qualified name+ * @throws SAXException+ * @see DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)+ */+ public void endElement(String namespaceURI, String localName, String qName) throws SAXException {+ this.currentElement = "";++ if (qName.equalsIgnoreCase(SITEMAP_URL)) {+ if (this.nextURL == null)+ return;++ // get the url hash+ String nexturlhash = null;yacyURL url = null;try {url = new yacyURL(this.nextURL, null);nexturlhash = url.hash();- } catch (MalformedURLException e1) {}-- // check if the url is known and needs to be recrawled- if (this.lastMod != null) {- String dbocc = this.switchboard.urlExists(nexturlhash);- if ((dbocc != null) && (dbocc.equalsIgnoreCase("loaded"))) {- // the url was already loaded. we need to check the date- indexURLReference oldEntry = switchboard.wordIndex.getURL(nexturlhash, null, 0);- if (oldEntry != null) {- Date modDate = oldEntry.moddate();- // check if modDate is null- if (modDate.after(this.lastMod)) return;- }- }- }--- // URL needs to crawled- String error = null;- error = this.switchboard.crawlStacker.stackCrawl(- url,- null, // this.siteMapURL.toString(),- yacyCore.seedDB.mySeed().hash,- this.nextURL,- new Date(),- 0,- this.crawlingProfile- );-- if (error != null) {- try {- this.logger.logInfo("The URL '" + this.nextURL + "' can not be crawled. Reason: " + error);-- // insert URL into the error DB- plasmaCrawlZURL.Entry ee = this.switchboard.crawlQueues.errorURL.newEntry(new yacyURL(this.nextURL, null), error);+ } catch (MalformedURLException e1) {+ }++ // check if the url is known and needs to be recrawled+ if (this.lastMod != null) {+ String dbocc = this.switchboard.urlExists(nexturlhash);+ if ((dbocc != null) && (dbocc.equalsIgnoreCase("loaded"))) {+ // the url was already loaded. we need to check the date+ indexURLReference oldEntry = switchboard.wordIndex.getURL(nexturlhash, null, 0);+ if (oldEntry != null) {+ Date modDate = oldEntry.moddate();+ // check if modDate is null+ if (modDate.after(this.lastMod))+ return;+ }+ }+ }++ // URL needs to crawled+ String error = null;+ error = this.switchboard.crawlStacker.stackCrawl(url,+ null, // this.siteMapURL.toString(),+ yacyCore.seedDB.mySeed().hash, this.nextURL, new Date(),+ 0, this.crawlingProfile);++ if (error != null) {+ try {+ this.logger.logInfo("The URL '" + this.nextURL + "' can not be crawled. Reason: " + error);++ // insert URL into the error DB+ plasmaCrawlZURL.Entry ee = this.switchboard.crawlQueues.errorURL.newEntry(new yacyURL(this.nextURL,+ null), error);ee.store();- this.switchboard.crawlQueues.errorURL.push(ee);- } catch (MalformedURLException e) {/* ignore this */ }- } else {- this.logger.logInfo("New URL '" + this.nextURL + "' added for crawling.");-- // count successfully added URLs- this.urlCounter++;- }- }- }-- public void characters(char[] buf, int offset, int len) throws SAXException {- if (this.currentElement.equalsIgnoreCase(SITEMAP_URL_LOC)) {- // TODO: we need to decode the URL here- this.nextURL =(new String(buf,offset,len)).trim();- if (!this.nextURL.startsWith("http") && !this.nextURL.startsWith("https")) {- this.logger.logInfo("The url '" + this.nextURL + "' has a wrong format. Ignore it.");- this.nextURL = null;- }- } else if (this.currentElement.equalsIgnoreCase(SITEMAP_URL_LASTMOD)) {- String dateStr = new String(buf,offset,len);- try {- this.lastMod = serverDate.parseISO8601(dateStr);- } catch (ParseException e) {- this.logger.logInfo("Unable to parse datestring '" + dateStr + "'");- }- }- }-- private plasmaCrawlProfile.entry createProfile(String domainName, yacyURL sitemapURL) {- return this.switchboard.profilesActiveCrawls.newEntry(- domainName,- sitemapURL,- // crawlingFilter- ".*", ".*",- // Depth- 0, 0,- // force recrawling- 0,- // disable Auto-Dom-Filter- -1, -1,- // allow crawling of dynamic URLs- true,- // index text + media- true, true,- // don't store downloaded pages to Web Cache- false,- // store to TX cache- true,- // remote Indexing disabled- false,- // exclude stop-words- true, true, true- );- }-}+ this.switchboard.crawlQueues.errorURL.push(ee);+ } catch (MalformedURLException e) {/* ignore this */+ }+ } else {+ this.logger.logInfo("New URL '" + this.nextURL + "' added for crawling.");+ // count successfully added URLs+ this.urlCounter++;+ }+ }+ }++ public void characters(char[] buf, int offset, int len) throws SAXException {+ if (this.currentElement.equalsIgnoreCase(SITEMAP_URL_LOC)) {+ // TODO: we need to decode the URL here+ this.nextURL = (new String(buf, offset, len)).trim();+ if (!this.nextURL.startsWith("http") && !this.nextURL.startsWith("https")) {+ this.logger.logInfo("The url '" + this.nextURL + "' has a wrong format. Ignore it.");+ this.nextURL = null;+ }+ } else if (this.currentElement.equalsIgnoreCase(SITEMAP_URL_LASTMOD)) {+ String dateStr = new String(buf, offset, len);+ try {+ this.lastMod = serverDate.parseISO8601(dateStr);+ } catch (ParseException e) {+ this.logger.logInfo("Unable to parse datestring '" + dateStr + "'");+ }+ }+ }++ private plasmaCrawlProfile.entry createProfile(String domainName, yacyURL sitemapURL) {+ return this.switchboard.profilesActiveCrawls.newEntry(domainName, sitemapURL,+ // crawlingFilter+ ".*", ".*",+ // Depth+ 0, 0,+ // force recrawling+ 0,+ // disable Auto-Dom-Filter+ -1, -1,+ // allow crawling of dynamic URLs+ true,+ // index text + media+ true, true,+ // don't store downloaded pages to Web Cache+ false,+ // store to TX cache+ true,+ // remote Indexing disabled+ false,+ // exclude stop-words+ true, true, true);+ }+}diff --git a/source/de/anomic/data/listManager.java b/source/de/anomic/data/listManager.javaindex 4f668b1f3..4da155ac4 100644--- a/source/de/anomic/data/listManager.java+++ b/source/de/anomic/data/listManager.java@@ -60,8 +60,8 @@ import java.util.Set;import java.util.Vector;import de.anomic.index.indexAbstractReferenceBlacklist;-import de.anomic.plasma.plasmaSwitchboard;import de.anomic.index.indexReferenceBlacklist.blacklistFile;+import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverCore;// The Naming of the functions is a bit strange...diff --git a/source/de/anomic/data/robotsParser.java b/source/de/anomic/data/robotsParser.javaindex 2882f5223..ff6d84c96 100644--- a/source/de/anomic/data/robotsParser.java+++ b/source/de/anomic/data/robotsParser.java@@ -54,8 +54,11 @@ import java.net.URLDecoder;import java.util.ArrayList;import java.util.Date;+import de.anomic.http.HttpClient;+import de.anomic.http.HttpFactory;+import de.anomic.http.HttpResponse;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;+import de.anomic.http.HttpResponse.Saver;import de.anomic.plasma.plasmaCrawlRobotsTxt;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverByteBuffer;@@ -380,47 +383,46 @@ 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();- //TODO: adding Traffic statistic for robots download?- con = new httpc(robotsURL.getHost(), robotsURL.getHost(), robotsURL.getPort(), 10000, robotsURL.getProtocol().equalsIgnoreCase("https"), sb.remoteProxyConfig, null, null);-- // if we previously have downloaded this robots.txt then we can set the if-modified-since header- httpHeader reqHeaders = new httpHeader();-- // adding referer- reqHeaders.put(httpHeader.REFERER, (yacyURL.newURL(robotsURL,"/")).toNormalform(true, true));-- if (entry != null) {- oldEtag = entry.getETag();- reqHeaders = new httpHeader();- Date modDate = entry.getModDate();- if (modDate != null) reqHeaders.put(httpHeader.IF_MODIFIED_SINCE,httpc.dateString(entry.getModDate()));-- }+ downloadStart = System.currentTimeMillis();++ // if we previously have downloaded this robots.txt then we can set the if-modified-since header+ httpHeader reqHeaders = new httpHeader();++ // adding referer+ reqHeaders.put(httpHeader.REFERER, (yacyURL.newURL(robotsURL,"/")).toNormalform(true, true));++ if (entry != null) {+ oldEtag = entry.getETag();+ reqHeaders = new httpHeader();+ Date modDate = entry.getModDate();+ if (modDate != null) reqHeaders.put(httpHeader.IF_MODIFIED_SINCE,HttpClient.dateString(entry.getModDate()));+ }++ // setup http-client+ //TODO: adding Traffic statistic for robots download?+ HttpClient client = HttpFactory.newClient(reqHeaders, 10000);+ HttpResponse res = null;+ try {// sending the get request- httpc.response res = con.GET(robotsURL.getFile(), reqHeaders);+ res = client.GET(robotsURL.toString());// check for interruptionif (Thread.currentThread().isInterrupted()) throw new InterruptedException("Shutdown in progress.");// check the response status- if (res.status.startsWith("2")) {- if (!res.responseHeader.mime().startsWith("text/plain")) {+ if (res.getStatusLine().startsWith("2")) {+ if (!res.getResponseHeader().mime().startsWith("text/plain")) {robotsTxt = null;- serverLog.logFinest("ROBOTS","Robots.txt from URL '" + robotsURL + "' has wrong mimetype '" + res.responseHeader.mime() + "'.");- con.close();+ serverLog.logFinest("ROBOTS","Robots.txt from URL '" + robotsURL + "' has wrong mimetype '" + res.getResponseHeader().mime() + "'.");} else {// getting some metadata- eTag = res.responseHeader.containsKey(httpHeader.ETAG)?((String)res.responseHeader.get(httpHeader.ETAG)).trim():null;- lastMod = res.responseHeader.lastModified();+ eTag = res.getResponseHeader().containsKey(httpHeader.ETAG)?((String)res.getResponseHeader().get(httpHeader.ETAG)).trim():null;+ lastMod = res.getResponseHeader().lastModified();// if the robots.txt file was not changed we break hereif ((eTag != null) && (oldEtag != null) && (eTag.equals(oldEtag))) {@@ -430,22 +432,19 @@ public final class robotsParser{// downloading the contentserverByteBuffer sbb = new serverByteBuffer();- res.writeContent(sbb, null);+ Saver.writeContent(res, sbb, null);robotsTxt = sbb.getBytes();- con.close();downloadEnd = System.currentTimeMillis();serverLog.logFinest("ROBOTS","Robots.txt successfully loaded from URL '" + robotsURL + "' in " + (downloadEnd-downloadStart) + " ms.");}- } else if (res.status.startsWith("304")) {- con.close();+ } else if (res.getStatusCode() == 304) {return null;- } else if (res.status.startsWith("3")) {+ } else if (res.getStatusLine().startsWith("3")) {// getting redirection URL- String redirectionUrlString = (String) res.responseHeader.get(httpHeader.LOCATION);- con.close();+ String redirectionUrlString = (String) res.getResponseHeader().get(httpHeader.LOCATION);if (redirectionUrlString==null) {- serverLog.logFinest("ROBOTS","robots.txt could not be downloaded from URL '" + robotsURL + "' because of missing redirecton header. [" + res.status + "].");+ serverLog.logFinest("ROBOTS","robots.txt could not be downloaded from URL '" + robotsURL + "' because of missing redirecton header. [" + res.getStatusLine() + "].");robotsTxt = null;}@@ -459,17 +458,20 @@ public final class robotsParser{"\nRedirecting request to: " + redirectionUrl);return downloadRobotsTxt(redirectionUrl,redirectionCount,entry);- } else if (res.status.startsWith("401") || res.status.startsWith("403")) {- con.close();+ } else if (res.getStatusCode() == 401 || res.getStatusCode() == 403) {accessCompletelyRestricted = true;serverLog.logFinest("ROBOTS","Access to Robots.txt not allowed on URL '" + robotsURL + "'.");} else {- serverLog.logFinest("ROBOTS","robots.txt could not be downloaded from URL '" + robotsURL + "'. [" + res.status + "].");- con.close();+ serverLog.logFinest("ROBOTS","robots.txt could not be downloaded from URL '" + robotsURL + "'. [" + res.getStatusLine() + "].");robotsTxt = null;}} catch (Exception e) {throw e;+ } finally {+ if(res != null) {+ // release connection+ res.closeStream();+ }}return new Object[]{new Boolean(accessCompletelyRestricted),robotsTxt,eTag,lastMod};}diff --git a/source/de/anomic/htmlFilter/htmlFilterContentScraper.java b/source/de/anomic/htmlFilter/htmlFilterContentScraper.javaindex 94d56e914..ff4c6931e 100644--- a/source/de/anomic/htmlFilter/htmlFilterContentScraper.java+++ b/source/de/anomic/htmlFilter/htmlFilterContentScraper.java@@ -63,8 +63,7 @@ import java.util.TreeSet;import javax.swing.event.EventListenerList;-import de.anomic.http.httpc;-import de.anomic.plasma.plasmaSwitchboard;+import de.anomic.http.HttpClient;import de.anomic.server.serverCharBuffer;import de.anomic.server.serverFileUtils;import de.anomic.yacy.yacyURL;@@ -112,12 +111,12 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemenprivate EventListenerList htmlFilterEventListeners = new EventListenerList();/**- * {@link URL} to the favicon that belongs to the document+ * {@link yacyURL} to the favicon that belongs to the document*/private yacyURL favicon;/**- * The document root {@link URL}+ * The document root {@link yacyURL}*/private yacyURL root;@@ -371,7 +370,7 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemen}/**- * @return the {@link URL} to the favicon that belongs to the document+ * @return the {@link yacyURL} to the favicon that belongs to the document*/public yacyURL getFavicon() {return this.favicon;@@ -516,16 +515,7 @@ public class htmlFilterContentScraper extends htmlFilterAbstractScraper implemenpublic static htmlFilterContentScraper parseResource(yacyURL location) throws IOException {// load page- byte[] page = httpc.wget(- location,- location.getHost(),- 10000,- null,- null,- plasmaSwitchboard.getSwitchboard().remoteProxyConfig,- null,- null- );+ byte[] page = HttpClient.wget(location.toString());if (page == null) throw new IOException("no response from url " + location.toString());// scrape contentdiff --git a/source/de/anomic/htmlFilter/htmlFilterWriter.java b/source/de/anomic/htmlFilter/htmlFilterWriter.javaindex a343738e0..208e43d4a 100644--- a/source/de/anomic/htmlFilter/htmlFilterWriter.java+++ b/source/de/anomic/htmlFilter/htmlFilterWriter.java@@ -490,10 +490,16 @@ public final class htmlFilterWriter extends Writer {}private static boolean binaryHint(char c) {-// return Character.isDefined(c);- if (c < 0) return false;- if (c > 31) return false;- if ((c == 8) || (c == 9) || (c == 10) || (c == 13)) return false;+ // space, punctiation and symbols, letters and digits (ASCII/latin)+ if (c > 31 && c < 128) return false;+ // 8 = backspace+ // 9 = horizontal tab+ // 10 = new line (line feed)+ // 11 = vertical tab+ // 12 = new page (form feed)+ // 13 = carriage return+ if (c > 7 && c <= 13) return false;+ //if (Character.isLetterOrDigit(c)) return false;// return false;// System.out.println("BINARY HINT: " + (int) b);return true;diff --git a/source/de/anomic/http/HttpClient.java b/source/de/anomic/http/HttpClient.javanew file mode 100644index 000000000..656aa8d60--- /dev/null+++ b/source/de/anomic/http/HttpClient.java@@ -0,0 +1,263 @@+// HttpClient.java+// (C) 2008 by Daniel Raap; [email protected]+// first published 2.4.2008 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate: 2008-03-14 01:16:04 +0100 (Fr, 14 Mrz 2008) $+// $LastChangedRevision: 4558 $+// $LastChangedBy: orbiter $+//+// LICENSE+//+// This program is free software; you can redistribute it and/or modify+// it under the terms of the GNU General Public License as published by+// the Free Software Foundation; either version 2 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+package de.anomic.http;++import java.io.IOException;+import java.util.Date;+import java.util.Map;++import de.anomic.server.logging.serverLog;++/**+ * Client who does http requests+ *+ * some methods must be implemented (the "socket-layer")+ */+public abstract class HttpClient {+ private static final String systemOST;+ static {+ // provide system information for client identification+ String loc = generateLocation();+ systemOST =+ System.getProperty("os.arch", "no-os-arch") + " " ++ System.getProperty("os.name", "no-os-name") + " " ++ System.getProperty("os.version", "no-os-version") + "; " ++ "java " + System.getProperty("java.version", "no-java-version") + "; " + loc;+ }++ /**+ * generating the location string+ *+ * @return+ */+ public static String generateLocation() {+ String loc = System.getProperty("user.timezone", "nowhere");+ final int p = loc.indexOf("/");+ if (p > 0) loc = loc.substring(0,p);+ loc = loc + "/" + System.getProperty("user.language", "dumb");+ return loc;+ }++ /**+ * @return the systemOST+ */+ public static String getSystemOST() {+ return systemOST;+ }++ /**+ * "This method can be used for obtaining metainformation about the entity implied by the request without+ * transferring the entity-body itself" [RFC 2616, sect. 9.4]+ *+ * @param uri+ * @return response header+ * @throws IOException if data cannot be read+ */+ public abstract HttpResponse HEAD(String uri) throws IOException;++ /**+ * "The GET method means retrieve whatever information [...] is identified by the Request-URI" [RFC 2616, sect. 9.3]+ *+ * @param uri+ * @return response body+ * @throws IOException if data cannot be read+ */+ public abstract HttpResponse GET(String uri) throws IOException;++ /**+ * "Providing a block of data [...] to a data-handling process;" [RFC 2616, sect. 9.5]+ *+ * @param uri+ * @param nameDataPairs+ * @return response body+ * @throws IOException if data cannot be read+ */+ public abstract HttpResponse POST(String uri, Map<String, ?> nameDataPairs) throws IOException;++ /**+ * "for use with a proxy that can dynamically switch to being a tunnel" [RFC 2616, sect. 9.9]+ *+ * @param host+ * @param port+ * @return+ * @throws IOException+ */+ public abstract HttpResponse CONNECT(String host, int port) throws IOException;++ /**+ * use proxyConfig to establish the connection+ *+ * @param proxyConfig+ */+ public abstract void setProxy(httpRemoteProxyConfig proxyConfig);++ /**+ * sets the header for all coming requests+ *+ * @param header may be null+ */+ public abstract void setHeader(httpHeader header);++ /**+ * sets the timeout in milliseconds+ *+ * @param timeout+ */+ public abstract void setTimeout(int timeout);++ /**+ * gives the user-agent used by this http-client+ *+ * @return+ */+ public abstract String getUserAgent();++ /**+ * Returns the given date in an HTTP-usable format. (according to RFC1123/RFC822)+ *+ * @param date The Date-Object to be converted.+ * @return String with the date.+ */+ public abstract String date2String(Date date);++ /**+ * for easy access+ * @see date2String(Date)+ * @param date+ * @return+ */+ public static String dateString(Date date) {+ return HttpFactory.newClient().date2String(date);+ }++ /**+ * Gets a page (as raw bytes)+ *+ * @param uri+ * @return+ */+ public static byte[] wget(final String uri) {+ return wget(uri, null, null);+ }++ /**+ * Gets a page (as raw bytes) addressing vhost at host in uri+ *+ * @param uri+ * @param vhost used if host in uri cannot be resolved (yacy tld)+ * @return+ */+ public static byte[] wget(final String uri, final String vhost) {+ return wget(uri, null, vhost);+ }++ /**+ * Gets a page (as raw bytes) with specified header+ *+ * @param uri+ * @param header+ * @return+ */+ public static byte[] wget(final String uri, final httpHeader header) {+ return wget(uri, header, null);+ }++ /**+ * Gets a page (as raw bytes) addressing vhost at host in uri with specified header+ *+ * @param uri+ * @param header+ * @param vhost+ * @return+ * @assert uri != null+ */+ public static byte[] wget(final String uri, httpHeader header, final String vhost) {+ assert uri != null : "precondition violated: uri != null";+ final HttpClient client = HttpFactory.newClient();++ // set header+ header = addHostHeader(header, vhost);+ client.setHeader(header);++ // do the request+ try {+ final HttpResponse response = client.GET(uri);+ return response.getData();+ } catch (final IOException e) {+ serverLog.logWarning("HTTPC", "wget(" + uri + ") failed: " + e.getMessage());+ }+ return null;+ }++ /**+ * adds a Host-header to the header if vhost is not null+ *+ * @param header+ * @param vhost+ * @return+ */+ private static httpHeader addHostHeader(httpHeader header, final String vhost) {+ if (vhost != null) {+ if (header != null) {+ header = new httpHeader();+ }+ // set host-header+ header.add(httpHeader.HOST, vhost);+ }+ return header;+ }++ /**+ * Gets a page-header+ *+ * @param uri+ * @return+ */+ public static httpHeader whead(final String uri) {+ return whead(uri, null);+ }++ /**+ * Gets a page-header+ *+ * @param uri+ * @param header request header+ * @return+ */+ public static httpHeader whead(final String uri, final httpHeader header) {+ final de.anomic.http.HttpClient client = HttpFactory.newClient();+ if (header != null) {+ client.setHeader(header);+ }+ try {+ final HttpResponse response = client.HEAD(uri);+ return response.getResponseHeader();+ } catch (final IOException e) {+ serverLog.logWarning("HTTPC", "whead(" + uri + ") failed: " + e.getMessage());+ }+ return null;+ }+}diff --git a/source/de/anomic/http/HttpFactory.java b/source/de/anomic/http/HttpFactory.javanew file mode 100644index 000000000..7e8b01af6--- /dev/null+++ b/source/de/anomic/http/HttpFactory.java@@ -0,0 +1,64 @@+// HttpFactory.java+// (C) 2008 by Daniel Raap; [email protected]+// first published 03.04.2008 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate: 2008-03-14 01:16:04 +0100 (Fr, 14 Mrz 2008) $+// $LastChangedRevision: 4558 $+// $LastChangedBy: orbiter $+//+// LICENSE+//+// This program is free software; you can redistribute it and/or modify+// it under the terms of the GNU General Public License as published by+// the Free Software Foundation; either version 2 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA++package de.anomic.http;++/**+ * generates generic Objects used in this package+ *+ * @author danielr+ */+public class HttpFactory {+ /**+ * no instances+ */+ private HttpFactory() {+ }++ /**+ * generates a new HttpClient object+ *+ * @return+ */+ public static HttpClient newClient() {+ return new JakartaCommonsHttpClient();+ }++ /**+ * generates a new HttpClient object with given header and timeout+ *+ * @param header+ * @param timeout+ * @return+ */+ public static HttpClient newClient(httpHeader header, int timeout) {+ HttpClient client = new JakartaCommonsHttpClient();+ client.setTimeout(timeout);+ client.setHeader(header);+ return client;+ }++}diff --git a/source/de/anomic/http/HttpResponse.java b/source/de/anomic/http/HttpResponse.javanew file mode 100644index 000000000..a1d2cbd6a--- /dev/null+++ b/source/de/anomic/http/HttpResponse.java@@ -0,0 +1,127 @@+// HttpResponse.java+// (C) 2008 by Daniel Raap; [email protected]+// first published 2.4.2008 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate: 2008-03-14 01:16:04 +0100 (Fr, 14 Mrz 2008) $+// $LastChangedRevision: 4558 $+// $LastChangedBy: orbiter $+//+// LICENSE+//+// This program is free software; you can redistribute it and/or modify+// it under the terms of the GNU General Public License as published by+// the Free Software Foundation; either version 2 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+package de.anomic.http;++import java.io.IOException;+import java.io.InputStream;+import java.io.OutputStream;+import java.io.OutputStreamWriter;+import java.io.UnsupportedEncodingException;+import java.io.Writer;++import de.anomic.tools.StreamTools;++/**+ * @author daniel+ *+ */+public interface HttpResponse {++ /**+ * returns the header as {@link de.anomic.http.httpHeader}+ * @return+ */+ public abstract httpHeader getResponseHeader();++ /**+ * get the body of the response+ * @return the data+ * @throws IOException+ */+ public abstract byte[] getData() throws IOException;++ /**+ * returns a stream to read the body of the response+ *+ * <strong>Important: When done call <code>closeStream()</code>!</strong>+ * @return+ * @throws IOException+ */+ public abstract InputStream getDataAsStream() throws IOException;++ /**+ * closes the input stream+ */+ public abstract void closeStream();++ /**+ * "Statuscode SPACE Statusmessage"+ * @return the statusLine+ */+ public abstract String getStatusLine();++ /**+ * the status code of this response+ * @return+ * @ensure result >= 100 && result <= 999 (is a 3-digit integer)+ */+ public abstract int getStatusCode();++ /**+ * HTTP version of the response+ * @return+ */+ public abstract String getHttpVer();++ /**+ * save a response to some storage+ * @author daniel+ *+ */+ public static class Saver {++ /**+ * copies the body of the response accordingly to hfos to the destination+ * @param res+ * @param hfos OutputStream (raw bytes) or Writer (decode to characters)+ * @param byteStream additional OutputStream where data is stored+ * @throws IOException+ * @throws UnsupportedEncodingException+ */+ public static void writeContent(HttpResponse res, Object hfos, OutputStream byteStream) throws IOException,+ UnsupportedEncodingException {+ try {+ InputStream data = res.getDataAsStream();+ if (hfos instanceof OutputStream) {+ OutputStream[] streams = (byteStream == null ? new OutputStream[] { (OutputStream) hfos }+ : new OutputStream[] { (OutputStream) hfos, byteStream });+ StreamTools.copyToStreams(data, streams);+ } else if (hfos instanceof Saver) {+ String charSet = httpHeader.getCharSet(res.getResponseHeader());+ Writer[] writers = (byteStream == null ? new Writer[] { (Writer) hfos } : new Writer[] { (Writer) hfos,+ new OutputStreamWriter(byteStream, charSet) });+ StreamTools.copyToWriters(data, writers, charSet);+ } else {+ throw new IOException("cannot save data: hfos-type ("+ hfos.getClass().toString() +") not supported!");+ }+ } finally {+ res.closeStream();+ }+ }++ }++}\ No newline at end of filediff --git a/source/de/anomic/http/JakartaCommonsHttpClient.java b/source/de/anomic/http/JakartaCommonsHttpClient.javanew file mode 100644index 000000000..e6f49cec3--- /dev/null+++ b/source/de/anomic/http/JakartaCommonsHttpClient.java@@ -0,0 +1,503 @@+// JakartaCommonsHttpClient.java+// (C) 2008 by Daniel Raap; [email protected]+// first published 2.4.2008 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate: 2008-03-14 01:16:04 +0100 (Fr, 14 Mrz 2008) $+// $LastChangedRevision: 4558 $+// $LastChangedBy: orbiter $+//+// LICENSE+//+// This program is free software; you can redistribute it and/or modify+// it under the terms of the GNU General Public License as published by+// the Free Software Foundation; either version 2 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+package de.anomic.http;++import java.io.ByteArrayOutputStream;+import java.io.File;+import java.io.FileInputStream;+import java.io.IOException;+import java.io.InputStream;+import java.io.OutputStream;+import java.util.Date;+import java.util.HashMap;+import java.util.Map;++import org.apache.commons.httpclient.ConnectMethod;+import org.apache.commons.httpclient.Header;+import org.apache.commons.httpclient.HostConfiguration;+import org.apache.commons.httpclient.HttpClient;+import org.apache.commons.httpclient.HttpException;+import org.apache.commons.httpclient.HttpMethod;+import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;+import org.apache.commons.httpclient.methods.GetMethod;+import org.apache.commons.httpclient.methods.HeadMethod;+import org.apache.commons.httpclient.methods.InputStreamRequestEntity;+import org.apache.commons.httpclient.methods.PostMethod;+import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;+import org.apache.commons.httpclient.methods.multipart.FilePart;+import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;+import org.apache.commons.httpclient.methods.multipart.Part;+import org.apache.commons.httpclient.methods.multipart.StringPart;+import org.apache.commons.httpclient.params.HttpClientParams;+import org.apache.commons.httpclient.params.HttpMethodParams;+import org.apache.commons.httpclient.util.DateUtil;++import de.anomic.kelondro.kelondroBase64Order;+import de.anomic.server.logging.serverLog;+import de.anomic.tools.StreamTools;+import de.anomic.yacy.yacyVersion;++/**+ * HttpClient implementation which uses Jakarta Commons HttpClient 3.x {@link http://hc.apache.org/httpclient-3.x/}+ *+ * @author danielr+ *+ */+public class JakartaCommonsHttpClient extends de.anomic.http.HttpClient {+ /**+ * "the HttpClient instance and connection manager should be shared among all threads for maximum efficiency."+ * (Concurrent execution of HTTP methods, http://hc.apache.org/httpclient-3.x/performance.html)+ */+ private final static MultiThreadedHttpConnectionManager conManager = new MultiThreadedHttpConnectionManager();+ private final static HttpClient apacheHttpClient = new HttpClient(conManager);++ static {+ // set user-agent+ apacheHttpClient.getParams().setParameter(HttpClientParams.USER_AGENT,+ "yacy/" + yacyVersion.thisVersion().releaseNr ++ " (www.yacy.net; " ++ de.anomic.http.HttpClient.getSystemOST() + ") " ++ getCurrentUserAgent().replace(';', ':')); // last ; must be before location (this is parsed)+ /**+ * set options for connection manager+ */+ // conManager.getParams().setDefaultMaxConnectionsPerHost(4); // default 2+ conManager.getParams().setMaxTotalConnections(50); // default 20+ // TODO should this be configurable?+ }++ private final Map<HttpMethod, InputStream> openStreams = new HashMap<HttpMethod, InputStream>();+ private Header[] headers = new Header[0];+ private httpRemoteProxyConfig proxyConfig = null;++ /**+ * constructor+ */+ public JakartaCommonsHttpClient() {+ super();+ }++ /**+ * constructs a new Client with given parameters+ *+ * @param timeout in milliseconds+ * @param header+ * @param proxyConfig+ */+ public JakartaCommonsHttpClient(final int timeout, final httpHeader header, final httpRemoteProxyConfig proxyConfig) {+ this();+ setTimeout(timeout);+ setHeader(header);+ setProxy(proxyConfig);+ }++ /*+ * (non-Javadoc)+ *+ * @see de.anomic.http.HttpClient#setProxy(de.anomic.http.httpRemoteProxyConfig)+ */+ public void setProxy(final httpRemoteProxyConfig proxyConfig) {+ if (proxyConfig != null && proxyConfig.useProxy()) {+ this.proxyConfig = proxyConfig;+ }+ }++ /*+ * (non-Javadoc)+ *+ * @see de.anomic.http.HttpClient#setHeader(de.anomic.http.httpHeader)+ */+ public void setHeader(final httpHeader header) {+ headers = convertHeaders(header);+ }++ /*+ * (non-Javadoc)+ *+ * @see de.anomic.http.HttpClient#setTimeout(int)+ */+ public void setTimeout(final int timeout) {+ apacheHttpClient.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, timeout);+ }++ /*+ * (non-Javadoc)+ *+ * @see de.anomic.http.HttpClient#getUserAgent()+ */+ public String getUserAgent() {+ return getCurrentUserAgent();+ }++ /**+ * This method GETs a page from the server.+ *+ * @param uri The URI to the page which should be GET.+ * @return InputStream of content (body)+ * @throws IOException+ */+ public HttpResponse GET(final String uri) throws IOException {+ final HttpMethod get = new GetMethod(uri);+ return execute(get);+ }++ /**+ * This method gets only the header of a page.+ *+ * @param uri The URI to the page whose header should be get.+ * @param requestHeader Prefilled httpHeader.+ * @return Instance of response with the content.+ * @throws IOException+ */+ public HttpResponse HEAD(final String uri) throws IOException {+ assert uri != null : "precondition violated: uri != null";+ final HttpMethod head = new HeadMethod(uri);+ return execute(head);+ }++ /**+ * This method POSTs some data from an InputStream to a page.+ *+ * This is for compatibility (an InputStream does not need to contain correct HTTP!)+ *+ * @param uri The URI to the page which the post is sent to.+ * @param ins InputStream with the data to be posted to the server.+ * @return Instance of response with the content.+ * @throws IOException+ */+ public HttpResponse POST(final String uri, final InputStream ins) throws IOException {+ assert uri != null : "precondition violated: uri != null";+ assert ins != null : "precondition violated: ins != null";+ final PostMethod post = new PostMethod(uri);+ post.setRequestEntity(new InputStreamRequestEntity(ins));+ return execute(post);+ }++ /**+ * This method sends several files at once via a POST request. Only those files in the Hashtable files are written+ * whose names are contained in args.+ *+ * @param uri The URI to the page which the post is sent to.+ * @param files HashMap with the names of data as key and the content (currently implemented is File, byte[] and+ * String) of the files as value.+ * @return Instance of response with the content.+ * @throws IOException+ */+ public HttpResponse POST(final String uri, final Map<String, ?> files) throws IOException {+ assert uri != null : "precondition violated: uri != null";+ final PostMethod post = new PostMethod(uri);++ final Part[] parts;+ if (files != null) {+ parts = new Part[files.size()];+ int i = 0;+ for (final String key : files.keySet()) {+ Object value = files.get(key);+ if (value instanceof File) {+ final File file = (File) value;+ if (file.isFile() && file.canRead()) {+ // read file+ final ByteArrayOutputStream fileData = new ByteArrayOutputStream();+ StreamTools.copyToStreams(new FileInputStream(file), new OutputStream[] { fileData });+ value = fileData.toByteArray();+ }+ }+ if (value instanceof byte[]) {+ // file/binary data+ parts[i] = new FilePart(key, new ByteArrayPartSource(key, (byte[]) value));+ } else if (value instanceof String) {+ // simple text value+ parts[i] = new StringPart(key, (String) value);+ } else {+ // not supported+ final String msg = "type of POST-data not supported: " + value.getClass();+ serverLog.logSevere("HTTPC", msg);+ throw new IOException("cannot POST data: " + msg);+ // break; // post nothing is not what is expected by the caller+ }+ i++;+ }+ } else {+ // nothing to POST+ parts = new Part[0];+ }+ post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));+ return execute(post);+ }++ /*+ * (non-Javadoc)+ *+ * @see de.anomic.http.HttpClient#CONNECT(java.lang.String, int, de.anomic.http.httpHeader)+ */+ public HttpResponse CONNECT(final String host, final int port) throws IOException {+ final HostConfiguration hostConfig = new HostConfiguration();+ hostConfig.setHost(host, port);+ final HttpMethod connect = new ConnectMethod(hostConfig);+ return execute(connect);+ }++ /*+ * (non-Javadoc)+ *+ * @see de.anomic.http.HttpClient#closeStream()+ */+ public void closeStream() {+ // close all opened streams (by this instance)+ synchronized (openStreams) {+ for (final HttpMethod method : openStreams.keySet()) {+ try {+ // close stream+ openStreams.get(method).close();+ } catch (final IOException e) {+ serverLog.logSevere("HTTPC", "connection cannot be closed! will unset variable.");+ e.printStackTrace();+ } finally {+ // remove from pool+ openStreams.remove(method);+ }+ // free the connection+ method.releaseConnection();+ }+ }+ }++ /**+ * adds the yacy-header to the method+ *+ * @param requestHeader+ * @param method+ */+ public void addHeader(final httpHeader requestHeader, final HttpMethod method) {+ assert method != null : "precondition violated: method != null";+ if (requestHeader != null) {+ addHeaders(convertHeaders(requestHeader), method);+ }+ }++ /**+ * adds every Header in the array to the method+ *+ * @param requestHeaders+ * @param method must not be null+ */+ private static void addHeaders(final Header[] requestHeaders, final HttpMethod method) {+ if (method == null) {+ throw new NullPointerException("method not set");+ }+ if (requestHeaders != null) {+ for (final Header header : requestHeaders) {+ method.addRequestHeader(header);+ }+ }+ }++ /**+ * convert from yacy-header to apache.commons.httpclient.Header+ *+ * @param requestHeader+ * @return+ */+ private static Header[] convertHeaders(final httpHeader requestHeader) {+ final Header[] headers;+ if (requestHeader == null) {+ headers = new Header[0];+ } else {+ headers = new Header[requestHeader.size()];+ int i = 0;+ for (final String name : requestHeader.keySet()) {+ headers[i] = new Header(name, requestHeader.get(name));+ i++;+ }+ }+ return headers;+ }++ /**+ * executes a method+ *+ * @param method+ * @return+ * @throws IOException+ * @throws HttpException+ */+ private HttpResponse execute(final HttpMethod method) throws IOException, HttpException {+ assert method != null : "precondition violated: method != null";+ // set header+ for (final Header header : headers) {+ method.setRequestHeader(header);+ }+ // set proxy+ final httpRemoteProxyConfig proxyConfig = getProxyConfig(method.getURI().getHost());+ addProxyAuth(method, proxyConfig);+ final HostConfiguration hostConfig = getProxyHostConfig(proxyConfig);+ // execute (send request)+ if (hostConfig == null) {+ apacheHttpClient.executeMethod(method);+ } else {+ apacheHttpClient.executeMethod(hostConfig, method);+ }+ // return response+ return new JakartaCommonsHttpResponse(method);+ }++ /**+ * if necessary adds a header for proxy-authentication+ *+ * @param method+ * @param proxyConfig+ */+ private void addProxyAuth(HttpMethod method, httpRemoteProxyConfig proxyConfig) {+ if(proxyConfig != null && proxyConfig.useProxy()) {+ final String remoteProxyUser = proxyConfig.getProxyUser();+ if (remoteProxyUser != null && remoteProxyUser.length() > 0) {+ if (remoteProxyUser.contains(":")) {+ serverLog.logWarning("HTTPC", "Proxy authentication contains invalid characters, trying anyway");+ }+ final String remoteProxyPwd = proxyConfig.getProxyPwd();+ final String credentials = kelondroBase64Order.standardCoder.encodeString(remoteProxyUser.replace(":", "") ++ ":" + remoteProxyPwd);+ method.setRequestHeader(httpHeader.PROXY_AUTHORIZATION, "Basic " + credentials);+ }+ }+ }++ /**+ *+ * @param hostname+ * @return+ */+ private httpRemoteProxyConfig getProxyConfig(final String hostname) {+ final httpRemoteProxyConfig proxyConfig;+ if (this.proxyConfig != null) {+ // client specific+ proxyConfig = httpdProxyHandler.getProxyConfig(hostname, this.proxyConfig);+ } else {+ // default settings+ proxyConfig = httpdProxyHandler.getProxyConfig(hostname, 0);+ }+ return proxyConfig;+ }++ /**+ * @param proxyConfig+ * @return current host-config with additional proxy set or null if no proxy should be used+ */+ private HostConfiguration getProxyHostConfig(final httpRemoteProxyConfig proxyConfig) {+ // generate http-configuration+ if (proxyConfig != null && proxyConfig.useProxy()) {+ // new config based on client (default)+ HostConfiguration hostConfig = new HostConfiguration(apacheHttpClient.getHostConfiguration());+ // add proxy+ hostConfig.setProxy(proxyConfig.getProxyHost(), proxyConfig.getProxyPort());+ return hostConfig;+ } else {+ return null;+ }+ }++ /**+ * Returns the given date in an HTTP-usable format. (according to RFC1123/RFC822)+ *+ * @param date The Date-Object to be converted.+ * @return String with the date.+ */+ public String date2String(Date date) {+ if (date == null)+ return "";++ return DateUtil.formatDate(date);+ }++ /**+ * close all connections+ */+ public static void closeAllConnections() {+ conManager.closeIdleConnections(1);+ conManager.shutdown();+ }++ /**+ * gets the maximum number of connections allowed+ *+ * @return+ */+ public static int maxConnections() {+ return conManager.getParams().getMaxTotalConnections();+ }++ /**+ * test+ *+ * @param args+ */+ public static void main(final String[] args) {+ HttpResponse resp = null;+ String url = args[0];+ if (!(url.toUpperCase().startsWith("HTTP://"))) {+ url = "http://" + url;+ }+ try {+ if (args.length > 1 && "post".equals(args[1])) {+ // POST+ final HashMap<String, byte[]> files = new HashMap<String, byte[]>();+ files.put("myfile.txt", "this is not a file ;)".getBytes());+ files.put("anotherfile.raw", "this is not a binary file ;)".getBytes());+ System.out.println("POST " + files.size() + " elements to " + url);+ final de.anomic.http.HttpClient client = HttpFactory.newClient();+ resp = client.POST(url, files);+ System.out.println("----- Header: -----");+ System.out.println(new String(resp.getResponseHeader().toString()));+ System.out.println("----- Body: -----");+ System.out.println(new String(resp.getData()));+ } else if (args.length > 1 && "head".equals(args[1])) {+ // whead+ System.out.println("whead " + url);+ System.out.println("--------------------------------------");+ System.out.println(de.anomic.http.HttpClient.whead(url).toString());+ } else {+ // wget+ System.out.println("wget " + url);+ System.out.println("--------------------------------------");+ System.out.println(new String(de.anomic.http.HttpClient.wget(url)));+ }+ } catch (final IOException e) {+ e.printStackTrace();+ } finally {+ if (resp != null) {+ // release connection+ resp.closeStream();+ }+ }+ }++ /**+ * @return+ */+ public static String getCurrentUserAgent() {+ return (String) apacheHttpClient.getParams().getParameter(HttpClientParams.USER_AGENT);+ }+}\ No newline at end of filediff --git a/source/de/anomic/http/JakartaCommonsHttpResponse.java b/source/de/anomic/http/JakartaCommonsHttpResponse.javanew file mode 100644index 000000000..db45dfbeb--- /dev/null+++ b/source/de/anomic/http/JakartaCommonsHttpResponse.java@@ -0,0 +1,168 @@+// JakartaCommonsHttpResponse.java+// (C) 2008 by Daniel Raap; [email protected]+// first published 2.4.2008 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate: 2008-03-14 01:16:04 +0100 (Fr, 14 Mrz 2008) $+// $LastChangedRevision: 4558 $+// $LastChangedBy: orbiter $+//+// LICENSE+//+// This program is free software; you can redistribute it and/or modify+// it under the terms of the GNU General Public License as published by+// the Free Software Foundation; either version 2 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+package de.anomic.http;++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.io.InputStream;++import org.apache.commons.httpclient.Header;+import org.apache.commons.httpclient.HttpMethod;++/**+ * container for http-response data+ *+ * @author daniel+ * @since 21.03.2008+ */+public class JakartaCommonsHttpResponse implements HttpResponse {+ private final HttpMethod method;+ private String incomingAccountingName = null;++ /**+ * cache of body-data+ */+ private byte[] responseBody;++ /**+ * constructor+ *+ * @param method+ * @throws IOException+ */+ public JakartaCommonsHttpResponse(final HttpMethod method) throws IOException {+ super();++ this.method = method;+ }++ /*+ * (non-Javadoc)+ *+ * @see de.anomic.http.HttpResponse#getResponseHeader()+ */+ public httpHeader getResponseHeader() {+ final httpHeader responseHeader = new httpHeader();+ for (final Header header : getHeaders()) {+ responseHeader.add(header.getName(), header.getValue());+ }+ return responseHeader;+ }++ /**+ * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders()+ * @return the headers+ */+ private Header[] getHeaders() {+ return method.getResponseHeaders();+ }++ /**+ * @see org.apache.commons.httpclient.HttpMethod#getResponseBody()+ * @return+ * @throws IOException+ */+ public byte[] getData() throws IOException {+ if (this.responseBody == null) {+ InputStream instream = null;+ try {+ instream = getDataAsStream();+ if (instream != null) {+ ByteArrayOutputStream outstream = new ByteArrayOutputStream();+ byte[] buffer = new byte[4096];+ int len;+ while ((len = instream.read(buffer)) > 0) {+ outstream.write(buffer, 0, len);+ }+ outstream.close();+ this.responseBody = outstream.toByteArray();+ }+ } finally {+ if (instream != null) {+ closeStream();+ }+ }+ }+ return this.responseBody;+ }++ /**+ * @see org.apache.commons.httpclient.HttpMethod#getResponseBodyAsStream()+ * @return+ * @throws IOException+ */+ public InputStream getDataAsStream() throws IOException {+ // count bytes for overall http-statistics+ return new httpdByteCountInputStream(method.getResponseBodyAsStream(), incomingAccountingName);+ }++ /*+ * (non-Javadoc)+ *+ * @see de.anomic.http.HttpResponse#closeStream()+ */+ public void closeStream() {+ method.releaseConnection();+ }++ /*+ * (non-Javadoc)+ *+ * @see de.anomic.http.HttpResponse#getStatusLine()+ */+ public String getStatusLine() {+ return getStatusCode() + " " + method.getStatusText();+ }++ /*+ * (non-Javadoc)+ *+ * @see de.anomic.http.HttpResponse#getStatusCode()+ */+ public int getStatusCode() {+ final int code = method.getStatusCode();+ assert code >= 100 && code <= 999 : "postcondition violated: StatusCode (" + code + ") has not 3 digits!";+ return code;+ }++ /*+ * (non-Javadoc)+ *+ * @see de.anomic.http.HttpResponse#getHttpVer()+ */+ public String getHttpVer() {+ return method.getStatusLine().getHttpVersion();+ }++ /**+ * sets the name for accounting incoming (loaded) bytes+ *+ * @param accName+ */+ public void setAccountingName(final String accName) {+ incomingAccountingName = accName;+ }+}diff --git a/source/de/anomic/http/httpContentLengthInputStream.java b/source/de/anomic/http/httpContentLengthInputStream.javadeleted file mode 100644index 82a333493..000000000--- a/source/de/anomic/http/httpContentLengthInputStream.java+++ /dev/null@@ -1,116 +0,0 @@-//httpContentLengthInputStream.java-//------------------------//(C) by Michael Peter Christen; [email protected]-//first published on http://www.anomic.de-//Frankfurt, Germany, 2004-//-// This file is contributed by Martin Thelian-//-// $LastChangedDate: 2006-09-15 17:01:25 +0200 (Fr, 15 Sep 2006) $-// $LastChangedRevision: 2598 $-// $LastChangedBy: theli $-//-//This program is free software; you can redistribute it and/or modify-//it under the terms of the GNU General Public License as published by-//the Free Software Foundation; either version 2 of the License, or-//(at your option) any later version.-//-//This program is distributed in the hope that it will be useful,-//but WITHOUT ANY WARRANTY; without even the implied warranty of-//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-//GNU General Public License for more details.-//-//You should have received a copy of the GNU General Public License-//along with this program; if not, write to the Free Software-//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA-//-//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.--package de.anomic.http;--import java.io.IOException;-import java.io.InputStream;--public class httpContentLengthInputStream extends httpdByteCountInputStream {-- private long contentLength;- private boolean closed = false;-- public httpContentLengthInputStream(InputStream inputStream, long contentLength) {- super(inputStream);- this.contentLength = contentLength;- }-- public long getContentLength() {- return this.contentLength;- }-- public boolean isClosed() {- return this.closed;- }-- /**- * Closes this input stream.- * <b>Attention:</b> This does not close the wrapped input stream, because- * otherwise keep-alive connections would terminate- */- public void close() throws IOException {- if (!this.closed) {- try {- // read to the end of the stream and throw read bytes away- httpChunkedInputStream.exhaustInputStream(this);- } finally {- this.closed = true;- }- }- }-- public int read() throws IOException {- if (this.closed) throw new IOException("Stream already closed.");-- // if we have already finished reading ...- if (this.byteCount >= this.contentLength) return -1;- return super.read();- }-- public int read(byte[] buffer) throws IOException {- return read(buffer, 0, buffer.length);- }-- public int read(byte[] buffer, int off, int len) throws IOException {- if (this.closed) throw new IOException("Stream already closed.");-- // if we have already finished reading ...- if (this.byteCount >= this.contentLength) return -1;-- // only read until body end- if (this.byteCount + len > this.contentLength) {- len = (int) (this.contentLength - this.byteCount);- }-- return super.read(buffer, off, len);- }-- public long skip(long len) throws IOException {- long skipLength = Math.min(len, this.contentLength - this.byteCount);- return super.skip(skipLength);- }--}diff --git a/source/de/anomic/http/httpHeader.java b/source/de/anomic/http/httpHeader.javaindex 76e7da5a5..fe7662273 100644--- a/source/de/anomic/http/httpHeader.java+++ b/source/de/anomic/http/httpHeader.java@@ -78,9 +78,9 @@ import de.anomic.yacy.yacyURL;public final class httpHeader extends TreeMap<String, String> implements Map<String, String> {- private static final long serialVersionUID = 17L;+ private static final long serialVersionUID = 18L;- public static final String DEFAULT_CHARSET = "ISO-8859-1";+ static final String DEFAULT_CHARSET = "ISO-8859-1";/* =============================================================* Constants defining http versions@@ -946,5 +946,17 @@ public final class httpHeader extends TreeMap<String, String> implements Map<Str/** Patch END:* Name: Header Property Patch- */+ */++ /**+ * @param header+ * @return+ */+ static String getCharSet(httpHeader header) {+ String charSet = header.getCharacterEncoding();+ if (charSet == null) {+ charSet = DEFAULT_CHARSET;+ }+ return charSet;+ }}diff --git a/source/de/anomic/http/httpRemoteProxyConfig.java b/source/de/anomic/http/httpRemoteProxyConfig.javaindex 6f6967c7c..4e7f6cfc0 100644--- a/source/de/anomic/http/httpRemoteProxyConfig.java+++ b/source/de/anomic/http/httpRemoteProxyConfig.java@@ -49,6 +49,7 @@package de.anomic.http;+import java.util.Arrays;import java.util.HashSet;import de.anomic.plasma.plasmaSwitchboard;@@ -67,7 +68,6 @@ public final class httpRemoteProxyConfig {private String remoteProxyUser;private String remoteProxyPwd;- private String remoteProxyNoProxy = "";private String[] remoteProxyNoProxyPatterns = null;public final HashSet<String> remoteProxyAllowProxySet = new HashSet<String>();@@ -101,16 +101,12 @@ public final class httpRemoteProxyConfig {return this.remoteProxyPwd;}- public String getProxyNoProxy() {- return this.remoteProxyNoProxy;- }-public String[] getProxyNoProxyPatterns() {return this.remoteProxyNoProxyPatterns;}public String toString() {- StringBuffer toStrBuf = new StringBuffer();+ final StringBuilder toStrBuf = new StringBuilder(50);toStrBuf.append("Status: ").append(this.remoteProxyUse?"ON":"OFF").append(" | ")@@ -126,10 +122,10 @@ public final class httpRemoteProxyConfig {if (this.remoteProxyUse4SSL) toStrBuf.append(" SSL");toStrBuf.append(" | ").append("No Proxy for: ")- .append(this.remoteProxyNoProxy);+ .append(Arrays.toString(this.remoteProxyNoProxyPatterns));- return new String(toStrBuf);+ return toStrBuf.toString();}public static httpRemoteProxyConfig init(@@ -179,8 +175,14 @@ public final class httpRemoteProxyConfig {newConfig.remoteProxyPwd = sb.getConfig("remoteProxyPwd", "").trim();// determining addresses for which the remote proxy should not be used- newConfig.remoteProxyNoProxy = sb.getConfig("remoteProxyNoProxy","").trim();- newConfig.remoteProxyNoProxyPatterns = newConfig.remoteProxyNoProxy.split(",");+ final String remoteProxyNoProxy = sb.getConfig("remoteProxyNoProxy","").trim();+ newConfig.remoteProxyNoProxyPatterns = remoteProxyNoProxy.split(",");+ // trim split entries+ int i = 0;+ for(final String pattern: newConfig.remoteProxyNoProxyPatterns) {+ newConfig.remoteProxyNoProxyPatterns[i] = pattern.trim();+ i++;+ }return newConfig;}diff --git a/source/de/anomic/http/httpc.java b/source/de/anomic/http/httpc.javadeleted file mode 100644index 6ae599a13..000000000--- a/source/de/anomic/http/httpc.java+++ /dev/null@@ -1,1675 +0,0 @@-// httpc.java-// --------------------------------------// (C) by Michael Peter Christen; [email protected]-// first published on http://www.anomic.de-// Frankfurt, Germany, 2004-// last major change: 26.02.2004-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA-//-// 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.--package de.anomic.http;--import java.io.File;-import java.io.FileNotFoundException;-import java.io.FileOutputStream;-import java.io.IOException;-import java.io.InputStream;-import java.io.InputStreamReader;-import java.io.OutputStream;-import java.io.OutputStreamWriter;-import java.io.PushbackInputStream;-import java.io.Writer;-import java.net.InetAddress;-import java.net.InetSocketAddress;-import java.net.MalformedURLException;-import java.net.Socket;-import java.net.SocketException;-import java.net.UnknownHostException;-import java.text.SimpleDateFormat;-import java.util.ArrayList;-import java.util.Arrays;-import java.util.Comparator;-import java.util.Date;-import java.util.HashMap;-import java.util.HashSet;-import java.util.Iterator;-import java.util.Locale;-import java.util.Map;-import java.util.TimeZone;-import java.util.zip.GZIPInputStream;-import java.util.zip.GZIPOutputStream;--import javax.net.ssl.HostnameVerifier;-import javax.net.ssl.HttpsURLConnection;-import javax.net.ssl.SSLContext;-import javax.net.ssl.SSLSocketFactory;-import javax.net.ssl.TrustManager;-import javax.net.ssl.X509TrustManager;--import de.anomic.kelondro.kelondroBase64Order;-import de.anomic.server.serverByteBuffer;-import de.anomic.server.serverCore;-import de.anomic.server.serverDomains;-import de.anomic.server.serverFileUtils;-import de.anomic.server.serverObjects;-import de.anomic.server.logging.serverLog;-import de.anomic.tools.nxTools;-import de.anomic.yacy.yacyURL;--/**-* This class implements an http client. While http access is built-in in java-* libraries, it is still necessary to implement the network interface since-* otherwise there is no access to the HTTP/1.0 / HTTP/1.1 header information-* that comes along each connection.-*/--public final class httpc {-- // some constants- /**- * Specifies that the httpc is allowed to use gzip content encoding for- * http post requests- * @see #POST(String, httpHeader, serverObjects, HashMap)- */- public static final String GZIP_POST_BODY = "GZIP_POST_BODY";-- // final statics- private static final String vDATE = "20040602";- private static final int terminalMaxLength = 30000;- private static final SimpleDateFormat HTTPGMTFormatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);- static final HashMap<String, String> reverseMappingCache = new HashMap<String, String>();- private static final HashSet<httpc> activeConnections = new HashSet<httpc>(); // all connections are stored here and deleted when they are finished- private static final long minimumTime_before_activeConnections_cleanup = 3600000; // 1 Hour- private static final long minimumTime_before_idleConnections_cleanup = 120000; // 2 Minutes- private static final int activeConnections_maximum = 64;- public static final connectionTimeComparator connectionTimeComparatorInstance = new connectionTimeComparator();-- private static int objCounter = 0; // will be increased with each object and is used to return a hash code-- // defined during set-up of switchboard- public static boolean yacyDebugMode = false;-- // statics to be defined in static section below- private static SSLSocketFactory theSSLSockFactory = null;- public static String systemOST;- public static String userAgent;-- static {- // set the time zone- HTTPGMTFormatter.setTimeZone(TimeZone.getTimeZone("GMT")); // The GMT standard date format used in the HTTP protocol-- // set time-out of InetAddress.getByName cache ttl- java.security.Security.setProperty("networkaddress.cache.ttl" , "60");- java.security.Security.setProperty("networkaddress.cache.negative.ttl" , "0");-- // initializing a dummy trustManager to enable https connections-- // Create a trust manager that does not validate certificate chains- TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {- public java.security.cert.X509Certificate[] getAcceptedIssuers() {- return null;- }-- public void checkClientTrusted(- java.security.cert.X509Certificate[] certs, String authType) {- }-- public void checkServerTrusted(- java.security.cert.X509Certificate[] certs, String authType) {- }- } };-- // Install the all-trusting trust manager- try {- SSLContext sc = SSLContext.getInstance("SSL");- // Create empty HostnameVerifier- HostnameVerifier hv = new HostnameVerifier() {- public boolean verify(String urlHostName, javax.net.ssl.SSLSession session) {- // logger.info("Warning: URL Host: "+urlHostName+"- // vs."+session.getPeerHost());- return true;- }- };-- sc.init(null, trustAllCerts, new java.security.SecureRandom());- HttpsURLConnection.setDefaultSSLSocketFactory(theSSLSockFactory = sc.getSocketFactory());- HttpsURLConnection.setDefaultHostnameVerifier(hv);- } catch (Exception e) {- }-- // provide system information for client identification- String loc = System.getProperty("user.timezone", "nowhere");- int p = loc.indexOf("/");- if (p > 0) loc = loc.substring(0,p);- loc = loc + "/" + System.getProperty("user.language", "dumb");- systemOST =- System.getProperty("os.arch", "no-os-arch") + " " +- System.getProperty("os.name", "no-os-name") + " " +- System.getProperty("os.version", "no-os-version") + "; " +- "java " + System.getProperty("java.version", "no-java-version") + "; " + loc;- userAgent = "yacy (www.yacy.net; v" + vDATE + "; " + systemOST + ")";- }--- // class variables- private Socket socket = null; // client socket for commands- public String adressed_host = null;- public int adressed_port = 80;- private String target_virtual_host = null;-- // output and input streams for client control connection- PushbackInputStream clientInput = null;- private OutputStream clientOutput = null;-- private httpdByteCountInputStream clientInputByteCount = null;- private httpdByteCountOutputStream clientOutputByteCount = null;-- private boolean remoteProxyUse = false;- private httpRemoteProxyConfig remoteProxyConfig = null;-- String requestPath = null;- private boolean allowContentEncoding = true;-- public boolean ssl;- public long initTime, lastIO;- public String command;- public int timeout;-- private int hashIndex;--- /**- * Initialize the httpc-instance with the given data.- *- * @param remoteProxyHost- * @param remoteProxyPort- * @throws IOException- */- public httpc(- String server,- String vhost,- int port,- int timeout,- boolean ssl,- httpRemoteProxyConfig theRemoteProxyConfig,- String incomingByteCountAccounting,- String outgoingByteCountAccounting- ) throws IOException {-- // remove old connections- // do NOT remove this check; in case that everything works fine this call does nothing- // but if in any arror case connections stay open, this will ensure that the peer keeps running and the host server is not blocked from working- checkIdleConnections();- assert timeout != 0;-- // register new connection- this.hashIndex = objCounter;- objCounter++;- synchronized (activeConnections) {activeConnections.add(this);}- //System.out.println("*** DEBUG init httpc: " + activeConnections.size() + " connections online");-- this.ssl = ssl;- this.initTime = Long.MAX_VALUE;- this.lastIO = Long.MAX_VALUE;- this.command = null;- this.timeout = timeout;-- if ((theRemoteProxyConfig == null) ||- (!theRemoteProxyConfig.useProxy())) {- initN(- server,- vhost,- port,- timeout,- ssl,- incomingByteCountAccounting,- outgoingByteCountAccounting- );- return;- }-- if (port == -1) {- port = (ssl)? 443 : 80;- }-- String remoteProxyHost = theRemoteProxyConfig.getProxyHost();- int remoteProxyPort = theRemoteProxyConfig.getProxyPort();-- this.initN(- remoteProxyHost,- vhost,- remoteProxyPort,- timeout,- ssl,- incomingByteCountAccounting,- outgoingByteCountAccounting);-- this.remoteProxyUse = true;- this.adressed_host = server;- this.adressed_port = port;- this.target_virtual_host = vhost;- this.remoteProxyConfig = theRemoteProxyConfig;- }-- /**- * Convert the status of this class into an String object to output it.- */- public String toString() {- return (this.adressed_host == null) ? "Disconnected" : "Connected to " + this.adressed_host +- ((this.remoteProxyUse) ? " via " + adressed_host : "");- }-- /**- * Sets wether the content is allowed to be unzipped while getting?- * FIXME: The name of this method seems misleading, if I read the usage of- * this method correctly?- *- * @param status true, if the content is allowed to be decoded on the fly?- */- public void setAllowContentEncoding(boolean status) {- this.allowContentEncoding = status;- }-- /**- * Check wether the connection of this instance is closed.- *- * @return true if the connection is no longer open.- */- public boolean isClosed() {- if (this.socket == null) return true;- return (!this.socket.isConnected()) || (this.socket.isClosed());- }-- /**- * Returns the given date in an HTTP-usable format.- * (according to RFC822)- *- * @param date The Date-Object to be converted.- * @return String with the date.- */- public static String dateString(Date date) {- if (date == null) return "";-- /*- * This synchronized is needed because SimpleDateFormat- * is not thread-safe.- * See: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6231579- */- synchronized(HTTPGMTFormatter) {- return HTTPGMTFormatter.format(date);- }- }-- /**- * Returns the current date as Date-Object.- *- * @return Date-object with the current time.- */- public static Date nowDate() {- return new Date();- }-- public int hashCode() {- // return a hash code so it is possible to store objects of httpc objects in a HashSet- return this.hashIndex;- }-- /**- * Initialize the https-instance with the given data. Opens the sockets to- * the remote server and creats input and output streams.- *- * @param server Hostname of the server to connect to.- * @param port On which port should we connect.- * @param timeout How long do we wait for answers?- * @param ssl Wether we should use SSL.- * @throws IOException- */- private void initN(- String server,- String vhost,- int port,- int timeout,- boolean ssl,- String incomingByteCountAccounting,- String outgoingByteCountAccounting- ) throws IOException {- //serverLog.logDebug("HTTPC", handle + " initialized");- this.remoteProxyUse = false;-- try {- if (port == -1) {- port = (ssl)? 443 : 80;- }-- this.adressed_host = server;- this.adressed_port = port;- this.target_virtual_host = vhost;-- // creating a socket- this.socket = (ssl)- ? theSSLSockFactory.createSocket()- : new Socket();-- // creating a socket address- InetSocketAddress address = null;- if (!this.remoteProxyUse) {- // only try to resolve the address if we are not using a proxy- InetAddress hostip = serverDomains.dnsResolve(server);- if (hostip == null) throw new UnknownHostException(server);- address = new InetSocketAddress(hostip, port);- } else {- address = new InetSocketAddress(server,port);- }-- // trying to establish a connection to the address- this.initTime = System.currentTimeMillis();- this.lastIO = System.currentTimeMillis();- //this.socket.setKeepAlive(true); // set socket timeout and keep alive behavior- assert timeout >= 1000;- this.socket.setSoTimeout(0); // waiting time for read; 0 means: no timeout, wait forever- this.socket.setTcpNoDelay(true); // no accumulation until buffer is full- this.socket.setSoLinger(false, 0); // !wait for all data being written on close()- this.socket.setSendBufferSize(1440); // read http://www.cisco.com/warp/public/105/38.shtml- //this.socket.setReceiveBufferSize(1440); // read http://www.cisco.com/warp/public/105/38.shtml-- /*-- public int getSoTimeout() {- return getIntParameter(SO_TIMEOUT, 0);- public boolean getTcpNoDelay() {- return getBooleanParameter(TCP_NODELAY, true);- public int getLinger() {- return getIntParameter(SO_LINGER, -1);- public int getSendBufferSize() {- return getIntParameter(SO_SNDBUF, -1);- public int getReceiveBufferSize() {- return getIntParameter(SO_RCVBUF, -1);-- */-- // get the connection- this.socket.connect(address, timeout);-- if (incomingByteCountAccounting != null) {- this.clientInputByteCount = new httpdByteCountInputStream(this.socket.getInputStream(),incomingByteCountAccounting);- }- if (outgoingByteCountAccounting != null) {- this.clientOutputByteCount = new httpdByteCountOutputStream(this.socket.getOutputStream(),outgoingByteCountAccounting);- }-- // getting input and output streams- this.clientInput = new PushbackInputStream((this.clientInputByteCount!=null)?- this.clientInputByteCount:- this.socket.getInputStream());- this.clientOutput = this.socket.getOutputStream();-- // if we reached this point, we should have a connection- } catch (UnknownHostException e) {- serverLog.logFine("HTTPC", "Couldn't find host " + server);- close();- throw new IOException("unknown host: " + server);- } catch (IOException e) {- // There was an error while connecting the socket, probably a SocketTimeoutException- // we have to close the httpc, otherwise it would stay in activeConnections forever- serverLog.logFine("HTTPC", "Couldn't open socket to " + this.adressed_host + ":" + this.adressed_port + ": " + e.getMessage());- close();-- // TODO do we need to hand it over to the caller?- throw e;- }- }- /* code from apache commons- protected boolean isStale() throws IOException {- boolean isStale = true;- if (isOpen) {- // the connection is open, but now we have to see if we can read it- // assume the connection is not stale.- isStale = false;- try {- if (inputStream.available() <= 0) {- try {- socket.setSoTimeout(1);- inputStream.mark(1);- int byteRead = inputStream.read();- if (byteRead == -1) {- // again - if the socket is reporting all data read,- // probably stale- isStale = true;- } else {- inputStream.reset();- }- } finally {- socket.setSoTimeout(this.params.getSoTimeout());- }- }- } catch (InterruptedIOException e) {- if (!ExceptionUtil.isSocketTimeoutException(e)) {- throw e;- }- // aha - the connection is NOT stale - continue on!- } catch (IOException e) {- // oops - the connection is stale, the read or soTimeout failed.- LOG.debug(- "An error occurred while reading from the socket, is appears to be stale",- e- );- isStale = true;- }- }-- return isStale;- }-*/- public long getInputStreamByteCount() {- return (this.clientInputByteCount == null)?0:this.clientInputByteCount.getCount();- }-- public long getOutputStreamByteCount() {- return (this.clientOutputByteCount == null)?0:this.clientOutputByteCount.getCount();- }-- public static int checkIdleConnections() {- // try to find and close all connections that did not find a target server and are idle waiting for a server socket-- httpc[] a = allConnections(); // put set into array to avoid ConcurrentModificationExceptions- int tbd = 0;- int c = 0;- if (a.length > activeConnections_maximum) {- // delete some connections; choose the oldest- Arrays.sort(a, httpc.connectionTimeComparatorInstance);- tbd = a.length - activeConnections_maximum;- for (int i = 0; i < tbd; i++) {- if (a[i] != null) {- a[i].close();- c++;- }- }- }- for (int i = tbd; i < a.length; i++) {- httpc clientConnection = a[i];- if (clientConnection != null) {- if ((clientConnection.initTime != Long.MAX_VALUE) &&- (clientConnection.initTime + Math.max(minimumTime_before_activeConnections_cleanup, clientConnection.timeout) < System.currentTimeMillis())) {- // the time-out limit is reached. close the connection- clientConnection.close();- c++;- }- if ((clientConnection.lastIO != Long.MAX_VALUE) &&- (clientConnection.lastIO + Math.max(minimumTime_before_idleConnections_cleanup, clientConnection.timeout) < System.currentTimeMillis())) {- // the time-out limit is reached. close the connection- clientConnection.close();- c++;- }- }- }- return c;- }-- public static int closeAllConnections() {- httpc[] a = allConnections(); // put set into array to avoid ConcurrentModificationExceptions- int c = 0;- for (int i = 0; i < a.length; i++) {- httpc clientConnection = a[i];- if (clientConnection != null) {- clientConnection.close();- c++;- }- }- return c;- }-- public static httpc[] allConnections() {- httpc[] a = null;- synchronized (activeConnections) {- a = new httpc[activeConnections.size()];- Iterator<httpc> i = httpc.activeConnections.iterator();- int c = 0;- while (i.hasNext()) {- a[c++] = i.next();- }- }- return a;- }-- public static class connectionTimeComparator implements Comparator<httpc> {-- public connectionTimeComparator() {- super();- }-- public int compare(httpc o1, httpc o2) {- long l1 = System.currentTimeMillis() - o1.lastIO;- long l2 = System.currentTimeMillis() - o2.lastIO;- if (l1 < l2) return 1;- if (l1 > l2) return -1;- return 0;- }- }-- public void finalize() {- this.close();- }-- public void close() {- synchronized (activeConnections) {activeConnections.remove(this);}- //System.out.println("*** DEBUG close httpc: " + activeConnections.size() + " connections online");-- if (this.clientInput != null) {- try {this.clientInput.close();} catch (Exception e) {}- this.clientInput = null;- }-- if (this.clientOutput != null) {- try {this.clientOutput.close();} catch (Exception e) {}- this.clientOutput = null;- }-- if (this.socket != null) {- try {this.socket.close();} catch (Exception e) {}- this.socket = null;- }-- if (this.clientInputByteCount != null) {- this.clientInputByteCount.finish();- this.clientInputByteCount = null;- }-- if (this.clientOutputByteCount != null) {- this.clientOutputByteCount.finish();- this.clientOutputByteCount = null;- }-- this.adressed_host = null;- this.target_virtual_host = null;-- this.remoteProxyConfig = null;- this.requestPath = null;- }-- /**- * This method invokes a call to the given server.- *- * @param method- * Which method should be called? GET, POST, HEAD or CONNECT- * @param path- * String with the path on the server to be get.- * @param header- * The prefilled header (if available) from the calling browser.- * @param zipped- * Is encoded content (gzip) allowed or not?- * @throws IOException- */- private void send(String method, String path, httpHeader header, boolean zipped) throws IOException {- // scheduled request through request-response objects/threads-- // check and correct path- if ((path == null) || (path.length() == 0)) path = "/";-- // for debuggug:- this.requestPath = path;-- // prepare header- if (header == null) header = new httpHeader();-- // set some standard values- if (!(header.containsKey(httpHeader.ACCEPT)))- header.put(httpHeader.ACCEPT, "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");- if (!(header.containsKey(httpHeader.ACCEPT_CHARSET)))- header.put(httpHeader.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");- if (!(header.containsKey(httpHeader.ACCEPT_LANGUAGE)))- header.put(httpHeader.ACCEPT_LANGUAGE, "en-us,en;q=0.5");- if (!(header.containsKey(httpHeader.KEEP_ALIVE)))- header.put(httpHeader.KEEP_ALIVE, "300");-- // set user agent. The user agent is only set if the value does not yet exists.- // this gives callers the opportunity, to change the user agent themselves, and- // it will not be changed.- if (!(header.containsKey(httpHeader.USER_AGENT))) header.put(httpHeader.USER_AGENT, userAgent);-- // set the host attribute. This is in particular necessary, if we contact another proxy- // the host is mandatory, if we use HTTP/1.1- if (!(header.containsKey(httpHeader.HOST))) {- if (this.remoteProxyUse) {- header.put(httpHeader.HOST, this.adressed_host);- } else {- header.put(httpHeader.HOST, this.target_virtual_host);- }- }-- if (this.remoteProxyUse) {- String remoteProxyUser = this.remoteProxyConfig.getProxyUser();- String remoteProxyPwd = this.remoteProxyConfig.getProxyPwd();- if ((remoteProxyUser!=null)&&(remoteProxyUser.length()>0)) {- header.put(httpHeader.PROXY_AUTHORIZATION,"Basic " + kelondroBase64Order.standardCoder.encodeString(remoteProxyUser + ":" + remoteProxyPwd));- }- }-- if (!(header.containsKey(httpHeader.CONNECTION))) {- header.put(httpHeader.CONNECTION, "close");- }-- // stimulate zipping or not- // we can unzip, and we will return it always as unzipped, unless not wanted- if (header.containsKey(httpHeader.ACCEPT_ENCODING)) {- String encoding = (String) header.get(httpHeader.ACCEPT_ENCODING);- if (zipped) {- if (encoding.indexOf("gzip") < 0) {- // add the gzip encoding- //System.out.println("!!! adding gzip encoding");- header.put(httpHeader.ACCEPT_ENCODING, "gzip,deflate" + ((encoding.length() == 0) ? "" : (";" + encoding)));- }- } else {- int pos = encoding.indexOf("gzip");- if (pos >= 0) {- // remove the gzip encoding- //System.out.println("!!! removing gzip encoding");- // ex: "gzip,deflate" => pos == 0, but we need to remove the "," as well => substring(pos+5),- // ex: "gzip" => pos == 0, but substring(pos+5) would exceed boundaries- String enc = encoding.substring(0, pos) + (encoding.length() > (pos+5) ? encoding.substring(pos + 5) : "");- header.put(httpHeader.ACCEPT_ENCODING, enc);- }- }- } else {- if (zipped) header.put(httpHeader.ACCEPT_ENCODING, "gzip,deflate");- }-- //header = new httpHeader(); header.put("Host", this.host); // debug-- StringBuffer sb = new StringBuffer();- // send request- if ((this.remoteProxyUse) && (!(method.equals(httpHeader.METHOD_CONNECT))))- path = ((this.adressed_port == 443) ? "https://" : "http://") + this.adressed_host + ":" + this.adressed_port + path;- sb.append(method + " " + path + " HTTP/1.0" + serverCore.CRLF_STRING); // TODO if set to HTTP/1.1, servers give time-outs?-- // send header- //System.out.println("***HEADER for path " + path + ": PROXY TO SERVER = " + header.toString()); // DEBUG- Iterator<String> i = header.keySet().iterator();- String key;- int count;- char tag;- while (i.hasNext()) {- key = i.next();- tag = key.charAt(0);- if ((tag != '*') && (tag != '#')) {- count = header.keyCount(key);- for (int j = 0; j < count; j++) {- sb.append(key + ": " + ((String) header.getSingle(key, j)).trim() + serverCore.CRLF_STRING);- }- //System.out.println("#" + key + ": " + value);- }- }-- // add terminating line- sb.append(serverCore.CRLF_STRING);- serverCore.send(this.clientOutput, sb.toString());- this.clientOutput.flush();-- // this is the place where www.stern.de refuses to answer ..???- }-- /**- * This method GETs a page from the server.- *- * @param path The path to the page which should be GET.- * @param requestHeader Prefilled httpHeader.- * @return Instance of response with the content.- * @throws IOException- */- public response GET(String path, httpHeader requestHeader) throws IOException {- //serverLog.logDebug("HTTPC", handle + " requested GET '" + path + "', time = " + (System.currentTimeMillis() - handle));- this.command = "GET " + path;- try {- boolean zipped = (!this.allowContentEncoding) ? false : httpd.shallTransportZipped(path);- send(httpHeader.METHOD_GET, path, requestHeader, zipped);- response r = new response(zipped);- //serverLog.logDebug("HTTPC", handle + " returned GET '" + path + "', time = " + (System.currentTimeMillis() - handle));- return r;- } catch (Exception e) {- if (e.getMessage().indexOf("heap space") > 0) {- e.printStackTrace();- }- throw new IOException(e.getMessage());- }- }-- /**- * This method gets only the header of a page.- *- * @param path The path to the page whose header should be get.- * @param requestHeader Prefilled httpHeader.- * @return Instance of response with the content.- * @throws IOException- */- public response HEAD(String path, httpHeader requestHeader) throws IOException {- this.command = "HEAD " + path;- try {- send(httpHeader.METHOD_HEAD, path, requestHeader, false);- return new response(false);- // in this case the caller should not read the response body,- // since there is none...- } catch (SocketException e) {- throw new IOException(e.getMessage());- }- }-- /**- * This method POSTs some data to a page.- *- * @param path The path to the page which the post is sent to.- * @param requestHeader Prefilled httpHeader.- * @param ins InputStream with the data to be posted to the server.- * @return Instance of response with the content.- * @throws IOException- */- public response POST(String path, httpHeader requestHeader, InputStream ins) throws IOException {- this.command = "POST " + path;- try {- send(httpHeader.METHOD_POST, path, requestHeader, false);- // if there is a body to the call, we would have a CONTENT-LENGTH tag in the requestHeader- String cl = (String) requestHeader.get(httpHeader.CONTENT_LENGTH);- int len, c;- byte[] buffer = new byte[512];- if (cl != null) {- len = Integer.parseInt(cl);- // transfer len bytes from ins to the server- while ((len > 0) && ((c = ins.read(buffer)) >= 0)) {- this.clientOutput.write(buffer, 0, c);- len -= c;- }- } else {- len = 0;- while ((c = ins.read(buffer)) >= 0) {- this.clientOutput.write(buffer, 0, c);- len += c;- }-- // TODO: we can not set the header here. This ist too late- requestHeader.put(httpHeader.CONTENT_LENGTH, Integer.toString(len));- }- this.clientOutput.flush();- return new response(false);- } catch (SocketException e) {- throw new IOException(e.getMessage());- }- }-- /**- * Call the server with the CONNECT-method.- * This is used to establish https-connections through a https-proxy- *- * @param host To which host should a connection be made?- * @param port Which port should be connected?- * @param requestHeader prefilled httpHeader.- * @return Instance of response with the content.- */-- public response CONNECT(String remotehost, int remoteport, httpHeader requestHeader) throws IOException {- this.command = "CONNECT " + remotehost + ":" + remoteport;- try {- send(httpHeader.METHOD_CONNECT, remotehost + ":" + remoteport, requestHeader, false);- return new response(false);- } catch (SocketException e) {- throw new IOException(e.getMessage());- }- }-- /**- * This method sends several files at once via a POST request. Only those- * files in the Hashtable files are written whose names are contained in- * args.- *- * @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 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, HashMap<String, byte[]> 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();- String boundary = (String) requestHeader.get(httpHeader.CONTENT_TYPE);- if (boundary == null) {- // create a boundary- boundary = "multipart/form-data; boundary=----------" + java.lang.System.currentTimeMillis();- requestHeader.put(httpHeader.CONTENT_TYPE, boundary);- }- // extract the boundary string- int pos = boundary.toUpperCase().indexOf("BOUNDARY=");- if (pos < 0) {- // again, create a boundary- boundary = "multipart/form-data; boundary=----------" + java.lang.System.currentTimeMillis();- requestHeader.put(httpHeader.CONTENT_TYPE, boundary);- pos = boundary.indexOf("boundary=");- }- boundary = "--" + boundary.substring(pos + "boundary=".length());-- boolean zipContent = args.containsKey(GZIP_POST_BODY);- args.remove(GZIP_POST_BODY);-- OutputStream out;- GZIPOutputStream zippedOut;- serverByteBuffer buf = new serverByteBuffer();- if (zipContent) {- zippedOut = new GZIPOutputStream(buf);- out = zippedOut;- } else {- out = buf;- }-- // in contrast to GET and HEAD, this method also transports a message body- // the body consists of repeated boundaries and values in between- if (args.size() != 0) {- // we have values for the POST, start with one boundary- String key, value;- Iterator<String> e = args.keySet().iterator();- while (e.hasNext()) {- // start with a boundary- out.write(boundary.getBytes("UTF-8"));- out.write(serverCore.CRLF);- // write value- key = e.next();- 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("UTF-8"));- out.write(serverCore.CRLF);- out.write(serverCore.CRLF);- out.write((byte[]) files.get(key));- out.write(serverCore.CRLF);- } else {- // write a single value- out.write(("Content-Disposition: form-data; name=" + '"' + key + '"').getBytes("UTF-8"));- out.write(serverCore.CRLF);- out.write(serverCore.CRLF);- out.write(value.getBytes("UTF-8"));- out.write(serverCore.CRLF);- }- }- // finish with a boundary- out.write(boundary.getBytes("UTF-8"));- out.write(serverCore.CRLF);- }- // create body array- out.close();- byte[] body = buf.getBytes();- buf = null; out = null;-- //System.out.println("DEBUG: PUT BODY=" + new String(body));- if (zipContent) {- requestHeader.put(httpHeader.CONTENT_ENCODING, "gzip");-- //TODO: should we also set the content length here?- } else {- // size of that body- requestHeader.put(httpHeader.CONTENT_LENGTH, Integer.toString(body.length));- }-- // send the header- send(httpHeader.METHOD_POST, path, requestHeader, false);-- // send the body- serverCore.send(this.clientOutput, body);-- return new response(false);- }-- public static byte[] singleGET(- String realhost,- String virtualhost,- int port,- String path,- int timeout,- String user,- String password,- boolean ssl,- httpRemoteProxyConfig theRemoteProxyConfig,- httpHeader requestHeader,- File download- ) throws IOException {- // if download == null, the get result is stored to a byte[] and returned,- // otherwise the get is streamed to the file and null is returned- if (requestHeader == null) requestHeader = new httpHeader();-- // setting host authorization header- if ((user != null) && (password != null) && (user.length() != 0)) {- requestHeader.put(httpHeader.AUTHORIZATION, kelondroBase64Order.standardCoder.encodeString(user + ":" + password));- }-- httpc con = new httpc(realhost, virtualhost, port, timeout, ssl, theRemoteProxyConfig, null, null);-- httpc.response res = con.GET(path, requestHeader);- if (res.status.startsWith("2")) {- if (download == null) {- // stream to byte[]- serverByteBuffer sbb = new serverByteBuffer();- res.writeContent(sbb, null);- con.close();- return sbb.getBytes();- } else {- // stream to file and return null- res.writeContent(null, download);- con.close();- return null;- }- }- return res.status.getBytes();- }-- public static byte[] singleGET(- yacyURL u,- String vhost,- int timeout,- String user,- String password,- httpRemoteProxyConfig theRemoteProxyConfig,- File download- ) throws IOException {- int port = u.getPort();- boolean ssl = u.getProtocol().equals("https");- if (port < 0) port = (ssl) ? 443: 80;- String path = u.getPath();- String query = u.getQuery();- if ((query != null) && (query.length() > 0)) path = path + "?" + query;- return singleGET(u.getHost(), vhost, port, path, timeout, user, password, ssl, theRemoteProxyConfig, null, download);- }-- public static byte[] singlePOST(- String realhost,- String virtualhost,- int port,- String path,- int timeout,- String user,- String password,- boolean ssl,- httpRemoteProxyConfig theRemoteProxyConfig,- httpHeader requestHeader,- serverObjects props,- HashMap<String, byte[]> files- ) throws IOException {-- if (requestHeader == null) requestHeader = new httpHeader();- if ((user != null) && (password != null) && (user.length() != 0)) {- requestHeader.put(httpHeader.AUTHORIZATION, kelondroBase64Order.standardCoder.encodeString(user + ":" + password));- }-- httpc con = new httpc(realhost, virtualhost, port, timeout, ssl, theRemoteProxyConfig, null, null);- httpc.response res = con.POST(path, requestHeader, props, files);-- //System.out.println("response=" + res.toString());- if (!(res.status.startsWith("2"))) {- byte[] status = res.status.getBytes();- con.close();- return status;- }-- // read connection body and return body- serverByteBuffer sbb = new serverByteBuffer();- res.writeContent(sbb, null);- if ((res.responseHeader.contentLength() > 0) && (res.responseHeader.contentLength() != sbb.length()))- throw new IOException("content length and loaded resource length from http://" + realhost + ":" + port + path + " does not match. HEADER.Content-Length = " + res.responseHeader.contentLength() + ", resource.length =" + sbb.length());- con.close();- return sbb.getBytes();- }-- public static byte[] singlePOST(- yacyURL u,- String vhost,- int timeout,- String user,- String password,- httpRemoteProxyConfig theRemoteProxyConfig,- serverObjects props,- HashMap<String, byte[]> files- ) throws IOException {- int port = u.getPort();- boolean ssl = u.getProtocol().equals("https");- if (port < 0) port = (ssl) ? 443 : 80;- String path = u.getPath();- String query = u.getQuery();- if ((query != null) && (query.length() > 0)) path = path + "?" + query;- return singlePOST(- u.getHost(),- vhost,- port,- path,- timeout,- user,- password,- ssl,- theRemoteProxyConfig,- null,- props,- files- );- }-- public static byte[] wget(- yacyURL url,- String vhost,- int timeout,- String user,- String password,- httpRemoteProxyConfig theRemoteProxyConfig,- httpHeader requestHeader,- File download- ) throws IOException {-- int port = url.getPort();- boolean ssl = url.getProtocol().equals("https");- if (port < 0) port = (ssl) ? 443: 80;- String path = url.getPath();- String query = url.getQuery();- if ((query != null) && (query.length() > 0)) path = path + "?" + query;-- // splitting of the byte array into lines- byte[] a = singleGET(- url.getHost(),- vhost,- port,- path,- timeout,- user,- password,- ssl,- theRemoteProxyConfig,- requestHeader,- download- );-- if (a == null) return null;-- // support of gzipped data (requested by roland)- a = serverFileUtils.uncompressGZipArray(a);-- // return result- return a;- }-- public static Map<String, String> loadHashMap(yacyURL url, httpRemoteProxyConfig proxy) {- try {- // should we use the proxy?- boolean useProxy = (proxy != null) &&- (proxy.useProxy()) &&- (proxy.useProxy4Yacy());-- // sending request- final HashMap<String, String> result = nxTools.table(- httpc.wget(- url,- url.getHost(),- 8000,- null,- null,- (useProxy) ? proxy : null,- null,- null- )- , "UTF-8");-- if (result == null) return new HashMap<String, String>();- return result;- } catch (Exception e) {- return new HashMap<String, String>();- }- }-- public static httpHeader whead(- yacyURL url,- String vhost,- int timeout,- String user,- String password,- httpRemoteProxyConfig theRemoteProxyConfig- ) throws IOException {- return whead(url,vhost,timeout,user,password,theRemoteProxyConfig,null);- }-- public static httpHeader whead(- yacyURL url,- String vhost,- int timeout,- String user,- String password,- httpRemoteProxyConfig theRemoteProxyConfig,- httpHeader requestHeader- ) throws IOException {- // generate request header- if (requestHeader == null) requestHeader = new httpHeader();- if ((user != null) && (password != null) && (user.length() != 0)) {- requestHeader.put(httpHeader.AUTHORIZATION, kelondroBase64Order.standardCoder.encodeString(user + ":" + password));- }- // parse query-- int port = url.getPort();- boolean ssl = url.getProtocol().equals("https");- if (port < 0) port = (ssl) ? 443 : 80;- String path = url.getPath();- String query = url.getQuery();- if ((query != null) && (query.length() > 0)) path = path + "?" + query;- String realhost = url.getHost();-- // start connection- httpc con = new httpc(realhost, vhost, port, timeout, ssl, theRemoteProxyConfig, null, null);- httpc.response res = con.HEAD(path, requestHeader);- httpHeader h = res.responseHeader;- con.close();- return h;- }-- public static byte[] wput(- yacyURL url,- String vhost,- int timeout,- String user,- String password,- httpRemoteProxyConfig theRemoteProxyConfig,- serverObjects props,- HashMap<String, byte[]> files- ) throws IOException {- // splitting of the byte array into lines- byte[] a = singlePOST(- url,- vhost,- timeout,- user,- password,- theRemoteProxyConfig,- props,- files- );-- if (a == null) return null;-- // support of gzipped data- a = serverFileUtils.uncompressGZipArray(a);-- // return result- return a;-- //System.out.println("wput-out=" + new String(a));- //return nxTools.strings(a);- }-- public static void main(String[] args) {- System.out.println("ANOMIC.DE HTTP CLIENT v" + vDATE);- String url = args[0];- if (!(url.toUpperCase().startsWith("HTTP://"))) url = "http://" + url;- ArrayList<String> text = new ArrayList<String>();- if (args.length == 4) {- int timeout = Integer.parseInt(args[1]);- String proxyHost = args[2];- int proxyPort = Integer.parseInt(args[3]);-- httpRemoteProxyConfig theRemoteProxyConfig = httpRemoteProxyConfig.init(proxyHost,proxyPort);- try {- yacyURL u = new yacyURL(url, null);- text = nxTools.strings(wget(u, u.getHost(), timeout, null, null, theRemoteProxyConfig, null, null));- } catch (MalformedURLException e) {- System.out.println("The url '" + url + "' is wrong.");- } catch (IOException e) {- System.out.println("Error loading url '" + url + "': " + e.getMessage());- }- } /*else {- serverObjects post = new serverObjects();- int p;- for (int i = 1; i < args.length; i++) {- p = args[i].indexOf("=");- if (p > 0) post.put(args[i].substring(0, p), args[i].substring(p + 1));- }- text = wput(url, post);- }*/- Iterator<String> i = text.listIterator();- while (i.hasNext()) System.out.println(i.next());- }-- /**- * Inner Class to get the response of an http-request and parse it.- */- public final class response {- // Response-Header = Date | Pragma | Allow | Content-Encoding | Content-Length | Content-Type |- // Expires | Last-Modified | HTTP-header- /*- Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF- 1xx: Informational - Not used, but reserved for future use- 2xx: Success - The action was successfully received, understood, and accepted.- 3xx: Redirection - Further action must be taken in order to complete the request- 4xx: Client Error - The request contains bad syntax or cannot be fulfilled- 5xx: Server Error - The server failed to fulfill an apparently valid request- */-- // header information- public httpHeader responseHeader = null;- public String httpVer = "HTTP/0.9";- public String status; // the success/failure response string starting with status-code- public int statusCode = 503;- public String statusText = "internal error";- private boolean gzip; // for gunzipping on-the-fly- private long gzippedLength = -1; // reported content length if content-encoding is set-- /**- * Constructor for this class. Reads in the content for the given outer- * instance and parses it.- *- * @param zipped true, if the content of this response is gzipped.- * @throws IOException- */- public response(boolean zipped) throws IOException {-- // lets start with worst-case attributes as set-up- this.responseHeader = new httpHeader(reverseMappingCache);- this.statusCode = 503;- this.statusText = "internal httpc error";- this.status = Integer.toString(this.statusCode) + " " + this.statusText;- this.gzip = false;-- // check connection status- if (httpc.this.clientInput == null) {- // the server has meanwhile disconnected- this.statusCode = 503;- this.statusText = "lost connection to server";- this.status = Integer.toString(this.statusCode) + " " + this.statusText;- return; // in bad mood- }-- // reads in the http header, right now, right here- byte[] b = serverCore.receive(httpc.this.clientInput, terminalMaxLength, true);- if (b == null) {- // the server has meanwhile disconnected- this.statusCode = 503;- this.statusText = "server has closed connection";- this.status = Integer.toString(this.statusCode) + " " + this.statusText;- return; // in bad mood- }-- // parsing the response status line- String buffer = new String(b);- Object[] responseInfo = httpHeader.parseResponseLine(buffer);- this.httpVer = (String) responseInfo[0];- this.statusCode = ((Integer)responseInfo[1]).intValue();- this.statusText = (String) responseInfo[2];- this.status = this.statusCode + " " + this.statusText;-- if ((this.statusCode==500)&&(this.statusText.equals("status line parse error"))) {- // flush in anything that comes without parsing- while ((b != null) && (b.length != 0)) b = serverCore.receive(httpc.this.clientInput, terminalMaxLength, true);- return; // in bad mood- }-- // check validity- if (this.statusCode == 400) {- // bad request- // flush in anything that comes without parsing- while ((b = serverCore.receive(httpc.this.clientInput, terminalMaxLength, true)).length != 0) {}- return; // in bad mood- }-- // at this point we should have a valid response. read in the header properties- String key = "";- while ((b = serverCore.receive(httpc.this.clientInput, terminalMaxLength, true)) != null) {- if (b.length == 0) break;- buffer = new String(b);- buffer=buffer.trim();- //System.out.println("#H#" + buffer); // debug- // RFC2616 4.2: headers beginning with LWS are appended to the previous line- if (b[0] == serverCore.SP || b[0] == serverCore.HT) {- // use old entry- if (key.length() == 0) throw new IOException("header corrupted - input error");- // attach new line- if (!(this.responseHeader.containsKey(key))) throw new IOException("header corrupted - internal error");- this.responseHeader.put(key, (String) this.responseHeader.get(key) + " " + buffer.trim());- } else {- // create new entry- int p = buffer.indexOf(":");- if (p > 0) {- this.responseHeader.add(buffer.substring(0, p).trim(), buffer.substring(p + 1).trim());- } else {- serverLog.logSevere("HTTPC", "RESPONSE PARSE ERROR: HOST='" + httpc.this.adressed_host + "', PATH='" + httpc.this.requestPath + "', STATUS='" + this.status + "'");- serverLog.logSevere("HTTPC", "..............BUFFER: " + buffer);- throw new IOException(this.status);- }- }- }- // finished with reading header-- // we will now manipulate the header if the content is gzip encoded, because- // reading the content with "writeContent" will gunzip on-the-fly- this.gzip = ((zipped) && (this.responseHeader.gzip()));-- if (this.gzip) {- if (this.responseHeader.containsKey(httpHeader.CONTENT_LENGTH)) {- this.gzippedLength = this.responseHeader.contentLength();- }- this.responseHeader.remove(httpHeader.CONTENT_ENCODING); // we fake that we don't have encoding, since what comes out does not have gzip and we also don't know what was encoded- this.responseHeader.remove(httpHeader.CONTENT_LENGTH); // we cannot use the length during gunzippig yet; still we can hope that it works- }- }-- public long getGzippedLength() {- return this.gzippedLength;- }-- public boolean isGzipped() {- return this.gzip;- }-- /**- * Converts an instance of this class into a readable string.- *- * @return String with some information about this instance.- */- public String toString() {- StringBuffer toStringBuffer = new StringBuffer();- toStringBuffer.append((this.status == null) ? "Status: Unknown" : "Status: " + this.status)- .append(" | Headers: ")- .append((this.responseHeader == null) ? "none" : this.responseHeader.toString());- return new String(toStringBuffer);- }-- /**- * Returns wether this request was successful or not. Stati beginning- * with 2 or 3 are considered successful.- *- * @return True, if the request was successful.- */- public boolean success() {- return ((this.status.charAt(0) == '2') || (this.status.charAt(0) == '3'));- }-- /**- * If the response was encoded using <code>Content-Encoding: gzip</code>- * a {@link GZIPInputStream} is returned. If the <code>Content-Length</code> header was set,- * a {@link httpContentLengthInputStream} is returned which returns <code>-1</code> if the end of the- * response body was reached.- *- * @return a {@link InputStream} to read the response body- * @throws IOException- */- public InputStream getContentInputStream() throws IOException {- if (this.gzip) {- // use a gzip input stream for Content-Encoding: gzip- return new GZIPInputStream(httpc.this.clientInput);- } else if (this.responseHeader.contentLength() != -1) {- // use a httpContentLengthInputStream to read until the end of the response body is reached- return new httpContentLengthInputStream(httpc.this.clientInput, this.responseHeader.contentLength());- }- // no Content-Lenght was set. In this case we can read until EOF- return httpc.this.clientInput;- }-- /**- * This method outputs the found content into an byte-array and- * additionally outputs it to procOS.- *- * @param procOS- * @return the found content- * @throws IOException- */- public byte[] writeContent(Object procOS, boolean returnByteArray) throws IOException {- serverByteBuffer sbb = null;-- if (returnByteArray) {- int contentLength = (int) this.responseHeader.contentLength();- sbb = new serverByteBuffer((contentLength==-1)?8192:contentLength);- }-- if (procOS instanceof OutputStream) {- writeX(this.getContentInputStream(), (OutputStream) procOS, sbb);- } else if (procOS instanceof Writer) {- String charSet = this.responseHeader.getCharacterEncoding();- if (charSet == null) charSet = httpHeader.DEFAULT_CHARSET;- writeX(this.getContentInputStream(), charSet, (Writer) procOS, sbb, charSet);- } else {- throw new IllegalArgumentException("Invalid procOS object type '" + procOS.getClass().getName() + "'");- }-- return (sbb==null)?null:sbb.getBytes();- }-- /**- * This method writes the input stream to either another output stream- * or a file or both.- * In case that an exception occurrs, the stream reading is just teminated- * and content received so far is returned- *- * @param procOS- * @param file- * @throws IOException- */- public void writeContent(Object procOS, File file) throws IOException {- // this writes the input stream to either another output stream or- // a file or both.- FileOutputStream bufferOS = null;- if (file != null) try {- bufferOS = new FileOutputStream(file);- } catch (FileNotFoundException e) {- file = null;- }- InputStream is = this.getContentInputStream();- if (procOS == null) {- writeX(is, null, bufferOS);- } else if (procOS instanceof OutputStream) {- writeX(is, (OutputStream) procOS, bufferOS);- //writeContentX(httpc.this.clientInput, this.gzip, this.responseHeader.contentLength(), procOS, bufferOS);- } else if (procOS instanceof Writer) {- String charSet = this.responseHeader.getCharacterEncoding();- if (charSet == null) charSet = httpHeader.DEFAULT_CHARSET;- writeX(is, charSet, (Writer) procOS, bufferOS, charSet);- } else {- throw new IllegalArgumentException("Invalid procOS object type '" + procOS.getClass().getName() + "'");- }-- if (bufferOS != null) {- try {- bufferOS.flush();- bufferOS.close();- } catch (IOException e) {- e.printStackTrace();- }- if ((file != null) && (file.length() == 0)) file.delete();- }- }--- public void writeX(InputStream source, OutputStream procOS, OutputStream bufferOS) throws IOException {- byte[] buffer = new byte[2048];- int l, c = 0;- lastIO = System.currentTimeMillis();-- io: while (true) {- l = source.read(buffer, 0, buffer.length);- if (l < 0) break;- if (l == 0) try {- if (System.currentTimeMillis() - lastIO > 30000) break;- this.wait(300);- continue io;- } catch (InterruptedException e) {- e.printStackTrace();- } // may happen without EOF- lastIO = System.currentTimeMillis();- c += l;- if (procOS != null) procOS.write(buffer, 0, l);- if (bufferOS != null) bufferOS.write(buffer, 0, l);- }-- // flush the streams- if (procOS != null) try { procOS.flush(); } catch (IOException e) {}- if (bufferOS != null) try { bufferOS.flush(); } catch (IOException e) {}- buffer = null;- }-- public void writeX(InputStream source, String inputCharset, Writer procOS, OutputStream bufferOS, String outputCharset) {- try {- InputStreamReader sourceReader = new InputStreamReader(source, inputCharset);- OutputStreamWriter bufferOSWriter = (bufferOS == null) ? null : new OutputStreamWriter(bufferOS,outputCharset);- char[] buffer = new char[2048];- int l, c= 0;- lastIO = System.currentTimeMillis();-- io: while (true) try{- l = sourceReader.read(buffer, 0, buffer.length);- if (l < 0) break;- if (l == 0) try {- if (System.currentTimeMillis() - lastIO > 30000) break;- this.wait(300);- continue io;- } catch (InterruptedException e) {- e.printStackTrace();- } // may happen without EOF- lastIO = System.currentTimeMillis();- c += l;- if (procOS != null) procOS.write(buffer, 0, l);- if (bufferOSWriter != null) bufferOSWriter.write(buffer, 0, l);- } catch (IOException e) {- System.out.println("*** DEBUG: writeX/ReaderWriter terminated with IOException, processed " + c + " bytes. cause: " + e.getMessage());- break;- }-- // flush the streams- if (procOS != null) try { procOS.flush(); } catch (IOException e) {}- if (bufferOSWriter != null) try { bufferOSWriter.flush(); } catch (IOException e) {}- buffer = null;- } catch (IOException e) {}- }-- /**- * This method outputs a logline to the serverlog with the current- * status of this instance.- */- public void print() {- serverLog.logInfo("HTTPC", "RESPONSE: status=" + this.status + ", header=" + this.responseHeader.toString());- }-- }--}--/*-import java.net.*;-import java.io.*;-import javax.net.ssl.*;-import javax.security.cert.X509Certificate;-import java.security.KeyStore;--- //The application can be modified to connect to a server outside- //the firewall by following SSLSocketClientWithTunneling.java.--public class SSLSocketClientWithClientAuth {-- public static void main(String[] args) throws Exception {- String host = null;- int port = -1;- String path = null;- for (int i = 0; i < args.length; i++)- System.out.println(args[i]);-- if (args.length < 3) {- System.out.println(- "USAGE: java SSLSocketClientWithClientAuth " +- "host port requestedfilepath");- System.exit(-1);- }-- try {- host = args[0];- port = Integer.parseInt(args[1]);- path = args[2];- } catch (IllegalArgumentException e) {- System.out.println("USAGE: java SSLSocketClientWithClientAuth " +- "host port requestedfilepath");- System.exit(-1);- }-- try {-- SSLSocketFactory factory = null;- try {- SSLContext ctx;- KeyManagerFactory kmf;- KeyStore ks;- char[] passphrase = "passphrase".toCharArray();-- ctx = SSLContext.getInstance("TLS");- kmf = KeyManagerFactory.getInstance("SunX509");- ks = KeyStore.getInstance("JKS");-- ks.load(new FileInputStream("testkeys"), passphrase);-- kmf.init(ks, passphrase);- ctx.init(kmf.getKeyManagers(), null, null);-- factory = ctx.getSocketFactory();- } catch (Exception e) {- throw new IOException(e.getMessage());- }-- SSLSocket socket = (SSLSocket)factory.createSocket(host, port);-- socket.startHandshake();-- PrintWriter out = new PrintWriter(- new BufferedWriter(- new OutputStreamWriter(- socket.getOutputStream())));- out.println("GET " + path + " HTTP/1.1");- out.println();- out.flush();-- if (out.checkError())- System.out.println(- "SSLSocketClient: java.io.PrintWriter error");-- BufferedReader in = new BufferedReader(- new InputStreamReader(- socket.getInputStream()));-- String inputLine;-- while ((inputLine = in.readLine()) != null)- System.out.println(inputLine);-- in.close();- out.close();- socket.close();-- } catch (Exception e) {- e.printStackTrace();- }- }-}- */diff --git a/source/de/anomic/http/httpd.java b/source/de/anomic/http/httpd.javaindex 9d10f37ea..01297dfba 100644--- a/source/de/anomic/http/httpd.java+++ b/source/de/anomic/http/httpd.java@@ -54,6 +54,7 @@ import java.io.PrintStream;import java.io.UnsupportedEncodingException;import java.net.InetAddress;import java.net.MalformedURLException;+import java.net.URLDecoder;import java.net.URLEncoder;import java.util.Arrays;import java.util.Date;@@ -329,6 +330,7 @@ public final class httpd implements serverHandler {serverCore.CRLF_STRING).getBytes());this.session.out.write((httpHeader.CONTENT_LENGTH + ": 0\r\n").getBytes());this.session.out.write("\r\n".getBytes());+ this.session.out.flush();return false;}}@@ -424,6 +426,7 @@ public final class httpd implements serverHandler {httpHeader.PROXY_AUTHENTICATE + ": Basic realm=\"log-in\"" + serverCore.CRLF_STRING).getBytes());this.session.out.write((httpHeader.CONTENT_LENGTH + ": 0\r\n").getBytes());this.session.out.write("\r\n".getBytes());+ this.session.out.flush();return false;}@@ -1211,7 +1214,7 @@ public final class httpd implements serverHandler {// Generated Tue, 23 Aug 2005 11:19:14 GMT by brain.wg (squid/2.5.STABLE3)// adding some system information- String systemDate = httpc.dateString(httpc.nowDate());+ String systemDate = HttpClient.dateString(new Date());tp.put("date", systemDate);// rewrite the file@@ -1312,9 +1315,9 @@ public final class httpd implements serverHandler {Date now = new Date(System.currentTimeMillis());headers.put(httpHeader.SERVER, "AnomicHTTPD (www.anomic.de)");- headers.put(httpHeader.DATE, httpc.dateString(now));+ headers.put(httpHeader.DATE, HttpClient.dateString(now));if (moddate.after(now)) moddate = now;- headers.put(httpHeader.LAST_MODIFIED, httpc.dateString(moddate));+ headers.put(httpHeader.LAST_MODIFIED, HttpClient.dateString(moddate));if (nocache) {if (httpVersion.toUpperCase().equals(httpHeader.HTTP_VERSION_1_1)) headers.put(httpHeader.CACHE_CONTROL, "no-cache");@@ -1328,7 +1331,7 @@ public final class httpd implements serverHandler {headers.put(httpHeader.CONTENT_TYPE, contentType);if (contentLength > 0) headers.put(httpHeader.CONTENT_LENGTH, Long.toString(contentLength));//if (cookie != null) headers.put(httpHeader.SET_COOKIE, cookie);- if (expires != null) headers.put(httpHeader.EXPIRES, httpc.dateString(expires));+ if (expires != null) headers.put(httpHeader.EXPIRES, HttpClient.dateString(expires));if (contentEnc != null) headers.put(httpHeader.CONTENT_ENCODING, contentEnc);if (transferEnc != null) headers.put(httpHeader.TRANSFER_ENCODING, transferEnc);@@ -1379,7 +1382,7 @@ public final class httpd implements serverHandler {// prepare headerif (!header.containsKey(httpHeader.DATE))- header.put(httpHeader.DATE, httpc.dateString(httpc.nowDate()));+ header.put(httpHeader.DATE, HttpClient.dateString(new Date()));if (!header.containsKey(httpHeader.CONTENT_TYPE))header.put(httpHeader.CONTENT_TYPE, "text/html; charset=UTF-8"); // fix thisif (!header.containsKey(httpHeader.CONNECTION) && conProp.containsKey(httpHeader.CONNECTION_PROP_PERSISTENT))diff --git a/source/de/anomic/http/httpdFileHandler.java b/source/de/anomic/http/httpdFileHandler.javaindex b570f8b45..9ce8d6fb0 100644--- a/source/de/anomic/http/httpdFileHandler.java+++ b/source/de/anomic/http/httpdFileHandler.java@@ -252,7 +252,7 @@ public final class httpdFileHandler {ext = path.substring(pos + 1).toLowerCase();}headers.put(httpHeader.SERVER, "AnomicHTTPD (www.anomic.de)");- headers.put(httpHeader.DATE, httpc.dateString(httpc.nowDate()));+ headers.put(httpHeader.DATE, HttpClient.dateString(new Date()));if(!(plasmaParser.mediaExtContains(ext))){headers.put(httpHeader.PRAGMA, "no-cache");}diff --git a/source/de/anomic/http/httpdProxyHandler.java b/source/de/anomic/http/httpdProxyHandler.javaindex e761d61af..9bd90246e 100644--- a/source/de/anomic/http/httpdProxyHandler.java+++ b/source/de/anomic/http/httpdProxyHandler.java@@ -63,7 +63,9 @@package de.anomic.http;import java.io.BufferedReader;+import java.io.ByteArrayOutputStream;import java.io.File;+import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;@@ -93,6 +95,7 @@ import java.util.zip.GZIPOutputStream;import de.anomic.htmlFilter.htmlFilterContentTransformer;import de.anomic.htmlFilter.htmlFilterTransformer;import de.anomic.htmlFilter.htmlFilterWriter;+import de.anomic.http.HttpResponse.Saver;import de.anomic.index.indexReferenceBlacklist;import de.anomic.plasma.plasmaHTCache;import de.anomic.plasma.plasmaParser;@@ -123,8 +126,11 @@ public final class httpdProxyHandler {private static BufferedReader redirectorReader;private static htmlFilterTransformer transformer = null;- public static final String proxyUserAgent = "yacy (" + httpc.systemOST +") yacy.net";- public static final String crawlerUserAgent = "yacybot (" + httpc.systemOST +") http://yacy.net/bot.html";+ /**+ * *The* remote Proxy configuration+ */+ private static httpRemoteProxyConfig remoteProxyConfig = null;+ private static final String proxyUserAgent = "yacy (" + HttpClient.getSystemOST() +") yacy.net";private static File htRootPath = null;//private Properties connectionProperties = null;@@ -383,10 +389,7 @@ public final class httpdProxyHandler {requestHeader.put(httpHeader.USER_AGENT, generateUserAgent(requestHeader));}- // setting the X-Forwarded-For Header- if (switchboard.getConfigBool("proxy.sendXForwardedForHeader", true)) {- requestHeader.put(httpHeader.X_FORWARDED_FOR,conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));- }+ addXForwardedForHeader(conProp, requestHeader);// decide wether to use a cache entry or connect to the networkFile cacheFile = plasmaHTCache.getCachePath(url);@@ -480,8 +483,7 @@ public final class httpdProxyHandler {httpChunkedOutputStream chunkedOut = null;Object hfos = null;- httpc remote = null;- httpc.response res = null;+ HttpResponse res = null;try {String host = conProp.getProperty(httpHeader.CONNECTION_PROP_HOST);@@ -510,48 +512,44 @@ public final class httpdProxyHandler {(!(remotePath.startsWith("/env"))) // this is the special path, staying always at root-level) remotePath = yAddress.substring(pos) + remotePath;- // open the connection- remote = (yAddress == null) ? newhttpc(host, port, timeout) : newhttpc(yAddress, timeout);+ prepareHeader(requestHeader, httpVer);- // removing hop by hop headers- removeHopByHopHeaders(requestHeader);+ // generate request-url+ final String connectHost = (yAddress == null) ? host +":"+ port : yAddress;+ final String getUrl = "http://"+ connectHost + remotePath;- // adding additional headers- setViaHeader(requestHeader, httpVer);+ // setup HTTP-client+ final HttpClient client = HttpFactory.newClient(requestHeader, timeout);// send request- res = remote.GET(remotePath, requestHeader);+ try {+ res = client.GET(getUrl);conProp.put(httpHeader.CONNECTION_PROP_CLIENT_REQUEST_HEADER,requestHeader);// determine if it's an internal error of the httpc- if (res.responseHeader.size() == 0) {- throw new Exception(res.statusText);+ if (res.getResponseHeader().size() == 0) {+ throw new Exception(res.getStatusLine());}// if the content length is not set we have to use chunked transfer encoding- long contentLength = res.responseHeader.contentLength();+ long contentLength = res.getResponseHeader().contentLength();if (contentLength < 0) {// according to http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html// a 204,304 message must not contain a message body.// Therefore we need to set the content-length to 0.- if (res.status.startsWith("204") ||- res.status.startsWith("304")) {- res.responseHeader.put(httpHeader.CONTENT_LENGTH,"0");+ if (res.getStatusCode() == 204 ||+ res.getStatusCode() == 304) {+ res.getResponseHeader().put(httpHeader.CONTENT_LENGTH,"0");} else {if (httpVer.equals(httpHeader.HTTP_VERSION_0_9) || httpVer.equals(httpHeader.HTTP_VERSION_1_0)) {conProp.setProperty(httpHeader.CONNECTION_PROP_PERSISTENT,"close");} else {chunkedOut = new httpChunkedOutputStream(respond);}- res.responseHeader.remove(httpHeader.CONTENT_LENGTH);+ res.getResponseHeader().remove(httpHeader.CONTENT_LENGTH);}}-// if (((String)requestHeader.get(httpHeader.ACCEPT_ENCODING,"")).indexOf("gzip") != -1) {-// zipped = new GZIPOutputStream((chunked != null) ? chunked : respond);-// res.responseHeader.put(httpHeader.CONTENT_ENCODING, "gzip");-// res.responseHeader.remove(httpHeader.CONTENT_LENGTH);-// }// the cache does either not exist or is (supposed to be) stalelong sizeBeforeDelete = -1;@@ -564,14 +562,14 @@ public final class httpdProxyHandler {// reserver cache entryDate requestDate = new Date(((Long)conProp.get(httpHeader.CONNECTION_PROP_REQUEST_START)).longValue());- IResourceInfo resInfo = new ResourceInfo(url,requestHeader,res.responseHeader);+ IResourceInfo resInfo = new ResourceInfo(url,requestHeader,res.getResponseHeader());plasmaHTCache.Entry cacheEntry = plasmaHTCache.newEntry(requestDate,0,url,"",//requestHeader,- res.status,+ res.getStatusLine(),//res.responseHeader,resInfo,null,@@ -581,41 +579,40 @@ public final class httpdProxyHandler {// handle file types and make (possibly transforming) output streamif ((!transformer.isIdentityTransformer()) &&- (plasmaParser.supportedHTMLContent(url,res.responseHeader.mime()))+ (plasmaParser.supportedHTMLContent(url,res.getResponseHeader().mime()))) {// make a transformertheLogger.logFine("create transformer for URL " + url);//hfos = new htmlFilterOutputStream((gzippedOut != null) ? gzippedOut : ((chunkedOut != null)? chunkedOut : respond), null, transformer, (ext.length() == 0));- String charSet = res.responseHeader.getCharacterEncoding();- if (charSet == null) charSet = httpHeader.DEFAULT_CHARSET;+ String charSet = httpHeader.getCharSet(res.getResponseHeader());hfos = new htmlFilterWriter((gzippedOut != null) ? gzippedOut : ((chunkedOut != null)? chunkedOut : respond),charSet, null, transformer, (ext.length() == 0));} else {// simply pass through without parsing- theLogger.logFine("create passthrough for URL " + url + ", extension '" + ext + "', mime-type '" + res.responseHeader.mime() + "'");+ theLogger.logFine("create passthrough for URL " + url + ", extension '" + ext + "', mime-type '" + res.getResponseHeader().mime() + "'");hfos = (gzippedOut != null) ? gzippedOut : ((chunkedOut != null)? chunkedOut : respond);}// handle incoming cookies- handleIncomingCookies(res.responseHeader, host, ip);+ handleIncomingCookies(res.getResponseHeader(), host, ip);// remove hop by hop headers- removeHopByHopHeaders(res.responseHeader);+ removeHopByHopHeaders(res.getResponseHeader());// adding additional headers- setViaHeader(res.responseHeader, res.httpVer);+ setViaHeader(res.getResponseHeader(), res.getHttpVer());// sending the respond header back to the clientif (chunkedOut != null) {- res.responseHeader.put(httpHeader.TRANSFER_ENCODING, "chunked");+ res.getResponseHeader().put(httpHeader.TRANSFER_ENCODING, "chunked");}httpd.sendRespondHeader(conProp,respond,httpVer,- res.statusCode,- res.statusText,- res.responseHeader);+ res.getStatusCode(),+ res.getStatusLine().substring(4), // status text+ res.getResponseHeader());String storeError = cacheEntry.shallStoreCacheForProxy();boolean storeHTCache = cacheEntry.profile().storeHTCache();@@ -636,7 +633,15 @@ public final class httpdProxyHandler {if ((contentLength > 0) && (contentLength < 1048576)) // if the length is known and < 1 MB{// ok, we don't write actually into a file, only to RAM, and schedule writing the file.- byte[] cacheArray = res.writeContent(hfos,true);+ ByteArrayOutputStream byteStream = new ByteArrayOutputStream();+ Saver.writeContent(res, hfos, byteStream);+ // cached bytes+ byte[] cacheArray;+ if(byteStream.size() > 0) {+ cacheArray = byteStream.toByteArray();+ } else {+ cacheArray = null;+ }theLogger.logFine("writeContent of " + url + " produced cacheArray = " + ((cacheArray == null) ? "null" : ("size=" + cacheArray.length)));if (hfos instanceof htmlFilterWriter) ((htmlFilterWriter) hfos).finalize();@@ -664,7 +669,7 @@ public final class httpdProxyHandler {// the file is too big to cache it in the ram, or the size is unknown// write to file right here.cacheFile.getParentFile().mkdirs();- res.writeContent(hfos, cacheFile);+ Saver.writeContent(res, hfos, new FileOutputStream(cacheFile));if (hfos instanceof htmlFilterWriter) ((htmlFilterWriter) hfos).finalize();theLogger.logFine("for write-file of " + url + ": contentLength = " + contentLength + ", sizeBeforeDelete = " + sizeBeforeDelete);plasmaHTCache.writeFileAnnouncement(cacheFile);@@ -694,7 +699,7 @@ public final class httpdProxyHandler {" StoreHTCache=" + storeHTCache +" SupportetContent=" + isSupportedContent);- res.writeContent(hfos, null);+ Saver.writeContent(res, hfos, null);if (hfos instanceof htmlFilterWriter) ((htmlFilterWriter) hfos).finalize();if (sizeBeforeDelete == -1) {// no old file and no load. just data passing@@ -707,8 +712,6 @@ public final class httpdProxyHandler {}conProp.setProperty(httpHeader.CONNECTION_PROP_PROXY_RESPOND_CODE,"TCP_MISS");}-- remote.close();if (gzippedOut != null) {gzippedOut.finish();@@ -717,14 +720,20 @@ public final class httpdProxyHandler {chunkedOut.finish();chunkedOut.flush();}+ } finally {+ // if opened ...+ if(res != null) {+ // ... close connection+ res.closeStream();+ }+ }} catch (Exception e) {// deleting cached contentif (cacheFile.exists()) cacheFile.delete();- handleProxyException(e,remote,conProp,respond,url);+ handleProxyException(e,conProp,respond,url);}}-private static void fulfillRequestFromCache(Properties conProp,yacyURL url,@@ -743,14 +752,10 @@ public final class httpdProxyHandler {// we respond on the request by using the cache, the cache is freshtry {- // remove hop by hop headers- removeHopByHopHeaders(cachedResponseHeader);-- // adding additional headers- setViaHeader(cachedResponseHeader, httpVer);+ prepareHeader(cachedResponseHeader, httpVer);// replace date field in old header by actual date, this is according to RFC- cachedResponseHeader.put(httpHeader.DATE, httpc.dateString(httpc.nowDate()));+ cachedResponseHeader.put(httpHeader.DATE, HttpClient.dateString(new Date()));// if (((String)requestHeader.get(httpHeader.ACCEPT_ENCODING,"")).indexOf("gzip") != -1) {// chunked = new httpChunkedOutputStream(respond);@@ -789,8 +794,7 @@ public final class httpdProxyHandler {//respondHeader(respond, "203 OK", cachedResponseHeader); // respond with 'non-authoritative'// determine the content charset- String charSet = cachedResponseHeader.getCharacterEncoding();- if (charSet == null) charSet = httpHeader.DEFAULT_CHARSET;+ String charSet = httpHeader.getCharSet(cachedResponseHeader);// make a transformerif (( !transformer.isIdentityTransformer()) &&@@ -863,8 +867,7 @@ public final class httpdProxyHandler {public static void doHead(Properties conProp, httpHeader requestHeader, OutputStream respond) {- httpc remote = null;- httpc.response res = null;+ HttpResponse res = null;yacyURL url = null;try {// remembering the starting time of the request@@ -920,10 +923,7 @@ public final class httpdProxyHandler {requestHeader.put(httpHeader.USER_AGENT, generateUserAgent(requestHeader));}- // setting the X-Forwarded-For Header- if (switchboard.getConfigBool("proxy.sendXForwardedForHeader", true)) {- requestHeader.put(httpHeader.X_FORWARDED_FOR,conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));- }+ addXForwardedForHeader(conProp, requestHeader);// resolve yacy and yacyh domainsString yAddress = yacyCore.seedDB.resolveYacyAddress(host);@@ -931,41 +931,51 @@ public final class httpdProxyHandler {// attach possible yacy-sublevel-domainif ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0)) remotePath = yAddress.substring(pos) + remotePath;- // removing hop by hop headers- removeHopByHopHeaders(requestHeader);-- // adding outgoing headers- setViaHeader(requestHeader, httpVer);+ prepareHeader(requestHeader, httpVer);++ // setup HTTP-client+ HttpClient client = HttpFactory.newClient();+ client.setTimeout(timeout);- // open the connection: second is needed for [AS] patch- remote = (yAddress == null) ? newhttpc(host, port, timeout): newhttpc(yAddress, timeout);+ // set header for connection+ client.setHeader(requestHeader);+ // send request+ final String connectHost = (yAddress == null) ? host +":"+ port : yAddress;+ client.setProxy(getProxyConfig(connectHost));+ final String getUrl = "http://"+ connectHost + remotePath;++ try {// sending the http-HEAD request to the server- res = remote.HEAD(remotePath, requestHeader);+ res = client.HEAD(getUrl);// determine if it's an internal error of the httpc- if (res.responseHeader.size() == 0) {- throw new Exception(res.statusText);+ if (res.getResponseHeader().size() == 0) {+ throw new Exception(res.getStatusLine());}// removing hop by hop headers- removeHopByHopHeaders(res.responseHeader);+ removeHopByHopHeaders(res.getResponseHeader());// adding outgoing headers- setViaHeader(res.responseHeader, res.httpVer);+ setViaHeader(res.getResponseHeader(), res.getHttpVer());// sending the server respond back to the client- httpd.sendRespondHeader(conProp,respond,httpVer,res.statusCode,res.statusText,res.responseHeader);+ httpd.sendRespondHeader(conProp,respond,httpVer,res.getStatusCode(),res.getStatusLine().substring(4),res.getResponseHeader());respond.flush();- remote.close();+ } finally {+ if(res != null) {+ // ... close connection+ res.closeStream();+ }+ }} catch (Exception e) {- handleProxyException(e,remote,conProp,respond,url);+ handleProxyException(e,conProp,respond,url);}}public static void doPost(Properties conProp, httpHeader requestHeader, OutputStream respond, PushbackInputStream body) throws IOException {- httpc remote = null;yacyURL url = null;try {// remembering the starting time of the request@@ -1006,10 +1016,7 @@ public final class httpdProxyHandler {requestHeader.put(httpHeader.USER_AGENT, generateUserAgent(requestHeader));}- // setting the X-Forwarded-For Header- if (switchboard.getConfigBool("proxy.sendXForwardedForHeader", true)) {- requestHeader.put(httpHeader.X_FORWARDED_FOR,conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));- }+ addXForwardedForHeader(conProp, requestHeader);// resolve yacy and yacyh domainsString yAddress = yacyCore.seedDB.resolveYacyAddress(host);@@ -1020,68 +1027,83 @@ public final class httpdProxyHandler {// attach possible yacy-sublevel-domainif ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0)) remotePath = yAddress.substring(pos) + remotePath;- // removing hop by hop headers- removeHopByHopHeaders(requestHeader);+ prepareHeader(requestHeader, httpVer);- // adding additional headers- setViaHeader(requestHeader, httpVer);+ // setup HTTP-client+ JakartaCommonsHttpClient client = new JakartaCommonsHttpClient();+ client.setTimeout(timeout);+ // set header for connection+ client.setHeader(requestHeader);++ // send request+ final String connectHost = (yAddress == null) ? host +":"+ port : yAddress;+ client.setProxy(getProxyConfig(connectHost));+ final String getUrl = "http://"+ connectHost + remotePath;+ HttpResponse res = null;+ try {// sending the request- remote = (yAddress == null) ? newhttpc(host, port, timeout) : newhttpc(yAddress, timeout);- httpc.response res = remote.POST(remotePath, requestHeader, body);+ // is the input stream required and valid HTTP-data?+ res = client.POST(getUrl, body);// determine if it's an internal error of the httpc- if (res.responseHeader.size() == 0) {- throw new Exception(res.statusText);+ if (res.getResponseHeader().size() == 0) {+ throw new Exception(res.getStatusLine());}// if the content length is not set we need to use chunked content encoding- long contentLength = res.responseHeader.contentLength();+ long contentLength = res.getResponseHeader().contentLength();httpChunkedOutputStream chunked = null;if (contentLength <= 0) {// according to http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html// a 204,304 message must not contain a message body.// Therefore we need to set the content-length to 0.- if (res.status.startsWith("204") ||- res.status.startsWith("304")) {- res.responseHeader.put(httpHeader.CONTENT_LENGTH,"0");+ if (res.getStatusCode() == 204 ||+ res.getStatusCode() == 304) {+ res.getResponseHeader().put(httpHeader.CONTENT_LENGTH,"0");} else {if (httpVer.equals("HTTP/0.9") || httpVer.equals("HTTP/1.0")) {forceConnectionClose(conProp);} else {chunked = new httpChunkedOutputStream(respond);}- res.responseHeader.remove(httpHeader.CONTENT_LENGTH);+ res.getResponseHeader().remove(httpHeader.CONTENT_LENGTH);}}// remove hop by hop headers- removeHopByHopHeaders(res.responseHeader);+ removeHopByHopHeaders(res.getResponseHeader());// adding additional headers- setViaHeader(res.responseHeader, res.httpVer);+ setViaHeader(res.getResponseHeader(), res.getHttpVer());// sending the respond header back to the clientif (chunked != null) {- res.responseHeader.put(httpHeader.TRANSFER_ENCODING, "chunked");+ res.getResponseHeader().put(httpHeader.TRANSFER_ENCODING, "chunked");}// sending response headershttpd.sendRespondHeader(conProp,respond,httpVer,- res.statusCode,- res.statusText,- res.responseHeader);+ res.getStatusCode(),+ res.getStatusLine().substring(4), // status text+ res.getResponseHeader());// respondHeader(respond, res.status, res.responseHeader);- res.writeContent((chunked != null) ? chunked : respond, null);+ Saver.writeContent(res, (chunked != null) ? chunked : respond, null);if (chunked != null) chunked.finish();- remote.close();respond.flush();+ } finally {+ // if opened ...+ if(res != null) {+ // ... close connection+ res.closeStream();+ }+ }} catch (Exception e) {- handleProxyException(e,remote,conProp,respond,url);+ handleProxyException(e,conProp,respond,url);} finally {respond.flush();if (respond instanceof httpdByteCountOutputStream) ((httpdByteCountOutputStream)respond).finish();@@ -1091,6 +1113,30 @@ public final class httpdProxyHandler {logProxyAccess(conProp);}}++ /**+ * adds the client-IP of conProp to the requestHeader+ *+ * @param conProp+ * @param requestHeader+ */+ private static void addXForwardedForHeader(Properties conProp, httpHeader requestHeader) {+ // setting the X-Forwarded-For Header+ if (switchboard.getConfigBool("proxy.sendXForwardedForHeader", true)) {+ requestHeader.put(httpHeader.X_FORWARDED_FOR,conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));+ }+ }++ /**+ * removing hop by hop headers and adding additional headers+ *+ * @param requestHeader+ * @param httpVer+ */+ private static void prepareHeader(httpHeader requestHeader, String httpVer) {+ removeHopByHopHeaders(requestHeader);+ setViaHeader(requestHeader, httpVer);+ }public static void doConnect(Properties conProp, de.anomic.http.httpHeader requestHeader, InputStream clientIn, OutputStream clientOut) throws IOException {@@ -1123,41 +1169,43 @@ public final class httpdProxyHandler {}// possibly branch into PROXY-PROXY connection+ final httpRemoteProxyConfig proxyConfig = getRemoteProxyConfig();if (- (switchboard.remoteProxyConfig != null) &&- (switchboard.remoteProxyConfig.useProxy()) &&- (switchboard.remoteProxyConfig.useProxy4SSL())+ (proxyConfig != null) &&+ (proxyConfig.useProxy()) &&+ (proxyConfig.useProxy4SSL())) {- httpc remoteProxy = null;- try {- remoteProxy = new httpc(- host,- host,- port,- timeout,- false,- switchboard.remoteProxyConfig,- null, null- );+ HttpClient remoteProxy = HttpFactory.newClient();+ remoteProxy.setTimeout(timeout);+ remoteProxy.setProxy(proxyConfig);+ remoteProxy.setHeader(requestHeader);- httpc.response response = remoteProxy.CONNECT(host, port, requestHeader);- response.print();- if (response.success()) {+ HttpResponse response = null;+ try {+ response = remoteProxy.CONNECT(host, port);+ // outputs a logline to the serverlog with the current status+ serverLog.logInfo("HttpdProxyHandler", "RESPONSE: status=" + response.getStatusLine() + ", header=" + response.getResponseHeader().toString());+ // (response.getStatusLine().charAt(0) == '2') || (response.getStatusLine().charAt(0) == '3')+ final boolean success = response.getStatusCode() >= 200 && response.getStatusCode() <= 399;+ if (success) {// replace connection details- host = switchboard.remoteProxyConfig.getProxyHost();- port = switchboard.remoteProxyConfig.getProxyPort();- remoteProxy.close();+ host = proxyConfig.getProxyHost();+ port = proxyConfig.getProxyPort();// go on (see below)} else {// pass error response back to client- httpd.sendRespondHeader(conProp,clientOut,httpVersion,response.statusCode,response.statusText,response.responseHeader);+ httpd.sendRespondHeader(conProp,clientOut,httpVersion,response.getStatusCode(),response.getStatusLine().substring(4),response.getResponseHeader());//respondHeader(clientOut, response.status, response.responseHeader);forceConnectionClose(conProp);- remoteProxy.close();return;}} catch (Exception e) {throw new IOException(e.getMessage());+ } finally {+ if(response != null) {+ // release connection+ response.closeStream();+ }}}@@ -1234,79 +1282,85 @@ public final class httpdProxyHandler {}}- private static httpc newhttpc(String server, int port, int timeout) throws IOException {-- // getting the remote proxy configuration- httpRemoteProxyConfig remProxyConfig = switchboard.remoteProxyConfig;-- // a new httpc connection, combined with possible remote proxy+ /**+ * checks if proxy-config exists for server (is allowed and not denied)+ *+ * @param server+ * @param port not used (only to indicate that server is plain address)+ * @return proxy which should be used or null if no proxy should be used+ */+ public static httpRemoteProxyConfig getProxyConfig(final String server, final int port) {+ return getProxyConfig(server, getRemoteProxyConfig());+ }++ /**+ * checks if proxy-config is allowed and not denied+ *+ * @param server+ * @param remProxyConfig+ * @return proxy which should be used or null if no proxy should be used+ */+ public static httpRemoteProxyConfig getProxyConfig(final String server, httpRemoteProxyConfig remProxyConfig) {+ // possible remote proxy// check no-proxy rule- if (- (remProxyConfig != null) &&- (remProxyConfig.useProxy()) &&- (!(remProxyConfig.remoteProxyAllowProxySet.contains(server)))) {- if (remProxyConfig.remoteProxyDisallowProxySet.contains(server)) {- remProxyConfig = null;- } else {- // analyse remoteProxyNoProxy;- // set either remoteProxyAllowProxySet or remoteProxyDisallowProxySet accordingly- int i = 0;- while (i < remProxyConfig.getProxyNoProxyPatterns().length) {- if (server.matches(remProxyConfig.getProxyNoProxyPatterns()[i])) {- // disallow proxy for this server- switchboard.remoteProxyConfig.remoteProxyDisallowProxySet.add(server);+ if (remProxyConfig != null) {+ if (remProxyConfig.useProxy()) {+ if (!(remProxyConfig.remoteProxyAllowProxySet.contains(server))) {+ if (remProxyConfig.remoteProxyDisallowProxySet.contains(server)) {remProxyConfig = null;- break;+ } else {+ // analyse remoteProxyNoProxy;+ // set either remoteProxyAllowProxySet or remoteProxyDisallowProxySet accordingly+ boolean allowed = true;+ synchronized (remProxyConfig) {+ for (final String pattern :remProxyConfig.getProxyNoProxyPatterns()) {+ if (server.matches(pattern)) {+ // disallow proxy for this server+ allowed = false;+ remProxyConfig.remoteProxyDisallowProxySet.add(server);+ remProxyConfig = null;+ break;+ }+ }+ if (allowed) {+ // no pattern matches: allow server+ remProxyConfig.remoteProxyAllowProxySet.add(server);+ }+ }}- i++;- }- if (i == remProxyConfig.getProxyNoProxyPatterns().length) {- // no pattern matches: allow server- switchboard.remoteProxyConfig.remoteProxyAllowProxySet.add(server);}+ } else {+ // not enabled+ remProxyConfig = null;}}-- // branch to server/proxy- return new httpc(- server,- server,- port,- timeout,- false,- remProxyConfig,- null, null- );++ return remProxyConfig;}- private static httpc newhttpc(String address, int timeout) throws IOException {- // a new httpc connection for <host>:<port>/<path> syntax- // this is called when a '.yacy'-domain is used+ /**+ * gets proxy config for full adress (without protocol (ie. "http://"))+ * @param address full address with host and optionally port or path <host>:<port>/<path>+ * @return null if no proxy should be used+ */+ public static httpRemoteProxyConfig getProxyConfig(String address) {+ // host goes to portint p = address.indexOf(":");- if (p < 0) return null;- String server = address.substring(0, p);- address = address.substring(p + 1);- // remove possible path elements (may occur for 'virtual' subdomains- p = address.indexOf("/");- if (p >= 0) address = address.substring(0, p); // cut it off- int port = Integer.parseInt(address);- // normal creation of httpc object- return newhttpc(server, port, timeout);- }- /*- private void textMessage(OutputStream out, String body) throws IOException {- out.write(("HTTP/1.1 200 OK\r\n").getBytes());- out.write((httpHeader.SERVER + ": AnomicHTTPD (www.anomic.de)\r\n").getBytes());- out.write((httpHeader.DATE + ": " + httpc.dateString(httpc.nowDate()) + "\r\n").getBytes());- out.write((httpHeader.CONTENT_TYPE + ": text/plain\r\n").getBytes());- out.write((httpHeader.CONTENT_LENGTH + ": " + body.length() +"\r\n").getBytes());- out.write(("\r\n").getBytes());- out.flush();- out.write(body.getBytes());- out.flush();+ if (p < 0) {+ // no port, so host goes to path+ p = address.indexOf("/");+ }+ // host should have minimum 1 character ;)+ if(p > 0) {+ String server = address.substring(0, p);+ return getProxyConfig(server, 0);+ } else {+ // check if full address is in allow/deny-list+ return getProxyConfig(address, 0);+ }}- */- private static void handleProxyException(Exception e, httpc remote, Properties conProp, OutputStream respond, yacyURL url) {++ private static void handleProxyException(Exception e, Properties conProp, OutputStream respond, yacyURL url) {// this may happen if// - the targeted host does not exist// - anything with the remote server was wrong.@@ -1370,9 +1424,6 @@ public final class httpdProxyHandler {(exceptionMsg.indexOf("server has closed connection") >= 0))) {errorMessage = exceptionMsg;- } else if ((remote != null)&&(remote.isClosed())) {- // TODO: query for broken pipe- errorMessage = "Destination host unexpectedly closed connection";} else {errorMessage = "Unexpected Error. " + e.getClass().getName() + ": " + e.getMessage();unknownError = true;@@ -1627,6 +1678,20 @@ public final class httpdProxyHandler {// sending the logging message to the loggerproxyLog.logFine(new String(logMessage));}++ /**+ * @param remoteProxyConfig the remoteProxyConfig to set+ */+ public static void setRemoteProxyConfig(httpRemoteProxyConfig remoteProxyConfig) {+ httpdProxyHandler.remoteProxyConfig = remoteProxyConfig;+ }++ /**+ * @return the remoteProxyConfig+ */+ public static httpRemoteProxyConfig getRemoteProxyConfig() {+ return remoteProxyConfig;+ }}diff --git a/source/de/anomic/icap/icapd.java b/source/de/anomic/icap/icapd.javaindex 915580d71..e5e8b4574 100644--- a/source/de/anomic/icap/icapd.java+++ b/source/de/anomic/icap/icapd.java@@ -57,9 +57,9 @@ import java.net.InetAddress;import java.util.Date;import java.util.Properties;+import de.anomic.http.HttpClient;import de.anomic.http.httpChunkedInputStream;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.plasma.plasmaHTCache;import de.anomic.plasma.plasmaParser;import de.anomic.plasma.plasmaSwitchboard;@@ -145,7 +145,7 @@ public class icapd implements serverHandler {icapHeader newHeaders = new icapHeader();newHeaders.put(icapHeader.SERVER,"YaCy/" + switchboard.getConfig("vString",""));- newHeaders.put(icapHeader.DATE, httpc.dateString(httpc.nowDate()));+ newHeaders.put(icapHeader.DATE, HttpClient.dateString(new Date()));newHeaders.put(icapHeader.ISTAG, "\"" + switchboard.getConfig("vString","") + "\"");return newHeaders;diff --git a/source/de/anomic/index/indexRepositoryReference.java b/source/de/anomic/index/indexRepositoryReference.javaindex ed1a8321a..492438e08 100644--- a/source/de/anomic/index/indexRepositoryReference.java+++ b/source/de/anomic/index/indexRepositoryReference.java@@ -36,9 +36,10 @@ import java.util.HashSet;import java.util.Iterator;import de.anomic.data.htmlTools;+import de.anomic.http.HttpClient;+import de.anomic.http.HttpFactory;+import de.anomic.http.HttpResponse;import de.anomic.http.httpRemoteProxyConfig;-import de.anomic.http.httpc;-import de.anomic.http.httpc.response;import de.anomic.kelondro.kelondroBase64Order;import de.anomic.kelondro.kelondroCache;import de.anomic.kelondro.kelondroCloneableIterator;@@ -212,8 +213,8 @@ public final class indexRepositoryReference {/*** Uses an Iteration over urlHash.db to detect malformed URL-Entries.* Damaged URL-Entries will be marked in a HashSet and removed at the end of the function.- *- * @param homePath Root-Path where all information is to be found.+ *+ * @param proxyConfig*/public void deadlinkCleaner(httpRemoteProxyConfig proxyConfig) {serverLog log = new serverLog("URLDBCLEANUP");@@ -241,7 +242,6 @@ public final class indexRepositoryReference {urlHash = (String) eiter2.next();// trying to fix the invalid URL- httpc theHttpc = null;String oldUrlStr = null;try {// getting the url data as byte array@@ -257,26 +257,30 @@ public final class indexRepositoryReference {yacyURL newUrl = new yacyURL(newUrlStr, null);// doing a http head request to test if the url is correct- theHttpc = new httpc(newUrl.getHost(), newUrl.getHost(), newUrl.getPort(), 30000, false, proxyConfig, null, null);- response res = theHttpc.HEAD(newUrl.getPath(), null);+ HttpClient client = HttpFactory.newClient();+ client.setProxy(proxyConfig);+ HttpResponse res = null;+ try {+ res = client.HEAD(newUrl.toString());+ } finally {+ if(res != null) {+ // release connection+ res.closeStream();+ }+ }- if (res.statusCode == 200) {+ if (res.getStatusCode() == 200) {entry.setCol(1, newUrl.toString().getBytes());urlIndexFile.put(entry);log.logInfo("UrlDB-Entry with urlHash '" + urlHash + "' corrected\n\tURL: " + oldUrlStr + " -> " + newUrlStr);} else {remove(urlHash);- log.logInfo("UrlDB-Entry with urlHash '" + urlHash + "' removed\n\tURL: " + oldUrlStr + "\n\tConnection Status: " + res.status);+ log.logInfo("UrlDB-Entry with urlHash '" + urlHash + "' removed\n\tURL: " + oldUrlStr + "\n\tConnection Status: " + res.getStatusLine());}- theHttpc.close();}} catch (Exception e) {remove(urlHash);log.logInfo("UrlDB-Entry with urlHash '" + urlHash + "' removed\n\tURL: " + oldUrlStr + "\n\tExecption: " + e.getMessage());- } finally {- if (theHttpc != null) try {- theHttpc.close();- } catch (Exception e) { }}}diff --git a/source/de/anomic/kelondro/kelondroBufferedRA.java b/source/de/anomic/kelondro/kelondroBufferedRA.javaindex 58a61f5e8..120083ea3 100644--- a/source/de/anomic/kelondro/kelondroBufferedRA.java+++ b/source/de/anomic/kelondro/kelondroBufferedRA.java@@ -42,6 +42,7 @@package de.anomic.kelondro;import java.io.IOException;+import de.anomic.server.serverByteBuffer;public class kelondroBufferedRA extends kelondroAbstractRA implements kelondroRA {diff --git a/source/de/anomic/net/natLib.java b/source/de/anomic/net/natLib.javaindex 05958ae8c..a85526f0d 100644--- a/source/de/anomic/net/natLib.java+++ b/source/de/anomic/net/natLib.java@@ -48,12 +48,11 @@ import java.net.InetAddress;import java.net.UnknownHostException;import java.util.ArrayList;-import de.anomic.http.httpc;+import de.anomic.http.HttpClient;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverDomains;import de.anomic.tools.disorderHeap;import de.anomic.tools.nxTools;-import de.anomic.yacy.yacyURL;public class natLib {@@ -65,7 +64,7 @@ public class natLib {rm status.htm*/try {- ArrayList<String> x = nxTools.strings(httpc.wget(new yacyURL("http://192.168.0.1:80/status.htm", null), "192.168.0.1", 5000, "admin", password, null, null, null));+ ArrayList<String> x = nxTools.strings(HttpClient.wget("http://admin:"+password+"@192.168.0.1:80/status.htm"));x = nxTools.grep(x, 1, "IP Address");if ((x == null) || (x.size() == 0)) return null;String line = nxTools.tail1(x);@@ -77,7 +76,7 @@ public class natLib {private static String getWhatIsMyIP() {try {- ArrayList<String> x = nxTools.strings(httpc.wget(new yacyURL("http://www.whatismyip.com/", null), "www.whatsmyip.com", 5000, null, null, null, null, null));+ ArrayList<String> x = nxTools.strings(HttpClient.wget("http://www.whatismyip.com/"));x = nxTools.grep(x, 0, "Your IP is");String line = nxTools.tail1(x);return nxTools.awk(line, " ", 4);@@ -88,7 +87,7 @@ public class natLib {private static String getStanford() {try {- ArrayList<String> x = nxTools.strings(httpc.wget(new yacyURL("http://www.slac.stanford.edu/cgi-bin/nph-traceroute.pl", null), "www.slac.stanford.edu", 5000, null, null, null, null, null));+ ArrayList<String> x = nxTools.strings(HttpClient.wget("http://www.slac.stanford.edu/cgi-bin/nph-traceroute.pl"));x = nxTools.grep(x, 0, "firewall protecting your browser");String line = nxTools.tail1(x);return nxTools.awk(line, " ", 7);@@ -99,7 +98,7 @@ public class natLib {private static String getIPID() {try {- ArrayList<String> x = nxTools.strings(httpc.wget(new yacyURL("http://ipid.shat.net/", null), "ipid.shat.net", 5000, null, null, null, null, null), "UTF-8");+ ArrayList<String> x = nxTools.strings(HttpClient.wget("http://ipid.shat.net/"), "UTF-8");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/crawler/plasmaHTTPLoader.java b/source/de/anomic/plasma/crawler/plasmaHTTPLoader.javaindex 8a59a7e1c..139b160d5 100644--- a/source/de/anomic/plasma/crawler/plasmaHTTPLoader.java+++ b/source/de/anomic/plasma/crawler/plasmaHTTPLoader.java@@ -54,12 +54,13 @@ import java.net.SocketException;import java.net.UnknownHostException;import java.util.Date;+import de.anomic.http.HttpClient;+import de.anomic.http.HttpFactory;+import de.anomic.http.HttpResponse;+import de.anomic.http.JakartaCommonsHttpResponse;import de.anomic.http.httpHeader;-import de.anomic.http.httpRemoteProxyConfig;-import de.anomic.http.httpc;import de.anomic.http.httpdBoundedSizeOutputStream;import de.anomic.http.httpdLimitExceededException;-import de.anomic.http.httpdProxyHandler;import de.anomic.index.indexReferenceBlacklist;import de.anomic.plasma.plasmaCrawlEURL;import de.anomic.plasma.plasmaCrawlEntry;@@ -75,6 +76,7 @@ import de.anomic.yacy.yacyURL;public final class plasmaHTTPLoader {public static final int DEFAULT_CRAWLING_RETRY_COUNT = 5;+ private static final String crawlerUserAgent = "yacybot (" + HttpClient.getSystemOST() +") http://yacy.net/bot.html";/*** The socket timeout that should be used@@ -86,11 +88,6 @@ public final class plasmaHTTPLoader {*/private long maxFileSize = -1;- /**- * The remote http proxy that should be used- */- private httpRemoteProxyConfig remoteProxyConfig;-private String acceptEncoding;private String acceptLanguage;private String acceptCharset;@@ -111,19 +108,24 @@ public final class plasmaHTTPLoader {this.acceptEncoding = sb.getConfig("crawler.http.acceptEncoding", "gzip,deflate");this.acceptLanguage = sb.getConfig("crawler.http.acceptLanguage","en-us,en;q=0.5");this.acceptCharset = sb.getConfig("crawler.http.acceptCharset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");-- // getting the http proxy config- this.remoteProxyConfig = sb.remoteProxyConfig;- }+ }- protected plasmaHTCache.Entry createCacheEntry(plasmaCrawlEntry entry, Date requestDate, httpHeader requestHeader, httpc.response response) {- IResourceInfo resourceInfo = new ResourceInfo(entry.url(), requestHeader, response.responseHeader);+ /**+ * @param entry+ * @param requestDate+ * @param requestHeader+ * @param responseHeader+ * @param responseStatus Status-Code SPACE Reason-Phrase+ * @return+ */+ protected plasmaHTCache.Entry createCacheEntry(plasmaCrawlEntry entry, Date requestDate, httpHeader requestHeader, httpHeader responseHeader, final String responseStatus) {+ IResourceInfo resourceInfo = new ResourceInfo(entry.url(), requestHeader, responseHeader);return plasmaHTCache.newEntry(requestDate,entry.depth(),entry.url(),entry.name(),- response.status,+ responseStatus,resourceInfo,entry.initiator(),sb.profilesActiveCrawls.getEntry(entry.profileHandle())@@ -158,12 +160,11 @@ public final class plasmaHTTPLoader {}// take a file from the net- httpc remote = null;plasmaHTCache.Entry htCache = null;try {// create a request headerhttpHeader requestHeader = new httpHeader();- requestHeader.put(httpHeader.USER_AGENT, httpdProxyHandler.crawlerUserAgent);+ requestHeader.put(httpHeader.USER_AGENT, crawlerUserAgent);yacyURL refererURL = null;if (entry.referrerhash() != null) refererURL = sb.getURL(entry.referrerhash());if (refererURL != null)@@ -175,24 +176,22 @@ public final class plasmaHTTPLoader {if (this.acceptEncoding != null && this.acceptEncoding.length() > 0)requestHeader.put(httpHeader.ACCEPT_ENCODING, this.acceptEncoding);- // open the connection- remote = new httpc(host, host, port, this.socketTimeout, ssl, this.remoteProxyConfig, "CRAWLER", null);-- // specifying if content encoding is allowed- remote.setAllowContentEncoding((this.acceptEncoding != null && this.acceptEncoding.length() > 0));-- // send request- httpc.response res = remote.GET(path, requestHeader);+ // HTTP-Client+ HttpClient client = HttpFactory.newClient(requestHeader, socketTimeout);++ HttpResponse res = null;+ try {+ // send request+ res = client.GET(entry.url().toString());- if (res.status.startsWith("200") || res.status.startsWith("203")) {+ if (res.getStatusCode() == 200 || res.getStatusCode() == 203) {// the transfer is ok// create a new cache entry- htCache = createCacheEntry(entry, requestDate, requestHeader, res);+ htCache = createCacheEntry(entry, requestDate, requestHeader, res.getResponseHeader(), res.getStatusLine());// aborting download if content is to long ...if (htCache.cacheFile().getAbsolutePath().length() > serverSystem.maxPathLength) {- remote.close();this.log.logInfo("REJECTED URL " + entry.url().toString() + " because path too long '" + plasmaHTCache.cachePath.getAbsolutePath() + "'");sb.crawlQueues.errorURL.newEntry(entry, null, new Date(), 1, plasmaCrawlEURL.DENIED_CACHEFILE_PATH_TOO_LONG);return (htCache = null);@@ -201,7 +200,6 @@ public final class plasmaHTTPLoader {// reserve cache entryif (!htCache.cacheFile().getCanonicalPath().startsWith(plasmaHTCache.cachePath.getCanonicalPath())) {// if the response has not the right file type then reject file- remote.close();this.log.logInfo("REJECTED URL " + entry.url().toString() + " because of an invalid file path ('" +htCache.cacheFile().getCanonicalPath() + "' does not start with '" +plasmaHTCache.cachePath.getAbsolutePath() + "').");@@ -212,7 +210,7 @@ public final class plasmaHTTPLoader {// request has been placed and result has been returned. work off responseFile cacheFile = plasmaHTCache.getCachePath(entry.url());try {- if (plasmaParser.supportedContent(parserMode, entry.url(), res.responseHeader.mime())) {+ if (plasmaParser.supportedContent(parserMode, entry.url(), res.getResponseHeader().mime())) {// delete old contentif (cacheFile.isFile()) {plasmaHTCache.deleteURLfromCache(entry.url());@@ -227,14 +225,13 @@ public final class plasmaHTTPLoader {fos = new FileOutputStream(cacheFile);// getting content length- long contentLength = (res.isGzipped()) ? res.getGzippedLength() : res.responseHeader.contentLength();+ long contentLength = res.getResponseHeader().contentLength();// check the maximum allowed file sizeif (this.maxFileSize > -1) {if (contentLength == -1) {fos = new httpdBoundedSizeOutputStream(fos,this.maxFileSize);} else if (contentLength > this.maxFileSize) {- remote.close();this.log.logInfo("REJECTED URL " + entry.url() + " because file size '" + contentLength + "' exceeds max filesize limit of " + this.maxFileSize + " bytes.");sb.crawlQueues.errorURL.newEntry(entry, null, new Date(), 1, plasmaCrawlEURL.DENIED_FILESIZE_LIMIT_EXCEEDED);return null;@@ -242,21 +239,19 @@ public final class plasmaHTTPLoader {}// we write the new cache entry to file system directly- byte[] cacheArray = null;- cacheArray = res.writeContent(fos, false);- remote.close();- htCache.setCacheArray(cacheArray);+ ((JakartaCommonsHttpResponse)res).setAccountingName("CRAWLER");+ byte[] responseBody = res.getData();+ fos.write(responseBody);+ htCache.setCacheArray(responseBody);plasmaHTCache.writeFileAnnouncement(cacheFile);} finally {if (fos!=null)try{fos.close();}catch(Exception e){/* ignore this */}- remote.close();}return htCache;} else {// if the response has not the right file type then reject file- remote.close();- this.log.logInfo("REJECTED WRONG MIME/EXT TYPE " + res.responseHeader.mime() + " for URL " + entry.url().toString());+ this.log.logInfo("REJECTED WRONG MIME/EXT TYPE " + res.getResponseHeader().mime() + " for URL " + entry.url().toString());sb.crawlQueues.errorURL.newEntry(entry, null, new Date(), 1, plasmaCrawlEURL.DENIED_WRONG_MIMETYPE_OR_EXT);return null;}@@ -271,10 +266,10 @@ public final class plasmaHTTPLoader {sb.crawlQueues.errorURL.newEntry(entry, null, new Date(), 1, plasmaCrawlEURL.DENIED_CONNECTION_ERROR);htCache = null;}- } else if (res.status.startsWith("30")) {- if (res.responseHeader.containsKey(httpHeader.LOCATION)) {+ } else if (res.getStatusLine().startsWith("30")) {+ if (res.getResponseHeader().containsKey(httpHeader.LOCATION)) {// getting redirection URL- String redirectionUrlString = (String) res.responseHeader.get(httpHeader.LOCATION);+ String redirectionUrlString = (String) res.getResponseHeader().get(httpHeader.LOCATION);redirectionUrlString = redirectionUrlString.trim();if (redirectionUrlString.length() == 0) {@@ -287,7 +282,7 @@ public final class plasmaHTTPLoader {yacyURL redirectionUrl = yacyURL.newURL(entry.url(), redirectionUrlString);// restart crawling with new url- this.log.logInfo("CRAWLER Redirection detected ('" + res.status + "') for URL " + entry.url().toString());+ this.log.logInfo("CRAWLER Redirection detected ('" + res.getStatusLine() + "') for URL " + entry.url().toString());this.log.logInfo("CRAWLER ..Redirecting request to: " + redirectionUrl);// if we are already doing a shutdown we don't need to retry crawling@@ -315,13 +310,18 @@ public final class plasmaHTTPLoader {}} else {// if the response has not the right response type then reject file- this.log.logInfo("REJECTED WRONG STATUS TYPE '" + res.status + "' for URL " + entry.url().toString());+ this.log.logInfo("REJECTED WRONG STATUS TYPE '" + res.getStatusLine() + "' for URL " + entry.url().toString());// not processed any further- sb.crawlQueues.errorURL.newEntry(entry, null, new Date(), 1, plasmaCrawlEURL.DENIED_WRONG_HTTP_STATUSCODE + res.statusCode + ")");+ sb.crawlQueues.errorURL.newEntry(entry, null, new Date(), 1, plasmaCrawlEURL.DENIED_WRONG_HTTP_STATUSCODE + res.getStatusCode() + ")");}- if (remote != null) remote.close();+ } finally {+ if(res != null) {+ // release connection+ res.closeStream();+ }+ }return htCache;} catch (Exception e) {String errorMsg = e.getMessage();diff --git a/source/de/anomic/plasma/parser/odt/odtParser.java b/source/de/anomic/plasma/parser/odt/odtParser.javaindex 82a693f4a..c117e7895 100644--- a/source/de/anomic/plasma/parser/odt/odtParser.java+++ b/source/de/anomic/plasma/parser/odt/odtParser.java@@ -58,7 +58,7 @@ import com.catcode.odf.ODFMetaFileAnalyzer;import com.catcode.odf.OpenDocumentMetadata;import com.catcode.odf.OpenDocumentTextInputStream;-import de.anomic.http.httpc;+import de.anomic.http.HttpClient;import de.anomic.plasma.plasmaParserDocument;import de.anomic.plasma.parser.AbstractParser;import de.anomic.plasma.parser.Parser;@@ -250,7 +250,7 @@ public class odtParser extends AbstractParser implements Parser {testParser.setLogger(new serverLog("PARSER.ODT"));// downloading the document content- byte[] content = httpc.singleGET(contentUrl, contentUrl.getHost(), 10000, null, null, null, null);+ byte[] content = HttpClient.wget(contentUrl.toString());ByteArrayInputStream input = new ByteArrayInputStream(content);// parsing the documentdiff --git a/source/de/anomic/plasma/parser/rpm/rpmParser.java b/source/de/anomic/plasma/parser/rpm/rpmParser.javaindex 2ed2c643b..0be0c0bb9 100644--- a/source/de/anomic/plasma/parser/rpm/rpmParser.java+++ b/source/de/anomic/plasma/parser/rpm/rpmParser.java@@ -52,7 +52,7 @@ import java.util.Hashtable;import com.jguild.jrpm.io.RPMFile;import com.jguild.jrpm.io.datatype.DataTypeIf;-import de.anomic.http.httpc;+import de.anomic.http.HttpClient;import de.anomic.plasma.plasmaParserDocument;import de.anomic.plasma.parser.AbstractParser;import de.anomic.plasma.parser.Parser;@@ -180,7 +180,7 @@ public class rpmParser extends AbstractParser implements Parser {yacyURL contentUrl = new yacyURL(args[0], null);rpmParser testParser = new rpmParser();- byte[] content = httpc.singleGET(contentUrl, contentUrl.getHost(), 10000, null, null, null, null);+ byte[] content = HttpClient.wget(contentUrl.toString());ByteArrayInputStream input = new ByteArrayInputStream(content);testParser.parse(contentUrl, "application/x-rpm", null, input);} catch (Exception e) {diff --git a/source/de/anomic/plasma/parser/vcf/vcfParser.java b/source/de/anomic/plasma/parser/vcf/vcfParser.javaindex 44752e311..9981fec77 100644--- a/source/de/anomic/plasma/parser/vcf/vcfParser.java+++ b/source/de/anomic/plasma/parser/vcf/vcfParser.java@@ -53,7 +53,7 @@ import java.util.Hashtable;import java.util.Iterator;import java.util.LinkedList;-import de.anomic.http.httpc;+import de.anomic.http.HttpClient;import de.anomic.kelondro.kelondroBase64Order;import de.anomic.plasma.plasmaParserDocument;import de.anomic.plasma.parser.AbstractParser;@@ -291,7 +291,7 @@ public class vcfParser extends AbstractParser implements Parser {yacyURL contentUrl = new yacyURL(args[0], null);vcfParser testParser = new vcfParser();- byte[] content = httpc.singleGET(contentUrl, contentUrl.getHost(), 10000, null, null, null, null);+ byte[] content = HttpClient.wget(contentUrl.toString());ByteArrayInputStream input = new ByteArrayInputStream(content);testParser.parse(contentUrl, "text/x-vcard", "UTF-8",input);} catch (Exception e) {diff --git a/source/de/anomic/plasma/plasmaParser.java b/source/de/anomic/plasma/plasmaParser.javaindex 0344ae68b..ba7e47224 100644--- a/source/de/anomic/plasma/plasmaParser.java+++ b/source/de/anomic/plasma/plasmaParser.java@@ -54,7 +54,9 @@ import de.anomic.htmlFilter.htmlFilterContentScraper;import de.anomic.htmlFilter.htmlFilterImageEntry;import de.anomic.htmlFilter.htmlFilterInputStream;import de.anomic.htmlFilter.htmlFilterWriter;-import de.anomic.http.httpc;+import de.anomic.http.HttpClient;+import de.anomic.http.HttpFactory;+import de.anomic.http.HttpResponse;import de.anomic.plasma.parser.Parser;import de.anomic.plasma.parser.ParserException;import de.anomic.plasma.parser.ParserInfo;@@ -833,7 +835,6 @@ public final class plasmaParser {public static void main(String[] args) {//javac -sourcepath source source/de/anomic/plasma/plasmaParser.java//java -cp source de.anomic.plasma.plasmaParser bug.html bug.out- httpc remote = null;try {Object content = null;yacyURL contentURL = null;@@ -846,6 +847,9 @@ public final class plasmaParser {}String mode = args[0];+ HttpResponse res = null;+ plasmaParserDocument document = null;+ try { // close InputStream when doneif (mode.equalsIgnoreCase("-f")) {content = new File(args[1]);contentURL = new yacyURL((File)content);@@ -853,25 +857,18 @@ public final class plasmaParser {contentURL = new yacyURL(args[1], null);// downloading the document content- remote = new httpc(- contentURL.getHost(),- contentURL.getHost(),- contentURL.getPort(),- 5000,- contentURL.getProtocol().equalsIgnoreCase("https"),- null,- null, null);+ HttpClient client = HttpFactory.newClient();+ client.setTimeout(5000);- httpc.response res = remote.GET(contentURL.getFile(), null);- if (res.statusCode != 200) {- System.err.println("Unable to download " + contentURL + ". " + res.status);- return;+ res = client.GET(args[1]);+ if (res.getStatusCode() != 200) {+ System.err.println("Unable to download " + contentURL + ". " + res.getStatusLine());+ return;}- content = res.getContentInputStream();- contentMimeType = res.responseHeader.mime();- charSet = res.responseHeader.getCharacterEncoding();- contentLength = res.responseHeader.contentLength();- remote.close();+ content = res.getDataAsStream();+ contentMimeType = res.getResponseHeader().mime();+ charSet = res.getResponseHeader().getCharacterEncoding();+ contentLength = res.getResponseHeader().contentLength();}if ((args.length >= 4)&&(args[2].equalsIgnoreCase("-m"))) {@@ -889,7 +886,6 @@ public final class plasmaParser {plasmaParser.initHTMLParsableMimeTypes("application/xhtml+xml,text/html,text/plain,text/sgml");// parsing the content- plasmaParserDocument document = null;if (content instanceof byte[]) {document = theParser.parseSource(contentURL, contentMimeType, charSet, (byte[])content);} else if (content instanceof File) {@@ -897,6 +893,11 @@ public final class plasmaParser {} else if (content instanceof InputStream) {document = theParser.parseSource(contentURL, contentMimeType, charSet, contentLength, (InputStream)content);}+ } finally {+ if(res != null) {+ res.closeStream();+ }+ }// printing out all parsed sentencesif (document != null) {diff --git a/source/de/anomic/plasma/plasmaSnippetCache.java b/source/de/anomic/plasma/plasmaSnippetCache.javaindex 2067dc924..9a7e791ee 100644--- a/source/de/anomic/plasma/plasmaSnippetCache.java+++ b/source/de/anomic/plasma/plasmaSnippetCache.java@@ -57,8 +57,8 @@ import java.util.TreeMap;import java.util.TreeSet;import de.anomic.htmlFilter.htmlFilterImageEntry;+import de.anomic.http.HttpClient;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.index.indexURLReference;import de.anomic.index.indexWord;import de.anomic.kelondro.kelondroMScoreCluster;@@ -396,6 +396,8 @@ public class plasmaSnippetCache {** @param url the URL of the resource* @param fetchOnline specifies if the resource should be loaded from web if it'as not available in the cache+ * @param timeout+ * @param forText* @return the parsed document as {@link plasmaParserDocument}*/public static plasmaParserDocument retrieveDocument(yacyURL url, boolean fetchOnline, int timeout, boolean forText) {@@ -805,7 +807,7 @@ public class plasmaSnippetCache {// getting URL mimeTypetry {- httpHeader header = httpc.whead(url, url.getHost(), 10000, null, null, plasmaSwitchboard.getSwitchboard().remoteProxyConfig);+ httpHeader header = HttpClient.whead(url.toString());docInfo = plasmaHTCache.getResourceInfoFactory().buildResourceInfoObj(url, header);} catch (Exception e) {// ingore this. http header download failed@@ -851,6 +853,7 @@ public class plasmaSnippetCache {* @param url* @param fetchOnline* @param socketTimeout+ * @param forText* @return an Object array containing* <table>* <tr><td>[0]</td><td>the content as {@link InputStream}</td></tr>diff --git a/source/de/anomic/plasma/plasmaStore.java b/source/de/anomic/plasma/plasmaStore.javaindex 6dbb43dfc..5238b2349 100644--- a/source/de/anomic/plasma/plasmaStore.java+++ b/source/de/anomic/plasma/plasmaStore.java@@ -38,7 +38,6 @@ import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;-//import java.io.RandomAccessFile;public class plasmaStore {diff --git a/source/de/anomic/plasma/plasmaSwitchboard.java b/source/de/anomic/plasma/plasmaSwitchboard.javaindex 44bd63575..58b2ead28 100644--- a/source/de/anomic/plasma/plasmaSwitchboard.java+++ b/source/de/anomic/plasma/plasmaSwitchboard.java@@ -117,10 +117,12 @@ import de.anomic.data.messageBoard;import de.anomic.data.userDB;import de.anomic.data.wikiBoard;import de.anomic.data.wiki.wikiParser;+import de.anomic.http.HttpClient;+import de.anomic.http.JakartaCommonsHttpClient;import de.anomic.http.httpHeader;import de.anomic.http.httpRemoteProxyConfig;-import de.anomic.http.httpc;import de.anomic.http.httpd;+import de.anomic.http.httpdProxyHandler;import de.anomic.http.httpdRobotsTxtConfig;import de.anomic.index.indexDefaultReferenceBlacklist;import de.anomic.index.indexReferenceBlacklist;@@ -151,6 +153,7 @@ import de.anomic.server.serverSwitch;import de.anomic.server.serverThread;import de.anomic.server.logging.serverLog;import de.anomic.tools.crypt;+import de.anomic.tools.nxTools;import de.anomic.yacy.yacyClient;import de.anomic.yacy.yacyCore;import de.anomic.yacy.yacyNewsPool;@@ -245,17 +248,6 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<plasmaSwitchbopublic serverProcessor<indexingQueueEntry> indexingAnalysisProcessor;public serverProcessor<indexingQueueEntry> indexingStorageProcessor;- /*- * Remote Proxy configuration- */- // public boolean remoteProxyUse;- // public boolean remoteProxyUse4Yacy;- // public String remoteProxyHost;- // public int remoteProxyPort;- // public String remoteProxyNoProxy = "";- // public String[] remoteProxyNoProxyPatterns = null;- public httpRemoteProxyConfig remoteProxyConfig = null;-public httpdRobotsTxtConfig robotstxtConfig = null;@@ -895,8 +887,8 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<plasmaSwitchboif (applyPro) this.log.logInfo("This is the pro-version of YaCy");// remote proxy configuration- this.remoteProxyConfig = httpRemoteProxyConfig.init(this);- this.log.logConfig("Remote proxy configuration:\n" + this.remoteProxyConfig.toString());+ httpdProxyHandler.setRemoteProxyConfig(httpRemoteProxyConfig.init(this)); // TODO refactoring+ this.log.logConfig("Remote proxy configuration:\n" + httpdProxyHandler.getRemoteProxyConfig().toString());// load network configuration into settingsString networkUnitDefinition = getConfig("network.unit.definition", "defaults/yacy.network.freeworld.unit");@@ -915,7 +907,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<plasmaSwitchboMap<String, String> initProps;if (networkUnitDefinition.startsWith("http://")) {try {- this.setConfig(httpc.loadHashMap(new yacyURL(networkUnitDefinition, null), remoteProxyConfig));+ this.setConfig(plasmaSwitchboard.loadHashMap(new yacyURL(networkUnitDefinition, null)));} catch (MalformedURLException e) {}} else {@@ -927,7 +919,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<plasmaSwitchbo}if (networkGroupDefinition.startsWith("http://")) {try {- this.setConfig(httpc.loadHashMap(new yacyURL(networkGroupDefinition, null), remoteProxyConfig));+ this.setConfig(plasmaSwitchboard.loadHashMap(new yacyURL(networkGroupDefinition, null)));} catch (MalformedURLException e) {}} else {@@ -1247,12 +1239,6 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<plasmaSwitchbotestresult = facilityDB.selectLong("statistik", (new serverDate()).toShortString(false).substring(0, 11));*/- /*- * Initializing httpc- */- // initializing yacyDebugMode- httpc.yacyDebugMode = getConfig(YACY_MODE_DEBUG, "false").equals("true");-// init nameCacheNoCachingListString noCachingList = getConfig(HTTPC_NAME_CACHE_CACHING_PATTERNS_NO,"");String[] noCachingEntries = noCachingList.split(",");@@ -1449,7 +1435,8 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<plasmaSwitchboInetAddress hostAddress = serverDomains.dnsResolve(host);// if we don't know the host, we cannot load that resource anyway.// But in case we use a proxy, it is possible that we dont have a DNS service.- if (hostAddress == null) return ((this.remoteProxyConfig != null) && (this.remoteProxyConfig.useProxy()));+ final httpRemoteProxyConfig remoteProxyConfig = httpdProxyHandler.getRemoteProxyConfig();+ if (hostAddress == null) return ((remoteProxyConfig != null) && (remoteProxyConfig.useProxy()));// check if this is a local address and we are allowed to index local pages:boolean local = hostAddress.isSiteLocalAddress() || hostAddress.isLoopbackAddress();//assert local == yacyURL.isLocalDomain(url.hash()); // TODO: remove the dnsResolve above!@@ -1729,7 +1716,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<plasmaSwitchboindexingAnalysisProcessor.shutdown(2000);indexingStorageProcessor.shutdown(1000);this.dbImportManager.close();- httpc.closeAllConnections();+ JakartaCommonsHttpClient.closeAllConnections();wikiDB.close();blogDB.close();blogCommentDB.close();@@ -2088,6 +2075,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<plasmaSwitchbo/*** With this function the crawling process can be paused+ * @param jobType*/public void pauseCrawlJob(String jobType) {Object[] status = (Object[])this.crawlJobsStatus.get(jobType);@@ -2099,6 +2087,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<plasmaSwitchbo/*** Continue the previously paused crawling+ * @param jobType*/public void continueCrawlJob(String jobType) {Object[] status = (Object[])this.crawlJobsStatus.get(jobType);@@ -2112,6 +2101,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<plasmaSwitchbo}/**+ * @param jobType* @return <code>true</code> if crawling was paused or <code>false</code> otherwise*/public boolean crawlJobIsPaused(String jobType) {@@ -2742,6 +2732,28 @@ public final class plasmaSwitchboard extends serverAbstractSwitch<plasmaSwitchbothis.shutdownSync.P();return this.terminate;}++ /**+ * loads the url as Map+ *+ * Strings like abc=123 are parsed as pair: abc => 123+ *+ * @param url+ * @return+ */+ public static Map<String, String> loadHashMap(yacyURL url) {+ try {+ // sending request+ final HashMap<String, String> result = nxTools.table(+ HttpClient.wget(url.toString())+ , "UTF-8");++ if (result == null) return new HashMap<String, String>();+ return result;+ } catch (Exception e) {+ return new HashMap<String, String>();+ }+ }}class MoreMemory extends TimerTask {diff --git a/source/de/anomic/server/serverAbstractSwitch.java b/source/de/anomic/server/serverAbstractSwitch.javaindex ca516a7e1..837f239b7 100644--- a/source/de/anomic/server/serverAbstractSwitch.java+++ b/source/de/anomic/server/serverAbstractSwitch.java@@ -274,6 +274,9 @@ public abstract class serverAbstractSwitch<E> implements serverSwitch<E> {}}+ /* (non-Javadoc)+ * @see de.anomic.server.serverSwitch#getConfig(java.lang.String, java.lang.String)+ */public String getConfig(String key, String dflt) {Iterator<serverSwitchAction> i = switchActions.values().iterator();synchronized (configProps) {diff --git a/source/de/anomic/server/serverCore.java b/source/de/anomic/server/serverCore.javaindex 267144499..746e86427 100644--- a/source/de/anomic/server/serverCore.java+++ b/source/de/anomic/server/serverCore.java@@ -86,27 +86,57 @@ import de.anomic.yacy.yacySeed;public final class serverCore extends serverAbstractBusyThread implements serverBusyThread {// special ASCII codes used for protocol handling- public static final byte HT = 9; // Horizontal Tab- public static final byte LF = 10; // Line Feed- public static final byte CR = 13; // Carriage Return- public static final byte SP = 32; // Space- public static final byte[] CRLF = {CR, LF}; // Line End of HTTP/ICAP headers+ /**+ * Horizontal Tab+ */+ public static final byte HT = 9;+ /**+ * Line Feed+ */+ public static final byte LF = 10;+ /**+ * Carriage Return+ */+ public static final byte CR = 13;+ /**+ * Space+ */+ public static final byte SP = 32;+ /**+ * Line End of HTTP/ICAP headers+ */+ public static final byte[] CRLF = {CR, LF};public static final String CRLF_STRING = new String(CRLF);public static final String LF_STRING = new String(new byte[]{LF});public static final Class<?>[] stringType = {"".getClass()}; // set up some reflectionpublic static final long startupTime = System.currentTimeMillis();public static final ThreadGroup sessionThreadGroup = new ThreadGroup("sessionThreadGroup");- static int sessionCounter = 0; // will be increased with each session and is used to return a hash code+ /**+ * will be increased with each session and is used to return a hash code+ */+ static int sessionCounter = 0;// static variablespublic static final Boolean TERMINATE_CONNECTION = Boolean.FALSE;public static final Boolean RESUME_CONNECTION = Boolean.TRUE;- public static HashMap<String, Integer> bfHost = new HashMap<String, Integer>(); // for brute-force prevention+ /**+ * for brute-force prevention+ */+ public static HashMap<String, Integer> bfHost = new HashMap<String, Integer>();// class variables- private String extendedPort; // the port, which is visible from outside (in most cases bind-port)- private String bindPort; // if set, yacy will bind to this port, but set extendedPort in the seed- public boolean forceRestart = false; // specifies if the server should try to do a restart+ /**+ * the port, which is visible from outside (in most cases bind-port)+ */+ private String extendedPort;+ /**+ * if set, yacy will bind to this port, but set extendedPort in the seed+ */+ private String bindPort;+ /**+ * specifies if the server should try to do a restart+ */+ public boolean forceRestart = false;public static boolean portForwardingEnabled = false;public static boolean useStaticIP = false;diff --git a/source/de/anomic/tools/StreamTools.java b/source/de/anomic/tools/StreamTools.javanew file mode 100644index 000000000..e86970b09--- /dev/null+++ b/source/de/anomic/tools/StreamTools.java@@ -0,0 +1,114 @@+// LowLevelTools.java+// (C) 2008 by Daniel Raap; [email protected]+// first published 2.4.2008 on http://yacy.net+//+// This is a part of YaCy, a peer-to-peer based web search engine+//+// $LastChangedDate: 2008-03-14 01:16:04 +0100 (Fr, 14 Mrz 2008) $+// $LastChangedRevision: 4558 $+// $LastChangedBy: orbiter $+//+// LICENSE+//+// This program is free software; you can redistribute it and/or modify+// it under the terms of the GNU General Public License as published by+// the Free Software Foundation; either version 2 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+package de.anomic.tools;++import java.io.BufferedInputStream;+import java.io.BufferedOutputStream;+import java.io.BufferedReader;+import java.io.BufferedWriter;+import java.io.IOException;+import java.io.InputStream;+import java.io.InputStreamReader;+import java.io.OutputStream;+import java.io.Writer;++/**+ * @author danielr+ *+ */+public class StreamTools {+ /**+ * copies the input stream to all output streams (byte per byte)+ * @param in+ * @param outs+ * @return+ * @throws IOException+ */+ public static int copyToStreams(InputStream in, final OutputStream[] outs) throws IOException {+ if(!(in instanceof BufferedInputStream)) {+ // add buffer+ in = new BufferedInputStream(in);+ }++ // check if buffer is used+ int i = 0;+ for(final OutputStream output: outs) {+ if (!(output instanceof BufferedOutputStream)) {+ // add buffer+ outs[i] = new BufferedOutputStream(output);+ }+ i++;+ }++ int count = 0;+ // copy bytes+ int b;+ while((b = in.read()) != -1) {+ count++;+ for(final OutputStream out: outs) {+ out.write(b);+ }+ }+ return count;+ }++ /**+ * copies the input stream to all writers (byte per byte)+ * @param data+ * @param writers+ * @param charSet+ * @return+ * @throws IOException+ */+ public static int copyToWriters(final InputStream data, final Writer[] writers, final String charSet) throws IOException {+ // the docs say: "For top efficiency, consider wrapping an InputStreamReader within a BufferedReader."+ final BufferedReader sourceReader = new BufferedReader(new InputStreamReader(data, charSet));++ // check if buffer is used. From the documentation:+ // "For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent+ // converter invocations"+ int i = 0;+ for(final Writer writer: writers) {+ if (!(writer instanceof BufferedWriter)) {+ // add buffer+ writers[i] = new BufferedWriter(writer);+ }+ i++;+ }++ int count = 0;+ // copy bytes+ int b;+ while((b = sourceReader.read()) != -1) {+ count++;+ for(final Writer writer: writers) {+ writer.write(b);+ }+ }+ return count;+ }++}diff --git a/source/de/anomic/tools/loaderThreads.java b/source/de/anomic/tools/loaderThreads.javaindex 4f5008d08..b547d8cc1 100644--- a/source/de/anomic/tools/loaderThreads.java+++ b/source/de/anomic/tools/loaderThreads.java@@ -44,8 +44,9 @@ import java.net.MalformedURLException;import java.util.ArrayList;import java.util.Hashtable;+import de.anomic.http.HttpClient;import de.anomic.http.httpRemoteProxyConfig;-import de.anomic.http.httpc;+import de.anomic.http.httpdProxyHandler;import de.anomic.yacy.yacyURL;public class loaderThreads {@@ -61,23 +62,17 @@ public class loaderThreads {int completed, failed;public loaderThreads() {- this(null);- }-- public loaderThreads(httpRemoteProxyConfig theremoteProxyConfig) {- this(10000, null, null, theremoteProxyConfig);+ this(10000, null, null);}public loaderThreads(int timeout,String user,- String password,- httpRemoteProxyConfig theremoteProxyConfig+ String password) {this.timeout = timeout;this.user = user;this.password = password;- this.remoteProxyConfig = theremoteProxyConfig;this.threads = new Hashtable<String, Thread>();this.completed = 0;this.failed = 0;@@ -146,7 +141,7 @@ public class loaderThreads {public void run() {try {- page = httpc.wget(url, url.getHost(), timeout, user, password, remoteProxyConfig, null, null);+ page = HttpClient.wget(url.toString());loaded = true;process.feed(page);if (process.status() == loaderCore.STATUS_FAILED) {@@ -229,8 +224,8 @@ public class loaderThreads {}public static void main(String[] args) {- httpRemoteProxyConfig proxyConfig = httpRemoteProxyConfig.init("192.168.1.122", 3128);- loaderThreads loader = new loaderThreads(proxyConfig);+ httpdProxyHandler.setRemoteProxyConfig(httpRemoteProxyConfig.init("192.168.1.122", 3128));+ loaderThreads loader = new loaderThreads();try {loader.newPropLoaderThread("load1", new yacyURL("http://www.anomic.de/superseed.txt", null));} catch (MalformedURLException e) {diff --git a/source/de/anomic/tools/nxTools.java b/source/de/anomic/tools/nxTools.javaindex b93047538..0bf477630 100644--- a/source/de/anomic/tools/nxTools.java+++ b/source/de/anomic/tools/nxTools.java@@ -74,6 +74,18 @@ public class nxTools {return table(strings(a, encoding));}+ /**+ * parse config files+ *+ * splits the lines in list into pairs sperarated by =, lines beginning with # are ignored+ * ie:+ * abc=123+ * # comment+ * fg=dcf+ * => Map{abc => 123, fg => dcf}+ * @param list+ * @return+ */public static HashMap<String, String> table(ArrayList<String> list) {if (list == null) return new HashMap<String, String>();Iterator<String> i = list.iterator();@@ -214,7 +226,8 @@ public class nxTools {* Example returns:<br>* <dl><dt>normal domain:</dt><dd>http://domain.net/leftpath..rightpath</dd>* <dt>long domain:</dt><dd>http://very_very_long_domain.net/le..</dd></dl>- * @param String like a URL+ * @param url String like a URL+ * @param len* @return the shorten or the old String*/public static String shortenURLString(String url, int len) {diff --git a/source/de/anomic/urlRedirector/urlRedirectord.java b/source/de/anomic/urlRedirector/urlRedirectord.javaindex 563b6b73e..2765f654b 100644--- a/source/de/anomic/urlRedirector/urlRedirectord.java+++ b/source/de/anomic/urlRedirector/urlRedirectord.java@@ -8,8 +8,8 @@ import java.net.MalformedURLException;import java.util.Date;import de.anomic.data.userDB;+import de.anomic.http.HttpClient;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.plasma.plasmaCrawlProfile;import de.anomic.plasma.plasmaParser;import de.anomic.plasma.plasmaSwitchboard;@@ -182,7 +182,7 @@ public class urlRedirectord implements serverHandler {yacyURL reqURL = new yacyURL(this.nextURL, null);// getting URL mimeType- httpHeader header = httpc.whead(reqURL, reqURL.getHost(), 10000, null, null, switchboard.remoteProxyConfig);+ httpHeader header = HttpClient.whead(reqURL.toString());if (plasmaParser.supportedContent(plasmaParser.PARSER_MODE_URLREDIRECTOR,diff --git a/source/de/anomic/yacy/yacyClient.java b/source/de/anomic/yacy/yacyClient.javaindex aeff6332b..fc1599a24 100644--- a/source/de/anomic/yacy/yacyClient.java+++ b/source/de/anomic/yacy/yacyClient.java@@ -52,8 +52,12 @@ import java.util.Iterator;import java.util.Map;import java.util.TreeMap;+import de.anomic.http.HttpClient;+import de.anomic.http.HttpFactory;+import de.anomic.http.HttpResponse;+import de.anomic.http.httpHeader;import de.anomic.http.httpRemoteProxyConfig;-import de.anomic.http.httpc;+import de.anomic.http.httpdProxyHandler;import de.anomic.index.indexContainer;import de.anomic.index.indexRWIEntry;import de.anomic.index.indexRWIRowEntry;@@ -79,6 +83,11 @@ import de.anomic.xml.rssReader;public final class yacyClient {+ /**+ *+ */+ private static final String GZIP_POST_BODY = "GZIP_POST_BODY";+public static int publishMySeed(String address, String otherHash) {// this is called to enrich the seed information by// - own address (if peer is behind a nat/router)@@ -106,24 +115,15 @@ public final class yacyClient {post.put("seed", yacyCore.seedDB.mySeed().genSeedStr(post.get("key", "")));yacyCore.log.logFine("yacyClient.publishMySeed thread '" + Thread.currentThread().getName() + "' contacting peer at " + address);// send request- result = nxTools.table(- httpc.wput(new yacyURL("http://" + address + "/yacy/hello.html", null),- yacySeed.b64Hash2hexHash(otherHash) + ".yacyh",- 12000,- null,- null,- proxyConfig(),- post,- null- ), "UTF-8"- );+ byte[] content = wput("http://" + address + "/yacy/hello.html", yacySeed.b64Hash2hexHash(otherHash) + ".yacyh", post);+ result = nxTools.table(content, "UTF-8");break;} catch (Exception e) {if (Thread.currentThread().isInterrupted()) {yacyCore.log.logWarning("yacyClient.publishMySeed thread '" + Thread.currentThread().getName() + "' interrupted.");return -1;} else {- yacyCore.log.logWarning("yacyClient.publishMySeed thread '" + Thread.currentThread().getName() + "' exception: " + e.getMessage() + "; retry = " + retry); // here VERY OFTEN a 'Connection reset' appears. What is the cause?+ yacyCore.log.logWarning("yacyClient.publishMySeed thread '" + Thread.currentThread().getName() + "' exception: " + e.getMessage() + "; retry = " + retry);// try again (go into loop)}result = null;@@ -239,6 +239,53 @@ public final class yacyClient {return count;}+ /**+ * send data to the server named by vhost+ * @param address address of the server+ * @param vhost name of the server at address which should respond+ * @param post data to send (name-value-pairs)+ * @return response body+ * @throws IOException+ */+ private static byte[] wput(final String url, String vhost, final Map<String, ?> post) throws IOException {+ HttpClient client = HttpFactory.newClient(null, 12000);+ client.setProxy(proxyConfig());++ // address vhost+ httpHeader header = new httpHeader();+ header.add(httpHeader.HOST, vhost);+ client.setHeader(header);++ HttpResponse res = null;+ byte[] content = null;+ try {+ // send request/data+ res = client.POST(url, post);+ content = res.getData();+ } finally {+ if(res != null) {+ // release connection+ res.closeStream();+ }+ }+ return content;+ }++ /**+ * @see wput+ * @param target+ * @param filename+ * @param post+ * @return+ * @throws IOException+ */+ private static byte[] postToFile(final yacySeed target, final String filename, final serverObjects post) throws IOException {+ return wput("http://" + target.getClusterAddress() + "/yacy/" + filename, target.getHexHash() + ".yacyh", post);+ }+ private static byte[] postToFile(final String targetHash, final String filename, final serverObjects post) throws IOException {+ return wput("http://" + targetAddress(targetHash) + "/yacy/" + filename, yacySeed.b64Hash2hexHash(targetHash)+ ".yacyh", post);+ }+public static yacySeed querySeed(yacySeed target, String seedHash) {// prepare requestfinal serverObjects post = yacyNetwork.basicRequestPost(plasmaSwitchboard.getSwitchboard(), target.hash);@@ -247,17 +294,8 @@ public final class yacyClient {// send requesttry {- final HashMap<String, String> result = nxTools.table(- httpc.wput(new yacyURL("http://" + target.getClusterAddress() + "/yacy/query.html", null),- target.getHexHash() + ".yacyh",- 8000,- null,- null,- proxyConfig(),- post,- null- ), "UTF-8"- );+ byte[] content = postToFile(target, "query.html", post);+ final HashMap<String, String> result = nxTools.table(content, "UTF-8");if (result == null || result.size() == 0) { return null; }//final Date remoteTime = yacyCore.parseUniversalDate((String) result.get(yacySeed.MYTIME)); // read remote time@@ -277,17 +315,8 @@ public final class yacyClient {// send requesttry {- final HashMap<String, String> result = nxTools.table(- httpc.wput(new yacyURL("http://" + target.getClusterAddress() + "/yacy/query.html", null),- target.getHexHash() + ".yacyh",- 8000,- null,- null,- proxyConfig(),- post,- null- ), "UTF-8"- );+ byte[] content = postToFile(target, "query.html", post);+ final HashMap<String, String> result = nxTools.table(content, "UTF-8");if (result == null || result.size() == 0) { return -1; }return Integer.parseInt((String) result.get("response"));@@ -309,17 +338,8 @@ public final class yacyClient {// send requesttry {- final HashMap<String, String> result = nxTools.table(- httpc.wput(new yacyURL("http://" + target.getClusterAddress() + "/yacy/query.html", null),- target.getHexHash() + ".yacyh",- 6000,- null,- null,- proxyConfig(),- post,- null- ), "UTF-8"- );+ byte[] content = postToFile(target, "query.html", post);+ final HashMap<String, String> result = nxTools.table(content, "UTF-8");if ((result == null) || (result.size() == 0)) return -1;final String resp = (String) result.get("response");@@ -348,16 +368,7 @@ public final class yacyClient {// send requesttry {- final byte[] result =- httpc.wput(new yacyURL("http://" + target.getClusterAddress() + "/yacy/urls.xml", null),- target.getHexHash() + ".yacyh",- 60000, /* a long time-out is needed */- null,- null,- proxyConfig(),- post,- null- );+ final byte[] result = wput("http://" + target.getClusterAddress() + "/yacy/urls.xml", target.getHexHash() + ".yacyh", post);rssReader reader = rssReader.parse(result);if (reader == null) {@@ -433,17 +444,7 @@ public final class yacyClient {// send requestHashMap<String, String> result = null;try {- result = nxTools.table(- httpc.wput(new yacyURL("http://" + target.getClusterAddress() + "/yacy/search.html", null),- target.getHexHash() + ".yacyh",- 60000,- null,- null,- proxyConfig(),- post,- null- ), "UTF-8"- );+ result = nxTools.table(postToFile(target, "search.html", post), "UTF-8");} catch (IOException e) {yacyCore.log.logInfo("SEARCH failed, Peer: " + target.hash + ":" + target.getName() + " (" + e.getMessage() + "), score=" + target.selectscore + ", DHTdist=" + yacyDHTAction.dhtDistance(target.hash, wordhashes.substring(0, 12)));//yacyCore.peerActions.peerDeparture(target, "search request to peer created io exception: " + e.getMessage());@@ -638,17 +639,8 @@ public final class yacyClient {// send requesttry {- final HashMap<String, String> result = nxTools.table(- httpc.wput(new yacyURL("http://" + targetAddress(targetHash) + "/yacy/message.html", null),- yacySeed.b64Hash2hexHash(targetHash)+ ".yacyh",- 8000,- null,- null,- proxyConfig(),- post,- null- ), "UTF-8"- );+ final byte[] content = postToFile(targetHash, "message.html", post);+ final HashMap<String, String> result = nxTools.table(content, "UTF-8");return result;} catch (Exception e) {// most probably a network time-out exception@@ -673,17 +665,8 @@ public final class yacyClient {// send requesttry {- final HashMap<String, String> result = nxTools.table(- httpc.wput(new yacyURL("http://" + targetAddress(targetHash) + "/yacy/message.html", null),- yacySeed.b64Hash2hexHash(targetHash)+ ".yacyh",- 20000,- null,- null,- proxyConfig(),- post,- null- ), "UTF-8"- );+ final byte[] content = postToFile(targetHash, "message.html", post);+ final HashMap<String, String> result = nxTools.table(content, "UTF-8");return result;} catch (Exception e) {yacyCore.log.logSevere("yacyClient.postMessage error:" + e.getMessage());@@ -717,18 +700,10 @@ public final class yacyClient {// send requesttry {+ // TODO is targetAddress == url.getHost()?final yacyURL url = new yacyURL("http://" + targetAddress + "/yacy/transfer.html", null);- final HashMap<String, String> result = nxTools.table(- httpc.wput(url,- url.getHost(),- 6000,- null,- null,- proxyConfig(),- post,- null- ), "UTF-8"- );+ final byte[] content = wput("http://" + targetAddress + "/yacy/transfer.html", url.getHost(), post);+ final HashMap<String, String> result = nxTools.table(content, "UTF-8");return result;} catch (Exception e) {// most probably a network time-out exception@@ -752,18 +727,10 @@ public final class yacyClient {// send requesttry {+ // TODO is targetAddress == url.getHost()?final yacyURL url = new yacyURL("http://" + targetAddress + "/yacy/transfer.html", null);- final HashMap<String, String> result = nxTools.table(- httpc.wput(url,- url.getHost(),- 20000,- null,- null,- proxyConfig(),- post,- files- ), "UTF-8"- );+ final byte[] content = wput("http://" + targetAddress + "/yacy/transfer.html", url.getHost(), post);+ final HashMap<String, String> result = nxTools.table(content, "UTF-8");return result;} catch (Exception e) {yacyCore.log.logSevere("yacyClient.postMessage error:" + e.getMessage());@@ -836,17 +803,8 @@ public final class yacyClient {// send requesttry {- return nxTools.table(- httpc.wput(new yacyURL("http://" + address + "/yacy/crawlReceipt.html", null),- target.getHexHash() + ".yacyh",- 60000,- null,- null,- proxyConfig(),- post,- null- ), "UTF-8"- );+ byte[] content = wput("http://" + address + "/yacy/crawlReceipt.html", target.getHexHash() + ".yacyh", post);+ return nxTools.table(content, "UTF-8");} catch (Exception e) {// most probably a network time-out exceptionyacyCore.log.logSevere("yacyClient.crawlReceipt error:" + e.getMessage());@@ -953,7 +911,7 @@ public final class yacyClient {// enabling gzip compression for post request bodyif ((gzipBody) && (targetSeed.getVersion() >= yacyVersion.YACY_SUPPORTS_GZIP_POST_REQUESTS)) {- post.put(httpc.GZIP_POST_BODY,"true");+ post.put(GZIP_POST_BODY,"true");}post.put("wordc", Integer.toString(indexes.length));@@ -983,17 +941,8 @@ public final class yacyClient {post.put("entryc", indexcount);post.put("indexes", entrypost.toString());try {- final ArrayList<String> v = nxTools.strings(- httpc.wput(- new yacyURL("http://" + address + "/yacy/transferRWI.html", null),- targetSeed.getHexHash() + ".yacyh",- timeout,- null,- null,- proxyConfig(),- post,- null- ), "UTF-8");+ final byte[] content = wput("http://" + address + "/yacy/transferRWI.html", targetSeed.getHexHash() + ".yacyh", post);+ final ArrayList<String> v = nxTools.strings(content, "UTF-8");// this should return a list of urlhashes that are unknwonif ((v != null) && (v.size() > 0)) {yacyCore.seedDB.mySeed().incSI(indexcount);@@ -1019,7 +968,7 @@ public final class yacyClient {// enabling gzip compression for post request bodyif ((gzipBody) && (targetSeed.getVersion() >= yacyVersion.YACY_SUPPORTS_GZIP_POST_REQUESTS)) {- post.put(httpc.GZIP_POST_BODY,"true");+ post.put(GZIP_POST_BODY,"true");}String resource = "";@@ -1037,17 +986,8 @@ public final class yacyClient {}post.put("urlc", urlc);try {- final ArrayList<String> v = nxTools.strings(- httpc.wput(- new yacyURL("http://" + address + "/yacy/transferURL.html", null),- targetSeed.getHexHash() + ".yacyh",- timeout,- null,- null,- proxyConfig(),- post,- null- ), "UTF-8");+ final byte[] content = wput("http://" + address + "/yacy/transferURL.html", targetSeed.getHexHash() + ".yacyh", post);+ final ArrayList<String> v = nxTools.strings(content, "UTF-8");if ((v != null) && (v.size() > 0)) {yacyCore.seedDB.mySeed().incSU(urlc);@@ -1071,25 +1011,20 @@ public final class yacyClient {String address = targetSeed.getClusterAddress();if (address == null) { address = "localhost:8080"; }try {- return nxTools.table(- httpc.wput(- new yacyURL("http://" + address + "/yacy/profile.html", null),- targetSeed.getHexHash() + ".yacyh",- 10000,- null,- null,- proxyConfig(),- post,- null- ), "UTF-8");+ final byte[] content = wput("http://" + address + "/yacy/profile.html", targetSeed.getHexHash() + ".yacyh", post);+ return nxTools.table(content, "UTF-8");} catch (Exception e) {yacyCore.log.logSevere("yacyClient.getProfile error:" + e.getMessage());return null;}}+ /**+ * proxy for "to YaCy connections"+ * @return+ */private static final httpRemoteProxyConfig proxyConfig() {- httpRemoteProxyConfig p = plasmaSwitchboard.getSwitchboard().remoteProxyConfig;+ httpRemoteProxyConfig p = httpdProxyHandler.getRemoteProxyConfig();return ((p != null) && (p.useProxy()) && (p.useProxy4Yacy())) ? p : null;}@@ -1103,30 +1038,17 @@ public final class yacyClient {final String wordhashe = indexWord.word2hash("test");//System.out.println("permission=" + permissionMessage(args[1]));- // should we use the proxy?- boolean useProxy = (sb.remoteProxyConfig != null) &&- (sb.remoteProxyConfig.useProxy()) &&- (sb.remoteProxyConfig.useProxy4Yacy());-- final HashMap<String, String> result = nxTools.table(- httpc.wget(- new yacyURL("http://" + target.getPublicAddress() + "/yacy/search.html" +- "?myseed=" + yacyCore.seedDB.mySeed().genSeedStr(null) +- "&youare=" + target.hash + "&key=" +- "&myseed=" + yacyCore.seedDB.mySeed() .genSeedStr(null) +- "&count=10" +- "&resource=global" +- "&query=" + wordhashe +- "&network.unit.name=" + plasmaSwitchboard.getSwitchboard().getConfig("network.unit.name", yacySeed.DFLT_NETWORK_UNIT), null),- target.getHexHash() + ".yacyh",- 5000,- null,- null,- (useProxy) ? sb.remoteProxyConfig : null,- null,- null- )- , "UTF-8");+ final byte[] content = HttpClient.wget(+ "http://" + target.getPublicAddress() + "/yacy/search.html" ++ "?myseed=" + yacyCore.seedDB.mySeed().genSeedStr(null) ++ "&youare=" + target.hash + "&key=" ++ "&myseed=" + yacyCore.seedDB.mySeed() .genSeedStr(null) ++ "&count=10" ++ "&resource=global" ++ "&query=" + wordhashe ++ "&network.unit.name=" + plasmaSwitchboard.getSwitchboard().getConfig("network.unit.name", yacySeed.DFLT_NETWORK_UNIT),+ target.getHexHash() + ".yacyh");+ final HashMap<String, String> result = nxTools.table(content, "UTF-8");System.out.println("Result=" + result.toString());} catch (Exception e) {e.printStackTrace();diff --git a/source/de/anomic/yacy/yacyPeerActions.java b/source/de/anomic/yacy/yacyPeerActions.javaindex a64d8c9ae..65e0dded7 100644--- a/source/de/anomic/yacy/yacyPeerActions.java+++ b/source/de/anomic/yacy/yacyPeerActions.java@@ -49,8 +49,8 @@ import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;+import de.anomic.http.HttpClient;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.plasma.plasmaCrawlNURL;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverCore;@@ -172,7 +172,7 @@ public class yacyPeerActions {url = new yacyURL(seedListFileURL, null);long start = System.currentTimeMillis();- header = httpc.whead(url, url.getHost(), this.bootstrapLoadTimeout, null, null, this.sb.remoteProxyConfig,reqHeader);+ header = HttpClient.whead(url.toString(), reqHeader);long loadtime = System.currentTimeMillis() - start;if (header == null) {if (loadtime > this.bootstrapLoadTimeout) {@@ -186,7 +186,8 @@ public class yacyPeerActions {yacyCore.log.logInfo("BOOTSTRAP: seed-list URL " + seedListFileURL + " too old (" + (header.age() / 86400000) + " days)");} else {ssc++;- seedList = nxTools.strings(httpc.wget(url, url.getHost(), this.bootstrapLoadTimeout, null, null, this.sb.remoteProxyConfig,reqHeader, null), "UTF-8");+ final byte[] content = HttpClient.wget(url.toString(), reqHeader);+ seedList = nxTools.strings(content, "UTF-8");enu = seedList.iterator();lc = 0;while (enu.hasNext()) {diff --git a/source/de/anomic/yacy/yacySearch.java b/source/de/anomic/yacy/yacySearch.javaindex 878695c5e..4159f19f0 100644--- a/source/de/anomic/yacy/yacySearch.java+++ b/source/de/anomic/yacy/yacySearch.java@@ -54,8 +54,8 @@ import de.anomic.index.indexReferenceBlacklist;import de.anomic.kelondro.kelondroBitfield;import de.anomic.kelondro.kelondroMScoreCluster;import de.anomic.plasma.plasmaCrawlResults;-import de.anomic.plasma.plasmaSearchRankingProcess;import de.anomic.plasma.plasmaSearchQuery;+import de.anomic.plasma.plasmaSearchRankingProcess;import de.anomic.plasma.plasmaSearchRankingProfile;import de.anomic.plasma.plasmaWordIndex;import de.anomic.server.logging.serverLog;diff --git a/source/de/anomic/yacy/yacySeedDB.java b/source/de/anomic/yacy/yacySeedDB.javaindex 08a484e91..1b6b06919 100644--- a/source/de/anomic/yacy/yacySeedDB.java+++ b/source/de/anomic/yacy/yacySeedDB.java@@ -60,8 +60,10 @@ import java.util.Iterator;import java.util.Map;import java.util.TreeMap;+import de.anomic.http.HttpClient;+import de.anomic.http.HttpFactory;+import de.anomic.http.HttpResponse;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.http.httpd;import de.anomic.kelondro.kelondroBase64Order;import de.anomic.kelondro.kelondroDyn;@@ -809,35 +811,33 @@ public final class yacySeedDB {}private ArrayList<String> downloadSeedFile(yacyURL seedURL) throws IOException {- httpc remote = null;+ // Configure http headers+ httpHeader reqHeader = new httpHeader();+ reqHeader.put(httpHeader.PRAGMA, "no-cache");+ reqHeader.put(httpHeader.CACHE_CONTROL, "no-cache"); // httpc uses HTTP/1.0 is this necessary?++ // init http-client+ HttpClient client = HttpFactory.newClient(reqHeader, 10000);+ byte[] content = null;+ HttpResponse res = null;try {- // init httpc- remote = new httpc(- seedURL.getHost(),- seedURL.getHost(),- seedURL.getPort(),- 10000,- seedURL.getProtocol().equalsIgnoreCase("https"),- sb.remoteProxyConfig,- null, null);-- // Configure http headers- httpHeader reqHeader = new httpHeader();- reqHeader.put(httpHeader.PRAGMA, "no-cache");- reqHeader.put(httpHeader.CACHE_CONTROL, "no-cache"); // httpc uses HTTP/1.0 is this necessary?-// send request- httpc.response res = remote.GET(seedURL.getFile(), reqHeader);+ res = client.GET(seedURL.toString());// check response code- if (res.statusCode != 200) {- throw new IOException("Server returned status: " + res.status);+ if (res.getStatusCode() != 200) {+ throw new IOException("Server returned status: " + res.getStatusLine());}// read byte array- byte[] content = serverFileUtils.read(res.getContentInputStream());- remote.close();+ content = res.getData();+ } finally {+ if(res != null) {+ res.closeStream();+ }+ }+ try {// uncompress it if it is gzippedcontent = serverFileUtils.uncompressGZipArray(content);diff --git a/source/de/anomic/yacy/yacyVersion.java b/source/de/anomic/yacy/yacyVersion.javaindex cc6eb05d6..c6b12efda 100644--- a/source/de/anomic/yacy/yacyVersion.java+++ b/source/de/anomic/yacy/yacyVersion.java@@ -28,6 +28,7 @@package de.anomic.yacy;import java.io.File;+import java.io.FileOutputStream;import java.io.IOException;import java.util.ArrayList;import java.util.Comparator;@@ -39,7 +40,10 @@ import java.util.regex.Matcher;import java.util.regex.Pattern;import de.anomic.htmlFilter.htmlFilterContentScraper;-import de.anomic.http.httpc;+import de.anomic.http.HttpClient;+import de.anomic.http.HttpFactory;+import de.anomic.http.HttpResponse;+import de.anomic.http.HttpResponse.Saver;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverCore;import de.anomic.server.serverSystem;@@ -324,16 +328,17 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<yaFile storagePath = plasmaSwitchboard.getSwitchboard().releasePath;// load fileFile download = new File(storagePath, release.url.getFileName());- httpc.wget(- release.url,- release.url.getHost(),- 300000,- null,- null,- plasmaSwitchboard.getSwitchboard().remoteProxyConfig,- null,- download- );+ HttpClient client = HttpFactory.newClient(null, 30000);+ HttpResponse res = null;+ try {+ res = client.GET(release.url.toString());+ Saver.writeContent(res, new FileOutputStream(download), null);+ } finally {+ if(res != null) {+ // release connection+ res.closeStream();+ }+ }if ((!download.exists()) || (download.length() == 0)) throw new IOException("wget of url " + release.url + " failed");plasmaSwitchboard.getSwitchboard().setConfig("update.time.download", System.currentTimeMillis());}@@ -450,11 +455,12 @@ public final class yacyVersion implements Comparator<yacyVersion>, Comparable<ya* @param svn Current version given from SVN.* @return String with the combined version.*/- public static double versvn2combinedVersion(double v, int svn) {- return (Math.rint((v*100000000.0) + ((double)svn))/100000000);+ public static double versvn2combinedVersion(double version, int svn) {+ return (Math.rint((version*100000000.0) + ((double)svn))/100000000);}public static void main(String[] args) {+ System.out.println(thisVersion());float base = (float) 0.53;String blacklist = "....[123]";String test;diff --git a/source/de/anomic/ymage/ymageCaptcha.java b/source/de/anomic/ymage/ymageCaptcha.javaindex 81323ee4f..5693a2d11 100644--- a/source/de/anomic/ymage/ymageCaptcha.java+++ b/source/de/anomic/ymage/ymageCaptcha.java@@ -43,6 +43,7 @@package de.anomic.ymage;import java.util.Random;+import javax.imageio.ImageIO;public class ymageCaptcha extends ymageMatrix {diff --git a/source/yacy.java b/source/yacy.javaindex 2c9129842..7928c240f 100644--- a/source/yacy.java+++ b/source/yacy.java@@ -64,9 +64,12 @@ import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;import de.anomic.data.translator;+import de.anomic.http.HttpClient;+import de.anomic.http.HttpFactory;+import de.anomic.http.HttpResponse;import de.anomic.http.httpHeader;-import de.anomic.http.httpc;import de.anomic.http.httpd;+import de.anomic.http.HttpResponse.Saver;import de.anomic.index.indexContainer;import de.anomic.index.indexRWIEntry;import de.anomic.index.indexRWIRowEntry;@@ -421,8 +424,9 @@ public final class yacy {server.terminate(false);server.interrupt();if (server.isAlive()) try {+ // TODO only send request, don't read response (cause server is already down resulting in error)yacyURL u = new yacyURL((server.withSSL()?"https":"http")+"://localhost:" + serverCore.getPortNr(port), null);- httpc.wget(u, u.getHost(), 1000, null, null, null, null, null); // kick server+ HttpClient.wget(u.toString()); // kick serverserverLog.logConfig("SHUTDOWN", "sent termination signal to server socket");} catch (IOException ee) {serverLog.logConfig("SHUTDOWN", "termination signal to server socket missed (server shutdown, ok)");@@ -517,25 +521,29 @@ public final class yacy {// send 'wget' to web interfacehttpHeader requestHeader = new httpHeader();requestHeader.put("Authorization", "realm=" + encodedPassword); // for http-authentify+ HttpClient con = HttpFactory.newClient(requestHeader, 10000);+ HttpResponse res = null;try {- httpc con = new httpc("localhost", "localhost", port, 10000, false, null, null, null);- httpc.response res = con.GET("Steering.html?shutdown=", requestHeader);+ res = con.GET("http://localhost:"+ port +"/Steering.html?shutdown=");// read response- if (res.status.startsWith("2")) {+ if (res.getStatusLine().startsWith("2")) {serverLog.logConfig("REMOTE-SHUTDOWN", "YACY accepted shutdown command.");serverLog.logConfig("REMOTE-SHUTDOWN", "Stand by for termination, which may last some seconds.");ByteArrayOutputStream bos = new ByteArrayOutputStream();- res.writeContent(bos, null);- con.close();+ Saver.writeContent(res, bos, null);} else {- serverLog.logSevere("REMOTE-SHUTDOWN", "error response from YACY socket: " + res.status);- con.close();+ serverLog.logSevere("REMOTE-SHUTDOWN", "error response from YACY socket: " + res.getStatusLine());System.exit(-1);}} catch (IOException e) {serverLog.logSevere("REMOTE-SHUTDOWN", "could not establish connection to YACY socket: " + e.getMessage());System.exit(-1);+ } finally {+ // release connection+ if(res != null) {+ res.closeStream();+ }}// finished@@ -594,7 +602,7 @@ public final class yacy {/*** @param homePath path to the YaCy directory- * @param dbcache cache size in MB+ * @param networkName*/public static void minimizeUrlDB(File homePath, String networkName) {// run with "java -classpath classes yacy -minimizeUrlDB"