Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance
Java decentralizedintranet-searchintranet-search-enginep2pp2p-networkprivacyprivacy-protectionsearch-enginesearchenginewebweb-search-enginewebsearchwebseearch-engine
Multiple updates regarding the yacy seedUpload facility, optional content parsers, thread pool configuration ...
theli361f05978df1
diff --git a/build.xml b/build.xmlindex 3144e0629..8cb9301af 100644--- a/build.xml+++ b/build.xml@@ -97,26 +97,40 @@</target><target name="compile" depends="init" description="Compiling the yacy sources ...">++ <!-- defining the classpath that should be used for compiling -->+ <path id="project.class.path">+ <pathelement location="${build}"/>++ <!-- libs needed for the yacy thread/object-pools -->+ <pathelement location="${lib}/commons-collections.jar" />+ <pathelement location="${lib}/commons-pool-1.2.jar" />+ </path>++ <!-- compiling the main sources --><javac srcdir="${src}/" destdir="${build}"- excludes="de/anomic/plasma/parser/*/*"+ excludes="de/anomic/plasma/parser/*/*,de/anomic/yacy/seedUpload/**,de/anomic/soap/**"debug="true"source="${javacSource}" target="${javacTarget}">- <classpath>- <pathelement location="${build}" />-- <!-- libs needed for the yacy thread/object-pools -->- <pathelement location="${lib}/commons-collections.jar" />- <pathelement location="${lib}/commons-pool-1.2.jar" />- </classpath>+ <classpath refid="project.class.path"/></javac>+ <!-- compiling the two standard seed uploader methods -->+ <javac srcdir="${src}" destdir="${build}"+ classpathref="project.class.path"+ source="1.4" target="1.4">+ <include name="de/anomic/yacy/seedUpload/yacySeedUploadFile.java" />+ <include name="de/anomic/yacy/seedUpload/yacySeedUploadFtp.java"/>+ </javac>+ <!-- compiling htroot and htdocsdefault --><javac srcdir="${htroot}/" destdir="${htroot}"- classpath="${build}"+ classpathref="project.class.path"source="1.4" target="1.4"/><javac srcdir="${htroot}/htdocsdefault" destdir="${htroot}/htdocsdefault"- classpath="${build}"+ classpathref="project.class.path"source="1.4" target="1.4"/>+ <!-- compiling yacy.java --><javac srcdir="${htroot}/yacy" destdir="${htroot}/yacy"- classpath="${build}"+ classpathref="project.class.path"source="1.4" target="1.4"/></target>@@ -125,6 +139,7 @@<move file="${src}/yacy.java.orig" tofile="${src}/yacy.java" /></target>+<!-- compiling optional content parsers and building install packages --><target name="parsers" depends="compile" description="Compiling and zipping all additional parsers"><subant target=""><property name="src" location="${src}"/>@@ -133,23 +148,47 @@<property name="release" location="${release}"/><property name="javacSource" value="${javacSource}"/><property name="javacTarget" value="${javacTarget}"/>+ <!-- each optional parser must have its own build file --><fileset dir="${src}/" includes="de/anomic/plasma/parser/*/build.xml"/></subant></target>++<!-- compiling optional seed uploaders and building install packages -->+<target name="seedUploaders" depends="compile" description="Compiling and zipping additional seed uploaders">+ <subant target="">+ <property name="src" location="${src}"/>+ <property name="build" location="${build}"/>+ <property name="libx" location="${libx}"/>+ <property name="htroot" value="${htroot}"/>+ <property name="release" location="${release}"/>+ <property name="javacSource" value="${javacSource}"/>+ <property name="javacTarget" value="${javacTarget}"/>+ <!-- each optionl uploader module must have its own build file -->+ <fileset dir="${src}/" includes="de/anomic/yacy/seedUpload/yacySeedUpload*.xml"/>+ </subant>+</target>-<target name="dist" depends="all,parsers" description="Compiling sources and make a release file ...">+<!-- making a release file for yacy -->+<target name="dist" depends="all,parsers,seedUploaders" description="Compiling sources and make a release file ...">+ <!-- defining some file/directory access rights --><property name="accessRightsDir" value="755"/><property name="accessRightsFile" value="644"/><tar destfile="${release}/${releaseFile}" compression="gzip" defaultexcludes="yes">- <!-- copy classes -->+ <!-- copy class files --><tarfileset dir="${build}" prefix="classes" dirmode="${accessRightsDir}" mode="${accessRightsFile}" ><include name="**/*.*"/><exclude name="de/anomic/plasma/parser/*/*"/>+ <exclude name="de/anomic/yacy/seedUpload/**"/>+ <exclude name="de/anomic/soap/**"/></tarfileset>-+ <tarfileset dir="${build}" prefix="classes" dirmode="${accessRightsDir}" mode="${accessRightsFile}" >+ <include name="de/anomic/yacy/seedUpload/yacySeedUploadFile.class"/>+ <include name="de/anomic/yacy/seedUpload/yacySeedUploadFtp.class"/>+ </tarfileset>+<!-- copy libs --><tarfileset dir="${lib}" includes="**/*" prefix="lib" dirmode="${accessRightsDir}" mode="${accessRightsFile}"/>@@ -190,12 +229,23 @@<tarfileset dir="${src}" prefix="source" dirmode="${accessRightsDir}" mode="${accessRightsFile}"><include name="**/*.*"/><exclude name="de/anomic/plasma/parser/*/*"/>+ <exclude name="de/anomic/yacy/seedUpload/yacySeedUpload**"/>+ <exclude name="de/anomic/soap/**"/></tarfileset>+ <tarfileset dir="${src}" prefix="source" dirmode="${accessRightsDir}" mode="${accessRightsFile}">+ <include name="de/anomic/yacy/seedUpload/yacySeedUploadFile.java"/>+ <include name="de/anomic/yacy/seedUpload/yacySeedUploadFtp.java"/>+ </tarfileset><!-- copy server pages --><tarfileset dir="${htroot}" prefix="htroot" dirmode="${accessRightsDir}" mode="${accessRightsFile}"><include name="**/*"/>+ <exclude name="yacy/seedUpload/**"/></tarfileset>+ <tarfileset dir="${htroot}" prefix="htroot" dirmode="${accessRightsDir}" mode="${accessRightsFile}" >+ <include name="yacy/seedUpload/yacySeedUploadFile.html"/>+ <include name="yacy/seedUpload/yacySeedUploadFtp.html"/>+ </tarfileset><!-- copy add-on's --><tarfileset dir="${addon}" prefix="addon" dirmode="${accessRightsDir}" mode="${accessRightsFile}">@@ -203,9 +253,12 @@</tarfileset></tar>+ <!-- writing the current release version into a file --><echo message="${releaseVersion}" file="${doc}/release.txt"/></target>++<!-- make clean --><target name="clean" description="make clean"><delete><fileset dir="${build}" includes="**/*.class" />diff --git a/htroot/IndexCreate_p.java b/htroot/IndexCreate_p.javaindex efc269194..7009cc280 100644--- a/htroot/IndexCreate_p.java+++ b/htroot/IndexCreate_p.java@@ -122,7 +122,7 @@ public class IndexCreate_p {}// check if pattern matches- if ((crawlingStartURL == null) || (!(crawlingStart.matches(newcrawlingfilter)))) {+ if ((crawlingStartURL == null) /* || (!(crawlingStart.matches(newcrawlingfilter))) */) {// print error messageprop.put("error", 4); //crawlfilter does not match urlprop.put("error_newcrawlingfilter", newcrawlingfilter);diff --git a/htroot/Performance_p.html b/htroot/Performance_p.htmlindex 9b965d967..f19d542ad 100644--- a/htroot/Performance_p.html+++ b/htroot/Performance_p.html@@ -117,6 +117,35 @@ Changes take effect immediately</td></form></table></p>++<div class=small><b>Thread pool settings:</b></div>+<form action="Performance_p.html" method="post" enctype="multipart/form-data">+<table border="0" cellpadding="2" cellspacing="1" width="100%">+<tr class="TableHeader" valign="bottom">+<td class="small" width="150">Thread Pool</td>+<td class="small" width="80">maximum Active</td>+<td class="small" width="80">maximum Idle</td>+<td class="small" width="80">minimum Idle</td>+<td class="small">Full Description</td>+</tr>+#{pool}#+<tr class="TableCellDark">+<td class="small" align="left">#[name]#</td>+<td class="small" align="right"><input name="#[name]#_maxActive" type="text" size="8" maxlength="8" value="#[maxActive]#"></td>+<td class="small" align="right"><input name="#[name]#_maxIdle" type="text" size="8" maxlength="8" value="#[maxIdle]#"></td>+<td class="small" align="right"><input name="#[name]#_minIdle" type="text" size="8" maxlength="8" value="#[minIdle]#"></td>+<td class="small" align="left"></td>+</tr>+#{/pool}#+<tr class="TableCellLight">+<td class="small" align="left" colspan="5">+<input type="submit" name="poolConfig" value="Enter new Threadpool Configuration">+Changes take effect immediately</td>+</tr>+</table>+</p></form>++#[footer]#</body></html>diff --git a/htroot/Performance_p.java b/htroot/Performance_p.javaindex d84c94a74..cda6bc1ca 100644--- a/htroot/Performance_p.java+++ b/htroot/Performance_p.java@@ -45,8 +45,12 @@import java.util.Iterator;+import org.apache.commons.pool.impl.GenericObjectPool;+import de.anomic.http.httpHeader;+import de.anomic.http.httpd;import de.anomic.plasma.plasmaSwitchboard;+import de.anomic.server.serverCore;import de.anomic.server.serverObjects;import de.anomic.server.serverSwitch;import de.anomic.server.serverThread;@@ -141,6 +145,34 @@ public class Performance_p {int maxWaitingWordFlush = Integer.parseInt((String) post.get("maxWaitingWordFlush", "180"));switchboard.setConfig("maxWaitingWordFlush", "" + maxWaitingWordFlush);}++ if ((post != null) && (post.containsKey("poolConfig"))) {+ GenericObjectPool.Config crawlerPoolConfig = switchboard.cacheLoader.getPoolConfig();+ int maxActive = Integer.parseInt(post.get("Crawler Pool_maxActive","8"));+ int maxIdle = Integer.parseInt(post.get("Crawler Pool_maxIdle","4"));+ int minIdle = Integer.parseInt(post.get("Crawler Pool_minIdle","0"));++ crawlerPoolConfig.minIdle = (minIdle > maxIdle) ? maxIdle/2 : minIdle;+ crawlerPoolConfig.maxIdle = (maxIdle > maxActive) ? maxActive/2 : maxIdle;+ crawlerPoolConfig.maxActive = maxActive;++ plasmaSwitchboard.crawlSlots = maxActive;+ switchboard.cacheLoader.setPoolConfig(crawlerPoolConfig);++ serverThread httpd = switchboard.getThread("10_httpd");+ GenericObjectPool.Config httpdPoolConfig = ((serverCore)httpd).getPoolConfig();+ maxActive = Integer.parseInt(post.get("httpd Session Pool_maxActive","8"));+ maxIdle = Integer.parseInt(post.get("httpd Session Pool_maxIdle","4"));+ minIdle = Integer.parseInt(post.get("httpd Session Pool_minIdle","0"));++ httpdPoolConfig.minIdle = (minIdle > maxIdle) ? maxIdle/2 : minIdle;+ httpdPoolConfig.maxIdle = (maxIdle > maxActive) ? maxActive/2 : maxIdle;+ httpdPoolConfig.maxActive = maxActive;++ ((serverCore)httpd).maxSessions = maxActive;+ ((serverCore)httpd).setPoolConfig(httpdPoolConfig);+ }+// table cache settingsprop.put("wordCacheRAMSize", switchboard.wordIndex.wordCacheRAMSize());prop.put("maxURLinWordCache", "" + switchboard.wordIndex.maxURLinWordCache());@@ -148,6 +180,22 @@ public class Performance_p {prop.put("wordCacheMax", switchboard.getConfig("wordCacheMax", "10000"));prop.put("singletonsSize", switchboard.wordIndex.singletonsSize());+ // table thread pool settings+ GenericObjectPool.Config crawlerPoolConfig = switchboard.cacheLoader.getPoolConfig();+ prop.put("pool_0_name","Crawler Pool");+ prop.put("pool_0_maxActive",crawlerPoolConfig.maxActive);+ prop.put("pool_0_maxIdle",crawlerPoolConfig.maxIdle);+ prop.put("pool_0_minIdle",crawlerPoolConfig.maxIdle);++ serverThread httpd = switchboard.getThread("10_httpd");+ GenericObjectPool.Config httpdPoolConfig = ((serverCore)httpd).getPoolConfig();+ prop.put("pool_1_name","httpd Session Pool");+ prop.put("pool_1_maxActive",httpdPoolConfig.maxActive);+ prop.put("pool_1_maxIdle",httpdPoolConfig.maxIdle);+ prop.put("pool_1_minIdle",httpdPoolConfig.maxIdle);+ prop.put("pool",2);++// return rewrite values for templatesreturn prop;}diff --git a/htroot/SettingsAck_p.html b/htroot/SettingsAck_p.htmlindex 342d92767..b02f57f83 100644--- a/htroot/SettingsAck_p.html+++ b/htroot/SettingsAck_p.html@@ -52,9 +52,11 @@ You are now permanently <b>online</b>. After a short while you should see the ef<b>Transparent Proxy Support is: <font color="#556699">#[isTransparentProxy]#</font></b><p><u>if you changed the Port, you need to restart the Proxy.</u>::-<b>SeedFTP Server Settings changed. You are now a principal peer.</b><br>+<b>Seed Settings changed. You are now a principal peer.</b><br>::-<b>SeedFTP Server Settings changed, but something is wrong. Please return to the settings page and modify the data.</b><br>+<b>Seed Settings changed, but something is wrong.<b>+Seed Uploading was deactivated automatically.+Please return to the settings page and modify the data.</b><br>::<b>The remote-proxy setting has been changed</b><br>The new setting is effective immediately, you don't need to re-start.@@ -66,7 +68,20 @@ The settings have not been changed.Peer names must not contain characters other than (a-z, A-Z, 0-9, '-', '_') and must not be longer than 80 characters.The settings have not been changed.::-The new parser settings where changed successfully.#(/info)#+The new parser settings where changed successfully.<p>+Parsing of the following mime-types was enabled:<br>+<ul>+#{parser}#+<li><font color="#556699">#[enabledMime]#</font></li>+#{/parser}#+</ul>+::+Seed Upload method was changed successfully.<p>+<table>+<tr><td>Seed Upload Method:</td><td><font color="#556699">#[seedUploadMethod]#</font></td></tr>+<tr><td>Seed File URL:</td><td><a href="#[seedURL]#"><font color="#556699">#[seedURL]#</font></a></td></tr>+</table>+#(/info)#</p><p>You can now go back to the <a href="Settings_p.html">Settings</a> page if you want to make more changes.</p>diff --git a/htroot/SettingsAck_p.java b/htroot/SettingsAck_p.javaindex 593e706e0..9dcd7f891 100644--- a/htroot/SettingsAck_p.java+++ b/htroot/SettingsAck_p.java@@ -43,7 +43,14 @@// javac -classpath .:../Classes SettingsAck_p.java// if the shell's current path is HTROOT+import java.net.URL;+import java.util.Arrays;+import java.util.Collection;+import java.util.Collections;import java.util.Enumeration;+import java.util.Hashtable;+import java.util.Iterator;+import java.util.List;import de.anomic.http.httpHeader;import de.anomic.http.httpdProxyHandler;@@ -53,9 +60,12 @@ import de.anomic.server.serverObjects;import de.anomic.server.serverSwitch;import de.anomic.yacy.yacyCore;import de.anomic.yacy.yacySeed;+import de.anomic.yacy.yacySeedUploader;public class SettingsAck_p {+ private static boolean nothingChanged;+public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {// return variable that accumulates replacementsserverObjects prop = new serverObjects();@@ -245,26 +255,106 @@ public class SettingsAck_p {return prop;}- if (post.containsKey("seedFTPsettings")) {- env.setConfig("seedFTPServer", (String)post.get("seedFTPServer"));- env.setConfig("seedFTPPath", (String)post.get("seedFTPPath"));- env.setConfig("seedFTPAccount", (String)post.get("seedFTPAccount"));- env.setConfig("seedFTPPassword", (String)post.get("seedFTPPassword"));- env.setConfig("seedURL", (String)post.get("seedURL"));- if (yacyCore.saveSeedList(env))- prop.put("info", 13);//SeedServer changed- else- prop.put("info", 14);//Seedserver changed, but something is wrong- return prop;+ if (post.containsKey("seedSettings")) {+ try {+ // getting the currently used uploading method+ String oldSeedUploadMethod = env.getConfig("seedUploadMethod","none");+ String newSeedUploadMethod = (String)post.get("seedUploadMethod");+ String oldSeedURLStr = env.getConfig("seedURL","");+ String newSeedURLStr = (String)post.get("seedURL");+ new URL(newSeedURLStr);++ boolean seedUrlChanged = !oldSeedURLStr.equals(newSeedURLStr);+ boolean uploadMethodChanged = !oldSeedUploadMethod.equals(newSeedUploadMethod);+ if (uploadMethodChanged) {+ uploadMethodChanged = yacyCore.changeSeedUploadMethod((String) post.get("seedUploadMethod"));+ }++ if (seedUrlChanged || uploadMethodChanged) {+ env.setConfig("seedUploadMethod", (String)post.get("seedUploadMethod"));+ env.setConfig("seedURL", newSeedURLStr);++ boolean success = yacyCore.saveSeedList(env);+ if (!success) {+ prop.put("info", 14);+ env.setConfig("seedUploadMethod","none");+ } else {+ prop.put("info_seedUploadMethod",newSeedUploadMethod);+ prop.put("info_seedURL",newSeedURLStr);+ prop.put("info", 19);+ }+ }+ } catch (Exception e) {+ prop.put("info",14);+ }+ return prop;+ }++ /*+ * Loop through the available seed uploaders to see if the+ * configuration of one of them has changed+ */+ Hashtable uploaders = yacyCore.getSeedUploadMethods();+ Enumeration uploaderKeys = uploaders.keys();+ while (uploaderKeys.hasMoreElements()) {+ // getting the uploader module name+ String uploaderName = (String) uploaderKeys.nextElement();++ // determining if the user has reconfigured the settings of this uploader+ if (post.containsKey("seed" + uploaderName + "Settings")) {+ nothingChanged = true;+ yacySeedUploader theUploader = yacyCore.getSeedUploader(uploaderName);+ String[] configOptions = theUploader.getConfigurationOptions();+ if (configOptions != null) {+ for (int i=0; i<configOptions.length; i++) {+ String newSettings = post.get(configOptions[i],"");+ String oldSettings = env.getConfig(configOptions[i],"");+ nothingChanged &= newSettings.equals(oldSettings);+ if (!nothingChanged) {+ env.setConfig(configOptions[i],newSettings);+ }+ }+ }+ if ((!nothingChanged)&&(env.getConfig("seedUploadMethod","none").equals(theUploader))) {+ boolean success = yacyCore.saveSeedList(env);+ if (!success) {+ prop.put("info", 14);+ env.setConfig("seedUploadMethod","none");+ } else {+ prop.put("info", 13);+ }+ } else {+ prop.put("info", 13);+ }+ }+}++if (post.containsKey("parserSettings")) {plasmaSwitchboard sb = (plasmaSwitchboard)env;post.remove("parserSettings");- // activate all received parsers- Enumeration mimeTypeEnum = post.keys();- sb.parser.setEnabledParserList(mimeTypeEnum);+ String[] enabledMimes = null;+ if (post.containsKey("allParserEnabled")) {+ // enable all available parsers+ enabledMimes = sb.parser.setEnabledParserList(sb.parser.getAvailableParserList().keySet());+ } else {+ // activate all received parsers+ enabledMimes = sb.parser.setEnabledParserList(post.keySet());+ }+ Arrays.sort(enabledMimes);++ StringBuffer enabledMimesTxt = new StringBuffer();+ for (int i=0; i < enabledMimes.length; i++) {+ enabledMimesTxt.append(enabledMimes[i]).append(",");+ prop.put("info_parser_" + i + "_enabledMime",enabledMimes[i]);+ }+ prop.put("info_parser",enabledMimes.length);+ if (enabledMimesTxt.length() > 0) enabledMimesTxt.deleteCharAt(enabledMimesTxt.length()-1);++ env.setConfig("parseableMimeTypes",enabledMimesTxt.toString());prop.put("info", 18);return prop;diff --git a/htroot/Settings_p.html b/htroot/Settings_p.htmlindex e195ba8d8..114d1c30f 100644--- a/htroot/Settings_p.html+++ b/htroot/Settings_p.html@@ -134,65 +134,72 @@ delete the file 'DATA/SETTINGS/httpProxy.conf' in the YaCy application root fold</fieldset></form><br>-<p><form action="SettingsAck_p.html" method="post" enctype="multipart/form-data">+<p><fieldset><legend>Seed Upload Settings</legend>-<p>This is the account for an ftp server where you can host a seed-list file.-If you set this, you will become a principal peer.+<p>With this settings you can configure if you have an account on a public accessable+server where you can host a seed-list file.</p>+<p><b>General Settings:</b></p>+If you enable one of the available uploading methods, you will become a principal peer.Your peer will then upload the seed-bootstrap information periodically,but only if there had been changes to the seed-list.</p>-<p>+<form action="SettingsAck_p.html" method="post" enctype="multipart/form-data"><table border="0" cellspacing="5"><tr valign="top">- <td>Server:</td>- <td><input name="seedFTPServer" type="text" size="40" value="#[seedFTPServer]#"></td>- <td><i>The host where you have an FTP account, like 'ftp.<my-host>.net'</i></td>- </tr>- <tr valign="top">- <td>Path:</td>- <td><input name="seedFTPPath" type="text" size="40" value="#[seedFTPPath]#"></td>- <td><i>The remote path on the ftp server, like 'yacy/seed.txt'.- Missing sub-directories are NOT created automatically.</i></td>+ <td>Upload Method:</td>+ <td><select name="seedUploadMethod" size="1">+#{seedUploadMethods}#+ <option value="#[name]#" #(selected)#::selected#(/selected)#>#[name]#</option>+#{/seedUploadMethods}#+ </select></td>+ <td><i>Here you can specify which upload method should be used. Select 'none' to deativate uploading.</i></td></tr>- <tr valign="top">- <td>Username:</td>- <td><input name="seedFTPAccount" type="text" size="40" value="#[seedFTPAccount]#"></td>- <td><i>Your log-in at the ftp server</i></td>- </tr>- <tr valign="top">- <td>Password:</td>- <td><input name="seedFTPPassword" type="password" size="40" value="#[seedFTPPassword]#"></td>- <td><i>The password</i></td>- </tr>- <tr><tr valign="top"><td>URL:</td><td><input name="seedURL" type="text" size="40" value="#[seedURL]#"></td><td><i>The URL that can be used to retrieve the uploaded seed file, likehttp://www.<my-host>.net/yacy/seed.txt'</i></td>- </tr>+ </tr><tr>- <td><input type="submit" name="seedFTPsettings" value="submit"></td>- </tr>+ <td colspan="3"><input type="submit" name="seedSettings" value="submit"></td>+ </tr></table>+</form>++#{seedUploadMethods}#+#%[file]%#+#{/seedUploadMethods}#</fieldset>-</form><br>+<br><p><form action="SettingsAck_p.html" method="post" enctype="multipart/form-data"><fieldset><legend>Content Parser Settings</legend>-<p>Activation/Deactivation of additional content parsers ...</p>+<p>With this settings you can activate or deactivate parsing of additional content types based on there mime-types.<br>+For a detailed description of the various mime-types take a look at <a href="http://www.iana.org/assignments/media-types/">http://www.iana.org/assignments/media-types/</a></p><p>-<table>+<table border="0" cellpadding="2" cellspacing="1">+<tr class="TableHeader" valign="bottom">+<td class="small" >Activate</td>+<td class="small" >Mime-Type</td>+<td class="small" >Parser Class Name</td>+<td class="small" ></td>+</tr>#{parser}#-<tr>- <td><input type="checkbox" name="#[mime]#" align="top" #(status)#::checked#(/status)#></td>- <td>#[mime]#</td>- <td>#[name]#</td>+<tr class="TableCellDark">+ <td class="small" align="center"><input type="checkbox" name="#[mime]#" align="top" #(status)#::checked#(/status)#></td>+ <td class="small" >#[mime]#</td>+ <td class="small" title="Full qualified name: #[name]#">#[shortname]#</td>+ <td class="small" width="100%"></td></tr>#{/parser}#- <tr>- <td colspan="3"><input type="submit" name="parserSettings" value="submit"></td>+ <tr class="TableCellLight">+ <td class="small" align="center"><input type="checkbox" name="allParserEnabled" align="top" #(allParserEnabled)#::checked#(/allParserEnabled)#>+ <td colspan="2" class="small" >Enable all parsers</td>+ <td class="small"> </td>+ </tr>+ <tr class="TableCellLight">+ <td colspan="4" class="small" ><input type="submit" name="parserSettings" value="submit"> Changes take effect immediately</td></tr></table></fieldset>diff --git a/htroot/Settings_p.java b/htroot/Settings_p.javaindex 3dd287fc0..adb43ea85 100644--- a/htroot/Settings_p.java+++ b/htroot/Settings_p.java@@ -45,6 +45,7 @@import java.util.Arrays;import java.util.Collections;+import java.util.Enumeration;import java.util.Hashtable;import java.util.Iterator;import java.util.List;@@ -53,117 +54,152 @@ import de.anomic.http.httpHeader;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverObjects;import de.anomic.server.serverSwitch;+import de.anomic.yacy.yacyCore;+import de.anomic.yacy.yacySeedUploader;-public class Settings_p {+public final class Settings_p {public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {- // return variable that accumulates replacements- serverObjects prop = new serverObjects();-- //if (post == null) System.out.println("POST: NULL"); else System.out.println("POST: " + post.toString());-- prop.put("port", env.getConfig("port", "8080"));- prop.put("peerName", env.getConfig("peerName", "nameless"));- prop.put("isTransparentProxy", env.getConfig("isTransparentProxy", "false").equals("true") ? 1 : 0);-- // set values- String s;- int pos;-- // admin password- if (env.getConfig("adminAccountBase64", "").length() == 0) {- // no password has been specified- prop.put("adminuser","admin");- } else {- s = env.getConfig("adminAccount", "admin:void");- pos = s.indexOf(":");- if (pos < 0) {- prop.put("adminuser","admin");- } else {- prop.put("adminuser",s.substring(0, pos));- }- }-+ // return variable that accumulates replacements+ serverObjects prop = new serverObjects();++ //if (post == null) System.out.println("POST: NULL"); else System.out.println("POST: " + post.toString());++ prop.put("port", env.getConfig("port", "8080"));+ prop.put("peerName", env.getConfig("peerName", "nameless"));+ prop.put("isTransparentProxy", env.getConfig("isTransparentProxy", "false").equals("true") ? 1 : 0);++ // set values+ String s;+ int pos;++ // admin password+ if (env.getConfig("adminAccountBase64", "").length() == 0) {+ // no password has been specified+ prop.put("adminuser","admin");+ } else {+ s = env.getConfig("adminAccount", "admin:void");+ pos = s.indexOf(":");+ if (pos < 0) {+ prop.put("adminuser","admin");+ } else {+ prop.put("adminuser",s.substring(0, pos));+ }+ }+// remote proxyprop.put("remoteProxyHost", env.getConfig("remoteProxyHost", ""));prop.put("remoteProxyPort", env.getConfig("remoteProxyPort", ""));prop.put("remoteProxyNoProxy", env.getConfig("remoteProxyNoProxy", ""));prop.put("remoteProxyUseChecked", ((String) env.getConfig("remoteProxyUse", "false")).equals("true") ? 1 : 0);-- // proxy access filter- prop.put("proxyfilter", env.getConfig("proxyClient", "*"));-- // proxy password- if (env.getConfig("proxyAccountBase64", "").length() == 0) {- // no password has been specified- prop.put("proxyuser","proxy");- } else {- s = env.getConfig("proxyAccount", "proxy:void");- pos = s.indexOf(":");- if (pos < 0) {- prop.put("proxyuser","proxy");- } else {- prop.put("proxyuser",s.substring(0, pos));- }- }-- // server access filter- prop.put("serverfilter", env.getConfig("serverClient", "*"));-- // server password- if (env.getConfig("serverAccountBase64", "").length() == 0) {- // no password has been specified- prop.put("serveruser","server");- } else {- s = env.getConfig("serverAccount", "server:void");- pos = s.indexOf(":");- if (pos < 0) {- prop.put("serveruser","server");- } else {- prop.put("serveruser",s.substring(0, pos));- }- }-- // clientIP- prop.put("clientIP", (String) header.get("CLIENTIP", "<unknown>")); // read an artificial header addendum- //seedFTPSettings- prop.put("seedFTPServer", env.getConfig("seedFTPServer", ""));- prop.put("seedFTPPath", env.getConfig("seedFTPPath", ""));- prop.put("seedFTPAccount", env.getConfig("seedFTPAccount", ""));- prop.put("seedFTPPassword", env.getConfig("seedFTPPassword", ""));- prop.put("seedURL", env.getConfig("seedURL", ""));--- /*- * Parser Configuration- */- plasmaSwitchboard sb = (plasmaSwitchboard)env;- Hashtable enabledParsers = sb.parser.getEnabledParserList();- Hashtable availableParsers = sb.parser.getAvailableParserList();-- // fetching a list of all available mimetypes- List availableParserKeys = Arrays.asList(availableParsers.keySet().toArray(new String[availableParsers.size()]));-- // sort it- Collections.sort(availableParserKeys);-- // loop through the mimeTypes and add it to the properties- int parserIdx = 0;- Iterator availableParserIter = availableParserKeys.iterator();- while (availableParserIter.hasNext()) {- String mimeType = (String) availableParserIter.next();- prop.put("parser_" + parserIdx + "_mime", mimeType);- prop.put("parser_" + parserIdx + "_name", availableParsers.get(mimeType));- prop.put("parser_" + parserIdx + "_status", enabledParsers.containsKey(mimeType) ? 1:0);+ // proxy access filter+ prop.put("proxyfilter", env.getConfig("proxyClient", "*"));- parserIdx++;- }-- prop.put("parser", parserIdx);-- // return rewrite properties- return prop;+ // proxy password+ if (env.getConfig("proxyAccountBase64", "").length() == 0) {+ // no password has been specified+ prop.put("proxyuser","proxy");+ } else {+ s = env.getConfig("proxyAccount", "proxy:void");+ pos = s.indexOf(":");+ if (pos < 0) {+ prop.put("proxyuser","proxy");+ } else {+ prop.put("proxyuser",s.substring(0, pos));+ }+ }++ // server access filter+ prop.put("serverfilter", env.getConfig("serverClient", "*"));++ // server password+ if (env.getConfig("serverAccountBase64", "").length() == 0) {+ // no password has been specified+ prop.put("serveruser","server");+ } else {+ s = env.getConfig("serverAccount", "server:void");+ pos = s.indexOf(":");+ if (pos < 0) {+ prop.put("serveruser","server");+ } else {+ prop.put("serveruser",s.substring(0, pos));+ }+ }++ // clientIP+ prop.put("clientIP", (String) header.get("CLIENTIP", "<unknown>")); // read an artificial header addendum++ /*+ * seed upload settings+ */+ // available methods+ String enabledUploader = env.getConfig("seedUploadMethod", "none");+ Hashtable uploaders = yacyCore.getSeedUploadMethods();+ prop.put("seedUploadMethods", uploaders.size() + 1);+ prop.put("seedUploadMethods_0_name", "none");+ prop.put("seedUploadMethods_0_selected", 1);+ prop.put("seedUploadMethods_0_file", "");++ int count = 0;+ Enumeration uploaderKeys = uploaders.keys();+ while (uploaderKeys.hasMoreElements()) {+ count++;+ String uploaderName = (String) uploaderKeys.nextElement();+ prop.put("seedUploadMethods_" +count+ "_name", uploaderName);+ prop.put("seedUploadMethods_" +count+ "_selected", uploaderName.equals(enabledUploader)?1:0);+ prop.put("seedUploadMethods_" +count+ "_file", "yacy/seedUpload/yacySeedUpload" + uploaderName + ".html");++ yacySeedUploader theUploader = yacyCore.getSeedUploader(uploaderName);+ String[] configOptions = theUploader.getConfigurationOptions();+ if (configOptions != null) {+ for (int i=0; i<configOptions.length; i++) {+ prop.put("seedUploadMethods_" +count+ "_" + configOptions[i], env.getConfig(configOptions[i], ""));+ // prop.put("seedUpload" + uploaderName,1);+ }+ }+ }++ // general settings+ prop.put("seedURL", env.getConfig("seedURL", ""));+++ /*+ * Parser Configuration+ */+ plasmaSwitchboard sb = (plasmaSwitchboard)env;+ Hashtable enabledParsers = sb.parser.getEnabledParserList();+ Hashtable availableParsers = sb.parser.getAvailableParserList();++ // fetching a list of all available mimetypes+ List availableParserKeys = Arrays.asList(availableParsers.keySet().toArray(new String[availableParsers.size()]));++ // sort it+ Collections.sort(availableParserKeys);++ // loop through the mimeTypes and add it to the properties+ boolean allParsersEnabled = true;+ int parserIdx = 0;+ Iterator availableParserIter = availableParserKeys.iterator();+ while (availableParserIter.hasNext()) {+ String mimeType = (String) availableParserIter.next();+ String parserName = (String) availableParsers.get(mimeType);+ boolean parserIsEnabled = enabledParsers.containsKey(mimeType);++ prop.put("parser_" + parserIdx + "_mime", mimeType);+ prop.put("parser_" + parserIdx + "_name", parserName);+ prop.put("parser_" + parserIdx + "_shortname", parserName.substring(parserName.lastIndexOf(".")+1));+ prop.put("parser_" + parserIdx + "_status", parserIsEnabled ? 1:0);+ allParsersEnabled &= parserIsEnabled;++ parserIdx++;+ }++ prop.put("allParserEnabled",allParsersEnabled ? 1:0);+ prop.put("parser", parserIdx);++ // return rewrite properties+ return prop;}}diff --git a/htroot/yacy/seedUpload/yacySeedUploadFile.html b/htroot/yacy/seedUpload/yacySeedUploadFile.htmlnew file mode 100644index 000000000..64ddeedb3--- /dev/null+++ b/htroot/yacy/seedUpload/yacySeedUploadFile.html@@ -0,0 +1,14 @@+<p><b>Store into filesystem:</b></p>+<p>You must configure this if you want to store the seed-list file onto the file system.</p>+<form action="SettingsAck_p.html" method="post" enctype="multipart/form-data">+<table border="0" cellspacing="5">+ <tr valign="top">+ <td>File Location:</td>+ <td><input name="seedFilePath" type="text" size="40" value="#[seedFilePath]#"></td>+ <td><i>Here you can specify the path within the filesystem where the seed-list file should be stored.</i></td>+ </tr>+ <tr>+ <td colspan="3"><input type="submit" name="seedFileSettings" value="submit"></td>+ </tr>+</table>+</form>\ No newline at end of filediff --git a/htroot/yacy/seedUpload/yacySeedUploadFtp.html b/htroot/yacy/seedUpload/yacySeedUploadFtp.htmlnew file mode 100644index 000000000..84c390e06--- /dev/null+++ b/htroot/yacy/seedUpload/yacySeedUploadFtp.html@@ -0,0 +1,34 @@+<p><b>Uploading via FTP:</b></p>+<p>This is the account for an ftp server where you can host a seed-list file.+If you set this, you will become a principal peer.+Your peer will then upload the seed-bootstrap information periodically,+but only if there had been changes to the seed-list.+</p>+<form action="SettingsAck_p.html" method="post" enctype="multipart/form-data">+<table border="0" cellspacing="5">+ <tr valign="top">+ <td>Server:</td>+ <td><input name="seedFTPServer" type="text" size="40" value="#[seedFTPServer]#"></td>+ <td><i>The host where you have an FTP account, like 'ftp.<my-host>.net'</i></td>+ </tr>+ <tr valign="top">+ <td>Path:</td>+ <td><input name="seedFTPPath" type="text" size="40" value="#[seedFTPPath]#"></td>+ <td><i>The remote path on the ftp server, like 'yacy/seed.txt'.+ Missing sub-directories are NOT created automatically.</i></td>+ </tr>+ <tr valign="top">+ <td>Username:</td>+ <td><input name="seedFTPAccount" type="text" size="40" value="#[seedFTPAccount]#"></td>+ <td><i>Your log-in at the ftp server</i></td>+ </tr>+ <tr valign="top">+ <td>Password:</td>+ <td><input name="seedFTPPassword" type="password" size="40" value="#[seedFTPPassword]#"></td>+ <td><i>The password</i></td>+ </tr>+ <tr>+ <td colspan="3"><input type="submit" name="seedFTPsettings" value="submit"></td>+ </tr>+</table>+</form>\ No newline at end of filediff --git a/htroot/yacy/seedUpload/yacySeedUploadScp.html b/htroot/yacy/seedUpload/yacySeedUploadScp.htmlnew file mode 100644index 000000000..4b726075b--- /dev/null+++ b/htroot/yacy/seedUpload/yacySeedUploadScp.html@@ -0,0 +1,31 @@+<p><b>Uploading via SCP:</b></p>+<p>This is the account for a server where you are able to login via ssh.</p>+<form action="SettingsAck_p.html" method="post" enctype="multipart/form-data">+<table border="0" cellspacing="5">+ <tr valign="top">+ <td>Server:</td>+ <td><input name="seedScpServer" type="text" size="40" value="#[seedScpServer]#"></td>+ <td><i>The host where you have an account, like 'my.host.net'</i></td>+ </tr>+ <tr valign="top">+ <td>Path:</td>+ <td><input name="seedScpPath" type="text" size="40" value="#[seedScpPath]#"></td>+ <td><i>The remote path on the server, like '~/yacy/seed.txt'.+ Missing sub-directories are NOT created automatically.</i></td>+ </tr>+ <tr valign="top">+ <td>Username:</td>+ <td><input name="seedScpAccount" type="text" size="40" value="#[seedScpAccount]#"></td>+ <td><i>Your log-in at the server</i></td>+ </tr>+ <tr valign="top">+ <td>Password:</td>+ <td><input name="seedScpPassword" type="password" size="40" value="#[seedScpPassword]#"></td>+ <td><i>The password</i></td>+ </tr>+ <tr>+ <td colspan="3"><input type="submit" name="seedScpSettings" value="submit"></td>+ </tr>+</table>+</fieldset>+</form>\ No newline at end of filediff --git a/libx/axis-ant.jar b/libx/axis-ant.jarnew file mode 100644index 000000000..be9d3fe60Binary files /dev/null and b/libx/axis-ant.jar differdiff --git a/libx/axis.jar b/libx/axis.jarnew file mode 100644index 000000000..20fa79d94Binary files /dev/null and b/libx/axis.jar differdiff --git a/libx/bzip2.jar b/libx/bzip2.jarnew file mode 100644index 000000000..94eeb9789Binary files /dev/null and b/libx/bzip2.jar differdiff --git a/libx/commons-discovery.jar b/libx/commons-discovery.jarnew file mode 100644index 000000000..eff4db19eBinary files /dev/null and b/libx/commons-discovery.jar differdiff --git a/libx/jakarta-oro-2.0.7.jar b/libx/jakarta-oro-2.0.7.jarnew file mode 100644index 000000000..46c630e46Binary files /dev/null and b/libx/jakarta-oro-2.0.7.jar differdiff --git a/libx/jaxrpc.jar b/libx/jaxrpc.jarnew file mode 100644index 000000000..6c8fd67e1Binary files /dev/null and b/libx/jaxrpc.jar differdiff --git a/libx/jmimemagic-0.0.4a.jar b/libx/jmimemagic-0.0.4a.jarnew file mode 100644index 000000000..7e8b9d00aBinary files /dev/null and b/libx/jmimemagic-0.0.4a.jar differdiff --git a/libx/jsch-0.1.19.License b/libx/jsch-0.1.19.Licensenew file mode 100644index 000000000..2cf7a501a--- /dev/null+++ b/libx/jsch-0.1.19.License@@ -0,0 +1,30 @@+JSch 0.0.* was released under the GNU LGPL license. Later, we have switched+over to a BSD-style license.++------------------------------------------------------------------------------+Copyright (c) 2002,2003,2004 Atsuhiko Yamanaka, JCraft,Inc.+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ 1. Redistributions of source code must retain the above copyright notice,+ this list of conditions and the following disclaimer.++ 2. Redistributions in binary form must reproduce the above copyright+ notice, this list of conditions and the following disclaimer in+ the documentation and/or other materials provided with the distribution.++ 3. The names of the authors may not be used to endorse or promote products+ derived from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,+INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,+OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/libx/jsch-0.1.19.jar b/libx/jsch-0.1.19.jarnew file mode 100644index 000000000..f601660efBinary files /dev/null and b/libx/jsch-0.1.19.jar differdiff --git a/libx/saaj.jar b/libx/saaj.jarnew file mode 100644index 000000000..ff67990e0Binary files /dev/null and b/libx/saaj.jar differdiff --git a/libx/tar.jar b/libx/tar.jarnew file mode 100644index 000000000..0d4def631Binary files /dev/null and b/libx/tar.jar differdiff --git a/libx/wsdl4j.jar b/libx/wsdl4j.jarnew file mode 100644index 000000000..27385d2d0Binary files /dev/null and b/libx/wsdl4j.jar differdiff --git a/libx/xerces.jar b/libx/xerces.jarnew file mode 100644index 000000000..e9fe08ad4Binary files /dev/null and b/libx/xerces.jar differdiff --git a/source/de/anomic/http/httpd.java b/source/de/anomic/http/httpd.javaindex 3d4b14eb6..df8bcaf46 100644--- a/source/de/anomic/http/httpd.java+++ b/source/de/anomic/http/httpd.java@@ -77,6 +77,7 @@ public final class httpd implements serverHandler {private static HashMap reverseMappingCache = new HashMap();private static httpdHandler proxyHandler = null; // a servlet that holds the proxy functionsprivate static httpdHandler fileHandler = null; // a servlet that holds the file serving functions+ private static httpdHandler soapHandler = null;private static serverSwitch switchboard = null;private static String virtualHost = null;@@ -254,18 +255,36 @@ public final class httpd implements serverHandler {if (prop.getProperty("HOST").equals(virtualHost)) {// pass to serverif (allowServer) {- if (serverAccountBase64MD5 == null) serverAccountBase64MD5 = switchboard.getConfig("serverAccountBase64MD5", "");- if (serverAccountBase64MD5.length() == 0) {++ /*+ * Handling SOAP Requests here ...+ */+ if (this.prop.containsKey("PATH") && this.prop.getProperty("PATH").startsWith("/soap")) {+ if (soapHandler == null) {+ try {+ soapHandler = (httpdHandler) Class.forName("de.anomic.soap.httpdSoapHandler").newInstance();+ } catch (Exception e) {+ throw new IOException("Unable to load the soap handler");+ }+ }+ soapHandler.doGet(prop, header, this.session.out);++ /*+ * Handling HTTP requests here ...+ */+ } else {+ if (serverAccountBase64MD5 == null) serverAccountBase64MD5 = switchboard.getConfig("serverAccountBase64MD5", "");+ if (serverAccountBase64MD5.length() == 0) {// no authenticate requested- if (fileHandler == null) fileHandler = new httpdFileHandler(this.switchboard);- fileHandler.doGet(prop, header, this.session.out);+ if (fileHandler == null) fileHandler = new httpdFileHandler(this.switchboard);+ fileHandler.doGet(prop, header, this.session.out);} else {String auth = (String) header.get(httpHeader.AUTHORIZATION);if (auth == null) {// authorization requested, but no authorizeation given in header. Ask for authenticate:session.out.write((httpVersion + " 401 log-in required" + serverCore.crlfString +- httpHeader.WWW_AUTHENTICATE + ": Basic realm=\"log-in\"" + serverCore.crlfString +- serverCore.crlfString).getBytes());+ httpHeader.WWW_AUTHENTICATE + ": Basic realm=\"log-in\"" + serverCore.crlfString ++ serverCore.crlfString).getBytes());return serverCore.TERMINATE_CONNECTION;} else if (serverAccountBase64MD5.equals(serverCodings.standardCoder.encodeMD5Hex(auth.trim().substring(6)))) {// we are authorized@@ -276,10 +295,11 @@ public final class httpd implements serverHandler {serverLog.logInfo("HTTPD", "Wrong log-in for account 'server' in HTTPD.GET " + prop.getProperty("PATH") + " from IP " + clientIP);session.out.write((httpVersion + " 401 log-in required" + serverCore.crlfString +httpHeader.WWW_AUTHENTICATE + ": Basic realm=\"log-in\"" + serverCore.crlfString +- serverCore.crlfString).getBytes());+ serverCore.crlfString).getBytes());return serverCore.TERMINATE_CONNECTION;}}+ }} else {// not authorized through firewall blocking (ip does not match filter)session.out.write((httpVersion + " 403 refused (IP not granted)" + serverCore.crlfString + serverCore.crlfString + "you are not allowed to connect to this server, because you are using the non-granted IP " + clientIP + ". allowed are only connections that match with the following filter: " + switchboard.getConfig("serverClient", "*") + serverCore.crlfString).getBytes());@@ -409,7 +429,24 @@ public final class httpd implements serverHandler {if (prop.getProperty("HOST").equals(virtualHost)) {// pass to serverif (allowServer) {- if (serverAccountBase64MD5 == null) serverAccountBase64MD5 = switchboard.getConfig("serverAccountBase64MD5", "");++ /*+ * Handling SOAP Requests here ...+ */+ if (this.prop.containsKey("PATH") && this.prop.getProperty("PATH").startsWith("/soap")) {+ if (soapHandler == null) {+ try {+ soapHandler = (httpdHandler) Class.forName("de.anomic.soap.httpdSoapHandler").newInstance();+ } catch (Exception e) {+ throw new IOException("Unable to load the soap handler");+ }+ }+ soapHandler.doPost(prop, header, this.session.out, this.session.in);+ /*+ * Handling normal HTTP requests here ...+ */+ } else {+ if (serverAccountBase64MD5 == null) serverAccountBase64MD5 = switchboard.getConfig("serverAccountBase64MD5", "");if (serverAccountBase64MD5.length() == 0) {// no authenticate requestedif (fileHandler == null) fileHandler = new httpdFileHandler(this.switchboard);@@ -419,8 +456,8 @@ public final class httpd implements serverHandler {if (auth == null) {// ask for authenticatesession.out.write((httpVersion + " 401 log-in required" + serverCore.crlfString +- httpHeader.WWW_AUTHENTICATE + ": Basic realm=\"log-in\"" + serverCore.crlfString +- serverCore.crlfString).getBytes());+ httpHeader.WWW_AUTHENTICATE + ": Basic realm=\"log-in\"" + serverCore.crlfString ++ serverCore.crlfString).getBytes());return serverCore.TERMINATE_CONNECTION;} else if (serverAccountBase64MD5.equals(serverCodings.standardCoder.encodeMD5Hex(auth.trim().substring(6)))) {// we are authorized@@ -430,39 +467,40 @@ public final class httpd implements serverHandler {// wrong password given: ask for authenticate againserverLog.logInfo("HTTPD", "Wrong log-in for account 'server' in HTTPD.POST " + prop.getProperty("PATH") + " from IP " + clientIP);session.out.write((httpVersion + " 401 log-in required" + serverCore.crlfString +- httpHeader.WWW_AUTHENTICATE + ": Basic realm=\"log-in\"" + serverCore.crlfString +- serverCore.crlfString).getBytes());+ httpHeader.WWW_AUTHENTICATE + ": Basic realm=\"log-in\"" + serverCore.crlfString ++ serverCore.crlfString).getBytes());return serverCore.TERMINATE_CONNECTION;}}- } else {- // not authorized through firewall blocking (ip does not match filter)- session.out.write((httpVersion + " 403 refused (IP not granted)" + serverCore.crlfString + serverCore.crlfString + "you are not allowed to connect to this server, because you are using the non-granted IP " + clientIP + ". allowed are only connections that match with the following filter: " + switchboard.getConfig("serverClient", "*") + serverCore.crlfString).getBytes());- return serverCore.TERMINATE_CONNECTION;- }+ }+ } else {+ // not authorized through firewall blocking (ip does not match filter)+ session.out.write((httpVersion + " 403 refused (IP not granted)" + serverCore.crlfString + serverCore.crlfString + "you are not allowed to connect to this server, because you are using the non-granted IP " + clientIP + ". allowed are only connections that match with the following filter: " + switchboard.getConfig("serverClient", "*") + serverCore.crlfString).getBytes());+ return serverCore.TERMINATE_CONNECTION;+ }} else {- // pass to proxy- if (allowProxy) {- if (proxyAccountBase64MD5 == null) proxyAccountBase64MD5 = switchboard.getConfig("proxyAccountBase64MD5", "");- if ((proxyAccountBase64MD5.length() == 0) ||- (proxyAccountBase64MD5.equals(serverCodings.standardCoder.encodeMD5Hex(((String) header.get(httpHeader.PROXY_AUTHORIZATION, "xxxxxx")).trim().substring(6))))) {- // we are authorized or no authenticate requested- if (proxyHandler != null) proxyHandler.doPost(prop, header, this.session.out, this.session.in);- } else {- // ask for authenticate- session.out.write((httpVersion + " 407 Proxy Authentication Required" + serverCore.crlfString +- httpHeader.PROXY_AUTHENTICATE + ": Basic realm=\"log-in\"" + serverCore.crlfString +- serverCore.crlfString).getBytes());- return serverCore.TERMINATE_CONNECTION;- }- } else {- // not authorized through firewall blocking (ip does not match filter)- session.out.write((httpVersion + " 403 refused (IP not granted)" + serverCore.crlfString + serverCore.crlfString + "you are not allowed to connect to this proxy, because you are using the non-granted IP " + clientIP + ". allowed are only connections that match with the following filter: " + switchboard.getConfig("proxyClient", "*") + serverCore.crlfString).getBytes());- return serverCore.TERMINATE_CONNECTION;- }- }- //return serverCore.RESUME_CONNECTION;- return (persistent) ? serverCore.RESUME_CONNECTION : serverCore.TERMINATE_CONNECTION;+ // pass to proxy+ if (allowProxy) {+ if (proxyAccountBase64MD5 == null) proxyAccountBase64MD5 = switchboard.getConfig("proxyAccountBase64MD5", "");+ if ((proxyAccountBase64MD5.length() == 0) ||+ (proxyAccountBase64MD5.equals(serverCodings.standardCoder.encodeMD5Hex(((String) header.get(httpHeader.PROXY_AUTHORIZATION, "xxxxxx")).trim().substring(6))))) {+ // we are authorized or no authenticate requested+ if (proxyHandler != null) proxyHandler.doPost(prop, header, this.session.out, this.session.in);+ } else {+ // ask for authenticate+ session.out.write((httpVersion + " 407 Proxy Authentication Required" + serverCore.crlfString ++ httpHeader.PROXY_AUTHENTICATE + ": Basic realm=\"log-in\"" + serverCore.crlfString ++ serverCore.crlfString).getBytes());+ return serverCore.TERMINATE_CONNECTION;+ }+ } else {+ // not authorized through firewall blocking (ip does not match filter)+ session.out.write((httpVersion + " 403 refused (IP not granted)" + serverCore.crlfString + serverCore.crlfString + "you are not allowed to connect to this proxy, because you are using the non-granted IP " + clientIP + ". allowed are only connections that match with the following filter: " + switchboard.getConfig("proxyClient", "*") + serverCore.crlfString).getBytes());+ return serverCore.TERMINATE_CONNECTION;+ }+ }+ //return serverCore.RESUME_CONNECTION;+ return (persistent) ? serverCore.RESUME_CONNECTION : serverCore.TERMINATE_CONNECTION;}@@ -863,14 +901,14 @@ permissionreturn new httpd(this.switchboard, this.fileHandler, this.proxyHandler);}- public static boolean isTextMime(String mime, Set whitelist) {- if (whitelist.contains(mime)) return true;- // some mime-types are given as "text/html; charset=...", so look for ";"- if (mime.length() == 0) return false;- int pos = mime.indexOf(';');- if (pos < 0) return false;- return whitelist.contains(mime.substring(0, pos));- }+// public static boolean isTextMime(String mime, Set whitelist) {+// if (whitelist.contains(mime)) return true;+// // some mime-types are given as "text/html; charset=...", so look for ";"+// if (mime.length() == 0) return false;+// int pos = mime.indexOf(';');+// if (pos < 0) return false;+// return whitelist.contains(mime.substring(0, pos));+// }}/*diff --git a/source/de/anomic/http/httpdAbstractHandler.java b/source/de/anomic/http/httpdAbstractHandler.javaindex 3afc25f7d..21bfcc2c4 100644--- a/source/de/anomic/http/httpdAbstractHandler.java+++ b/source/de/anomic/http/httpdAbstractHandler.java@@ -53,7 +53,7 @@ package de.anomic.http;import java.text.SimpleDateFormat;-abstract class httpdAbstractHandler {+public abstract class httpdAbstractHandler {// static toolsdiff --git a/source/de/anomic/http/httpdProxyHandler.java b/source/de/anomic/http/httpdProxyHandler.javaindex 6ab4f71ee..b9928ffd2 100644--- a/source/de/anomic/http/httpdProxyHandler.java+++ b/source/de/anomic/http/httpdProxyHandler.java@@ -85,6 +85,7 @@ import de.anomic.htmlFilter.htmlFilterOutputStream;import de.anomic.htmlFilter.htmlFilterTransformer;import de.anomic.plasma.plasmaCrawlLURL;import de.anomic.plasma.plasmaHTCache;+import de.anomic.plasma.plasmaParser;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverCore;import de.anomic.server.serverFileUtils;@@ -448,8 +449,8 @@ public final class httpdProxyHandler extends httpdAbstractHandler implements htt// make a transformerif ((!(transformer.isIdentityTransformer())) &&- ((ext == null) || (!(switchboard.extensionBlack.contains(ext)))) &&- ((cachedResponseHeader == null) || (httpd.isTextMime(cachedResponseHeader.mime(), switchboard.mimeWhite)))) {+ ((ext == null) || (!(plasmaParser.mediaExtContains(ext)))) &&+ ((cachedResponseHeader == null) || (plasmaParser.realtimeParsableMimeTypesContains(cachedResponseHeader.mime())))) {hfos = new htmlFilterOutputStream(respond, null, transformer, (ext.length() == 0));} else {hfos = respond;@@ -507,8 +508,8 @@ public final class httpdProxyHandler extends httpdAbstractHandler implements httcacheEntry = cacheManager.newEntry(requestDate, 0, url, requestHeader, res.status, res.responseHeader, null, switchboard.defaultProxyProfile);// handle file types- if (((ext == null) || (!(switchboard.extensionBlack.contains(ext)))) &&- (httpd.isTextMime(res.responseHeader.mime(), switchboard.mimeWhite))) {+ if (((ext == null) || (!(plasmaParser.mediaExtContains(ext)))) &&+ (plasmaParser.realtimeParsableMimeTypesContains(res.responseHeader.mime()))) {// this is a file that is a possible candidate for parsing by the indexerif (transformer.isIdentityTransformer()) {log.logDebug("create passthrough (parse candidate) for url " + url);diff --git a/source/de/anomic/plasma/parser/AbstractParser.java b/source/de/anomic/plasma/parser/AbstractParser.javaindex fe702d1eb..2f5384b52 100644--- a/source/de/anomic/plasma/parser/AbstractParser.java+++ b/source/de/anomic/plasma/parser/AbstractParser.java@@ -62,11 +62,17 @@ import de.anomic.plasma.plasmaParserDocument;*/public abstract class AbstractParser implements Parser{+ /**+ * a list of library names that are needed by this parser+ */+ protected String[] libxDependencies = null;+/*** The Constructor of this class.*/- public AbstractParser() {+ public AbstractParser(String[] libxDependencies) {super();+ this.libxDependencies = libxDependencies;}/**@@ -122,4 +128,12 @@ public abstract class AbstractParser implements Parser{public abstract plasmaParserDocument parse(URL location, String mimeType,InputStream source) throws ParserException;+ /**+ * @return Returns a list of library names that are needed by this parser+ * @see de.anomic.plasma.parser.Parser#getLibxDependences()+ */+ public String[] getLibxDependences() {+ return this.libxDependencies;+ }+}diff --git a/source/de/anomic/plasma/parser/Parser.java b/source/de/anomic/plasma/parser/Parser.javaindex a714735f1..f2b334ca2 100644--- a/source/de/anomic/plasma/parser/Parser.java+++ b/source/de/anomic/plasma/parser/Parser.java@@ -110,5 +110,9 @@ public interface Parser {*/public void reset();+ /**+ * @return Returns a list of library names that are needed by this parser+ */+ public String[] getLibxDependences();}diff --git a/source/de/anomic/plasma/parser/bzip/build.xml b/source/de/anomic/plasma/parser/bzip/build.xmlnew file mode 100644index 000000000..da8adf223--- /dev/null+++ b/source/de/anomic/plasma/parser/bzip/build.xml@@ -0,0 +1,45 @@+<?xml version="1.0"?>+<project name="YACY - bzipParser" default="dist">+ <description>+ A class to parse bzip files+ </description>++ <property name="parserShortName" value="bzip"/>+ <property name="parserVersion" value="0.1"/>++ <property name="parserLongName" value="yacyContentParser_${parserShortName}"/>+ <property name="parserArchive" location="${release}/${parserLongName}_${parserVersion}.tgz"/>++ <target name="compile">+ <echo message="Compiling ${parserLongName} Version ${parserVersion} ..."/>+ <javac srcdir="${src}/de/anomic/plasma/parser/${parserShortName}" destdir="${build}" source="${javacSource}" target="${javacTarget}">+ <classpath>+ <pathelement location="${build}" />+ <pathelement location="${libx}/bzip2.jar" />+ </classpath>+ </javac>+ </target>+++ <target name="zip" depends="compile">+ <echo message="Compressing ${parserLongName} Version ${parserVersion} ..."/>+ <tar destfile="${parserArchive}" compression="gzip">+ <tarfileset dir="${libx}"+ includes="bzip2.jar"+ prefix="libx/"+ dirmode="755" mode="644"/>+ <tarfileset dir="${src}/de/anomic/plasma/parser/${parserShortName}"+ prefix="source/de/anomic/plasma/parser/${parserShortName}"+ dirmode="755" mode="644"/>+ <tarfileset dir="${build}/de/anomic/plasma/parser/${parserShortName}"+ prefix="classes/de/anomic/plasma/parser/${parserShortName}"+ dirmode="755" mode="644"/>+ </tar>+ </target>+++ <target name="dist" depends="compile,zip" description="Compile and zip the parser"/>+++</project>+diff --git a/source/de/anomic/plasma/parser/bzip/bzipParser.java b/source/de/anomic/plasma/parser/bzip/bzipParser.javanew file mode 100644index 000000000..e2db67863--- /dev/null+++ b/source/de/anomic/plasma/parser/bzip/bzipParser.java@@ -0,0 +1,137 @@+//bzipParser.java+//------------------------+//part of YaCy+//(C) by Michael Peter Christen; [email protected]+//first published on http://www.anomic.de+//Frankfurt, Germany, 2005+//+//this file is contributed by Martin Thelian+//last major change: 16.05.2005+//+//This program is free software; you can redistribute it and/or modify+//it under the terms of the GNU General Public License as published by+//the Free Software Foundation; either version 2 of the License, or+//(at your option) any later version.+//+//This program is distributed in the hope that it will be useful,+//but WITHOUT ANY WARRANTY; without even the implied warranty of+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+//GNU General Public License for more details.+//+//You should have received a copy of the GNU General Public License+//along with this program; if not, write to the Free Software+//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+//+//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.plasma.parser.bzip;++import java.io.File;+import java.io.FileOutputStream;+import java.io.InputStream;+import java.net.URL;+import java.util.Hashtable;++import org.apache.tools.bzip2.CBZip2InputStream;++import de.anomic.plasma.plasmaParser;+import de.anomic.plasma.plasmaParserDocument;+import de.anomic.plasma.parser.AbstractParser;+import de.anomic.plasma.parser.Parser;+import de.anomic.plasma.parser.ParserException;++public class bzipParser extends AbstractParser implements Parser {++ /**+ * a list of mime types that are supported by this parser class+ * @see #getSupportedMimeTypes()+ */+ public static final Hashtable SUPPORTED_MIME_TYPES = new Hashtable();+ static {+ SUPPORTED_MIME_TYPES.put("application/x-bzip2","bz2,tbz,tbz2");+ }++ /**+ * a list of library names that are needed by this parser+ * @see Parser#getLibxDependences()+ */+ private static final String[] LIBX_DEPENDENCIES = new String[] {+ "bzip2.jar"+ };++ public bzipParser() {+ super(LIBX_DEPENDENCIES);+ }++ public Hashtable getSupportedMimeTypes() {+ return SUPPORTED_MIME_TYPES;+ }++ public plasmaParserDocument parse(URL location, String mimeType, InputStream source) throws ParserException {++ File tempFile = null;+ try {+ /*+ * First we have to consume the first two char from the stream. Otherwise+ * the bzip decompression will fail with a nullpointerException!+ */+ int b = source.read();+ if (b != 'B') {+ throw new Exception("Invalid bz2 content.");+ }+ b = source.read();+ if (b != 'Z') {+ throw new Exception("Invalid bz2 content.");+ }++ int read = 0;+ byte[] data = new byte[1024];++ CBZip2InputStream zippedContent = new CBZip2InputStream(source);++ tempFile = File.createTempFile("bunzip","tmp");+ tempFile.deleteOnExit();++ // creating a temp file to store the uncompressed data+ FileOutputStream out = new FileOutputStream(tempFile);++ // reading gzip file and store it uncompressed+ while((read = zippedContent.read(data, 0, 1024)) != -1)+ {+ out.write(data, 0, read);+ }+ zippedContent.close();+ out.close();++ // creating a new parser class to parse the unzipped content+ plasmaParser theParser = new plasmaParser();+ return theParser.parseSource(location,null,tempFile);+ } catch (Exception e) {+ throw new ParserException("Unable to parse the gzip content. " + e.getMessage());+ } finally {+ if (tempFile != null) tempFile.delete();+ }+ }++ public void reset() {+ // Nothing todo here at the moment++ }+}diff --git a/source/de/anomic/plasma/parser/doc/build.xml b/source/de/anomic/plasma/parser/doc/build.xmlindex 93b29dbfe..d9dcae2b4 100644--- a/source/de/anomic/plasma/parser/doc/build.xml+++ b/source/de/anomic/plasma/parser/doc/build.xml@@ -7,7 +7,7 @@<property name="parserShortName" value="doc"/><property name="parserVersion" value="0.1"/>- <property name="parserLongName" value="${parserShortName}Parser"/>+ <property name="parserLongName" value="yacyContentParser_${parserShortName}"/><property name="parserArchive" location="${release}/${parserLongName}_${parserVersion}.tgz"/><target name="compile">diff --git a/source/de/anomic/plasma/parser/doc/docParser.java b/source/de/anomic/plasma/parser/doc/docParser.javaindex b1da44659..b71f62eb7 100644--- a/source/de/anomic/plasma/parser/doc/docParser.java+++ b/source/de/anomic/plasma/parser/doc/docParser.java@@ -65,8 +65,16 @@ implements Parser {public static final Hashtable SUPPORTED_MIME_TYPES = new Hashtable();static { SUPPORTED_MIME_TYPES.put("application/msword","doc"); }+ /**+ * a list of library names that are needed by this parser+ * @see Parser#getLibxDependences()+ */+ private static final String[] LIBX_DEPENDENCIES = new String[] {+ "tm-extractors-0.4.jar"+ };+public docParser() {- super();+ super(LIBX_DEPENDENCIES);}public plasmaParserDocument parse(URL location, String mimeType,diff --git a/source/de/anomic/plasma/parser/gzip/build.xml b/source/de/anomic/plasma/parser/gzip/build.xmlnew file mode 100644index 000000000..293aabd8d--- /dev/null+++ b/source/de/anomic/plasma/parser/gzip/build.xml@@ -0,0 +1,40 @@+<?xml version="1.0"?>+<project name="YACY - gzipParser" default="dist">+ <description>+ A class to parse gzip files+ </description>++ <property name="parserShortName" value="gzip"/>+ <property name="parserVersion" value="0.1"/>++ <property name="parserLongName" value="yacyContentParser_${parserShortName}"/>+ <property name="parserArchive" location="${release}/${parserLongName}_${parserVersion}.tgz"/>++ <target name="compile">+ <echo message="Compiling ${parserLongName} Version ${parserVersion} ..."/>+ <javac srcdir="${src}/de/anomic/plasma/parser/${parserShortName}" destdir="${build}" source="${javacSource}" target="${javacTarget}">+ <classpath>+ <pathelement location="${build}" />+ </classpath>+ </javac>+ </target>+++ <target name="zip" depends="compile">+ <echo message="Compressing ${parserLongName} Version ${parserVersion} ..."/>+ <tar destfile="${parserArchive}" compression="gzip">+ <tarfileset dir="${src}/de/anomic/plasma/parser/${parserShortName}"+ prefix="source/de/anomic/plasma/parser/${parserShortName}"+ dirmode="755" mode="644"/>+ <tarfileset dir="${build}/de/anomic/plasma/parser/${parserShortName}"+ prefix="classes/de/anomic/plasma/parser/${parserShortName}"+ dirmode="755" mode="644"/>+ </tar>+ </target>+++ <target name="dist" depends="compile,zip" description="Compile and zip the parser"/>+++</project>+diff --git a/source/de/anomic/plasma/parser/gzip/gzipParser.java b/source/de/anomic/plasma/parser/gzip/gzipParser.javanew file mode 100644index 000000000..f33993f1f--- /dev/null+++ b/source/de/anomic/plasma/parser/gzip/gzipParser.java@@ -0,0 +1,121 @@+//gzipParser.java+//------------------------+//part of YaCy+//(C) by Michael Peter Christen; [email protected]+//first published on http://www.anomic.de+//Frankfurt, Germany, 2005+//+//this file is contributed by Martin Thelian+//last major change: 24.04.2005+//+//This program is free software; you can redistribute it and/or modify+//it under the terms of the GNU General Public License as published by+//the Free Software Foundation; either version 2 of the License, or+//(at your option) any later version.+//+//This program is distributed in the hope that it will be useful,+//but WITHOUT ANY WARRANTY; without even the implied warranty of+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+//GNU General Public License for more details.+//+//You should have received a copy of the GNU General Public License+//along with this program; if not, write to the Free Software+//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+//+//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.plasma.parser.gzip;++import java.io.File;+import java.io.FileOutputStream;+import java.io.InputStream;+import java.net.URL;+import java.util.Hashtable;+import java.util.zip.GZIPInputStream;++import de.anomic.plasma.plasmaParser;+import de.anomic.plasma.plasmaParserDocument;+import de.anomic.plasma.parser.AbstractParser;+import de.anomic.plasma.parser.Parser;+import de.anomic.plasma.parser.ParserException;++public class gzipParser extends AbstractParser implements Parser {++ /**+ * a list of mime types that are supported by this parser class+ * @see #getSupportedMimeTypes()+ */+ public static final Hashtable SUPPORTED_MIME_TYPES = new Hashtable();+ static {+ SUPPORTED_MIME_TYPES.put("application/x-gzip","gz,tgz");+ SUPPORTED_MIME_TYPES.put("application/gzip","gz,tgz");+ }++ /**+ * a list of library names that are needed by this parser+ * @see Parser#getLibxDependences()+ */+ private static final String[] LIBX_DEPENDENCIES = new String[] {};++ public gzipParser() {+ super(LIBX_DEPENDENCIES);+ }++ public Hashtable getSupportedMimeTypes() {+ return SUPPORTED_MIME_TYPES;+ }++ public plasmaParserDocument parse(URL location, String mimeType, InputStream source) throws ParserException {++ File tempFile = null;+ try {+ int read = 0;+ byte[] data = new byte[1024];++ GZIPInputStream zippedContent = new GZIPInputStream(source);++ tempFile = File.createTempFile("gunzip","tmp");+ tempFile.deleteOnExit();++ // creating a temp file to store the uncompressed data+ FileOutputStream out = new FileOutputStream(tempFile);++ // reading gzip file and store it uncompressed+ while((read = zippedContent.read(data, 0, 1024)) != -1) {+ out.write(data, 0, read);+ }+ zippedContent.close();+ out.close();++ // creating a new parser class to parse the unzipped content+ plasmaParser theParser = new plasmaParser();+ return theParser.parseSource(location,null,tempFile);+ } catch (Exception e) {+ throw new ParserException("Unable to parse the gzip content. " + e.getMessage());+ } finally {+ if (tempFile != null) tempFile.delete();+ }+ }++ public void reset() {+ // Nothing todo here at the moment++ }+}diff --git a/source/de/anomic/plasma/parser/mimeType/build.xml b/source/de/anomic/plasma/parser/mimeType/build.xmlnew file mode 100644index 000000000..b74f1c02c--- /dev/null+++ b/source/de/anomic/plasma/parser/mimeType/build.xml@@ -0,0 +1,50 @@+<?xml version="1.0"?>+<project name="YACY - mimeTypeParser" default="dist">+ <description>+ A class to determine the mimetype of unknown documents+ </description>++ <property name="parserShortName" value="mimeType"/>+ <property name="parserVersion" value="0.1"/>++ <property name="parserLongName" value="yacyContentParser_${parserShortName}"/>+ <property name="parserArchive" location="${release}/${parserLongName}_${parserVersion}.tgz"/>++ <target name="compile">+ <echo message="Compiling ${parserLongName} Version ${parserVersion} ..."/>+ <javac srcdir="${src}/de/anomic/plasma/parser/${parserShortName}" destdir="${build}" source="${javacSource}" target="${javacTarget}">+ <classpath>+ <pathelement location="${build}" />++ <!-- main lib needed to parse doc files -->+ <pathelement location="${libx}/jmimemagic-0.0.4a.jar" />+ <pathelement location="${libx}/jakarta-oro-2.0.7.jar" />+ <pathelement location="${libx}/log4j-1.2.9.jar" />+ <pathelement location="${libx}/xerces.jar"/>+ </classpath>+ </javac>+ </target>+++ <target name="zip" depends="compile">+ <echo message="Compressing ${parserLongName} Version ${parserVersion} ..."/>+ <tar destfile="${parserArchive}" compression="gzip">+ <tarfileset dir="${libx}"+ includes="jmimemagic-0.0.4a.jar,jakarta-oro-2.0.7.jar,log4j-1.2.9.jar,xerces.jar"+ prefix="libx/"+ dirmode="755" mode="644"/>+ <tarfileset dir="${src}/de/anomic/plasma/parser/${parserShortName}"+ prefix="source/de/anomic/plasma/parser/${parserShortName}"+ dirmode="755" mode="644"/>+ <tarfileset dir="${build}/de/anomic/plasma/parser/${parserShortName}"+ prefix="classes/de/anomic/plasma/parser/${parserShortName}"+ dirmode="755" mode="644"/>+ </tar>+ </target>+++ <target name="dist" depends="compile,zip" description="Compile and zip the parser"/>+++</project>+diff --git a/source/de/anomic/plasma/parser/mimeType/mimeTypeParser.java b/source/de/anomic/plasma/parser/mimeType/mimeTypeParser.javanew file mode 100644index 000000000..cc2d36c10--- /dev/null+++ b/source/de/anomic/plasma/parser/mimeType/mimeTypeParser.java@@ -0,0 +1,149 @@+//mimeTypeParser.java+//------------------------+//part of YaCy+//(C) by Michael Peter Christen; [email protected]+//first published on http://www.anomic.de+//Frankfurt, Germany, 2005+//+//this file is contributed by Martin Thelian+//last major change: 16.05.2005+//+//This program is free software; you can redistribute it and/or modify+//it under the terms of the GNU General Public License as published by+//the Free Software Foundation; either version 2 of the License, or+//(at your option) any later version.+//+//This program is distributed in the hope that it will be useful,+//but WITHOUT ANY WARRANTY; without even the implied warranty of+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+//GNU General Public License for more details.+//+//You should have received a copy of the GNU General Public License+//along with this program; if not, write to the Free Software+//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+//+//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.plasma.parser.mimeType;++import java.io.File;+import java.io.InputStream;+import java.net.URL;+import java.util.Collection;+import java.util.Hashtable;++import org.apache.log4j.Level;+import org.apache.log4j.Logger;++import net.sf.jmimemagic.Magic;+import net.sf.jmimemagic.MagicMatch;++import de.anomic.plasma.plasmaParser;+import de.anomic.plasma.plasmaParserDocument;+import de.anomic.plasma.parser.AbstractParser;+import de.anomic.plasma.parser.Parser;+import de.anomic.plasma.parser.ParserException;+import de.anomic.server.serverFileUtils;++public class mimeTypeParser+extends AbstractParser+implements Parser {++ /**+ * a list of mime types that are supported by this parser class+ * @see #getSupportedMimeTypes()+ */+ public static final Hashtable SUPPORTED_MIME_TYPES = new Hashtable();+ static {+ SUPPORTED_MIME_TYPES.put("text/xml","xml");+ SUPPORTED_MIME_TYPES.put("application/xml","xml");+ SUPPORTED_MIME_TYPES.put("application/octet-stream","");+ }++ /**+ * a list of library names that are needed by this parser+ * @see Parser#getLibxDependences()+ */+ private static final String[] LIBX_DEPENDENCIES = new String[] {+ "jmimemagic-0.0.4a.jar",+ "jakarta-oro-2.0.7.jar",+ "log4j-1.2.9.jar",+ "xerces.jar"+ };++ public mimeTypeParser() {+ super(LIBX_DEPENDENCIES);+ }++ public plasmaParserDocument parse(URL location, String mimeType, File sourceFile) throws ParserException {++ // determining the mime type of the file ...+ try {+ // deactivating the logging for jMimeMagic+ Logger theLogger = Logger.getLogger("net.sf.jmimemagic");+ theLogger.setLevel(Level.OFF);++ Magic theMagic = new Magic();+ MagicMatch match = theMagic.getMagicMatch(sourceFile);+++ // if a match was found we can return the new mimeType+ if (match!=null) {+ Collection subMatches = match.getSubMatches();+ if ((subMatches != null) && (!subMatches.isEmpty())) {+ mimeType = ((MagicMatch) subMatches.iterator().next()).getMimeType();+ } else {+ mimeType = match.getMimeType();+ }++ plasmaParser theParser = new plasmaParser();+ return theParser.parseSource(location,mimeType,sourceFile);+ }+ return null;++ } catch (Exception e) {+ return null;+ }+ }++ public plasmaParserDocument parse(URL location, String mimeType,+ InputStream source) throws ParserException {+ File dstFile = null;+ try {+ dstFile = File.createTempFile("mimeTypeParser",".tmp");+ serverFileUtils.copy(source,dstFile);+ return parse(location,mimeType,dstFile);+ } catch (Exception e) {+ return null;+ } finally {+ if (dstFile != null) {dstFile.delete();}+ }++ }++ public java.util.Hashtable getSupportedMimeTypes() {+ return mimeTypeParser.SUPPORTED_MIME_TYPES;+ }++ public void reset() {+ // Nothing todo here at the moment+ }++}diff --git a/source/de/anomic/plasma/parser/pdf/build.xml b/source/de/anomic/plasma/parser/pdf/build.xmlindex bbcac62a7..be0c80850 100644--- a/source/de/anomic/plasma/parser/pdf/build.xml+++ b/source/de/anomic/plasma/parser/pdf/build.xml@@ -7,7 +7,7 @@<property name="parserShortName" value="pdf"/><property name="parserVersion" value="0.1"/>- <property name="parserLongName" value="${parserShortName}Parser"/>+ <property name="parserLongName" value="yacyContentParser_${parserShortName}"/><property name="parserArchive" location="${release}/${parserLongName}_${parserVersion}.tgz"/><target name="compile">diff --git a/source/de/anomic/plasma/parser/pdf/pdfParser.java b/source/de/anomic/plasma/parser/pdf/pdfParser.javaindex db3118a42..40be8e264 100644--- a/source/de/anomic/plasma/parser/pdf/pdfParser.java+++ b/source/de/anomic/plasma/parser/pdf/pdfParser.java@@ -47,10 +47,10 @@ import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.io.OutputStreamWriter;import java.net.URL;-import java.util.Arrays;-import java.util.HashSet;import java.util.Hashtable;+import org.apache.log4j.Level;+import org.apache.log4j.Logger;import org.pdfbox.pdfparser.PDFParser;import org.pdfbox.pdmodel.PDDocument;import org.pdfbox.pdmodel.PDDocumentInformation;@@ -61,8 +61,7 @@ import de.anomic.plasma.parser.AbstractParser;import de.anomic.plasma.parser.Parser;import de.anomic.plasma.parser.ParserException;-public class pdfParser extends AbstractParser implements Parser-{+public class pdfParser extends AbstractParser implements Parser {/*** a list of mime types that are supported by this parser class@@ -72,15 +71,16 @@ public class pdfParser extends AbstractParser implements Parserstatic { SUPPORTED_MIME_TYPES.put("application/pdf","pdf"); }/**- * a list of file extensions that are supported by this parser class- * @see #getSupportedMimeTypes()+ * a list of library names that are needed by this parser+ * @see Parser#getLibxDependences()*/- public static final HashSet SUPPORTED_FILE_EXT = new HashSet(Arrays.asList(new String[] {- new String("pdf")- }));+ private static final String[] LIBX_DEPENDENCIES = new String[] {+ "PDFBox-0.7.1.jar",+ "log4j-1.2.9.jar"+ };- public pdfParser() {- super();+ public pdfParser() {+ super(LIBX_DEPENDENCIES);}public Hashtable getSupportedMimeTypes() {@@ -90,6 +90,11 @@ public class pdfParser extends AbstractParser implements Parserpublic plasmaParserDocument parse(URL location, String mimeType, InputStream source) throws ParserException {try {++ // deactivating the logging for jMimeMagic+ Logger theLogger = Logger.getLogger("org.pdfbox");+ theLogger.setLevel(Level.INFO);+String docTitle = null, docSubject = null, docAuthor = null, docKeyWords = null;PDFParser parser = new PDFParser(source);@@ -148,8 +153,4 @@ public class pdfParser extends AbstractParser implements Parser}- public HashSet getSupportedFileExtensions() {- return SUPPORTED_FILE_EXT;- }-}diff --git a/source/de/anomic/plasma/parser/rss/build.xml b/source/de/anomic/plasma/parser/rss/build.xmlindex 360564ad8..e6c5d0cf2 100644--- a/source/de/anomic/plasma/parser/rss/build.xml+++ b/source/de/anomic/plasma/parser/rss/build.xml@@ -8,7 +8,7 @@<property name="parserShortName" value="rss"/><property name="parserVersion" value="0.1"/>- <property name="parserLongName" value="${parserShortName}Parser"/>+ <property name="parserLongName" value="yacyContentParser_${parserShortName}"/><property name="parserArchive" location="${release}/${parserLongName}_${parserVersion}.tgz"/><target name="compile">diff --git a/source/de/anomic/plasma/parser/rss/rssParser.java b/source/de/anomic/plasma/parser/rss/rssParser.javaindex 44b4b7c1c..d2e01160c 100644--- a/source/de/anomic/plasma/parser/rss/rssParser.java+++ b/source/de/anomic/plasma/parser/rss/rssParser.java@@ -1,3 +1,46 @@+//rssParser.java+//------------------------+//part of YaCy+//(C) by Michael Peter Christen; [email protected]+//first published on http://www.anomic.de+//Frankfurt, Germany, 2005+//+//this file is contributed by Martin Thelian+//last major change: 16.05.2005+//+//This program is free software; you can redistribute it and/or modify+//it under the terms of the GNU General Public License as published by+//the Free Software Foundation; either version 2 of the License, or+//(at your option) any later version.+//+//This program is distributed in the hope that it will be useful,+//but WITHOUT ANY WARRANTY; without even the implied warranty of+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+//GNU General Public License for more details.+//+//You should have received a copy of the GNU General Public License+//along with this program; if not, write to the Free Software+//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+//+//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.plasma.parser.rss;import java.io.ByteArrayInputStream;@@ -41,21 +84,19 @@ public class rssParser extends AbstractParser implements Parser {SUPPORTED_MIME_TYPES.put("application/rss+xml","xml,rss,rdf");SUPPORTED_MIME_TYPES.put("application/atom+xml","xml,atom");}--+/**- * a list of file extensions that are supported by this parser class- * @see #getSupportedMimeTypes()+ * a list of library names that are needed by this parser+ * @see Parser#getLibxDependences()*/- public static final HashSet SUPPORTED_FILE_EXT = new HashSet(Arrays.asList(new String[] {- new String("xml"),- new String("rss"),- new String("rdf"),- new String("atom")- }));+ private static final String[] LIBX_DEPENDENCIES = new String[] {+ "informa-0.6.0.jar",+ "commons-logging.jar",+ "jdom.jar"+ };public rssParser() {- super();+ super(LIBX_DEPENDENCIES);}public plasmaParserDocument parse(URL location, String mimeType,@@ -172,9 +213,4 @@ public class rssParser extends AbstractParser implements Parser {}- public HashSet getSupportedFileExtensions() {- // TODO Auto-generated method stub- return SUPPORTED_FILE_EXT;- }-}diff --git a/source/de/anomic/plasma/parser/rtf/build.xml b/source/de/anomic/plasma/parser/rtf/build.xmlnew file mode 100644index 000000000..3d01a57f7--- /dev/null+++ b/source/de/anomic/plasma/parser/rtf/build.xml@@ -0,0 +1,40 @@+<?xml version="1.0"?>+<project name="YACY - rtfParser" default="dist">+ <description>+ A class to parse doc documents (application/msword)+ </description>++ <property name="parserShortName" value="rtf"/>+ <property name="parserVersion" value="0.1"/>++ <property name="parserLongName" value="yacyContentParser_${parserShortName}"/>+ <property name="parserArchive" location="${release}/${parserLongName}_${parserVersion}.tgz"/>++ <target name="compile">+ <echo message="Compiling ${parserLongName} Version ${parserVersion} ..."/>+ <javac srcdir="${src}/de/anomic/plasma/parser/${parserShortName}" destdir="${build}" source="${javacSource}" target="${javacTarget}">+ <classpath>+ <pathelement location="${build}" />+ </classpath>+ </javac>+ </target>+++ <target name="zip" depends="compile">+ <echo message="Compressing ${parserLongName} Version ${parserVersion} ..."/>+ <tar destfile="${parserArchive}" compression="gzip">+ <tarfileset dir="${src}/de/anomic/plasma/parser/${parserShortName}"+ prefix="source/de/anomic/plasma/parser/${parserShortName}"+ dirmode="755" mode="644"/>+ <tarfileset dir="${build}/de/anomic/plasma/parser/${parserShortName}"+ prefix="classes/de/anomic/plasma/parser/${parserShortName}"+ dirmode="755" mode="644"/>+ </tar>+ </target>+++ <target name="dist" depends="compile,zip" description="Compile and zip the parser"/>+++</project>+diff --git a/source/de/anomic/plasma/parser/rtf/rtfParser.java b/source/de/anomic/plasma/parser/rtf/rtfParser.javanew file mode 100644index 000000000..bdde6de98--- /dev/null+++ b/source/de/anomic/plasma/parser/rtf/rtfParser.java@@ -0,0 +1,121 @@+//rtfParser.java+//------------------------+//part of YaCy+//(C) by Michael Peter Christen; [email protected]+//first published on http://www.anomic.de+//Frankfurt, Germany, 2005+//+//this file is contributed by Martin Thelian+//last major change: 16.05.2005+//+//This program is free software; you can redistribute it and/or modify+//it under the terms of the GNU General Public License as published by+//the Free Software Foundation; either version 2 of the License, or+//(at your option) any later version.+//+//This program is distributed in the hope that it will be useful,+//but WITHOUT ANY WARRANTY; without even the implied warranty of+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+//GNU General Public License for more details.+//+//You should have received a copy of the GNU General Public License+//along with this program; if not, write to the Free Software+//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+//+//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.plasma.parser.rtf;++import java.io.InputStream;+import java.net.URL;+import java.util.Hashtable;++import javax.swing.text.DefaultStyledDocument;+import javax.swing.text.rtf.RTFEditorKit;++import de.anomic.plasma.plasmaParserDocument;+import de.anomic.plasma.parser.AbstractParser;+import de.anomic.plasma.parser.Parser;+import de.anomic.plasma.parser.ParserException;++public class rtfParser+extends AbstractParser+implements Parser {++ /**+ * a list of mime types that are supported by this parser class+ * @see #getSupportedMimeTypes()+ */+ public static final Hashtable SUPPORTED_MIME_TYPES = new Hashtable();+ static {+ SUPPORTED_MIME_TYPES.put("application/rtf","rtf");+ SUPPORTED_MIME_TYPES.put("text/rtf","rtf");+ }++ /**+ * a list of library names that are needed by this parser+ * @see Parser#getLibxDependences()+ */+ private static final String[] LIBX_DEPENDENCIES = new String[] {};++ public rtfParser() {+ super(LIBX_DEPENDENCIES);+ }++ public plasmaParserDocument parse(URL location, String mimeType,+ InputStream source) throws ParserException {+++ try {+ DefaultStyledDocument doc = new DefaultStyledDocument();++ RTFEditorKit theRtfEditorKit = new RTFEditorKit();+ theRtfEditorKit.read(source, doc, 0);++ String bodyText = doc.getText(0, doc.getLength());++ plasmaParserDocument theDoc = new plasmaParserDocument(+ location,+ mimeType,+ null,+ null,+ null,+ null,+ null,+ bodyText.getBytes(),+ null,+ null);++ return theDoc;+ }+ catch (Exception e) {+ throw new ParserException("Unable to parse the doc content. " + e.getMessage());+ }+ }++ public java.util.Hashtable getSupportedMimeTypes() {+ return rtfParser.SUPPORTED_MIME_TYPES;+ }++ public void reset() {+ // Nothing todo here at the moment+ }++}diff --git a/source/de/anomic/plasma/parser/tar/build.xml b/source/de/anomic/plasma/parser/tar/build.xmlnew file mode 100644index 000000000..c6722711e--- /dev/null+++ b/source/de/anomic/plasma/parser/tar/build.xml@@ -0,0 +1,46 @@+<?xml version="1.0"?>+<project name="YACY - tarParser" default="dist">+ <description>+ A class to parse tar files+ </description>++ <property name="parserShortName" value="tar"/>+ <property name="parserVersion" value="0.1"/>++ <property name="parserLongName" value="yacyContentParser_${parserShortName}"/>+ <property name="parserArchive" location="${release}/${parserLongName}_${parserVersion}.tgz"/>++ <target name="compile">+ <echo message="Compiling ${parserLongName} Version ${parserVersion} ..."/>+ <javac srcdir="${src}/de/anomic/plasma/parser/${parserShortName}" destdir="${build}" source="${javacSource}" target="${javacTarget}">+ <classpath>+ <pathelement location="${build}" />++ <pathelement location="${libx}/tar.jar" />+ </classpath>+ </javac>+ </target>+++ <target name="zip" depends="compile">+ <echo message="Compressing ${parserLongName} Version ${parserVersion} ..."/>+ <tar destfile="${parserArchive}" compression="gzip">+ <tarfileset dir="${libx}"+ includes="tar.jar"+ prefix="libx/"+ dirmode="755" mode="644"/>+ <tarfileset dir="${src}/de/anomic/plasma/parser/${parserShortName}"+ prefix="source/de/anomic/plasma/parser/${parserShortName}"+ dirmode="755" mode="644"/>+ <tarfileset dir="${build}/de/anomic/plasma/parser/${parserShortName}"+ prefix="classes/de/anomic/plasma/parser/${parserShortName}"+ dirmode="755" mode="644"/>+ </tar>+ </target>+++ <target name="dist" depends="compile,zip" description="Compile and zip the parser"/>+++</project>+diff --git a/source/de/anomic/plasma/parser/tar/tarParser.java b/source/de/anomic/plasma/parser/tar/tarParser.javanew file mode 100644index 000000000..dc227bce2--- /dev/null+++ b/source/de/anomic/plasma/parser/tar/tarParser.java@@ -0,0 +1,181 @@+//tarParser.java+//------------------------+//part of YaCy+//(C) by Michael Peter Christen; [email protected]+//first published on http://www.anomic.de+//Frankfurt, Germany, 2005+//+//this file is contributed by Martin Thelian+//last major change: 16.05.2005+//+//This program is free software; you can redistribute it and/or modify+//it under the terms of the GNU General Public License as published by+//the Free Software Foundation; either version 2 of the License, or+//(at your option) any later version.+//+//This program is distributed in the hope that it will be useful,+//but WITHOUT ANY WARRANTY; without even the implied warranty of+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+//GNU General Public License for more details.+//+//You should have received a copy of the GNU General Public License+//along with this program; if not, write to the Free Software+//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+//+//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.plasma.parser.tar;++import java.io.ByteArrayOutputStream;+import java.io.InputStream;+import java.net.URL;+import java.util.Arrays;+import java.util.HashMap;+import java.util.Hashtable;+import java.util.LinkedList;+import java.util.Map;++import com.ice.tar.TarEntry;+import com.ice.tar.TarInputStream;++import de.anomic.plasma.plasmaParser;+import de.anomic.plasma.plasmaParserDocument;+import de.anomic.plasma.parser.AbstractParser;+import de.anomic.plasma.parser.Parser;+import de.anomic.plasma.parser.ParserException;+import de.anomic.server.serverByteBuffer;++public class tarParser extends AbstractParser implements Parser {++ /**+ * a list of mime types that are supported by this parser class+ * @see #getSupportedMimeTypes()+ */+ public static final Hashtable SUPPORTED_MIME_TYPES = new Hashtable();+ static {+ SUPPORTED_MIME_TYPES.put("application/x-tar","tar");+ }++ /**+ * a list of library names that are needed by this parser+ * @see Parser#getLibxDependences()+ */+ private static final String[] LIBX_DEPENDENCIES = new String[] {+ "tar.jar"+ };++ public tarParser() {+ super(LIBX_DEPENDENCIES);+ }++ public Hashtable getSupportedMimeTypes() {+ return SUPPORTED_MIME_TYPES;+ }++ public plasmaParserDocument parse(URL location, String mimeType, InputStream source) throws ParserException {++ try {+ StringBuffer docKeywords = new StringBuffer();+ StringBuffer docShortTitle = new StringBuffer();+ StringBuffer docLongTitle = new StringBuffer();+ LinkedList docSections = new LinkedList();+ StringBuffer docAbstrct = new StringBuffer();+ serverByteBuffer docText = new serverByteBuffer();+ Map docAnchors = new HashMap();+ Map docImages = new HashMap();+++ // creating a new parser class to parse the unzipped content+ plasmaParser theParser = new plasmaParser();++ // looping through the contained files+ TarEntry entry;+ TarInputStream tin = new TarInputStream(source);+ while ((entry = tin.getNextEntry()) !=null) {++ if (entry.isDirectory()) continue;++ // Get the entry name+ String entryName = entry.getName();+ int idx = entryName.lastIndexOf(".");+ String entryExt = (idx > -1) ? entryName.substring(idx+1) : null;++ // trying to determine the mimeType per file extension+ String entryMime = theParser.getMimeTypeByFileExt(entryExt);++ // getting the entry content+ ByteArrayOutputStream bos = new ByteArrayOutputStream();+ byte[] buf = new byte[(int) entry.getSize()];+ int bytesRead = tin.read(buf);+ bos.write(buf);+ byte[] ut = bos.toByteArray();++ // parsing the content+ plasmaParserDocument theDoc = theParser.parseSource(location,entryMime,ut);+ if (theDoc == null) continue;++ // merging all documents together+ if (docKeywords.length() > 0) docKeywords.append("\n");+ docKeywords.append(theDoc.getKeywords());++ if (docLongTitle.length() > 0) docLongTitle.append("\n");+ docLongTitle.append(theDoc.getMainLongTitle());++ if (docShortTitle.length() > 0) docShortTitle.append("\n");+ docShortTitle.append(theDoc.getMainShortTitle());++ docSections.addAll(Arrays.asList(theDoc.getSectionTitles()));++ if (docAbstrct.length() > 0) docAbstrct.append("\n");+ docAbstrct.append(theDoc.getAbstract());++ if (docText.length() > 0) docText.append("\n");+ docText.append(theDoc.getText());++ docAnchors.putAll(theDoc.getAnchors());+ docImages.putAll(theDoc.getImages());+ }++ /* (URL location, String mimeType,+ String keywords, String shortTitle, String longTitle,+ String[] sections, String abstrct,+ byte[] text, Map anchors, Map images)+ */+ return new plasmaParserDocument(+ location,+ mimeType,+ docKeywords.toString(),+ docShortTitle.toString(),+ docLongTitle.toString(),+ (String[])docSections.toArray(new String[docSections.size()]),+ docAbstrct.toString(),+ docText.toByteArray(),+ docAnchors,+ docImages);+ } catch (Exception e) {+ throw new ParserException("Unable to parse the zip content. " + e.getMessage());+ }+ }++ public void reset() {+ // Nothing todo here at the moment++ }+}diff --git a/source/de/anomic/plasma/parser/zip/build.xml b/source/de/anomic/plasma/parser/zip/build.xmlnew file mode 100644index 000000000..1bee299b8--- /dev/null+++ b/source/de/anomic/plasma/parser/zip/build.xml@@ -0,0 +1,40 @@+<?xml version="1.0"?>+<project name="YACY - zipParser" default="dist">+ <description>+ A class to parse gzip files+ </description>++ <property name="parserShortName" value="zip"/>+ <property name="parserVersion" value="0.1"/>++ <property name="parserLongName" value="yacyContentParser_${parserShortName}"/>+ <property name="parserArchive" location="${release}/${parserLongName}_${parserVersion}.tgz"/>++ <target name="compile">+ <echo message="Compiling ${parserLongName} Version ${parserVersion} ..."/>+ <javac srcdir="${src}/de/anomic/plasma/parser/${parserShortName}" destdir="${build}" source="${javacSource}" target="${javacTarget}">+ <classpath>+ <pathelement location="${build}" />+ </classpath>+ </javac>+ </target>+++ <target name="zip" depends="compile">+ <echo message="Compressing ${parserLongName} Version ${parserVersion} ..."/>+ <tar destfile="${parserArchive}" compression="gzip">+ <tarfileset dir="${src}/de/anomic/plasma/parser/${parserShortName}"+ prefix="source/de/anomic/plasma/parser/${parserShortName}"+ dirmode="755" mode="644"/>+ <tarfileset dir="${build}/de/anomic/plasma/parser/${parserShortName}"+ prefix="classes/de/anomic/plasma/parser/${parserShortName}"+ dirmode="755" mode="644"/>+ </tar>+ </target>+++ <target name="dist" depends="compile,zip" description="Compile and zip the parser"/>+++</project>+diff --git a/source/de/anomic/plasma/parser/zip/zipParser.java b/source/de/anomic/plasma/parser/zip/zipParser.javanew file mode 100644index 000000000..bbf5ad927--- /dev/null+++ b/source/de/anomic/plasma/parser/zip/zipParser.java@@ -0,0 +1,179 @@+//zipParser.java+//------------------------+//part of YaCy+//(C) by Michael Peter Christen; [email protected]+//first published on http://www.anomic.de+//Frankfurt, Germany, 2005+//+//this file is contributed by Martin Thelian+//last major change: 16.05.2005+//+//This program is free software; you can redistribute it and/or modify+//it under the terms of the GNU General Public License as published by+//the Free Software Foundation; either version 2 of the License, or+//(at your option) any later version.+//+//This program is distributed in the hope that it will be useful,+//but WITHOUT ANY WARRANTY; without even the implied warranty of+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+//GNU General Public License for more details.+//+//You should have received a copy of the GNU General Public License+//along with this program; if not, write to the Free Software+//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+//+//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.plasma.parser.zip;++import java.io.ByteArrayOutputStream;+import java.io.InputStream;+import java.net.URL;+import java.util.Arrays;+import java.util.HashMap;+import java.util.Hashtable;+import java.util.LinkedList;+import java.util.Map;+import java.util.zip.ZipEntry;+import java.util.zip.ZipInputStream;++import de.anomic.plasma.plasmaParser;+import de.anomic.plasma.plasmaParserDocument;+import de.anomic.plasma.parser.AbstractParser;+import de.anomic.plasma.parser.Parser;+import de.anomic.plasma.parser.ParserException;+import de.anomic.server.serverByteBuffer;++public class zipParser extends AbstractParser implements Parser {++ /**+ * a list of mime types that are supported by this parser class+ * @see #getSupportedMimeTypes()+ */+ public static final Hashtable SUPPORTED_MIME_TYPES = new Hashtable();+ static {+ SUPPORTED_MIME_TYPES.put("application/zip","zip");+ SUPPORTED_MIME_TYPES.put("application/java-archive","jar");+ }++ /**+ * a list of library names that are needed by this parser+ * @see Parser#getLibxDependences()+ */+ private static final String[] LIBX_DEPENDENCIES = new String[] {};++ public zipParser() {+ super(LIBX_DEPENDENCIES);+ }++ public Hashtable getSupportedMimeTypes() {+ return SUPPORTED_MIME_TYPES;+ }++ public plasmaParserDocument parse(URL location, String mimeType, InputStream source) throws ParserException {++ try {+ StringBuffer docKeywords = new StringBuffer();+ StringBuffer docShortTitle = new StringBuffer();+ StringBuffer docLongTitle = new StringBuffer();+ LinkedList docSections = new LinkedList();+ StringBuffer docAbstrct = new StringBuffer();+ serverByteBuffer docText = new serverByteBuffer();+ Map docAnchors = new HashMap();+ Map docImages = new HashMap();+++ // creating a new parser class to parse the unzipped content+ plasmaParser theParser = new plasmaParser();++ // looping through the contained files+ ZipEntry entry;+ ZipInputStream zippedContent = new ZipInputStream(source);+ while ((entry = zippedContent.getNextEntry()) !=null) {++ if (entry.isDirectory()) continue;++ // Get the entry name+ String entryName = entry.getName();+ int idx = entryName.lastIndexOf(".");+ String entryExt = (idx > -1) ? entryName.substring(idx+1) : null;++ // trying to determine the mimeType per file extension+ String entryMime = theParser.getMimeTypeByFileExt(entryExt);++ // getting the entry content+ ByteArrayOutputStream bos = new ByteArrayOutputStream();+ byte[] buf = new byte[(int) entry.getSize()];+ int bytesRead = zippedContent.read(buf);+ bos.write(buf);+ byte[] ut = bos.toByteArray();++ // parsing the content+ plasmaParserDocument theDoc = theParser.parseSource(location,entryMime,ut);+ if (theDoc == null) continue;++ // merging all documents together+ if (docKeywords.length() > 0) docKeywords.append("\n");+ docKeywords.append(theDoc.getKeywords());++ if (docLongTitle.length() > 0) docLongTitle.append("\n");+ docLongTitle.append(theDoc.getMainLongTitle());++ if (docShortTitle.length() > 0) docShortTitle.append("\n");+ docShortTitle.append(theDoc.getMainShortTitle());++ docSections.addAll(Arrays.asList(theDoc.getSectionTitles()));++ if (docAbstrct.length() > 0) docAbstrct.append("\n");+ docAbstrct.append(theDoc.getAbstract());++ if (docText.length() > 0) docText.append("\n");+ docText.append(theDoc.getText());++ docAnchors.putAll(theDoc.getAnchors());+ docImages.putAll(theDoc.getImages());+ }++ /* (URL location, String mimeType,+ String keywords, String shortTitle, String longTitle,+ String[] sections, String abstrct,+ byte[] text, Map anchors, Map images)+ */+ return new plasmaParserDocument(+ location,+ mimeType,+ docKeywords.toString(),+ docShortTitle.toString(),+ docLongTitle.toString(),+ (String[])docSections.toArray(new String[docSections.size()]),+ docAbstrct.toString(),+ docText.toByteArray(),+ docAnchors,+ docImages);+ } catch (Exception e) {+ throw new ParserException("Unable to parse the zip content. " + e.getMessage());+ }+ }++ public void reset() {+ // Nothing todo here at the moment++ }+}diff --git a/source/de/anomic/plasma/plasmaCrawlLoader.java b/source/de/anomic/plasma/plasmaCrawlLoader.javaindex b979659a3..e7b2c2cbc 100644--- a/source/de/anomic/plasma/plasmaCrawlLoader.java+++ b/source/de/anomic/plasma/plasmaCrawlLoader.java@@ -46,6 +46,7 @@ import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashSet;+import java.util.Hashtable;import org.apache.commons.pool.impl.GenericObjectPool;@@ -62,6 +63,7 @@ public final class plasmaCrawlLoader extends Thread {private final CrawlerMessageQueue theQueue;private final CrawlerPool crawlwerPool;+ private GenericObjectPool.Config cralwerPoolConfig = null;private final ThreadGroup theThreadGroup = new ThreadGroup("CrawlerThreads");private boolean stopped = false;@@ -73,8 +75,7 @@ public final class plasmaCrawlLoader extends Thread {int mslots,boolean proxyUse,String proxyHost,- int proxyPort,- HashSet acceptMimeTypes) {+ int proxyPort) {this.setName("plasmaCrawlLoader");this.cacheManager = cacheManager;@@ -88,24 +89,24 @@ public final class plasmaCrawlLoader extends Thread {// configuring the crawler thread pool// implementation of session thread pool- GenericObjectPool.Config config = new GenericObjectPool.Config();+ this.cralwerPoolConfig = new GenericObjectPool.Config();// The maximum number of active connections that can be allocated from pool at the same time,// 0 for no limit- config.maxActive = this.maxSlots;+ this.cralwerPoolConfig.maxActive = this.maxSlots;// The maximum number of idle connections connections in the pool// 0 = no limit.- config.maxIdle = this.maxSlots / 2;- config.minIdle = this.maxSlots / 4;+ this.cralwerPoolConfig.maxIdle = this.maxSlots / 2;+ this.cralwerPoolConfig.minIdle = this.maxSlots / 4;// block undefinitely- config.maxWait = -1;+ this.cralwerPoolConfig.maxWait = -1;// Action to take in case of an exhausted DBCP statement pool// 0 = fail, 1 = block, 2= grow- config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;- config.minEvictableIdleTimeMillis = 30000;+ this.cralwerPoolConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;+ this.cralwerPoolConfig.minEvictableIdleTimeMillis = 30000;// config.testOnReturn = true;CrawlerFactory theFactory = new CrawlerFactory(@@ -115,15 +116,22 @@ public final class plasmaCrawlLoader extends Thread {proxyUse,proxyHost,proxyPort,- acceptMimeTypes,log);- this.crawlwerPool = new CrawlerPool(theFactory,config,this.theThreadGroup);+ this.crawlwerPool = new CrawlerPool(theFactory,this.cralwerPoolConfig,this.theThreadGroup);// start the crawl loaderthis.start();}+ public GenericObjectPool.Config getPoolConfig() {+ return this.cralwerPoolConfig;+ }++ public void setPoolConfig(GenericObjectPool.Config newConfig) {+ this.crawlwerPool.setConfig(newConfig);+ }+public void close() {try {// setting the stop flag to true@@ -343,8 +351,7 @@ final class CrawlerFactory implements org.apache.commons.pool.PoolableObjectFactprivate final int socketTimeout;private final boolean remoteProxyUse;private final String remoteProxyHost;- private final int remoteProxyPort;- private final HashSet acceptMimeTypes;+ private final int remoteProxyPort;private final serverLog theLog;public CrawlerFactory(@@ -354,7 +361,6 @@ final class CrawlerFactory implements org.apache.commons.pool.PoolableObjectFactboolean remoteProxyUse,String remoteProxyHost,int remoteProxyPort,- HashSet acceptMimeTypes,serverLog theLog) {super();@@ -367,8 +373,7 @@ final class CrawlerFactory implements org.apache.commons.pool.PoolableObjectFactthis.socketTimeout = socketTimeout;this.remoteProxyUse = remoteProxyUse;this.remoteProxyHost = remoteProxyHost;- this.remoteProxyPort = remoteProxyPort;- this.acceptMimeTypes = acceptMimeTypes;+ this.remoteProxyPort = remoteProxyPort;this.theLog = theLog;}@@ -388,7 +393,6 @@ final class CrawlerFactory implements org.apache.commons.pool.PoolableObjectFactthis.remoteProxyUse,this.remoteProxyHost,this.remoteProxyPort,- this.acceptMimeTypes,this.theLog);}diff --git a/source/de/anomic/plasma/plasmaCrawlWorker.java b/source/de/anomic/plasma/plasmaCrawlWorker.javaindex d5a9926d0..f4964346c 100644--- a/source/de/anomic/plasma/plasmaCrawlWorker.java+++ b/source/de/anomic/plasma/plasmaCrawlWorker.java@@ -47,7 +47,6 @@ import java.io.IOException;import java.net.SocketException;import java.net.URL;import java.util.Date;-import java.util.HashSet;import de.anomic.http.httpHeader;import de.anomic.http.httpc;@@ -65,7 +64,6 @@ public final class plasmaCrawlWorker extends Thread {private final boolean remoteProxyUse;private final String remoteProxyHost;private final int remoteProxyPort;- private final HashSet acceptMimeTypes;private final serverLog log;public plasmaCrawlLoaderMessage theMsg;@@ -90,7 +88,6 @@ public final class plasmaCrawlWorker extends Thread {boolean remoteProxyUse,String remoteProxyHost,int remoteProxyPort,- HashSet acceptMimeTypes,serverLog log) {super(theTG,threadBaseName + "_inPool");@@ -100,7 +97,6 @@ public final class plasmaCrawlWorker extends Thread {this.remoteProxyUse = remoteProxyUse;this.remoteProxyHost = remoteProxyHost;this.remoteProxyPort = remoteProxyPort;- this.acceptMimeTypes = acceptMimeTypes;this.log = log;}@@ -228,7 +224,7 @@ public final class plasmaCrawlWorker extends Thread {//System.out.println("CRAWLER_REQUEST_HEADER=" + requestHeader.toString()); // DEBUG// open the connection- remote = newhttpc(host, port, ssl);+ remote = newhttpc(host, port, ssl);// send requesthttpc.response res = remote.GET(path, requestHeader);@@ -243,7 +239,7 @@ public final class plasmaCrawlWorker extends Thread {// request has been placed and result has been returned. work off responseFile cacheFile = cacheManager.getCachePath(url);try {- if (!(httpd.isTextMime(res.responseHeader.mime().toLowerCase(), acceptMimeTypes))) {+ if (!(plasmaParser.supportedMimeTypesContains(res.responseHeader.mime()))) {// if the response has not the right file type then reject fileremote.close();log.logInfo("REJECTED WRONG MIME TYPE " + res.responseHeader.mime() + " for url " + url.toString());diff --git a/source/de/anomic/plasma/plasmaHTCache.java b/source/de/anomic/plasma/plasmaHTCache.javaindex 23cbc74a2..70ca288c3 100644--- a/source/de/anomic/plasma/plasmaHTCache.java+++ b/source/de/anomic/plasma/plasmaHTCache.java@@ -259,23 +259,23 @@ public final class plasmaHTCache {if (((entry.status == CACHE_FILL) || (entry.status == CACHE_STALE_RELOAD_GOOD)) &&((storeError = entry.shallStoreCache()) == null)) {- // write file if not written yet- if (entry.cacheArray != null) try {- if (entry.cacheFile.exists()) {- currCacheSize -= entry.cacheFile.length();- entry.cacheFile.delete();- }- entry.cacheFile.getParentFile().mkdirs();- log.logInfo("WRITE FILE (" + entry.cacheArray.length + " bytes) " + entry.cacheFile);- serverFileUtils.write(entry.cacheArray, entry.cacheFile);- log.logDebug("AFTER WRITE cacheArray = " + entry.cacheFile + ": " + ((entry.cacheArray == null) ? "empty" : "full"));- //entry.cacheArray = null;- } catch (FileNotFoundException e) {- // this is the case of a "(Not a directory)" error, which should be prohibited- // by the shallStoreCache() property. However, sometimes the error still occurs- // In this case do nothing.- log.logError("File storage failed: " + e.getMessage());- }+ // write file if not written yet+ if (entry.cacheArray != null) try {+ if (entry.cacheFile.exists()) {+ currCacheSize -= entry.cacheFile.length();+ entry.cacheFile.delete();+ }+ entry.cacheFile.getParentFile().mkdirs();+ log.logInfo("WRITE FILE (" + entry.cacheArray.length + " bytes) " + entry.cacheFile);+ serverFileUtils.write(entry.cacheArray, entry.cacheFile);+ log.logDebug("AFTER WRITE cacheArray = " + entry.cacheFile + ": " + ((entry.cacheArray == null) ? "empty" : "full"));+ //entry.cacheArray = null;+ } catch (FileNotFoundException e) {+ // this is the case of a "(Not a directory)" error, which should be prohibited+ // by the shallStoreCache() property. However, sometimes the error still occurs+ // In this case do nothing.+ log.logError("File storage failed: " + e.getMessage());+ }// update statisticscurrCacheSize += entry.cacheFile.length();@@ -352,36 +352,44 @@ public final class plasmaHTCache {}public static boolean isPicture(httpHeader response) {- Object ct = response.get("Content-Type");- if (ct == null) return false;- return ((String)ct).toUpperCase().startsWith("IMAGE");+ Object ct = response.get(httpHeader.CONTENT_TYPE);+ if (ct == null) return false;+ return ((String)ct).toUpperCase().startsWith("IMAGE");}public static boolean isText(httpHeader response) {- Object ct = response.get("Content-Type");- if (ct == null) return false;- String t = ((String)ct).toLowerCase();- return ((t.startsWith("text")) || (t.equals("application/xhtml+xml")));+// Object ct = response.get(httpHeader.CONTENT_TYPE);+// if (ct == null) return false;+// String t = ((String)ct).toLowerCase();+// return ((t.startsWith("text")) || (t.equals("application/xhtml+xml")));+ return plasmaParser.supportedMimeTypesContains(response.mime());}public static boolean noIndexingURL(String urlString) {- if (urlString == null) return false;+ if (urlString == null) return false;urlString = urlString.toLowerCase();- return (- (urlString.endsWith(".gz")) ||- (urlString.endsWith(".msi")) ||- (urlString.endsWith(".doc")) ||- (urlString.endsWith(".zip")) ||- (urlString.endsWith(".tgz")) ||- (urlString.endsWith(".rar")) ||- (urlString.endsWith(".pdf")) ||- (urlString.endsWith(".ppt")) ||- (urlString.endsWith(".xls")) ||- (urlString.endsWith(".log")) ||- (urlString.endsWith(".java")) ||- (urlString.endsWith(".c")) ||- (urlString.endsWith(".p"))- );+// return (+// (urlString.endsWith(".gz")) ||+// (urlString.endsWith(".msi")) ||+// (urlString.endsWith(".doc")) ||+// (urlString.endsWith(".zip")) ||+// (urlString.endsWith(".tgz")) ||+// (urlString.endsWith(".rar")) ||+// (urlString.endsWith(".pdf")) ||+// (urlString.endsWith(".ppt")) ||+// (urlString.endsWith(".xls")) ||+// (urlString.endsWith(".log")) ||+// (urlString.endsWith(".java")) ||+// (urlString.endsWith(".c")) ||+// (urlString.endsWith(".p"))+// );+ int idx = urlString.indexOf("?");+ if (idx > 0) urlString = urlString.substring(0,idx);++ idx = urlString.lastIndexOf(".");+ if (idx > 0) urlString = urlString.substring(idx+1);++ return plasmaParser.mediaExtContains(urlString);}// this method creates from a given host and path a cache path@@ -537,7 +545,7 @@ public final class plasmaHTCache {public URL referrerURL() {if (requestHeader == null) return null;try {- return new URL((String) requestHeader.get("Referer", ""));+ return new URL((String) requestHeader.get(httpHeader.REFERER, ""));} catch (Exception e) {return null;}@@ -573,18 +581,18 @@ public final class plasmaHTCache {// -CGI access in request// CGI access makes the page very individual, and therefore not usable in caches- if ((isPOST(nomalizedURLString)) && (!(profile.crawlingQ()))) return "dynamic_post";- if (isCGI(nomalizedURLString)) return "dynamic_cgi";+ if ((isPOST(nomalizedURLString)) && (!(profile.crawlingQ()))) return "dynamic_post";+ if (isCGI(nomalizedURLString)) return "dynamic_cgi";// -authorization cases in request// authorization makes pages very individual, and therefore we cannot use the// content in the cache- if ((requestHeader != null) && (requestHeader.containsKey("AUTHORIZATION"))) return "personalized";+ if ((requestHeader != null) && (requestHeader.containsKey(httpHeader.AUTHORIZATION))) return "personalized";// -ranges in request and response// we do not cache partial content- if ((requestHeader != null) && (requestHeader.containsKey("RANGE"))) return "partial";- if ((responseHeader != null) && (responseHeader.containsKey("CONTENT-RANGE"))) return "partial";+ if ((requestHeader != null) && (requestHeader.containsKey(httpHeader.RANGE))) return "partial";+ if ((responseHeader != null) && (responseHeader.containsKey(httpHeader.CONTENT_RANGE))) return "partial";// -if-modified-since in request// we do not care about if-modified-since, because this case only occurres if the@@ -602,8 +610,8 @@ public final class plasmaHTCache {// -pragma in response// if we have a pragma non-cache, we don't cache. usually if this is wanted from// the server, it makes sense- if ((responseHeader.containsKey("PRAGMA")) &&- (((String) responseHeader.get("Pragma")).toUpperCase().equals("NO-CACHE"))) return "controlled_no_cache";+ if ((responseHeader.containsKey(httpHeader.PRAGMA)) &&+ (((String) responseHeader.get(httpHeader.PRAGMA)).toUpperCase().equals("NO-CACHE"))) return "controlled_no_cache";// -expires in response// we do not care about expires, because at the time this is called the data is@@ -611,7 +619,7 @@ public final class plasmaHTCache {// -cache-control in response// the cache-control has many value options.- String cacheControl = (String) responseHeader.get("Cache-Control");+ String cacheControl = (String) responseHeader.get(httpHeader.CACHE_CONTROL);if (cacheControl != null) {cacheControl = cacheControl.trim().toUpperCase();if (cacheControl.startsWith("MAX-AGE=")) {@@ -645,21 +653,21 @@ public final class plasmaHTCache {if (isCGI(nomalizedURLString)) return false;// -authorization cases in request- if (requestHeader.containsKey("AUTHORIZATION")) return false;+ if (requestHeader.containsKey(httpHeader.AUTHORIZATION)) return false;// -ranges in request// we do not cache partial content- if ((requestHeader != null) && (requestHeader.containsKey("RANGE"))) return false;+ if ((requestHeader != null) && (requestHeader.containsKey(httpHeader.RANGE))) return false;//Date d1, d2;// -if-modified-since in request// The entity has to be transferred only if it has// been modified since the date given by the If-Modified-Since header.- if (requestHeader.containsKey("IF-MODIFIED-SINCE")) {+ if (requestHeader.containsKey(httpHeader.IF_MODIFIED_SINCE)) {// checking this makes only sense if the cached response contains// a Last-Modified field. If the field does not exist, we go the safe way- if (!(responseHeader.containsKey("Last-Modified"))) return false;+ if (!(responseHeader.containsKey(httpHeader.LAST_MODIFIED))) return false;// parse dateDate d1, d2;d2 = responseHeader.lastModified(); if (d2 == null) d2 = new Date();@@ -673,25 +681,25 @@ public final class plasmaHTCache {// -cookies in request// unfortunately, we should reload in case of a cookie// but we think that pictures can still be considered as fresh- if ((requestHeader.containsKey("COOKIE")) && (isNotPicture)) return false;+ if ((requestHeader.containsKey(httpHeader.COOKIE)) && (isNotPicture)) return false;// -set-cookie in cached response// this is a similar case as for COOKIE.- if ((responseHeader.containsKey("SET-COOKIE")) && (isNotPicture)) return false; // too strong- if ((responseHeader.containsKey("SET-COOKIE2")) && (isNotPicture)) return false; // too strong+ if ((responseHeader.containsKey(httpHeader.SET_COOKIE)) && (isNotPicture)) return false; // too strong+ if ((responseHeader.containsKey(httpHeader.SET_COOKIE2)) && (isNotPicture)) return false; // too strong// -pragma in cached response// logically, we would not need to care about no-cache pragmas in cached response headers,// because they cannot exist since they are not written to the cache.// So this IF should always fail..- if ((responseHeader.containsKey("PRAGMA")) &&- (((String) responseHeader.get("Pragma")).toUpperCase().equals("NO-CACHE"))) return false;+ if ((responseHeader.containsKey(httpHeader.PRAGMA)) &&+ (((String) responseHeader.get(httpHeader.PRAGMA)).toUpperCase().equals("NO-CACHE"))) return false;// calculate often needed values for freshness attributesDate date = responseHeader.date();Date expires = responseHeader.expires();Date lastModified = responseHeader.lastModified();- String cacheControl = (String) responseHeader.get("Cache-Control");+ String cacheControl = (String) responseHeader.get(httpHeader.CACHE_CONTROL);// see for documentation also:@@ -784,8 +792,8 @@ public final class plasmaHTCache {// -if-modified-since in request// if the page is fresh at the very moment we can index itif ((requestHeader != null) &&- (requestHeader.containsKey("IF-MODIFIED-SINCE")) &&- (responseHeader.containsKey("Last-Modified"))) {+ (requestHeader.containsKey(httpHeader.IF_MODIFIED_SINCE)) &&+ (responseHeader.containsKey(httpHeader.LAST_MODIFIED))) {// parse dateDate d1, d2;d2 = responseHeader.lastModified(); if (d2 == null) d2 = new Date();@@ -800,7 +808,7 @@ public final class plasmaHTCache {// -cookies in request// unfortunately, we cannot index pages which have been requested with a cookie// because the returned content may be special for the client- if ((requestHeader != null) && (requestHeader.containsKey("COOKIE"))) {+ if ((requestHeader != null) && (requestHeader.containsKey(httpHeader.COOKIE))) {//System.out.println("***not indexed because cookie");return "Dynamic_(Requested_With_Cookie)";}@@ -810,8 +818,8 @@ public final class plasmaHTCache {// thus we do not care about it here for indexing// -pragma in cached response- if ((responseHeader.containsKey("PRAGMA")) &&- (((String) responseHeader.get("Pragma")).toUpperCase().equals("NO-CACHE"))) return "Denied_(pragma_no_cache)";+ if ((responseHeader.containsKey(httpHeader.PRAGMA)) &&+ (((String) responseHeader.get(httpHeader.PRAGMA)).toUpperCase().equals("NO-CACHE"))) return "Denied_(pragma_no_cache)";// see for documentation also:// http://www.web-caching.com/cacheability.html@@ -820,7 +828,7 @@ public final class plasmaHTCache {Date date = responseHeader.date();Date expires = responseHeader.expires();Date lastModified = responseHeader.lastModified();- String cacheControl = (String) responseHeader.get("Cache-Control");+ String cacheControl = (String) responseHeader.get(httpHeader.CACHE_CONTROL);// look for freshnes informationdiff --git a/source/de/anomic/plasma/plasmaParser.java b/source/de/anomic/plasma/plasmaParser.javaindex 4b41781c0..93914c174 100644--- a/source/de/anomic/plasma/plasmaParser.java+++ b/source/de/anomic/plasma/plasmaParser.java@@ -49,6 +49,7 @@ import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileFilter;import java.io.FileInputStream;+import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FilenameFilter;import java.io.IOException;@@ -56,15 +57,19 @@ import java.io.OutputStream;import java.net.MalformedURLException;import java.net.URI;import java.net.URL;+import java.util.ArrayList;import java.util.Arrays;+import java.util.Collection;import java.util.Enumeration;import java.util.HashMap;import java.util.HashSet;import java.util.Hashtable;import java.util.Iterator;+import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.Properties;+import java.util.Set;import org.apache.commons.pool.KeyedPoolableObjectFactory;import org.apache.commons.pool.impl.GenericKeyedObjectPool;@@ -74,6 +79,7 @@ import de.anomic.htmlFilter.htmlFilterContentScraper;import de.anomic.htmlFilter.htmlFilterOutputStream;import de.anomic.plasma.parser.Parser;import de.anomic.server.serverFileUtils;+import de.anomic.yacy.yacySeedUploader;public final class plasmaParser {@@ -81,33 +87,32 @@ public final class plasmaParser {* A list containing all installed parsers and the mimeType that they support* @see #loadAvailableParserList()*/- private final Properties availableParserList = new Properties();+ private static final Properties availableParserList = new Properties();/*** A list containing all enabled parsers and the mimeType that they can handle* @see #loadEnabledParserList()* @see #setEnabledParserList(Enumeration)*/- private final Properties enabledParserList = new Properties();+ private static final Properties enabledParserList = new Properties();/*** A list of file extensions that are supported by all enabled parsers*/private static final HashSet supportedFileExt = new HashSet();+ /**+ * A list of mimeTypes that can be parsed in Realtime (on the fly)+ */+ private static final HashSet realtimeParsableMimeTypes = new HashSet();+/*** A pool of parsers.* @see plasmaParserPool* @see plasmaParserFactory*/- private final plasmaParserPool theParserPool;+ private static plasmaParserPool theParserPool;- /**- * The configuration file containing a list of enabled parsers- * @see plasmaParser#plasmaParser(File)- */- private final File parserDispatcherPropertyFile;-/*** A list of media extensions that should not be handled by the plasmaParser*/@@ -118,7 +123,7 @@ public final class plasmaParser {* which seems to be additional content parsers.* Currently the filenames of all content parser classes must end with <code>Parser.class</code>*/- private final FilenameFilter parserFileNameFilter = new FilenameFilter() {+ private static final FilenameFilter parserFileNameFilter = new FilenameFilter() {public boolean accept(File dir, String name) {return name.endsWith("Parser.class");}@@ -128,7 +133,7 @@ public final class plasmaParser {* This {@link FileFilter} is used to get all subpackages* of the parser package.*/- private final FileFilter parserDirectoryFilter = new FileFilter() {+ private static final FileFilter parserDirectoryFilter = new FileFilter() {public boolean accept(File file) {return file.isDirectory();}@@ -141,11 +146,63 @@ public final class plasmaParser {static {initMediaExt("swf,wmv,jpg,jpeg,jpe,rm,mov,mpg,mpeg,mp3,asf,gif,png,avi,zip,rar," +"sit,hqx,img,dmg,tar,gz,ps,xls,ppt,ram,bz2,arj");++ /* ===================================================+ * initializing the parser object pool+ * =================================================== */+ GenericKeyedObjectPool.Config config = new GenericKeyedObjectPool.Config();++ // The maximum number of active connections that can be allocated from pool at the same time,+ // 0 for no limit+ config.maxActive = 0;++ // The maximum number of idle connections connections in the pool+ // 0 = no limit.+ config.maxIdle = 10;++ config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;+ config.minEvictableIdleTimeMillis = 30000;++ plasmaParser.theParserPool = new plasmaParserPool(new plasmaParserFactory(),config);++ /* ===================================================+ * loading a list of available parsers+ * =================================================== */+ loadAvailableParserList();+ }++ public static void initRealtimeParsableMimeTypes(String realtimeParsableMimeTypes) {+ if ((realtimeParsableMimeTypes == null) || (realtimeParsableMimeTypes.length() == 0)) return;++ String[] realtimeParsableMimeTypeList = realtimeParsableMimeTypes.split(",");+ LinkedList mimeTypes = new LinkedList();+ for (int i = 0; i < realtimeParsableMimeTypeList.length; i++) mimeTypes.add(realtimeParsableMimeTypeList[i].toLowerCase().trim());+ initRealtimeParsableMimeTypes(mimeTypes);+ }++ public static void initRealtimeParsableMimeTypes(List mimeTypesList) {+ synchronized (realtimeParsableMimeTypes) {+ realtimeParsableMimeTypes.clear();+ realtimeParsableMimeTypes.addAll(mimeTypesList);+ }+ }++ public static void initParseableMimeTypes(String enabledMimeTypes) {+ if ((enabledMimeTypes == null) || (enabledMimeTypes.length() == 0)) return;++ String[] enabledMimeTypeList = enabledMimeTypes.split(",");+ HashSet mimeTypes = new HashSet();+ for (int i = 0; i < enabledMimeTypeList.length; i++) mimeTypes.add(enabledMimeTypeList[i].toLowerCase().trim());+ setEnabledParserList(mimeTypes);}public static void initMediaExt(String mediaExtString) {+ if ((mediaExtString == null) || (mediaExtString.length() == 0)) return;+String[] xs = mediaExtString.split(",");- initMediaExt(Arrays.asList(xs));+ LinkedList extensions = new LinkedList();+ for (int i = 0; i < xs.length; i++) extensions.add(xs[i].toLowerCase().trim());+ initMediaExt(extensions);}public static void initMediaExt(List mediaExtList) {@@ -155,99 +212,111 @@ public final class plasmaParser {}}+ public static boolean realtimeParsableMimeTypesContains(String mimeType) {+ mimeType = getRealMimeType(mimeType);+ synchronized (realtimeParsableMimeTypes) {+ return realtimeParsableMimeTypes.contains(mimeType);+ }+ }++ public static boolean supportedMimeTypesContains(String mimeType) {+ mimeType = getRealMimeType(mimeType);++ synchronized (realtimeParsableMimeTypes) {+ if (realtimeParsableMimeTypes.contains(mimeType)) return true;+ }++ synchronized (enabledParserList) {+ return enabledParserList.containsKey(mimeType);+ }+ }+public static boolean mediaExtContains(String mediaExt) {+ if (mediaExt == null) return false;synchronized (supportedFileExt) {if (supportedFileExt.contains(mediaExt)) return false;}synchronized (mediaExtSet) {- return mediaExtSet.contains(mediaExtSet);+ return mediaExtSet.contains(mediaExt);}}-- public plasmaParser(File parserDispatcherPropertyFile) {+ public static String getRealMimeType(String mimeType) {+ //if (mimeType == null) doMimeTypeAnalysis+ if (mimeType == null) mimeType = "application/octet-stream";- this.parserDispatcherPropertyFile = parserDispatcherPropertyFile;-- /* ===================================================- * initializing the parser object pool- * =================================================== */- GenericKeyedObjectPool.Config config = new GenericKeyedObjectPool.Config();-- // The maximum number of active connections that can be allocated from pool at the same time,- // 0 for no limit- config.maxActive = 0;-- // The maximum number of idle connections connections in the pool- // 0 = no limit.- config.maxIdle = 10;-- config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;- config.minEvictableIdleTimeMillis = 30000;-- this.theParserPool = new plasmaParserPool(new plasmaParserFactory(),config);-- /* ===================================================- * loading a list of available parsers- * =================================================== */- loadAvailableParserList();-- /* ===================================================- * loading a list of activated parsers- * =================================================== */- loadEnabledParserList();+ int pos = mimeType.indexOf(';');+ return ((pos < 0) ? mimeType : mimeType.substring(0, pos)).toLowerCase();+ }++ public static String getMimeTypeByFileExt(String fileExt) {+ // loading a list of extensions from file+ Properties prop = new Properties();+ try {+ prop.load(new FileInputStream(new File("httpd.mime")));+ } catch (IOException e) {+ System.err.println("ERROR: httpd.mime not found in settings path");+ }+ return prop.getProperty(fileExt,"application/octet-stream");}- public boolean setEnabledParserList(Enumeration mimeTypes) {+ public plasmaParser() {+ // nothing todo here at the moment+ }++ public static String[] setEnabledParserList(Set mimeTypeSet) {Properties newEnabledParsers = new Properties();HashSet newSupportedFileExt = new HashSet();- if (mimeTypes != null) {- while (mimeTypes.hasMoreElements()) {- String mimeType = (String) mimeTypes.nextElement();- if (this.availableParserList.containsKey(mimeType)) {+ if (mimeTypeSet != null) {+ Iterator mimeTypes = mimeTypeSet.iterator();+ while (mimeTypes.hasNext()) {+ String mimeType = (String) mimeTypes.next();+ if (availableParserList.containsKey(mimeType)) {Parser theParser = null;try {// getting the parser- theParser = (Parser) this.theParserPool.borrowObject(this.availableParserList.get(mimeType));+ theParser = (Parser) plasmaParser.theParserPool.borrowObject(availableParserList.get(mimeType));// getting a list of mimeTypes that the parser supportsHashtable parserSupportsMimeTypes = theParser.getSupportedMimeTypes();if (parserSupportsMimeTypes != null) {Object supportedExtensions = parserSupportsMimeTypes.get(mimeType);- if ((supportedExtensions != null) && (supportedExtensions instanceof String)) {+ if ((supportedExtensions != null) &&+ (supportedExtensions instanceof String) &&+ (((String)supportedExtensions).length() > 0)) {String[] extArray = ((String)supportedExtensions).split(",");newSupportedFileExt.addAll(Arrays.asList(extArray));}}- newEnabledParsers.put(mimeType,this.availableParserList.get(mimeType));+ newEnabledParsers.put(mimeType,availableParserList.get(mimeType));} catch (Exception e) {e.printStackTrace();} finally {if (theParser != null)- try { this.theParserPool.returnObject(mimeType,theParser); } catch (Exception e) {}+ try { plasmaParser.theParserPool.returnObject(mimeType,theParser); } catch (Exception e) {}}}}}- synchronized (this.enabledParserList) {- this.enabledParserList.clear();- this.enabledParserList.putAll(newEnabledParsers);+ synchronized (enabledParserList) {+ enabledParserList.clear();+ enabledParserList.putAll(newEnabledParsers);}synchronized (supportedFileExt) {supportedFileExt.clear();- supportedFileExt.addAll(supportedFileExt);+ supportedFileExt.addAll(newSupportedFileExt);}- return true;+ return newEnabledParsers.keySet().toArray(new String[newEnabledParsers.size()]);}public Hashtable getEnabledParserList() {@@ -260,29 +329,32 @@ public final class plasmaParser {return this.availableParserList;}- private void loadEnabledParserList() {+ private static void loadEnabledParserList() {// loading a list of availabe parser from fileProperties prop = new Properties();try {- prop.load(new FileInputStream(this.parserDispatcherPropertyFile));+ prop.load(new FileInputStream(new File("yacy.parser")));} catch (IOException e) {- System.err.println("ERROR: " + this.parserDispatcherPropertyFile.toString() + " not found in settings path");+ System.err.println("ERROR: yacy.parser not found in settings path");}// enable them ...- this.setEnabledParserList(prop.keys());+ setEnabledParserList(prop.keySet());}- private void loadAvailableParserList() {+ private static void loadAvailableParserList() {try {- this.availableParserList.clear();+ plasmaParser.availableParserList.clear();++ // getting the current java classpath+ String javaClassPath = System.getProperty("java.class.path");// getting the current package name- String plasmaParserPkgName = this.getClass().getPackage().getName() + ".parser";+ String plasmaParserPkgName = plasmaParser.class.getPackage().getName() + ".parser";System.out.println("INFO: Searching for additional content parsers in package " + plasmaParserPkgName);// getting an uri to the parser subpackage- String packageURI = this.getClass().getResource("/"+plasmaParserPkgName.replace('.','/')).toString();+ String packageURI = plasmaParser.class.getResource("/"+plasmaParserPkgName.replace('.','/')).toString();System.out.println("INFO: Parser directory is " + packageURI);// open the parser directory@@ -293,12 +365,12 @@ public final class plasmaParser {* loop through all subdirectories and test if we can* find an additional parser class*/- File[] parserDirectories = parserDir.listFiles(this.parserDirectoryFilter);+ File[] parserDirectories = parserDir.listFiles(parserDirectoryFilter);if (parserDirectories == null) return;for (int parserDirNr=0; parserDirNr< parserDirectories.length; parserDirNr++) {File currentDir = parserDirectories[parserDirNr];System.out.println("INFO: Searching in directory " + currentDir.toString());- String[] parserClasses = currentDir.list(this.parserFileNameFilter);+ String[] parserClasses = currentDir.list(parserFileNameFilter);if (parserClasses == null) continue;for (int parserNr=0; parserNr<parserClasses.length; parserNr++) {@@ -306,14 +378,25 @@ public final class plasmaParser {String className = parserClasses[parserNr].substring(0,parserClasses[parserNr].indexOf(".class"));String fullClassName = plasmaParserPkgName + "." + currentDir.getName() + "." + className;try {+ // trying to load the parser class by its nameClass parserClass = Class.forName(fullClassName);Object theParser = parserClass.newInstance();if (!(theParser instanceof Parser)) continue;++ // testing if all needed libx libraries are available+ String[] neededLibx = ((Parser)theParser).getLibxDependences();+ if (neededLibx != null) {+ for (int libxId=0; libxId < neededLibx.length; libxId++) {+ if (javaClassPath.indexOf(neededLibx[libxId]) == -1) continue;+ }+ }++ // loading the list of mime-types that are supported by this parser classHashtable supportedMimeTypes = ((Parser)theParser).getSupportedMimeTypes();Iterator mimeTypeIterator = supportedMimeTypes.keySet().iterator();while (mimeTypeIterator.hasNext()) {String mimeType = (String) mimeTypeIterator.next();- this.availableParserList.put(mimeType,fullClassName);+ availableParserList.put(mimeType,fullClassName);System.out.println("INFO: Found parser for mimeType " + mimeType);}@@ -329,12 +412,6 @@ public final class plasmaParser {public void close() {// clearing the parser listsynchronized (this.enabledParserList) {- try {- this.enabledParserList.store(new FileOutputStream(this.parserDispatcherPropertyFile),"plasmaParser configuration file");- } catch (IOException e) {- System.err.println("ERROR: " + this.parserDispatcherPropertyFile.toString() + " can not be stored.");- }-this.enabledParserList.clear();}@@ -348,10 +425,7 @@ public final class plasmaParser {Parser theParser = null;try {-- if ((mimeType != null) && (mimeType.indexOf(";") != -1)) {- mimeType = mimeType.substring(0,mimeType.indexOf(";"));- }+ mimeType = getRealMimeType(mimeType);// getting the correct parser for the given mimeTypetheParser = this.getParser(mimeType);@@ -359,22 +433,21 @@ public final class plasmaParser {// if a parser was found we use it ...if (theParser != null) {return theParser.parse(location, mimeType,source);+ } else if (realtimeParsableMimeTypesContains(mimeType)) {+ // ... otherwise we make a html scraper and transformer+ htmlFilterContentScraper scraper = new htmlFilterContentScraper(location);+ OutputStream hfos = new htmlFilterOutputStream(null, scraper, null, false);++ hfos.write(source);+ return transformScraper(location, mimeType, scraper);+ } else {+ return null;}-- // ...otherwise we make a html scraper and transformer- htmlFilterContentScraper scraper = new htmlFilterContentScraper(location);- OutputStream hfos = new htmlFilterOutputStream(null, scraper, null, false);-- hfos.write(source);- return transformScraper(location, mimeType, scraper);} catch (Exception e) {return null;} finally {if (theParser != null) {- try {- this.theParserPool.returnObject(mimeType, theParser);- } catch (Exception e) {- }+ try { this.theParserPool.returnObject(mimeType, theParser); } catch (Exception e) {}}}}@@ -383,9 +456,7 @@ public final class plasmaParser {Parser theParser = null;try {- if ((mimeType != null) && (mimeType.indexOf(";") != -1)) {- mimeType = mimeType.substring(0,mimeType.indexOf(";"));- }+ mimeType = getRealMimeType(mimeType);// getting the correct parser for the given mimeTypetheParser = this.getParser(mimeType);@@ -393,22 +464,22 @@ public final class plasmaParser {// if a parser was found we use it ...if (theParser != null) {return theParser.parse(location, mimeType,sourceFile);- }-- // ...otherwise we make a scraper and transformer- htmlFilterContentScraper scraper = new htmlFilterContentScraper(location);- OutputStream hfos = new htmlFilterOutputStream(null, scraper, null, false);-- serverFileUtils.copy(sourceFile, hfos);- return transformScraper(location, mimeType, scraper);+ } else if (realtimeParsableMimeTypesContains(mimeType)) {+ // ...otherwise we make a scraper and transformer+ htmlFilterContentScraper scraper = new htmlFilterContentScraper(location);+ OutputStream hfos = new htmlFilterOutputStream(null, scraper, null, false);++ serverFileUtils.copy(sourceFile, hfos);+ return transformScraper(location, mimeType, scraper);+ } else {+ return null;+ }} catch (Exception e) {+ // e.printStackTrace();return null;} finally {if (theParser != null) {- try {- this.theParserPool.returnObject(mimeType, theParser);- } catch (Exception e) {- }+ try { this.theParserPool.returnObject(mimeType, theParser); } catch (Exception e) { }}}}@@ -431,19 +502,15 @@ public final class plasmaParser {* @return*/public Parser getParser(String mimeType) {-- if (mimeType == null) {- // TODO: do automatic mimetype detection- return null;- }-++ mimeType = getRealMimeType(mimeType);try {// determining the proper parser class name for the mimeTypeString parserClassName = null;- synchronized (this.enabledParserList) {- if (this.enabledParserList.containsKey(mimeType)) {- parserClassName = (String)this.enabledParserList.get(mimeType);+ synchronized (plasmaParser.enabledParserList) {+ if (plasmaParser.enabledParserList.containsKey(mimeType)) {+ parserClassName = (String)plasmaParser.enabledParserList.get(mimeType);} else {return null;}@@ -454,7 +521,7 @@ public final class plasmaParser {// checking if the created parser really supports the given mimetypeHashtable supportedMimeTypes = theParser.getSupportedMimeTypes();- if ((supportedMimeTypes != null) && (supportedMimeTypes.contains(mimeType))) {+ if ((supportedMimeTypes != null) && (supportedMimeTypes.containsKey(mimeType))) {return theParser;}this.theParserPool.returnObject(parserClassName,theParser);@@ -533,11 +600,13 @@ public final class plasmaParser {try {File in = new File(args[0]);File out = new File(args[1]);- plasmaParser theParser = new plasmaParser(new File("yacy.parser"));+ plasmaParser theParser = new plasmaParser();+ theParser.initRealtimeParsableMimeTypes("application/xhtml+xml,text/html,text/plain");+ theParser.initParseableMimeTypes("application/atom+xml,application/gzip,application/java-archive,application/msword,application/octet-stream,application/pdf,application/rdf+xml,application/rss+xml,application/rtf,application/x-gzip,application/x-tar,application/xml,application/zip,text/rss,text/rtf,text/xml,application/x-bzip2");FileInputStream theInput = new FileInputStream(in);ByteArrayOutputStream theOutput = new ByteArrayOutputStream();serverFileUtils.copy(theInput, theOutput);- plasmaParserDocument document = theParser.parseSource(new URL("http://brain.yacy"), "text/html", theOutput.toByteArray());+ plasmaParserDocument document = theParser.parseSource(new URL("http://brain/~theli/test.pdf"), null, theOutput.toByteArray());//plasmaParserDocument document = theParser.parseSource(new URL("http://brain.yacy"), "application/pdf", theOutput.toByteArray());byte[] theText = document.getText();serverFileUtils.write(theText, out);diff --git a/source/de/anomic/plasma/plasmaParserDocument.java b/source/de/anomic/plasma/plasmaParserDocument.javaindex 7cff5dac9..f5027efb6 100644--- a/source/de/anomic/plasma/plasmaParserDocument.java+++ b/source/de/anomic/plasma/plasmaParserDocument.java@@ -75,9 +75,9 @@ public class plasmaParserDocument {this.keywords = (keywords==null)?"":keywords;this.shortTitle = (shortTitle==null)?"":shortTitle;this.longTitle = (longTitle==null)?"":longTitle;- this.sections = sections;+ this.sections = (sections==null)?new String[0]:sections;this.abstrct = (abstrct==null)?"":abstrct;- this.text = text;+ this.text = (text==null)?new byte[0]:text;this.anchors = (anchors==null)?new HashMap():anchors;this.images = (images==null)?new HashMap():images;this.hyperlinks = null;@@ -114,6 +114,11 @@ public class plasmaParserDocument {return text;}+ public String getKeywords() {+ return this.keywords;++ }+public Map getAnchors() {// returns all links embedded as anchors (clickeable entities)return anchors;@@ -201,5 +206,7 @@ public class plasmaParserDocument {hyperlinks.putAll(plasmaParser.allSubpaths(hyperlinks));hyperlinks.putAll(plasmaParser.allSubpaths(medialinks));}++}diff --git a/source/de/anomic/plasma/plasmaSearch.java b/source/de/anomic/plasma/plasmaSearch.javaindex 0121f0dd2..6eddc5184 100644--- a/source/de/anomic/plasma/plasmaSearch.java+++ b/source/de/anomic/plasma/plasmaSearch.java@@ -57,14 +57,14 @@ import de.anomic.kelondro.kelondroMScoreCluster;import de.anomic.server.serverCodings;import de.anomic.server.serverLog;-public class plasmaSearch {+public final class plasmaSearch {public static final char O_QUALITY = 'q';public static final char O_AGE = 'a';public static final String splitrex = " |/|\\(|\\)|-|\\:|_|\\.|,|\\?|!|'|" + '"';- private plasmaCrawlLURL urlStore;- private plasmaWordIndex wordIndex;+ private final plasmaCrawlLURL urlStore;+ private final plasmaWordIndex wordIndex;public plasmaSearch(plasmaCrawlLURL urlStore, plasmaWordIndex wordIndex) {this.urlStore = urlStore;@@ -138,44 +138,44 @@ public class plasmaSearch {}public plasmaWordIndexEntity searchHashes(Set hashes, long time) throws IOException {- // search for the set of hashes and return an array of urlEntry elements-+ // search for the set of hashes and return an array of urlEntry elements+long stamp = System.currentTimeMillis();- TreeMap map = new TreeMap();- String singleHash;- plasmaWordIndexEntity singleResult;+ TreeMap map = new TreeMap();+ String singleHash;+ plasmaWordIndexEntity singleResult;Iterator i = hashes.iterator();- while (i.hasNext()) {- // get next hash:- singleHash = (String) i.next();-- // retrieve index- singleResult = wordIndex.getEntity(singleHash, true);-- // check result- if (singleResult.size() == 0) return new plasmaWordIndexEntity(null); // as this is a cunjunction of searches, we have no result if any word is not known-- // store result in order of result size- map.put(serverCodings.enhancedCoder.encodeHex(singleResult.size(), 8) + singleHash, singleResult);- }-- // check if there is any result- if (map.size() == 0) return new plasmaWordIndexEntity(null); // no result, nothing found-- // the map now holds the search results in order of number of hits per word- // we now must pairwise build up a conjunction of these sets- String k = (String) map.firstKey(); // the smallest, which means, the one with the least entries- plasmaWordIndexEntity searchResult = (plasmaWordIndexEntity) map.remove(k);- while ((map.size() > 0) && (searchResult.size() > 0) && (time > 0)) {- // take the first element of map which is a result and combine it with result- k = (String) map.firstKey(); // the next smallest...+ while (i.hasNext()) {+ // get next hash:+ singleHash = (String) i.next();++ // retrieve index+ singleResult = wordIndex.getEntity(singleHash, true);++ // check result+ if (singleResult.size() == 0) return new plasmaWordIndexEntity(null); // as this is a cunjunction of searches, we have no result if any word is not known++ // store result in order of result size+ map.put(serverCodings.enhancedCoder.encodeHex(singleResult.size(), 8) + singleHash, singleResult);+ }++ // check if there is any result+ if (map.size() == 0) return new plasmaWordIndexEntity(null); // no result, nothing found++ // the map now holds the search results in order of number of hits per word+ // we now must pairwise build up a conjunction of these sets+ String k = (String) map.firstKey(); // the smallest, which means, the one with the least entries+ plasmaWordIndexEntity searchResult = (plasmaWordIndexEntity) map.remove(k);+ while ((map.size() > 0) && (searchResult.size() > 0) && (time > 0)) {+ // take the first element of map which is a result and combine it with result+ k = (String) map.firstKey(); // the next smallest...time -= (System.currentTimeMillis() - stamp); stamp = System.currentTimeMillis();searchResult = joinConstructive(searchResult, (plasmaWordIndexEntity) map.remove(k), 2 * time / (map.size() + 1));- }-- // in 'searchResult' is now the combined search result- if (searchResult.size() == 0) return new plasmaWordIndexEntity(null);- return searchResult;+ }++ // in 'searchResult' is now the combined search result+ if (searchResult.size() == 0) return new plasmaWordIndexEntity(null);+ return searchResult;}private static int log2(int x) {@@ -317,12 +317,12 @@ public class plasmaSearch {public class result /*implements Enumeration*/ {- TreeMap pageAcc; // key = order hash; value = plasmaLURL.entry- kelondroMScoreCluster ref; // reference score computation for the commonSense heuristic- Set searchhashes; // hashes that are searched here- Set stopwords; // words that are excluded from the commonSense heuristic- char[] order; // order of heuristics- ArrayList results; // this is a buffer for plasmaWordIndexEntry + plasmaCrawlLURL.entry - objects+ final TreeMap pageAcc; // key = order hash; value = plasmaLURL.entry+ final kelondroMScoreCluster ref; // reference score computation for the commonSense heuristic+ final Set searchhashes; // hashes that are searched here+ final Set stopwords; // words that are excluded from the commonSense heuristic+ final char[] order; // order of heuristics+ ArrayList results; // this is a buffer for plasmaWordIndexEntry + plasmaCrawlLURL.entry - objectspublic result(Set searchhashes, Set stopwords, char[] order) {this.pageAcc = new TreeMap();diff --git a/source/de/anomic/plasma/plasmaSwitchboard.java b/source/de/anomic/plasma/plasmaSwitchboard.javaindex 3a5b07b6c..4fcac33fe 100644--- a/source/de/anomic/plasma/plasmaSwitchboard.java+++ b/source/de/anomic/plasma/plasmaSwitchboard.java@@ -152,7 +152,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser// load slots- private static final int crawlSlots = 8;+ public static int crawlSlots = 8;// couloured list managementpublic static TreeSet blueList = null;@@ -178,8 +178,6 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements serpublic plasmaCrawlProfile.entry defaultProxyProfile;public plasmaCrawlProfile.entry defaultRemoteProfile;public distributeIndex indexDistribution;- public HashSet mimeWhite;- public HashSet extensionBlack;public HashMap outgoingCookies, incomingCookies;public kelondroTables facilityDB;public plasmaParser parser;@@ -245,42 +243,38 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements serprofiles = new plasmaCrawlProfile(new File(plasmaPath, "crawlProfiles0.db"));initProfiles();- // make parser- parser = new plasmaParser(new File("yacy.parser"));-// start indexing managementloadedURL = new plasmaCrawlLURL(new File(plasmaPath, "urlHash.db"), ramLURL);noticeURL = new plasmaCrawlNURL(plasmaPath, ramNURL);errorURL = new plasmaCrawlEURL(new File(plasmaPath, "urlErr0.db"), ramEURL);- wordIndex = new plasmaWordIndex(plasmaPath, ramRWI, log);+ wordIndex = new plasmaWordIndex(plasmaPath, ramRWI, log);int wordCacheMax = Integer.parseInt((String) getConfig("wordCacheMax", "10000"));wordIndex.setMaxWords(wordCacheMax);- searchManager = new plasmaSearch(loadedURL, wordIndex);+ searchManager = new plasmaSearch(loadedURL, wordIndex);// start a cache manager- cacheManager = new plasmaHTCache(this, ramHTTP);-+ this.cacheManager = new plasmaHTCache(this, ramHTTP);++ // make parser+ this.parser = new plasmaParser();+// define an extension-blacklist- String[] extensionBlackArray = getConfig("mediaExt","").split(",");- extensionBlack = new HashSet();- for (int i = 0; i < extensionBlackArray.length; i++) extensionBlack.add(extensionBlackArray[i].toLowerCase());+ plasmaParser.initMediaExt(getConfig("mediaExt",null));- // define mime-type-whitelist- String[] mimeWhiteArray = getConfig("parseableMime","").split(",");- mimeWhite = new HashSet();- for (int i = 0; i < mimeWhiteArray.length; i++) mimeWhite.add(mimeWhiteArray[i].toLowerCase());+ // define a realtime parsable mimetype list+ plasmaParser.initRealtimeParsableMimeTypes(getConfig("parseableRealtimeMimeTypes",null));+ plasmaParser.initParseableMimeTypes(getConfig("parseableMimeTypes",null));- // start a loader+ // start a loaderint remoteport;try { remoteport = Integer.parseInt(getConfig("remoteProxyPort","3128")); }catch (NumberFormatException e) { remoteport = 3128; }- cacheLoader = new plasmaCrawlLoader(cacheManager, log,- Integer.parseInt(getConfig("clientTimeout", "10000")),- 5000, crawlSlots,- getConfig("remoteProxyUse","false").equals("true"),- getConfig("remoteProxyHost",""),- remoteport,- mimeWhite);+ this.cacheLoader = new plasmaCrawlLoader(this.cacheManager, this.log,+ Integer.parseInt(getConfig("clientTimeout", "10000")),+ 5000, crawlSlots,+ getConfig("remoteProxyUse","false").equals("true"),+ getConfig("remoteProxyHost",""),+ remoteport);// init boardsmessageDB = new messageBoard(new File(getRootPath(), "DATA/SETTINGS/message.db"), ramMessage);@@ -627,30 +621,36 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements serinitiator = yacyCore.seedDB.getConnected(initiatorHash);processCase = 6;}-- log.logDebug("processResourceStack processCase=" + processCase + ", depth=" + entry.depth + ", maxDepth=" + entry.profile.generalDepth() + ", filter=" + entry.profile.generalFilter() + ", initiatorHash=" + initiatorHash + ", status=" + entry.status + ", source=" + ((entry.cacheArray == null) ? "scraper" : "byte[]") + ", url=" + entry.nomalizedURLString); // DEBUG-++ log.logDebug("processResourceStack processCase=" + processCase + ", depth=" + entry.depth + ", maxDepth=" + entry.profile.generalDepth() + ", filter=" + entry.profile.generalFilter() + ", initiatorHash=" + initiatorHash + ", status=" + entry.status + ", source=" + ((entry.cacheArray == null) ? "scraper" : "byte[]") + ", url=" + entry.nomalizedURLString); // DEBUG+// parse contentplasmaParserDocument document;- if (entry.scraper != null) {- log.logDebug("(Parser) '" + entry.nomalizedURLString + "' is pre-parsed by scraper");- document = parser.transformScraper(entry.url, entry.responseHeader.mime(), entry.scraper);- } else if (entry.cacheArray != null) {- log.logDebug("(Parser) '" + entry.nomalizedURLString + "' is not parsed yet, parsing now from cacheArray");- document = parser.parseSource(entry.url, entry.responseHeader.mime(), entry.cacheArray);++ if (plasmaParser.supportedMimeTypesContains(entry.responseHeader.mime())) {+ if (entry.scraper != null) {+ log.logDebug("(Parser) '" + entry.nomalizedURLString + "' is pre-parsed by scraper");+ document = parser.transformScraper(entry.url, entry.responseHeader.mime(), entry.scraper);+ } else if (entry.cacheArray != null) {+ log.logDebug("(Parser) '" + entry.nomalizedURLString + "' is not parsed yet, parsing now from cacheArray");+ document = parser.parseSource(entry.url, entry.responseHeader.mime(), entry.cacheArray);+ } else {+ if (entry.cacheFile.exists()) {+ log.logDebug("(Parser) '" + entry.nomalizedURLString + "' is not parsed yet, parsing now from File");+ document = parser.parseSource(entry.url, entry.responseHeader.mime(), entry.cacheFile);+ } else {+ log.logDebug("(Parser) '" + entry.nomalizedURLString + "' cannot be parsed, no resource available");+ return;+ }+ }+ if (document == null) {+ log.logError("(Parser) '" + entry.nomalizedURLString + "' parse failure");+ return;+ }} else {- if (entry.cacheFile.exists()) {- log.logDebug("(Parser) '" + entry.nomalizedURLString + "' is not parsed yet, parsing now from File");- document = parser.parseSource(entry.url, entry.responseHeader.mime(), entry.cacheFile);- } else {- log.logDebug("(Parser) '" + entry.nomalizedURLString + "' cannot be parsed, no resource available");- return;- }- }- if (document == null) {- log.logError("(Parser) '" + entry.nomalizedURLString + "' parse failure");- return;- }+ log.logDebug("(Parser) '" + entry.nomalizedURLString + "'. Unsupported mimeType '" + entry.responseHeader.mime() + "'.");+ return;+ }// put anchors on crawl stackif (((processCase == 4) || (processCase == 5)) &&@@ -784,14 +784,14 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements serreturn reason;}- // filter deny- if (!(nexturlString.matches(profile.generalFilter()))) {- reason = "denied_(does_not_match_filter)";+ // filter deny+ if ((currentdepth > 0) && (!(nexturlString.matches(profile.generalFilter())))) {+ reason = "denied_(does_not_match_filter)";errorURL.newEntry(nexturl, referrerHash, initiatorHash, yacyCore.seedDB.mySeed.hash,- name, reason, new bitfield(plasmaURL.urlFlagLength), false);- return reason;- }-+ name, reason, new bitfield(plasmaURL.urlFlagLength), false);+ return reason;+ }+// deny cgiif (plasmaHTCache.isCGI(nexturlString)) {reason = "denied_(cgi_url)";@@ -1517,7 +1517,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements serpublic int adminAuthenticated(httpHeader header) {String adminAccountBase64MD5 = getConfig("adminAccountBase64MD5", "");if (adminAccountBase64MD5.length() == 0) return 2; // not necessary- String authorization = ((String) header.get("Authorization", "xxxxxx")).trim().substring(6);+ String authorization = ((String) header.get(httpHeader.AUTHORIZATION, "xxxxxx")).trim().substring(6);if (authorization.length() == 0) return 1; // no authentication information givenif ((((String) header.get("CLIENTIP", "")).equals("localhost")) && (adminAccountBase64MD5.equals(authorization))) return 3; // soft-authenticated for localhostif (adminAccountBase64MD5.equals(serverCodings.standardCoder.encodeMD5Hex(authorization))) return 4; // hard-authenticated, all okdiff --git a/source/de/anomic/plasma/plasmaWordIndex.java b/source/de/anomic/plasma/plasmaWordIndex.javaindex 373e14748..d165d998a 100644--- a/source/de/anomic/plasma/plasmaWordIndex.java+++ b/source/de/anomic/plasma/plasmaWordIndex.java@@ -57,10 +57,10 @@ import de.anomic.kelondro.kelondroMSetTools;import de.anomic.yacy.yacySeedDB;import de.anomic.server.serverLog;-public class plasmaWordIndex {+public final class plasmaWordIndex {- File databaseRoot;- plasmaWordIndexCache ramCache;+ final File databaseRoot;+ final plasmaWordIndexCache ramCache;public plasmaWordIndex(File databaseRoot, int bufferkb, serverLog log) throws IOException {this.databaseRoot = databaseRoot;diff --git a/source/de/anomic/plasma/plasmaWordIndexCache.java b/source/de/anomic/plasma/plasmaWordIndexCache.javaindex a9d87c0ea..89645b993 100644--- a/source/de/anomic/plasma/plasmaWordIndexCache.java+++ b/source/de/anomic/plasma/plasmaWordIndexCache.java@@ -1,578 +1,578 @@-// plasmaWordIndexCache.java-// --------------------------// part of YACY-// (C) by Michael Peter Christen; [email protected]-// first published on http://www.anomic.de-// Frankfurt, Germany, 2005-// last major change: 6.5.2005-//-// This program is free software; you can redistribute it and/or modify-// it under the terms of the GNU General Public License as published by-// the Free Software Foundation; either version 2 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU General Public License for more details.-//-// You should have received a copy of the GNU General Public License-// along with this program; if not, write to the Free Software-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA-//-// 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.plasma;--import java.io.*;-import java.util.*;-import java.lang.RuntimeException;-import de.anomic.kelondro.*;-import de.anomic.server.serverLog;-import de.anomic.yacy.yacySeedDB;--public class plasmaWordIndexCache implements plasmaWordIndexInterface {-- // environment constants- private static final String indexDumpFileName = "indexDump0.stack";- private static final String singletonFileName = "indexSingletons0.db";- private static final int[] bufferStructure = new int[]{- plasmaWordIndexEntry.wordHashLength, // a wordHash- 4, // occurrence counter- 8, // timestamp of last access- plasmaWordIndexEntry.urlHashLength, // corresponding URL hash- plasmaWordIndexEntry.attrSpaceLong // URL attributes- };-- // class variables- private File databaseRoot;- private plasmaWordIndexInterface backend;- private TreeMap cache;- private kelondroMScoreCluster hashScore;- private HashMap hashDate;- private int maxWords;- private serverLog log;- private kelondroTree singletons;- private long singletonBufferSize;-- // calculated constants- private static String minKey, maxKey;- static {- maxKey = "";- for (int i = 0; i < yacySeedDB.commonHashLength; i++) maxKey += 'z';- minKey = "";- for (int i = 0; i < yacySeedDB.commonHashLength; i++) maxKey += '-';- }-- public plasmaWordIndexCache(File databaseRoot, plasmaWordIndexInterface backend, int singletonbufferkb, serverLog log) {- // creates a new index cache- // the cache has a back-end where indexes that do not fit in the cache are flushed- this.databaseRoot = databaseRoot;- this.singletonBufferSize = singletonbufferkb * 1024;- this.cache = new TreeMap();- this.hashScore = new kelondroMScoreCluster();- this.hashDate = new HashMap();- this.maxWords = 10000;- this.backend = backend;- this.log = log;- File singletonFile = new File(databaseRoot, singletonFileName);- if (singletonFile.exists()) {- // open existing singeton tree file- try {- singletons = new kelondroTree(singletonFile, singletonBufferSize);- log.logSystem("Opened Singleton Database, " + singletons.size() + " entries.");- } catch (IOException e){- log.logError("unable to open singleton database: " + e.getMessage());- e.printStackTrace();- }- } else {- // create new sigleton tree file- try {- singletons = new kelondroTree(singletonFile, singletonBufferSize, bufferStructure);- log.logSystem("Created new Singleton Database");- } catch (IOException e){- log.logError("unable to create singleton database: " + e.getMessage());- e.printStackTrace();- }- }- // read in dump of last session- try {- restore();- } catch (IOException e){- log.logError("unable to restore cache dump: " + e.getMessage());- e.printStackTrace();- }- }-- private void dump(int waitingSeconds) throws IOException {- log.logSystem("creating dump for index cache, " + cache.size() + " words (and much more urls)");- File indexDumpFile = new File(databaseRoot, indexDumpFileName);- if (indexDumpFile.exists()) indexDumpFile.delete();- kelondroStack dumpStack = new kelondroStack(indexDumpFile, 0, bufferStructure);- long startTime = System.currentTimeMillis();- long messageTime = System.currentTimeMillis() + 5000;- long wordsPerSecond = 0, wordcount = 0, urlcount = 0;- synchronized (cache) {- Iterator i = cache.entrySet().iterator();- //Iterator i = hashScore.scores(true);- Map.Entry entry;- String wordHash;- plasmaWordIndexEntryContainer container;- long creationTime;- plasmaWordIndexEntry wordEntry;- byte[][] row = new byte[5][];- while (i.hasNext()) {- // get entries- entry = (Map.Entry) i.next();- //wordHash = (String) i.next();- wordHash = (String) entry.getKey();- creationTime = getCreationTime(wordHash);- //container = (plasmaWordIndexEntryContainer) cache.get(wordHash);- container = (plasmaWordIndexEntryContainer) entry.getValue();-- // put entries on stack- if (container != null) {- Iterator ci = container.entries();- while (ci.hasNext()) {- wordEntry = (plasmaWordIndexEntry) ci.next();- row[0] = wordHash.getBytes();- row[1] = kelondroRecords.long2bytes(container.size(), 4);- row[2] = kelondroRecords.long2bytes(creationTime, 8);- row[3] = wordEntry.getUrlHash().getBytes();- row[4] = wordEntry.toEncodedForm(true).getBytes();- dumpStack.push(row);- urlcount++;- }- }- wordcount++;-- // write a log- if (System.currentTimeMillis() > messageTime) {- wordsPerSecond = wordcount * 1000 / (1 + System.currentTimeMillis() - startTime);- log.logInfo("dumping status: " + wordcount + " words done, " + ((cache.size() - wordcount) / wordsPerSecond) + " seconds remaining");- messageTime = System.currentTimeMillis() + 5000;- }- }- }- dumpStack.close();- log.logSystem("dumped " + urlcount + " word/url relations in " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds");- }-- private long restore() throws IOException {- File indexDumpFile = new File(databaseRoot, indexDumpFileName);- if (!(indexDumpFile.exists())) return 0;- kelondroStack dumpStack = new kelondroStack(indexDumpFile, 0);- log.logSystem("restore dump of index cache, " + dumpStack.size() + " word/url relations");- long startTime = System.currentTimeMillis();- long messageTime = System.currentTimeMillis() + 5000;- long urlCount = 0, urlsPerSecond = 0;- synchronized (cache) {- Iterator i = dumpStack.iterator();- kelondroRecords.Node node;- String wordHash;- plasmaWordIndexEntryContainer container;- long creationTime;- plasmaWordIndexEntry wordEntry;- byte[][] row;- while (i.hasNext()) {- // get out one entry- node = (kelondroRecords.Node) i.next();- row = node.getValues();- wordHash = new String(row[0]);- creationTime = kelondroRecords.bytes2long(row[2]);- wordEntry = new plasmaWordIndexEntry(new String(row[3]), new String(row[4]));-- // store to cache- addEntry(wordHash, wordEntry, creationTime);- urlCount++;-- // write a log- if (System.currentTimeMillis() > messageTime) {- urlsPerSecond = 1 + urlCount * 1000 / (1 + System.currentTimeMillis() - startTime);- log.logInfo("restoring status: " + urlCount + " urls done, " + ((dumpStack.size() - urlCount) / urlsPerSecond) + " seconds remaining");- messageTime = System.currentTimeMillis() + 5000;- }- }- }- dumpStack.close();- log.logSystem("restored " + cache.size() + " words in " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds");- return urlCount;- }-- // singleton access methods-- private void storeSingleton(String wordHash, plasmaWordIndexEntry entry, long creationTime) {- // stores a word index to singleton database- // this throws an exception if the word hash already existed- //log.logDebug("storeSingleton: wordHash=" + wordHash + ", urlHash=" + entry.getUrlHash() + ", time=" + creationTime);- byte[][] row = new byte[5][];- row[0] = wordHash.getBytes();- row[1] = kelondroRecords.long2bytes(1, 4);- row[2] = kelondroRecords.long2bytes(creationTime, 8);- row[3] = entry.getUrlHash().getBytes();- row[4] = entry.toEncodedForm(true).getBytes();- byte[][] oldrow = null;- try {- oldrow = singletons.put(row);- } catch (IOException e) {- log.logFailure("storeSingleton/IO-error: " + e.getMessage() + " - reset singleton-DB");- e.printStackTrace();- resetSingletonDatabase();- } catch (kelondroException e) {- log.logFailure("storeSingleton/kelondro-error: " + e.getMessage() + " - reset singleton-DB");- e.printStackTrace();- resetSingletonDatabase();- }- if (oldrow != null) throw new RuntimeException("Store to singleton ambiguous");- }-- public Object[] /*{plasmaWordIndexEntry, Long(creationTime)}*/ readSingleton(String wordHash) {- // returns a single word index from singleton database; returns null if index does not exist- //log.logDebug("readSingleton: wordHash=" + wordHash);- byte[][] row = null;- try {- row = singletons.get(wordHash.getBytes());- } catch (IOException e) {- log.logFailure("readSingleton/IO-error: " + e.getMessage() + " - reset singleton-DB");- e.printStackTrace();- resetSingletonDatabase();- } catch (kelondroException e) {- log.logFailure("readSingleton/kelondro-error: " + e.getMessage() + " - reset singleton-DB");- e.printStackTrace();- resetSingletonDatabase();- }- if (row == null) return null;- long creationTime = kelondroRecords.bytes2long(row[2]);- plasmaWordIndexEntry wordEntry = new plasmaWordIndexEntry(new String(row[3]), new String(row[4]));- return new Object[]{wordEntry, new Long(creationTime)};- }-- private void removeSingleton(String wordHash) {- // deletes a word index from singleton database- //log.logDebug("removeSingleton: wordHash=" + wordHash);- byte[][] row = null;- try {- row = singletons.remove(wordHash.getBytes());- } catch (IOException e) {- log.logFailure("removeSingleton/IO-error: " + e.getMessage() + " - reset singleton-DB");- e.printStackTrace();- resetSingletonDatabase();- } catch (kelondroException e) {- log.logFailure("removeSingleton/kelondro-error: " + e.getMessage() + " - reset singleton-DB");- e.printStackTrace();- resetSingletonDatabase();- }- }-- private void resetSingletonDatabase() {- // deletes the singleton database and creates a new one- try {- singletons.close();- } catch (IOException e) {}- File singletonFile = new File(databaseRoot, singletonFileName);- if (!(singletonFile.delete())) throw new RuntimeException("cannot delete singleton database");- try {- singletons = new kelondroTree(singletonFile, singletonBufferSize, bufferStructure);- } catch (IOException e){- log.logError("unable to re-create singleton database: " + e.getMessage());- e.printStackTrace();- }- }-- public Iterator singletonHashes(String startWordHash, boolean up, boolean rot) {- try {- return singletons.keys(up, rot, startWordHash.getBytes());- } catch (IOException e) {- log.logFailure("iterateSingleton/IO-error: " + e.getMessage() + " - reset singleton-DB");- e.printStackTrace();- resetSingletonDatabase();- return null;- }- }-- // cache settings-- public int maxURLinWordCache() {- return hashScore.getScore(hashScore.getMaxObject());- }-- public int wordCacheRAMSize() {- return cache.size();- }-- public int singletonsSize() {- return singletons.size();- }-- public void setMaxWords(int maxWords) {- this.maxWords = maxWords;- }-- public int size() {- return java.lang.Math.max(singletons.size(), java.lang.Math.max(backend.size(), cache.size()));- }-- public Iterator wordHashes(String startWordHash, boolean up) {- // here we merge 3 databases into one view:- // - the RAM Cache- // - the singleton File Cache- // - the backend- if (!(up)) throw new RuntimeException("plasmaWordIndexCache.wordHashes can only count up");- return new kelondroMergeIterator(- new kelondroMergeIterator(- cache.keySet().iterator(),- singletonHashes(startWordHash, true, false),- true),- backend.wordHashes(startWordHash, true),- true);- }-- private int flushFromMem(String key, boolean reintegrate) {- // this method flushes indexes out from the ram to the disc.- // at first we check the singleton database and act accordingly- // if we we are to flush an index, but see also an entry in the singletons, we- // decide upn the 'reintegrate'-Flag:- // true: do not flush to disc, but re-Integrate the singleton to the RAM- // false: flush the singleton together with container to disc-- plasmaWordIndexEntryContainer container = null;- long time;- synchronized (cache) {- // get the container- container = (plasmaWordIndexEntryContainer) cache.get(key);- if (container == null) return 0; // flushing of nonexisting key- time = getCreationTime(key);-- // remove it from the cache- cache.remove(key);- hashScore.deleteScore(key);- hashDate.remove(key);- }- // now decide where to flush that container- Object[] singleton = readSingleton(key);- if (singleton == null) {- // not found in singletons- if (container.size() == 1) {- // it is a singleton: store to singleton- storeSingleton(key, container.getOne(), time);- return 1;- } else {- // store to back-end; this should be a rare case- return backend.addEntries(container, time);- }- } else {- // we have a singleton and need to integrate this in the flush- plasmaWordIndexEntry oldEntry = (plasmaWordIndexEntry) singleton[0];- long oldTime = ((Long) singleton[1]).longValue();- if (container.contains(oldEntry.getUrlHash())) {- // we have an double-occurrence- if (container.size() == 1) {- // it is superfluous to flush this, simple do nothing- return 0;- } else {- // we flush to the backend, and the entry from the singletons- removeSingleton(key);- return backend.addEntries(container, java.lang.Math.max(time, oldTime));- }- } else {- // now we have more than one entry- // we must remove the key from the singleton database- removeSingleton(key);- // .. and put it to the container- container.add(oldEntry);- if (reintegrate) {- // put singleton together with container back to ram- synchronized (cache) {- cache.put(key, container);- hashScore.setScore(key, container.size());- hashDate.put(key, new Long(time));- }- return -1;- } else {- // add this to the backend- return backend.addEntries(container, java.lang.Math.max(time, oldTime));- }- }- }- }-- private boolean flushFromSingleton(String key) {- // this should only be called if the singleton shall be deleted or returned in an index entity- Object[] singleton = readSingleton(key);- if (singleton == null) {- return false;- } else {- // we have a singleton- plasmaWordIndexEntry entry = (plasmaWordIndexEntry) singleton[0];- long time = ((Long) singleton[1]).longValue();- // remove it from the singleton database- removeSingleton(key);- // integrate it to the backend- return backend.addEntries(plasmaWordIndexEntryContainer.instantContainer(key, entry), time) > 0;- }- }-- private int flushFromMemToLimit() {- if ((hashScore.size() == 0) && (cache.size() == 0)) {- serverLog.logDebug("PLASMA INDEXING", "flushToLimit: called but cache is empty");- return 0;- }- if ((hashScore.size() == 0) && (cache.size() != 0)) {- serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=0 but cache.size=" + cache.size());- return 0;- }- if ((hashScore.size() != 0) && (cache.size() == 0)) {- serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=" + hashScore.size() + " but cache.size=0");- return 0;- }-- int count = 0;- //serverLog.logDebug("PLASMA INDEXING", "flushSpecific: hashScore.size=" + hashScore.size() + ", cache.size=" + cache.size());- synchronized (hashScore) {- String key;- Long createTime;-- // generate flush list- Iterator i = hashScore.scores(true);- TreeMap[] al = new TreeMap[hashScore.getMaxScore() + 1];- for (int k = 0; k < al.length; k++) al[k] = new TreeMap(); // by create time ordered hash-list- while (i.hasNext()) {- // get the entry properties- key = (String) i.next();- createTime = (Long) hashDate.get(key);- count = hashScore.getScore(key);-- // put it into a specific ohl- al[count].put(createTime, key);- //System.out.println("COUNT FOR KEY " + key + ": " + count);- }-- // print statistics- for (int k = 1; k < al.length; k++) log.logDebug("FLUSH-LIST " + k + ": " + al[k].size() + " entries");-- // flush singletons- i = al[1].entrySet().iterator();- Map.Entry entry;- while (i.hasNext()) {- entry = (Map.Entry) i.next();- key = (String) entry.getValue();- createTime = (Long) entry.getKey();- if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) > 90000)) {- //log.logDebug("flushing singleton-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size());- count += flushFromMem((String) key, true);- }- }-- // flush high-scores- for (int k = al.length - 1; k >= 2; k--) {- i = al[k].entrySet().iterator();- while (i.hasNext()) {- entry = (Map.Entry) i.next();- key = (String) entry.getValue();- createTime = (Long) entry.getKey();- if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) > (600000/k))) {- //log.logDebug("flushing high-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size());- count += flushFromMem(key, false);- }- if (count > 2000) return count;- }- }-- }- return count;- }-- public plasmaWordIndexEntity getIndex(String wordHash, boolean deleteIfEmpty) {- flushFromMem(wordHash, false);- flushFromSingleton(wordHash);- return backend.getIndex(wordHash, deleteIfEmpty);- }-- public long getCreationTime(String wordHash) {- Long time = (Long) hashDate.get(wordHash);- if (time == null) return 0;- return time.longValue();- }-- public void deleteIndex(String wordHash) {- synchronized (cache) {- cache.remove(wordHash);- hashScore.deleteScore(wordHash);- hashDate.remove(wordHash);- }- removeSingleton(wordHash);- backend.deleteIndex(wordHash);- }-- public synchronized int removeEntries(String wordHash, String[] urlHashes, boolean deleteComplete) {- flushFromMem(wordHash, false);- flushFromSingleton(wordHash);- return backend.removeEntries(wordHash, urlHashes, deleteComplete);- }-- public synchronized int addEntries(plasmaWordIndexEntryContainer container, long creationTime) {- //serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem: cache.size=" + cache.size() + "; hashScore.size=" + hashScore.size());- if (cache.size() >= this.maxWords) flushFromMemToLimit();- //if (flushc > 0) serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem - flushed " + flushc + " entries");-- // put new words into cache- int added = 0;- synchronized (cache) {- String wordHash = container.wordHash();- plasmaWordIndexEntryContainer entries = (plasmaWordIndexEntryContainer) cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null- if (entries == null) entries = new plasmaWordIndexEntryContainer(wordHash);- added = entries.add(container);- if (added > 0) {- cache.put(wordHash, entries);- hashScore.addScore(wordHash, added);- hashDate.put(wordHash, new Long(creationTime));- }- }- //System.out.println("DEBUG: cache = " + cache.toString());- return added;- }-- private void addEntry(String wordHash, plasmaWordIndexEntry newEntry, long creationTime) {- plasmaWordIndexEntryContainer entries = (plasmaWordIndexEntryContainer) cache.get(wordHash);- if (entries == null) entries = new plasmaWordIndexEntryContainer(wordHash);- if (entries.add(newEntry)) {- cache.put(wordHash, entries);- hashScore.incScore(wordHash);- hashDate.put(wordHash, new Long(creationTime));- }- }-- public void close(int waitingSeconds) {- try {- singletons.close();- } catch (IOException e){- log.logError("unable to close singleton database: " + e.getMessage());- e.printStackTrace();- }- try {- dump(waitingSeconds);- } catch (IOException e){- log.logError("unable to dump cache: " + e.getMessage());- e.printStackTrace();- }- }--}+// plasmaWordIndexCache.java+// -------------------------+// part of YACY+// (C) by Michael Peter Christen; [email protected]+// first published on http://www.anomic.de+// Frankfurt, Germany, 2005+// last major change: 6.5.2005+//+// This program is free software; you can redistribute it and/or modify+// it under the terms of the GNU General Public License as published by+// the Free Software Foundation; either version 2 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+//+// 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.plasma;++import java.io.*;+import java.util.*;+import java.lang.RuntimeException;+import de.anomic.kelondro.*;+import de.anomic.server.serverLog;+import de.anomic.yacy.yacySeedDB;++public final class plasmaWordIndexCache implements plasmaWordIndexInterface {++ // environment constants+ private static final String indexDumpFileName = "indexDump0.stack";+ private static final String singletonFileName = "indexSingletons0.db";+ private static final int[] bufferStructure = new int[]{+ plasmaWordIndexEntry.wordHashLength, // a wordHash+ 4, // occurrence counter+ 8, // timestamp of last access+ plasmaWordIndexEntry.urlHashLength, // corresponding URL hash+ plasmaWordIndexEntry.attrSpaceLong // URL attributes+ };++ // class variables+ private File databaseRoot;+ private plasmaWordIndexInterface backend;+ private TreeMap cache;+ private kelondroMScoreCluster hashScore;+ private HashMap hashDate;+ private int maxWords;+ private serverLog log;+ private kelondroTree singletons;+ private long singletonBufferSize;++ // calculated constants+ private static String minKey, maxKey;+ static {+ maxKey = "";+ for (int i = 0; i < yacySeedDB.commonHashLength; i++) maxKey += 'z';+ minKey = "";+ for (int i = 0; i < yacySeedDB.commonHashLength; i++) maxKey += '-';+ }++ public plasmaWordIndexCache(File databaseRoot, plasmaWordIndexInterface backend, int singletonbufferkb, serverLog log) {+ // creates a new index cache+ // the cache has a back-end where indexes that do not fit in the cache are flushed+ this.databaseRoot = databaseRoot;+ this.singletonBufferSize = singletonbufferkb * 1024;+ this.cache = new TreeMap();+ this.hashScore = new kelondroMScoreCluster();+ this.hashDate = new HashMap();+ this.maxWords = 10000;+ this.backend = backend;+ this.log = log;+ File singletonFile = new File(databaseRoot, singletonFileName);+ if (singletonFile.exists()) {+ // open existing singeton tree file+ try {+ singletons = new kelondroTree(singletonFile, singletonBufferSize);+ log.logSystem("Opened Singleton Database, " + singletons.size() + " entries.");+ } catch (IOException e){+ log.logError("unable to open singleton database: " + e.getMessage());+ e.printStackTrace();+ }+ } else {+ // create new sigleton tree file+ try {+ singletons = new kelondroTree(singletonFile, singletonBufferSize, bufferStructure);+ log.logSystem("Created new Singleton Database");+ } catch (IOException e){+ log.logError("unable to create singleton database: " + e.getMessage());+ e.printStackTrace();+ }+ }+ // read in dump of last session+ try {+ restore();+ } catch (IOException e){+ log.logError("unable to restore cache dump: " + e.getMessage());+ e.printStackTrace();+ }+ }++ private void dump(int waitingSeconds) throws IOException {+ log.logSystem("creating dump for index cache, " + cache.size() + " words (and much more urls)");+ File indexDumpFile = new File(databaseRoot, indexDumpFileName);+ if (indexDumpFile.exists()) indexDumpFile.delete();+ kelondroStack dumpStack = new kelondroStack(indexDumpFile, 0, bufferStructure);+ long startTime = System.currentTimeMillis();+ long messageTime = System.currentTimeMillis() + 5000;+ long wordsPerSecond = 0, wordcount = 0, urlcount = 0;+ synchronized (cache) {+ Iterator i = cache.entrySet().iterator();+ //Iterator i = hashScore.scores(true);+ Map.Entry entry;+ String wordHash;+ plasmaWordIndexEntryContainer container;+ long creationTime;+ plasmaWordIndexEntry wordEntry;+ byte[][] row = new byte[5][];+ while (i.hasNext()) {+ // get entries+ entry = (Map.Entry) i.next();+ //wordHash = (String) i.next();+ wordHash = (String) entry.getKey();+ creationTime = getCreationTime(wordHash);+ //container = (plasmaWordIndexEntryContainer) cache.get(wordHash);+ container = (plasmaWordIndexEntryContainer) entry.getValue();++ // put entries on stack+ if (container != null) {+ Iterator ci = container.entries();+ while (ci.hasNext()) {+ wordEntry = (plasmaWordIndexEntry) ci.next();+ row[0] = wordHash.getBytes();+ row[1] = kelondroRecords.long2bytes(container.size(), 4);+ row[2] = kelondroRecords.long2bytes(creationTime, 8);+ row[3] = wordEntry.getUrlHash().getBytes();+ row[4] = wordEntry.toEncodedForm(true).getBytes();+ dumpStack.push(row);+ urlcount++;+ }+ }+ wordcount++;++ // write a log+ if (System.currentTimeMillis() > messageTime) {+ wordsPerSecond = wordcount * 1000 / (1 + System.currentTimeMillis() - startTime);+ log.logInfo("dumping status: " + wordcount + " words done, " + ((cache.size() - wordcount) / wordsPerSecond) + " seconds remaining");+ messageTime = System.currentTimeMillis() + 5000;+ }+ }+ }+ dumpStack.close();+ log.logSystem("dumped " + urlcount + " word/url relations in " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds");+ }++ private long restore() throws IOException {+ File indexDumpFile = new File(databaseRoot, indexDumpFileName);+ if (!(indexDumpFile.exists())) return 0;+ kelondroStack dumpStack = new kelondroStack(indexDumpFile, 0);+ log.logSystem("restore dump of index cache, " + dumpStack.size() + " word/url relations");+ long startTime = System.currentTimeMillis();+ long messageTime = System.currentTimeMillis() + 5000;+ long urlCount = 0, urlsPerSecond = 0;+ synchronized (cache) {+ Iterator i = dumpStack.iterator();+ kelondroRecords.Node node;+ String wordHash;+ plasmaWordIndexEntryContainer container;+ long creationTime;+ plasmaWordIndexEntry wordEntry;+ byte[][] row;+ while (i.hasNext()) {+ // get out one entry+ node = (kelondroRecords.Node) i.next();+ row = node.getValues();+ wordHash = new String(row[0]);+ creationTime = kelondroRecords.bytes2long(row[2]);+ wordEntry = new plasmaWordIndexEntry(new String(row[3]), new String(row[4]));++ // store to cache+ addEntry(wordHash, wordEntry, creationTime);+ urlCount++;++ // write a log+ if (System.currentTimeMillis() > messageTime) {+ urlsPerSecond = 1 + urlCount * 1000 / (1 + System.currentTimeMillis() - startTime);+ log.logInfo("restoring status: " + urlCount + " urls done, " + ((dumpStack.size() - urlCount) / urlsPerSecond) + " seconds remaining");+ messageTime = System.currentTimeMillis() + 5000;+ }+ }+ }+ dumpStack.close();+ log.logSystem("restored " + cache.size() + " words in " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds");+ return urlCount;+ }++ // singleton access methods++ private void storeSingleton(String wordHash, plasmaWordIndexEntry entry, long creationTime) {+ // stores a word index to singleton database+ // this throws an exception if the word hash already existed+ //log.logDebug("storeSingleton: wordHash=" + wordHash + ", urlHash=" + entry.getUrlHash() + ", time=" + creationTime);+ byte[][] row = new byte[5][];+ row[0] = wordHash.getBytes();+ row[1] = kelondroRecords.long2bytes(1, 4);+ row[2] = kelondroRecords.long2bytes(creationTime, 8);+ row[3] = entry.getUrlHash().getBytes();+ row[4] = entry.toEncodedForm(true).getBytes();+ byte[][] oldrow = null;+ try {+ oldrow = singletons.put(row);+ } catch (IOException e) {+ log.logFailure("storeSingleton/IO-error: " + e.getMessage() + " - reset singleton-DB");+ e.printStackTrace();+ resetSingletonDatabase();+ } catch (kelondroException e) {+ log.logFailure("storeSingleton/kelondro-error: " + e.getMessage() + " - reset singleton-DB");+ e.printStackTrace();+ resetSingletonDatabase();+ }+ if (oldrow != null) throw new RuntimeException("Store to singleton ambiguous");+ }++ public Object[] /*{plasmaWordIndexEntry, Long(creationTime)}*/ readSingleton(String wordHash) {+ // returns a single word index from singleton database; returns null if index does not exist+ //log.logDebug("readSingleton: wordHash=" + wordHash);+ byte[][] row = null;+ try {+ row = singletons.get(wordHash.getBytes());+ } catch (IOException e) {+ log.logFailure("readSingleton/IO-error: " + e.getMessage() + " - reset singleton-DB");+ e.printStackTrace();+ resetSingletonDatabase();+ } catch (kelondroException e) {+ log.logFailure("readSingleton/kelondro-error: " + e.getMessage() + " - reset singleton-DB");+ e.printStackTrace();+ resetSingletonDatabase();+ }+ if (row == null) return null;+ long creationTime = kelondroRecords.bytes2long(row[2]);+ plasmaWordIndexEntry wordEntry = new plasmaWordIndexEntry(new String(row[3]), new String(row[4]));+ return new Object[]{wordEntry, new Long(creationTime)};+ }++ private void removeSingleton(String wordHash) {+ // deletes a word index from singleton database+ //log.logDebug("removeSingleton: wordHash=" + wordHash);+ byte[][] row = null;+ try {+ row = singletons.remove(wordHash.getBytes());+ } catch (IOException e) {+ log.logFailure("removeSingleton/IO-error: " + e.getMessage() + " - reset singleton-DB");+ e.printStackTrace();+ resetSingletonDatabase();+ } catch (kelondroException e) {+ log.logFailure("removeSingleton/kelondro-error: " + e.getMessage() + " - reset singleton-DB");+ e.printStackTrace();+ resetSingletonDatabase();+ }+ }++ private void resetSingletonDatabase() {+ // deletes the singleton database and creates a new one+ try {+ singletons.close();+ } catch (IOException e) {}+ File singletonFile = new File(databaseRoot, singletonFileName);+ if (!(singletonFile.delete())) throw new RuntimeException("cannot delete singleton database");+ try {+ singletons = new kelondroTree(singletonFile, singletonBufferSize, bufferStructure);+ } catch (IOException e){+ log.logError("unable to re-create singleton database: " + e.getMessage());+ e.printStackTrace();+ }+ }++ public Iterator singletonHashes(String startWordHash, boolean up, boolean rot) {+ try {+ return singletons.keys(up, rot, startWordHash.getBytes());+ } catch (IOException e) {+ log.logFailure("iterateSingleton/IO-error: " + e.getMessage() + " - reset singleton-DB");+ e.printStackTrace();+ resetSingletonDatabase();+ return null;+ }+ }++ // cache settings++ public int maxURLinWordCache() {+ return hashScore.getScore(hashScore.getMaxObject());+ }++ public int wordCacheRAMSize() {+ return cache.size();+ }++ public int singletonsSize() {+ return singletons.size();+ }++ public void setMaxWords(int maxWords) {+ this.maxWords = maxWords;+ }++ public int size() {+ return java.lang.Math.max(singletons.size(), java.lang.Math.max(backend.size(), cache.size()));+ }++ public Iterator wordHashes(String startWordHash, boolean up) {+ // here we merge 3 databases into one view:+ // - the RAM Cache+ // - the singleton File Cache+ // - the backend+ if (!(up)) throw new RuntimeException("plasmaWordIndexCache.wordHashes can only count up");+ return new kelondroMergeIterator(+ new kelondroMergeIterator(+ cache.keySet().iterator(),+ singletonHashes(startWordHash, true, false),+ true),+ backend.wordHashes(startWordHash, true),+ true);+ }++ private int flushFromMem(String key, boolean reintegrate) {+ // this method flushes indexes out from the ram to the disc.+ // at first we check the singleton database and act accordingly+ // if we we are to flush an index, but see also an entry in the singletons, we+ // decide upn the 'reintegrate'-Flag:+ // true: do not flush to disc, but re-Integrate the singleton to the RAM+ // false: flush the singleton together with container to disc++ plasmaWordIndexEntryContainer container = null;+ long time;+ synchronized (cache) {+ // get the container+ container = (plasmaWordIndexEntryContainer) cache.get(key);+ if (container == null) return 0; // flushing of nonexisting key+ time = getCreationTime(key);++ // remove it from the cache+ cache.remove(key);+ hashScore.deleteScore(key);+ hashDate.remove(key);+ }+ // now decide where to flush that container+ Object[] singleton = readSingleton(key);+ if (singleton == null) {+ // not found in singletons+ if (container.size() == 1) {+ // it is a singleton: store to singleton+ storeSingleton(key, container.getOne(), time);+ return 1;+ } else {+ // store to back-end; this should be a rare case+ return backend.addEntries(container, time);+ }+ } else {+ // we have a singleton and need to integrate this in the flush+ plasmaWordIndexEntry oldEntry = (plasmaWordIndexEntry) singleton[0];+ long oldTime = ((Long) singleton[1]).longValue();+ if (container.contains(oldEntry.getUrlHash())) {+ // we have an double-occurrence+ if (container.size() == 1) {+ // it is superfluous to flush this, simple do nothing+ return 0;+ } else {+ // we flush to the backend, and the entry from the singletons+ removeSingleton(key);+ return backend.addEntries(container, java.lang.Math.max(time, oldTime));+ }+ } else {+ // now we have more than one entry+ // we must remove the key from the singleton database+ removeSingleton(key);+ // .. and put it to the container+ container.add(oldEntry);+ if (reintegrate) {+ // put singleton together with container back to ram+ synchronized (cache) {+ cache.put(key, container);+ hashScore.setScore(key, container.size());+ hashDate.put(key, new Long(time));+ }+ return -1;+ } else {+ // add this to the backend+ return backend.addEntries(container, java.lang.Math.max(time, oldTime));+ }+ }+ }+ }++ private boolean flushFromSingleton(String key) {+ // this should only be called if the singleton shall be deleted or returned in an index entity+ Object[] singleton = readSingleton(key);+ if (singleton == null) {+ return false;+ } else {+ // we have a singleton+ plasmaWordIndexEntry entry = (plasmaWordIndexEntry) singleton[0];+ long time = ((Long) singleton[1]).longValue();+ // remove it from the singleton database+ removeSingleton(key);+ // integrate it to the backend+ return backend.addEntries(plasmaWordIndexEntryContainer.instantContainer(key, entry), time) > 0;+ }+ }++ private int flushFromMemToLimit() {+ if ((hashScore.size() == 0) && (cache.size() == 0)) {+ serverLog.logDebug("PLASMA INDEXING", "flushToLimit: called but cache is empty");+ return 0;+ }+ if ((hashScore.size() == 0) && (cache.size() != 0)) {+ serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=0 but cache.size=" + cache.size());+ return 0;+ }+ if ((hashScore.size() != 0) && (cache.size() == 0)) {+ serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=" + hashScore.size() + " but cache.size=0");+ return 0;+ }++ int count = 0;+ //serverLog.logDebug("PLASMA INDEXING", "flushSpecific: hashScore.size=" + hashScore.size() + ", cache.size=" + cache.size());+ synchronized (hashScore) {+ String key;+ Long createTime;++ // generate flush list+ Iterator i = hashScore.scores(true);+ TreeMap[] al = new TreeMap[hashScore.getMaxScore() + 1];+ for (int k = 0; k < al.length; k++) al[k] = new TreeMap(); // by create time ordered hash-list+ while (i.hasNext()) {+ // get the entry properties+ key = (String) i.next();+ createTime = (Long) hashDate.get(key);+ count = hashScore.getScore(key);++ // put it into a specific ohl+ al[count].put(createTime, key);+ //System.out.println("COUNT FOR KEY " + key + ": " + count);+ }++ // print statistics+ for (int k = 1; k < al.length; k++) log.logDebug("FLUSH-LIST " + k + ": " + al[k].size() + " entries");++ // flush singletons+ i = al[1].entrySet().iterator();+ Map.Entry entry;+ while (i.hasNext()) {+ entry = (Map.Entry) i.next();+ key = (String) entry.getValue();+ createTime = (Long) entry.getKey();+ if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) > 90000)) {+ //log.logDebug("flushing singleton-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size());+ count += flushFromMem((String) key, true);+ }+ }++ // flush high-scores+ for (int k = al.length - 1; k >= 2; k--) {+ i = al[k].entrySet().iterator();+ while (i.hasNext()) {+ entry = (Map.Entry) i.next();+ key = (String) entry.getValue();+ createTime = (Long) entry.getKey();+ if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) > (600000/k))) {+ //log.logDebug("flushing high-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size());+ count += flushFromMem(key, false);+ }+ if (count > 2000) return count;+ }+ }++ }+ return count;+ }++ public plasmaWordIndexEntity getIndex(String wordHash, boolean deleteIfEmpty) {+ flushFromMem(wordHash, false);+ flushFromSingleton(wordHash);+ return backend.getIndex(wordHash, deleteIfEmpty);+ }++ public long getCreationTime(String wordHash) {+ Long time = (Long) hashDate.get(wordHash);+ if (time == null) return 0;+ return time.longValue();+ }++ public void deleteIndex(String wordHash) {+ synchronized (cache) {+ cache.remove(wordHash);+ hashScore.deleteScore(wordHash);+ hashDate.remove(wordHash);+ }+ removeSingleton(wordHash);+ backend.deleteIndex(wordHash);+ }++ public synchronized int removeEntries(String wordHash, String[] urlHashes, boolean deleteComplete) {+ flushFromMem(wordHash, false);+ flushFromSingleton(wordHash);+ return backend.removeEntries(wordHash, urlHashes, deleteComplete);+ }++ public synchronized int addEntries(plasmaWordIndexEntryContainer container, long creationTime) {+ //serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem: cache.size=" + cache.size() + "; hashScore.size=" + hashScore.size());+ if (cache.size() >= this.maxWords) flushFromMemToLimit();+ //if (flushc > 0) serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem - flushed " + flushc + " entries");++ // put new words into cache+ int added = 0;+ synchronized (cache) {+ String wordHash = container.wordHash();+ plasmaWordIndexEntryContainer entries = (plasmaWordIndexEntryContainer) cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null+ if (entries == null) entries = new plasmaWordIndexEntryContainer(wordHash);+ added = entries.add(container);+ if (added > 0) {+ cache.put(wordHash, entries);+ hashScore.addScore(wordHash, added);+ hashDate.put(wordHash, new Long(creationTime));+ }+ }+ //System.out.println("DEBUG: cache = " + cache.toString());+ return added;+ }++ private void addEntry(String wordHash, plasmaWordIndexEntry newEntry, long creationTime) {+ plasmaWordIndexEntryContainer entries = (plasmaWordIndexEntryContainer) cache.get(wordHash);+ if (entries == null) entries = new plasmaWordIndexEntryContainer(wordHash);+ if (entries.add(newEntry)) {+ cache.put(wordHash, entries);+ hashScore.incScore(wordHash);+ hashDate.put(wordHash, new Long(creationTime));+ }+ }++ public void close(int waitingSeconds) {+ try {+ singletons.close();+ } catch (IOException e){+ log.logError("unable to close singleton database: " + e.getMessage());+ e.printStackTrace();+ }+ try {+ dump(waitingSeconds);+ } catch (IOException e){+ log.logError("unable to dump cache: " + e.getMessage());+ e.printStackTrace();+ }+ }++}diff --git a/source/de/anomic/server/serverCodings.java b/source/de/anomic/server/serverCodings.javaindex 7c6fe51f5..065381833 100644--- a/source/de/anomic/server/serverCodings.java+++ b/source/de/anomic/server/serverCodings.java@@ -54,12 +54,12 @@ public final class serverCodings {// the resulting string is filename-friendly, it contains no special character that is not// suitable for file names.- public static serverCodings standardCoder = new serverCodings(true);- public static serverCodings enhancedCoder = new serverCodings(false);+ public static final serverCodings standardCoder = new serverCodings(true);+ public static final serverCodings enhancedCoder = new serverCodings(false);- boolean rfc1113compliant;- public char[] alpha;- public byte[] ahpla;+ final boolean rfc1113compliant;+ public final char[] alpha;+ public final byte[] ahpla;public serverCodings(boolean rfc1113compliant) {// if we choose not to be rfc1113compliant,diff --git a/source/de/anomic/server/serverCore.java b/source/de/anomic/server/serverCore.javaindex 11b976f7f..ea67fcfc4 100644--- a/source/de/anomic/server/serverCore.java+++ b/source/de/anomic/server/serverCore.java@@ -64,6 +64,7 @@ import javax.net.ssl.SSLContext;import javax.net.ssl.SSLServerSocketFactory;import org.apache.commons.pool.impl.GenericObjectPool;+import org.apache.commons.pool.impl.GenericObjectPool.Config;public final class serverCore extends serverAbstractThread implements serverThread {@@ -81,7 +82,7 @@ public final class serverCore extends serverAbstractThread implements serverThre// class variablesprivate int port; // the listening portprivate ServerSocket socket; // listener- private int maxSessions = 0; // max. number of sessions; 0=unlimited+ public int maxSessions = 0; // max. number of sessions; 0=unlimitedserverLog log; // log objectprivate int timeout; // connection time-out of the socket@@ -101,6 +102,7 @@ public final class serverCore extends serverAbstractThread implements serverThre*/final SessionPool theSessionPool;final ThreadGroup theSessionThreadGroup = new ThreadGroup("sessionThreadGroup");+ private Config cralwerPoolConfig = null;private static ServerSocketFactory getServerSocketFactory(boolean dflt, File keyfile, String passphrase) {// see doc's at@@ -151,69 +153,78 @@ public final class serverCore extends serverAbstractThread implements serverThre// class initializerpublic serverCore(int port, int maxSessions, int timeout,- boolean termSleepingThreads, boolean blockAttack,- serverHandler handlerPrototype, serverSwitch switchboard,- int commandMaxLength, int logl) throws IOException {+ boolean termSleepingThreads, boolean blockAttack,+ serverHandler handlerPrototype, serverSwitch switchboard,+ int commandMaxLength, int logl) throws IOException {this.port = port;this.commandMaxLength = commandMaxLength;this.denyHost = (blockAttack) ? new Hashtable() : null;-+/*+ try {+ ServerSocketFactory ssf = getServerSocketFactory(false, new File("D:\\dev\\proxy\\addon\\testkeys"), "passphrase");+ this.socket = ssf.createServerSocket(port);+ //((SSLServerSocket) this.socket ).setNeedClientAuth(true);+ } catch (java.net.BindException e) {+ System.out.println("FATAL ERROR: " + e.getMessage() + " - probably root access rights needed. check port number"); System.exit(0);+ }+ */++try {- ServerSocketFactory ssf = getServerSocketFactory(false, new File("D:\\dev\\proxy\\addon\\testkeys"), "passphrase");- this.socket = ssf.createServerSocket(port);- //((SSLServerSocket) this.socket ).setNeedClientAuth(true);+ this.socket = new ServerSocket(port);} catch (java.net.BindException e) {System.out.println("FATAL ERROR: " + e.getMessage() + " - probably root access rights needed. check port number"); System.exit(0);}- */-- try {- this.socket = new ServerSocket(port);- } catch (java.net.BindException e) {- System.out.println("FATAL ERROR: " + e.getMessage() + " - probably root access rights needed. check port number"); System.exit(0);- }try {this.handlerPrototype = handlerPrototype;this.switchboard = switchboard;- this.initHandlerClasses = new Class[] {Class.forName("de.anomic.server.serverSwitch")};- this.initSessionClasses = new Class[] {Class.forName("de.anomic.server.serverCore$Session")};- this.maxSessions = maxSessions;- this.timeout = timeout;- this.termSleepingThreads = termSleepingThreads;+ this.initHandlerClasses = new Class[] {Class.forName("de.anomic.server.serverSwitch")};+ this.initSessionClasses = new Class[] {Class.forName("de.anomic.server.serverCore$Session")};+ this.maxSessions = maxSessions;+ this.timeout = timeout;+ this.termSleepingThreads = termSleepingThreads;this.log = new serverLog("SERVER", logl);-// activeThreads = new Hashtable();-// sleepingThreads = new Hashtable();- } catch (java.lang.ClassNotFoundException e) {- System.out.println("FATAL ERROR: " + e.getMessage() + " - Class Not Found"); System.exit(0);- }+// activeThreads = new Hashtable();+// sleepingThreads = new Hashtable();+ } catch (java.lang.ClassNotFoundException e) {+ System.out.println("FATAL ERROR: " + e.getMessage() + " - Class Not Found"); System.exit(0);+ }// implementation of session thread pool- GenericObjectPool.Config config = new GenericObjectPool.Config();+ this.cralwerPoolConfig = new GenericObjectPool.Config();// The maximum number of active connections that can be allocated from pool at the same time,// 0 for no limit- config.maxActive = this.maxSessions;+ this.cralwerPoolConfig.maxActive = this.maxSessions;// The maximum number of idle connections connections in the pool// 0 = no limit.- config.maxIdle = this.maxSessions / 2;- config.minIdle = this.maxSessions / 4;+ this.cralwerPoolConfig.maxIdle = this.maxSessions / 2;+ this.cralwerPoolConfig.minIdle = this.maxSessions / 4;// block undefinitely- config.maxWait = timeout;+ this.cralwerPoolConfig.maxWait = timeout;// Action to take in case of an exhausted DBCP statement pool// 0 = fail, 1 = block, 2= grow- config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;- config.minEvictableIdleTimeMillis = this.thresholdSleep;- config.testOnReturn = true;+ this.cralwerPoolConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;+ this.cralwerPoolConfig.minEvictableIdleTimeMillis = this.thresholdSleep;+ this.cralwerPoolConfig.testOnReturn = true;- this.theSessionPool = new SessionPool(new SessionFactory(this.theSessionThreadGroup),config);+ this.theSessionPool = new SessionPool(new SessionFactory(this.theSessionThreadGroup),this.cralwerPoolConfig);++ }+ public GenericObjectPool.Config getPoolConfig() {+ return this.cralwerPoolConfig ;}+ public void setPoolConfig(GenericObjectPool.Config newConfig) {+ this.theSessionPool.setConfig(newConfig);+ }+public static boolean isNotLocal(URL url) {return isNotLocal(url.getHost());}@@ -228,52 +239,58 @@ public final class serverCore extends serverAbstractThread implements serverThre}public static InetAddress publicIP() {- try {- // list all addresses- //InetAddress[] ia = InetAddress.getAllByName("localhost");- InetAddress[] ia = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());- //for (int i = 0; i < ia.length; i++) System.out.println("IP: " + ia[i].getHostAddress()); // DEBUG- if (ia.length == 0) {- try {- return InetAddress.getLocalHost();- } catch (UnknownHostException e) {- try {- return InetAddress.getByName("127.0.0.1");- } catch (UnknownHostException ee) {- return null;- }- }- }- if (ia.length == 1) {- // only one network connection available- return ia[0];- }- // we have more addresses, find an address that is not local- int b0, b1;- for (int i = 0; i < ia.length; i++) {- b0 = 0Xff & ia[i].getAddress()[0];- b1 = 0Xff & ia[i].getAddress()[1];- if ((b0 != 10) && // class A reserved- (b0 != 127) && // loopback- ((b0 != 172) || (b1 < 16) || (b1 > 31)) && // class B reserved- ((b0 != 192) || (b0 != 168)) && // class C reserved- (ia[i].getHostAddress().indexOf(":") < 0)- ) return ia[i];- }- // there is only a local address, we filter out the possibly returned loopback address 127.0.0.1- for (int i = 0; i < ia.length; i++) {- if (((0Xff & ia[i].getAddress()[0]) != 127) &&- (ia[i].getHostAddress().indexOf(":") < 0)) return ia[i];- }- // if all fails, give back whatever we have- for (int i = 0; i < ia.length; i++) {- if (ia[i].getHostAddress().indexOf(":") < 0) return ia[i];- }- return ia[0];- } catch (java.net.UnknownHostException e) {- System.err.println("ERROR: (internal) " + e.getMessage());- return null;- }+ try {++// TODO: implement port forwarding here ...+// if (portForwardingEnabled) {+//+// }++ // list all addresses+ //InetAddress[] ia = InetAddress.getAllByName("localhost");+ InetAddress[] ia = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());+ //for (int i = 0; i < ia.length; i++) System.out.println("IP: " + ia[i].getHostAddress()); // DEBUG+ if (ia.length == 0) {+ try {+ return InetAddress.getLocalHost();+ } catch (UnknownHostException e) {+ try {+ return InetAddress.getByName("127.0.0.1");+ } catch (UnknownHostException ee) {+ return null;+ }+ }+ }+ if (ia.length == 1) {+ // only one network connection available+ return ia[0];+ }+ // we have more addresses, find an address that is not local+ int b0, b1;+ for (int i = 0; i < ia.length; i++) {+ b0 = 0Xff & ia[i].getAddress()[0];+ b1 = 0Xff & ia[i].getAddress()[1];+ if ((b0 != 10) && // class A reserved+ (b0 != 127) && // loopback+ ((b0 != 172) || (b1 < 16) || (b1 > 31)) && // class B reserved+ ((b0 != 192) || (b0 != 168)) && // class C reserved+ (ia[i].getHostAddress().indexOf(":") < 0)+ ) return ia[i];+ }+ // there is only a local address, we filter out the possibly returned loopback address 127.0.0.1+ for (int i = 0; i < ia.length; i++) {+ if (((0Xff & ia[i].getAddress()[0]) != 127) &&+ (ia[i].getHostAddress().indexOf(":") < 0)) return ia[i];+ }+ // if all fails, give back whatever we have+ for (int i = 0; i < ia.length; i++) {+ if (ia[i].getHostAddress().indexOf(":") < 0) return ia[i];+ }+ return ia[0];+ } catch (java.net.UnknownHostException e) {+ System.err.println("ERROR: (internal) " + e.getMessage());+ return null;+ }}public void open() {diff --git a/source/de/anomic/server/serverObjects.java b/source/de/anomic/server/serverObjects.javaindex d0b8a36b5..72f4a01ff 100644--- a/source/de/anomic/server/serverObjects.java+++ b/source/de/anomic/server/serverObjects.java@@ -57,6 +57,7 @@package de.anomic.server;+import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;@@ -68,9 +69,13 @@ import java.util.Vector;public final class serverObjects extends Hashtable implements Cloneable {public serverObjects() {- super();+ super();}-++ public serverObjects(int initialCapacity) {+ super(initialCapacity);+ }+public serverObjects(Map input) {super(input);}@@ -157,16 +162,24 @@ public final class serverObjects extends Hashtable implements Cloneable {// convenience methods for storing and loading to a file systempublic void store(File f) throws IOException {- FileOutputStream fos = new FileOutputStream(f);- Enumeration e = keys();- String key, value;- while (e.hasMoreElements()) {- key = (String) e.nextElement();- value = ((String) get(key)).replaceAll("\n", "\\\\n");- fos.write((key + "=" + value + "\r\n").getBytes());- }- fos.flush();- fos.close();+ BufferedOutputStream fos = null;+ try {+ fos = new BufferedOutputStream(new FileOutputStream(f));+ Enumeration e = keys();+ String key, value;+ while (e.hasMoreElements()) {+ key = (String) e.nextElement();+ value = ((String) get(key)).replaceAll("\n", "\\\\n");+ fos.write((key + "=" + value + "\r\n").getBytes());+ }+ } finally {+ if (fos != null) {+ try {+ fos.flush();+ fos.close();+ } catch (Exception e){}+ }+ }}public Object clone() {diff --git a/source/de/anomic/soap/build.xml b/source/de/anomic/soap/build.xmlnew file mode 100644index 000000000..bf469d41e--- /dev/null+++ b/source/de/anomic/soap/build.xml@@ -0,0 +1,53 @@+<?xml version="1.0"?>+<project name="YACY - SOAP API" default="dist">+ <description>+ A SOAP API for Yacy+ </description>++ <property name="addonShortName" value="Soap"/>+ <property name="addonVersion" value="0.1"/>++ <property name="addonLongName" value="${addonShortName}Addon"/>+ <property name="addonArchive" location="${release}/${addonLongName}_${addonVersion}.tgz"/>++ <target name="compile">+ <echo message="Compiling ${addonLongName} Version ${addonVersion} ..."/>+ <javac srcdir="${src}/de/anomic/soap/" destdir="${build}" source="${javacSource}" target="${javacTarget}">+ <classpath>+ <pathelement location="${build}" />++ <!-- all needed libs -->+ <pathelement location="${libx}/axis.jar" />+ <pathelement location="${libx}/axis-ant.jar" />+ <pathelement location="${libx}/commons-discovery.jar" />+ <pathelement location="${libx}/commons-logging.jar" />+ <pathelement location="${libx}/jaxrpc.jar" />+ <pathelement location="${libx}/saaj.jar" />+ <pathelement location="${libx}/wsdl4j.jar" />+ </classpath>+ </javac>+ </target>+++ <target name="zip" depends="compile">+ <echo message="Compressing ${addonLongName} Version ${addonVersion} ..."/>+ <tar destfile="${addonArchive}" compression="gzip">+ <tarfileset dir="${libx}"+ includes="axis.jar,axis-ant.jar,commons-discovery.jar,commons-logging.jar,jaxrpc.jar,saaj.jar,wsdl4j.jar"+ prefix="libx/"+ dirmode="755" mode="644"/>+ <tarfileset dir="${src}/de/anomic/soap/"+ prefix="source/de/anomic/soap/"+ dirmode="755" mode="644"/>+ <tarfileset dir="${build}/de/anomic/soap/"+ prefix="classes/de/anomic/soap/"+ dirmode="755" mode="644"/>+ </tar>+ </target>+++ <target name="dist" depends="compile,zip" description="Compile and zip the addon"/>+++</project>+diff --git a/source/de/anomic/soap/httpdSoapHandler.java b/source/de/anomic/soap/httpdSoapHandler.javanew file mode 100644index 000000000..aba633c47--- /dev/null+++ b/source/de/anomic/soap/httpdSoapHandler.java@@ -0,0 +1,513 @@+package de.anomic.soap;++import java.io.ByteArrayInputStream;+import java.io.File;+import java.io.IOException;+import java.io.InputStream;+import java.io.OutputStream;+import java.io.PushbackInputStream;+import java.util.Date;+import java.util.HashMap;+import java.util.Properties;++import javax.xml.namespace.QName;+import javax.xml.parsers.ParserConfigurationException;++import org.apache.axis.Constants;+import org.apache.axis.EngineConfiguration;+import org.apache.axis.Message;+import org.apache.axis.MessageContext;+import org.apache.axis.WSDDEngineConfiguration;+import org.apache.axis.deployment.wsdd.WSDDDeployment;+import org.apache.axis.deployment.wsdd.WSDDDocument;+import org.apache.axis.server.AxisServer;+import org.apache.axis.utils.XMLUtils;+import org.w3c.dom.Document;+import org.xml.sax.SAXException;++import de.anomic.http.httpHeader;+import de.anomic.http.httpc;+import de.anomic.http.httpdAbstractHandler;+import de.anomic.http.httpdHandler;+import de.anomic.server.serverClassLoader;+import de.anomic.server.serverFileUtils;+import de.anomic.server.serverSwitch;++/**+ * Class to accept SOAP Requests and invoke the desired {@link de.anomic.http.httpdSoapService soapService}.+ * An example how to do a soap call from php:+ * <code>+ * <?php+ * $client = new SoapClient("http://192.168.1.201:8080/soap/index?wsdl", array(+ * "trace" => 1,+ * "exceptions" => 1));+ *+ * try+ * {+ * $result = $client->__call("crawling", array("http://test.at"), NULL,+ * new SoapHeader("http://http.anomic.de/header", "Authorization", md5(base64_encode("admin:xxxxxxx"))));+ * }+ * catch (SoapFault $fault)+ * {+ * $result = $fault->faultstring;+ * }+ *+ * print($result);+ * ?>+ * </code>+ *+ *+ *+ * @author Martin Thelian+ */+final class httpdSoapHandler extends httpdAbstractHandler implements httpdHandler+{++ /* ===============================================================+ * Constants needed to set some SOAP properties+ * =============================================================== */+ /**+ * SOAP Header Namespace needed to access the soap header field containing+ * the user authentication+ */+ public static final String serviceHeaderNamespace = "http://http.anomic.de/header";++ /**+ * define the needed deployment strings+ */+ public static final String serviceDeploymentString =+ "<deployment "+ + "xmlns=\"http://xml.apache.org/axis/wsdd/\" "+ + "xmlns:java=\"http://xml.apache.org/axis/wsdd/providers/java\" >"+ + "<service name=\"index\" provider=\"java:RPC\" >"+ + "<parameter name=\"className\" value=\"" + httpdSoapService.class.getName() + "\" />"+ + "<parameter name=\"allowedMethods\" value=\"*\" />"+ + "</service>"+ + "</deployment>";++ /* ===============================================================+ * Constants needed to set the SOAP message context+ * =============================================================== */+ /**+ * CONSTANT: the http root path+ */+ public static final String MESSAGE_CONTEXT_HTTP_ROOT_PATH = "htRootPath";+ /**+ * CONSTANT: tge server switchboard+ */+ public static final String MESSAGE_CONTEXT_SERVER_SWITCH = "serverSwitch";+ /**+ * CONSTANT: received http headers+ */+ public static final String MESSAGE_CONTEXT_HTTP_HEADER = "httpHeader";+ /**+ * CONSTANT: the server classloader+ */+ public static final String MESSAGE_CONTEXT_SERVER_CLASSLOADER = "serverClassLoader";+ /**+ * CONSTANT: available templates+ */+ public static final String MESSAGE_CONTEXT_TEMPLATES = "templates";++ /* ===============================================================+ * Other object fields+ * =============================================================== */+ private serverClassLoader provider = null;+ private HashMap templates;+ private serverSwitch switchboard;++ private static AxisServer engine = null;+ private File htRootPath;+ private File htTemplatePath;++ /*+ * Creating and configuring an apache Axis server.+ * This is only needed once.+ */+ static+ {+ // create an Axis server+ engine = new AxisServer();++ // setting some options ...+ engine.setShouldSaveConfig(false);++ // deploy the service+ deployService(serviceDeploymentString,engine);+ }++ /**+ * Constructor of this class+ * @param switchboard+ */+ public httpdSoapHandler(serverSwitch switchboard)+ {+ super();++ this.switchboard = switchboard;++ // create a htRootPath: system pages+ if (this.htRootPath == null) {+ this.htRootPath = new File(this.switchboard.getRootPath(), this.switchboard.getConfig("htRootPath","htroot"));+ // if (!(htRootPath.exists())) htRootPath.mkdir();+ }++ if (this.htTemplatePath == null) {+ this.htTemplatePath = new File(switchboard.getRootPath(), switchboard.getConfig("htTemplatePath","htroot/env/templates"));+ // if (!(this.htTemplatePath.exists())) this.htTemplatePath.mkdir();+ }++ if (this.provider == null) {+ this.provider = new serverClassLoader(/*this.getClass().getClassLoader()*/);+ }++ if (this.templates == null) this.templates = loadTemplates(this.htTemplatePath);+ }++ /**+ * Handle http-GET requests. For soap this is usually a query for the wsdl-file.+ * Therefore we always return the wsdl file for a get request+ *+ * @param conProp+ * @param requestHeader all received http headers+ * @param response {@link OutputStream} to the client+ *+ * @throws IOException+ *+ * @see de.anomic.http.httpdHandler#doGet(java.util.Properties, de.anomic.http.httpHeader, java.io.OutputStream)+ */+ public void doGet(Properties conProp, httpHeader requestHeader, OutputStream response) throws IOException+ {+ String path = conProp.getProperty("PATH");+ try+ {+ MessageContext msgContext = this.generateMessageContext(path, requestHeader);++ engine.generateWSDL(msgContext);+ Document doc = (Document) msgContext.getProperty("WSDL");++ if (doc != null)+ {+ // Converting the the wsdl document into a byte-array+ String responseDoc = XMLUtils.DocumentToString(doc);+ byte[] result = responseDoc.getBytes();++ /*+ * Setting the response header+ * - Status: 200 OK+ * - Content Type: text/xml+ * - Encoding: UTF8+ * - Date: current Date+ */+ respondHeader(response, 200, "text/xml; charset=utf-8", result.length, new Date(), null, null);++ // writing out the data+ Thread.currentThread().join(200);+ serverFileUtils.write(result, response);+ response.flush();++ if (!(requestHeader.get("Connection", "close").equals("keep-alive"))) {+ // wait a little time until everything closes so that clients can read from the streams/sockets+ try {Thread.currentThread().join(1000);} catch (InterruptedException e) {}+ }+ }++ // if we where unable to generate the wsdl file ....+ else+ {+ String errorMsg = "Internal Server Error: Unable to generate the WSDL file.";+ respondHeader(response, 500, "text/plain", errorMsg.length(), httpc.nowDate(), null, null);+ response.write(errorMsg.getBytes());+ response.flush();+ }++ return;+ }+ catch (Exception e)+ {+ System.out.println("ERROR: Exception with query: " + path + "; '" + e.toString() + ":" + e.getMessage() + "'\r\n");+ }++ }++ /**+ * HTTP HEAD method. Not needed for soap.+ * @param conProp+ * @param header+ * @param response+ * @throws IOException+ *+ * @see de.anomic.http.httpdHandler#doHead(java.util.Properties, de.anomic.http.httpHeader, java.io.OutputStream)+ */+ public void doHead(Properties conProp, httpHeader header, OutputStream response) throws IOException+ {+ // the http HEAD method is not allowed for this SOAP API+ String errorMsg = "Method Not Allowed";+ respondHeader(response, 405, "text/plain", errorMsg.length(), httpc.nowDate(), null, null);+ response.write(errorMsg.getBytes());+ response.flush();+ }++ /**+ * HTTP Post method. Needed to call a soap service on this server from a soap client+ * @param conProp the connection properties+ * @param requestHeader the received http headers+ * @param response {@link OutputStream} to the client+ * @param body the request body containing the SOAP message+ *+ * @throws IOException+ *+ * @see de.anomic.http.httpdHandler#doPost(java.util.Properties, de.anomic.http.httpHeader, java.io.OutputStream, java.io.PushbackInputStream)+ */+ public void doPost(Properties conProp, httpHeader requestHeader, OutputStream response, PushbackInputStream body) throws IOException+ {+ String path = conProp.getProperty("PATH");+ try+ {+ /*+ * Converting the request body into a bytehstream needed by the apache+ * axis engine+ */+ int contentLength = requestHeader.containsKey("CONTENT-LENGTH")?+ Integer.parseInt((String) requestHeader.get("CONTENT-LENGTH")):+ 0;++ byte[] buffer = new byte[contentLength];+ body.read(buffer);+ InputStream soapInputStream = new ByteArrayInputStream(buffer);++ /*+ * generating the SOAP message context that will be passed over to the invoked+ * service+ */+ MessageContext msgContext = this.generateMessageContext(path, requestHeader);++ /*+ * Generating a SOAP Request Message Object from the XML document+ * and store it into the message context+ */+ Message requestMsg = new Message(soapInputStream, false, "text/xml;charset=\"utf-8\"", "");+ msgContext.setRequestMessage(requestMsg);++ // invoke the service+ engine.invoke(msgContext);++ // Retrieve the response from Axis+ Message responseMsg = msgContext.getResponseMessage();++ if (responseMsg != null)+ {+ respondHeader(response, 200, "text/xml; charset=utf-8", responseMsg.getContentLength(), new Date(), null, null);+ Thread.currentThread().join(200);+ responseMsg.writeTo(response);+ response.flush();+ }+ else+ {+ String errorMsg = "Internal Server Error: Unable to invoke the requested service.";+ respondHeader(response, 500, "text/plain", errorMsg.length(), httpc.nowDate(), null, null);+ response.write(errorMsg.getBytes());+ response.flush();+ }++ return;+ }+ catch (Exception e)+ {+ System.out.println("ERROR: Exception with query: " + path + "; '" + e.toString() + ":" + e.getMessage() + "'\r\n");+ }+ }++ /**+ * HTTP Connect Method. Not needed for SOAP+ * @param conProp+ * @param requestHeader+ * @param clientIn+ * @param clientOut+ * @throws IOException+ *+ * @see de.anomic.http.httpdHandler#doConnect(java.util.Properties, de.anomic.http.httpHeader, java.io.InputStream, java.io.OutputStream)+ */+ public void doConnect(Properties conProp, httpHeader requestHeader, InputStream clientIn, OutputStream clientOut) throws IOException+ {+ // the CONNECT method is not allowed for this SOAP API+ String errorMsg = "Method Not Allowed";+ respondHeader(clientOut, 405, "text/plain", errorMsg.length(), httpc.nowDate(), null, null);+ clientOut.write(errorMsg.getBytes());+ clientOut.flush();+ }++ /**+ * This function deplays all java classes that should be available via SOAP call.+ *+ * @param deploymentString the deployment string containing detailed information about+ * the java class that should be deployed+ * @param theAxisServer the apache axis engine where the service should be deployed+ *+ * @return <code>true</code> if the deployment was done successfully or <code>false</code>+ * otherwise+ */+ private static boolean deployService(String deploymentString, AxisServer theAxisServer)+ {+ // convert WSDD file string into bytestream for furhter processing+ InputStream deploymentStream = null;+ if (deploymentString != null)+ {+ deploymentStream = new ByteArrayInputStream(deploymentString.getBytes());++ Document root = null;++ try+ {+ // build XML document from stream+ root = XMLUtils.newDocument(deploymentStream);++ // parse WSDD file+ WSDDDocument wsddDoc = new WSDDDocument(root);++ // get the configuration of this axis engine+ EngineConfiguration config = theAxisServer.getConfig();++ if (config instanceof WSDDEngineConfiguration)+ {+ // get the current configuration of the Axis engine+ WSDDDeployment deploymentWSDD =+ ((WSDDEngineConfiguration) config).getDeployment();++ // undeply unneeded standard services+ deploymentWSDD.undeployService(new QName("Version"));+ deploymentWSDD.undeployService(new QName("AdminService"));++ // deploy the new service+ // an existing service with the same name gets deleted+ wsddDoc.deploy(deploymentWSDD);+ }+ }+ catch (ParserConfigurationException e)+ {+ System.err.println("Could not deploy service.");+ return false;+ }+ catch (SAXException e)+ {+ System.err.println("Could not deploy service.");+ return false;+ }+ catch (IOException e)+ {+ System.err.println("Could not deploy service.");+ return false;+ }+ }+ else+ {+ System.err.println("Service deployment string is NULL! SOAP Service not deployed.");+ return false;+ }+ return true;+ }++ /**+ * This function is used to generate the SOAP Message Context that is handed over to+ * the called service.+ * This message context contains some fields needed by the service to fullfil the request.+ *+ * @param path the path of the request+ * @param requestHeader the http headers of the request+ *+ * @return the generated {@link MessageContext}+ *+ * @throws Exception if the {@link MessageContext} could not be generated successfully.+ */+ private MessageContext generateMessageContext(String path, httpHeader requestHeader)+ throws Exception+ {+ try+ {+ // create and initialize a message context+ MessageContext msgContext = new MessageContext(httpdSoapHandler.engine);+ msgContext.setTransportName("SimpleHTTP");+ msgContext.setProperty(org.apache.axis.Constants.MC_REALPATH, path.toString());+ msgContext.setProperty(Constants.MC_RELATIVE_PATH, path.toString());+ msgContext.setProperty(Constants.MC_JWS_CLASSDIR, "jwsClasses");+ msgContext.setProperty(Constants.MC_HOME_DIR, ".");+ msgContext.setProperty(MessageContext.TRANS_URL, "http://" + requestHeader.get("Host") + this.switchboard.getConfig("port","8080") + "/soap/index");++ msgContext.setProperty(MESSAGE_CONTEXT_HTTP_ROOT_PATH ,this.htRootPath.toString());+ msgContext.setProperty(MESSAGE_CONTEXT_SERVER_SWITCH,this.switchboard);+ msgContext.setProperty(MESSAGE_CONTEXT_HTTP_HEADER ,requestHeader);+ msgContext.setProperty(MESSAGE_CONTEXT_SERVER_CLASSLOADER ,this.provider);+ msgContext.setProperty(MESSAGE_CONTEXT_TEMPLATES ,this.templates);++ msgContext.setTargetService(path.substring(6));++ return msgContext;+ }+ catch (Exception e)+ {+ throw new Exception ("Unable to generate the message context. ",e);+ }+ }++ /**+ * This method was copied from {@link httpdFileHandler}. Maybe it would be a good idea+ * to move this function up into {@link httpdAbstractHandler}+ *+ * @param path the path to the template dir+ * @return a hasmap containing all templates+ */+ private static HashMap loadTemplates(File path) {+ // reads all templates from a path+ // we use only the folder from the given file path+ HashMap result = new HashMap();+ if (path == null) return result;+ if (!(path.isDirectory())) path = path.getParentFile();+ if ((path == null) || (!(path.isDirectory()))) return result;+ String[] templates = path.list();+ int c;+ for (int i = 0; i < templates.length; i++) {+ if (templates[i].endsWith(".template")) try {+ //System.out.println("TEMPLATE " + templates[i].substring(0, templates[i].length() - 9) + ": " + new String(buf, 0, c));+ result.put(templates[i].substring(0, templates[i].length() - 9),+ new String(serverFileUtils.read(new File(path, templates[i]))));+ } catch (Exception e) {}+ }+ return result;+ }++ /**+ * This method was copied from {@link httpdFileHandler}. Maybe it would be a good idea+ * to move this function up into {@link httpdAbstractHandler}+ *+ * @param out the {@link OutputStream} to the client+ * @param retcode the http code+ * @param conttype the content type and encoding+ * @param contlength the content length+ * @param moddate the modification date of the content+ * @param expires the date of expiry of the content+ * @param cookie cookies to be send+ *+ * @throws IOException+ */+ protected void respondHeader(OutputStream out, int retcode, String conttype, long contlength, Date moddate, Date expires, String cookie) throws IOException+ {+ try {+ out.write(("HTTP/1.1 " + retcode + " OK\r\n").getBytes());+ out.write(("Server: AnomicHTTPD (www.anomic.de)\r\n").getBytes());+ out.write(("Date: " + httpc.dateString(httpc.nowDate()) + "\r\n").getBytes());+ if (expires != null) out.write(("Expires: " + httpc.dateString(expires) + "\r\n").getBytes());+ out.write(("Content-type: " + conttype /* "image/gif", "text/html" */ + "\r\n").getBytes());+ out.write(("Last-modified: " + httpc.dateString(moddate) + "\r\n").getBytes());+ out.write(("Content-length: " + contlength +"\r\n").getBytes());+ out.write(("Pragma: no-cache\r\n").getBytes());+ // out.write(("Accept-ranges: bytes\r\n").getBytes());+ if (cookie != null) out.write(("Set-Cookie: " + cookie + "\r\n").getBytes());+ out.write(("\r\n").getBytes());+ out.flush();+ } catch (Exception e) {+ // any interruption may be caused be network error or because the user has closed+ // the windows during transmission. We simply pass it as IOException+ throw new IOException(e.getMessage());+ }+ }+}diff --git a/source/de/anomic/soap/httpdSoapService.java b/source/de/anomic/soap/httpdSoapService.javanew file mode 100644index 000000000..4068486da--- /dev/null+++ b/source/de/anomic/soap/httpdSoapService.java@@ -0,0 +1,339 @@+package de.anomic.soap;++import java.io.ByteArrayOutputStream;+import java.io.File;+import java.io.FileInputStream;+import java.io.IOException;+import java.lang.reflect.Method;+import java.util.Arrays;+import java.util.HashMap;+import java.util.HashSet;++import org.apache.axis.AxisFault;+import org.apache.axis.Message;+import org.apache.axis.MessageContext;+import org.apache.axis.message.SOAPEnvelope;+import org.apache.axis.message.SOAPHeaderElement;++import de.anomic.http.httpHeader;+import de.anomic.http.httpTemplate;+import de.anomic.server.serverClassLoader;+import de.anomic.server.serverCodings;+import de.anomic.server.serverObjects;+import de.anomic.server.serverSwitch;++/**+ * SOAP Service Class that will be invoked by the {@link de.anomic.http.httpdSoapHandler}+ *+ * @author Martin Thelian+ */+final public class httpdSoapService+{+ /* ================================================================+ * Constants needed to set the template that should be used to+ * fullfil the request+ * ================================================================ */+ /**+ * Constant: template for searching+ */+ private static final String TEMPLATE_SEARCH = "index.rss";+ /**+ * Constant: template for the network status page+ */+ private static final String TEMPLATE_NETWORK_XML = "Network.xml";+ /**+ * Constant: template for crawling+ */+ private static final String TEMPLATE_CRAWLING = "IndexCreate_p.html";++ /* ================================================================+ * Other Object fields+ * ================================================================ */+ /**+ * A hashset containing all templates that requires user authentication+ */+ private static final HashSet SERVICE_NEEDS_AUTHENTICATION = new HashSet(Arrays.asList(new String[]+ {TEMPLATE_CRAWLING}));++ private String rootPath;+ private serverClassLoader provider;+ private HashMap templates;+ private serverSwitch switchboard;+ private httpHeader requestHeader;+ private MessageContext messageContext;+++ /**+ * Constructor of this class+ */+ public httpdSoapService()+ {+ super();++ // nothing special todo here at the moment+ }++ /**+ * Service for doing a simple search with the standard settings+ *+ * @param searchString the search string that should be used+ * @return an rss document containing the search results.+ *+ * @throws AxisFault if the service could not be executed propery.+ */+ public String search(String searchString)+ throws AxisFault+ {+ try+ {+ // extracting the message context+ extractMessageContext();++ // setting the searching properties+ serverObjects args = new serverObjects();+ args.put("order","Quality-Date");+ args.put("Enter","Search");+ args.put("count","10");+ args.put("resource","global");+ args.put("time","10");+ args.put("urlmaskfilter",".*");++ args.put("search",searchString);++ // generating the template containing the search result+ String result = writeTemplate(TEMPLATE_SEARCH, args);++ // sending back the result to the client+ return result;+ }+ catch (Exception e)+ {+ throw new AxisFault(e.getMessage());+ }+ }++ /**+ * Service used to query the network properties+ * @throws AxisFault if the service could not be executed propery.+ */+ public String network() throws AxisFault+ {+ try+ {+ // extracting the message context+ extractMessageContext();++ // generating the template containing the network status information+ String result = writeTemplate(TEMPLATE_NETWORK_XML, new serverObjects());++ // sending back the result to the client+ return result;+ }+ catch (Exception e)+ {+ throw new AxisFault(e.getMessage());+ }+ }++ /**+ * Service used start a new crawling job using the default settings for crawling+ *+ * @return returns the http status page containing the crawling properties to the user+ * TODO: creating an extra xml template that can be send back to the client.+ *+ * @throws AxisFault if the service could not be executed propery.+ */+ public String crawling(String crawlingURL) throws AxisFault+ {+ try+ {+ // extracting the message context+ extractMessageContext();++ // setting the crawling properties+ serverObjects args = new serverObjects();+ args.put("crawlingQ","on");+ args.put("xsstopw","on");+ args.put("crawlOrder","on");+ args.put("crawlingstart","Start New Crawl");+ args.put("crawlingDepth","2");+ args.put("crawlingFilter",".*");+ args.put("storeHTCache","on");+ args.put("localIndexing","on");+ args.put("crawlingURL",crawlingURL);++ // triggering the crawling+ String result = writeTemplate(TEMPLATE_CRAWLING, args);++ // sending back the crawling status page to the user+ return result;+ }+ catch (Exception e)+ {+ throw new AxisFault(e.getMessage());+ }+ }++ /**+ * This function is called by the available service functions to+ * extract all needed informations from the SOAP message context.+ */+ private void extractMessageContext()+ {+ this.messageContext = MessageContext.getCurrentContext();++ this.rootPath = (String) this.messageContext.getProperty(httpdSoapHandler.MESSAGE_CONTEXT_HTTP_ROOT_PATH);+ this.provider = (serverClassLoader) this.messageContext.getProperty(httpdSoapHandler.MESSAGE_CONTEXT_SERVER_CLASSLOADER);+ this.templates = (HashMap) this.messageContext.getProperty(httpdSoapHandler.MESSAGE_CONTEXT_TEMPLATES);+ this.switchboard = (serverSwitch) this.messageContext.getProperty(httpdSoapHandler.MESSAGE_CONTEXT_SERVER_SWITCH);+ this.requestHeader = (httpHeader) this.messageContext.getProperty(httpdSoapHandler.MESSAGE_CONTEXT_HTTP_HEADER);+ }++ /**+ * This function is called by the service functions to+ * invoke the desired server-internal method and to generate+ * a output document using one of the available templates.+ *+ * @param templateName+ * @param args+ * @return+ * @throws AxisFault+ */+ private String writeTemplate(String templateName, serverObjects args)+ throws AxisFault+ {+ try+ {+ // determining the proper class that should be invoked+ File file = new File(this.rootPath, templateName);+ File rc = rewriteClassFile(file);++ if (SERVICE_NEEDS_AUTHENTICATION.contains(templateName))+ {+ this.doAuthentication();+ }++ // invoke the desired method+ serverObjects tp = (serverObjects) rewriteMethod(rc).invoke(null, new Object[] {this.requestHeader, args, this.switchboard});++ // testing if a authentication was needed by the invoked method+ validateAuthentication(tp);++ // adding all available templates+ tp.putAll(this.templates);++ // generating the output document+ ByteArrayOutputStream o = new ByteArrayOutputStream();+ FileInputStream fis = new FileInputStream(file);+ httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes());+ o.close();+ fis.close();++ // convert it into a byte array and send it back as result+ byte[] result = o.toByteArray();+ return new String(result);+ }+ catch (Exception e)+ {+ throw new AxisFault(e.getMessage());+ }+ }++ /**+ * This function is used to test if an invoked method requires authentication+ *+ * @param tp the properties returned by a previous method invocation+ *+ * @throws AxisFault if an authentication was required.+ */+ private void validateAuthentication(serverObjects tp)+ throws AxisFault+ {+ // check if the servlets requests authentification+ if (tp.containsKey("AUTHENTICATE"))+ {+ throw new AxisFault("log-in required");+ }+ }++ /**+ * Doing the user authentication. To improve security, this client+ * accepts the base64 encoded and md5 hashed password directly.+ *+ * @throws AxisFault if the authentication could not be done successfully+ */+ private void doAuthentication()+ throws AxisFault+ {+ // accessing the SOAP request message+ Message message = this.messageContext.getRequestMessage();++ // getting the contained soap envelope+ SOAPEnvelope envelope = message.getSOAPEnvelope();++ // getting the proper soap header containing the authorization field+ SOAPHeaderElement authElement = envelope.getHeaderByName(httpdSoapHandler.serviceHeaderNamespace, "Authorization");+ if (authElement != null)+ {+ // the base64 encoded and md5 hashed authentication string+ String authString = authElement.getValue();++ String adminAccountBase64MD5 = this.switchboard.getConfig("adminAccountBase64MD5","");+ if (adminAccountBase64MD5.length() == 0)+ {+ throw new AxisFault("log-in required");+ }+ else if (!(adminAccountBase64MD5.equals(authString)))+ {+ throw new AxisFault("log-in required");+ }+ }+ else throw new AxisFault("log-in required");+ }++ /**+ * This method was copied from the {@link httpdFileHandler httpdFileHandler-class}+ * @param template+ * @return+ */+ private File rewriteClassFile(File template) {+ try {+ String f = template.getCanonicalPath();+ int p = f.lastIndexOf(".");+ if (p < 0) return null;+ f = f.substring(0, p) + ".class";+ //System.out.println("constructed class path " + f);+ File cf = new File(f);+ if (cf.exists()) return cf;+ return null;+ } catch (IOException e) {+ return null;+ }+ }++ /**+ * This method was copied from the {@link httpdFileHandler httpdFileHandler-class}+ * @param classFile+ * @return+ */+ private Method rewriteMethod(File classFile) {+ Method m = null;+ // now make a class out of the stream+ try {+ //System.out.println("**DEBUG** loading class file " + classFile);+ Class c = provider.loadClass(classFile);+ Class[] params = new Class[] {+ Class.forName("de.anomic.http.httpHeader"),+ Class.forName("de.anomic.server.serverObjects"),+ Class.forName("de.anomic.server.serverSwitch")};+ m = c.getMethod("respond", params);+ } catch (ClassNotFoundException e) {+ System.out.println("INTERNAL ERROR: class " + classFile + " is missing:" + e.getMessage());+ } catch (NoSuchMethodException e) {+ System.out.println("INTERNAL ERROR: method respond not found in class " + classFile + ": " + e.getMessage());+ }+ //System.out.println("found method: " + m.toString());+ return m;+ }++}diff --git a/source/de/anomic/yacy/seedUpload/yacySeedUploadFile.java b/source/de/anomic/yacy/seedUpload/yacySeedUploadFile.javanew file mode 100644index 000000000..b63de716c--- /dev/null+++ b/source/de/anomic/yacy/seedUpload/yacySeedUploadFile.java@@ -0,0 +1,38 @@+package de.anomic.yacy.seedUpload;++import java.io.File;+import java.net.URL;++import de.anomic.server.serverFileUtils;+import de.anomic.server.serverSwitch;+import de.anomic.yacy.yacySeedDB;+import de.anomic.yacy.yacySeedUploader;++public class yacySeedUploadFile implements yacySeedUploader {++ public static final String CONFIG_FILE_PATH = "seedFilePath";++ public String uploadSeedFile(serverSwitch sb, yacySeedDB seedDB, File seedFile) {++ String logt;+ try {+ String seedFilePath = sb.getConfig(CONFIG_FILE_PATH,null);+ if (seedFilePath == null) return "Error: Path to seed file is not configured properly";++ File publicSeedFile = new File(seedFilePath);+ serverFileUtils.copy(seedFile,publicSeedFile);++ return "Seed-List file stored successfully";+ } catch (Exception e) {+ return "Error: " + e.getMessage();+ }+ }++ public String[] getConfigurationOptions() {+ return new String[]{CONFIG_FILE_PATH};+ }++ public String[] getLibxDependences() {+ return new String[]{};+ }+}diff --git a/source/de/anomic/yacy/seedUpload/yacySeedUploadFtp.java b/source/de/anomic/yacy/seedUpload/yacySeedUploadFtp.javanew file mode 100644index 000000000..13d9d9224--- /dev/null+++ b/source/de/anomic/yacy/seedUpload/yacySeedUploadFtp.java@@ -0,0 +1,48 @@+package de.anomic.yacy.seedUpload;++import java.io.File;++import de.anomic.net.ftpc;+import de.anomic.server.serverSwitch;+import de.anomic.yacy.yacySeedDB;+import de.anomic.yacy.yacySeedUploader;++public class yacySeedUploadFtp implements yacySeedUploader {++ public static final String CONFIG_FTP_SERVER = "seedFTPServer";+ public static final String CONFIG_FTP_ACCOUNT = "seedFTPAccount";+ public static final String CONFIG_FTP_PASSWORD = "seedFTPPassword";+ public static final String CONFIG_FTP_PATH = "seedFTPPath";++ public String uploadSeedFile (serverSwitch sb, yacySeedDB seedDB, File seedFile) {+ try {+ if (sb == null) throw new NullPointerException("Reference to serverSwitch nut not be null.");+ if (seedDB == null) throw new NullPointerException("Reference to seedDB must not be null.");+ if ((seedFile == null)||(!seedFile.exists())) throw new Exception("Seed file does not exist.");++ String seedFTPServer = sb.getConfig(CONFIG_FTP_SERVER,null);+ String seedFTPAccount = sb.getConfig(CONFIG_FTP_ACCOUNT,null);+ String seedFTPPassword = sb.getConfig(CONFIG_FTP_PASSWORD,null);+ File seedFTPPath = new File(sb.getConfig(CONFIG_FTP_PATH,null));++ if ((seedFTPServer != null) && (seedFTPAccount != null) && (seedFTPPassword != null) && (seedFTPPath != null)) {+ String log = ftpc.put(seedFTPServer, seedFile, seedFTPPath.getParent(), seedFTPPath.getName(), seedFTPAccount, seedFTPPassword);+ return log;+ }+ return "Seed upload settings not configured properly. password-len=" ++ seedFTPPassword.length() + ", filePath=" ++ seedFTPPath;+ } catch (Exception e) {+ return "Error: " + e.getMessage();+ }+ }++ public String[] getConfigurationOptions() {+ return new String[] {CONFIG_FTP_SERVER,CONFIG_FTP_ACCOUNT,CONFIG_FTP_PASSWORD,CONFIG_FTP_PATH};+ }++ public String[] getLibxDependences() {+ return new String[]{};+ }++}diff --git a/source/de/anomic/yacy/seedUpload/yacySeedUploadScp.java b/source/de/anomic/yacy/seedUpload/yacySeedUploadScp.javanew file mode 100644index 000000000..c662dc027--- /dev/null+++ b/source/de/anomic/yacy/seedUpload/yacySeedUploadScp.java@@ -0,0 +1,254 @@+package de.anomic.yacy.seedUpload;++import java.io.File;+import java.io.FileInputStream;+import java.io.IOException;+import java.io.InputStream;+import java.io.OutputStream;++import com.jcraft.jsch.Channel;+import com.jcraft.jsch.ChannelExec;+import com.jcraft.jsch.JSch;+import com.jcraft.jsch.Session;+import com.jcraft.jsch.UIKeyboardInteractive;+import com.jcraft.jsch.UserInfo;++import de.anomic.server.serverSwitch;+import de.anomic.yacy.yacySeedDB;+import de.anomic.yacy.yacySeedUploader;++public class yacySeedUploadScp implements yacySeedUploader {++ public static final String CONFIG_SCP_SERVER = "seedScpServer";+ public static final String CONFIG_SCP_ACCOUNT = "seedScpAccount";+ public static final String CONFIG_SCP_PASSWORD = "seedScpPassword";+ public static final String CONFIG_SCP_PATH = "seedScpPath";++ public String uploadSeedFile(serverSwitch sb, yacySeedDB seedDB, File seedFile) {+ try {+ if (sb == null) throw new NullPointerException("Reference to serverSwitch nut not be null.");+ if (seedDB == null) throw new NullPointerException("Reference to seedDB must not be null.");+ if ((seedFile == null)||(!seedFile.exists())) throw new Exception("Seed file does not exist.");++ String seedScpServer = sb.getConfig(CONFIG_SCP_SERVER,null);+ String seedScpAccount = sb.getConfig(CONFIG_SCP_ACCOUNT,null);+ String seedScpPassword = sb.getConfig(CONFIG_SCP_PASSWORD,null);+ String seedScpPath = sb.getConfig(CONFIG_SCP_PATH,null);++ if ((seedScpServer != null) && (seedScpAccount != null) && (seedScpPassword != null) && (seedScpPath != null)) {+ String log = sshc.put(seedScpServer, seedFile, seedScpPath, seedScpAccount, seedScpPassword);+ return "Seed file uploaded successfully using scp. " + log;+ }+ return "Seed upload settings not configured properly. password-len=" ++ seedScpPassword.length() + ", filePath=" ++ seedScpPath;+ } catch (Exception e) {+ return "Error: " + e.getMessage();+ }+ }++ public String[] getConfigurationOptions() {+ return new String[] {CONFIG_SCP_SERVER,CONFIG_SCP_ACCOUNT,CONFIG_SCP_PASSWORD,CONFIG_SCP_PATH};+ }++ public String[] getLibxDependences() {+ return new String[]{"jsch-0.1.19.jar"};+ }++}++class sshc {+ public static String put(String host,+ File localFile, String remoteName,+ String account, String password) {++ Session session = null;+ try {+ // Creating a new secure channel object+ JSch jsch=new JSch();++ // setting hostname, username, userpassword+ session = jsch.getSession(account, host, 22);+ session.setPassword(password);++ /*+ * Setting the StrictHostKeyChecking to ignore unknown+ * hosts because of a missing known_hosts file ...+ */+ java.util.Properties config = new java.util.Properties();+ config.put("StrictHostKeyChecking","no");+ session.setConfig(config);++ /*+ * we need this user interaction interface to support+ * the interactive-keyboard mode+ */+ UserInfo ui=new SchUserInfo(password);+ session.setUserInfo(ui);++ // trying to connect ...+ session.connect();++ String command="scp -p -t " + remoteName;+ Channel channel = session.openChannel("exec");+ ((ChannelExec)channel).setCommand(command);++ // get I/O streams for remote scp+ OutputStream out=channel.getOutputStream();+ InputStream in=channel.getInputStream();++ channel.connect();++ byte[] tmp=new byte[1];+ checkAck(in);++ // send "C0644 filesize filename", where filename should not include '/'+ int filesize=(int)(localFile).length();+ command="C0644 "+filesize+" ";+ if(localFile.toString().lastIndexOf('/')>0){+ command+=localFile.toString().substring(localFile.toString().lastIndexOf('/')+1);+ }+ else{+ command+=localFile.toString();+ }+ command+="\n";+ out.write(command.getBytes()); out.flush();++ checkAck(in);++ // send a content of lfile+ FileInputStream fis=new FileInputStream(localFile);+ byte[] buf=new byte[1024];+ while(true){+ int len=fis.read(buf, 0, buf.length);+ if(len<=0) break;+ out.write(buf, 0, len); out.flush();+ }++ // send '\0'+ buf[0]=0; out.write(buf, 0, 1); out.flush();++ checkAck(in);++ return "";+ } catch (Exception e) {+ System.out.println("ERROR: scp put failed:" + e.getMessage());+ e.printStackTrace();+ return "";+ } finally+ {+ if ((session != null) && (session.isConnected()))+ session.disconnect();+ }+ }++ static int checkAck(InputStream in) throws IOException{+ int b=in.read();+ // b may be 0 for success,+ // 1 for error,+ // 2 for fatal error,+ // -1+ if(b==0) return b;+ if(b==-1) return b;++ if(b==1 || b==2){+ StringBuffer sb=new StringBuffer();+ int c;+ do {+ c=in.read();+ sb.append((char)c);+ }+ while(c!='\n');++ if(b==1){ // error+ throw new IOException(sb.toString());+ }+ if(b==2){ // fatal error+ throw new IOException(sb.toString());+ }+ }+ return b;+ }+}+++class SchUserInfo+implements UserInfo, UIKeyboardInteractive {+ String passwd;++ public SchUserInfo(String password) {+ this.passwd = password;+ }++ public String getPassword() {+ return this.passwd;+ }++ public boolean promptYesNo(String str){+ System.err.println("User was prompted from: " + str);+ return true;+ }++ public String getPassphrase() {+ return null;+ }++ public boolean promptPassphrase(String message) {+ System.out.println("promptPassphrase : " + message);+ return false;+ }++ public boolean promptPassword(String message) {+ System.out.println("promptPassword : " + message);+ return true;+ }++ /**+ * @see com.jcraft.jsch.UserInfo#showMessage(java.lang.String)+ */+ public void showMessage(String message) {+ System.out.println("Sch has tried to show the following message to the user: " + message);+ }++ public String[] promptKeyboardInteractive(String destination,+ String name,+ String instruction,+ String[] prompt,+ boolean[] echo) {+ System.out.println("User was prompted using interactive-keyboard: " ++ "\n\tDestination: " + destination ++ "\n\tName: " + name ++ "\n\tInstruction: " + instruction ++ "\n\tPrompt: " + arrayToString2(prompt,"|") ++ "\n\techo: " + arrayToString2(echo,"|"));++ if ((prompt.length >= 1) && (prompt[0].startsWith("Password")))+ return new String[]{this.passwd};+ return new String[]{};+ }++ String arrayToString2(String[] a, String separator) {+ StringBuffer result = new StringBuffer();// start with first element+ if (a.length > 0) {+ result.append(a[0]);+ for (int i=1; i<a.length; i++) {+ result.append(separator);+ result.append(a[i]);+ }+ }+ return result.toString();+}++ String arrayToString2(boolean[] a, String separator) {+ StringBuffer result = new StringBuffer();// start with first element+ if (a.length > 0) {+ result.append(a[0]);+ for (int i=1; i<a.length; i++) {+ result.append(separator);+ result.append(a[i]);+ }+ }+ return result.toString();+}+}+diff --git a/source/de/anomic/yacy/seedUpload/yacySeedUploadScp.xml b/source/de/anomic/yacy/seedUpload/yacySeedUploadScp.xmlnew file mode 100644index 000000000..bf03fde0d--- /dev/null+++ b/source/de/anomic/yacy/seedUpload/yacySeedUploadScp.xml@@ -0,0 +1,54 @@+<?xml version="1.0"?>+<project name="YACY - seedUpload via SCP" default="dist">+ <description>+ A class that allows to upload the seed list via scp+ </description>++ <property name="addonShortName" value="Scp"/>+ <property name="addonVersion" value="0.1"/>++ <property name="addonLongName" value="${addonShortName}SeedUploader"/>+ <property name="parserArchive" location="${release}/${addonLongName}_${addonVersion}.tgz"/>++ <target name="compile">+ <echo message="Compiling ${addonLongName} Version ${addonVersion} ..."/>+ <javac srcdir="${src}/de/anomic/yacy/seedUpload/" destdir="${build}" source="${javacSource}" target="${javacTarget}">+ <include name="${src}/de/anomic/yacy/seedUpload/yacySeedUpload${addonShortName}.java"/>+ <classpath>+ <pathelement location="${build}" />++ <!-- main lib needed to parse rss/atom feed files -->+ <pathelement location="${libx}/jsch-0.1.19.jar" />+ </classpath>+ </javac>+ </target>+++ <target name="zip" depends="compile">+ <echo message="Compressing ${addonLongName} Version ${addonVersion} ..."/>+ <tar destfile="${parserArchive}" compression="gzip">+ <tarfileset dir="${libx}"+ includes="jsch-0.1.19.*"+ prefix="libx/"+ dirmode="755" mode="644"/>+ <tarfileset dir="${src}/de/anomic/yacy/seedUpload/"+ includes="yacySeedUpload${addonShortName}.java"+ prefix="source/de/anomic/yacy/seedUpload/"+ dirmode="755" mode="644"/>+ <tarfileset dir="${build}/de/anomic/yacy/seedUpload/"+ includes="yacySeedUpload${addonShortName}.class"+ prefix="classes/de/anomic/yacy/seedUpload/"+ dirmode="755" mode="644"/>+ <tarfileset dir="${htroot}/yacy/seedUpload/"+ includes="yacySeedUpload${addonShortName}.html"+ prefix="htroot/yacy/seedUpload/"+ dirmode="755" mode="644"/>+ </tar>+ </target>+++ <target name="dist" depends="compile,zip" description="Compile and zip the addon"/>+++</project>+diff --git a/source/de/anomic/yacy/yacyCore.java b/source/de/anomic/yacy/yacyCore.javaindex dea6cab03..8af5b03d3 100644--- a/source/de/anomic/yacy/yacyCore.java+++ b/source/de/anomic/yacy/yacyCore.java@@ -56,26 +56,33 @@package de.anomic.yacy;import java.io.File;+import java.io.FilenameFilter;import java.io.IOException;import java.net.MalformedURLException;+import java.net.URI;import java.net.URL;import java.text.SimpleDateFormat;import java.util.Date;import java.util.GregorianCalendar;+import java.util.Hashtable;+import java.util.Iterator;import java.util.TimeZone;import java.util.Vector;import de.anomic.http.httpc;import de.anomic.net.natLib;import de.anomic.plasma.plasmaSwitchboard;+import de.anomic.plasma.parser.Parser;import de.anomic.server.serverLog;import de.anomic.server.serverSwitch;+import de.anomic.yacy.seedUpload.yacySeedUploadFtp;public class yacyCore {// staticspublic static long startupTime = System.currentTimeMillis();public static yacySeedDB seedDB = null;+ public static final Hashtable seedUploadMethods = new Hashtable();public static yacyPeerActions peerActions = null;public static yacyDHTAction dhtAgent = null;public static serverLog log;@@ -93,7 +100,7 @@ public class yacyCore {private int onlineMode = 1;private plasmaSwitchboard switchboard;- private static TimeZone GMTTimeZone = TimeZone.getTimeZone("PST");+ private static TimeZone GMTTimeZone = TimeZone.getTimeZone("America/Los_Angeles");public static SimpleDateFormat shortFormatter = new SimpleDateFormat("yyyyMMddHHmmss");public static long universalTime() {@@ -123,62 +130,64 @@ public class yacyCore {}public yacyCore(plasmaSwitchboard sb) throws IOException {- long time = System.currentTimeMillis();-- this.switchboard = sb;- switchboard.setConfig("yacyStatus","");-- // set log level- log = new serverLog("YACY", Integer.parseInt(switchboard.getConfig("yacyLoglevel", "0")));-- // create a yacy db- yacyDBPath = new File(sb.getRootPath(), sb.getConfig("yacyDB", "DATA/YACYDB"));- if (!(yacyDBPath.exists())) yacyDBPath.mkdir();-+ long time = System.currentTimeMillis();++ this.switchboard = sb;+ switchboard.setConfig("yacyStatus","");++ // set log level+ log = new serverLog("YACY", Integer.parseInt(switchboard.getConfig("yacyLoglevel", "0")));++ // create a yacy db+ yacyDBPath = new File(sb.getRootPath(), sb.getConfig("yacyDB", "DATA/YACYDB"));+ if (!(yacyDBPath.exists())) yacyDBPath.mkdir();+// read memory amountint mem = Integer.parseInt(switchboard.getConfig("ramCacheSize", "1")) * 0x400 *- Integer.parseInt(switchboard.getConfig("ramCachePercentDHT", "1")) / 100;+ Integer.parseInt(switchboard.getConfig("ramCachePercentDHT", "1")) / 100;log.logSystem("DHT Cache memory = " + mem + " KB");// create or init seed cache- seedDB = new yacySeedDB(- sb,- new File(yacyDBPath, "seed.new.db"),- new File(yacyDBPath, "seed.old.db"),- new File(yacyDBPath, "seed.pot.db"),- mem);-+ seedDB = new yacySeedDB(+ sb,+ new File(yacyDBPath, "seed.new.db"),+ new File(yacyDBPath, "seed.old.db"),+ new File(yacyDBPath, "seed.pot.db"),+ mem);++ loadSeedUploadMethods();+peerActions = new yacyPeerActions(seedDB, switchboard,- new File(sb.getRootPath(), sb.getConfig("superseedFile", "superseed.txt")),- switchboard.getConfig("superseedLocation", "http://www.yacy.net/yacy/superseed.txt"));+ new File(sb.getRootPath(), sb.getConfig("superseedFile", "superseed.txt")),+ switchboard.getConfig("superseedLocation", "http://www.yacy.net/yacy/superseed.txt"));dhtAgent = new yacyDHTAction(seedDB);peerActions.deploy(dhtAgent);// create or init index sharing//shareManager = new yacyShare(switchboard);- seedCacheSizeStamp = seedDB.sizeConnected();-- log.logSystem("CORE INITIALIZED");- // ATTENTION, VERY IMPORTANT: before starting the thread, the httpd yacy server must be running!-- speedKey = System.currentTimeMillis() - time;+ seedCacheSizeStamp = seedDB.sizeConnected();++ log.logSystem("CORE INITIALIZED");+ // ATTENTION, VERY IMPORTANT: before starting the thread, the httpd yacy server must be running!++ speedKey = System.currentTimeMillis() - time;// start with a seedList update to propagate out peer, if possible- onlineMode = Integer.parseInt(switchboard.getConfig("onlineMode", "1"));- //lastSeedUpdate = universalTime();- lastOnlineTime = 0;-- // cycle- // within cycle: update seed file, strengthen network, pass news (new, old seed's)- if (online())- log.logSystem("you are in online mode");- else {- log.logSystem("YOU ARE OFFLINE! ---");- log.logSystem("--- TO START BOOTSTRAPING, YOU MUST USE THE PROXY,");- log.logSystem("--- OR HIT THE BUTTON 'go online'");+ onlineMode = Integer.parseInt(switchboard.getConfig("onlineMode", "1"));+ //lastSeedUpdate = universalTime();+ lastOnlineTime = 0;++ // cycle+ // within cycle: update seed file, strengthen network, pass news (new, old seed's)+ if (online())+ log.logSystem("you are in online mode");+ else {+ log.logSystem("YOU ARE OFFLINE! ---");+ log.logSystem("--- TO START BOOTSTRAPING, YOU MUST USE THE PROXY,");+ log.logSystem("--- OR HIT THE BUTTON 'go online'");log.logSystem("--- ON THE STATUS PAGE http://localhost:" + switchboard.getConfig("port", "8080") + "/Status.html");- }+ }}@@ -198,17 +207,10 @@ public class yacyCore {}public void publishSeedList() {+log.logDebug("triggered Seed Publish");- // we want to be a principal...- if ((switchboard.getConfig("seedFTPPassword","").length() == 0) &&- (switchboard.getConfig("seedFilePath", "").length() == 0)) {- log.logDebug("yacyCore.publishSeedList: no FTP settings present; password-len=" +- switchboard.getConfig("seedFTPPassword","").length() + ", filePath=" +- switchboard.getConfig("seedFilePath", ""));- return;- }-+/*if (oldIPStamp.equals((String) seedDB.mySeed.get("IP", "127.0.0.1")))System.out.println("***DEBUG publishSeedList: oldIP is equal");@@ -218,16 +220,32 @@ public class yacyCore {System.out.println("***DEBUG publishSeedList: I can reach myself");*/- if ((!(oldIPStamp.equals((String) seedDB.mySeed.get("IP", "127.0.0.1")))) ||+ if (!(!(oldIPStamp.equals(seedDB.mySeed.get("IP", "127.0.0.1")))) ||(seedCacheSizeStamp != seedDB.sizeConnected()) ||(!(canReachMyself()))) {- // publish seed-list to ftp account, this can only a principal peer+ log.logDebug("not necessary to publish: oldIP is equal, sizeConnected is equal and I can reach myself under the old IP.");+ return;+ }++ // getting the seed upload method that should be used ...+ String seedUploadMethod = this.switchboard.getConfig("seedUploadMethod","");++ if (!(seedUploadMethod.equalsIgnoreCase("none")) ||+ ((seedUploadMethod.equals("")) &&+ (this.switchboard.getConfig("seedFTPPassword","").length() > 0) &&+ (this.switchboard.getConfig("seedFilePath", "").length() > 0))) {+ if (seedUploadMethod.equals("")) this.switchboard.setConfig("seedUploadMethod","Ftp");+ // we want to be a principal...saveSeedList();- seedCacheSizeStamp = seedDB.sizeConnected();- oldIPStamp = (String) seedDB.mySeed.get("IP", "127.0.0.1");+ this.seedCacheSizeStamp = seedDB.sizeConnected();+ this.oldIPStamp = seedDB.mySeed.get("IP", "127.0.0.1");} else {- log.logDebug("not necessary to publish: oldIP is equal, sizeConnected is equal and I can reach myself under the old IP.");+ if (seedUploadMethod.equals("")) this.switchboard.setConfig("seedUploadMethod","none");+ log.logDebug("yacyCore.publishSeedList: No uploading method configured");+ return;}++}public void peerPing() {@@ -382,78 +400,151 @@ public class yacyCore {return 0;}-+ public static Hashtable getSeedUploadMethods() {+ synchronized (yacyCore.seedUploadMethods) {+ return (Hashtable) yacyCore.seedUploadMethods.clone();+ }+ }++ public static yacySeedUploader getSeedUploader(String methodname) {+ String className = null;+ synchronized (yacyCore.seedUploadMethods) {+ if (yacyCore.seedUploadMethods.containsKey(methodname)) {+ className = (String) yacyCore.seedUploadMethods.get(methodname);+ }+ }++ if (className == null) return null;+ try {+ Class uploaderClass = Class.forName(className);+ Object uploader = uploaderClass.newInstance();+ return (yacySeedUploader) uploader;+ } catch (Exception e) {+ return null;+ }+ }++ public static void loadSeedUploadMethods() {+ Hashtable availableUploaders = new Hashtable();++ try {+ String uploadersPkgName = yacyCore.class.getPackage().getName() + ".seedUpload";+ String packageURI = yacyCore.class.getResource("/"+uploadersPkgName.replace('.','/')).toString();++ // open the parser directory+ File uploadersDir = new File(new URI(packageURI));+ if ((uploadersDir == null) || (!uploadersDir.exists()) || (!uploadersDir.isDirectory())) {+ yacyCore.seedUploadMethods.clear();+ changeSeedUploadMethod("none");+ }++ String[] uploaderClasses = uploadersDir.list(new FilenameFilter() {+ public boolean accept(File dir, String name) {+ return name.startsWith("yacySeedUpload") && name.endsWith(".class");+ }});++ String javaClassPath = System.getProperty("java.class.path");++ if (uploaderClasses == null) return;+ for (int uploaderNr=0; uploaderNr<uploaderClasses.length; uploaderNr++) {+ String className = uploaderClasses[uploaderNr].substring(0,uploaderClasses[uploaderNr].indexOf(".class"));+ String fullClassName = uploadersPkgName + "." + className;+ try {+ Class uploaderClass = Class.forName(fullClassName);+ Object theUploader = uploaderClass.newInstance();+ if (!(theUploader instanceof yacySeedUploader)) continue;+ String[] neededLibx = ((yacySeedUploader)theUploader).getLibxDependences();+ if (neededLibx != null) {+ for (int libxId=0; libxId < neededLibx.length; libxId++) {+ if (javaClassPath.indexOf(neededLibx[libxId]) == -1) continue;+ }+ }+ availableUploaders.put(className.substring("yacySeedUpload".length()),fullClassName);+ } catch (Exception e) { /* we can ignore this for the moment */ }+ }+ } catch (Exception e) {++ } finally {+ synchronized (yacyCore.seedUploadMethods) {+ yacyCore.seedUploadMethods.clear();+ yacyCore.seedUploadMethods.putAll(availableUploaders);+ }+ }+ }++ public static boolean changeSeedUploadMethod(String method) {+ if ((method == null)||(method.length() == 0)) return false;++ if (method.equals("none")) return true;++ synchronized (yacyCore.seedUploadMethods) {+ return yacyCore.seedUploadMethods.containsKey(method);+ }+ }+public boolean saveSeedList() {return saveSeedList(this.switchboard);}-+public static boolean saveSeedList(serverSwitch sb) {- String logt;- // be shure that we have something to say- if (seedDB.mySeed.getAddress() == null) return false;- // upload a seed file- String seedFTPServer = sb.getConfig("seedFTPServer","");- String seedFTPAccount = sb.getConfig("seedFTPAccount","");- String seedFTPPassword = sb.getConfig("seedFTPPassword","");- File seedFTPPath = new File(sb.getConfig("seedFTPPath",""));- File seedFile = new File(sb.getConfig("seedFilePath",""));- String prevStatus = seedDB.mySeed.get("PeerType", "junior");- if (prevStatus.equals("principal")) prevStatus = "senior";- URL seedURL;- try{- seedURL = new URL(sb.getConfig("seedURL",""));- }catch(MalformedURLException e){- return false;- }- if ((seedFTPServer.length() != 0) &&- (seedFTPAccount.length() != 0) &&- (seedFTPPassword.length() != 0) &&- (seedFTPPath.toString().length() != 0)) {- try {- seedDB.mySeed.put("PeerType", "principal"); // this information shall also be uploaded- logt = seedDB.uploadCache(seedFTPServer, seedFTPAccount, seedFTPPassword, seedFTPPath, seedURL);- log.logInfo(logt);- if (logt.indexOf("Error") >= 0) {- seedDB.mySeed.put("PeerType", prevStatus);- log.logInfo("seed upload failed (ftp error): " + logt.substring(logt.indexOf("Error") + 6));- return false;- }- // check if seed file has arrived a public accessible location- // seedURL=http://www.yacy.net/yacy/seed.txt-- // finally, set the principal status- sb.setConfig("yacyStatus","principal");- return true;- } catch (IOException e) {- seedDB.mySeed.put("PeerType", prevStatus);- log.logInfo("seed upload failed (IO error): " + e.getMessage());- return false;- }- }else if(seedFile.toString().length() != 0){ // [AS]- try{- seedDB.mySeed.put("PeerType", "principal"); // this information shall also be uploaded- logt = seedDB.copyCache(seedFile, seedURL);- log.logInfo(logt);+ String logt;++ // be shure that we have something to say+ if (seedDB.mySeed.getAddress() == null) return false;++ // getting the configured seed uploader+ String seedUploadMethod = sb.getConfig("seedUploadMethod","");++ // for backward compatiblity ....+ if ((seedUploadMethod.equalsIgnoreCase("Ftp")) ||+ ((seedUploadMethod.equals("")) &&+ (sb.getConfig("seedFTPPassword","").length() > 0) &&+ (sb.getConfig("seedFilePath", "").length() > 0))) {+ seedUploadMethod = "Ftp";+ sb.setConfig("seedUploadMethod",seedUploadMethod);+ }++ // determine the seed uploader that should be used ...+ if (seedUploadMethod.equalsIgnoreCase("none")) return true;++ yacySeedUploader uploader = getSeedUploader(seedUploadMethod);+ if (uploader == null) return false;++ // ensure that the seed file url is configured properly+ URL seedURL;+ try{+ seedURL = new URL(sb.getConfig("seedURL",""));+ }catch(MalformedURLException e){+ return false;+ }++ // upload the seed-list using the configured uploader class+ String prevStatus = seedDB.mySeed.get("PeerType", "junior");+ if (prevStatus.equals("principal")) prevStatus = "senior";++ try {+ seedDB.mySeed.put("PeerType", "principal"); // this information shall also be uploaded++ //logt = seedDB.uploadCache(seedFTPServer, seedFTPAccount, seedFTPPassword, seedFTPPath, seedURL);+ logt = seedDB.uploadCache(uploader,sb, seedDB, seedURL);+ if (logt != null) {if (logt.indexOf("Error") >= 0) {seedDB.mySeed.put("PeerType", prevStatus);- log.logInfo("seed copy failed (IO error): " + logt.substring(logt.indexOf("Error") + 6));- return false;+ log.logError("seed upload failed using " + uploader.getClass().getName() + " (error): " + logt.substring(logt.indexOf("Error") + 6));+ return false;}- // check if seed file has arrived a public accessible location- // seedURL=http://www.yacy.net/yacy/seed.txt-- // finally, set the principal status- sb.setConfig("yacyStatus","principal");- return true;- } catch (IOException e) {- seedDB.mySeed.put("PeerType", prevStatus);- log.logInfo("seed copy failed (IO error): " + e.getMessage());- return false;+ log.logInfo(logt);}++ // finally, set the principal status+ sb.setConfig("yacyStatus","principal");+ return true;+ } catch (Exception e) {+ seedDB.mySeed.put("PeerType", prevStatus);+ sb.setConfig("yacyStatus", prevStatus);+ log.logInfo("seed upload failed (IO error): " + e.getMessage());+ return false;}- seedDB.mySeed.put("PeerType", prevStatus);- sb.setConfig("yacyStatus", prevStatus);- return false;}private class vprobe implements Runnable {diff --git a/source/de/anomic/yacy/yacyPeerActions.java b/source/de/anomic/yacy/yacyPeerActions.javaindex 8126f6215..1f45b951d 100644--- a/source/de/anomic/yacy/yacyPeerActions.java+++ b/source/de/anomic/yacy/yacyPeerActions.java@@ -91,7 +91,8 @@ public class yacyPeerActions {}public void updateMySeed() {- if (sb.getConfig("peerName", "nameless").equals("nameless")) sb.setConfig("peerName", serverCore.publicIP().getHostName() + yacyCore.speedKey + serverSystem.infoKey() + (System.currentTimeMillis() & 99));+ if (sb.getConfig("peerName", "nameless").equals("nameless"))+ sb.setConfig("peerName", serverCore.publicIP().getHostName() + yacyCore.speedKey + serverSystem.infoKey() + (System.currentTimeMillis() & 99));seedDB.mySeed.put("Name", sb.getConfig("peerName", "nameless"));seedDB.mySeed.put("Port", sb.getConfig("port", "8080"));seedDB.mySeed.put("ISpeed", "unknown"); // the speed of indexing (words/minute) of the peerdiff --git a/source/de/anomic/yacy/yacySeedDB.java b/source/de/anomic/yacy/yacySeedDB.javaindex b94f0c8e0..f05dbf402 100644--- a/source/de/anomic/yacy/yacySeedDB.java+++ b/source/de/anomic/yacy/yacySeedDB.java@@ -40,6 +40,7 @@package de.anomic.yacy;+import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;@@ -60,6 +61,7 @@ import de.anomic.kelondro.kelondroMap;import de.anomic.net.ftpc;import de.anomic.plasma.plasmaSwitchboard;import de.anomic.server.serverCore;+import de.anomic.server.serverSwitch;import de.anomic.tools.disorderHeap;public class yacySeedDB {@@ -480,56 +482,76 @@ public class yacySeedDB {}private Vector storeCache(File seedFile, boolean addMySeed) throws IOException {- PrintWriter pw = new PrintWriter(new FileWriter(seedFile));- Vector v = new Vector();- // store own seed- String line;- if ((addMySeed) && (mySeed != null)) {- line = mySeed.genSeedStr(null);- v.add(line);- pw.print(line + serverCore.crlfString);- }- // store other seeds- yacySeed ys;- for (int i = 0; i < seedActiveDB.size(); i++) {- ys = anySeed();- if (ys != null) {- line = ys.genSeedStr(null);- v.add(line);- pw.print(line + serverCore.crlfString);- }- }- pw.close();- return v;+ PrintWriter pw = null;+ Vector v = new Vector(seedActiveDB.size()+1);+ try {++ pw = new PrintWriter(new BufferedWriter(new FileWriter(seedFile)));++ // store own seed+ String line;+ if ((addMySeed) && (mySeed != null)) {+ line = mySeed.genSeedStr(null);+ v.add(line);+ pw.print(line + serverCore.crlfString);+ }++ // store other seeds+ yacySeed ys;+ for (int i = 0; i < seedActiveDB.size(); i++) {+ ys = anySeed();+ if (ys != null) {+ line = ys.genSeedStr(null);+ v.add(line);+ pw.print(line + serverCore.crlfString);+ }+ }+ pw.flush();+ } finally {+ if (pw != null) try { pw.close(); } catch (Exception e) {}+ }+ return v;}- public String uploadCache(String seedFTPServer,- String seedFTPAccount,- String seedFTPPassword,- File seedFTPPath,+ public String uploadCache(yacySeedUploader uploader,+ serverSwitch sb,+ yacySeedDB seedDB,+// String seedFTPServer,+// String seedFTPAccount,+// String seedFTPPassword,+// File seedFTPPath,URL seedURL) throws IOException {- // upload a seed file, if possible- if (seedURL == null) return "UPLOAD - Error: URL not given";- File seedFile = new File("seedFile.txt");- Vector uv = storeCache(seedFile, true);- // upload the seed file- String log = ftpc.put(seedFTPServer, seedFile, seedFTPPath.getParent(), seedFTPPath.getName(), seedFTPAccount, seedFTPPassword);- try {- // check also if the result can be retrieved again- if (checkCache(uv, seedURL))++ // upload a seed file, if possible+ if (seedURL == null) throw new NullPointerException("UPLOAD - Error: URL not given");++ String log = null;+ File seedFile = null;+ try {+ // create a seed file which for uploading ...+ seedFile = new File("seedFile.txt");+ Vector uv = storeCache(seedFile, true);++ // uploading the seed file+ log = uploader.uploadSeedFile(sb,seedDB,seedFile);++ // check also if the result can be retrieved again+ if (checkCache(uv, seedURL))log = log + "UPLOAD CHECK - Success: the result vectors are equal" + serverCore.crlfString;elselog = log + "UPLOAD CHECK - Error: the result vector is different" + serverCore.crlfString;- } catch (IOException e) {- log = log + "UPLOAD CHECK - Error: IO problem " + e.getMessage() + serverCore.crlfString;- }- seedFile.delete();- return log;+ } catch (IOException e) {+ log = log + "UPLOAD CHECK - Error: IO problem " + e.getMessage() + serverCore.crlfString;+ } finally {+ if (seedFile != null) seedFile.delete();+ }++ return log;}public String copyCache(File seedFile, URL seedURL) throws IOException {if (seedURL == null) return "COPY - Error: URL not given";- Vector uv = storeCache(seedFile, true);+ Vector uv = storeCache(seedFile, true);try {// check also if the result can be retrieved againif (checkCache(uv, seedURL))diff --git a/source/de/anomic/yacy/yacySeedUploader.java b/source/de/anomic/yacy/yacySeedUploader.javanew file mode 100644index 000000000..a1fa3802c--- /dev/null+++ b/source/de/anomic/yacy/yacySeedUploader.java@@ -0,0 +1,11 @@+package de.anomic.yacy;++import java.io.File;++import de.anomic.server.serverSwitch;++public interface yacySeedUploader {+ public String uploadSeedFile(serverSwitch sb, yacySeedDB seedDB, File seedFile);+ public String[] getConfigurationOptions();+ public String[] getLibxDependences();+}diff --git a/source/yacy.java b/source/yacy.javaindex ea0d351c5..56d470eac 100644--- a/source/yacy.java+++ b/source/yacy.java@@ -103,8 +103,8 @@ import de.anomic.yacy.yacyCore;public final class yacy {// static objects- private static final String vString = "@REPL_VERSION@";- private static final String vDATE = "@REPL_DATE@";+ private static final String vString = "0.374";+ private static final String vDATE = "20050514";private static final String copyright = "[ YACY Proxy v" + vString + ", build " + vDATE + " by Michael Christen / www.yacy.net ]";private static final String hline = "-------------------------------------------------------------------------------";@@ -232,9 +232,6 @@ public final class yacy {sb.setConfig("downloadAccountBase64", "");}- // init parser- de.anomic.plasma.plasmaParser.initMediaExt(sb.getConfig("mediaExt",""));-// start main threadstry {httpd protocolHandler = new httpd(sb, new httpdFileHandler(sb), new httpdProxyHandler(sb));diff --git a/yacy.init b/yacy.initindex 250ebbade..ec0b51704 100644--- a/yacy.init+++ b/yacy.init@@ -79,7 +79,11 @@ proxyCache = DATA/HTCACHEproxyCacheSize = 200# the following mime-types are the whitelist for indexing-parseableMime=application/xhtml+xml,text/html,text/plain+#+# parseableRealtimeMimeTypes: specifies mime-types that can be indexed on the fly+# parseableMime: specifies mime-types that can be indexed but not on the fly+parseableRealtimeMimeTypes=application/xhtml+xml,text/html,text/plain+parseableMimeTypes=# media extension string# a comma-separated list of extensions that denote media file formats@@ -222,15 +226,30 @@ adminAccountBase64MD5=superseedFile=superseed.txtsuperseedLocation=http://www.yacy.net/superseed.txt+# if you are running a principal peer, you must update the following variables-# This is an ftp account with all relevant information-# the cycle parameter is the update period in minutes.+# The upload method that should be used to upload the seed-list file to+# a public accessible webserver where it can be loaded by other peers.+#+# You can set the seedUploadMethod-Property to+# - None+# - Ftp+# - File+# - Scp (only if you have installed the optional addon)+#+seedUploadMethod=++# The URL to the seed list file+seedURL=++# This is the most common method to upload the seed-list+#+# This is an ftp account with all relevant information.# The update is only made if there had been changes in between.seedFTPServer=seedFTPAccount=seedFTPPassword=seedFTPPath=-seedURL=# alternatively to an FTP account, a peer can also become a principal peer# if the seed-list can be generated as a file and that file is also accessible from@@ -240,6 +259,15 @@ seedURL=# file is actually accessible from the internetseedFilePath=+# Settings needed to upload the seed-list file via scp+#+# Please note that this upload method can only be used if you have installed+# this optional upload method.+seedScpServer=+seedScpAccount=+seedScpPassword=+seedScpPath=+# every peer should have a name. inded, we try to give every peer an unique ID,# which is necessary for internal organization of the index sharing, but the# peer's name is purely informal. No function but information is applied.diff --git a/yacy.parser b/yacy.parserdeleted file mode 100644index f517351f0..000000000--- a/yacy.parser+++ /dev/null@@ -1,2 +0,0 @@-#plasmaParser configuration file-#Fri May 13 01:38:38 CEST 2005